Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In a windows form application what is the impact of calling `Thread.Sleep(1)` as illustrated in the following code:
```
public Constructor()
{
Thread thread = new Thread(Task);
thread.IsBackground = true;
thread.Start();
}
private void Task()
{
while (true)
{
// do something
Thread.Sleep(1);
}
}
```
Will this thread hog all of the available CPU?
What profiling techniques can I use to measure this Thread's CPU usage ( other than task manager )? | As stated, your loop will not hog the CPU.
*But beware*: Windows is **not** a real-time OS, so you will **not** get 1000 wakes per second from Thread.Sleep(1). If you haven't used [timeBeginPeriod](http://msdn.microsoft.com/en-us/library/ms713413.aspx) to set your minimum resolution you'll wake about every 15 ms. Even after you've set the minimum resolution to 1 ms, you'll still only wake up every 3-4 ms.
In order to get millisecond level timer granularity you have to use the Win32 multimedia timer ([C# wrapper](http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx)). | No it won't hog the CPU, it will just pause your thread for *at least* that long. While your thread is paused, the operating system can schedule another, unrelated thread to make use of the processor. | What is the impact of Thread.Sleep(1) in C#? | [
"",
"c#",
"multithreading",
""
] |
Is there a way to dynamically execute code contained in a string using .net 2.0, in a similar way to eval() in javascript or using sp\_executeSQL in tsql?
I have a string value in a variable that I want to manipulate at some point in my application - so the code would essentially be string manipulation. I don't know what different manipulations will be needed so i'd like them to be configurable.
I don't really care what language the dynamic code is written in, whatever is easiest to implement and simple enough to write.
For example I might want to replace instances of '.' character with '-', or strip out all spaces, or similar. If I was doing this in sql I'd use dynamic sql, but I want to execute it in .net code, something like this:
```
// Get the value to be manipulated
string s = ... // wherever s comes from
// Get the manipulation code, eg this might come from a database
// setting that can be changed without recompiling the .net code.
string manipulation = Settings.GetSomeValue("ManipulationSetting");
// This is what I want to know how to do: apply some manipulation to the string.
string result = MagicDynamicEvalClass.Eval(manipulation, s);
// Now I would do stuff with the result.
```
I could possibly just use regex find/replace expressions. Since all i'm doing is string manipulation this should be sufficient provided I can write clever enough regular expressions. eg:
```
// Get the value to be manipulated
string s = ... // wherever s comes from
// Get the code to use to manipulate s, eg this might come from a database
// setting that can be changed without recompiling the .net code.
string findRegex = Settings.GetSomeValue("RegexPattern");
string replaceRegex = Settings.GetSomeValue("RegexReplace");
// This is what I want to know how to do: apply some manipulation to the string.
string result = Regex.Replace(s, findRegex, replaceRegex);
// Now I can do stuff with the result.
```
But in some cases my manipulation requirement might exceed what's possible with regex, or I might want to apply multiple steps, eg replace '.' with '-' and also strip spaces. Perhaps I could store a list of find/replace regexes and iterate over them... but anyone have a better suggestion?
UPDATE - example using dynamic sql
I don't want a solution that requires me to know in advance what manipulations are possible, and I'm really looking for something simple. eg in sql I'd do something like this:
```
declare @s nvarchar(1000)
declare @manipulation nvarchar(1000)
declare @result nvarchar(1000)
-- ... Get the values from wherever they come from
-- Execute the manipulation dynamically
EXEC sp_ExecuteSQL @stmt = @manipulation
, @params = N'@s nvarchar(1000), @result nvarchar(1000) OUTPUT'
, @s = @s, @result = @result OUTPUT
```
Then I could put arbitrary sql into my @manipulation, something like this
SET @result = REPLACE( REPLACE( @s, '.', '-'), ' ', '' )
Yes, this would require me to be careful about what values are allowed to be put into @manipulation, but it would give me the flexibility I need in future.
A similar approach would be possible in javascript I guess, using eval().
UPDATE - example using MSScript control from .net:
[This](http://weblogs.asp.net/rosherove/articles/DotNetScripting.aspx) seems like a possible approach, although perhaps overkill for the simple case I want to deal with. It uses the Microsoft Script Control library to allow execution of arbitrary VBScript. | like the others already mentioned its not really possible to compile c# in an eval() function. that functionality is planed for a latter release of the clr which anders demoed at the PDC.
as a diffrent solutionm, if your application is able to run on mono you can just use its eval function which can dynamicly compile c# code, just like javascript. it is basicly already doing what .net will be able to do in a year or two.
as an alternative if you cant use mono you could write the part that does the string manipulation in ironruby which has eval(). the rest of your code wont even know you are using ruby for that class/assambly.
the link you posted in the update looks pretty complicated for such a simple use case. using ironruby all you would have to do is write the MyDynamicEvalClass something like this:
```
class MyDynamicEvalClass
def eval(someString,transformString)
eval(someString,transformString)
end
end
```
and replacing "ManipulationSetting" with some ruby code that returns a new string | It's not tooo hard ;)
I put together a little example.
This should help you decide if you want to use dynamic scripts.. or regexes.
What you can do is create an interface in your assembly, which your dynamic code will implement:
```
namespace CompileScriptExample
{
public interface IStringManipulator
{
string processString(string aString);
}
}
```
Then create a ScriptRunner class:
```
namespace CompileScriptExample
{
public class ScriptRunner
{
public static string RunScript(string scriptCode, string scriptParameter)
{
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
//configure parameters
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.IncludeDebugInformation = false;
string reference;
// Set reference to current assembly - this reference is a hack for the example..
reference = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
parameters.ReferencedAssemblies.Add(reference+"\\CompileScriptExample.exe");
//compile
CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { scriptCode });
if (results.Errors.Count == 0)
{
IStringManipulator compiledScript=(IStringManipulator)FindInterface(results.CompiledAssembly, "IStringManipulator");
return compiledScript.processString(scriptParameter);//run the script, pass the string param..
}
else
{
foreach(CompilerError anError in results.Errors)
{
MessageBox.Show(anError.ErrorText);
}
//handle compilation errors here
//..use results.errors collection
throw new Exception("Compilation error...");
}
}
private static object FindInterface(Assembly anAssembly, string interfaceName)
{
// find our interface type..
foreach (Type aType in anAssembly.GetTypes())
{
if (aType.GetInterface(interfaceName, true) != null)
return anAssembly.CreateInstance(aType.FullName);
}
return null;
}
}
```
}
Now all you have to do is create a script string with code that implements your interface like..
```
string myScriptString=@"using CompileScriptExample;
public class MyStringManipulator : IStringManipulator
{
public string processString(string aString)
{
return aString+aString;
}
};
```
and then.. in your code, make use of the ScriptRunner to process your string with your dynamic code:
```
string processedString = ScriptRunner.RunScript(myScriptString, "hello");
``` | Is there a way to dynamically execute a string in .net, similar to eval() in javascript or dynamic sql in sql? | [
"",
"c#",
".net",
"string",
"dynamic",
""
] |
I have a program where an array gets its data using string.Split(char[] delimiter).
(using ';' as delimiter.)
Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:
> 1 ;2 ; ; 3;
This leads to my array having null values.
How do I get rid of them? | Try this:
```
yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
``` | You could use the Where linq extension method to only return the non-null or empty values.
```
string someString = "1;2;;3;";
IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
``` | Getting rid of null/empty string values in a C# array | [
"",
"c#",
"arrays",
"null",
"string",
""
] |
Why are semicolons necessary at the end of each line in C#?
Why can't the complier just know where each line is ended? | The line terminator character will make you be able to break a statement across multiple lines.
On the other hand, languages like VB have a *line continuation character* (and may raise compile error for semicolon). I personally think it's much cleaner to terminate statements with a semicolon rather than continue using undersscore.
Finally, languages like `JavaScript` (JS) and `Swift` have optional semicolon(s), but at least JS has a convention to always put semicolons (even if not required, which prevents accidents). | No, the compiler doesn't know that a line break is for statement termination, nor should it. It allows you to carry a statement to multilines if you like.
See:
```
string sql = @"SELECT foo
FROM bar
WHERE baz=42";
```
Or how about large method overloads:
```
CallMyMethod(thisIsSomethingForArgument1,
thisIsSomethingForArgument2,
thisIsSomethingForArgument2,
thisIsSomethingForArgument3,
thisIsSomethingForArgument4,
thisIsSomethingForArgument5,
thisIsSomethingForArgument6);
```
And the reverse, the semi-colon also allows multi-statement lines:
```
string s = ""; int i = 0;
``` | Semicolons in C# | [
"",
"c#",
""
] |
How can I switch back to main thread from a different thread when there is an exception. When an exception is raised on a child thread, I want a notification to be sent to main thread and execute a method from the main thread. How can I do this?
Thanks.
**Additional information**
I am calling a method from my main method and starting a new thread there after some calculations and changes
```
Thread thread = new Thread() {
@Override
public void run() {
.....
}
}
thread.start();
``` | When the exception occurs in the child thread, what is the main thread going to be doing? It will have to be *waiting* for any errors in a child thread.
You can establish an [`UncaughtExceptionHandler`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) in the child thread, which can raise an event that the main thread is waiting for. | As TofuBeer says you need to provide more context, if however that context is that you're a swing app...
SwingUtilities.invokeLater(Runnable r) allows you to call back on Swing's main execution thread.
```
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
//do whatever you want with the exception
}
});
}
``` | Java - switching back to main thread? | [
"",
"java",
"multithreading",
""
] |
Is there some way to delay defining the size of an array until a class method or constructor?
What I'm thinking of might look something like this, which (of course) doesn't work:
```
class Test
{
private:
int _array[][];
public:
Test::Test(int width, int height);
};
Test::Test(int width, int height)
{
_array[width][height];
}
``` | What Daniel is talking about is that you will need to allocate memory for your array dynamically when your Test (width, height) method is called.
You would declare your two dimensional like this (assuming array of integers):
```
int ** _array;
```
And then in your Test method you would need to first allocate the array of pointers, and then for each pointer allocate an array of integers:
```
_array = new *int [height];
for (int i = 0; i < height; i++)
{
_array [i] = new int[width];
}
```
And then when the object is released you will need to explicit delete the memory you allocated.
```
for (int i = 0; i < height; i++)
{
delete [] _array[i];
_array [i] = NULL;
}
delete [] _array;
_array = NULL;
``` | vector is your best friend
```
class Test
{
private:
vector<vector<int> > _array;
public:
Test(int width, int height) :
_array(width,vector<int>(height,0))
{
}
};
``` | Delaying array size in class definition in C++? | [
"",
"c++",
"arrays",
"size",
"delay",
""
] |
I have a large amount of data to move using two PHP scripts: one on the client side using a command line PHP script and other behind Apache. I POST the data to the server side and use php://input stream to save it on the web-server end. To prevent from reaching any memory limits, data is separated into 500kB chunks for each POST request. All this works fine.
Now, to save the bandwidth and speed it up, I want to compress the data before sending and decompress when received on the other end. I found 3 pairs of functions that can do the job, but I cannot decide which one to use:
* [`gzencode`](http://php.net/manual/en/function.gzencode.php) / [`gzdecode`](http://php.net/manual/en/function.gzdecode.php)
* [`gzdeflate`](http://php.net/manual/en/function.gzdeflate.php) / [`gzinflate`](http://php.net/manual/en/function.gzinflate.php)
* [`gzcompress`](http://php.net/manual/en/function.gzcompress.php) / [`gzuncompress`](http://php.net/manual/en/function.gzuncompress.php)
Which pair of functions would you recommend and why?
**UPDATE:** I just read zlib FAQ:
*The gzip format (`gzencode`) was designed to retain the directory information about a single file, such as the name and last modification date. The zlib format (`gzcompress`) on the other hand was designed for in-memory and communication channel applications, and has a much more compact header and trailer and uses a faster integrity check than gzip.* | All of these can be used. There are subtle differences between the three:
* [**gzencode()**](http://php.net/manual/en/function.gzencode.php) uses the GZIP file format, the same as the `gzip` command line tool. This file format has a header containing optional metadata, DEFLATE compressed data, and footer containing a CRC32 checksum and length check.
* [**gzcompress()**](http://php.net/manual/en/function.gzcompress.php) uses the ZLIB format. It has a shorter header serving only to identify the compression format, DEFLATE compressed data, and a footer containing an ADLER32 checksum.
* [**gzdeflate()**](http://php.net/manual/en/function.gzdeflate.php) uses the raw DEFLATE algorithm on its own, which is the basis for both of the other formats.
All three use the same algorithm under the hood, so they won't differ in speed or efficiency. `gzencode()` and `gzcompress()` both add a checksum, so the integrity of the archive can be verified, which can be useful over unreliable transmission and storage methods. If everything is stored locally and you don't need any additional metadata then `gzdeflate()` would suffice. For portability I'd recommend `gzencode()` (GZIP format) which is probably better supported than `gzcompress()` (ZLIB format) among other tools.
When compressing very short strings the overhead of each method becomes relevant since for very short input the overhead can comprise a significant part of the output. The overhead for each method, measured by compressing an empty string, is:
* `gzencode('')` - 20 bytes
* `gzcompress('')` - 8 bytes
* `gzdeflate('')` - 2 bytes | I am no PHP expert and cannot answer the question posed, but it seems like there is a lot of guessing going on here, and fuzzy information being proffered.
DEFLATE is the name of the compression algorithm that is used by ZLIB, GZIP and others. In theory, GZIP supports alternative compression algorithms, but in practice, there are none.
There is no such thing as "the GZIP algorithm". GZIP uses the DEFLATE algorithm, and puts framing data around the compressed data. With GZIP you can add things like the filename, the time of the file, a CRC, even a comment. This metadata is optional, though, and many gzippers just omit it.
ZLIB is similar, except with a different, more limited set of metadata, and a specific 2-byte header.
This is all in IETF RFCs [1950](http://www.ietf.org/rfc/rfc1950.txt), [1951](http://www.ietf.org/rfc/rfc1951.txt), and [1952](http://www.ietf.org/rfc/rfc1952.txt).
To say that "the gzip algorithm compresses better than DEFLATE" is just nonsense. There is no gzip algorithm. And the algorithm used in the GZIP format **is DEFLATE**. | Which compression method to use in PHP? | [
"",
"php",
"compression",
"gzip",
""
] |
I am trying to understand LINQ and become confident at using it. What I am struggling with are the parameters asked for. Example:
```
var sortedWords = words.OrderBy(a=>a.Length)
```
`words` is an array collection. `OrderBy`'s intellisense says:
```
Func<string, TKey> keyselector
```
A `func` executes a method, and a `string` is the value, `TKey` a key.
In the example <http://msdn.microsoft.com/en-us/vcsharp/aa336756.aspx#thenBySimple> (`ThenBy` - Comparer), we compare length by saying `a => a.Length`. I understand that syntax, but how is that related to what the intellisense is asking for?
I tend to find the method signature and intellisense unreadable because of all the generics.
Thanks. | ```
a => a.Length
```
> I understand that syntax, but how is that related to what the intellisense is asking for?
This chunk of code is a lambda expression. A lambda expression is a handy way of generating an **Anonymous method** (in this case), or a System.Linq.Expressions.Expression . Let's break it down by parts.
* The most noticeable feature is the **=>**, which seperates parameters from a method body.
* On the left side of the **=>**, there is a symbol: **a**. This is the declaration of a parameter for our anonymous method. The compiler is aware that we are calling OrderBy(), and that OrderBy requires a `Func<string, object>`. The parameter for such a function is a string, so the compiler determines that **a** must be a string. The only thing the programmer needed to provide is a name.
* On the right side of the **=>**, there is method body. Since this is a one-liner, the **return** keyword is implied. The IDE provides intellisense against **a** as a string, which allows you to use the Length property.
Now, consider this C# 2.0 ...
```
IEnumerable<string> sortedWords =
Enumerable.OrderBy(words, delegate(string a) {return a.Length;});
```
With the C# 3.0
```
IEnumerable<string> sortedWords = words
.OrderBy(a => a.Length);
``` | The type (as displayed by Intellisense) makes sense if you understand the nature of [lambda expressions](http://msdn.microsoft.com/en-us/library/bb397687.aspx) in .NET/C#. Otherwise, it can indeed seem a bit strange to the newcomer. Begin by considering that the type of keySelector, *Func<TSource, TKey>* is simply a delegate. Before C# 3.0, you would call such a method by passing a delegate as a parameter, for example:
```
IEnumerable<string> sortedWords = words.OrderBy(new Func<string, int>(mySelectorMethod));
```
where mySelectorMethod is the name of an ordinary method which takes a *string* as a parameter and returns an *int*. (As a side point, I suppose you could use anonymous delegates, but let's not go there for now.) Also, note that this example is purely illustrative, as LINQ is almost always used with .NET 3.5/C# 3.0 (though I believe it can be used with either/both .NET 2.0/C# 2.0 - someone correct me if I'm wrong). Since C# 3.0, methods can be defined inline as lambda expressions, which are intended to be used in precisely such circumstances as these. Read over the MSDN article on lambda expressions (linked above) if you want to get a proper introduction, but here I will simply describe the use in this specific context. As you state, your code (in C# 3.0) is something like the following:
```
var sortedWords = words.OrderBy(a => a.Length);
```
The part of the expression that is `a => a.Length` is the *lambda expression*, which is really just shorthand for declaring a function inline. The syntax of lambda expressions is quite simple for the most part; to the left of the => the arguments are specified, generally in the form *(arg1, arg2, arg3)*, but since there's only one in this case you can omit the brackets. To the right of the => is the expression that is the return value of the function (lambda expression more accurately). Alternatively you can enclose actual code with a return statement within { and } though this is usually unnecessary. What I believe the C# compiler does is recognises the parameter passed to OrderBy as a lambda expression and then compiles it into a function and creates and passes the delegate for you. Note that lambda expressions can also be converted to *System.Linq.Expressions.Expression* objects (accessible expression trees) instead of delegates, but this is a much less common usage. Anyway, there's a lot going on behind the scenes here, but hopefully this should at least clarify why the type is *Func<TSource, TKey>* and how it relates to the lambda expression. As I said, read up on MSDN if you want a deeper understanding of LINQ/lambdas/delegates... | Confused about LINQ parameters | [
"",
"c#",
"linq",
""
] |
I've seen static methods written (but I've never run the code) which uses instance data from another class (instance based).
Usually, instance data work with instance methods and likewise for static fields/methods. What is the implication of working on static data in an instance method? I'm assuming it is frowned upon but I can't find any details on what will happen under the hood. Also, what about instance methods working with static data?
Thanks | When working with static data in an instance method, the only implication I can think of is synchronization in a multithreaded application. I can't think of any adverse implications when working with instance data from a static method. However, just because something *can* be done doesn't mean it *should* be done.
Here is a concrete example you provided.
> Class A is instance based and has an
> instance field called ProductPrice of
> double. Class B is static and has a
> static method called
> PlayAroundWithPrice(double price), and
> the coder passes in the ProductPrice
> field.
Obviously, there is nothing technically *illegal* with this example, but it goes against the grain for me. First of all, the ProductPrice field of Class A is obviously public since Class B can operate on it. For the purposes of encapsulation, I personally always make fields private and use a public property to access them. Second, because ProductPrice is a public field instead of a public property, there's no way for Class A to prevent ProductPrice from being set to invalid values (negative values, for example). Third (as stated above), if this example occurs in a multithreaded program, there could be synchronization issues. Fourth, I guess this is the real rub, why have a static method on Class B to operate on the field of Class A? Why not put the static method on Class A?
I don't know that I'd go as far as making this a hard-and-fast rule (perhaps simply a rule-of-thumb), but I would restrict using static methods for when you do not want to pay for the cost of constructing an object just to use the method.
For example, in the project I work on, I have an IPHeader class that will fully construct an IPHeader instance from a byte buffer. However, in most cases, I only need a couple of values from the IPHeader. So to avoid the costs associated with creating and garbage-collecting an IPHeader instance, I added a couple of static methods that will extract the values from the byte buffer directly.
I hope I've understood your question correctly. | I don't see a problem working on instance data from another object within a static method.
I assume that you mean, for example, passing an object's instance variable to a static method via a parameter, and that method then working on that variable.
Static just means you don't get **this**, but you could get **otherobject->something**
I don't think it would be any more frowned upon than just using a static method would be in the first place. | Static methods working on instance fields | [
"",
"c#",
""
] |
I have the following javascript being called to request a focus when page is loaded.
This code works 100% OK with Firefox and IE7, but Chrome and Safari do not seem to move the focus at all. How to make it work with all browsers?
```
document.getElementById("MyFlashFile").focus();
``` | Ensure this code is being called after the **entire** page has been rendered. It's probably being called above the HTML it refers to, so the element will not exist yet.
Various JavaScript frameworks have utilities to tell you when the [DOM is ready](http://docs.jquery.com/Tutorials:Introducing_%24(document).ready()). | It took me hours searching the Internet, but finally I found a solution that works on the lastest versions of IE, Firefox, Chrome and Safari.
The following code solves the problem for good:
```
<head>
<script type="text/javascript" src="swfobject.js"></script>
<script>
function setFocusOnFlash() {
var f=swfobject.getObjectById('myFlashObjectId');
if (f) { f.tabIndex = 0; f.focus(); }
}
</script>
</head>
<body onload="setFocusOnFlash()">
```
This example assumes the flash is embedded using the SWFObject library. If not, you should set the f variable to the Object or Embed tag which holds the flash movie.
**Edited on 5 May 2012**: Well, unfortunately it seems that the `tabIndex` workaround no longer works for all combinations of browser (Chrome/Safari) and operating system.
For instance, currently Chrome 18 on Windows fails.
See the link below, provided by *Christian Junk*, to get the status of the problem's resolution. | Object Focus problem with Safari and Chrome browsers | [
"",
"javascript",
"flash",
"actionscript-3",
"safari",
""
] |
**Summary of answers:
Don't do it. The legal and financial implications will be disastrous. Look for established third party solutions or hire an expert. Never store any sensitive information on a shared server. Research for the most appropriate encryption mechanism.**
I am buiding a website for a customer that needs to store his clients' bank info (routing + account number) in the db for direct deposit. Here are some specifics:
1) The website will initially be on a shared hosting server (this is my first concern).
2) I am using PHP/MySQL.
3) I plan on using mcrypt.
4) The key will be located outside the web root.
Please let me know your thoughts. If possible, please provide me with some resources on ACH processing.
Thanks!
**EDIT: I expected such response as I am terrified of security issues out there also. I have expressed my concern to my customer and this will be a good support.**
**EDIT 2: Will walk away from this. Was not happy with the idea in the first place! Will investigate PayPal's Mass Payment API.** | I think you can solve this problem without storing any bank information yourself through using something like [Paypal's Mass Payment API](https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_masspay). That way, your client can pay people, and PayPal stores all the information so you don't have to.
If you want to read about all of the steps you need to take to even have a remote possiblity of securing your client's sensitive financial data, google '[PCI Compliance](http://en.wikipedia.org/wiki/PCI_DSS)'
If you're not deathly afraid of storing financial data online, you're horribly naive. | 1) The website will initially be on a shared hosting server (this is my first concern).
--REALLY BAD. Not having absolute administrative control over the server, and be able to keep other people out is a really big problem.
I would be really concerned that you're directly accessing the database from the front end web server. That's a big no-no with financial data.
Even if you have the strongest encryption algorithm ever, what's to prevent someone from hijacking your system and using it to decrypt the data for them. They won't need the key, they'll just need your application to do the work for them. This is assuming you're using a single key to encrypt and decrypt the data or you are retrieving the data from the db to show to the users of the system.
Ok here's the thing. If you have to ask these questions, you don't have the technical expertise to do this correctly. I'm not trying to sound mean, it's just a fact. I would go work with a group of seasoned people who do this professionaly first. There will be a lot of things that aren't mentioned here that will need to be taken into consideration. there' a lot of stuff about security that isn't written down per se. Things that you won't pick up on from reading a book. This is a really hard thing to build, becuase there are big rewards to people who break into financial systems. | Best practices for storing bank information in a database | [
"",
"php",
"mysql",
"mcrypt",
""
] |
I want to post my 5 recent twitters on my website. I've build a datagrid with XMLTextReader in C# which reads the feed but the problem I face is that it shows ALL the feeds and I can't find a way to only show 5. Any idea's?
```
XmlTextReader reader = new XmlTextReader("http://some.rss/feed.rss");
DataSet ds = new DataSet();
ds.ReadXml(reader);
dg.DataSource = ds.Tables[2];
dg.AutoGenerateColumns = false;
dg.AllowPaging = false;
dg.DataBind();
``` | to answer directly your question:
```
<asp:GridView ID="gv" runat="server"
PageSize="5" AllowPaging="true">
<PagerSettings Visible="false" />
</asp:GridView>
```
But I'm just wondering, why not trying to use a C# wrapper for Twitter API?
like:
<http://devblog.yedda.com/index.php/2007/05/16/twitter-c-library/>
or follow the fantastic post of Petar in
<http://blogs.vertigo.com/personal/petar/Blog/archive/2008/06/23/twitter-wcf-client.aspx>
**P.S.** add twitter to your tags! | How about the simple solution of manually deleting all the rows from the DataTable except the first 5? | Only show X rows from DataGrid | [
"",
"c#",
"xml",
"datagrid",
"rss",
"twitter",
""
] |
I tried to find a place where I can find ready to copy list of all functions and classes available in each stl header file.
Looking through /usr/include/c++ is not so convenient as I expected.
Google very often shows
<http://www.cplusplus.com/reference/>
which is not so convenient to copy and paste.
Does anyone knows a good place to look?
Thanks.
**Edit:**
This is for an "auto stl header" plugin. So I don't need an examples. Just correspondence of each std::xxx to <yyy>.
**For Vim users and those who might be interested**
Using half given links and the std header files I've created auto std include vim plugin. I can't choose right one answer by now. But the method with which I can receive such kind of information more automatically is still considering by me.
Thanks. | I'm not sure if I understood correctly, but if you need a reference and a list of functions from the headers, then maybe [dinkumware](http://www.dinkumware.com/manuals/) manuals. If you want examples then try [this](http://www.java2s.com/Code/Cpp/CatalogCpp.htm). If you want an absolute and the true reference then go to the ISO standard.
I forgot to mention [SGI STL programmers guide](http://www.sgi.com/tech/stl/)... | One site that I've always found useful for STL is [SGI's STL page](http://www.sgi.com/tech/stl/).
Have a look in the Index page and the Index by Category page.
HTH
cheers, | list of public functions/classes with their corresponded header files | [
"",
"c++",
"stl",
""
] |
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing *python*.
The only thing I have found so far that lets me do this in the most obvious way possible is [web.py](http://webpy.org/) but I have slight concerns on its performance.
For those of you using nginx(or another flavour)+mod\_wsgi+web.py... how's performance? Can it be improved further?
For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?
I'd like to hear about all the conspicuous, minimal yet powerful approaches. | It's hilarious how, even prompted with a question asking how to write without a framework, everyone still piles in to promote their favourite framework. The OP whinges about not wanting a “heavyweight framework”, and the replies mention *Twisted*, of all things?! Come now, really.
Yes, it *is* perfectly possible to write straight WSGI apps, and grab bits of wanted functionality from standalone modules, instead of fitting your code into one particular framework's view of the world.
To take this route you'll generally want to be familiar with the basics of HTTP and CGI (since WSGI inherits an awful lot from that earlier specification). It's not necessarily an approach to recommend to beginners, but it's quite doable.
> I'd like to hear about all the conspicuous, minimal yet powerful approaches
You won't *hear* about them, because no-one has a tribal interest in promoting “do it yourself” as a methodology. Me, I use a particular standalone templating package, a particular standalone form-reading package, a particular data access layer, and a few home-brew utility modules. I'm not writing to one particular philosophy I can proselytise about, they're all just boring tools that could be swapped out and replaced with something else just as good. | The way to go is [wsgi](http://wsgi.org).
WSGI is the **Web Server Gateway Interface**. It is a specification for web servers and application servers to communicate with web applications (though it can also be used for more than that). **It is a Python standard, described in detail in [PEP 333](http://www.python.org/dev/peps/pep-0333/)**.
All current frameworks support wsgi. A lot of webservers support it also (apache included, through [mod\_wsgi](http://code.google.com/p/modwsgi/)). It is the way to go if you want to write your own framework.
Here is hello world, written to wsgi directly:
```
def application(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
```
Put this in a `file.py`, point your `mod_wsgi` apache configuration to it, and it will run. Pure python. No imports. Just a python function.
If you are really writing your own framework, you could check [werkzeug](http://werkzeug.pocoo.org/). It is not a framework, but a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules. Takes the boring part out of your hands. | How do I use python for web development without relying on a framework? | [
"",
"python",
"performance",
"web.py",
""
] |
I'm programming in C++ CLI with VS.Net C++ 2008. I'm seeking a tool that can create my C++ source definitions (\*.cpp) from the header files. Does such a tool exist? please advise, thanks. | For pure C++ code, if its possible to add a 3rd party generator to the VS.Net frame work, then I would strongly recommend: [lzz](http://www.lazycplusplus.com/).
This tools takes a text file as input, and will provide a header and source file for you as appropriate. The following is the basic example from the web page:
> ```
> // A.lzz
> class A
> {
> public:
> inline void f (int i) { ... }
> void g (int j = 0) { ... }
> };
> bool operator == (A const & a1, A const & a2) { ... }
> ```
>
> Lzz will generate a header file:
>
> ```
> // A.h
> #ifndef LZZ_A_h
> #define LZZ_A_h
> class A
> {
> public:
> void f (int i);
> void g (int j = 0);
> };
> inline void A::f (int i) { ... }
> bool operator == (A const & a1, A const & a2);
> #endif
> ```
>
> And a source file:
>
> ```
> // A.cpp
> #include "A.h"
> void A::g (int j) { ... }
> bool operator == (A const & a1, A const & a2) { ... }
> ``` | Code::Blocks IDE seems to have a "Insert / All class methods without Implementation" method
which generates some basic skeleton of the functions. | C++ Header To Source? | [
"",
"c++",
""
] |
I recently used a Java Web Start application. I launched it from my web browser using an embedded jnlp link in the page I was viewing. The application was downloaded, launched and worked just fine. It had access to my local file-system and remembered my preferences between restarting it.
What I want to know is why are Java Web Start applications not a more popular delivery format for complex applications on the web? Why do developers often spend considerable time & energy replicating desktop functionality in html/javascript when the power of a desktop application could be delivered more easily using Java & Java Web Start?
I know that in some corporate environments, e.g banking, they are relatively popular ways of delivering complex trading applications to clients, but why are they not pervasive across the web as a whole?
(For the sake of discussion let's assume a world where: download sources are "trusted" & applications are "signed" (i.e. no security concerns), download speeds are fast (load time is quick) and developers know Java (in the numbers they know html/js/php)). | I think the reason is not security nor startup time of the app. Let's understand what's behind the scene before we find out the root cause.
Java Control Panel has settings that allow users to use the default browser's proxy settings or to override them. In other words, infrastructure teams are able to customize the Windows or OS installation images to have JVM pre-installed with enterprise proxy settings. So I believe this is not an issue at all.
Java Web Start actually caches all apps with customizable settings in Java Control Panel. Once the app is cached, the app is "installed" just like other apps. Although first time execution may be slow, the second time will be fast due to JVM's smart memory allocation technique. So start up time could be an issue but a lot of web sites (even enterprise internal) are now migrated to portal. A web portal normally contains lots of unused libraries for development purposes due to the fact that the portal itself does not anticipate what kinds of portlets are built and deployed on a specific page. Therefore, downloading a single portal page could consume up to MBs and complete a page in more than 5 seconds; this is only one page and caching helps up to 30% but there are still lots of HTML/Javascript/CSS components required to download every time. With this, I am sure Java Web Start is an advantage here.
Java Web Start does not download again if it is cached as long as the server copy is NOT upgraded. Therefore, if, e.g. a project management software like MS Project, is completed using SmartClient (similar to JWS), the information exchange between the client and server would be purely data without presentation like browser's full page refresh. Even with the help of Ajax, it doesn't eliminate full page download entirely. Besides, a lot of companies consider Ajax to be immature and unsecured still. That is why Ajax is a hot topic in the circles of developers but not within enterprise software yet. With that in mind, JWS apps definitely have more advantages such as how JWS apps are deployed and executed in sandboxes, signed, and have much more interactive GUI.
Other advantages include faster development (easier to debug in code and performance), responsive user interface (does not require Comet Servers to provide PUSH functionality), and executing faster (for sure because client computers renders GUI without translation like HTML/Javascript/CSS, and less data processing).
After all these, I haven't touched the question yet, why JWS is not so famous?
My opinion is that it is the same as Brian Knoblauch's comment, it's without awareness.
IT folks are too attracted by the hype of Web Technologies, Ajax PUSH, GWT, and all those buzz words make them bias towards the fun of using different technologies or to resolve technical challenges instead of what's really working for the clients.
Take a look at Citrix. I think Citrix is actually a great idea. Citrix allows you to build your own app farms behind the scene. There are tons of upgrade and implementation strategies you can go for without impact to client experience. Citrix deployment is extremely easy, stable and secure. Enterprises are still using it. However, I think JWS is even better than Citrix. The idea of JWS is to run apps on client machines instead of hosting tons of server farms where client machines are capable of running these apps themselves. This saves a company a lot of money!!! With JWS, development team can still build business logic and data on server side. However, without the web processing unit and let the client computers do the rendering process, it greatly reduces the amount of network consumption and server processing power.
Another example of why JWS is an amazing idea is Blackberry MDS. Blackberry apps are actually Java apps translated from Javascript. With BB's MDS studio, you use the GUI tool to build BB app GUI, coding GUI logic in Javascript. Then apps are then translated and deployed on a BES server. Then the BES server will distribute these apps to BB. On each BB, it runs a thin Java App with GUI rendering and networking capability only. Whenever the app requires data, it communicates with the BES through web services to consume services from other servers. Isn't this just JWS BB version? It's been extremely successful.
Finally I think JWS is not popular because of how Sun advertises it. BB never advertises how good their BB Java apps are, they believe clients won't even care what is it. BB advertises the benefits of using MDS to develop apps: Fast, Cost Saving, Business Return.
Just my, a bit long, 2 cents... :) | A major roadblock for Java Webstart is probably that you still need to have a JVM installed before it can even attempt to download and start your application. Everyone has a browser. Not everyone has a JVM.
**Edit:**
I've since acquired some hands-on webstart experience and can now add these two points:
* The [Deployment Toolkit script](http://download.oracle.com/javase/tutorial/deployment/webstart/deploying.html) and the modularized JVM released somewhere around Java 1.6u10 make the JVM requirement less problematic since it can automatically download a JVM and the API core and start the program wile downloading the rest.
* Web Start is seriously buggy. Even among the Java 1.6 releases there was one which downloaded the entire app every time, and another which downloaded it and then failed with an obscure error message. All in all, I cannot really recommend relying on such a fragile system. | Java Web Start - Popularity | [
"",
"java",
"jnlp",
"java-web-start",
""
] |
I need to profile a program to see whether any changes need to be made regarding performance. I suspect there is a need, but measuring first is the way to go. This is not that program, but it illustrates the problem I'm having:
```
#include <stdio.h>
int main (int argc, char** argv)
{
FILE* fp = fopen ("trivial.c", "r");
if (fp)
{
char line[80];
while (fgets (line, 80, fp))
printf (line);
fclose (fp);
}
return 0;
}
```
Here's what I did with it:
```
% gcc trivial.c -pg -o trivial
% ./trivial
...
% gprof trivial gmon.out
```
Granted, this is a trivial program, but I would have thought it would make some kind of blip on the profiling radar. It didn't:
```
called/total parents
index %time self descendents called+self name index
called/total children
0.00 0.00 1/1 __start [1704]
[105] 0.0 0.00 0.00 1 _main [105]
-----------------------------------------------
% cumulative self self total
time seconds seconds calls ms/call ms/call name
0.0 0.00 0.00 1 0.00 0.00 _main [105]
Index by function name
[105] _main
```
Can anyone guide me here? I would like the output to reflect that it called fgets and printf at least 14 times, and it did hit the disk after all - there should be some measured time, surely.
When I run the same command on the real program, I get more functions listed, but even then it is not a complete list - just a sample.
Perhaps gprof is not the right tool to use. What is?
This is on OS X Leopard.
Edit: I ran the real program and got this:
```
% time real_program
real 4m24.107s
user 2m34.630s
sys 0m38.716s
``` | There are certain commonly-accepted beliefs in this business, that I would suggest you examine closely.
One is that the best (if not only) way to find performance problems is to measure the time each subroutine takes and count how many times it is called.
That is top-down. It stems from a belief that the forest is more important than the trees. It is based on myths about "speed of code" and "bottlenecks". It is not very scientific.
A performance problem is more like a bug than a quantitative thing. What it is doing wrong is it is *wasting time*, and it needs to be fixed. It is based on a simple observation:
**Slowness consists of time being spent for poor reasons.**
To find it, sample the program state at random slivers of clock time, and investigate their reasons.
If something is causing slowness, then that fact alone exposes it to your samples. So if you take enough samples, you will see it. You will know approximately how much time it is costing you, by the fraction of samples that show it.
A good way to tell if a sliver of time is being spent for a good reason is to look carefully at the call stack. Every function invocation on the stack has an implicit reason, and if any of those reasons are poor, then the reason for the entire sample is poor.
Some profilers tell you, at the statement level, what each statement is costing you.
Personally, I just randomly halt the program several times. Any invocations showing up on multiple samples are likely candidates for suspicion. It never fails.
You may say "It's not accurate." It's extremely accurate. It precisely pinpoints the instructions causing the problem. It doesn't give you 3 decimal places of timing accuracy. I.e. it is lousy for measurement, but superb for diagnosis.
You may say "What about recursion?". Well, what about it?
You may say "I think that could only work on toy programs." That would be just wishing. In fact large programs tend to have more performance problems, because they have deeper stacks, thus more opportunity for invocations with poor reasons, and sampling finds them just fine, thanks.
Sorry to be a curmudgeon. I just hate to see myths in what should be a scientifically-based field.
[MORE](https://stackoverflow.com/questions/566014/why-does-my-c-code-run-slow/567926#567926) | I think that you could try various Valgrind tools, especially `callgrind` (used to get call counts and inclusive cost for each call happening in your program).
There are various nice visualisation tools for the valgrind output. I don't know about particular tools for OS X though. | How can I get better profiling? | [
"",
"c++",
"c",
"macos",
"gcc",
"profiling",
""
] |
I have a vector that I am loading with a know amount of elements (N).
The processing dynamically creates new elements, which are appended to the vector.
I am expecting about 2 \* N additional elements to be created,
so I resize the vector to 3 \* N.
If the additional elements exceed that, I would like a program abort, rather than a dynamic expansion of the vector.
**Is there a way to detect that, that is portable between AIX/TRU64/Linux?** | Detect what? Whether the vector will be resized? Whether it has been?
The only real way to achieve this is to provide checking functionality either in a custom allocator or a function that adds elements to the vector.
e.g
```
template<class T>
void add_element(std::vector<T>& container, T const& v)
{
if (container.capacity()+1 >= 3*N)
{
// terminate/exception/whatever
}
container.push_back(v);
}
``` | Why are you using a vector? The whole point of the vector is to dynamically expand when needed.
Instead of making a class to delegate to the vector, just make a class to delegate to a simple array. Have your push\_back check the size and abort when needed. | vector resizing - portable way to detect | [
"",
"c++",
"cross-platform",
"vector",
""
] |
Pretty basic question I think - I'm performing this function:
```
private double convertMetersToFeet(double meters)
{
//function converts Feet to Meters.
double toFeet = meters;
toFeet = meters*3.2808; // official conversion rate of Meters to Feet
return toFeet;
}
```
Problem is the output; for example I get 337.36080000000004 from an input of 101.
What's the appropriate practice for truncating the floating points?
As the answers below assumed, I'd want 4 significant figures to remain consistent with my conversion ratio. | You can use a [NumberFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/NumberFormat.html) instance.
```
NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMinimumFractionDigits(4);
nf.setMaximumFractionDigits(4);
System.out.println(nf.format(feet));
```
Or you can use [DecimalFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html).
```
DecimalFormat df = new DecimalFormat("0.0000");
System.out.println(df.format(feet));
```
The latter (DecimalFormat), is to be used when you explicitly want to state the format and the former (NumberFormat), when want localized settings.
For four consistent fractional figures, there is no need to drag in BigDecimal, if your aren't working with really long distances. | I'm answering my own question for posterity's sake. I used the DecimalFormat answer above, but the answers failed to take into account the return type of the method.
Here's the finished code:
```
private double convertMetersToFeet(double meters)
{
//function converts Feet to Meters.
double toFeet = meters;
toFeet = meters*3.2808; // official conversion rate of Meters to Feet
String formattedNumber = new DecimalFormat("0.0000").format(toFeet); //return with 4 decimal places
double d = Double.valueOf(formattedNumber.trim()).doubleValue();
return d;
}
``` | Java floating point math - (conversion for feet/meters) | [
"",
"java",
"floating-point",
""
] |
Inspired by the question [Difference in initalizing and zeroing an array in c/c++ ?](https://stackoverflow.com/questions/453432/difference-in-initalizing-and-zeroing-an-array-in-c-c), I decided to actually examine the assembly of, in my case, an optimized release build for Windows Mobile Professional (ARM processor, from the Microsoft Optimizing Compiler). What I found was somewhat surprising, and I wonder if someone can shed some light on my questions concerning it.
These two examples are examined:
```
byte a[10] = { 0 };
byte b[10];
memset(b, 0, sizeof(b));
```
They are used in the same function, so the stack looks like this:
```
[ ] // padding byte to reach DWORD boundary
[ ] // padding byte to reach DWORD boundary
[ ] // b[9] (last element of b)
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ] // b[0] = sp + 12 (stack pointer + 12 bytes)
[ ] // padding byte to reach DWORD boundary
[ ] // padding byte to reach DWORD boundary
[ ] // a[9] (last element of a)
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ] // a[0] = sp (stack pointer, at bottom)
```
The generated assembly with my comments:
```
; byte a[10] = { 0 };
01: mov r3, #0 // r3 = 0
02: mov r2, #9 // 3rd arg to memset: 9 bytes, note that sizeof(a) = 10
03: mov r1, #0 // 2nd arg to memset: 0-initializer
04: add r0, sp, #1 // 1st arg to memset: &a[1] = a + 1, since only 9 bytes will be set
05: strb r3, [sp] // a[0] = r3 = 0, sets the first element of a
06: bl memset // continue in memset
; byte b[10];
; memset(b, 0, sizeof(b));
07: mov r2, #0xA // 3rd arg to memset: 10 bytes, sizeof(b)
08: mov r1, #0 // 2nd arg to memset: 0-initializer
09: add r0, sp, #0xC // 1st arg to memset: sp + 12 bytes (the 10 elements
// of a + 2 padding bytes for alignment) = &b[0]
10: bl memset // continue in memset
```
Now, there are two things that confuses me:
1. What's the point of lines 02 and 05? Why not just give &a[0] and 10 bytes to memset?
2. Why isn't the padding bytes of a 0-initialized? Is that only for padding in structs?
Edit: I was too curious to not test the struct case:
```
struct Padded
{
DWORD x;
byte y;
};
```
The assembler for 0-initializing it:
```
; Padded p1 = { 0 };
01: mov r3, #0
02: str r3, [sp]
03: mov r3, #0
04: str r3, [sp, #4]
; Padded p2;
; memset(&p2, 0, sizeof(p2));
05: mov r3, #0
06: str r3, [sp]
07: andcs r4, r0, #0xFF
08: str r3, [sp, #4]
```
Here we see in line 04 that a padding indeed occur, since `str` (as opposed to `strb`) is used. Right? | The reason for lines 2 and 5 is because you specified a 0 in the array initializer. The compiler will initialize all constants then pad out the rest using memset. If you were to put two zeros in your initializer, you'd see it strw (word instead of byte) then memset 8 bytes.
As for the padding, it's only used to align memory accesses -- the data shouldn't be used under normal circumstances, so memsetting it is wasteful.
Edit: For the record, I may be wrong about the strw assumption above. 99% of my ARM experience is reversing code generated by GCC/LLVM on the iPhone, so my assumption may not carry over to MSVC. | Both bits of code are bugfree. The two lines mentioned aren't smart, but you're just proving that this compiler is emitting suboptimal code.
Padding bytes are usually only initialized if that simplifies the assembly or speeds up the code. E.g if you have padding between two zero-filled members, it's often easier to zero-fill the padding as well. Also, if you have padding at the end and your memset() is optimized for multi-byte writes, it may be faster to overwrite that padding too. | Strange assembly from array 0-initialization | [
"",
"c++",
"c",
"compiler-construction",
"assembly",
""
] |
Consider the following Python code:
```
30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey"
31 url_object = urllib.request.urlopen(url);
32 print(url_object.read());
```
When this is run, an Exception is thrown:
```
File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
```
However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?
Any thoughts? | If you want to do Google searches "properly" through a programming interface, take a look at [Google APIs](http://code.google.com/more/). Not only are these the official way of searching Google, they are also not likely to change if Google changes their result page layout. | this should do the trick
```
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = "http://www.google.com/search?hl=en&safe=off&q=Monkey"
headers={'User-Agent':user_agent,}
request=urllib2.Request(url,None,headers) //The assembled request
response = urllib2.urlopen(request)
data = response.read() // The data u need
``` | Why does Google Search return HTTP Error 403? | [
"",
"python",
"google-search",
""
] |
What is the difference between [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) and [BOO](http://boo.codehaus.org/)? Is there a need for 2 Python-like languages? | [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supported).
[Boo](http://boo.codehaus.org/)'s stated aim is to be a "wrist-friendly [dynamic] language for the CLI." It takes a lot of inspiration from Python, but diverges on four main points:
1. It's designed specifically to take good advantage of the .NET platform
2. The designer diverges from Python syntax where he doesn't agree with the design decisions (most notably, lack of explicit self)
3. The language is explicitly designed to be "wrist friendly" -- that is, to minimize the need for the Shift key or other multi-key combinations to be used.
4. Boo is statically typed by default, but allows optional duck typing.
There are some other minor differences in implementation/performance, but the divergent design goals above should (IMO) inform your choice of languages.
Two more things to take into account are maturity and community. Python is much more mature than Boo, and has a much larger community. IronPython also has the explicit blessing of Microsoft. | IronPython is a python implementation wheras Boo is another language with a python-esque syntax. One major difference is that Boo is statically typed by default.
I'm sure there are more differences, I've only looked at Boo briefly, but I've been meaning to look at bit deeper (so many languages so little time!).
Here is a list of Boo gotchas for python programmers which sums up the differences quite nicely:
* <http://boo.codehaus.org/Gotchas+for+Python+Users> | BOO Vs IronPython | [
"",
"python",
"clr",
"ironpython",
"boo",
""
] |
Given this C API declaration how would it be imported to C#?
```
const char* _stdcall z4LLkGetKeySTD(void);
```
I've been able to get this far:
```
[DllImport("zip4_w32.dll",
CallingConvention = CallingConvention.StdCall,
EntryPoint = "z4LLkGetKeySTD",
ExactSpelling = false)]
private extern static const char* z4LLkGetKeySTD();
``` | Try this
```
[DllImport("zip4_w32.dll",
CallingConvention = CallingConvention.StdCall,
EntryPoint = "z4LLkGetKeySTD",
ExactSpelling = false)]
private extern static IntPtr z4LLkGetKeySTD();
```
You can then convert the result to a String by using Marshal.PtrToStringAnsi(). You will still need to free the memory for the IntPtr using the appropriate Marshal.Free\* method. | Always use C++ const char\* or char\* and not std::string.
Also keep in mind that char in C++ is a sbyte in C#
and unsigned char is a byte in C#.
It is advisable to use unsafe code when dealing with DllImport.
```
[DllImport("zip4_w32.dll",
CallingConvention = CallingConvention.StdCall,
EntryPoint = "z4LLkGetKeySTD",
ExactSpelling = false)]
private extern static sbyte* or byte* z4LLkGetKeySTD();
void foo()
{
string res = new string(z4LLkGetKeySTD());
}
``` | How to import const char* API to C#? | [
"",
"c#",
"dllimport",
""
] |
I'm using C++ templates to pass in Strategy functors to change my function's behavior. It works fine. The functor I pass is a stateless class with no storage and it just overloads the () operator in the classic functor way.
```
template <typename Operation> int foo(int a)
{
int b=Operation()(a);
/* use b here, etc */
}
```
I do this often, and it works well, and often I'm making templates with 6 or 7 templated functors passed in!
However I worry both about code elegance and also efficiency. The functor is stateless so I assume the Operation() constructor is free and the evaluation of the functor is just as efficient as an inlined function, but like all C++ programmers I always have some nagging doubt.
My second question is whether I could use an alternate functor approach.. one that does not override the () operator, but does everything in the constructor as a side effect!
Something like:
```
struct Operation {
Operation(int a, int &b) { b=a*a; }
};
template <typename Operation> int foo(int a)
{
int b;
Operation(a,b);
/* use b here, etc */
}
```
I've never seen anyone use a constructor as the "work" of a functor, but it seems like it should work. Is there any advantage? Any disadvantage? I do like the removal of the strange doubled parenthesis "Operator()(a)" , but that's likely just aesthetic. | > Any disadvantage?
* Ctors do not return any useful value -- cannot be used in chained calls (e.g. foo(bar()).
* They can throw.
* Design point of view -- ctors are object creation functions, not really meant to be workhorses. | 1. Compilers actually inline the empty constructor of Operation (at least gcc in similar situations does, except when you turned off optimization)
2. The disadvantage of doing everything in the constructor is that you cannot create a functor with some internal state this way - eg. functor for counting the number of elements satisfying a predicate. Also, using a method of a real object as a functor allows you to store the instance of it for later execution, something you cannot do with your constructor approach. | Functor class doing work in constructor | [
"",
"c++",
"templates",
"functor",
"strategy-pattern",
""
] |
I've got a page that has a category list at the top, and should normally list posts below it. The category list is created using:
```
<?php $display_categories = array( 4, 7, 8, 9, 21, 1); $i = 1;
foreach ( $display_categories as $category ) { ?>
<div>
<?php single_cat_title(); ?> //etc
</div>
<?php }
?>
```
However, this seems to make the post loop order posts by category. I want it to ignore category ordering and order by date in descending order. I've created a new WP\_Query since according to the docs you can't use query\_posts() twice, so just in case.
```
<?php $q = new WP_Query( "cat=-1&showposts=15&orderby=date&order=DESC" );
if ( $q->have_posts() ) :
while ( $q->have_posts() ) : $q->the_post(); ?>
the_title(); // etc
endwhile;
endif;
?>
```
However, this **still** seems to be ordered by category (the same order as the list above) and then by date, as opposed to just by date. | I've had problems with this before as well.
Try this:
```
<?php
global $post;
$myposts = get_posts( 'numberposts=5' );
foreach( $myposts as $post ) : setup_postdata( $post ); ?>
<div <?php post_class(); ?>>
<div class="title">
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<p class="small"><?php the_time( 'F j, Y' ); ?> by <?php the_author(); ?></p>
</div>
<?php the_excerpt(); ?>
</div>
<?php endforeach;
?>
```
The important line is `global $post;`.
That should reset your global query. The `setup_postdata($post)` method is necessary to give you access to functions like `the_author()` or `the_content()`.
-Chris | query\_posts is finicky sometimes. Try something like this and see if it works:
```
query_posts(array('category__not_in'=>array(1),
'showposts'=>15,
'orderby'=>date,
'order'=>DESC));
```
Since that's not the issue, try adding update\_post\_caches($posts) to the second loop, like this:
```
<?php $q = new WP_Query("cat=-1&showposts=15&orderby=date&order=DESC");
if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); update_post_caches($posts); ?>
the_title(); // etc
endwhile; endif; ?>
```
Supposedly this [solves some plugin problems](http://codex.wordpress.org/The_Loop#Multiple_Loops_Example_3_-_Plugins). | How do I get wordpress to override a previous posts query? | [
"",
"php",
"wordpress",
""
] |
I have a service that user can configure to run during "off-peak" hours. They have the ability to set the time frame that the service can run.
For Example:
User A works 8am-5pm, so they want to schedule the app to run between 5:30pm and 7:30am.
User B works 9pm-6am, so they schedule the app to run between 6:30am and 8:30 pm.
The point is that the app uses their computer while they are not.
Given a DateTime of the current time, a DateTime of the start and a DateTime of the stop time, how can I check if current is between start and stop.
The tricky part for me is that the time can cross the midnight boundary. | If `startTime` and `endTime` represent a single time interval (it will only happen once, and `startTime` and `endTime` represent the date and the time to start/stop), then it's as easy as saying
```
bool isTimeBetween = someTime >= startTime && someTime <= endTime;
```
If it's a recurring event (happens every day, during some interval), you can do comparisons using the [`TimeOfDay`](http://msdn.microsoft.com/en-us/library/system.datetime.timeofday.aspx) property. (The recurring case is the one where you have to consider a start/stop that crosses midnight)
```
static public bool IsTimeOfDayBetween(DateTime time,
TimeSpan startTime, TimeSpan endTime)
{
if (endTime == startTime)
{
return true;
}
else if (endTime < startTime)
{
return time.TimeOfDay <= endTime ||
time.TimeOfDay >= startTime;
}
else
{
return time.TimeOfDay >= startTime &&
time.TimeOfDay <= endTime;
}
}
```
(Note: This code assumes that if `start == end`, then it covers all times. You made a comment to this effect on another post)
For example, to check if it's between 5 AM and 9:30 PM
```
IsTimeOfDayBetween(someTime, new TimeSpan(5, 0, 0), new TimeSpan(21, 30, 0))
```
If `startTime` and `endTime` are `DateTime`s, you could say
```
IsTimeOfDayBetween(someTime, startTime.TimeOfDay, endTime.TimeOfDay)
``` | So I assume from the question that you want to know if given a start time and end time for a day (not including the actual date, i.e., 1/1/1900 or something like that) to see if another time is with the time specified by start and end. E.g., if start is 9pm and end is 9am, accept 10pm but reject 10am.
You can do this either per time range types (times are equal, end is after start, end is before start) which is simple:
```
if (end==start) return true
else if (end>start) return start<=time && time<=end
else return !(time>end && time<start)
```
Or you can extend the range of start and end such that end is always after start as such:
```
if (end<=start) end += <24 hours>
if (time<start) time+= <24 hours>
return time<=end
``` | How can I check if the current time is between in a time frame? | [
"",
"c#",
"datetime",
""
] |
I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called [**psutil**](http://code.google.com/p/psutil/) for reading process information in a cross-platform way. One of the functions is a `pid_exists(pid)` function for determining if a PID is in the current process list.
Right now I'm doing this the obvious way, using [EnumProcesses()](http://msdn.microsoft.com/en-us/library/ms682629(VS.85).aspx) to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid\_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using `kill(pid, 0)` with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.
Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried [OpenProcess()](http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx) and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?
**NOTE**: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.
**EDIT**: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid\_exists() function isn't intended to replace proper error handling.
**UPDATE**: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much *faster* not slower. | [OpenProcess](http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx) could tell you w/o enumerating all. I have no idea how fast.
**EDIT**: note that you also need `GetExitCodeProcess` to verify the state of the process even if you get a handle from `OpenProcess`. | Turns out that my benchmarks evidently were flawed somehow, as later testing reveals OpenProcess and GetExitCodeProcess are much faster than using EnumProcesses after all. I'm not sure what happened but I did some new tests and verified this is the faster solution:
```
int pid_is_running(DWORD pid)
{
HANDLE hProcess;
DWORD exitCode;
//Special case for PID 0 System Idle Process
if (pid == 0) {
return 1;
}
//skip testing bogus PIDs
if (pid < 0) {
return 0;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
//invalid parameter means PID isn't in the system
if (GetLastError() == ERROR_INVALID_PARAMETER) {
return 0;
}
//some other error with OpenProcess
return -1;
}
if (GetExitCodeProcess(hProcess, &exitCode)) {
CloseHandle(hProcess);
return (exitCode == STILL_ACTIVE);
}
//error in GetExitCodeProcess()
CloseHandle(hProcess);
return -1;
}
```
Note that you do need to use `GetExitCodeProcess()` because `OpenProcess()` will succeed on processes that have died recently so you can't assume a valid process handle means the process is running.
Also note that `OpenProcess()` succeeds for PIDs that are within 3 of any valid PID (See [Why does OpenProcess succeed even when I add three to the process ID?](http://blogs.msdn.com/oldnewthing/archive/2008/06/06/8576557.aspx)) | Fast way to determine if a PID exists on (Windows)? | [
"",
"python",
"c",
"winapi",
"pid",
""
] |
I am using jQuery to retrieve a JSON object from a page method. I have a DAL which uses SubSonic and if I return objects created from SubSonic-generated classes I will clog up the pipes. :) You know, all public properties get serialized. I don't want a separate business layer for this application, because it's small and focused on read operations and yet another layer seems like an overkill. To avoid downloading some SubSonic bloated objects (possibly with sensitive information as well) and avoid building a separate layer I tried returning a list of objects, like this:
```
[WebMethod]
public static List<object> GetFiles()
{
FileCollection collection = DB
.Select()
.From(DataAccess.File.Schema)
.ExecuteAsCollection<FileCollection>();
List<object> files = new List<object>(collection.Count);
foreach (DataAccess.File file in collection)
{
files.Add(new {
file.FileId,
file.ApplicantFirstName,
file.ApplicantLastName,
file.UploadDate
}
);
}
return files;
}
```
It works and I get a nice JSON object in return (disregard the DateTime value):
```
[{"FileId":1,"ApplicantFirstName":"Paweł","ApplicantLastName":"Krakowiak","UploadDate":"\/Date(1235656448387
)\/"}]
```
Is this a good approach? I am concerned about `List<object>` - is it worse than returning say a `List<SomeDomainObject`>? Performance? Something else?
This is .NET 2.0, I can't use 3.5 features. At least anonymous types work... | Looks like there's nothing wrong with my approach. All that I want to do is to return a JSON object to the calling client (browser) to update the UI. This application does 99% read operations, so I am fine with it. I actually started adding a Services and Domain (I keep my business entities here) layers, but I'm going to throw them away. I really try to keep it simple for this application and don't add stuff I don't need. | The biggest recommendation might be to make it a "Collection" rather than a List, but with a simple webservice return, it isn't as big of a deal, as that recommendation is most typically in environments where the object still lives in a .NET assembly.
I think it is easy to read as well. | Quick way to return a list of custom objects from a page method w/o a separate BLL | [
"",
"c#",
"json",
".net-2.0",
"subsonic",
""
] |
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.
What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me? | For the STL at least there are tools available that will output more human-friendly error messages. See <http://www.bdsoft.com/tools/stlfilt.html>
For non-STL templates you'll just have to learn what the errors mean. After you've seen them a dozen times it becomes easier to guess what the problem is. If you post them here maybe somebody can help you figure it out. | You can try using a newer compiler. If you're using Visual C++ 6.0, switch to 9.0 and you'll see a huge jump in the helpfulness of the compiler errors.
Otherwise, my techniques are usually been to test out as small a section of code as possible until I get the errors isolated. This is probably the template system's greatest failing - there is no sensible way of debugging them.
In your own code, make liberal use of [compile-time asserts](http://www.boost.org/doc/libs/1_38_0/doc/html/boost_staticassert.html) to make usage problems a little easier to diagnose. | How do you debug heavily templated code in c++? | [
"",
"c++",
"debugging",
"templates",
"metaprogramming",
""
] |
I'm appending some HTML containing javascript.
```
<td onclick="toggleDay('+data+',this,\'tue\');">T</td>
```
and
```
<img src="img/cross.png" onclick="deleteAlarm('+data+');">
```
These two pieces of code are in the big amount of HTML I'm appending.
They work fine if they are already there when the page loads but not when I'm appending.
What do you suggest me to do? Is it needed some sort request for the DOM to re-interpret the JavaScript after the append or?
EDIT:
Just some more info, I'm with this problem, because I'm adding some stuff with AJAX to the database, and on success I'm appending the html to where it needs to be. Kinda the same way SO does with the comments.
Edit2:
Even with all the discussion about it, thanks for the answers, got it working. | I'd do it like this:
First add id attributes to your html:
```
<td id="toggleDayCell">T</td>
<img src="img/cross.png" id="crossImg">
```
Then have Javascript that runs on the onload event of the page and attaches to the events you're interested in.
In [PrototypeJS](http://www.prototypejs.org), it might look like this:
```
Event.observe(window, 'load', function(){
if( $('toggleDayCell') ) {
Event.observe( $('toggleDayCell'), 'click', function(event){
//do stuff here
}
}
if( $('crossImg') ) {
Event.observe( $('crossImg'), 'click', function(event) {
//do stuff here
}
}
});
```
Using something like Prototype (or jQuery) is nice because it takes care of cross-browser compatibility. | Are you appending the HTML via AJAX? If so you will have to manually eval() the JavaScript that you are returning. You could wrap the response in a div and do something like this:
```
wrapper.getElementsByTagName("script")
// for script in wrapper...
eval(script.innerHTML)
```
If you are using a library like prototype it would be much simpler as you can pass the response to the evalScripts() method. | Appended HTML that contains javascript doesn't run, how can I make it run? | [
"",
"javascript",
"html",
"dom",
"dom-manipulation",
""
] |
I'm looking to create a reusable function that will generate a random key with printable ACSII characters of chosen length (anywhere from 2 to 1000+). I'm thinking printable ASCII characters would be 33-126. They key does not need to be completely unique, just unique if generated at the exact same millisecond (so `uniqid()` won't work).
I'm thinking a combination of `chr()` and `mt_rand()` might work.
Is this the way to go, or is something else the best method?
**Edit:** `uniqid()` will also not work because it doesn't have a length parameter, it's just whatever PHP gives you.
**My Idea**: This is what I came up with:
```
function GenerateKey($length = 16) {
$key = '';
for($i = 0; $i < $length; $i ++) {
$key .= chr(mt_rand(33, 126));
}
return $key;
}
```
Are there any problems with this?
**Another Edit:** Most of the other questions deal with password generation. I want a wider variety of characters and I don't care about `1` vs `l`. I want the maximum number of possible keys to be possible.
**Note: the generated key does not necessarily have to be cryptographically secure.** | **Update (12/2015): For PHP 7.0, you should use [`random_int()`](https://www.php.net/manual/en/function.random-int.php) instead of `mt_rand` as it provides "cryptographically secure values"**
Personally, I like to use `sha1(microtime(true).mt_rand(10000,90000))` but you are looking for more of a customizable approach, so try this function (which is a modification to your request of [this answer][1]):
```
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
```
Still, this will probably be significantly slower than uniqid(), md5(), or sha1().
**Edit:** Looks like you got to it first, sorry. :D
**Edit 2:** I decided to do a nice little test on my Debian machine with PHP 5 and eAccelerator (excuse the long code):
```
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
function rand_sha1($length) {
$max = ceil($length / 40);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= sha1(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
function rand_md5($length) {
$max = ceil($length / 32);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= md5(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_char(1000);
echo "Rand:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_sha1(1000);
echo "SHA-1:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_md5(1000);
echo "MD5:\t".(microtime(true) - $a)."\n";
```
Results:
```
Rand: 2.09621596336
SHA-1: 0.611464977264
MD5: 0.618473052979
```
So my suggestion, if you want speed (but not full charset), is to stick to MD5, SHA-1, or Uniqid (which I didn't test.. yet)
[1]: [Short unique id in php](https://stackoverflow.com/questions/307486/short-unique-id-in-php/307773#307773) | None of the answers here are sufficient if you want cryptographic-strength randomness (is there a determined attacker trying to guess what your random keys are?). Hashing the time is not secure, an attacker can greatly speed up their search by guessing around the time they think your server generated the key, and it's easy to search over all milliseconds in a given year, even on a commodity laptop (it's a 35 bit search space). Also, the suggestion to just run the results of `uniqid()` or some other weak random source through a hash function to "expand it" is dangerous-this doesn't make an attacker's search harder once they find out that you did this.
If you really need crypto-level security, you should read from /dev/random, the following code should work for you in any POSIX-compliant system (anything but Windows):
```
#Generate a random key from /dev/random
function get_key($bit_length = 128){
$fp = @fopen('/dev/random','rb');
if ($fp !== FALSE) {
$key = substr(base64_encode(@fread($fp,($bit_length + 7) / 8)), 0, (($bit_length + 5) / 6) - 2);
@fclose($fp);
return $key;
}
return null;
}
```
If you need a bit more speed, you can read from 'dev/urandom' instead. | What is the best way to generate a random key within PHP? | [
"",
"php",
"random",
""
] |
I am trying to use the Extensibility Method Definitions from my datacontext.designer.cs file to do some validation.
So I created a new file and added this code:
```
public partial class LawEnforcementDataContext : System.Data.Linq.DataContext
{
partial void InsertCourse(Course instance) // this definition copied from generated file
{
ValidateCourse(instance);
this.ExecuteDynamicInsert(instance);
}
partial void UpdateCourse(Course instance) // this definition copied from generated file
{
ValidateCourse(instance);
this.ExecuteDynamicUpdate(instance);
}
private void ValidateCourse(Course instance)
{
if (instance.StartDate > instance.EndDate)
{
throw new ApplicationException("Start date cannot be later than end date.");
}
}
}
```
I can't compile because of these errors:
```
Error 1 No defining declaration found for implementing declaration of partial method 'LawEnforcementDataContext.InsertCourse(reservation.lawenforcement.Course)'
Error 2 No defining declaration found for implementing declaration of partial method 'LawEnforcementDataContext.UpdateCourse(reservation.lawenforcement.Course)'
```
I don't see what I am doing wrong. I have done this before. Also, after adding the above code, in code that references the classes created by the LINQ to SQL, it complains that my entity types no longer exist. It's as if the partial class LawEnforcementDataContext is completely taking over the generated code.
## EDIT
Here are the other halves of the partial declarations from the generated code:
```
// the class
public partial class LawEnforcementDataContext : System.Data.Linq.DataContext
// the methods
partial void InsertCourse(Course instance);
partial void UpdateCourse(Course instance);
``` | Your two partial classes are defined in different namespaces, so the compiler does not 'share' them.
There is a setting under Properties in the DBML designer for this. Perhaps it reset? | In order to validate fields in Linq, you need to implement the OnValidate method not the Insert & Update methods.
For example:
```
partial void OnValidate(System.Data.Linq.ChangeAction action)
{
//All content items need titles
if (Description == null || Description == "")
throw new Exception("The description field is empty!");
//Content types of image need...images
if (ContentItemTypeId == (int)ContentItemTypes.Image && ImageData == null)
throw new Exception("An image is required in order to save this content item!");
//New Content Items don't have ids. If a new one comes through, set the default values for it.
if (this.ContentItemId == 0)
{
this.CreatedOn = DateTime.Now;
this.LastUpdatedOn = DateTime.Now;
this.IsDeletable = true;
}
}
``` | LINQ to SQL - Compile error when extending data context with partial class and methods | [
"",
"c#",
"linq",
"linq-to-sql",
"oop",
"partial-classes",
""
] |
I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.
Is this possible? | **By “the last position”, do you mean the end of the text?**
Changing the ‘.value’ of a form field will move the cursor to the end in every browser except IE. With IE you have to get your hands dirty and deliberately manipulate the selection, using non-standard interfaces:
```
if (browserIsIE) {
var range= element.createTextRange();
range.collapse(false);
range.select();
} else {
element.focus();
var v= element.value();
element.value= '';
element.value= v;
}
```
**Or do you mean put the cursor back to the place it was previously, the last time the textarea was focused?**
In every browser except IE, this will already happen just by calling ‘element.focus()’; the browser remembers the last cursor/selection position per input and puts it back on focus.
This would be quite tricky to reproduce in IE. You would have to poll all the time to check where the cursor/selection was, and remember that position if it was in an input element, then fetch the position for a given element when the button was pressed and restore it. This involves some really quite tedious manipulation of ‘document.selection.createRange()’.
I'm not aware of anything in jQuery that would help you do this, but there might be a plugin somewhere perhaps? | xgMz's answer was best for me. You don't need to worry about the browser:
```
var html = $("#MyTextArea").val();
$("#MyTextArea").focus().val("").val(html);
```
And here's a quick jQuery extension I wrote to do this for me next time:
```
; (function($) {
$.fn.focusToEnd = function() {
return this.each(function() {
var v = $(this).val();
$(this).focus().val("").val(v);
});
};
})(jQuery);
```
Use like this:
```
$("#MyTextArea").focusToEnd();
``` | How can you move the cursor to the last position of a textarea in Javascript? | [
"",
"javascript",
"jquery",
"position",
"textarea",
"mouse-cursor",
""
] |
At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? | yeah there are some pitfalls, but most of the time, in practice, they turn out to be enemy [windmills of the Quixotic style](http://en.wikipedia.org/wiki/Tilting_at_windmills), i.e. imaginary, and nothing to worry about in reality.
I would estimate that the pitfalls one is *most likely to encounter* are (including mitigating steps identified):
1. **working with others a.k.a. collaboration**
a. if you have others which for whatever reason refuse to adhere to [PEP 8](http://www.python.org/dev/peps/pep-0008/), then it could become a pain to maintain code. I've never seen this in practice once I point out to them the almost universal convention for python is **indent level == four spaces**
b. get anyone/everyone you work with to accept the convention and have them figure out how to have their editor automatically do it (or better yet, if you use the same editor, show them how to configure it) such that copy-and-paste and stuff *just works*.
2. **having to invest in a "decent" editor other than your current preferred one, if your current preferred editor is not python friendly** -- not really a pitfall, more an investment requirement to avoid the other pitfalls mentioned associated with copy-and-paste, re-factoring, etc. stop using Notepad and you'll thank yourself in the morning.
a. your efficiency in editing the code will be much higher under an editor which understands `python`
b. most *modern* code editors handle python decently. I myself prefer GNU Emacs, and recent versions come with excellent `python-mode` support out-of-the-box. The are plenty of [other editors to explore](http://wiki.python.org/moin/PythonEditors), including many free alternatives and [IDEs](http://wiki.python.org/moin/IntegratedDevelopmentEnvironments).
c. python itself comes out of the box with a "smart" python editor, `idle`. Check it out if you are not familiar, as it is probably already available with your python install, and may even support `python` better than your current editor. [PyCrust](http://wxpython.org/py.php) is another option for a python editor implemented in python, and comes as part of wxPython.
3. **some code generation or templating environments that incorporate python (think HTML generation or python CGI/WSGI apps) can have quirks**
a. most of them, if they touch python, have taken steps to minimize the nature of python as an issue, but it still pops up once in a while.
b. if you encounter this, familiarize yourself with the steps that the framework authors have already taken to minimize the impact, and read their suggestions (*and yes they will have some if it has ever been encountered in their project*), and it will be simple to avoid the pitfalls related to python on this. | It can be confusing in some editors where one line is indented with spaces and the next is indented with a tab. This is confusing as the indentation looks the same but causes an error.
Also when your copying code, if your editor doesn't have a function to indent entire blocks, it could be annoying fixing all the indentation.
But with a good editor and a bit of practice, this shouldn't be a problem. I personally really like the way Python uses white space. | Are there any pitfalls with using whitespace in Python? | [
"",
"python",
"whitespace",
""
] |
My old web site has an `index.html` page … nothing strange! Everything is fine.
The new web site has an english and a french version, so the new index is `index.php?lang=eng…`. That makes sense.
I don’t like to make a front page that will say “english” or “french”. But that’s not good for ranking or seo.
So the question is: How do I manage to get a default `index.php` with request (`?lang=eng`) to become the front page? | what do you think about that solution
```
<?php
$lang = $_GET['lang'];
if ( empty($lang) ) $lang = 'fra';
header( 'Location: http://acecrodeo.com/new/01-acec.php?lang='.$lang) ;
?>
``` | * domain.com/en/index.php
* domain.com/fr/index.php
Use url rewriting with regular expressions (mod\_rewrite, ISAPI, whatever) to handle requests to relevant pages so
* domain.com/en/index.php REWRITE TO domain.com/index.php?lang=en
* domain.com/fr/index.php REWRITE TO domain.com/index.php?lang=fr
This way your pages are two seperate pages to search engines but handled via one gateway in code. I'm not a regex expert but it would be a very simple regex I would imagine | Language neutral entry pages | [
"",
"php",
"url",
"localization",
""
] |
The MSDN article on [String Basics](http://msdn.microsoft.com/en-us/library/ms228362.aspx) shows this:
```
string str = "hello";
string nullStr = null;
string emptyStr = "";
string tempStr = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
string newStr = emptyStr + nullStr; // creates a new empty string
int len = nullStr.Length; // throws NullReferenceException
```
Why doesn't concatenating with null throw a null reference exception? Is it to make a programmer's life easier, such that they don't have to check for null before concatenation? | From [MSDN](http://msdn.microsoft.com/en-us/library/ms228504.aspx):
> In string concatenation operations,
> the C# compiler treats a null string
> the same as an empty string, but it
> does not convert the value of the
> original null string.
More information on the [+ binary operator](http://msdn.microsoft.com/en-us/library/aa691375(VS.71).aspx):
> The binary + operator performs string
> concatenation when one or both
> operands are of type string.
>
> If an
> operand of string concatenation is
> null, an empty string is substituted.
> Otherwise, any non-string argument is
> converted to its string representation
> by invoking the virtual ToString
> method inherited from type object.
>
> If
> ToString returns null, an empty string
> is substituted. | I agree that conceptually strings are just values. However, consider the following code:
```
int? i = null;
i += 1; // The result of this is that i == null
```
If the other value type operators used default() the way the string operators are converting null to "", your explanation would make sense.
It's simplest to say that the string operators are a shortcut (special case) for convenience. | Why is adding null to a string legal? | [
"",
"c#",
"language-design",
""
] |
I am looking to open up a command prompt and pass in a copy command, some switches, and the source file plus destination. I've tried the code below but nothing appears to be happening. What am I not seeing? What could I be doing wrong?
```
String line;
line = "cmd COPY /Y C:\srcfolder\112.bin C:\destfolder";
Process p = Runtime.getRuntime().exec(line);
p.waitFor();
``` | **If you really have** to use an external command, then you probably want to execute (notice the /C):
```
CMD /C COPY /Y C:\srcfolder\112.bin C:\destfolder
```
I recommend you use the array version of `exec` to avoid handling of quoting (should any files or directories contain spaces - or double-quotes - in them):
```
String[] args = { "CMD", "/C", "COPY", "/Y", src_file, dest_folder };
Process p = Runtime.getRuntime().exec(args);
p.waitFor();
```
Remember that this is not portable (will not work on Unix), so unless you really really need to use `COPY` then you should use the method linked to by `bstpierre`. | Is there a reason you aren't simply [copying the file in Java](http://www.java2s.com/Code/Java/File-Input-Output/FileCopyinJava.htm) rather than creating a system process?
Copying the files using Java rather than an exec call would keep your code portable. | CMD file copy from Java | [
"",
"java",
""
] |
Is there an easy way to keep VS2005 project in sync with changes made directly on filesystem? In eclipse I can simply "refresh" the project and any changes show up. Does something similar exist in VS? | You can click the Show All Files button in the Solution Explorer, which will show files that are not currently in your project. From there, you can right click and include the file in your project.
You will have to occasionally click refresh to see the new files | VS2005 will automatically detect file system changes on the files in your project and ask you if you'd like to reload the source code. If you have unsaved changes, it will ask you if you want to discard the old changes or not.
So no extra work is needed to setup VS2005 staying in sync with your file system for files that are added to your project.
As for files that are added to the file system but not in your project, you can for example create a new web solution on top of an existing location, it will automatically add all files that's in your folder. | Keep VS2005 in sync with filesytem? | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2005",
""
] |
First off, here is some code:
```
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
```
Is there a way to find out the size of the array that `ptr` is pointing to (instead of just giving its size, which is four bytes on a 32-bit system)? | No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using `sizeof()`.
Another trick is the one mentioned by [Zan](https://stackoverflow.com/users/13422/zan-lynx), which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one `size_t` bigger than the one you need, stash the size in the there, and return `ptr+sizeof(size_t)` as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array. | The answer is, "No."
What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and `malloc()` more memory than requested in order to store a length value before the start of the array. | How to find the size of an array (from a pointer pointing to the first element array)? | [
"",
"c++",
"arrays",
"c",
"pointers",
"sizeof",
""
] |
When I compile the Python code below, I get
> IndentationError: unindent does not match any outer indentation level
---
```
import sys
def Factorial(n): # Return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
```
Why? | One possible cause for this error is that there might be spaces mixed with tabs for indentation. Try doing a search & replace to replace all tabs with a few spaces.
Try this:
```
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
``` | ***Important***:
Spaces are the ***preferred*** method - see PEP 8 [Indentation](https://www.python.org/dev/peps/pep-0008/#indentation) and [Tabs or Spaces?](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces). (Thanks to @Siha for this.)
For [Sublime Text](https://en.wikipedia.org/wiki/Sublime_Text) users:
Set Sublime Text to use tabs for indentation:
Menu *View* → *Indentation* → *Convert Indentation to Tabs*
Uncheck the *Indent Using Spaces* option as well in the same sub-menu above.
This will immediately resolve this issue. | IndentationError: unindent does not match any outer indentation level, although the indentation looks correct | [
"",
"python",
"indentation",
"python-2.x",
""
] |
How do you get the Domain Controller IP address programmatically using `C#`? | Thanks All,
I done it as in this code
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
public doIt()
{
DirectoryContext mycontext = new DirectoryContext(DirectoryContextType.Domain,"project.local");
DomainController dc = DomainController.FindOne(mycontext);
IPAddress DCIPAdress = IPAddress.Parse(dc.IPAddress);
}
```
Thanks again | Here's how I would do it.
You'll need to use System.Net and System.DirectoryServices.
```
// get root of the directory data tree on a directory server
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://rootDSE");
// get the hostname of the directory server of your root (I'm assuming that's what you want)
string dnsHostname = dirEntry.Properties["dnsHostname"].Value.ToString();
IPAddress[] ipAddresses = Dns.GetHostAddresses(dnsHostname);
``` | How to get domain controller IP Address | [
"",
"c#",
"networking",
"active-directory",
"network-programming",
""
] |
I have a requirement that a Map will be constructed with up to 50~200 entries (it could be more, let's call it not-too-little anyway). The writing is only done once and the reading (using Map.get("keyName")) can go more than 20 per request (it's a webapp).
I'm going for Hashmap currently as it (I suppose) gives me the most optimum performance (note: numerous reads per request). Not being a data-structure guy, can any of you suggest a Map implementation that's best fit for my requirement, say from the java.lang.\*, Apache commons, etc. packages?
yc | Unless you are actually having performance problems (and have traced them to this code) I wouldn't worry about it.
And before I tried to replace the Map I'd look at why, exactly, I need to do 4000 lookups (200 entries by 20 reads each) to generate a web page.
But at a bet I'd guess that the time to do those 4000 lookups will turn out to be negligible compared to other parts of the process. | If all of the writes are done before any of the reads then you could use the [Collectons.unmodifiableMap](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#unmodifiableMap(java.util.Map)) method.
If that isn't the case then writing code to do what you want isn't terribly hard (wanders off to find the post that has the basic code in it...)
Hmm... just to be sure that the question is what I am thinking... is the read only aspect the important part or is trying to access the data fast the most important part?
Edit: (based on comment)
Have you checked to see, with a profiler if the code is slow? If not then you should not be worrying about it yet. | Write-Once + Read-Numerous Map in Java? | [
"",
"java",
"performance",
"data-structures",
""
] |
I tried to make character by character comparison under string type,
with the following code:
```
vector <int> getQuality(string seedTag, vector <string> &MuTag) {
vector <int> Quals;
for (unsigned i = 0; i<MuTag.size(); i++) {
Quals.push_back(-40);
cout << MuTag[i] << " " << seedTag[i] << endl;
if (MuTag[i] == seedTag[i]) { // This line 33 with error
Quals.push_back(40);
}
}
return Quals;
}
```
But why it gives such error:
```
Mycode.cc:33: error: no match for 'operator==' in '(+ MuTag)->std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::string, _Alloc = std::allocator<std::string>](((long unsigned int)i)) == seedTag. std::basic_string<_CharT, _Traits, _Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((long unsigned int)i)
```
How can I resolve it? | You are trying to compare a string (MuTag[i]) with a char (seedTag[i]). | As Alexander said, you are comparing a string and a char.
The sad thing is that the compiler already told you that, only it encrypted it in ISO-STL-TEMPLATE encryption, which is more difficult to read that perl!
You may want to look at [this script](http://www.bdsoft.com/tools/stlfilt.html) for decrypting C++ STL error messages. | About Comparing String With String | [
"",
"c++",
"string",
"comparison",
""
] |
Any using nHibernate with a Domain object & DTO object implemented from a common interface? I'm trying to separate all of my nHibernate attributes into the Domain object, leaving my DTO's and interface clean.
The problem comes with nHibernate throwing errors when it tries to associate the interfaces with the concrete classes.
**NHibernate.MappingException: Association references unmapped class: IContact**
I understand why its complaining about the use of the non-hibernated interface, but I'm struggling to visual a way to restructure around it. A skeleton reproduction of my code is set out as below, any ideas for how to structure my code better?
```
public interface ICompany
{
IList<IContact> Contacts { get; set; }
}
public class CompanyDTO : ICompany
{
private IList<IContact> contacts;
public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}
[ActiveRecord]
public class Company : ActiveRecordBase<Company>, ICompany
{
private IList<IContact> contacts;
[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")]
[ScriptIgnore]
public IList<IContact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}
```
Edit:
I want to have a common interface so that I can ensure they are keeping the same fields (ie. leaning on the compiler to keep them consistent). It also allows me to use the DTO's in the view part of my application, but casts them to domain objects for business and data access.
Also, alex's solution does not work because ICompany's Contacts is of type IList, not IList. I would like to keep it as IContact so my DTO object has no knowledge of the Contact Domain object. | In your concrete case you should just add `Type = typeof(Contact)` to the mapping attribute, like so:
```
[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId", Type=typeof(Contact))]
``` | Well in your domain you can't use the IContract to reference to your domain entity use Concrete class instead. If you want to correct your version use simply this:
```
[ActiveRecord]
public class Company : ActiveRecordBase<Company>
{
private IList<Contact> contacts;
[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")]
[ScriptIgnore]
public IList<Contact> Contacts { get { return this.contacts; } set { this.contacts = value; } }
}
```
I don't see the point to interface your domain and your DTOs. They are coupled, and they can have not the same informations. For example you could keep some information very weel encapsulated into your Domain and only communicate few other informations. DTO are made to transfert the data you want to share with up-layers.
You can have Base class to define your entity and your ValueObject. In brief Entity : DomainEntity are ID able means they can be persisted. ValueObject = DTO cannot be persisted (not ID able)
Look at the core design of Sharp-Arch:
* /BaseObject.cs: Provides basic object comparative services.
* /Entity.cs: Provides an object with a domain
signature and a typeable ID property. This also has the validation
support of NHibernate Validator. Objects which extend from Entity
MUST have at least one [DomainSignature] property; it'll throw a
Design-By-Contract exception if this is violated. The interface
IEntityWithTypedID allows you to roll your own.
* /ValueObject.cs: This is a value object wherein all of its
properties are used when compared to another value object. Objects
which extend from ValueObject may not have any [DomainSignature]
properties; it'll throw a Design-By-Contract exception if this is
violated. | nHibernate (w/ Castle ActiveRecord) with C# interfaces (esp for DTO's) | [
"",
"c#",
"asp.net",
"nhibernate",
"castle-activerecord",
"dto",
""
] |
I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).
Like so:
```
python -u parse.py 1> /tmp/output3.txt 2> /dev/null
```
but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out with stderr. It runs noisily and normally if I don't direct stderr somewhere.
So let's try redirecting it to a file somewhere rather than /dev/null, and take a look at what it's outputting:
```
python -u parse.py 1> /tmp/output3.txt 2> /tmp/foo || tail /tmp/foo
Traceback (most recent call last):
File "parse.py", line 79, in <module>
parseit('pages-articles.xml')
File "parse.py", line 33, in parseit
print >>sys.stderr, "bad page title", page_title
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
```
So, the stderr that's being generated contains utf8, and for some reason python refuses to print non-ascii when it's being redirected, even though it's being directed to /dev/null (though of course python doesn't know that).
How can I silence the stderr of a python script even though it contains utf8? Is there any way to do it without re-writing every print to stderr in this script? | You can silence stderr by binding it to a custom writer:
```
#!/usr/bin/env python
import codecs, sys
class NullWriter:
def write(self, *args, **kwargs):
pass
if len(sys.argv) == 2:
if sys.argv[1] == '1':
sys.stderr = NullWriter()
elif sys.argv[1] == '2':
#NOTE: sys.stderr.encoding is *read-only*
# therefore the whole stderr should be replaced
# encode all output using 'utf8'
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
print >>sys.stderr, u"\u20AC" # euro sign
print "ok"
```
Example:
```
$ python silence_stderr.py
Traceback (most recent call last):
File "silence_stderr.py", line 11, in <module>
print >>sys.stderr, u"\u20AC"
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
```
Silenced stderr:
```
$ python silence_stderr.py 1
ok
```
Encoded stderr:
```
$ python silence_stderr.py 2
€
ok
```
**NOTE**: I've got the above outputs inside emacs therefore to emulate it in a terminal you could do:
```
$ python ... 2>out.txt
$ cat out.txt
```
**NOTE**: Inside Windows console (after `chcp 65001` that switch to 'utf-8' and with truetype font (`Lucida Console`)) I've got strange results:
```
C:\> python silence_stderr.py 2
Traceback (most recent call last):
File "silence_stderr.py", line 14, in <module>
print >>sys.stderr, u"\u20AC" # euro sign
File "C:\pythonxy\python\lib\codecs.py", line 304, in write
self.stream.write(data)
IOError: [Errno 13] Permission denied
```
If the font is not truetype then the exception doesn't raise but the output is wrong.
Perl works for the truetype font:
```
C:\> perl -E"say qq(\x{20ac})"
Wide character in print at -e line 1.
€
```
Redirection works though:
```
C:\>python silence_stderr.py 2 2>tmp.log
ok
C:\>cat tmp.log
€
cat: write error: Permission denied
```
### re comment
From [`codecs.getwriter`](http://docs.python.org/library/codecs.html#codecs.getwriter) documentation:
> Look up the codec for the given
> encoding and return its StreamWriter
> class or factory function. Raises a
> `LookupError` in case the encoding
> cannot be found.
An oversimplified view:
```
class UTF8StreamWriter:
def __init__(self, writer):
self.writer = writer
def write(self, s):
self.writer.write(s.encode('utf-8'))
sys.stderr = UTF8StreamWriter(sys.stderr)
``` | When stderr is not redirected, it takes on the encoding of your terminal. This all goes out the door when you redirect it though. You'll need to use sys.stderr.isatty() in order to detect if it's redirected and encode appropriately. | Default encoding for python for stderr? | [
"",
"python",
"bash",
"shell",
"unicode",
""
] |
Is there any way for a web application to access the location data of an iPhone without the installation of an additional iPhone client app?
If not, the next best thing would be if any can recommend an existing native app, preferably free to the end user and as lightweight as possible, that *does* expose this information to Mobile Safari. | Yes, in iPhone OS 3.0. | You can do that using the [HTML5 Geolocation API](http://dev.w3.org/geo/api/spec-source.html). | Accessing location information on iPhone from web application | [
"",
"javascript",
"iphone",
"web-applications",
"core-location",
""
] |
I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname.
This concept is used in every full-blown windows network as well as in any other well configured network. | Just make sure Avahi / Bonjour's running, then type *hostname*.local (or also try *hostname*.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts. | On interface up, possible to scan for a specific MAC address? | [
"",
"python",
"linux",
"networking",
"system-administration",
""
] |
Is there any method for creating a dynamic array in C#? | Take a look at [Generic Lists](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). | Expanding on Chris and Migol`s answer with a code sample.
Using an array
```
Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");
```
Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.
```
List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
``` | Dynamic array in C# | [
"",
"c#",
""
] |
I've got some projects that are already doing site generation via maven, and I want to integrate cobertura reports in them, but no maven goal I seem to run will generate a local preview for me to look at that includes the Cobertura reports in the site. I want to be sure they're generating correctly before I commit the pom changes to the repo and have broken site generated.
Below is what I've added to the maven poms (parent and module), but the site I see when I run `mvn site:run` does not include the cobertura reports:
```
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<configuration>
<check>
<haltOnFailure>false</haltOnFailure>
<regexes>
<regex>
<pattern>parent-package-name-here.*</pattern>
<branchRate>80</branchRate>
<lineRate>80</lineRate>
</regex>
</regexes>
</check>
<instrumentation>
<includes>
<include>parent-package-name-here/**/*.class</include>
</includes>
</instrumentation>
</configuration>
<executions>
<execution>
<id>clean</id>
<phase>pre-site</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
<execution>
<id>instrument</id>
<phase>site</phase>
<goals>
<goal>instrument</goal>
<goal>cobertura</goal>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
</plugins>
</reporting>
...
</project>
```
What maven command should I use to generate the site with cobertura reports? Or, what should I add (additionally) to get the site generation to include the cobertura reports? | I figured out how to do this.
It seems there are a lot of bugs in the link generation within the maven site generation plugin.
The only way I've found to make maven generate a local copy of the site with working module links is to modify the `distributionManagement/site` tag to point to some local directory instead of the real-live deploy directory, then use `maven site:deploy`.
Every attempt to use `mvn site:stage` generates broken links. Same goes for `mvn site:run`.
The report links work with `mvn site:run` / `mvn site:stage` but the links to modules do not. | Should do:
```
mvn site
```
To elaborate, running **mvn a:b** runs the goal b in plugin a. Saying **mvn c** means to run the lifecycle phase c, which runs all of the bound goals in all of the phases up to c. As a result, this will trigger a lot more things to happen (such as doing the necessary preparation to produce cobertura reports). | Generating a maven site including a Cobertura Report | [
"",
"java",
"maven-2",
"code-coverage",
"cobertura",
""
] |
I am working on an application that runs locally on a Fedora 10 machine through PHP and Apache. It depends on a process that runs in the background.
The higher-ups want to be able to start/stop/restart the process, through the browser. I was trying to get this to work by having PHP make calls to the system using exec() and shell\_exec, but it doesn't seem to work.
When I try to start the process using "exec('processName')", nothing happens.
When I try to use "exec('killall processName')", SELinux starts constantly popping up warnings that the process was permitted (because I put it into permissive mode), however it doesn't actually kill the process! But this seems to go on even after the page is fully loaded!?!?
I AM able to call another script in a similar fashion: "exec('/var/www/cgi-bin/ControlProgram START')". So I'm not really sure what the major differences are between the two calls/commands.
I also put the script call into the /etc/rc.local file to have the script run at login. However, will I be able to kill this script from PHP since its run by... the system?
I'm not a guru when it comes to permissions/SELinux, so don't spare on the gory details! Thanks in advance! | I believe I found the problem. I'm still not exactly sure what the problem is, but it looks like it has something to do with file/directory permissions. When I moved the scripts into my /var/www/html directory, the scripts ran. I moved them into /var/www/cgi-bin and they work there too. So it might be something where apache can't execute scripts that are outside the /var/www directory, or at least it can't do it directly. Thanks for your help though! | If you have administrative control over this system you will want to check the PHP configuration (make sure it is the config profile for the web server).
Safe\_Mode will prevent PHP from executing anything outside a particular folder. In a shared hosting environment, this usually means you can only execute things that are relative to your home/www folder--which seems to be the case based on your notes. | Unable to call system commands and shell scripts from PHP Fedora 10 | [
"",
"php",
"apache",
"shell",
"cgi",
"fedora10",
""
] |
The [HTML spec](http://www.w3.org/TR/REC-html40/types.html#type-name) says
> ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by **any number of** letters, digits ([0-9]), hyphens ("-"), underscores ("\_"), colons (":"), and periods (".").
And even though the [SGML declaration](http://www.w3.org/TR/REC-html40/sgml/sgmldecl.html#h-20.1) of HTML 4 uses the value 65536 for NAMELEN, it notes "Avoid fixed limits."
But surely browsers, CSS implementations, and JavaScript toolkits must have *some* limits on the length they support. What is the smallest such limit that is safe to use in a HTML/CSS/JS application? | Just tested: **1M** characters works on every modern browser: Chrome1, FF3, IE7, Konqueror3, Opera9, Safari3.
I suspect even longer IDs could become hard to remember. | A practical limit, for me, is however long an ID I can store in my head during the time I'm working with the HTML/CSS.
This limit is usually between 8 and 13 characters, depending on how long I've been working and if the names make sense in the context of the element. | What is a practical maximum length for HTML id? | [
"",
"javascript",
"html",
"css",
""
] |
I want to reload a page using:
```
window.location.reload(true);
```
But I receive the POSTDATA warning because the refresh function want to resend previous POST form data. How can I refresh my page without this warning?
UPDATED: I have no control of the project! I can't workaround the POST itself! | Just changing `window.location` in JavaScript is **dangerous** because the user could still hit the **back button** and resubmit the post, which could have unexpected results (such as a **duplicate purchase**). PRG is a much better solution
[Use the Post/Redirect/Get (PRG) pattern](http://en.wikipedia.org/wiki/Post/Redirect/Get)
> To avoid this problem, many web applications use the PRG pattern — instead of returning an HTML page directly, the POST operation returns a redirection command (using the HTTP 303 response code (sometimes 302) together with the HTTP "Location" response header), instructing the browser to load a different page using an HTTP GET request. The result page can then safely be bookmarked or reloaded without unexpected side effects.
### Client Side
If you want to do it entirely client side, you'll need to change the browser history before you do the refresh:
```
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
window.location = window.location.href;
``` | You can't refresh without the warning; refresh instructs the browser to repeat the last action. It is up to the browser to choose whether to warn the user if repeating the last action involves resubmitting data.
You could re-navigate to the same page with a fresh session by doing:
```
window.location = window.location.href;
``` | How do I reload a page without a POSTDATA warning in Javascript? | [
"",
"javascript",
"refresh",
"reload",
"postdata",
""
] |
When developing an application with lots of stored procedures, should you store them in some sort of source versioning system (such as source-safe, TFS, SVN)? If so, why? And is there a convenient front end way to do this with SQL Server Management Studio? | Yes. All code should be stored in source control.
Simply put, code is code and mistakes happen. It's nice to be able to go back and see what changed over time and be able to go back to those changes.
We have to add it manually to a source control system, but you can create addons for the Sql Server the Management System. I haven't ever created one to automatically add it to source control, but I suppose you could. Also, all the code is stored in sql tables, so you could in theory create a process or something to go through the table(s) and retrieve all the code and commit it automatically.
Update: I would always write extra code to check and see if the code exists and if it doesn't create a filler procedure and then the actual script do and alter procedure.
```
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE
id = OBJECT_ID(N'[dbo].[SomeStoredProcedure]') AND
OBJECTPROPERTY(id,N'IsProcedure') = 1)
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[SomeStoredProcedure] AS
SELECT ''SPROC Template'''
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE SomeStoredProcedure
```
Doing a drop and recreate will remove all the user permissions you have setup for it. | **ABSOLUTELY POSITIVELY WITHOUT QUESTION NO EXCEPTIONS IN ALL PERPETUITY THROUGHOUT THE UNIVERSE YES!** | Should you store your SQL Stored Procedures in Source Control? | [
"",
"sql",
"sql-server",
"stored-procedures",
"version-control",
""
] |
Good night :)
I am currently playing with the DevIL library that allows me to load in image and check RGB values per pixel. Just as a personal learning project, I'm trying to write a very basic OCR system for a couple of images I made myself in Photoshop.
I am successfully able to remove all the distortions in the image and I'm left with text and numbers. I am currently not looking for an advanced neural network that learns from input. I want to start out relatively easy and so I've set out to identify the individual characters and count the pixels in those characters.
I have two problems:
* Identifying the individual characters.
* Most importantly: I need an algorithm to count connected pixels (of the same color) without counting pixels I've previously counted. I have no mathemathical background so this is the biggest issue for me.
Any help in the matter is appreciated, thanks.
edit:
I have tagged this question as C++ because that is what I am currently using. However, pseudo-code or easily readable code from another language is also fine. | The [flood fill](http://en.wikipedia.org/wiki/Flood_fill) algorithm will work for counting the included pixels, as long as you have the images filtered down to simple black & white bitmaps.
Having said that, you can perform character recognition by comparing each character to a set of standard images of each character in your set, measuring the similarity, and then choosing the character with the highest score.
Take a look at [this question](https://stackoverflow.com/questions/25977/how-can-i-measure-the-similarity-between-two-images) for more information. | Not sure this helps, but there is a GPL OCR lib called [gocr](http://jocr.sourceforge.net/). | Basic Pixel/Cell Counting Algorithm | [
"",
"c++",
"algorithm",
"ocr",
"counting",
""
] |
Maybe I've had too much coffee, maybe I've been working too long, regardless, I'm at a loss as to what this method does, or rather, why and how it does it, could anyone shed some light upon me? What is the nextColor?
```
public Color nextColor() {
int max = 0, min = 1000000000, cr = 0, cg = 0, cb = 0;
for (int r = 0; r < 256; r += 4) {
for (int g = 0; g < 256; g += 4) {
for (int b = 0; b < 256; b += 4) {
if (r + g + b < 256 || r + g + b > 512) {
continue;
}
min = 1000000000;
for (Color c : colorTable) {
int dred = r - c.getRed();
int dgreen = g - c.getGreen();
int dblue = b - c.getBlue();
int dif = dred * dred + dgreen * dgreen + dblue * dblue;
if (min > dif) {
min = dif;
}
}
if (max < min) {
max = min;
cr = r;
cg = g;
cb = b;
}
}
}
}
return new Color(cr, cg, cb, 0x90);
}
```
---
UPDATE
Thanks for the responses everyone. Looking at the context of the method within the program it is clear that their intent was indeed to return a new Color that is "furthest away" from the set of existing Colors.
Thanks Sparr for posing the [followup](https://stackoverflow.com/questions/592310/finding-the-farthest-point-in-one-set-from-another-set) to this question, I will definitely rewrite the above with your advice in mind.
I am not very well versed in the RGB color scale. Knowing the intention of the above method is to retrieve a "complimentary?" color to the existing set of colors, will the solution provided in [1](https://stackoverflow.com/questions/592310/finding-the-farthest-point-in-one-set-from-another-set) actually be complimentary in the sense of how we perceive the color? Is there a simpler way to choose a color that will compliment the set, or does the numerical analysis of the RGB components actually yield the appropriate color? | Consider the case where the pseudo-solid defined by the points in the colorTable has a large "hollow" in its interior, such that nextColor selects the point in the center of that hollow as the nextColor. Depending on what you know about the colorTable, this case could be exceedingly rare. If it is predicted to be rare enough, and you are willing to accept a less than optimal (assuming we take nextColor's output to be optimal) solution in those cases, then a significant optimization presents itself.
In all cases except the above-described one, the color selected by nextColor will be somewhere on the surface of the minimal convex hull enclosing all of the points in the 1/64-dense colorspace defined by your loops. Generating the list of points on that surface is slightly more computationally complex than the simple loops that generate the list of all the points, but it would reduce your search space by about a factor of 25.
In the vast majority of cases, the result of that simplified search will be a point on one of the corners of that convex hull. Considering only those reduces your search space to a trivial list (24 candidates, if my mental geometry serves me well) that could simply be stored ahead of time.
If the nextColor selected from those is "too close" to your colorTable, then you could fall back on running the original type of search in hopes of finding the sort of "hollow" mentioned above. The density of that search could be adapted based on how close the first pass got, and narrowed down from there. That is, if the super fast search finds a nextColor 8 units away from its nearest neighbor in colorTable, then to do better than that you would have to find a hollow at least 16 units across within the colorTable. Run the original search with a step of 8 and store any candidates more than 4 units distant (the hollow is not likely to be aligned with your search grid), then center a radius-12 search of higher density on each of those candidates.
It occurs to me that the 1/64-dense nature (all the multiples of 4) of your search space was probably instituted by the original author for the purpose of speeding up the search in the first place. Given these improvements, you do away with that compromise.
All of this presumes that you want to stick with improvements on this naive method of finding a contrasting color. There are certainly better ways, given equal or more (which colors in colorTable are the most prevalent in your usage? what colors appear more contrast-y to the human eye?) information. | It seems like you have colortable which is a storing a list of colors.
Then you have this strangely hardcoded colorspace of
> Colors that have component which are a
> multiple of 4 and are "not too bright"
> but not "too dark either".
This function seems to be giving you the color in the latter which "contrasts" the best with your color table.
When I say contrast , this is defined by choosing the color that is as far as possible from the color table using the 2-norm. | What does this mysterious Color Method do? What does it return? | [
"",
"java",
"colors",
"puzzle",
""
] |
What are the differences between multidimensional arrays `double[,]` and array of arrays `double[][]` in C#?
If there is a difference?
What is the best use for each one? | Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.
If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.
Consider the following methods:
```
static void SetElementAt(int[][] array, int i, int j, int value)
{
array[i][j] = value;
}
static void SetElementAt(int[,] array, int i, int j, int value)
{
array[i, j] = value;
}
```
Their IL will be the following:
```
.method private hidebysig static void SetElementAt(int32[][] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldelem.ref
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: stelem.i4
IL_0006: ret
} // end of method Program::SetElementAt
.method private hidebysig static void SetElementAt(int32[0...,0...] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 10 (0xa)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: ldarg.3
IL_0004: call instance void int32[0...,0...]::Set(int32,
int32,
int32)
IL_0009: ret
} // end of method Program::SetElementAt
```
When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects. | A multidimensional array creates a nice linear memory layout while a jagged array implies several extra levels of indirection.
Looking up the value `jagged[3][6]` in a jagged array `var jagged = new int[10][5]` works like this:
* Look up the element at index 3 (which is an array).
* Look up the element at index 6 in that array (which is a value).
For each dimension in this case, there's an additional look up (this is an expensive memory access pattern).
A multidimensional array is laid out linearly in memory, the actual value is found by multiplying together the indexes. However, given the array `var mult = new int[10,30]`, the `Length` property of that multidimensional array returns the total number of elements i.e. 10 \* 30 = 300.
The `Rank` property of a jagged array is always 1, but a multidimensional array can have any rank. The `GetLength` method of any array can be used to get the length of each dimension. For the multidimensional array in this example `mult.GetLength(1)` returns 30.
Indexing the multidimensional array is faster. e.g. given the multidimensional array in this example `mult[1,7]` = 30 \* 1 + 7 = 37, get the element at that index 37. This is a better memory access pattern because only one memory location is involved, which is the base address of the array.
A multidimensional array therefore allocates a continuous memory block, while a jagged array does not have to be square, e.g. `jagged[1].Length` does not have to equal `jagged[2].Length`, which would be true for any multidimensional array.
### Performance
Performance wise, multidimensional arrays should be faster. A lot faster, but due to a really bad CLR implementation they are not.
```
23.084 16.634 15.215 15.489 14.407 13.691 14.695 14.398 14.551 14.252
25.782 27.484 25.711 20.844 19.607 20.349 25.861 26.214 19.677 20.171
5.050 5.085 6.412 5.225 5.100 5.751 6.650 5.222 6.770 5.305
```
The first row are timings of jagged arrays, the second shows multidimensional arrays and the third, well that's how it should be. The program is shown below, FYI this was tested running Mono. (The Windows timings are vastly different, mostly due to the CLR implementation variations).
On Windows, the timings of the jagged arrays are greatly superior, about the same as my own interpretation of what multidimensional array look up should be like, see 'Single()'. Sadly the Windows JIT-compiler is really stupid, and this unfortunately makes these performance discussions difficult, there are too many inconsistencies.
These are the timings I got on Windows, same deal here, the first row are jagged arrays, second multidimensional and third my own implementation of multidimensional, note how much slower this is on Windows compared to Mono.
```
8.438 2.004 8.439 4.362 4.936 4.533 4.751 4.776 4.635 5.864
7.414 13.196 11.940 11.832 11.675 11.811 11.812 12.964 11.885 11.751
11.355 10.788 10.527 10.541 10.745 10.723 10.651 10.930 10.639 10.595
```
Source code:
```
using System;
using System.Diagnostics;
static class ArrayPref
{
const string Format = "{0,7:0.000} ";
static void Main()
{
Jagged();
Multi();
Single();
}
static void Jagged()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var jagged = new int[dim][][];
for(var i = 0; i < dim; i++)
{
jagged[i] = new int[dim][];
for(var j = 0; j < dim; j++)
{
jagged[i][j] = new int[dim];
for(var k = 0; k < dim; k++)
{
jagged[i][j][k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Multi()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var multi = new int[dim,dim,dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
multi[i,j,k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Single()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var single = new int[dim*dim*dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
single[i*dim*dim+j*dim+k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
}
``` | Differences between a multidimensional array "[,]" and an array of arrays "[][]" in C#? | [
"",
"c#",
"arrays",
"multidimensional-array",
"jagged-arrays",
""
] |
Basically I have a custom List class that contains different fruits. Assume that each fruit has an ID number that is stored in the list.
Is it better to have:
```
new AppleList();
new OrangeList();
new LemonList();
```
or
```
new FruitList<Fruit.Apple>();
new FruitList<Fruit.Orange>();
new FruitList<Fruit.Lemon>();
```
Things to consider:
* All IDs are of type int.
* The type of the fruit will not affect the implementation of the List itself. It will only be used by the client of the list, like an external method, etc.
I would like to use the one that is clearer, better in design, faster, more efficient, etc. Additionally if these above 2 techniques are not the best, please suggest your ideas.
EDIT: Btw Fruit is an enum if that wasn't clear. | > •All IDs are of type int.
>
> •The type of the fruit will not affect the implementation of the List itself. It will only be used by the client of the list, like an external method, etc.
Given these two facts, I wouldn't bother with generics. I would put a normal property on FruitList to indicate which type of fruit it is. | Use a combo:
```
public class AppleList : FruitList<Apple> { ... }
public class OrangeList : FruitList<Orange> { ... }
public class LemonList : FruitList<Lemon> { ... }
```
Put the common logic in the base list class:
```
public class FruitList<T> : List<T>
where T : IFruit
{ ... }
``` | Generics or not Generics | [
"",
"c#",
".net",
"generics",
""
] |
I am writing a web application that requires friendly urls, but I'm not sure how to deal with non 7bit ASCII characters. I don't want to replace accented characters with URL encoded entities either. Is there a C# method that allows this sort of conversion or do I need to actually map out every single case I want to handle? | I don't know how to do it in C#, but the magic words you want are "Unicode decomposition". There's a standard way to break down composed characters like "é", and then you should be able to just filter out the non-ASCII ones.
Edit: [this](http://www.codeproject.com/KB/cs/UnicodeNormalization.aspx?display=Print) might be what you're looking for. | Use UTF-8:
> Non-ASCII
> characters must first be encoded according to UTF-8 [STD63], and then
> each octet of the corresponding UTF-8 sequence must be percent-
> encoded to be represented as URI characters.
> — [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) | Making strings URL Friendly (eg: convert Montréal to Montreal) | [
"",
"c#",
"string",
"internationalization",
"friendly-url",
""
] |
\*I'm using Java.
I have this thread, agent, that explores a room to determine its size and clean it if it's dirty. Then I have the interface, which draws the agent as it explores the environment. Agent is subclassed from Thread, and Java takes care of managing the threads. All I do is create the thread and say object.start().
This works very well under normal circustances. However, the menus are enabled during this time, and that means the user can mess with the room while the agent is exploring it. That shouldn't happen.
So, once the user clicks the option that tells the agent to clean the room, I'd like to disable all the menus. Except this isn't working as it should. Here's the problem:
```
...
public void ActionPerformed(ActionEvent e)
{
//disable the menus with setEnabled(false);
agent.start();
//enable the menus with setEnabled(true);
}
```
The problem is that the menus are enabled before the agent thread executes its function. I thought about using Thread.join() - that would garantee that the code to enable the menus is only executed after the agent thread ends. But, if I use Thread.join() the interface doesn't update itself while the agent is moving, because it's waiting for the agent to finish!
I've thought about disabling the interface from the agent and then enabling it once the agent is done, but I'm not sure that would work and the biggest problem here is that the agent shouldn't be messing around with the menus.
So, to sum it up, I need a thread executing to update the interface/draw the agent moving, but that thread cannot be the same that enables the menu. It seems currently there is one thread doing both. Assuming that's possible and not too complicated. | > I've thought about disabling the
> interface from the agent and then
> enabling it once the agent is done,
> but I'm not sure that would work and
> the biggest problem here is that the
> agent shouldn't be messing around with
> the menus.
You could make the agent call a method in the GUI class that re-enables the menus, when it is done. The method would, of course, call the appropriate Swing methods on the EDT.
```
class Agent extends Thread
{
@override
public void run()
{
// run around the room
// finally done
gui.agentIsDone();
}
}
class GUI extends JFrame
{
...
void agentIsDone()
{
SwingUtilities.invokeLater(new Runnable()
{
@override
public void run()
{
menus.setEnabled(true);
}
});
}
}
```
If multiple agents can run concurrently, you'll need to check if all of them are done, before re-enabling the menu. | It sounds like you need your agent to issue notification (Does anyone still use `Observer`/`Observable`?) to your interface that cleaning has begun and finished. Your interface would, respectively, call `setEnabled(false)` and `setEnabled(true)` when it receives those notifications.
EDIT: The idea is to decouple the manipulation of the menu from the execution of the agent. I.e. what happens if you introduce another way to initiate cleaning, aside from the menu item? You probably still want the menu to be disabled in that case. | Problem with threads | [
"",
"java",
"multithreading",
"user-interface",
""
] |
is there any tristate type in c++ stl? | No, but there is [boost tribool](http://www.boost.org/doc/libs/1_38_0/doc/html/tribool.html). | You could also use a enumerated type with three values | is there any tristate type in c++ stl? | [
"",
"c++",
"stl",
""
] |
I have a simple table with just name and email called name\_email.
I am trying to fetch data out of it so that:
If two rows **have the same name**, but one has an email which is ending with ‘@yahoo.com’ and the other has a different email, then the one with the ‘@yahoo.com’ email should be discarded.
what would be best way to get this data out? | Okay, I'm not going to get involved in yet another fight with those who say I shouldn't advocate database schema changes (yes, you know who you are :-), but here's how I'd do it.
1/ If you absolutely cannot change the schema, I would solve it with code (either real honest-to-goodness procedural code outside the database or as a stored procedure in whatever language your DBMS permits).
This would check the database for a non-yahoo name and return it, if there. If not there, it would attempt to return the yahoo name. If neither are there, it would return an empty data set.
2/ If you can change the schema and you want an SQL query to do the work, here's how I'd do it. Create a separate column in your table called CLASS which is expected to be set to 0 for non-yahoo addresses and 1 for yahoo addresses.
Create insert/update triggers to examine each addition or change of a row, setting the CLASS based on the email address (what it ends in). This guarantees that CLASS will always be set correctly.
When you query your table, order it by name and class, and only select the first row. This will give you the email address in the following preference: non-yahoo, yahoo, empty dataset.
Something like:
```
select name, email
from tbl
where name = '[name]'
order by name, class
fetch first row only;
```
If your DBMS doesn't have an equivalent to the DB2 "fetch first row only" clause, you'll probably still need to write code to only process one record.
If you want to process all names but only the specific desired email for that name, a program such as this will suffice (my views on trying to use a relational algebra such as SQL in a procedural way are pretty brutal, so I won't inflict them on you here):
```
# Get entire table contents sorted in name/class order.
resultSet = execQuery "select name, email from tbl order by name, class"
# Ensure different on first row
lastName = resultSet.value["name"] + "X"
# Process every single row returned.
while not resultSet.endOfFile:
# Only process the first in each name group (lower classes are ignored).
if resultSet.value["name"] != lastName:
processRow resultSet.value["name"] resultSet.value["email"]
# Store the last name so we can detect next name group.
lastName = resultSet.value["name"]
``` | ```
select ne.*
from name_email ne
where ne.email not like '%@yahoo.com' escape '\' or
not exists(
select 1 from name_email
where name = ne.name and
email not like '%@yahoo.com' escape '\'
)
``` | distinct sql query | [
"",
"sql",
""
] |
I'm looking for a python browser widget (along the lines of pyQT4's [QTextBrowser](http://doc.trolltech.com/3.3/qtextbrowser.html) class or [wxpython's HTML module](http://www.wxpython.org/docs/api/wx.html-module.html)) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (`<h1>`, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.
Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance! | It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:
<http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html>
Since the API for this class is based on the signals and slots paradigm used in Qt, you will need to connect various signals to slots in your own code to find out when parts of a document have been changed. There's also a DOM API, so it should also be possible to access DOM nodes for selected parts of the document.
More information can be found here:
<http://api.kde.org/pykde-4.2-api/khtml/index.html> | I would also love such a thing. I suspect one with Python bindings does not exist, but would be really happy to be wrong about this.
One option I recently looked at (but never tried) is the [Webkit](http://webkit.org/) browser. Now this has some bindings for Python, and built against different toolkits (I use GTK). However there are available API for the entire Javascript machine for C++, but no Python bindings and I don't see any reason why these can't be bound for Python. It's a fairly huge task, I know, but it would be a universally useful project, so maybe worth the investment. | DOM Aware Browser Python GUI Widget | [
"",
"python",
"browser",
"widget",
""
] |
We are porting an old application that used a hierarchical database to a relational web app, and are trying to figure out the best way to port configuration switches (Y/N values).
Our old system had 256 distinct switches (per client) that were each stored as a bit in one of 8 32-bit data fields. Each client would typically have ~100 switches set. To read or set a switch, we'd use bitwise arithmetic using a #define value. For example:
```
if (a_switchbank4 & E_SHOW_SALARY_ON_CHECKS) //If true, print salary on check
```
We were debating what approach to store switches in our new relational (MS-SQL) database:
1. Put each switch in its own field
* Pros: fast and easy read/write/access - 1 row per client
* Cons: seems kludgey, need to change schema every time we add a switch
2. Create a row per switch per client
* Pros: unlimited switches, no schema changes necessary w/ new switches
* Cons: slightly more arduous to pull data, lose intellisense w/o extra work
3. Maintain bit fields
* Pros: same code can be leveraged, smaller XML data transmissions between machines
* Cons: doesn't make any sense to our developers, hard to debug, too easy to use wrong 'switch bank' field for comparison
I'm leaning towards #1 ... any thoughts? | It depends on a few factors such as:
* How many switches are set for each client
* How many switches are actually used
* How often switches are added
If I had to guess (and I would be guessing) I'd say what you really want are tags. One table has clients, with a unique ID for each, another has tags (the tag name and a unique ID) and a third has client ID / tag ID pairs, to indicate which clients have which tags.
This differs from your solution #2 in that tags are only present for the clients where that switch is true. In other words, rather than storing a client ID, a switch ID, and a boolean you store just a client ID and a switch ID, but only for the clients with that switch set.
This takes up about one third the space over solution number two, but the real advantage is over solutions one and three: indexing. If you want to find out things like which clients have switches 7, 45, and 130 set but not 86 or 14, you can do them efficiently with a single index on a tag table, but there's no practical way to do them with the other solutions. | You could think about using database views to give you the best of each solution.
For example store the data as one row per switch, but use a view that pivots the switches (rows) into columns where this is more convenient. | Design Question - Put hundreds of Yes/No switches in columns, rows, or other? | [
"",
"sql",
"sql-server",
"database-design",
""
] |
I am currently doing some work for a company that runs a legacy web app built on Java Servlets (the system pre-dates JSP's, although they now use them when building new pages). The code base is a big jumbled mess as its around 10 years of building on top of an out of date framework. They have very little consistency in the code base(the app has been developed by various people over the years, most of which no longer work here), no concept of DRY (every page is basically created from scratch) a lot of unreadable / cryptic code and just in general a very inconsistent infrastructure.
As I have been working here I have been adding in modern features / trying to clean up the code base a little bit. I added some jQuery to where I was exposed, introduced a bit of security with input validations, cleaned up some of the modules to employ unobtrusive JavaScript principles etc. My work here is on new modules so I am not exposed to a lot of the old logic. I have tried to introduce best practices to all my work under their current infrastructure but I am forced to call a lot of their old code to make my stuff consistent.
They have reached a point where they are now considering a massive update to the system. They want to improve the maintainability of the code base and attempt to move to some sort of modern framework / MVC type application. A lot of the system predates XHTML with inline stylistic markup, javascript:function() calls, no unit testing, predates Hibernate, etc. There is a mix of out.println html generation and calling jsp's from within the Servlet.
Some apps they have been looking at include Wicket, Struts, Tapestry and possibly Grails. The problem is, the move to any of these may require a huge rewrite of a system that is already in use and they cannot afford to start over.
My question is: What would be the best way to migrate a legacy code base such as this to a more modern framework while keeping the existing business logic (no sense in rewriting stuff that has been tested and works).
Some of the ideas being thought of include:
* write an in house templating system that would work with their current infrastructure (generate pages in a consistent way)
* port code to a framework such as tapestry (reusing a lot of their old code)
* rewrite system from scratch using a modern framework but copying over logic from old system (if possible)
* keep the old system as is and just update the front end pages to give it a more modern look (might be best given time/money etc.)
what is the best way to update legacy Java Servlet code to a modern framework (using modern practices for easy maintenance, unit testing, DRY) while keeping the logic intact?
any insight is welcome. | Refactor the hell out of it, working toward a consistent style of design, as a preliminary to porting it over to the framework closest in spirit to whatever that style ends up being.
By "refactor" I mean - introduce tests in strategic locations, unit as well as functional, and work like mad to reduce duplication, leaning on these tests. | I asked a very similar question a few months ago, some of the answers might be useful for you:
[What is the best way to migrate an existing messy webapp to elegant MVC?](https://stackoverflow.com/questions/40242/what-is-the-best-way-to-migrate-an-existing-messy-webapp-to-elegant-mvc) | Recommendations for migrating a legacy web app to a modern framework | [
"",
"java",
"web-applications",
"servlets",
"migration",
""
] |
This is perfectly fine C# code and works fine provided correct URL. But the everything is just done at one line by reducing the readability of the code.
Here is the code :
```
return new StreamReader(WebRequest.Create(urlName).GetResponse().GetResponseStream()).ReadToEnd();
```
I am just wondering what are the opinions of fellow developers on this kind of short cut way of writing code | Push it into a well-named method, and perhaps break it up so that single statment stretches over a couple lines. I'd also probably use WebClient:
```
return new WebClient().DownloadString(urlName);
``` | No, it's not really perfectly fine C# code. You should dispose the StreamReader, so at least have a `using` statement:
```
using (StreamReader reader = new StreamReader(WebRequest.Create(urlName).GetResponse().GetResponseStream()) {
return reader.ReadToEnd();
}
```
That code may gain a bit readability by dividing it into more lines, but not very much.
Generally I prefer readable code before compact code. Having one statement on each line makes the code easier to read and understand. For example:
```
if (i <= 4) i = 4 - i;
```
This becomes more readable with the if statement on one line and the code inside it on a separate line, with the if statement always having brackets:
```
if (i <= 4) {
i = 4 - i;
}
```
This code is of course rather readable even in the compact form, but the more complex the code is, the more it gains from putting each statement on a separate line. | Lengthy lines of code vs readability | [
"",
"c#",
".net",
"webrequest",
"streamreader",
"responsestream",
""
] |
I want to create something similar to a double linked list (but with arrays) that works with lower/upper bounds.
A typical circular array would probably look like:
```
next = (current + 1) % count;
previous = (current - 1) % count;
```
But what's the mathematical arithmetic to incorporate lower/upper bounds properly into this ?
* 0 (lower bound item 1)
* 1
* 2 (upper bound item 1)
* 3 (lower bound item 2)
* 4 (upper bound item 2)
So that:
-> next on index 2 for item 1 returns 0
-> previous on index 0 for item 1 returns 2
-> next on index 4 for item 2 returns 3
-> previous on index 3 for item 2 returns 4
Thank you !
**NOTE: Can't use external libraries.** | In general mathematical terms:
```
next === current + 1 (mod count)
prev === current - 1 (mod count)
```
where === is the 'congruent' operator. Converting this to the modulus operator, it would be:
```
count = upper - lower
next = ((current + 1 - (lower%count) + count) % count) + lower
prev = ((current - 1 - (lower%count) + count) % count) + lower
```
It would be up to you to find out the upper & lower bounds for each item. You could store this in a binary tree for fast retrieval. Maybe I'm not understanding your question.
(note that this assumes lower < upper, and lower > 0) | ```
+=======+ +=======+ +=======+
| Obj | ---> | Obj | ---> | Obj |
buffer | 1 | <--- | 2 | <--- | 3 |
+=======+ +=======+ +=======+
index 0 1 2 /* our first run */
index 3 4 5 /* second run */
and so on ...
```
So, you see for a 3 member list, the 1st item is indexed by `0, 3, 6,` etc. Similarly, the second item is indexed by `1, 4 (1 + 3), 7 (4 + 3), ...`
The general rule is: `next <- (next + 1) % size`, where `size = upper - lower + 1`
Using this formula we get:
```
curr | next
-------+-----------------
0 | (0 + 1) % 3 = 1
-------+-----------------
1 | (1 + 1) % 3 = 2
-------+-----------------
2 | (2 + 1) % 3 = 0
-------+-----------------
```
Hope that helps | C++ - Circular array with lower/upper bounds? | [
"",
"c++",
"c",
"math",
""
] |
How to check if argv (argument vector) contains a char, i.e.: A-Z
Would like to make sure that argv only contains unsigned intergers
For example:
```
if argv[1] contained "7abc7\0" - ERROR
if argv[1] contains "1234\0" - OK
``` | ```
bool isuint(char const *c) {
while (*c) {
if (!isdigit(*c++)) return false;
}
return true;
}
...
if (isuint(argv[1])) ...
```
Additional error checking could be done for a NULL c pointer and an empty string, as desired.
**update**: (added the missing c++) | How about this:
```
const std::string numbers="0123456789";
for(int i=1; i<argc; i++) {
if(std::string(argv[i]).find_first_not_of(numbers)!=std::string::npos)
// error, act accordingly
;
}
``` | Simple way to validate command line arguments | [
"",
"c++",
"visual-studio-2008",
""
] |
I am working on a small text editor project and want to add basic syntax highlighting for a couple of languages (Java, XML..just to name a few). As a learning experience I wanted to add one of the popular or non popular Java lexer parser.
What project do you recommend. Antlr is probably the most well known, but it seems pretty complex and heavy.
Here are the option that I know of.
1. Antlr
2. Ragel (yes, it can generate Java source for processing input)
3. Do it yourself (I guess I could write a simple token parser and highlight the source code). | ANTLR or JavaCC would be the two I know. I'd recommend ANTLR first. | ANTLR may seem complex and heavy but you don't need to use all of the functionality that it includes; it's nicely layered. I'm a big fan of using it to develop parsers. For starters, you can use the excellent [ANTLRWorks](http://www.antlr.org/works/index.html) to visualize and test the grammars that you are creating. It's really nice to be able to watch it capture tokens, build parse trees and step through the process.
For your text editor project, I would check out [filter grammars](http://www.antlr.org/wiki/display/ANTLR3/Lexical+filters), which might suit your needs nicely. For filter grammars you don't need to specify the entire lexical structure of your language, only the parts that you care about (i.e. need to highlight, color or index) and you can always add in more until you can handle a whole language. | Which Java oriented lexer parser for simple project (ANTLR, DIY, etc) | [
"",
"java",
"parsing",
"antlr",
"dsl",
"ragel",
""
] |
I am working on an C# and ASP.Net application, that uses Windows Authentication.
i.e. in Web.config:
```
<system.web>
<authentication mode="Windows" />
</system.web>
```
I want to get details for the current user (full name, email address, etc) from Active Directory.
---
I can get their pre Windows 2000 user login name (eg: `SOMEDOMAIN\someuser`) by using
```
string username = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
```
I've worked out the LDAP query for the user, using their current login name (not their pre Windows 2000 user login name):
```
DirectorySearcher adSearch = new DirectorySearcher(
"(userprincipalname=someuser@somedomain.com.au)");
SearchResult adSearchResult = adSearch.FindOne();
```
However, I don't know how to either search AD for the user using their pre W2K login name, or get their login name in the 'someuser@somedomain.com.au' format.
Any ideas? | The "pre Windows 2000" name i.e. `DOMAIN\SomeBody`, the `Somebody` portion is known as sAMAccountName.
So try:
```
using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
using(DirectorySearcher adSearch = new DirectorySearcher(de))
{
adSearch.Filter = "(sAMAccountName=someuser)";
SearchResult adSearchResult = adSearch.FindOne();
}
}
```
someuser@somedomain.com.au is the UserPrincipalName, but it isn't a required field. | Alan already gave you the right answer - use the `sAMAccountName` to filter your user.
I would add a recommendation on your use of `DirectorySearcher` - if you only want one or two pieces of information, add them into the `"PropertiesToLoad"` collection of the `DirectorySearcher`.
Instead of retrieving the whole big user object and then picking out one or two items, this will just return exactly those bits you need.
Sample:
```
adSearch.PropertiesToLoad.Add("sn"); // surname = last name
adSearch.PropertiesToLoad.Add("givenName"); // given (or first) name
adSearch.PropertiesToLoad.Add("mail"); // e-mail addresse
adSearch.PropertiesToLoad.Add("telephoneNumber"); // phone number
```
Those are just the usual AD/LDAP property names you need to specify. | How to get the current user's Active Directory details in C# | [
"",
"c#",
".net",
"active-directory",
"ldap",
"windows-authentication",
""
] |
Say I have ini/json to store configuration setting of my desktop application,Will it be ok to have a static object with all property loaded at startup/when ever it is required or is there any other better alternative?
Since this is the very first time I am doing this ,so just wanted to know whether static object is fine or singleton pattern or something else would be better | Either way is fine.
If it was me, I would have it on construction of the config object.
```
cConfig Config("config.ini");
```
This Config class would load the settings found in the file. Any code can access the settings by doing
```
Config.Get("NumberOfFoobars")
```
For testability purposes, if there is no file in the construction, the class' settings is set to default or a log file is created with a line advising the user of the missing settings.
And then for functions that needs the config, I would pass the Config instance as part of the parameters:
```
DoStuff(Config, [...]);
```
and have DoStuff get the variables from the Config class.
This makes the class testable (you can mock Config class), readeable (at a glance, you can tell which function requires Configs) and you don't have to rely on static instances (singletons are dangerous if you don't know how to use them).
You might be interested to [learn more about this](http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/) | I usually use [Boost.Program\_options](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options.html), and I usually use a singleton. | What would be the correct design for keeping configuration settings in c++? | [
"",
"c++",
"configuration",
"singleton",
""
] |
I was doing some reading on enums and find them very similar to declaring constants. How would I know when to use a constant rather than an enum or vice versa. What are some of the advantages of using enums? | Use enums when you want to define a range of values that something can be. Colour is an obvious example like:
```
public enum Colour
{
White,
Red,
Blue
}
```
Or maybe a set of possible things like:
(Example I stole from [here](http://mark.michaelis.net/Blog/FlagsAttributeAndBitwiseORWithoutTheFlagsAttribute.aspx) as I'm lazy)
```
[FlagsAttribute]
enum DistributedChannel
{
None = 0,
Transacted = 1,
Queued = 2,
Encrypted = 4,
Persisted = 16,
FaultTolerant = Transacted | Queued | Persisted
}
```
Constants should be for a single value, like PI. There isn't a range of PI values, there is just PI.
Other points to consider are:
* a: Constants don't necessarily indicate a relationship between the constants, whereas an enumeration indicates that something can be one of the set defined by the enum.
* b: A defined enumeration can help you with type checking when used as an argument. Constants are just values, so they don't provide any additional semantic information. | What's missing from the other answers is that enums have an integer base type. You can change the default from int to any other integral type except char like:
```
enum LongEnum : long {
foo,
bar,
}
```
You can cast explicitly from and implicitly to the the base type, which is useful in switch-statements. Beware that one can cast any value of the base type to an enum, even if the enum has no member with the appropriate value. So using always the default section in a switch is a good idea. BTW, .NET itself allows even floating point valued enums, but you can't define them in C#, although I think you can still use them (except in switch).
Furthermore, using enums gives you more type safety. If you intend to use e.g. int constants as method parameters, then I could call the method with any int value. Granted, via casting it can happen with enums, too, but it won't happen accidentally. Worse is the possibility to confuse the order of parameters.
```
void method(int a, int b) {...}
```
If constant A only may go into a and constant B only may go into b, then using two different enum types will uncover any misuse during the compilation. | Enums and Constants. Which to use when? | [
"",
"c#",
"language-agnostic",
"enums",
""
] |
The applet is in a signed JAR. Last line in console reads:
```
security: Checking if certificate is in Deployment permanent certificate store
```
CPU and memory usage are normal. Other page elements still respond. It's just that the applet is not displayed.
There is another applet in the same page but it works.
Any ideas?
Thread dump follows:
```
Dump thread list ...
Group main,ac=15,agc=3,pri=10
main,5,alive
AWT-Shutdown,5,alive
AWT-Windows,6,alive,daemon
traceMsgQueueThread,5,alive,daemon
CacheCleanUpThread,5,alive,daemon
AWT-EventQueue-0,6,alive
Thread-9,5,alive
Group Plugin Thread Group,ac=3,agc=0,pri=10
AWT-EventQueue-1,6,alive
ConsoleWriterThread,6,alive,daemon
TimerQueue,5,alive,daemon
Group file:/c:/project/lib/-threadGroup,ac=2,agc=0,pri=4
thread applet-OsApplet,4,alive
AWT-EventQueue-2,4,alive
Group file:/c:/project/html/-threadGroup,ac=3,agc=0,pri=4
thread applet-javax.swing.JApplet.class,4,alive
TimerQueue,4,alive,daemon
AWT-EventQueue-3,4,alive
Done.
``` | Fixed it. Applet is sized relatively but containing DIV is not sized explicitly. When DIV's height CSS property was set, IE rendered the applet. | Open up the applet console (Right click on the small Java icon on your taskbar assuming you are on Windows, or selecting 'View Console' from the browser's menu if Linux). Press 't' to take a thread dump. That would give you more information about what the plugin JVM is doing. | Applet hangs in IE during security phase | [
"",
"java",
"security",
"internet-explorer",
"applet",
""
] |
How do you clear the thread principal in c#.
I have a background thread that does a
```
Membership.ValidateUser(username, password);
```
which then copies the resulting Principal back to the main thread
```
AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);
```
this works fine. But, if I log off I want to clear the principal, if I set it to null it does nothing Thread.CurrentPrincipal = null; if I try and set it again via
```
AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);
```
I get the error
```
Default principal object cannot be set twice.
```
Any ideas? | The trick to solve this was to create a facade principal and assign that to the thread. Then behind it you can switch out the current user for a new one. | I don't think you can reset the principal without shutting down the AppDomain and recreating it. You only get one shot at calling SetThreadPrincipal.
Assuming that you are using your own custom principal object that you create after ValidateUser; you can probably put a "Logout" method on your principal that resets its internal state to an unauthenticated user. | C# clearing the thread principal | [
"",
"c#",
"wpf",
""
] |
This seems to be a simple problem, but I dont use alot of javascript.
I have a div, with a checkbox in it, and would like the whole div to toggle the checkbox. This is what I have so far:
```
<div style="padding: 2em; border: 1px solid"
onClick="if (document.getElementById('cb').checked) document.getElementById('cb').checked=false; else document.getElementById('cb').checked=true;">
<input name="cb" id="cb" type="checkbox">
</div>
```
Only problem is when you click the actual checkbox, it get toggled twice, and therefore doesn't change.
Any ideas? | It's possible you could implement this in a more robust and accessible way by using the label element to wrap the area you want to click.
For example:
```
<label for="cb">
<div style="padding: 2em; border: 1px solid">
<input name="cb" id="cb" type="checkbox">
</div>
</label>
```
I haven't tested the above code, but I believe all browsers support clicking of labels to check an input box. | ```
onclick="if (event.target.tagName != 'INPUT') document.getElementById('cb').checked = !document.getElementById('cb').checked"
``` | Click on a div to toggle a checkbox inside of it using javascript | [
"",
"javascript",
"html",
""
] |
I have the following variables:
```
string str1 = "1";
string str2 = "asd";
string str3 = "3.5";
string str4 = "a";
```
Now I need to find the data type of each string i.e. the data type to which it can be converted if quotes are removed. Here is what I would like each variable to convert to:
> str1 - integer
> str2 - string
> str3 - double
> str4 - char
Note: if the string has single character it should be char, though a string can have single letter, I'm limiting it.
FYI: these values are obtained from DataGrid where i manually entered values. So everything is becoming a string.
Is there any way to do this? | **Use meta-data**, if you can
That you have to guess what the data types are, is not a good idea.
Two things
1 Where is the data coming from?
If it's a database, are you sure they're strings?
If it is a database, there should be some meta data returned that will tell you what the datatypes of the fields are.
If it's an Xml file, is there a schema defined that will give you the types?
2 If you have to continue to guess.
Be aware that you can have strings that happen to be numbers, but are perfectly valid strings e.g phone numbers, bank acount numbers, that are best expressed as strings.
Also these numbers can have many digits, if you convert them to doubles you may loose some digits to floating point inaccuracies (you should be OK up to 14 or 15 digits)
I'm sure by now - cause I've taken my time typing this - there are lots of answers telling you how to do this (i.e. tryparse int first, then double, then test length for char, if not then it's a string etc), but if I were you, I'd try to NOT do that, and see if there's any way you can get, or pass some meta-data that will tell you what type it **IS** and not just what type it *might* be | Of course, there's no definite way to do this, but if you create a list of data types you want to check ordered by priority, then something like this may do the trick.
```
object ParseString(string str)
{
int intValue;
double doubleValue;
char charValue;
bool boolValue;
// Place checks higher if if-else statement to give higher priority to type.
if (int.TryParse(str, out intValue))
return intValue;
else if (double.TryParse(str, out doubleValue))
return doubleValue;
else if (char.TryParse(str, out charValue))
return charValue;
else if (bool.TryParse(str, out boolValue))
return boolValue;
return null;
}
```
Just call this function on each string, and you should have the appropiate type of object returned. A simple type check can then tell you how the string was parsed. | C# doubt, finding the datatype | [
"",
"c#",
"parsing",
"types",
""
] |
Am trying to create a server application in c#.In the code am using the TcpListener class.
```
TcpListener t = new TcpListener(5555);
t.Start();
```
However it is providing an error saying: Invalid token '(' in class, struct, or interface member declaration.
Are there additional references required?.
Please help.
```
namespace WindowsApplication1
{
public partial class lanmessenger : Form
{
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public lanmessenger()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder(this.textBox1.Text);
sb.AppendLine(this.textBox2.Text);
this.textBox1.Text = sb.ToString();
this.textBox2.Text = "\0";
HideCaret(this.textBox1.Handle);
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
HideCaret(this.textBox1.Handle);
}
StreamWriter streamWriter;
StreamReader streamReader;
NetworkStream networkStream;
TcpListener t = new TcpListener(5555);
t.Start();
}
}
```
This is the full source code upto now. Am unable to find the error. | Providing you have a reference to System.dll in your project and have a using statement for the System.Net.Sockets namespace, there is nothing wrong with the code you've provided.
It looks like you've got one too many '(' lying around somewhere.
Your call to t.Start() has to be in a method of the class. This is wrong:
```
class lanmessenger
{
...
TcpListener t = new TcpListener(5555); // ok to initialize like this
t.Start(); // wrong...put this in a method
}
```
This is right:
```
class lanmessenger
{
TcpListener t = new TcpListener(5555); // ok to initialize like this
public lanmessenger
{
InitializeComponent();
t.Start(); // put it here
}
}
``` | Works fine for me. You need to add following line in your code.
using System.Net.Sockets; | Socket Programming | [
"",
"c#",
"sockets",
""
] |
```
java.lang.VerifyError: (class: a method: parse signature:
()Z) Incompatible argument to function
public boolean parse() {
}
```
What does this error mean and how to fix these kind of errors | Normally this kind of error is related to version problems, you are compiling with a different version of a library than you are running with. There are also some quite subtle varieties of this that can occur with java 1.5 type coercion, where a 1.4 compiler would choose differently. Recompile everything with 1.5, and make sure you're using the same versions. | It usually is about a java 1.5 or 6 compatibility issue (like trying to compile a Java5 or 6 code with an older 1.4 javac).
Clean all your .class files and rebuild from scratch, checking that you have your JDK and JRE at the same level.
---
It can also be a bad typecast from a third party class method "return items" to your local ones. | java lang verify error | [
"",
"java",
""
] |
The Basecamp URL like .basecamphq.com, eg seymores.basecamp.com.
How can I do the same in a Tomcat environment? | Other aproximation is use [UrlRewriteFilter](http://tuckey.org/urlrewrite/). Using this filter with few policies you can, for example, convert calls like:
<http://username.domain> (before url rewriting)
to
<http://domain/your_servlet?user=username> (after url rewriting) | If you just want to have one copy of the web application that acts differently depending on the virtual host name that was used, [examine the "Host" header.](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpServletRequest.html#getHeader(java.lang.String)) This could be done in a [Filter](http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Filter.html) or a dispatcher servlet, depending on what you want to do with the result.
You can have a different copy of the web application for each virtual server by [adding `Host` elements](http://tomcat.apache.org/tomcat-5.5-doc/virtual-hosting-howto.html) to the `Engine` element in your server configuration. This creates separate virtual hosts, each with their own independent set of web applications. | How do you implement Basecamp style URL in Java/Java EE environment? eg <username>.hostname.com | [
"",
"java",
"jakarta-ee",
"server-side",
""
] |
I'm building an XML page inside of a function, and for some strange reason I don't get the whole thing spit out of the function. I've tried
```
return $thisXml;
}
echo $thisXML;
```
and I only get the xml declaration which is in the variable before the function.
If i put an echo in the function, i get everything back as I should.
my page essentially looks like this
```
$thisXml = 'xml declaration stuff';
function getThisXML($thisXML){
for(i=1; i<5; i++){
$query "has the 5 in it";
while ($mysqlQuery =mysql_fetch_array($theQuery) {
$thisXml.='add the xml';
}
$thisXml.='close the last element';
return $thisXml;
}
echo $thisXml;
```
as i said, if I replace the 'return' with 'echo', I get all the nice xml. if I echo outside the function, I only get the original declaration.
really strange, and i've been struggling with this one all day. | ```
return $thisXml;
}
echo $thisXML;
```
$thisXML; only exists in the scope of the function.
Either make $thisXML; global (bad idea) or `echo getThisXML()` where getThisXML is the function that returns `$thisXML`; | Are you actually calling the function in the sense of:
```
$thisXml = getThisXML($someinput);
```
Maybe a silly question, but I don´t see it in your description. | Returning a variable from a function in php (return not working) | [
"",
"php",
""
] |
I have this query:
```
SELECT p.id, r.status, r.title
FROM page AS p
INNER JOIN page_revision as r ON r.pageId = p.id AND (
r.id = (SELECT MAX(r2.id) from page_revision as r2 WHERE r2.pageId = r.pageId AND r2.status = 'active')
OR r.id = (SELECT MAX(r2.id) from page_revision as r2 WHERE r2.pageId = r.pageId)
)
```
Which returns each page and the latest active revision for each, unless no active revision is available, in which case it simply returns the latest revision.
Is there any way this can be optimised to improve performance or just general readability? I'm not having any issues right now, but my worry is that when this gets into a production environment (where there could be **a lot** of pages) it's going to perform badly.
Also, are there any obvious problems I should be aware of? The use of sub-queries always bugs me, but to the best of my knowledge this cant be done without them.
*Note:*
The reason the conditions are in the JOIN rather than a WHERE clause is that in other queries (where this same logic is used) I'm LEFT JOINing from the "site" table to the "page" table, and If no pages exist I still want the site returned.
Jack
**Edit:** I'm using MySQL | If "active" is the first in alphabetical order you migt be able to reduce subqueries to:
```
SELECT p.id, r.status, r.title
FROM page AS p
INNER JOIN page_revision as r ON r.pageId = p.id AND
r.id = (SELECT r2.id
FROM page_revision as r2
WHERE r2.pageId = r.pageId
ORDER BY r2.status, r2.id DESC
LIMIT 1)
```
Otherwise you can replace ORDER BY line with
```
ORDER BY CASE r2.status WHEN 'active' THEN 0 ELSE 1 END, r2.id DESC
```
These all come from my assumptions on SQL Server, your mileage with MySQL may vary. | Maybe a little re-factoring is in order?
If you added a `latest_revision_id` column onto `pages` your problem would disappear, hopefully with only a couple of lines added to your page editor.
I know it's not normalized but it would simplify (and greatly speed up) the query, and sometimes you do have to denormalize for performance. | SQL query performance question (multiple sub-queries) | [
"",
"sql",
"mysql",
"performance",
"join",
"subquery",
""
] |
I always wondered why I have to manually set the JAVA\_HOME environment variable after installing the Java SDK.
> JAVA\_HOME=c:\Program Files\Java\jdk1.6.0\_12
Visual Studio at least provides a batch file to set these kind of environment variables:
> call "c:\Program Files\Microsoft Visual
> Studio 9.0\VC\vcvarsall.bat"
Does Java have something similar? I'm trying to make a build script that should simply work after installing the Java SDK. I don't want people to mess with environment variables on their PC. | You can install as many versions of Java as you like.
It would be dangerous for the setup to modify a ***local*** environment variable such as `JAVA_HOME`, since it might reference an existing Java installation.
This has nothing to do with an alleged "platform dependent issue". ;)
Since scripts might depend on `JAVA_HOME` to launch themselves, again, this would be disasterous for a new Java install to modify `JAVA_HOME`: all those scripts would suddenly have to be launched with a new potentially incompatible JVM.
Plus, by setting `$JAVA_HOME/bin` or `%JAVA_HOME%/bin` in your path, you can dynamically change `JAVA_HOME` to whatever version of Java you want to use without having to much with your PATH variable.
---
[Michael Borgwardt](https://stackoverflow.com/users/16883/michael-borgwardt) has made in the comments the interesting followup's question
> Still, this does not explain why the installer does not set JAVA\_HOME when it is not previously set at all.
The answer is simple:
The setup **cannot know if a script already depends on `JAVA_HOME` or not**.
Meaning: some scripts could test for `JAVA_HOME` value, and if not set, refer to another JVM installed elsewhere (and do not forget that by "install", one can only refer to "copied": a JDK/JRE is not always installed by a setup)
If you set `JAVA_HOME`, that can disrupt the default behavior of some of your scripts.
> Not wanting to disturb hypothetical scripts that depend on a env var not being set sound pointlessly paranoid to me - If a script does that, then it clearly WANTS to use a different JVM when one is installed - no reason to avoid that.
Mmm... Sweet. For dealing with massive **deployment** issues on a daily-basis (for internal application in my shop), I can assure you: it is very sane "paranoid"
treat to have.
When you deploy to a (very) large set of users, you do not want to make any assumption about their platform and configurations. "clearly WANTS" is an assumption I would not dare to make (or I redirect my phone to yours ;) and you handle the angry calls).
For instance, we have many scripts which launches with a 1.4.2 JVM from sun (JAVA\_HOME not set on development platform, default path set directly in the script), or with 1.4.2 from JRockit (`JAVA_HOME` set, as it is the intended target on integration, pre-production and production platforms).
But we install regularly the new JDK1.6.x since we use it for launching eclipse.
Assume that those scripts want their `JAVA_HOME` set... and nothing works anymore.
... To which [Robert Grant](https://stackoverflow.com/users/61938/robert-grant) makes this on-the-spot critic:
> > You're describing scripts that require one specific version, but still look at global JAVA\_HOME. That's just badly thought out scripts.
While that may or may not be true, that also illustrates precisely my point:
"you do not want to make any assumption": no assumption on their platform/settings, and no assumption on their "best practices".
The former may sound paranoid, the latter is plain common-sense: thinking that your product (here a JDK setup) will not break anything on the user's environment because the user has "correctly" thought out his scripts... would be insane.
---
[GvS](https://stackoverflow.com/users/40615/gvs) suggests:
> Or it could just have option to do it, disabled by default
That would mean another option to include in the setup screens, option which should be carefully reviewed by the user, and which may have unintended consequences, even when the user selects it thinking he knows what he is doing...
It is simply not worth it. | I don't think JAVA\_HOME is a convention invented or supported by Sun.
They probably remember the fiasco that was the CLASSPATH environment variable\*\* all too well and prefer to stay the hell away from environment variables.
\*\* This was encouraged as the primary way to set the JVM classpath in earlier Java SDKs and literature, and resulted in the user and various applications messing with the environment variable, overwriting each other's changes and depending on mutually contradictive contents. | Why doesn't the Java SDK installer set JAVA_HOME? | [
"",
"java",
"sdk",
"environment-variables",
""
] |
I need to determine if given IP address is from some special network in order to authenticate automatically. | [Apache Commons Net](http://commons.apache.org/net/) has `org.apache.commons.net.util.SubnetUtils` that appears to satisfy your needs. It looks like you do something like this:
```
SubnetInfo subnet = (new SubnetUtils("10.10.10.0", "255.255.255.128")).getInfo();
boolean test = subnet.isInRange("10.10.10.10");
```
Note, as [carson](https://stackoverflow.com/users/25343/carson) points out, that Apache Commons Net has [a bug](http://mail-archives.apache.org/mod_mbox/commons-issues/200902.mbox/%3C2039253761.1233796319684.JavaMail.jira@brutus%3E) that prevents it from giving the correct answer in some cases. Carson suggests using the SVN version to avoid this bug. | ## Option 1:
Use [`spring-security-web`](https://mvnrepository.com/artifact/org.springframework.security/spring-security-web)'s [IpAddressMatcher](http://docs.spring.io/spring-security/site/docs/3.2.8.RELEASE/apidocs/org/springframework/security/web/util/matcher/IpAddressMatcher.html#matches(java.lang.String)). Unlike Apache Commons Net, it supports both ipv4 and ipv6.
```
import org.springframework.security.web.util.matcher.IpAddressMatcher;
...
private void checkIpMatch() {
matches("192.168.2.1", "192.168.2.1"); // true
matches("192.168.2.1", "192.168.2.0/32"); // false
matches("192.168.2.5", "192.168.2.0/24"); // true
matches("92.168.2.1", "fe80:0:0:0:0:0:c0a8:1/120"); // false
matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/120"); // true
matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/128"); // false
matches("fe80:0:0:0:0:0:c0a8:11", "192.168.2.0/32"); // false
}
private boolean matches(String ip, String subnet) {
IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(subnet);
return ipAddressMatcher.matches(ip);
}
```
---
## Option 2 (a lightweight solution!):
*The code in previous part works perfectly fine* but it needs `spring-security-web` to be included.
If you are not willing to include Spring framework in your project, you may use this class which is a slightly modified version of the [original class](https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java) from Spring, so that it has no non-JRE dependencies.
```
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Matches a request based on IP Address or subnet mask matching against the remote
* address.
* <p>
* Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an
* IPv4 address will never match a request which returns an IPv6 address, and vice-versa.
*
* @author Luke Taylor
* @since 3.0.2
*
* Slightly modified by omidzk to have zero dependency to any frameworks other than the JRE.
*/
public final class IpAddressMatcher {
private final int nMaskBits;
private final InetAddress requiredAddress;
/**
* Takes a specific IP address or a range specified using the IP/Netmask (e.g.
* 192.168.1.0/24 or 202.24.0.0/14).
*
* @param ipAddress the address or range of addresses from which the request must
* come.
*/
public IpAddressMatcher(String ipAddress) {
if (ipAddress.indexOf('/') > 0) {
String[] addressAndMask = ipAddress.split("/");
ipAddress = addressAndMask[0];
nMaskBits = Integer.parseInt(addressAndMask[1]);
}
else {
nMaskBits = -1;
}
requiredAddress = parseAddress(ipAddress);
assert (requiredAddress.getAddress().length * 8 >= nMaskBits) :
String.format("IP address %s is too short for bitmask of length %d",
ipAddress, nMaskBits);
}
public boolean matches(String address) {
InetAddress remoteAddress = parseAddress(address);
if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (nMaskBits < 0) {
return remoteAddress.equals(requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = requiredAddress.getAddress();
int nMaskFullBytes = nMaskBits / 8;
byte finalByte = (byte) (0xFF00 >> (nMaskBits & 0x07));
// System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));
for (int i = 0; i < nMaskFullBytes; i++) {
if (remAddr[i] != reqAddr[i]) {
return false;
}
}
if (finalByte != 0) {
return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte);
}
return true;
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to parse address" + address, e);
}
}
}
```
**NOTICE**: Notice that for using this option, it's your responsibility to carefully examine the [license](https://www.apache.org/licenses/LICENSE-2.0) to make sure by using this code, you are not in violation of any terms mandated by the aforementioned license. (Of course publishing this code to Stackoverflow.com by me is not a violation.) | How to check if an IP address is from a particular network/netmask in Java? | [
"",
"java",
"networking",
"ip",
""
] |
I may be teaching a "Java crash-course" soon. While it is probably safe to assume that the audience members will know Big-O notation, it is probably not safe to assume that they will know what the order of the various operations on various collection implementations is.
I could take time to generate a summary matrix myself, but if it's already out there in the public domain somewhere, I'd sure like to reuse it (with proper credit, of course.)
Anyone have any pointers? | The book [Java Generics and Collections](http://oreilly.com/catalog/9780596527754/) has this information (pages: 188, 211, 222, 240).
List implementations:
```
get add contains next remove(0) iterator.remove
ArrayList O(1) O(1) O(n) O(1) O(n) O(n)
LinkedList O(n) O(1) O(n) O(1) O(1) O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n) O(1) O(n) O(n)
```
Set implementations:
```
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table capacity
LinkedHashSet O(1) O(1) O(1)
CopyOnWriteArraySet O(n) O(n) O(1)
EnumSet O(1) O(1) O(1)
TreeSet O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
```
Map implementations:
```
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table capacity
LinkedHashMap O(1) O(1) O(1)
IdentityHashMap O(1) O(1) O(h/n) h is the table capacity
EnumMap O(1) O(1) O(1)
TreeMap O(log n) O(log n) O(log n)
ConcurrentHashMap O(1) O(1) O(h/n) h is the table capacity
ConcurrentSkipListMap O(log n) O(log n) O(1)
```
Queue implementations:
```
offer peek poll size
PriorityQueue O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1) O(1) O(1) O(n)
ArrayBlockingQueue O(1) O(1) O(1) O(1)
LinkedBlockingQueue O(1) O(1) O(1) O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue O(log n) O(1) O(log n) O(1)
LinkedList O(1) O(1) O(1) O(1)
ArrayDeque O(1) O(1) O(1) O(1)
LinkedBlockingDeque O(1) O(1) O(1) O(1)
```
The bottom of the javadoc for the [java.util](https://docs.oracle.com/javase/8/docs/api/java/util/package-summary.html) package contains some good links:
* [Collections Overview](https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html) has a nice summary table.
* [Annotated Outline](https://docs.oracle.com/javase/8/docs/technotes/guides/collections/reference.html) lists all of the implementations on one page. | This website is pretty good but not specific to Java: <http://bigocheatsheet.com/>
[](https://i.stack.imgur.com/rtf34.jpg) | Big-O summary for Java Collections Framework implementations? | [
"",
"java",
"collections",
"big-o",
""
] |
I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:
```
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
```
And this is breaking if the provided *url* is an `https://` URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks. | You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:
```
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
```
where `AcceptAllCertifications` is defined as
```
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
``` | This one worked for me:
```
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
``` | How do I use WebRequest to access an SSL encrypted site using HTTPS? | [
"",
"c#",
".net",
"https",
"httpwebrequest",
"webrequest",
""
] |
Given the following XML:
```
<?xml version="1.0"?>
<user_list>
<user>
<id>1</id>
<name>Joe</name>
</user>
<user>
<id>2</id>
<name>John</name>
</user>
</user_list>
```
And the following class:
```
public class User {
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
```
Is it possible to use `XmlSerializer` to deserialize the xml into a `List<User>` ? If so, what type of additional attributes will I need to use, or what additional parameters do I need to use to construct the `XmlSerializer` instance?
An array ( `User[]` ) would be acceptable, if a bit less preferable. | You can *encapsulate* the list trivially:
```
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("user_list")]
public class UserList
{
public UserList() {Items = new List<User>();}
[XmlElement("user")]
public List<User> Items {get;set;}
}
public class User
{
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializer ser= new XmlSerializer(typeof(UserList));
UserList list = new UserList();
list.Items.Add(new User { Id = 1, Name = "abc"});
list.Items.Add(new User { Id = 2, Name = "def"});
list.Items.Add(new User { Id = 3, Name = "ghi"});
ser.Serialize(Console.Out, list);
}
}
``` | If you decorate the `User` class with the `XmlType` to match the required capitalization:
```
[XmlType("user")]
public class User
{
...
}
```
Then the `XmlRootAttribute` on the `XmlSerializer` ctor can provide the desired root and allow direct reading into List<>:
```
// e.g. my test to create a file
using (var writer = new FileStream("users.xml", FileMode.Create))
{
XmlSerializer ser = new XmlSerializer(typeof(List<User>),
new XmlRootAttribute("user_list"));
List<User> list = new List<User>();
list.Add(new User { Id = 1, Name = "Joe" });
list.Add(new User { Id = 2, Name = "John" });
list.Add(new User { Id = 3, Name = "June" });
ser.Serialize(writer, list);
}
```
...
```
// read file
List<User> users;
using (var reader = new StreamReader("users.xml"))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<User>),
new XmlRootAttribute("user_list"));
users = (List<User>)deserializer.Deserialize(reader);
}
```
Credit: based on [answer](https://stackoverflow.com/a/21775195/451944) from [YK1](https://stackoverflow.com/users/1529246/yk1). | Is it possible to deserialize XML into List<T>? | [
"",
"c#",
"serialization",
"xml-serialization",
"xml-deserialization",
""
] |
Hello everyone, I'm developing a photo sharing web site using the [CodeIgniter PHP framework](http://www.codeigniter.com/). The idea is that people could upload their photos, manage them (through some sort of file browser which allows them to create subfolders, drag files around, etc) and edit them (some basic things like resizing, rotating and cropping to start with, and later on, I'll add some advanced features).
I've already implemented a third party authentication solution for CI ([Redux Authentication 2 Beta](http://code.google.com/p/reduxauth/)) and I'm now integrating a JS/PHP file manager ([AjaxExplorer](http://sourceforge.net/projects/ajax-explorer/)), but the problem is that the PHP backend for managing files (moving, copying, etc) is trusting too much on the user input from the ajax calls. For instance, it's doing things like this (simplified for the sake of clarity):
```
move_uploaded_file($_FILES['upload']['tmp_name'], $root.$username.$_POST['destination_dir']);
```
As you can see, there are obvious security concerns as it blindly accepts whatever path the user throws in! I can already see someone sending something like "../AnotherUser/" as the $\_POST['destination\_dir'] value.
My question is: **What's the best way to "sandbox" a user, in order to only allow him to manage his own data?** Do I just validate+filter the inputs, hoping to catch every attempt of intrusion? Are there any libraries/packages dedicated to address this specific issue?
I think this problem must be somehow solved in any (mature enough) project, which gives its users the power of managing their files through a web browser, so I expected to find some clear guidelines around this (as there are a lot about SQL Injection, XSS, CSRF, etc) but I guess I'm not using the right keywords. | > What's the best way to "sandbox" a user, in order to only allow him to manage his own data?
Allow any filenames/directory names the user wants, but simply don't use them on the server side filesystem. Instead, write the path names into a database with a primary key, and use the primary key as a filename like ‘34256.dat’ in a flat storage directory (or even as a BLOB in the database if you prefer). Then serve up via a download script or URL rewrite to make the desired filename appear in the URL.
Sanitising incoming filenames is **hard**. Detecting ‘..’ is only the beginning. Too-long filenames; too-short filenames; combinations of leading and trailing dots; combinations of leading and trailing whitespace; the different directory separators of different platforms; characters that are invalid on some platforms; control characters; Unicode characters and the environment-specific ways of addressing them; ADSs; filenames (‘.htaccess’) or extensions (‘.php’, ‘.cgi’) that might be ‘special’ to your web server; Windows's reserved filenames...
You can spend a lifetime tracking down funny little quirks of filepath rules on various platforms, or you can just forget it and use the database. | I'm not sure what your `destination_dir` looks like, but what I thought of was assigning directories keys, and then getting the directory based on that key. For example:
```
//$_POST['destination_dir'] = '4hg43h5g453j45b3';
*_query('SELECT dir FROM destinations WHERE key = ? LIMIT 1'); //etc.
```
However you have to predefine keys before hand. Another alternative could be the opposite: md5/sha1 the input and use that as the destination\_dir, then store that key in the database with the associated label. | Securing a PHP file manager from its users | [
"",
"php",
"ajax",
"security",
"file",
"codeigniter",
""
] |
C# 2008/3.5 SP1
I want to check to see if the application is running for the first time. I have developed an application and once this is installed on the clients computer. I want to make a check if it is first time running.
I have installed using the windows installer project.
```
if (System.Deployment.Application.ApplicationDeployment.CurrentDeployment.IsFirstRun)
{
// Do something here
}
```
The above code works for a clickonce development. But how can I do something similar with a windows installer.
I was thinking of added a registery when the application installs. Then check this registery item, when the program runs for the first time (true). Once it has run for the first time edit the registry to (false).
However, rather then use the registry, is there a better method that I can use? | A good place to store application data outside of the registry is the application data folder. If you create this directory on first run then you would just need to test for it on subsequent loads. Also if your application requires it you then have a good storage location for data.
```
string data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
string path = Path.Combine(data, name);
if (Directory.Exists(path))
{
// application has been run
}
else
{
// create the directory on first run
DirectoryInfo di = Directory.CreateDirectory(path);
}
``` | Just add a boolean value to your Applications Settings. The simplest way is to use the IDE and the settings designer. It has to be user scope though, application scope is not writeable.
Don't forget to toggle the value and save the settings when you detect first-time.
The code looks like this:
```
if (Properties.Settings.Default.FirstUse)
{
Properties.Settings.Default.FirstUse = false;
Properties.Settings.Default.Save();
// do things first-time only
}
``` | Check condition if the application is running for the first time after being installed | [
"",
"c#",
"deployment",
""
] |
Using SQL Server 2005, I have a table where certain events are being logged, and I need to create a query that returns only very specific results. There's an example below:
```
Log:
Log_ID | FB_ID | Date | Log_Name | Log_Type
7 | 4 | 2007/11/8 | Nina | Critical
6 | 4 | 2007/11/6 | John | Critical
5 | 4 | 2007/11/6 | Mike | Critical
4 | 4 | 2007/11/6 | Mike | Critical
3 | 3 | 2007/11/3 | Ben | Critical
2 | 3 | 2007/11/1 | Ben | Critical
```
The query should do the following: return ONLY one row per each FB\_ID, but this needs to be the one where Log\_Name has changed for the first time, or if the name never changes, then the first dated row.
In layman's terms I need this to browse through a DB to check for each instance where the responsibility of a case (FB\_ID) has been moved to another person, and in case it never has, then just get the original logger's name.
In the example above, I should get rows (Log\_ID) 2 and 6.
Is this even possible? Right now there's a discussion going on whether the DB was just made the wrong way. :)
I imagine I need to somehow be able to store the first resulting Log\_Name into a variable and then compare it with an IF condition etc. I have no idea how to do such a thing with SQL though.
Edit: Updated the date. And to clarify on this, the correct result would look like this:
```
Log_ID | FB_ID | Date | Log_Name | Log_Type
6 | 4 | 2007/11/6 | John | Critical
2 | 3 | 2007/11/1 | Ben | Critical
```
It's not the first date per FB\_ID I'm after, but the row where the Log\_Name is changed from the original.
Originally FB\_ID 4 belongs to Mike, but the query should return the row where it moves on to John. However, it should NOT return the row where it moves further on to Nina, because the first responsibility change already happened when John got it.
In the case of Ben with FB\_ID 3, the logger is never changed, so the first row for Ben should be returned. | This will efficiently use an index on `(fb_id, cdate, id)`:
```
SELECT lo4.*
FROM
(
SELECT CASE WHEN ln.log_id IS NULL THEN lo2.log_id ELSE ln.log_id END AS log_id,
ROW_NUMBER() OVER (PARTITION BY lo2.fb_id ORDER BY lo2.cdate) AS rn
FROM (
SELECT
lo.*,
(
SELECT TOP 1 log_id
FROM t_log li
WHERE li.fb_id = lo.fb_id
AND li.cdate >= lo.cdate
AND li.log_id <> lo.log_id
AND li.log_name <> lo.log_name
ORDER BY
cdate, log_id
) AS next_id
FROM t_log lo
) lo2
LEFT OUTER JOIN
t_log ln
ON ln.log_id = lo2.next_id
) lo3, t_log lo4
WHERE lo3.rn = 1
AND lo4.log_id = lo3.log_id
``` | I guess that there is a better and more performant way, but this one seems to work:
```
SELECT *
FROM log
WHERE log_id IN
( SELECT MIN(log_id)
FROM log
WHERE
( SELECT COUNT(DISTINCT log_name)
FROM log log2
WHERE log2.fb_id = log.fb_id ) = 1
OR log.log_name <> ( SELECT log_name
FROM log log_3
WHERE log_3.log_id =
( SELECT MIN(log_id)
FROM log log4
WHERE log4.fb_id = log.fb_id ) )
GROUP BY fb_id )
``` | SQL query filtering | [
"",
"sql",
"filter",
""
] |
I have the following class hierarchy in C++:
```
class Base {
virtual void apply() = 0;
};
class Derived : public Base {
virtual void apply() {
// implementation here that uses derived_specialty
}
virtual void derived_specialty() = 0;
};
class Implementation : public Derived {
virtual void derived_specialty() {
// implementation
}
};
```
I'd like to guarantee that classes at the level of Implementation don't supply their own implementation of apply, and that they only implement derived\_specialty. Is there any way to guarantee that classes inheriting from Derived will not implement apply, so that the Derived::apply implementation is used? My understanding is that in C++, a method made virtual in the Base class is virtual all the way down the inheritance hierarchy, but if there are any tricks in C++ to accomplish, I'd be interested in hearing about them.
I'm always surprised by the things that are allowed by C++, so I thought it was worth asking. :) | You can kind of do it by composition:
```
class Base {
virtual void apply();
};
class Derived : public Base {
class IImplementation {
virtual void derived_specialty() = 0;
};
IImplementation& m_implementation;
Derived(IImplementation& implementation)
: m_implementation(implementation)
{}
virtual void apply() {
// implementation here that uses m_implementation.derived_specialty
}
};
class Implementation : Derived::IImplementation {
virtual void derived_specialty() {
// implementation
}
};
```
Other classes can still subclass Derived and override the apply method, but your Implementation class is no longer one of these classes. | You could make Implementation a delegate class rather than a specialization of Derived
```
class Derived : public Base
{
Derived()
void apply()
{
//whatever, delegate to impl class instance
impl->apply_specialization();
}
Impl* impl;
};
class Impl : public WhateverImplInterface
{
void apply_specialization(){}
};
```
Then the implementation doesn't have access to the apply function and is separated from the hierarchy. The Derived class is then parameterized by an instance of Impl class. | Preventing Virtual Method Implementation in C++ | [
"",
"c++",
"inheritance",
"encapsulation",
""
] |
I've got the following (simplified):
```
interface IFindFilesObserver
{
void OnFoundFile(FileInfo fileInfo);
void OnFoundDirectory(DirectoryInfo directoryInfo);
}
class FindFiles
{
IFindFilesObserver _observer;
// ...
}
```
...and I'm conflicted. This is basically what I would have written in C++, but C# has events. Should I change the code to use events, or should I leave it alone?
What are the advantages or disadvantages of events over a traditional observer interface? | Consider an event to be a callback interface where the interface has only one method.
**Only hook events you need**
With events, you only need to implement handlers for events you're interested in handling. In the observer interface pattern, you'd have to implement all methods in the entire interface including implementing method bodies for notification types you don't actually care about handling. In your example, you always have to implement OnFoundDirectory and OnFoundFile, even if you only care about one of these events.
**Less maintenance**
Another good thing about events is you can add a new one to a particular class so that it will raise it, and you don't have to change every existing observer. Whereas if you want to add a new method to an interface, you have to go around every class that already implements that interface and implement the new method in all of them. With an event though, you only need to alter existing classes that actually want to do something in response to the new event you're adding.
**The pattern is built into the language so everybody knows how to use it**
Events are idiomatic, in that when you see an event, you know how to use it. With an observer interface, people often implement different ways of registering to receive notifications and hook up the observer.. with events though, once you've learnt how to register and use one (with the += operator), the rest are all the same.
**Pros for interfaces**
I haven't got many pros for interfaces. I guess they force someone to implement all methods in the interface. But, you can't really force somebody to implement all those methods correctly, so I don't think there's a lot of value on this.
**Syntax**
Some people don't like the way you have to declare a delegate type for each event. Also, standard event handlers in the .NET framework have these parameters: (object sender, EventArgs args). As sender doesn't specify a particular type, you have to down-cast if you want to use it. This often is fine in practice, it feels not quite right though because you're losing the protection of the static type system. But, if you implement your own events and don't follow the .NET framework convention on this, you can use the correct type so potential down-casting isn't required. | Hmm, events can be used to implement the Observer pattern. In fact, using events can be regarded as another implementation of the observer-pattern imho. | C#: events or an observer interface? Pros/cons? | [
"",
"c#",
"events",
"observer-pattern",
""
] |
For some reason the login to my site has to be done two times in order to work. If anyone has any idea why I appreciate it.
Here is the code I have for the authorization:
```
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
/*
* The purpose of this class is to manage
* access to the application, making sure the
* users are logged in before they can access
* certain features
*/
class Auth extends Model
{
function isUserLoggedIn()
{
/*
* Check for the user_id in $_SESSION
* and see if it's the database. Return
* true or false
*
*/
if(isset($_SESSION['user']))
{
return true;
}
else
{
return false;
}
}
static function redirectToLogin()
{
header("location: http://". DOMAIN .APP_DIR . "index.php?action=login");
}
static function redirectToMain()
{
header("location: http://". DOMAIN . APP_DIR . "index.php?action=main");
}
static function login($user)
{
/*
* Authenticate the user passing to the function
* a instance of the User object
*/
try
{
$db = parent::getConnection();
$pass = $user->getPassword();
$query = "select username, password from users where username = '".$user->getUsername()."' and password = '".$user->getPassword()."'";
$results = $db->query($query);
if(empty($results)) {
throw new Exception('There was a problem logging you in', EX_LOGIN_ERROR);
}
$row = $results->fetch_assoc();
$user = $row['username'];
$_SESSION['user'] = $user;
}
catch(Exception $e){
throw $e;
}
}
static function logout()
{
$old_user = $_SESSION['user'];
unset($_SESSION['user']);
session_destroy();
}
}
?>
```
Thx | I'd listen to @strager as your code, from my limited PHP exerience, doesn't seem to show anything that would cause the error. Although I can't help but offer some simple refactorings unrelated to your question but it would just make *me* feel better:
```
<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
/*
* The purpose of this class is to manage
* access to the application, making sure the
* users are logged in before they can access
* certain features
*/
class Auth extends Model
{
function isUserLoggedIn()
{
/*
* Check for the user_id in $_SESSION
* and see if it's the database. Return
* true or false
*
*/
return isset($_SESSION['user']);
}
static function redirectToLogin()
{
header("location: http://". DOMAIN .APP_DIR . "index.php?action=login");
}
static function redirectToMain()
{
header("location: http://". DOMAIN . APP_DIR . "index.php?action=main");
}
static function login($user)
{
/*
* Authenticate the user passing to the function
* a instance of the User object
*/
$db = parent::getConnection();
$pass = $user->getPassword(); // replaced getPassword in the query with this variable, else there is no need to set it here.
$query = "select username, password from users where username = '".$user->getUsername()."' and password = '".$pass."'";
$results = $db->query($query);
if(empty($results)) {
throw new Exception('There was a problem logging you in', EX_LOGIN_ERROR);
}
$row = $results->fetch_assoc();
$_SESSION['user'] = $row['username'];
// Why bother surrounding with try...catch just to throw the same exception
}
static function logout()
{
// what is $old_user used for? I can't see it set as a global variable anywhere
$old_user = $_SESSION['user'];
unset($_SESSION['user']);
session_destroy();
}
}
?>
``` | There just isn't enough code for us to pin-point an error. The problem is likely related to your site design where the information about your login status is sent BEFORE login is processed. If not, then I don't know what is wrong given this information. | I have to login twice | [
"",
"php",
""
] |
I wrote some smart generic counters and managers for my models (to avoid `select count` queries etc.). Therefore I got some heavy logic going on for post\_save.
I would like to prevent handling the signal when there's no need to.
I guess the perfect interface would be:
```
instance.save(dispatch_signal=False)
```
How can I accomplish this?
---
**Update**
More information about what I'm doing, if anyone's interested:
1. Generic counters are stored in a separate table
2. Every time Django paginates an object list, it calls overriden count() method of my custom manager, which basically retrieves the static counter value for appropriate object class.
3. Signals trigger the logic of counters update, which is a bit complicated since it checks many aspects of related models (i.e. it has to generate a visibility property based on a nested category tree). I can't put this logic in Model.save() because one counter depends on many different models. I'd like to have that logic in one piece, instead of fragments spread around.
4. I am denormalizing some of my models, so I rewrite (duplicate) certain values across tables.
5. For testing purposes I run my little command-extension -- [Dilla](http://code.google.com/p/dilla), to populate random data around.
6. I've noticed unwanted signals triggering, therefore I'd like them to run conditionally.
Hope it's clear enough. Excuse my language mistakes. | A quick and dirty solution would be:
```
from django.db.models.signals import post_save
from somewhere_in_my_app import my_post_save_handler
post_save.disconnect(my_post_save_handler)
instance.save()
post_save.connect(my_post_save_handler)
```
But otherwise i strongly recommend moving your logic into the `save()` method of your model. | You can disconnect and reconnect the signal. Try using a `with:` statement with this utility class:
```
class SignalBlocker(object):
def __init__(self, signal, receiver, **kwargs):
self.signal = signal
self.receiver = receiver
self.kwargs = kwargs
def __enter__(self, *args, **kwargs):
self.signal.disconnect(self.receiver)
def __exit__(self, *args, **kwargs):
self.signal.connect(self.receiver, **self.kwargs)
```
You can now use:
```
with SignalBlocker(post_save, my_post_save_handler):
instance.save()
``` | Django - how do I _not_ dispatch a signal? | [
"",
"python",
"django",
"django-signals",
""
] |
**[edit]**
We're collecting credit application data from users on a web form.
I have not tied my web form directly into QB.
I have no idea what the QB table structure is for this collection of data - nor of how it displays it to the user because I've never actually worked directly with QB. Others in my office do however.
---
I would still appreciate any information about open source / free options.
---
I'll simplify the problem by removing the first desired option.
Let's just talk about importing a flat file into quickbooks.
I don't have a copy of quickbooks that I can play with, so I have no idea what options exist that are native to quickbooks but I see some chatter on the web about QB expecting an .ini file for imports. (don't know the format that it expects yet, but I'll get that worked out later)
Please share your story if you have managed to import a flat file from mySQL into quickbooks or know of links that offer insight (I'm not finding much right now).
**[end edit]**
I realize that this scenario is probably uncommon, but I need to connect to an existing quickbooks database in one of two ways.
1) either directly from a php script running on our web site -- insert user supplied data directly from web to quickbooks.
or
2) put user's data directly into mySQL database and later export data from mySQL to quickbooks.
If the first option is viable, I would appreciate your thoughts on establishing an odbc connection to the quickbooks database.
can I go about it with something like:
```
try {
$conn = @odbc_connect("DSNName", "", "", "SQL_CUR_USE_ODBC");
// un and pw parameters are passed as empty strings since the DSN
// has knowledge of the password already.
// 4th parameter is optional
$exec = @odbc_exec($conn, $insert) or die ("exec error");
echo "success!";
}
catch (Exception $e) {
echo $e->getMessage();
} // end try catch
``` | The third option might work for you.
**Option 1 - QODBC:** If you're looking for simplicity, Qodbc as mentioned above is the main product that does it, and it does cost money.
**Option 2 - Quickbooks SDK:** If you're okay working through the SDK and using their XML structures, you can find some great resources on the developer network. Accounts are free for the SDK and you can work your way through it fairly easily.
This boils down to one thing, if you want it free, you might not be able to get it your way.. QODBC is reasonably priced the last time I checked.
The one thing that is important to be aware of with either approach -- ensure the tables you wish to write data into in Quickbooks are available by the SDK and QODBC.
As Quickbooks has gotten older, access to some tables have disappeared. For example, it's not possible to write directly to the payroll deductions table directly as it competes with Intuit's Payroll Service.
**Option 3 - Direct SQL manipulation:** Intuit encrypts their data in their SQL data making it unavailable for direct access.
**Edit: Option 4 - Quickbooks Web Connector** SOAP wrapper that sits on the computer with Quickbooks and interacts with it for you. Also free.
Good luck! | If you want ODBC access, QODBC is your only choice.
The newer versions of QuickBooks Enterprise Edition use an SQL database back-end, but it *does not* allow you to directly access the SQL tables. They lock the database down so you can't actually query any of the data.
AccessBooks is another option, which mirrors data from QuickBooks into MySQL, and then can push data back to QuickBooks as well. I have heard that it can be a bit flaky.
You can use the QuickBooks SDK and make it do pretty much anything you can do in the QuickBooks GUI, but it's a bit more work. If you're integrating a web application with QuickBooks, you'll want to use the Web Connector. I'm the developer of a QuickBooks/PHP framework which is quite stable and popular, and would probably be helpful to you:
<https://idnforums.intuit.com/messageview.aspx?catid=56&threadid=9164>
I'm in the middle of adding support for mirroring the entire QB schema to a database, keeping it in sync, and then allowing changes to be pushed back to QuickBooks. The work isn't near complete yet though. It currently pulls data from QuickBooks and keeps it in sync remarkably well however.
You can also import IIF files into QuickBooks, but it's now an unsupported and deprecated format by Intuit. They highly recommend you do not use it, here are some reasons why:
<http://wiki.consolibyte.com/wiki/doku.php/quickbooks_integration_methods> | connecting to quickbooks database via odbc with php? | [
"",
"php",
"mysql",
"odbc",
"quickbooks",
""
] |
Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?
```
MyClass = function(name){
this.name = name;
this.do = function() {
//do somthing
}
};
MyClass.prototype.do = function() {
if (this.name === 'something') {
//do something new
} else {
//CALL BASE METHOD
}
};
``` | I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:
```
function MyClass(name) {
this.name = name;
}
MyClass.prototype.doStuff = function() {
// generic behaviour
}
var myObj = new MyClass('foo');
var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
// do specialised stuff
// how to call the generic implementation:
MyClass.prototype.doStuff.call(this /*, args...*/);
}
``` | Well one way to do it would be saving the base method and then calling it from the overriden method, like so
```
MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){
if (this.name === 'something'){
//do something new
}else{
return this._do_base();
}
};
``` | Calling method using JavaScript prototype | [
"",
"javascript",
"prototype",
"overriding",
""
] |
I know this is probably the canonical "It depends..." question but I'd appreciate any pointers as to where to start looking.
I have a client/server app talking over ethernet. In one computer I run the server and a client and on another just the client. One runs Vista and one runs XP. After an uptime of about 3 weeks the entire computer freezes and nothing works, not mouse, not keyboard, nothing -just power off. Every ten seconds the server sends a ping message to see if the clients are alive, other than that just a few small messages go back and forth every day.
I'm trying to find out if it's me causing it or something else. I've started a session and after a few days I thought I'd check for strange increases in memory use but beyond that I have very few ideas. | Some thoughts to consider:
1. You know the computer doesn't respond, but that doesn't mean it's hung. Does it respond to a ping?
2. Maybe the disk activity light is on all the time?
3. You say "no keyboard" - do you mean no caps lock or num lock lights?
4. Although the .NET application may be the only one you're running at the time, that does not imply it is the cause of the problem. Some background job could be doing it.
For example, I notice that Retrospect backup, when it is creating a snapshot, freezes the entire system for 10-15 minutes. I mean, no caps lock, the clock in the task bar doesn't update, no CTRL-ALT-DEL, can't type into an "Answer" text box in SO, nothing. It had nothing to do with what I was doing at the time, which was answering a question on SO.
After it came back, SO asked if I was a human. My feelings were hurt. ;-) | You could attach a kernel debugger to the OS. That way you should be able to inspect the state of the OS and your process even if the OS is completely unresponsive. (Unfortunately, it's a lot harder than just hitting "break" in VS. I suggest reading John Robbin's "Debugging Applications for .NET and Windows" before trying that.)
You could also try to create memory dumps of your application in regular intervals. You might have to do a little scripting for that, though. (usually, you'd create a dump with a keystroke, using a tool like userdump or adplus, but if the OS is not responding to keystrokes, that won't work.) That way, you know what state your process is in during or shortly before a hang.
This page: <http://blogs.msdn.com/debuggingtoolbox/default.aspx> is a good starting point for scripting WinDbg. (If you don't know what to do with a memory dump, I'd again suggest John Robbin's excellent book on debugging!)
Other than that, I can only think of standard debugging tricks: does the problem occur on every PC? Does it happen if there are no client requests? Does it happen sooner if there are more client requests? Does it happen sooner if there is less available physical memory? Try removing parts of your application (maybe on a separate server for testing) and see if the problem still occurs, and so on. Try running it in a VM so you can see if it uses the CPU, harddisk, or network during those "hangs". | What can make a .NET app freeze the computer? | [
"",
"c#",
".net",
"managed",
"ethernet",
""
] |
I saw this in the java docs: [ScheduledAtFixedRate](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)), it says
> If any execution of the task
> encounters an exception, subsequent
> executions are suppressed
I don't want this to happen in my application. Even if I see an exception I would always want the subsequent executions to occur and continue. How can I get this behavior from `ScheduledExecutorService`. | Surround the Callable.call method or the Runnable.run method with a try/catch...
eg:
```
public void run()
{
try
{
// ... code
}
catch(final IOException ex)
{
// handle it
}
catch(final RuntimeException ex)
{
// handle it
}
catch(final Exception ex)
{
// handle it
}
catch(final Error ex)
{
// handle it
}
catch(final Throwable ex)
{
// handle it
}
}
```
Note that catching anything other than what the compiler tells you too (the IOException in my sample) isn't a good idea, but there are some times, and this sounds like one of them, that it can work out if you handle it properly.
Remember that things like Error are very bad - the VM ran out of memory etc... so be careful how you handle them (which is why I separated them out into their own handlers rather than just doing catch(final Throwable ex) and nothing else). | Try [`VerboseRunnable`](http://www.jcabi.com/jcabi-log/apidocs/com/jcabi/log/VerboseRunnable.html) class from [jcabi-log](http://www.jcabi.com/jcabi-log), which does the wrapping suggested by TofuBeer:
```
import com.jcabi.log.VerboseRunnable;
Runnable runnable = new VerboseRunnable(
Runnable() {
public void run() {
// do business logic, may Exception occurs
}
},
true // it means that all exceptions will be swallowed and logged
);
```
Now, when anybody calls `runnable.run()` no exceptions are thrown. Instead, they are swallowed and logged (to SLF4J). | How to reschedule a task using a ScheduledExecutorService? | [
"",
"java",
""
] |
I've been trying to learn about applets by studying the code for the ["Welcome to HotJava"](http://java.sun.com/j2se/1.4.2/docs/guide/misc/applet.html) applet. I decompiled the \*.class file using the Windows version of [Jad](http://www.kpdus.com/jad.html), and I see the following lines of code
```
public void init() {
// Skip some lines...
addMouseListener(this);
}
public void destroy()
{
removeMouseListener(this);
}
```
Is the destroy method really necessary here? Why does the applet need to remove itself as a mouse listener if it's just about to end? | The `destroy()` method cleans up resources so they can be released. When the whole JVM will be shutting down, it's not as critical to release all resources before shutting down, but it's always a good idea to do The Right Thing even when it is not strictly necessary.
Depending on the threading model, if you leave yourself as a mouse listener, then you will still be notified if mouse events occur. If there are multiple Applets in the same JVM and only one Applet is ending, then you can leave threads in a funny state if you leave a listener to which no action will be taken. It's possible that you can lock up the other Applets by doing so.
EDIT:
By threads in a funny state, I mean (for example) if a listener whose Applet thread has stopped is queuing messages to a queue that no-one is reading from, then eventually the queue will fill up and the dispatch thread will block. (In more detail, let's assume the listener does nothing but queue the message and that there is a thread in the Applet -- now stopped -- that reads from this queue. Once the queue fills, it will block!)
With a mouse listener, specifically, you may well be safe, assuming when the Applet quits it is no longer visible and can no longer receive mouse events. With a different sort of listener, however, you could get into trouble. Always doing the right thing, even when it is not truly necessary, gets you in the habit so you don't forget to do the right thing when it's actually critical. :) | The destroy() is critical if you want to leave any "evidence" that your applet had ever run...
For example, you could send all your state information to a file or a server for subsequent use, or let the server know that you are disconnecting.
Imagine that you had a chat application... | Why does this applet have a destroy method? | [
"",
"java",
"applet",
""
] |
Is it possible to authenticate users across sub-domains when the authentication takes place at a sub-domain instead of the parent domain?
For example:
User logs into site1.parent.com, and then we need to send them to reporting.parent.com.
Can I authenticate them to the reporting site even though the log-in occured at a sub-domain?
So far all of the research I have done has users logging into the parent domain first and then each sub-domain has access to the authentication cookie. | You can set the cookie to be the parent domain at authentication time but you have to explicitly set it, it will default to the full domain that you are on.
Once the auth cookie is correctly set to the parent domain, then all sub-domains should be able to read it. | When you authenticate the user, set the authentication cookie's domain to the second-level domain, i.e. parent.com. Each sub-domain will receive the parent domain's cookies on request, so authentication over each is possible since you will have a shared authentication cookie to work with.
Authentication code:
```
System.Web.HttpCookie authcookie = System.Web.Security.FormsAuthentication.GetAuthCookie(UserName, False);
authcookie.Domain = "parent.com";
HttpResponse.AppendCookie(authcookie);
HttpResponse.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(UserName,
False));
``` | Forms Authentication across Sub-Domains | [
"",
"c#",
"asp.net",
"forms-authentication",
""
] |
I am deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this.
So how can it be done?
1. Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it)
2. Pure Python web server eg paste, cherrypy, Spawning, Twisted.web
3. as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling
4. Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server.
More?
I want to know how you do it, and why it is the best way to do it. I would absolutely **love** you to bore me with details about the whats and the whys, application specific stuff, etc. | As always: It depends ;-)
When I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in using non blocking IO out of the box but I had sometimes problems with it because of the patching it's doing.
You are always free to put a varnish in front as well of course.
If an Apache is required I am usually going with solution 3 so that I can keep processes separate. You can also more easily move processes to other servers etc. I simply like to keep things separate.
For static files I am using right now a separate server for a project which just serves static images/css/js. I am using lighttpd as webserver which has great performance (in this case I don't have a varnish in front anymore).
Another useful tool is [supervisord](http://supervisord.org/) for controlling and monitoring these services.
I am additionally using [buildout](http://pypi.python.org/pypi/zc.buildout) for managing my deployments and development sandboxes (together with [virtualenv](http://pypi.python.org/pypi/virtualenv)). | The absolute easiest thing to deploy is CherryPy. Your web application can also become a standalone webserver. CherryPy is also a fairly fast server considering that it's written in pure Python. With that said, it's not Apache. Thus, I find that CherryPy is a good choice for lower volume webapps.
Other than that, I don't think there's any right or wrong answer to this question. Lots of high-volume websites have been built on the technologies you talk about, and I don't think you can go too wrong any of those ways (although I will say that I agree with mod-wsgi not being up to snuff on every non-apache server).
Also, I've been using [isapi\_wsgi](http://code.google.com/p/isapi-wsgi/) to deploy python apps under IIS. It's a less than ideal setup, but it works and you don't always get to choose otherwise when you live in a windows-centric world. | How do you deploy your WSGI application? (and why it is the best way) | [
"",
"python",
"deployment",
"wsgi",
""
] |
The title is partially static with an variable suffix. For example *"Window Title {- user\_id}"*.
How can I get the handle without knowing the exact title? | Look through all the Processes and check the [MainWindowTitle](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowtitle.aspx). (You can use regexps, or `StartsWith`, etc)
```
foreach(Process proc in Process.GetProcesses())
{
if(proc.MainWindowTitle.StartsWith("Some String"))
{
IntPtr handle = proc.MainWindowHandle;
// ...
}
}
``` | [This CodeProject article](http://www.codeproject.com/KB/cs/runninginstanceie.aspx) describes how to enumerate Top level windows (Based on Win32 API [EnumWindows](http://msdn.microsoft.com/en-us/library/ms633497.aspx)).
You can easily modify it to filter on a partial window title: Modify EnumWindowsCallBack.
HTH. | Get the handle of a window with not fully known title. (C#) | [
"",
"c#",
"api",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.