Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything:
`SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')`
Can parameters be used like this? or are they only valid in an instance such as:
`SELECT * FROM compliance_corner WHERE body LIKE '%<string>%'` (where `<string>` is the search object).
EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed?
Also, I ran this statement in SQL Server: `SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE`%max%')` and that returns results.
|
Your visual basic code would look something like this:
```
Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")
cmd.Parameters.Add("@query", searchString)
```
|
Well, I'd go with:
```
Dim cmd as New SqlCommand(
"SELECT * FROM compliance_corner"_
+ " WHERE (body LIKE @query )"_
+ " OR (title LIKE @query)")
cmd.Parameters.Add("@query", "%" +searchString +"%")
```
|
Howto? Parameters and LIKE statement SQL
|
[
"",
"asp.net",
"sql",
"vb.net",
""
] |
Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that).
The specific example I have is a [DirectoryIterator](http://www.php.net/directoryiterator) but it would be nice to have a solution general to any iterator.
```
$dir = new DirectoryIterator('.');
foreach ($dir as $file)
echo $file->getFilename();
```
I'd like to be able to sort these by various criteria (filename, size, etc)
|
There is no way to do that. An iterator should "iterate" through the list. You have to sort the underlying list to achieve the needed behavior.
By the way, the more complete reference to the SPL is here:
<http://www.php.net/~helly/php/ext/spl/>
|
For the ones that end up here 5 years later:
If you make the Iterator an extension of ArrayIterator you can use
ArrayIterator::uasort (to sort by value) and ArrayIterator::uksort (to sort by key)
<http://php.net/manual/en/arrayiterator.uasort.php>
<http://php.net/manual/en/arrayiterator.uksort.php>
|
Sorting PHP Iterators
|
[
"",
"php",
"iterator",
""
] |
I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that *imagedestroy* function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this:
```
function shutdown_func()
{
global $img;
if ($img)
imagedestroy($img);
}
register_shutdown_function("shutdown_func");
```
However, I believe that appropriate place for my class would be to place a call to *imagedestroy* in class' destructor.
I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser.
Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.
|
I just tested with Apache, PHP being used as Apache module. I created an endless loop like this:
```
<?php
class X
{
function __destruct()
{
$fp = fopen("/var/www/htdocs/dtor.txt", "w+");
fputs($fp, "Destroyed\n");
fclose($fp);
}
};
$obj = new X();
while (true) {
// do nothing
}
?>
```
Here's what I found out:
* pressing STOP button in Firefox does not stop this script
* If I shut down Apache, destructor does not get called
* It stops when it reaches PHP max\_execution\_time and destuctor does not get called
However, doing this:
```
<?php
function shutdown_func() {
$fp = fopen("/var/www/htdocs/dtor.txt", "w+");
fputs($fp, "Destroyed2\n");
fclose($fp);
}
register_shutdown_function("shutdown_func");
while (true) {
// do nothing
}
?>
```
shutdown\_func gets called. So this means that class destuctor is not that good as shutdown functions.
|
Based on the principle that you should [finish what you start](http://www.pragprog.com/the-pragmatic-programmer/extracts/tips), I'd say the destructor is the correct place for the free call.
The [destructor](http://www.php.net/manual/en/language.oop5.decon.php) will be called when the object is disposed of, whereas a [shutdown function](http://php.net/manual/en/function.register-shutdown-function.php) will not be called until script execution finishes. As noted by Wolfie, these won't necessarily happen if you forcibly halt the server or the script, but at that time, the memory allocated by PHP will be freed anyway.
Also noted by Wolfie, PHP will free up script resources when the script closes, so if you're only instantiating one of these objects, then you probably wouldn't notice a massive difference. However, if you later do end up instantiating these things, or do so in a loop, then you probably don't want to have to worry about a sudden spike in memory usage, so for the sake of future sanity, I return to my original recommendation; put it in the destructor.
|
PHP: destructor vs register_shutdown_function
|
[
"",
"php",
"image-processing",
"memory-leaks",
"destructor",
""
] |
What are the best practices to do transactions in C# .Net 2.0. What are the classes that should be used? What are the pitfalls to look out for etc. All that commit and rollback stuff. I'm just starting a project where I might need to do some transactions while inserting data into the DB. Any responses or links for even basic stuff about transactions are welcome.
|
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
```
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
```
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
```
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
```
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
* On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.
* There is a [glitch](https://stackoverflow.com/questions/195420/transactionscope-bug-in-net-more-information#195427) that means you might need to tweak your connection string
|
```
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
{
connection1.Open();
// Start a local transaction.
SqlTransaction sqlTran = connection1.BeginTransaction();
// Enlist a command in the current transaction.
SqlCommand command = connection1.CreateCommand();
command.Transaction = sqlTran;
try
{
// Execute two separate commands.
command.CommandText =
"insert into [doctor](drname,drspecialization,drday) values ('a','b','c')";
command.ExecuteNonQuery();
command.CommandText =
"insert into [doctor](drname,drspecialization,drday) values ('x','y','z')";
command.ExecuteNonQuery();
// Commit the transaction.
sqlTran.Commit();
Label3.Text = "Both records were written to database.";
}
catch (Exception ex)
{
// Handle the exception if the transaction fails to commit.
Label4.Text = ex.Message;
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Label5.Text = exRollback.Message;
}
}
}
}
```
|
Transactions in .net
|
[
"",
"c#",
".net",
"transactions",
""
] |
I've created a PHP DOM xml piece and saved it to a string like this:
```
<?php
// create a new XML document
$doc = new DomDocument('1.0');
...
...
...
$xmldata = $doc->saveXML();
?>
```
Now I can't use the headers to send a file download prompt and I can't write the file to the server, or rather I don't want the file laying around on it.
Something like a save this file link or a download prompt would be good. How do I do it?
|
I see from the comments that you're working from within a CMS framework and are unable to stop content from being output prior to where your code will be.
If the script in which you're working has already output content (beyond your control), then you can't do what you're trying to achieve in just one script.
Your script can either send headers saying "the following content is HTML" then output the HTML or send headers saying "the following content is XML, is an attachment and has a certain filename". You can't do both.
You can either output HTML containing a link to a separate script for downloading an XML file or you can issue a file download and output no HTML.
Therefore, you'll have to add a download link in the output of the CMS script you're modifying and then handle the download in a separate script.
I have made a working example that should help. The example includes a simple HTML document containing a download link, and a PHP script that then handles the download.
View the code below or take a look at the [live example](http://webignition.net/examples/xmldownload/).
**HTML (extraneous fluff removed, not necessarily valid)**
```
<html>
<head>
<title>XML Download Example</title>
</head>
<body>
<a href="download.php">Download XML example</a>
</body>
</html>
```
**PHP**
```
<?php
// Populate XML document
$doc = new DomDocument();
// ... various modifications to the document are made
// Output headers
header('Content-type: "text/xml"; charset="utf8"');
header('Content-disposition: attachment; filename="example.xml"');
// Output content
echo $doc->saveXML();
?>
```
If you are fully unable to handle the download via a second script (perhaps you can't get access to the relevant data), you'll have to re-think the problem.
|
You could enable output\_buffering in your php.ini, then you might have some options with sending headers.
<http://us.php.net/manual/en/function.headers-sent.php>
|
Create PHP DOM xml file and create a save file link/prompt without writing the file to the server when headers already sent
|
[
"",
"php",
"xml",
"dom",
"file",
""
] |
I want to be able to load a serialized xml class to a Soap Envelope. I am starting so I am not filling the innards so it appears like:
```
<Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" />
```
I want it to appear like:
```
<Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></Envelope>`
```
The class I wrote is this:
```
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",ElementName="Envelope", IsNullable = true)]
public class TestXmlEnvelope
{
[System.Xml.Serialization.XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public System.Collections.ArrayList Body = new System.Collections.ArrayList();
} //class TestXmlEnvelope`
```
I am using this as an example since other people might want it in an individual element. I am sure this must be simple but sadly I don't know the right keyword for this.
As always thanks for your help.
[Edit] The error comes when I try to use this instruction
```
System.Xml.Serialization.XmlSerializer xmlout = new System.Xml.Serialization.XmlSerializer(typeof(TestXmlEnvelope));
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
xmlout.Serialize(memOut, envelope, namespc);
Microsoft.Web.Services.SoapEnvelope soapEnv = new Microsoft.Web.Services.SoapEnvelope();
soapEnv.Load(memOut);
```
It gives me error "Root Element not found".
[Edit] I fixed the error the problem was that after I serialized the object I didn't set the memOut.Position = 0. Still I hope this question helps other people that may want to do this.
|
The main issue here is that the `XmlSerializer` calls `WriteEndElement()` on the `XmlWriter` when it would write an end tag. This, however, generates the shorthand `<tag/>` form when there is no content. The `WriteFullEndElement()` writes the end tag separately.
You can inject your own `XmlTextWriter` into the middle that the serializer would then use to exhibit that functionality.
Given that `serializer` is the appropriate `XmlSerializer`, try this:
```
public class XmlTextWriterFull : XmlTextWriter
{
public XmlTextWriterFull(TextWriter sink) : base(sink) { }
public override void WriteEndElement()
{
base.WriteFullEndElement();
}
}
...
var writer = new XmlTextWriterFull(innerwriter);
serializer.Serialize(writer, obj);
```
[Edit] for the case of your added code, add facade constructors for:
```
public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
```
Then, use the memory stream as your inner stream in the constructor as before:
```
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
XmlTextWriterFull writer = new XmlTextWriterFull(memOut, Encoding.UTF8Encoding); //Or the encoding of your choice
xmlout.Serialize(writer, envelope, namespc);
```
|
Note for the record: The OP was using the [\*\*\*Microsoft.\*\*\*Web.Services.SoapEnvelope](http://msdn.microsoft.com/en-us/library/ms977223.aspx#) class, which is part of the extremely obsolete WSE 1.0 product. This class derived from the XmlDocument class, so it's possible that the same issues would have been seen with XmlDocument.
Under no circumstances should WSE be used for any new development, and if it is already in use, the code should be migrated as soon as possible. WCF or ASP.NET Web API are the only technologies that should be used for .NET web services going forward.
|
XmlSerializer Serialize empty variable to use both tags?
|
[
"",
"c#",
"xml",
"xml-serialization",
""
] |
Does anyone know of a set of bindings for C# to drive the FFMpeg library directly ? I could shell to ffmpeg.exe directly but I found it hard to sync/control as a separate process. any help would be appreciated.
|
Tao.ffmpeg: <http://www.taoframework.com/project/ffmpeg>
it compiles and has a binary dist which is more than can be said for ffmpeg-sharp at this point. It is, however, not particularly easy to use.
|
I've seen this library:
[**ffmpeg-sharp**](http://code.google.com/p/ffmpeg-sharp/) a wrapper library over the FFmpeg multimedia suite that provides easy to use wrappers for use in C#.
|
Anyone know of a set of C# bindings for FFMPEG?
|
[
"",
"c#",
".net",
"binding",
"ffmpeg",
""
] |
I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.
Something along the lines of
```
static void Main () {
if (Debugger.IsAttached)
RunApp();
else {
try {
RunApp();
}
catch (Exception e) {
LogException(e);
throw;
}
}
}
```
While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.
Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.
Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?
|
As Paul Betts already mentioned, you might be better off using the [AppDomain.UnhandledException](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx) event instead of a try/catch block.
In your UnhandledException event handler you can log/display the exception and then offer the option to debug e.g. show a form with the exception details and buttons to ignore, debug or quit.
If the user selects the debug option, call [System.Diagnostics.Debugger.Break()](http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break.aspx) which allows the user to attach whatever debugger they want with the full call stack still available.
Obviously, you could disable this option for any builds you know you're not ever going to be attaching the debugger to.
```
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
RunApp();
}
static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject);
Console.WriteLine("Do you want to Debug?");
if (Console.ReadLine().StartsWith("y"))
Debugger.Break();
}
static void RunApp()
{
throw new Exception();
}
}
```
|
Horribly hacky but without runtime hooks (I know of none) the only way to get to the stack frame where you are throwing from....
All exceptions which are known to be terminal thrown would have to have the following in their constructor:
```
#if DEBUG
System.Diagnostics.Debugger.Launch()
#endif
```
This would present a dialogue allowing the user to either supply the relevant debugger or choose no and no debugging will occur (either way the exception will finish being constructed then be thrown. This obviously only works on exceptions whose source you control.
I don't recommend this, in a debug build with debugger attached you can just choose to get 'First Chance' break on exception throwing which should normally be sufficient to your needs.
Another option is to start generating mini dumps programmatically at the exception throw sites, such data could then be inspected later with a tool like windbg but not interfere too much with the desired behaviour of the exception unwinding the stack after.
The act of the exception reaching your catch-all trap is precisely the stack unwind you don't want, sorry.
If you're comfortable with C++ and fancy it you could build a minor (but complex to get right) fork of mono which caused all exceptions to trigger the debugger. Alternatively just rebuild mono's BCL Exception class to do the same as detailed above..
|
Attaching the .net debugger while still providing useful logging on death
|
[
"",
"c#",
"debugging",
"stack-trace",
""
] |
What are some ways that I can query the local machine's specifications (a range of things from CPU specs, OS version, graphics card specs and drivers, etc.) through a programmatic interface? We're writing a simple app in C# to test compatibility of our main app and want to have it dump out some system metrics, but I can't seem to find where to even start, what interfaces to use, libraries, anything.
I've tried all kinds of searches, but can only find programs, and GUI ones at that, which require a user to interact with, or have to install.
Alternatively, a small, command-line program would work just as well, as long as we'd be permitted to distribute it with the test app.
I have found one program that gets some of the specs I'd want, [PsInfo](http://technet.microsoft.com/en-us/sysinternals/bb897550.aspx). However, it seems to require each user to agree to some license when it is first run, even though it's a command line app. Plus, it only deals with OS/CPU info, and I will need more than that.
Also: forgot to mention explicitly, but this indeed is only going to be necessary for Windows machines. You folks are quick!
Edit: This WMI does look like what I need, thanks! Quite a can of worms though, so I've got to dive in. It mentions that for some things the user has to have administrator privileges; this probably won't be a big problem, but it might limit it a little.
|
For this type of information [WMI](http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx) is your friend. Fortunately dealing with WMI in .NET is much easier than in the unmanaged world. There are quite a lot of articles out there to get started with, like [this one](http://www.csharphelp.com/archives2/archive334.html), or [this one](http://69.10.233.10/KB/system/Wmi_Processor_infoWrapper.aspx) to retrieve processor information.
You will end up writing SQL-like queries against objects in the WMI namespace to retrieve the information you want.
|
Maybe look into using [Windows Management Instrumentation](http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx) (WMI), assuming it's a Windows machine your planning to query. Take a look at the [WMI Code Creator](http://www.microsoft.com/downloads/details.aspx?familyid=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en) from Microsoft. It can easily get you going with code samples for in a few languages.
WMI works excellent all the way back to the Windows 2000 era, but can also work in Win98 machines too with some help.
As long as you have, or can provide, administrator credentials for the machine you're trying to query, WMI is definitely the way to go.
|
Querying machine specs
|
[
"",
"c#",
"wmi",
""
] |
I'm trying to deserialize an xml structure that looks like this:
```
<somecontainer>
<key1>Value1</key1>
<key1>Value2</key1>
<key2>Value3</key2>
<key2>Value4</key2>
</somecontainer>
```
I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.
And no, I cannot change the xml structure. Anyone know how to do this with xstream ?
|
I have found that a custom serializer is needed for this case, no way around it.
Similarly
```
<node attr1="xxx">value1</node>
```
also needs a custom serializer.
|
I have not used XStream in some time, but [implicit collections](http://x-stream.github.io/alias-tutorial.html#omit) probably does what you want.
|
Deserializing a legacy XML structure in xstream
|
[
"",
"java",
"xstream",
""
] |
Added: Working with SQL Server 2000 and 2005, so has to work on both. Also, value\_rk is not a number/integer (Error: Operand data type uniqueidentifier is invalid for min operator)
Is there a way to do a single column "DISTINCT" match when I don't care about the other columns returned? Example:
```
**Table**
Value A, Value L, Value P
Value A, Value Q, Value Z
```
I need to return only one of these rows based on what is in the first one (Value A). I still need results from the second and third columns (the second should actually match all across the board anyway, but the third is a unique key, which I need at least one of).
Here's what I've got so far, although it doesn't work obviously:
```
SELECT value, attribute_definition_id, value_rk
FROM attribute_values
WHERE value IN (
SELECT value, max(value_rk)
FROM attribute_values
)
ORDER BY attribute_definition_id
```
I'm working in ColdFusion so if there's a simple workaround in that I'm open to that as well. I'm trying to limit or "group by" the first column "value". value\_rk is my big problem since every value is unique but I only need one.
NOTE: value\_rk is not a number, hence this DOES NOT WORK
UPDATE: I've got a working version, it's probably quite a bit slower than a pure SQL version, but honestly anything working at this point is better than nothing. It takes the results from the first query, does a second query except limiting it's results to one, and grabs a matching value\_rk for the value that matches. Like so:
```
<cfquery name="queryBaseValues" datasource="XXX" timeout="999">
SELECT DISTINCT value, attribute_definition_id
FROM attribute_values
ORDER BY attribute_definition_id
</cfquery>
<cfoutput query="queryBaseValues">
<cfquery name="queryRKValue" datasource="XXX">
SELECT TOP 1 value_rk
FROM attribute_values
WHERE value = '#queryBaseValues.value#'
</cfquery>
<cfset resourceKey = queryRKValue.value_rk>
...
```
So there you have it, selecting a single column distinctly in ColdFusion. Any pure SQL Server 2000/2005 suggestions are still very welcome :)
|
this might work:
```
SELECT DISTINCT a.value, a.attribute_definition_id,
(SELECT TOP 1 value_rk FROM attribute_values WHERE value = a.value) as value_rk
FROM attribute_values as a
ORDER BY attribute_definition_id
```
.. not tested.
|
```
SELECT a1.value, a1.attribute_definition_id, a1.value_rk
FROM attribute_values AS a1
LEFT OUTER JOIN attribute_values AS a2
ON (a1.value = a2.value AND a1.value_rk < a2.value_rk)
WHERE a2.value IS NULL
ORDER BY a1.attribute_definition_id;
```
In other words, find the row `a1` for which no row `a2` exists with the same `value` and a greater `value_rk`.
|
Select one column DISTINCT SQL
|
[
"",
"sql",
"sql-server",
"coldfusion",
"cfml",
""
] |
I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.
Pulling the class dynamically from the global namespace works:
```
result = globals()[classname](param).html
```
And it's certainly more succinct than:
```
if classname == 'Foo':
result = Foo(param).html
elif classname == 'Bar':
...
```
What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?
|
A flaw with this approach is that it may give the user the ability to to more than you want them to. They can call *any* single-parameter function in that namespace just by providing the name. You can help guard against this with a few checks (eg. isinstance(SomeBaseClass, theClass), but its probably better to avoid this approach. Another disadvantage is that it constrains your class placement. If you end up with dozens of such classes and decide to group them into modules, your lookup code will stop working.
You have several alternative options:
1. Create an explicit mapping:
```
class_lookup = {'Class1' : Class1, ... }
...
result = class_lookup[className](param).html
```
though this has the disadvantage that you have to re-list all the classes.
2. Nest the classes in an enclosing scope. Eg. define them within their own module, or within an outer class:
```
class Namespace(object):
class Class1(object):
...
class Class2(object):
...
...
result = getattr(Namespace, className)(param).html
```
You do inadvertantly expose a couple of additional class variables here though (\_\_bases\_\_, \_\_getattribute\_\_ etc) - probably not exploitable, but not perfect.
3. Construct a lookup dict from the subclass tree. Make all your classes inherit from a single baseclass. When all classes have been created, examine all baseclasses and populate a dict from them. This has the advantage that you can define your classes anywhere (eg. in seperate modules), and so long as you create the registry after all are created, you will find them.
```
def register_subclasses(base):
d={}
for cls in base.__subclasses__():
d[cls.__name__] = cls
d.update(register_subclasses(cls))
return d
class_lookup = register_subclasses(MyBaseClass)
```
A more advanced variation on the above is to use self-registering classes - create a metaclass than automatically registers any created classes in a dict. This is probably overkill for this case - its useful in some "user-plugins" scenarios though.
|
First of all, it sounds like you may be reinventing the wheel a little bit... most Python web frameworks (CherryPy/TurboGears is what I know) already include a way to dispatch requests to specific classes based on the contents of the URL, or the user input.
There is nothing **wrong** with the way that you do it, really, but in my experience it tends to indicate some kind of "missing abstraction" in your program. You're basically relying on the Python interpreter to store a list of the objects you might need, rather than storing it yourself.
So, as a first step, you might want to just make a dictionary of all the classes that you might want to call:
```
dispatch = {'Foo': Foo, 'Bar': Bar, 'Bizbaz': Bizbaz}
```
Initially, this won't make much of a difference. But as your web app grows, you may find several advantages: (a) you won't run into namespace clashes, (b) using `globals()` you may have security issues where an attacker can, in essence, access any global symbol in your program if they can find a way to inject an arbitrary `classname` into your program, (c) if you ever want to have `classname` be something other than the actual exact classname, using your own dictionary will be more flexible, (d) you can replace the `dispatch` dictionary with a more-flexible user-defined class that does database access or something like that if you find the need.
The security issues are particularly salient for a web app. Doing `globals()[variable]` where `variable` is input from a web form is just **asking for trouble**.
|
Best approach with dynamic classes using Python globals()
|
[
"",
"python",
"coding-style",
"namespaces",
""
] |
Are there any tools to transform SVG (XML) data to Canvas friendly input?
|
No I don't think so. SVG is actually rather different to Canvas. SVG is a vector graphics description language, whereas Canvases are programmatically "drawn" by sets of instructions. Also, Canvas isn't actually vector based at all.
Take a look at the [Raphael Javascript Library](http://www.raphaeljs.com/). Its API will draw SVG/Canvas/VML depending on the capabilities of the browser.
|
Take a look at canvg. It is a JavaScript library that will parse SVG and render into a specified canvas element:
<http://code.google.com/p/canvg/>
There's also an Ajaxian article (but I can only post one link per post) It's titled "CanVG: Using Canvas to render SVG files"
|
Are there any tools to transform SVG data to Canvas friendly input?
|
[
"",
"javascript",
"xml",
"svg",
""
] |
I've been wondering about how hard it would be to write some Python code to search a string for the index of a substring of the form `${`*expr*`}`, for example, where *expr* is meant to be a Python expression or something resembling one. Given such a thing, one could easily imagine going on to check the expression's syntax with `compile()`, evaluate it against a particular scope with `eval()`, and perhaps even substitute the result into the original string. People must do very similar things all the time.
I could imagine solving such a problem using a third-party parser generator [oof], or by hand-coding some sort of state machine [eek], or perhaps by convincing Python's own parser to do the heavy lifting somehow [hmm]. Maybe there's a third-party templating library somewhere that can be made to do exactly this. Maybe restricting the syntax of *expr* is likely to be a worthwhile compromise in terms of simplicity or execution time or cutting down on external dependencies -- for example, maybe all I really need is something that matches any *expr* that has balanced curly braces.
What's your sense?
## Update:
Thanks very much for your responses so far! Looking back at what I wrote yesterday, I'm not sure I was sufficiently clear about what I'm asking. Template substitution is indeed an interesting problem, and probably much more useful to many more people than the expression extraction subproblem I'm wondering about, but I brought it up only as a simple example of how the answer to my question might be useful in real life. Some other potential applications might include passing the extracted expressions to a syntax highlighter; passing the result to a real Python parser and looking at or monkeying with the parse tree; or using the sequence of extracted expressions to build up a larger Python program, perhaps in conjunction with some information taken from the surrounding text.
The `${`*expr*`}` syntax I mentioned is also intended as an example, and in fact I wonder if I shouldn't have used `$(`*expr*`)` as my example instead, because it makes the potential drawbacks of the obvious approach, along the lines of `re.finditer(r'$\{([^}]+)\}', s)`, a bit easier to see. Python expressions can (and often do) contain the `)` (or `}`) character. It seems possible that handling any of those cases might be much more trouble than it's worth, but I'm not convinced of that yet. Please feel free to try to make this case!
Prior to posting this question, I spent quite a bit of time looking at Python template engines hoping that one might expose the sort of low-level functionality I'm asking about -- namely, something that can find expressions in a variety of contexts and tell me where they are rather than being limited to finding expressions embedded using a single hard-coded syntax, always evaluating them, and always substituting the results back into the original string. I haven't figured out how to use any of them to solve my problem yet, but I do very much appreciate the suggestions regarding more to look at (can't believe I missed that wonderful list on the wiki!). The API documentation for these things tends to be pretty high-level, and I'm not too familiar with the internals of any of them, so I'm sure I could use help looking at those and figuring out how to get them to do this sort of thing.
Thanks for your patience!
|
I think your best bet is to match for all curly braced entries, and then check against Python itself whether or not it's valid Python, for which [compiler](https://docs.python.org/2/library/compiler.html) would be helpful.
|
I think what you're asking about is being able to insert Python code into text files to be evaluated. There are several modules that already exist to provide this kind of functionality. You can check the Python.org [**Templating wiki page**](http://wiki.python.org/moin/Templating) for a comprehensive list.
Some google searching also turned up a few other modules you might be interested in:
* [texttemplate](http://py-templates.sourceforge.net/texttemplate/index.html) (part of py-templates project)
* [template module](http://www.embl-heidelberg.de/~chenna/pythonpages/template.html)
If you're really looking just into writing this yourself for whatever reason, you can also dig into this Python cookbook solution [Yet Another Python Templating Utility (YAPTU)](http://code.activestate.com/recipes/52305/) :
> *"Templating" (copying an input file to output, on the fly inserting Python
> expressions and statements) is a frequent need, and YAPTU is a small but
> complete Python module for that; expressions and statements are identified
> by arbitrary user-chosen regular-expressions.*
**EDIT**: Just for the heck of it, I whipped up a severely simplistic code sample for this. I'm sure it has bugs but it illustrates a simplified version of the concept at least:
```
#!/usr/bin/env python
import sys
import re
FILE = sys.argv[1]
handle = open(FILE)
fcontent = handle.read()
handle.close()
for myexpr in re.finditer(r'\${([^}]+)}', fcontent, re.M|re.S):
text = myexpr.group(1)
try:
exec text
except SyntaxError:
print "ERROR: unable to compile expression '%s'" % (text)
```
Tested against the following text:
```
This is some random text, with embedded python like
${print "foo"} and some bogus python like
${any:thing}.
And a multiline statement, just for kicks:
${
def multiline_stmt(foo):
print foo
multiline_stmt("ahem")
}
More text here.
```
Output:
```
[user@host]$ ./exec_embedded_python.py test.txt
foo
ERROR: unable to compile expression 'any:thing'
ahem
```
|
Extracting a parenthesized Python expression from a string
|
[
"",
"python",
"parsing",
""
] |
I have a checkbox list control on my asp.net web form that I am dynamically populating from an arraylist. In javascript I want to be able to iterate through the values in the list and if a particular value has been selected to display other controls on the page.
My issue is that all the values in the checkbox list are showing up as 'on' instead of the actual value set. How do I get the actual values for each checkbox?
Thanks.
Javascript:
```
checkBoxs=document.getElementById(CheckboxList);
var options=checkBoxs.getElementsByTagName('input');
for(var i=0;i<options.length;i++)
{
if(options[i].value=="Other")
{
if(options[i].checked)
{
var otherPub=document.getElementById('<%=alsOtherPublicity.ClientID%>');
otherPub.style.display='block';
}
}
}
```
**Edit:** The line that I'm having problems with is if(options[i].value=="Other") as the values showing up in firebug are given as 'on' rather than the values that I set.
**Edit 2:** The html that is produces looks like:
```
<span id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity" class="ucFieldCBL" onChange="alValidate();" onClick="alPublicity('ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity');">
<input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$0"/>
<label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0">Text1</label>
<input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$1"/>
<label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1">Text2</label>
<input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$2"/>
<label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2">Text3</label>
<input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$3"/>
<label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3">Text4</label>
<input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$4"/>
<label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4">Text5</label>
</span>
```
It looks as if the issue stems from the lack of a value attribute available on the asp.net checkbox control as described by [Dave Parslow](http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html "Dave Parslow"). I'm currently trying a workaround by calling a function server side to return the text of the checkbox and using that instead.
|
I realised after much playing about with prerender events that I didn't actually need to know the exact value of the checkbox as the arraylist values would be in the same order as the checkboxes. I searched through the arraylist to get the position of the value that I needed and then used that position on the list of checkboxes.
It sounds a bit fiddly and I don't know if it would work for everyone but I thought I would put it up here anyway incase it helps someone else someday.
Thanks for all your help.
|
`options[i].checked` will return true or false.
`options[i].value` will give you the value attribute of the checkbox tag.
|
Webform checkbox value in javascript
|
[
"",
"asp.net",
"javascript",
""
] |
What is the difference in the accessibility of the following variables in Java?
```
public class Joe {
public int a;
protected int b;
private int b;
int c;
}
```
I'm most interested in what the last one is doing.
|
* `public`: read/writable for anyone
* `protected`: read/writable for
instances of subclasses **and from within the enclosing package**
* `private`: read/writable for **any** instance of the class
and inner or outer (enclosing) instance
* `int c`:
package-private, read/writable for
all classes inside same package
See the [JLS](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285) for more details
EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for `private`. I remember now... ;-)
|
Sorry for answering corrections to one previous answer but I don't have enough reputation to modify directly...
* `public` - read/writable for anyone
* `protected` - read/writable for
instances subclasses and all classes
inside same package
* `int c` : package-private,
read/writable for all classes inside
same package
* `private` - read/writable for any member of that class itself and inner classes (if any)
It is better to order the access modifiers this way, from the broadest access (`public`) to the narrowest (`private`), knowing that when going from narrow to broad, you don't lose any possibilities.
That's particularly important for "protected", where it is often misunderstood that classes in the same package can also access protected members of a class (not only its subclasses).
|
Java Instance Variable Accessibility
|
[
"",
"java",
"variables",
"inheritance",
""
] |
So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.
```
#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;
int main()
{
io_service io;
serial_port port( io, "COM3" );
port.set_option( serial_port_base::baud_rate( 19200 ) );
unsigned char commands[4] = { 1, 128, 240, 0 };
// write the commands to the device
return 0;
}
```
In short: need help with the io part of the serial\_port.
|
In addition to the baud rate, you may also need to set other options like: character\_size, flow\_control, parity and stop\_bits. To write your data to the serial port you can do the following:
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: [Buffers](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview/core/buffers.html).
|
Thanks to the help from here and other places I got it working. Wrote a small program that might help some people figure out the boost serial port stuff as well.
[boostserialportdemo.cpp](http://www.college-code.com/blog/wp-content/uploads/2008/11/boost_serial_port_demo.cpp)
|
Boost Asio serial_port - need help with io
|
[
"",
"c++",
"boost",
""
] |
My co-founder is currently asking on our blog for an embeddable code widget.
<http://devver.net/blog/2008/10/someone-please-build-an-awesome-embeddable-code-widget/>
Basically we want something like <http://pastie.org/> or <http://codepad.org/> but we really want to embed the code section in our blog. We know there are plugins for common blogs and server side solutions, but it would be great to be able to just embed a little javascript and have nicely formatted code anywhere...
Does something like this exist? Have we just missed it?
|
We had a user point out a WordPress plugin that uses Gist to do exactly what we were asking for...
<http://pomoti.com/gist-it-english>
Even if you don't use the plug in it looks like a feature of Gist lets you embed the code anywhere you want on the web. <http://gist.github.com>
Looks pretty sweet. Thanks goes to Dirceu Jr.
|
I think you want a javascript syntax highlighter
* <http://code.google.com/p/syntaxhighlighter/>
* <http://shjs.sourceforge.net/>
* <http://www.google.com/search?q=javascript+syntax+highlighter>
Sometimes you just keep thinking in the wrong keywords ;-)
|
Is there a good embeddable code widget for blogs
|
[
"",
"javascript",
"blogs",
"widget",
""
] |
I noticed the specificaition for Collections.sort:
```
public static <T> void sort(List<T> list, Comparator<? super T> c)
```
Why is the "`? super`" necessary here? If `ClassB` extends `ClassA`, then wouldn't we have a guarantee that a `Comparator<ClassA>` would be able to compare two `ClassB` objects anyway, without the "`? super`" part?
In other words, given this code:
```
List<ClassB> list = . . . ;
Comparator<ClassA> comp = . . . ;
Collections.sort(list, comp);
```
why isn't the compiler smart enough to know that this is OK even without specifying "`? super`" for the declaration of Collections.sort()?
|
Josh Bloch had a talk at Google I/O this year, called [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded), which you may find interesting. It talks about a mnemonic called "Pecs" (producer `extends`, consumer `super`), which explains why you use `? extends T` and `? super T` in your input parameters (only; never for return types), and when to use which.
|
There's a really nice (but twisty) explanation of this in [More Fun with Wildcards](http://java.sun.com/docs/books/tutorial/extra/generics/morefun.html).
|
Why is SomeClass<? super T> not equivalent to SomeClass<T> in Java generic types?
|
[
"",
"java",
"generics",
""
] |
I have a resource handler that is Response.WriteFile(fileName) based on a parameter passed through the querystring. I am handling the mimetype correctly, but the issue is in some browsers, the filename comes up as Res.ashx (The name of the handler) instead of MyPdf.pdf (the file I am outputting). Can someone inform me how to change the name of the file when it is sent back to the server? Here is my code:
```
// Get the name of the application
string application = context.Request.QueryString["a"];
string resource = context.Request.QueryString["r"];
// Parse the file extension
string[] extensionArray = resource.Split(".".ToCharArray());
// Set the content type
if (extensionArray.Length > 0)
context.Response.ContentType = MimeHandler.GetContentType(
extensionArray[extensionArray.Length - 1].ToLower());
// clean the information
application = (string.IsNullOrEmpty(application)) ?
"../App_Data/" : application.Replace("..", "");
// clean the resource
resource = (string.IsNullOrEmpty(resource)) ?
"" : resource.Replace("..", "");
string url = "./App_Data/" + application + "/" + resource;
context.Response.WriteFile(url);
```
|
Extending from Joel's comment, your actual code would look something like this:
```
context.Response.AddHeader("content-disposition", "attachment; filename=" + resource);
```
|
This Scott Hanselman post should be helpful:
<http://www.hanselman.com/blog/CommentView.aspx?guid=360>
|
Changing the name in the header for a resource handler in C#
|
[
"",
"c#",
"asp.net",
"mime-types",
"handler",
""
] |
Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?
```
function getSomethingAsync(someState, callback) {
var req = abc.createRequestObject(someParams);
req.invoke(makeCallback(someState, callback));
}
function makeCallback(someState, callback) {
return function getSomethingCallback(data) {
var result = processDataUsingState(data, someState);
callback(result); // alternately/optionally pass someState along to result
}
}
```
If not, is there a better or more idiomatic way?
|
I don't see any immediate problems with this - closures are powerful for numerous reasons, one of which is removing the need to use global variables for state maintenance.
That said, the only thing you need to be wary of with regards to closures is memory leaks that typically occur in IE, but those are usually, IIRC, related to DOM elements and event handlers attached thereto.
Proceed!
|
The more idiomatic way is to use [`Function.bind`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind), then you don't need to duplicate the code to create the closure. I'll use a simple example (that doesn't have your custom code) to explain
```
/**
* Retrieves the content of a url asyunchronously
* The callback will be called with one parameter: the html retrieved
*/
function getUrl(url, callback) {
$.ajax({url: url, success: function(data) {
callback(data);
}})
}
// Now lets' call getUrl twice, specifying the same
// callback but a different id will be passed to each
function updateHtml(id, html) {
$('#' + id).html(html);
}
// By calling bind on the callback, updateHTML will be called with
// the parameters you passed to it, plus the parameters that are used
// when the callback is actually called (inside )
// The first parameter is the context (this) to use, since we don't care,
// I'm passing in window since it's the default context
getUrl('/get/something.html', updateHTML.bind(window, 'node1'));
// results in updateHTML('node1', 'response HTML here') being called
getUrl('/get/something-else.html', updateHTML.bind(window, 'node2'));
// results in updateHTML('node2', 'response HTML here') being called
```
`Function.bind` is new so if you need backwards support, look at the Compatibility section of [`Function.bind`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind)
Lastly, I know the question wasn't tagged as jQuery. This was just the quickest way to show an asynchronous function without dealing with cross browser issues
|
Passing state to a callback in JavaScript an appropriate use of closures?
|
[
"",
"javascript",
"closures",
""
] |
How would I specify a color in app.config and then convert that into an actual System.Drawing.Color object at runtime?
|
One way would be to specify one of the [KnownColor](http://msdn.microsoft.com/en-us/library/system.drawing.knowncolor.aspx) values as the config text and then use [Color.FromName](http://msdn.microsoft.com/en-us/library/system.drawing.color.fromname.aspx) to create the Color object.
|
Have a look at [ColorTranslator](http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.aspx). You'll be able to specify a color, say in appSettings and use ColorTranslator to convert it into a real color. In particular I've found the .FromHtml() method very useful.
|
How to specify a Colour in config
|
[
"",
"c#",
".net",
"winforms",
""
] |
I use an anonymous object to pass my Html Attributes to some helper methods.
If the consumer didn't add an ID attribute, I want to add it in my helper method.
How can I add an attribute to this anonymous object?
|
If you're trying to extend this method:
```
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
```
Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:
This should do the trick:
```
public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
{
RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
// Add more parameters
foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
{
routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
}
return helper.ActionLink(linkText, actionName, routeValueDictionary);
}
```
|
The following extension class would get you what you need.
```
public static class ObjectExtensions
{
public static IDictionary<string, object> AddProperty(this object obj, string name, object value)
{
var dictionary = obj.ToDictionary();
dictionary.Add(name, value);
return dictionary;
}
// helper
public static IDictionary<string, object> ToDictionary(this object obj)
{
IDictionary<string, object> result = new Dictionary<string, object>();
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
foreach (PropertyDescriptor property in properties){
result.Add(property.Name, property.GetValue(obj));
}
return result;
}
}
```
|
Add property to anonymous type after creation
|
[
"",
"c#",
"reflection",
"anonymous-objects",
""
] |
Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )?
I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.
This is what I have as a proof of concept so far, but the "`<WebBrowser Source="{Binding Path=WebAddress}"`" does not compile.
```
<DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress">
<StackPanel Orientation="Horizontal">
<!--Web Control Here-->
<WebBrowser Source="{Binding Path=WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200"
/>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" />
<TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" />
</StackPanel>
<TextBox Text="{Binding Path=Street[0]}" />
<TextBox Text="{Binding Path=Street[1]}" />
<TextBox Text="{Binding Path=PhoneNumber}"/>
<TextBox Text="{Binding Path=FaxNumber}"/>
<TextBox Text="{Binding Path=Email}"/>
<TextBox Text="{Binding Path=WebAddress}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
```
|
The problem is that [`WebBrowser.Source`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.webbrowser.source?view=netframework-4.8) is not a `DependencyProperty`. One workaround would be to use some `AttachedProperty` magic to enable this ability.
```
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string) obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;
}
}
}
```
Then in your xaml do:
```
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"/>
```
|
I wrote a wrapper usercontrol, which makes use of the DependencyProperties:
XAML:
```
<UserControl x:Class="HtmlBox">
<WebBrowser x:Name="browser" />
</UserControl>
```
C#:
```
public static readonly DependencyProperty HtmlTextProperty = DependencyProperty.Register("HtmlText", typeof(string), typeof(HtmlBox));
public string HtmlText {
get { return (string)GetValue(HtmlTextProperty); }
set { SetValue(HtmlTextProperty, value); }
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
base.OnPropertyChanged(e);
if (e.Property == HtmlTextProperty) {
DoBrowse();
}
}
private void DoBrowse() {
if (!string.IsNullOrEmpty(HtmlText)) {
browser.NavigateToString(HtmlText);
}
}
```
and use it like so:
```
<Controls:HtmlBox HtmlText="{Binding MyHtml}" />
```
The only trouble with this one is that the WebBrowser control is not "pure" wpf... it is actually just a wrapper for a win32 component. This means that the control won't respect the z-index, and will always overlay other element (eg: in a scrollviewer this might cause some trouble)
more info about these win32-wpf issues on [MSDN](http://msdn.microsoft.com/en-us/library/ms742522.aspx)
|
databind the Source property of the WebBrowser in WPF
|
[
"",
"c#",
"wpf",
"xaml",
"data-binding",
"browser",
""
] |
I have a text file of URLs, about 14000. Below is a couple of examples:
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=100¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=10>
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=101¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=11>
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=102¶m2=123>
I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT\_ITEM\_ID separated off into a list of their own. What would be the best way to do this in Python?
Cheers
|
Here's another alternative to Graeme's, using the newer list comprehension syntax:
```
list2= [line for line in file if 'CONTENT_ITEM_ID' in line]
```
Which you prefer is a matter of taste!
|
I liked @bobince's answer (+1), but will up the ante.
Since you have a rather large starting set, you may wish to avoid loading the entire list into memory. Unless you need the whole list for something else, you could use a [Python generator expression](http://www.python.org/doc/2.5.2/ref/genexpr.html) to perform the same task by building up the filtered list item by item as they're requested:
```
for filtered_url in (line for line in file if 'CONTENT_ITEM_ID' in line):
do_something_with_filtered_url(filtered_url)
```
|
Python filter/remove URLs from a list
|
[
"",
"python",
"url",
"list",
"filter",
""
] |
Where can I find a list of all the C# Color constants and the associated R,G,B (Red, Green, Blue) values?
e.g.
Color.White == (255,255,255)
Color.Black == (0,0,0)
etc...
|
Run this program:
```
using System;
using System.Drawing;
using System.Reflection;
public class Test
{
static void Main()
{
var props = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (PropertyInfo prop in props)
{
Color color = (Color) prop.GetValue(null, null);
Console.WriteLine("Color.{0} = ({1}, {2}, {3})", prop.Name,
color.R, color.G, color.B);
}
}
}
```
Or alternatively:
```
using System;
using System.Drawing;
public class Test
{
static void Main()
{
foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))
{
Color color = Color.FromKnownColor(known);
Console.WriteLine("Color.{0} = ({1}, {2}, {3})", known,
color.R, color.G, color.B);
}
}
}
```
|
It looks like this [page](http://www.flounder.com/csharp_color_table.htm) has all of them.
|
C# Color constant R,G,B values
|
[
"",
"c#",
"colors",
"rgb",
"system.drawing.color",
""
] |
I have a form which takes both the user details and an image uploaded by them. I want to write the data to a user table and an image table but i am pretty sure that it cannot be done with just two separate insert statements. Any help would be much appreciated.
|
You need to insert the user first, then do "SELECT LAST\_INSERT\_ID()" to retrieve the id of the user. Then you can insert the image in the image table with the newly created user id. In PHP you can actually use [mysql\_insert\_id()](http://no.php.net/mysql_insert_id) to retrieve the new id. If you use mysql with InnoDB, you can also wrap the inserts in a [transaction](http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html), by issuing BEGIN, followed by the INSERTs, followed by either COMMIT if everything is successfully added, or ROLLBACK in case of failure.
|
```
$rec = mysql_query("insert into userdet values("$id","$username",....)");
if($rec)
mysql_query("insert into imag values("$id","$imgname",...)");
```
|
How do insert data into two different tables?
|
[
"",
"php",
"mysql",
""
] |
In C#, is it possible to extend a class that has no constructors?
Maybe I'm thinking about this incorrectly and just need a kick in the crotch. I have a Silverlight class that extends System.Windows.Media.Transform, With the official release of Silverlight 2, Transform now has no constructor. So, when I compile my class, I get an error saying that 'The type '...Transform' has no constructors defined.'
Is it still possible to extend this class in a useful way? If not, I'm going to be drawing an awful lot of sad faces.
|
The sole constructor to Transform is internal, so you can't derive from it yourself.
|
Hiding all public constructors is a technique used to prevent subclassing and force developers to use the class as intended. It may be the implementor wants you to use an Adapter or Facade or even a Proxy at the time of extension.
There may be important lifecycle details in the constructor that require the use as the original implementor intended, or it may be an oversight by the developer.
I've seen attempts at conversion to the Factory pattern where this is done in a manner that prevents subclassing. I.e. there is no protected constructor made available to subclasses. Sometimes advanced object patterns can strain the in-built capabilities of a language.
|
Extend No-Constructor class
|
[
"",
"c#",
".net",
"silverlight",
"oop",
""
] |
I found a while ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until the class constructor or load has been called. The reason was performance - but are there other reasons to do or not do this? Are there exceptions to this rule?
**ie: this is what I do based on what I think the best practice is:**
```
public class SomeClass
{
private PersonObject _person;
public SomeClass()
{
_person = new PersonObject("Smitface");
}
}
```
**opposed to:**
```
public class SomeClass
{
private PersonObject _person = new PersonObject("Smitface");
public SomeClass()
{
}
}
```
|
If you set your variable outside of the constructor then there is no error handling (handeling) available. While in your example it makes no difference, but there are many cases that you may want to have some sort of error handling. In that case using your first option would be correct.
Nescio talked about what implication this would have on your applicaiton if there were some constructor failures.
For that reason, I always use Option #1.
|
Honestly, if you look at the IL, all that happens in the second case is the compiler moves the initialization to the constructor for you.
Personally, I like to see all initialization done in the constructor. If I'm working on a throwaway prototype project, I don't mind having the initialization and declaration in the same spot, but for my "I want to keep this" projects I do it all in the constructor.
|
Declaring variables - best practices
|
[
"",
"c#",
".net",
""
] |
Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.
What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?
|
Enums. Replacing
```
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
```
with
```
public enum Suit {
CLUBS,
DIAMONDS,
HEARTS,
SPADES
}
```
|
Generics and no longer needing to create an iterator to go through all elements in a collection. The new version is much better, easier to use, and easier to understand.
EDIT:
Before:
```
List l = someList;
Iterator i = l.getIterator();
while (i.hasNext()) {
MyObject o = (MyObject)i.next();
}
```
After
```
List<MyObject> l = someList;
for (MyObject o : l) {
//do something
}
```
|
Java: Out with the Old, In with the New
|
[
"",
"java",
""
] |
I expected `A::~A()` to be called in this program, but it isn't:
```
#include <iostream>
struct A {
~A() { std::cout << "~A()" << std::endl; }
};
void f() {
A a;
throw "spam";
}
int main() { f(); }
```
However, if I change last line to
```
int main() try { f(); } catch (...) { throw; }
```
then `A::~A()` *is* called.
I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is `cl /EHa my.cpp`.
Is compiler right as usual? What does standard say on this matter?
|
The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.
The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.
According to the [draft standard](http://www.csci.csusb.edu/dick/c++std/cd2/except.html) section 15.3 bullet 9:
```
9 If no matching handler is found in a program, the function terminate()
(_except.terminate_) is called. Whether or not the stack is unwound
before calling terminate() is implementation-defined.
```
|
C++ language specification states:
*The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.”*
Your original code does not contain try block, that is why stack unwinding does not happen.
|
Why destructor is not called on exception?
|
[
"",
"c++",
"exception",
"visual-c++",
"destructor",
"stack-unwinding",
""
] |
In our desktop application, we have implemented a simple search engine using an [inverted index](http://en.wikipedia.org/wiki/Inverted_index).
Unfortunately, some of our users' datasets can get very large, e.g. taking up ~1GB of memory before the inverted index has been created. The inverted index itself takes up a lot of memory, almost as much as the data being indexed (another 1GB of RAM).
Obviously this creates problems with out of memory errors, as the 32 bit Windows limit of 2GB memory per application is hit, or users with lesser spec computers struggle to cope with the memory demand.
Our inverted index is stored as a:
```
Dictionary<string, List<ApplicationObject>>
```
And this is created during the data load when each object is processed such that the applicationObject's key string and description words are stored in the inverted index.
So, my question is: is it possible to store the search index more efficiently space-wise? Perhaps a different structure or strategy needs to be used? Alternatively is it possible to create a kind of CompressedDictionary? As it is storing lots of strings I would expect it to be highly compressible.
|
If it's going to be 1GB... put it on disk. Use something like Berkeley DB. It will still be very fast.
Here is a project that provides a .net interface to it:
<http://sourceforge.net/projects/libdb-dotnet>
|
I see a few solutions:
1. If you have the ApplicationObjects in an array, store just the index - might be smaller.
2. You could use a bit of C++/CLI to store the dictionary, using UTF-8.
3. Don't bother storing all the different strings, use a [Trie](http://en.wikipedia.org/wiki/Trie)
|
In-memory search index for application takes up too much memory - any suggestions?
|
[
"",
"c#",
"optimization",
"search",
"memory",
"search-engine",
""
] |
What's the best way to determine if the version of the JRE installed on a machine is high enough for the application which the user wants to run? Is there a way of doing it using java-only stuff? I'd like the solution to work on Windows/Linux/MacOSX - if the JRE version is too low a message should be displayed. Currently I'm getting an exception if i try to run it on Java 1.5 (the app is built for Java 1.6). If there's no universal solution, what's the best way to do it on Windows?
|
An application built for a higher-version JRE will not run on a lower-version JRE. So you wouldn't be able to just add code to your application to check the JRE version - if the JRE version was incompatible, your JRE-version-checking code would not run in the first place.
What you'd have to do is have some sort of launcher application that is built for a lower-version JRE (1.3?) that checks the version and then launches your app if necessary. This sounds kind of kludgy to me.
What about checking the version during installation? Are you installing the app in a way that allows you to check environment variables, or do any sort of scripting?
|
You could do this using reflection and two compilers. Compile a main class with the oldest java version you want to be able to run at all with. It checks the version using `System.getProperty("java.version")`, or whatever, and then uses reflection to load your *real* main class if that check passes, possibly even loading the jar directly. The JRE shouldn't load any classes that weren't referenced by your outer main class at compile time.
|
How to check JRE version prior to launch?
|
[
"",
"version",
"java",
"launch",
""
] |
As the title suggests, is it correct or valid to import/export static data from within a C++ class?
I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform.
Many thanks for the responses however.
|
Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using \_declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access it provided that that C++ access specification (public/protected/private) wouldn't block outside access in the first place.
Is it a good idea? Personally I don't think so as you would be exposing class internals not only within your library but to the outside world, which means that it will be pretty much impossible to change what is an implementation detail at the end of the day. Ask yourself if you are 100% certain if the interface of this class and large parts of its implementation will never, ever change...
|
An exported C++ class means that the DLL clients have to use the same compiler as the DLL because of name mangling and other issues. This is actually a pretty big problem, I once had to write C wrappers to a bunch of C++ classes because the client programs had switched to MSVC9, while the DLL itself was using MSVC71. [There were some other complications with switching the DLL to MSVC90]. Since then I've been quite skeptical about this business of exporting classes, and prefer to write a C wrapper for everything.
Now, if you're willing to pay the price of exporting classes, I'd say that exporting static data doesn't make the problem any worse. Arguably, among the kinds of things you could export, it is safest to export static constants. Even so, I'd rather not do it, because like Timo says, you're now locked into this implementation.
One of the frameworks that I worked on required its clients to provide a set of error code constants. Over time, we found that using a simple bunch of constants was too brittle, and we switched to an OO design. We had a default implementation that would return the common error codes, but each of the error codes was accessed using a virtual function which could be overridden by individual clients - and they used it from some advanced device specific error handling. This solution proved *far* more scalable than the one based on exporting constants.
I'd suggest that you think long and hard about how you expect the component to evolve before you exporting static variables.
|
Is it correct to export data members? (C++)
|
[
"",
"c++",
"dll",
"import",
"export",
""
] |
I have this piece of code (summarized)...
```
AnsiString working(AnsiString format,...)
{
va_list argptr;
AnsiString buff;
va_start(argptr, format);
buff.vprintf(format.c_str(), argptr);
va_end(argptr);
return buff;
}
```
And, on the basis that pass by reference is preferred where possible, I changed it thusly.
```
AnsiString broken(const AnsiString &format,...)
{
/* ... the rest, totally identical ... */
}
```
My calling code is like this:
```
AnsiString s1 = working("Hello %s", "World"); // prints "Hello World"
AnsiString s2 = broken("Hello %s", "World"); // prints "Hello (null)"
```
I think this is due to the way `va_start` works, but I'm not exactly sure what's going on.
|
If you look at what va\_start expands out to, you'll see what's happening:
```
va_start(argptr, format);
```
becomes (roughly)
```
argptr = (va_list) (&format+1);
```
If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the stack. When you take the address of the reference variable, you get the address or the original variable (in this case of a temporary AnsiString created before calling Broken), not the address of the argument.
If you don't want to pass around full classes, your options are to either pass by pointer, or put in a dummy argument:
```
AnsiString working_ptr(const AnsiString *format,...)
{
ASSERT(format != NULL);
va_list argptr;
AnsiString buff;
va_start(argptr, format);
buff.vprintf(format->c_str(), argptr);
va_end(argptr);
return buff;
}
...
AnsiString format = "Hello %s";
s1 = working_ptr(&format, "World");
```
or
```
AnsiString working_dummy(const AnsiString &format, int dummy, ...)
{
va_list argptr;
AnsiString buff;
va_start(argptr, dummy);
buff.vprintf(format.c_str(), argptr);
va_end(argptr);
return buff;
}
...
s1 = working_dummy("Hello %s", 0, "World");
```
|
Here's what the [C++ standard, [support.runtime]/[cstdarg.syn] p1.2](https://eel.is/c++draft/cstdarg.syn#1.2) says about `va_start()` (emphasis mine):
> The restrictions that ISO C places on
> the second parameter to the
> `va_start()` macro in header
> `<stdarg.h>` are different in this
> International Standard. The parameter
> `parmN` is the identifier of the
> rightmost parameter in the variable
> parameter list of the function
> definition (the one just before the
> `...`).
> **If the parameter `parmN` is declared with a function, array, or reference
> type,** or with a type that is not
> compatible with the type that results
> when passing an argument for which
> there is no parameter, **the behavior
> is undefined**.
As others have mentioned, using `va_list` in C++ is dangerous if you use it with non-straight-C items (and possibly even in other ways).
That said - I still use `printf()` all the time...
|
Are there gotchas using varargs with reference parameters
|
[
"",
"c++",
"reference",
"variadic-functions",
""
] |
Slightly related to my [other question](https://stackoverflow.com/questions/267750/java-instance-variable-accessibility): What is the difference between the following:
```
private class Joe
protected class Joe
public class Joe
class Joe
```
Once again, the difference between the last 2 is what I'm most interested in.
|
A public class is accessible to a class in any package.
A class with default access (`class Joe`) is only visible to other classes in the same package.
The private and protected modifiers can only be applied to inner classes.
A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.
A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.
|
* private: visible for outer classes only
* protected: visible for outer classes only
* public: visible for all other classes
* class: package-private, so visible for classes within the same package
See [JLS](http://java.sun.com/docs/books/jls/third_edition/html/names.html#104285) for more info.
|
Java Class Accessibility
|
[
"",
"java",
"class",
"accessibility",
""
] |
Is there any performance difference between the for loops on a primitive array?
Assume:
```
double[] doubleArray = new double[300000];
for (double var: doubleArray)
someComplexCalculation(var);
```
or :
```
for ( int i = 0, y = doubleArray.length; i < y; i++)
someComplexCalculation(doubleArray[i]);
```
**Test result**
I actually profiled it:
```
Total timeused for modern loop= 13269ms
Total timeused for old loop = 15370ms
```
So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5.
|
Your hand-written, "old" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The "new" form is definitely **not** faster.
If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the "new" form is equivalent to the following code:
```
1: double[] tmp = doubleArray;
2: for (int i = 0, y = tmp.length; i < y; i++) {
3: double var = tmp[i];
4: someComplexCalculation(var);
5: }
```
So, you can see that more local variables are used. The assignment of `doubleArray` to `tmp` at line 1 is "extra", but it doesn't occur in the loop, and probably can't be measured. The assignment to `var` at line 3 is also extra. If there is a difference in performance, this would be responsible.
Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop.
That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it "by hand", you may miss out on future optimizations. Generally, a good compiler can optimize "stupid" code well, but stumbles on "smart" code.
|
My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless.
There have been times people learned "Patterns" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.
Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your "fix" actually improved it enough to make that requirement pass.
The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.
Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.
To sum it up: the most value you can put into your code is to write it to be readable.
|
modern for loop for primitive array
|
[
"",
"java",
"performance",
"arrays",
"iteration",
""
] |
Specifically, I'm looking for a client-side, JavaScript and / or Flash based multiple file uploader. The closest thing I've found is [FancyUpload](http://digitarald.de/project/fancyupload/). Anyone have experience with it? If not, what else is out there?
|
Yahoo's [YUI Uploader](http://yuilibrary.com/yui/docs/uploader/uploader-dd.html) is your friend.
|
[Uploadify](http://www.uploadify.com/) is a jQuery / Flash hybrid (if you don't feel like adding in YUI just to handle uploads).
[Demo](http://www.uploadify.com/demo/)
[How to implement](http://www.uploadify.com/documentation/)
|
What is the best multiple file JavaScript / Flash file uploader?
|
[
"",
"javascript",
"ajax",
"flash",
"file-upload",
"multifile-uploader",
""
] |
I just downloaded Eclipse several hours ago, and needed to add Java3D to the classpath. Installing it went without a hitch, but Eclipse can't seem to find the documentation folders so that it can give super-IDE functionality, such as autocomplete and method signatures.
While I know how I would add them individually, this lead me to the question; what is the "correct" way to install a Java library in Eclipse? Is there a special directory format I should follow? Is there a plugin that already did this for me? (The answer to that is [yes](http://java3d-eclipse.sourceforge.net/), but I don't know how to use it, or whether or not it's appropriate).
Thanks!
**Edit 1:** It seems to me that someone down-voted the question. May I ask why?
**Edit 2:** So after monkeying around with the JARs, it seems that manually setting the doc path for each JAR in the library seems to be the least-error prone way.
|
when you add a .JAR(library) to your project in the LIBRARIES tab for your project, you have the option of attaching the javadoc directory for the jar.
So, go to the LIBRARIES tab of the "java build path" for your projects. select your jar. expand the (+) sign and you will see that you can set the javadoc. path.
good luck,
|
I think I've got it (had the same issue as you). Better late than never.
Go here - <http://java3d.java.net/binary-builds.html> and download the documentation zip (j3d-1\_5\_2-api-docs.zip).
Extract the directory anywhere on your HD (Right in the Java3d folder is fine).
Link the Jar's JavaDoc listing to that Folder (java build path >> Libraries >> expand the Jar Listing >> JavaDoc Location >> browse to the folder location, then validate). Do it for each j3d Jar.
That should integrate the J3D Javadoc.
|
Install [java library] in Eclipse
|
[
"",
"java",
"eclipse",
"configuration",
""
] |
I have db table with parent child relationship as:
```
NodeId NodeName ParentId
------------------------------
1 Node1 0
2 Node2 0
3 Node3 1
4 Node4 1
5 Node5 3
6 Node6 5
7 Node7 2
```
Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.
e.g. for nodeId = 1, it should return 3, 4, 5, 6.
I am using MS SQL Server 2005
|
```
with [CTE] as (
select * from [TheTable] c where c.[ParentId] = 1
union all
select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]
)
select * from [CTE]
```
|
You should look into using the Nested Set Model for parent-child relationships within an SQL database. It's much nicer than trying to store the parentID of records in the table like this, and makes queries like this much easier.
|
SQL Query for Parent Child Relationship
|
[
"",
"sql",
"sql-server-2005",
"hierarchical-data",
""
] |
I am wondering how to use NUnit correctly. First, I created a separate test project that uses my main project as reference. But in that case, I am not able to test private methods. My guess was that I need to include my test code into my main code?! - That doesn't seem to be the correct way to do it. (I dislike the idea of shipping code with tests in it.)
How do you test private methods with NUnit?
|
Generally, unit testing addresses a class's public interface, on the theory that the implementation is immaterial, so long as the results are correct from the client's point of view.
So, NUnit does not provide any mechanism for testing non-public members.
|
While I agree that the focus of unit testing should be the public interface, you get a far more granular impression of your code if you test private methods as well. The MS testing framework allows for this through the use of PrivateObject and PrivateType, NUnit does not. What I do instead is:
```
private MethodInfo GetMethod(string methodName)
{
if (string.IsNullOrWhiteSpace(methodName))
Assert.Fail("methodName cannot be null or whitespace");
var method = this.objectUnderTest.GetType()
.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
Assert.Fail(string.Format("{0} method not found", methodName));
return method;
}
```
This way means you don't have to compromise encapsulation in favour of testability. Bear in mind you'll need to modify your BindingFlags if you want to test private static methods. The above example is just for instance methods.
|
How do you test private methods with NUnit?
|
[
"",
"c#",
"unit-testing",
"testing",
"nunit",
""
] |
So let's say I have two different functions. One is a part of the BST class, one is just a helper function that will call on that Class function. I will list them out here.
```
sieve(BST<T>* t, int n);
```
this function is called like this: sieve(t,n) the object is called BST t;
I'm going to be using the class remove function within the sieve function to remove specific objects. I'm not sure what my prototype for this basic function should look like? Doing this:
```
sieve(BST<int> t, int n)
```
What happens here is everything compiles just fine, but when t.remove function is called I see no actual results. I'm assuming because it's just creating a copy or a whole other t object instead of passing the one from my main() function.
If I call the remove function (t.remove(value)) in my main function where the original object was created it removes everything properly. Once I start doing it through my sieve function I see no change when I re print it out from my main function. So my main function looks something like this:
```
int main ()
{
int n,
i,
len;
BST<int> t;
cin >> n;
vector<int> v(n);
srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
for (i = 0; i < n; i++)
t.insert(v[i]);
print_stat(t);
t.inOrder(print_data);
sieve(v,t,n);
print_stat(t);
t.inOrder(print_data);
return 0;
}
```
So my results end up being the same, even though my debug statements within the functions show it's actually deleting something. I'm guessing where I'm going wrong is how I am passing the t object onto the function.
|
```
sieve(BST<int>& t, int n)
```
The `&` specifies passing by *reference* rather than value. :-)
|
If I understand correctly your issue, you should use
```
BST t;
sieve(BST<T> *t, int n);
```
and invoke it as:
```
sieve(&t,n)
```
passing the pointer to the `t` object
OR
```
BST t;
sieve(BST<T> &t, int n);
```
and invoke it as:
```
sieve(t,n)
```
passing the reference to the `t` object
|
Passing a Class Object to a function (probably by pointer not reference) C++
|
[
"",
"c++",
"reference",
"arguments",
""
] |
As can be seen in the Mozilla changlog for JavaScript 1.7 they have added destructuring assignment. Sadly I'm not very fond of the syntax (why write a and b twice?):
```
var a, b;
[a, b] = f();
```
Something like this would have been a lot better:
```
var [a, b] = f();
```
That would still be backwards compatible. Python-like destructuring would not be backwards compatible.
Anyway the best solution for JavaScript 1.5 that I have been able to come up with is:
```
function assign(array, map) {
var o = Object();
var i = 0;
$.each(map, function(e, _) {
o[e] = array[i++];
});
return o;
}
```
Which works like:
```
var array = [1,2];
var _ = assign[array, { var1: null, var2: null });
_.var1; // prints 1
_.var2; // prints 2
```
But this really sucks because \_ has no meaning. It's just an empty shell to store the names. But sadly it's needed because JavaScript doesn't have pointers. On the plus side you can assign default values in the case the values are not matched. Also note that this solution doesn't try to slice the array. So you can't do something like `{first: 0, rest: 0}`. But that could easily be done, if one wanted that behavior.
What is a better solution?
|
First off, `var [a, b] = f()` works just fine in JavaScript 1.7 - try it!
Second, you can smooth out the usage syntax *slightly* using `with()`:
```
var array = [1,2];
with (assign(array, { var1: null, var2: null }))
{
var1; // == 1
var2; // == 2
}
```
Of course, this won't allow you to modify the values of existing variables, so IMHO it's a whole lot less useful than the JavaScript 1.7 feature. In code I'm writing *now*, I just return objects directly and reference their members - I'll wait for the 1.7 features to become more widely available.
|
You don't need the dummy "\_" variable. You can directly create "global" variables by using the window object scope:
```
window["foo"] = "bar";
alert(foo); // Gives "bar"
```
Here are few more points:
* I wouldn't name this function
"assign" because that's too generic
a term.
* To more closely resemble JS
1.7 syntax, I'd make the function take the destination as the first
argument and the source as the
second argument.
* Using an object literal to pass the destination variables is cool but can be confused with JS 1.7 destructuring where the destination is actually an object and not an array. I prefer just using a comma delimited list of variable names as a string.
Here's what I came up with:
```
function destructure(dest, src) {
dest = dest.split(",");
for (var i = 0; i < src.length; i++) {
window[dest[i]] = src[i];
}
}
var arr = [42, 66];
destructure("var1,var2", arr);
alert(var1); // Gives 42
alert(var2); // Gives 66
```
|
Destructuring assignment in JavaScript
|
[
"",
"javascript",
"variable-assignment",
"destructuring",
""
] |
I have some System.Diagnotics.Processes to run. I'd like to call the close method on them automatically. Apparently the "using" keyword does this for me.
Is this the way to use the using keyword?
```
foreach(string command in S) // command is something like "c:\a.exe"
{
try
{
using(p = Process.Start(command))
{
// I literally put nothing in here.
}
}
catch (Exception e)
{
// notify of process failure
}
}
```
I'd like to start multiple processes to run concurrently.
|
```
using(p = Process.Start(command))
```
This will compile, as the `Process` class implements `IDisposable`, however you actually want to call the `Close` method.
Logic would have it that the `Dispose` method would call `Close` for you, and by digging into the CLR using reflector, we can see that it does in fact do this for us. So far so good.
Again using reflector, I looked at what the `Close` method does - it releases the underlying native win32 process handle, and clears some member variables. This (releasing external resources) is *exactly* what the IDisposable pattern is supposed to do.
**However** I'm not sure if this is what you want to achieve here.
Releasing the underlying handles simply says to windows 'I am no longer interested in tracking this other process'. At no point does it actually cause the other process to quit, or cause your process to wait.
If you want to force them quit, you'll need to use the `p.Kill()` method on the processes - however be advised it is never a good idea to kill processes as they can't clean up after themselves, and may leave behind corrupt files, and so on.
If you want to wait for them to quit on their own, you could use `p.WaitForExit()` - however this will only work if you're waiting for one process at a time. If you want to wait for them all concurrently, it gets tricky.
Normally you'd use `WaitHandle.WaitAll` for this, but as there's no way to get a `WaitHandle` object out of a `System.Diagnostics.Process`, you can't do this (seriously, wtf were microsoft thinking?).
You could spin up a thread for each process, and call `WaitForExit in those threads, but this is also the wrong way to do it.
You instead have to use p/invoke to access the native win32 `WaitForMultipleObjects` function.
Here's a sample (which I've tested, and actually works)
```
[System.Runtime.InteropServices.DllImport( "kernel32.dll" )]
static extern uint WaitForMultipleObjects( uint nCount, IntPtr[] lpHandles, bool bWaitAll, uint dwMilliseconds );
static void Main( string[] args )
{
var procs = new Process[] {
Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 2'" ),
Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 3'" ),
Process.Start( @"C:\Program Files\ruby\bin\ruby.exe", "-e 'sleep 4'" ) };
// all started asynchronously in the background
var handles = procs.Select( p => p.Handle ).ToArray();
WaitForMultipleObjects( (uint)handles.Length, handles, true, uint.MaxValue ); // uint.maxvalue waits forever
}
```
|
For reference:
The *using* keyword for *IDisposable* objects:
```
using(Writer writer = new Writer())
{
writer.Write("Hello");
}
```
is just compiler syntax. What it compiles down to is:
```
Writer writer = null;
try
{
writer = new Writer();
writer.Write("Hello");
}
finally
{
if( writer != null)
{
((IDisposable)writer).Dispose();
}
}
```
`using` is a bit better since the compiler prevents you from reassigning the writer reference inside the using block.
The framework guidelines Section 9.3.1 p. 256 state:
> **CONSIDER** providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.
---
In your code example, the outer try-catch is unnecessary (see above).
Using probably isn't doing what you want to here since Dispose() gets called as soon as `p` goes out of scope. This doesn't shut down the process (tested).
Processes are independent, so unless you call `p.WaitForExit()` they spin off and do their own thing completely independent of your program.
Counter-intuitively, for a Process, Close() only releases resources but leaves the program running. CloseMainWindow() can work for some processes, and Kill() will work to kill any process. Both CloseMainWindow() and Kill() can throw exceptions, so be careful if you're using them in a finally block.
To finish, here's some code that waits for processes to finish but doesn't kill off the processes when an exception occurs. I'm not saying it's better than Orion Edwards, just different.
```
List<System.Diagnostics.Process> processList = new List<System.Diagnostics.Process>();
try
{
foreach (string command in Commands)
{
processList.Add(System.Diagnostics.Process.Start(command));
}
// loop until all spawned processes Exit normally.
while (processList.Any())
{
System.Threading.Thread.Sleep(1000); // wait and see.
List<System.Diagnostics.Process> finished = (from o in processList
where o.HasExited
select o).ToList();
processList = processList.Except(finished).ToList();
foreach (var p in finished)
{
// could inspect exit code and exit time.
// note many properties are unavailable after process exits
p.Close();
}
}
}
catch (Exception ex)
{
// log the exception
throw;
}
finally
{
foreach (var p in processList)
{
if (p != null)
{
//if (!p.HasExited)
// processes will still be running
// but CloseMainWindow() or Kill() can throw exceptions
p.Dispose();
}
}
}
```
I didn't bother Kill()'ing off the processes because the code starts get even uglier. Read the [msdn](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) documentation for more information.
|
How do I programmatically use the "using" keyword in C#?
|
[
"",
"c#",
"process",
""
] |
While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:
```
static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };
```
Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?
**Edit:** (re: Panos) In a file lexical order seems to be king? what about across files?
In looking I tried a cyclical dependency like this:
```
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };
```
and the program didn't run the same (the test suit failed across the board and I didn't look further).
|
It seems to depend on the sequence of lines. This code works:
```
static private List<int> a = new List<int>() { 1 };
static private List<int> b = new List<int>() { a[0] };
```
while this code does not work (it throws a `NullReferenceException`)
```
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { 1 };
```
So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...
---
EDIT - What's happening "across files"? If we declare these two classes:
```
public class A {
public static List<int> a = new List<int>() { B.b[0] };
}
public class B {
public static List<int> b = new List<int>() { A.a[0] };
}
```
and try to access them with this code:
```
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }
try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
```
we are getting this output:
```
The type initializer for 'A' threw an exception.
Object reference not set to an instance of an object.
The type initializer for 'A' threw an exception.
```
So the initialization of `B` causes an exception in static constructor `A` and lefts field `a` with the default value (null). Since `a` is `null`, `b` can not also be initialized properly.
If we do not have cyclical dependencies, everything works fine.
---
EDIT: Just in case you didn't read the comments, [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) provides a very interesting reading: [The differences between static constructors and type initializers](http://csharpindepth.com/Articles/General/Beforefieldinit.aspx).
|
See [section 10.4 of the C# spec](http://msdn.microsoft.com/en-us/library/aa645757(VS.71).aspx) for the rules here:
> when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.
So in other words, in your example 'b' is initialized to its default state (null) and so the reference to it in the initializer of 'a' is legal but would result in a NullReferenceException.
These rules are different to Java's (see [section 8.3.2.3 of the JLS](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#287406) for Java's rules about forward references, which are more restrictive).
|
Order of static constructors/initializers in C#
|
[
"",
"c#",
"static",
"dependencies",
"internals",
""
] |
I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions?
|
I don't use *pydev*, but to drop to python's interactive REPL from code:
```
import code
code.interact(local=locals())
```
To drop to python's debugger from code:
```
import pdb
pdb.set_trace()
```
Finally, to run a interactive REPL after running some code, you can use python's `-i` switch:
```
python -i script.py
```
That will give you a python prompt after the code, even if it throws an exception.
You may be able to hook some of those solutions into *pydev*, I think.
|
There is a dedicated Pydev Console available by clicking on the "New console" dropdown in the console view.
See <http://pydev.sourceforge.net/console.html>
|
Is there any way to get a REPL in pydev?
|
[
"",
"python",
"ide",
"pydev",
"read-eval-print-loop",
""
] |
I am desiging a new website for my company and I am trying to implement switch navigation which is what I have used on all my sites in the past.
```
<?php
switch($x) {
default:
include("inc/main.php");
break;
case "products":
include("inc/products.php");
break;
}
?>
```
For some reason when I go to index.php?x=products nothing happens, it still displays inc/main.php, in other words it hasn't detected the X variable from the URL. Is this something to do with global variables?
|
Yes, your PHP configuration has **correctly** got `register_globals` turned off, because that's incredibly insecure.
Just put:
```
$x = $_REQUEST['x']
```
at the top of your script.
You can also use `$_GET` if you specifically only want this to work for the `GET` HTTP method. I've seen some people claim that `$_REQUEST` is somehow insecure, but no evidence to back that up.
|
It seems like your previous webhosts all used [register\_globals](http://php.net/register_globals) and your code relies on that. This is a **dangerous** setting and was rightfully removed in PHP 6.0! Use `switch($_GET['x']) {` instead.
|
PHP Automatically "GET" Variables
|
[
"",
"php",
"get",
"global-variables",
""
] |
(Note: This is for MySQL's SQL, not SQL Server.)
I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.
|
Using REGEXP opearator:
```
SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'
```
It returns records where column body contains words starting with a,c,g or i (case insensitive)
Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)
|
You can use a `LIKE` operation. If your words are space-separated, append a space to the start of the string to give the first word a chance to match:
```
SELECT
StringCol
FROM
MyTable
WHERE
' ' + StringCol LIKE '% ' + MyLetterParam + '%'
```
Where `MyLetterParam` could be something like this:
```
'[acgj]'
```
To look for more than a space as a word separator, you can expand that technique. The following would treat TAB, CR, LF, space and NBSP as word separators.
```
WHERE
' ' + StringCol LIKE '%['+' '+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160)+'][acgj]%'
```
This approach has the nice touch of being standard SQL. It would work unchanged across the major SQL dialects.
|
SQL (MySQL): Match first letter of any word in a string?
|
[
"",
"sql",
"mysql",
""
] |
what's the quickest way to extract a 5 digit number from a string in c#.
I've got
```
string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]"));
```
Any others?
|
The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings:
```
static string Search(string expression)
{
int run = 0;
for (int i = 0; i < expression.Length; i++)
{
char c = expression[i];
if (Char.IsDigit(c))
run++;
else if (run == 5)
return expression.Substring(i - run, run);
else
run = 0;
}
return null;
}
const string pattern = @"\d{5}";
static string NotCached(string expression)
{
return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;
}
static Regex regex = new Regex(pattern, RegexOptions.Compiled);
static string Cached(string expression)
{
return regex.Match(expression).Value;
}
```
Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster):
Simple search: 0.648396us
Cached Regex: 2.1414645us
Non-cached Regex: 3.070116us
Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster):
Simple search: 423.801us
Cached Regex: 1155.3948us
Non-cached Regex: 1220.625us
A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.
|
Use a regular expression (\d{5}) to find the occurrence(s) of the 5 digit number in the string and use int.Parse or decimal.Parse on the match(s).
In the case where there is only one number in `text`.
```
int? value = null;
string pat = @"\d{5}"
Regex r = new Regex(pat);
Match m = r.Match(text);
if (m.Success)
{
value = int.Parse(m.Value);
}
```
|
what's the quickest way to extract a 5 digit number from a string in c#
|
[
"",
"c#",
"regex",
"string",
""
] |
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.)
This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
|
To encode any kind of PNG file, libpng is the way of the walk.
However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtimes and footprint.
|
Have you looked at libpng? <http://www.libpng.org/pub/png/libpng.html>
I'm not sure whether the memory footprint will be acceptable, but you should probably be aware that PNG files are a lot more involved than just an array of colors. Performance is likely to be a concern on a DS.
If you go with libpng, you'll also need zlib, and if you're using DevKitPro, you'll probably run into some missing functions (from playing with the code for 5 minutes, it looks like it relies on pow() which doesn't seem to be in libnds.) I have no idea what the official Nintendo SDK offers in the way of a standard library - you might be in better shape if that's what you're using.
|
Saving an array of colour data as a PNG file on DS
|
[
"",
"c++",
"png",
"nintendo-ds",
""
] |
Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?
|
Have you seen how many developers don't really understand ref/out?
I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least *thinking* about whether there's a way of making the method only do one thing instead. Sometimes using ref/out *is* the most appropriate approach - the various TryParse methods etc.
|
In my opinion, they are considered a code smell because in general there is a much better option: returning an object.
If you notice, in the .NET library they are only used in some special cases, namely *tryparse*-like scenarios where:
* returning a class would mean boxing a value type
* the contract of the method requires it to be fast, and so boxing/unboxing is not a viable option.
|
Why does the .Net framework guidelines recommend that you don't use ref/out arguments?
|
[
"",
"c#",
".net",
"parameters",
"function",
""
] |
Title says most of it.
I have inherited a Joomla site and the client wants part of the main template (a feature-type box) to be editable via the Joomla backend.
I guess really it is a content item that never gets displayed as its own page, but as a part of all pages.
Is that possible?
Thanks.
EDIT: By editable, I mean as a piece of content, not as editing the template HTML. I hardly expect non-tech users to get things right in a WYSIWYG text editor, much less change HTML code that could screw up the whole site.
|
You want the content items module.
[Content Items Module](http://extensions.joomla.org/component/option,com_mtree/task,viewlink/link_id,498/Itemid,35/)
This way a user can add content as normal using the standard content pages, but you as the developer can set the module up to show that content as a module only. You have a LOT of choices with the above module too, you can set individual, category, intro, main all that kind of thing. Dont link to the page or category and it wont be shown on the main site, just in the module :)
The joomla extension directory is full of great things.
Good luck
|
The Custom HTML Module allows you to create, edit, and display your own free-form HTML on a Joomla site using a WYSIWYG editor.
In your administration control panel you can find the "Module Manager" under "Extensions" in the drop down navigation menu. There you can create this module, choose a position in your template to display it, and then select what sections of your site the module should be displayed on.
|
How can I make part of a Joomla template editable via the CMS interface?
|
[
"",
"php",
"content-management-system",
"joomla",
""
] |
I'm writing a data structure in C# (a priority queue using a [fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap)) and I'm trying to use it as a learning experience for TDD which I'm quite new to.
I understand that each test should only test one piece of the class so that a failure in one unit doesn't confuse me with multiple test failures, but I'm not sure how to do this when the state of the data structure is important for a test.
For example,
```
private PriorityQueue<int> queue;
[SetUp]
public void Initialize()
{
this.queue = new PriorityQueue<int>();
}
[Test]
public void PeekShouldReturnMinimumItem()
{
this.queue.Enqueue(2);
this.queue.Enqueue(1);
Assert.That(this.queue.Peek(), Is.EqualTo(1));
}
```
This test would break if either `Enqueue` or `Peek` broke.
I was thinking that I could somehow have the test manually set up the underlying data structure's heap, but I'm not sure how to do that without exposing the implementation to the world.
Is there a better way to do this? Is relying on other parts ok?
I have a `SetUp` in place, just left it out for simplicity.
|
Add a private accessor for the class to your test project. Use the accessor to set up the private properties of the class in some known way instead of using the classes methods to do so.
You also need to use `SetUp` and `TearDown` methods on your test class to perform any initializations needed between tests. I would actually prefer recreating the queue in each test rather than reusing it between tests to reduce coupling between test cases.
|
Theoretically, you only want to test a single feature at a time. However, if your queue only has a couple methods (`Enqueue`, `Peek`, `Dequeue`, `Count`) then you're quite limited in the kinds of tests you can do while using one method only.
It's best you don't over-engineer the problem and simply create a few simple test cases (such as the one above) and build on top of that to ensure an appropriate coverage of various features.
I feel it is appropriate to write tests that cover multiple features, as long as you have something underneath that will also break if one of the used features is broken. Therefore, if you have a test suite and you break your `Enqueue`, obviously, all of your tests (or most of them will fail), but you'll know `Enqueue` broke because of your simplest tests. The relationship of a test to its test suite should not be neglected.
|
How do I set up the internal state of a data structure during unit testing?
|
[
"",
"c#",
"tdd",
""
] |
When we perform a fork in Unix, open file handles are inherited, and if we don't need to use them we should close them. However, when we use libraries, file handles may be opened for which we do not have access to the handle. How do we check for these open file handles?
|
If the libraries are opening files you don't know about, how do you know they don't need them after a fork? Unexported handles are an internal library detail, if the library wants them closed it will register an atfork() handler to close them. Walking around behind some piece of code closing its file handles behind its back will lead to subtle hard to debug problems since the library will error unexpectedly when it attempts to work with a handle it knows it opened correctly, but did not close.
|
In Linux you can check `/proc/<pid>/fd` directory - for every open fd there will be a file, named as handle. I'm almost sure this way is non-portable.
Alternatively you can use `lsof` - available for Linux, AIX, FreeBSD and NetBSD, according to `man lsof`.
|
How do I find the file handles that my process has opened in Linux?
|
[
"",
"c++",
"c",
"linux",
"file-io",
""
] |
I have a page which dynamically loads a section of content via AJAX. I'm concerned that this means the content will not be found by search engines.
To show you what I mean, the site is at <http://www.gold09.net> and the dynamic content is at [/speakers.php](http://www.gold09.net/speakers.php) - Normally no one would visit that second link, it's just loaded into the first page.
I know I can tell the crawlers to read the `speakers.php` by using a `sitemap.xml`, but then I'll get links to the speakers.php showing up in search results.
I guess the ultimate solution would be so that if someone requests `/speakers.php` it redirects them to the main page, whereas it lets crawlers read the data.
Any suggestions?
|
**Update: What I've done is this:**
Created another page called [`viewSpeakers.php`](http://www.gold09.net/viewSpeakers.php) which just includes the `speakers.php` file with the standard header and footer around it. This means that if someone goes to that site, then they'll see a vaguely attractive page. The only links to that page are in the HTML of the `index.php` page (where it immediately get removed via javascript) and in my sitemap.xml.
The effect of this is that the search engine crawlers and users who have javascript disabled get to see a link to information about the speakers. People who have javascript enabled get the AJAXy goodness of the data being loaded dynamically on the same index page and they never have to know about the `viewSpeakers.php` page.
The only downside I can forsee is that someone might come to the `viewSpeakers.php` page via a search listing, and then not be able to find a link back to that page from the `index.php`. Not really too much of a problem...
*This was added as an answer, rather than editing the question, because it's one way to solve this problem. I'd still be interested to know if there's a better way than this.*
|
Make the links that point to the pages you want indexed to have a real HREF to the content - but use javascript to intercept the event and "return false;" at the end.
|
How to make search engines find my AJAX content
|
[
"",
"php",
"ajax",
"seo",
""
] |
I'm having problems structuring classes in the Model part of an MVC pattern in my Python app. No matter how I turn things, I keep running into circular imports. Here's what I have:
**Model/\_\_init\_\_p.y**
* should hold all Model class names so
I can do a "from Model import User"
e.g. from a Controller or a unit
test case
**Model/Database.py**
* holds Database class
* needs to import all Model classes to do ORM
* initialization should be performed on first module import, i.e. no extra init calls or instantiations (all methods on Database class are @classmethods)
**Model/User.py**
* contains User model class
* needs access to Database class to do queries
* should inherit from base class common to all Model classes to share functionality (database persistency methods, parameter validation code etc.)
I have yet to see a real world Python app employing MVC, so my approach is probably un-Pythonic (and possibly a language-agnostic mess on top of that...) - any suggestions on how to solve this?
Thanks, Simon
|
There is an inconsistency in your specification. You say Database.py needs to import all Model classes to do ORM but then you say the User class need access to the Database to do queries.
Think of these as layers of an API. The Database class provides an API (maybe object-oriented) to some physical persistence layer (such as DB-API 2.0). The Model classes, like User, use the Database layer to load and save their state. There is no reason for the Database.py class to import all the Model classes, and in fact you wouldn't want that because you'd have to modify Database.py each time you created a new Model class - which is a code smell.
|
Generally, we put it all in one file. This isn't Java or C++.
Start with a single file until you get some more experience with Python. Unless your files are gargantuan, it will work fine.
For example, Django encourages this style, so copy their formula for success. One module for the model. A module for each application; each application imports a common model.
Your Database and superclass stuff can be in your `__init__.py` file, since it applies to the entire package. That may reduce some of the circularity.
|
MVC model structure in Python
|
[
"",
"python",
"model-view-controller",
"model",
"structure",
""
] |
After looking on MSDN, it's still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class)
For example:
```
public class Car
{
public string Make;
public string Model;
public int Year;
}
{ // somewhere in my code
List<Car> carList = new List<Car>();
// ... code to add Cars ...
Car myCar = new Car();
// Find the first of each car made between 1980 and 2000
for (int x = 1980; x < 2000; x++)
{
myCar = carList.Find(byYear(x));
Console.Writeline(myCar.Make + myCar.Model);
}
}
```
What should my "byYear" predicate look like?
(The MSDN example only talks about a List of dinosaurs and only searches for an unchanging value "saurus" -- It doesn't show how to pass a value into the predicate...)
EDIT: I'm using VS2005/.NET2.0, so I don't think Lambda notation is available to me...
EDIT2: Removed "1999" in the example because I may want to "Find" programatically based on different values. Example changed to range of cars from 1980 to 2000 using for-do loop.
|
Ok, in .NET 2.0 you can use delegates, like so:
```
static Predicate<Car> ByYear(int year)
{
return delegate(Car car)
{
return car.Year == year;
};
}
static void Main(string[] args)
{
// yeah, this bit is C# 3.0, but ignore it - it's just setting up the list.
List<Car> list = new List<Car>
{
new Car { Year = 1940 },
new Car { Year = 1965 },
new Car { Year = 1973 },
new Car { Year = 1999 }
};
var car99 = list.Find(ByYear(1999));
var car65 = list.Find(ByYear(1965));
Console.WriteLine(car99.Year);
Console.WriteLine(car65.Year);
}
```
|
You can use a lambda expression as follows:
```
myCar = carList.Find(car => car.Year == 1999);
```
|
How do I form a good predicate delegate to Find() something in my List<T>?
|
[
"",
"c#",
"list",
"delegates",
"find",
"predicate",
""
] |
I have written a Windows service that allows me to remotely run and stop applications. These applications are run using CreateProcess, and this works for me because most of them only perform backend processing. Recently, I need to run applications that present GUI to the current log in user. How do I code in C++ to allow my service to locate the currently active desktop and run the GUI on it?
|
Roger Lipscombe's answer, to use [WTSEnumerateSessions](http://msdn.microsoft.com/en-us/library/aa383833.aspx) to find the right desktop, then [CreateProcessAsUser](http://msdn.microsoft.com/en-us/library/ms682429.aspx) to start the application on that desktop (you pass it the handle of the desktop as part of the [STARTUPINFO](http://msdn.microsoft.com/en-us/library/ms686331.aspx) structure) is correct.
However, I would *strongly* recommend against doing this. In some environments, such as Terminal Server hosts with many active users, determining which desktop is the 'active' one isn't easy, and may not even be possible.
But most importantly, if an application will suddenly appear on a user's desktop, this may very well occur at a bad time (either because the user simply isn't expecting it, or because you're trying to launch the app when the session isn't quite initialized yet, in the process of shutting down, or whatever).
A more conventional approach would be to put a shortcut to a small client app for your service in the global startup group. This app will then launch along with every user session, and can be used start other apps (if so desired) without any juggling of user credentials, sessions and/or desktops.
Also, this shortcut can be moved/disabled by administrators as desired, which will make deployment of your application much easier, since it doesn't deviate from the standards used by other Windows apps...
|
The short answer is "You don't", as opening a GUI program running under another user context is a security vulnerability commonly known as a [Shatter Attack](http://en.wikipedia.org/wiki/Shatter_attack).
Take a look at this MSDN article: [Interactive Services](http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx). It gives some options for a service to interact with a user.
In short you have these options:
* Display a dialog box in the user's session using the WTSSendMessage function.
* Create a separate hidden GUI application and use the CreateProcessAsUser function to run the application within the context of the interactive user. Design the GUI application to communicate with the service through some method of interprocess communication (IPC), for example, named pipes. The service communicates with the GUI application to tell it when to display the GUI. The application communicates the results of the user interaction back to the service so that the service can take the appropriate action. Note that IPC can expose your service interfaces over the network unless you use an appropriate access control list (ACL).
If this service runs on a multiuser system, add the application to the following key so that it is run in each session: HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. If the application uses named pipes for IPC, the server can distinguish between multiple user processes by giving each pipe a unique name based on the session ID.
|
How can a Windows service execute a GUI application?
|
[
"",
"c++",
"winapi",
"windows-services",
""
] |
I was reading an article on MSDN Magazine about using the [Enumerable class in LINQ](http://msdn.microsoft.com/en-us/magazine/cc700332.aspx) to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:
```
Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
```
|
The [Developer Fusion VB.Net to C# converter](http://www.developerfusion.com/tools/convert/vb-to-csharp/) says that the equivalent C# code is:
```
System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
```
For future reference, they also have a [C# to VB.Net converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/). There are [several other tools](http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx) available for this as well.
|
I initially thought this would be a bad idea since the sort algorithm will need to do multiple comparisons for the numbers, and it will get a different sorting key for the same number each time it calls the lambda for that number. However, it looks like it only calls it once for each element in the list, and stores that value for later use. This code demonstrates this:
```
int timesCalled = 0;
Random rnd = new Random();
List<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>
{
timesCalled++;
return rnd.Next();
}
).ToList();
Assert.AreEqual(timesCalled, 100);
```
|
Random array using LINQ and C#
|
[
"",
"c#",
"vb.net",
"linq",
"enumerable",
""
] |
I'm looking for the .NET-preferred way of performing the same type of thing that ShellExecute does in Win32 (opening, printing, etc. for arbitrary file types).
I've been programming Windows for over 20 years, but I'm a complete newbie at .NET, so maybe I'm just looking in the wrong places. I'm currently using .NET 2.0 (VS C# 2005), but could use VS 2008 if need be.
If the only answer is to use P/Invoke, then I might be better just writing my small utility using Win32 anyway.
|
[Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx).
Note that advanced uses (printing etc) require using a [ProcessStartInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo_properties.aspx) and setting the [Verb](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.verb.aspx) property.
|
```
System.Diagnostics.Process.Start(command)
```
I bet you had trouble finding it because it is in the System.Diagnostics namespace. "Diagnostics"? Usually with 20 years experience one thing you get good at is guessing at what something will be called in a new API/language, but this one tricked me.
|
ShellExecute equivalent in .NET
|
[
"",
"c#",
".net",
"winapi",
"windows-shell",
"shellexecute",
""
] |
I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?
The scenario is as follows
```
pulbic class SillyClassName {
object moo;
...
public void method1(){
synchronized(moo)
{
....
method2();
....
}
}
public void method2(){
synchronized(moo)
{
doStuff();
}
}
}
```
Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?
I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.
|
# Reentrant
Synchronized blocks use *reentrant* locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.
See the bottom of the [Java Tutorial](https://docs.oracle.com/javase/tutorial/index.html) page [Intrinsic Locks and Synchronization](https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html).
To quote as of 2015-01…
> **Reentrant Synchronization**
>
> Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables *reentrant synchronization*. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.
|
I think we have to use reentrant lock for what you are trying to do. Here's a snippet from <http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html>.
> What do we mean by a reentrant lock? Simply that there is an acquisition count associated with the lock, and if a thread that holds the lock acquires it again, the acquisition count is incremented and the lock then needs to be released twice to truly release the lock. This parallels the semantics of synchronized; if a thread enters a synchronized block protected by a monitor that the thread already owns, the thread will be allowed to proceed, and the lock will not be released when the thread exits the second (or subsequent) synchronized block, but only will be released when it exits the first synchronized block it entered protected by that monitor.
Though I have not tried it, I guess if you want to do what you have above, you have to use a re-entrant lock.
|
Synchronising twice on the same object?
|
[
"",
"java",
"multithreading",
"synchronization",
"mutex",
""
] |
I ran into a problem while cleaning up some old code. This is the function:
```
uint32_t ADT::get_connectivity_data( std::vector< std::vector<uint8_t> > &output )
{
output.resize(chunks.size());
for(chunk_vec_t::iterator it = chunks.begin(); it < chunks.end(); ++it)
{
uint32_t success = (*it)->get_connectivity_data(output[it-chunks.begin()]);
}
return TRUE;
}
```
What i am interested in doing is cleaning up the for loop to be a lambda expression but quickly got stuck on how exactly I would pass the correct argument to get\_connectivity\_data. get\_connectivity\_data takes a std::vector by reference and fills it with some data. output contains a std::vector for each "chunk".
Basically my conclusion for this was that it was substantially easier, cleaner and *shorter* to leave my code as-is.
EDIT:
So the closest answer to my question as I envisioned it would look was this:
```
std::for_each( chunks.begin(), chunks.end(),
bind( &chunk_vec_t::value::type::get_connectivity_data,
_1,
output[ std::distance( _1, chunks.begn() ]
)
);
```
Yet that code does not compile, I made some modifications to the code to get it to compile but I ran into 2 issues:
1. \_ 1 is a smart ptr, and std::distance did not work on it, I think i needed to use &chunks[0] as the start
2. Since \_ 1 is a smart pointer, I had to do: &chunk\_vec\_t::value\_ type::ValueType::get\_ connectivity\_ data which caused a crash in the VC9 compiler...
The answer regarding zip\_ iterators looked good until i read more into it and discovered that for this particular use, the amount of extra code needed was substantial (binding this and that, etc).
EDIT2:
I found an acceptable solution that is both low on extraneous syntax and clear, which I've posted here and below.
```
std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
```
|
After a bit of work I came up with this solution:
```
std::transform(chunks.begin(), chunks.end(), back_inserter(tmp), boost::bind(&ADTChunk::get_connectivity_data, _1) );
```
It required that I change get\_connectivity\_data to return std::vector instead of taking one by reference, and it also required that I change the elements of chunks to be boost::shared\_ptr instead of Loki::SmartPtr.
|
I think you were correct in thinking that the best thing to do is leave the code as-is. If you're having a hard time understanding it when (a) you're writing it and (b) you understand the exact problem you're trying to solve, imagine how difficult it will be when someone comes along in 3 years time and has to understand both the problem and the solution that you've written.
|
boost lambda or phoenix problem: using std::for_each to operate on each element of a container
|
[
"",
"c++",
"boost-lambda",
"boost-phoenix",
""
] |
I just read a post mentioning "full text search" in SQL.
I was just wondering what the difference between FTS and LIKE are. I did read a couple of articles but couldn't find anything that explained it well.
|
In general, there is a tradeoff between "precision" and "recall". High precision means that fewer irrelevant results are presented (no false positives), while high recall means that fewer relevant results are missing (no false negatives). Using the LIKE operator gives you 100% precision with no concessions for recall. A full text search facility gives you a lot of flexibility to tune down the precision for better recall.
Most full text search implementations use an "inverted index". This is an index where the keys are individual terms, and the associated values are sets of records that contain the term. Full text search is optimized to compute the intersection, union, etc. of these record sets, and usually provides a ranking algorithm to quantify how strongly a given record matches search keywords.
The SQL LIKE operator can be extremely inefficient. If you apply it to an un-indexed column, a full scan will be used to find matches (just like any query on an un-indexed field). If the column is indexed, matching can be performed against index keys, but with far less efficiency than most index lookups. In the worst case, the LIKE pattern will have leading wildcards that require every index key to be examined. In contrast, many information retrieval systems can enable support for leading wildcards by pre-compiling suffix trees in selected fields.
Other features typical of full-text search are
* lexical analysis or tokenization—breaking a
block of unstructured text into
individual words, phrases, and
special tokens
* morphological
analysis, or stemming—collapsing variations
of a given word into one index term;
for example, treating "mice" and
"mouse", or "electrification" and
"electric" as the same word
* ranking—measuring the
similarity of a matching record to
the query string
|
FTS involves indexing the individual words within a text field in order to make searching through many records quick. Using LIKE still requires you to do a string search (linear or the like) within the field.
|
What is Full Text Search vs LIKE
|
[
"",
"sql",
"full-text-search",
"sql-like",
""
] |
When I'm building a java object using JNI methods, in order to pass it in as a parameter to a java method I'm invoking using the JNI invocation API, how do I manage its memory?
Here's what I am working with:
I have a C object that has a destructor method that is more complex that `free()`. This C object is to be associated with a Java object, and once the application is finished with the Java object, I have no more need for the C object.
I am creating the Java object like so (error checking elided for clarity):
```
c_object = c_object_create ();
class = (*env)->FindClass (env, "my.class.name");
constructor = (*env)->GetMethodID (env, class, "<init>", "(J)V");
instance = (*env)->NewObject (env, class, constructor, (jlong) c_object);
method = (*env)->GetMethodID (env, other_class, "doSomeWork", "(Lmy.class.name)V");
(*env)->CallVoidMethod (env, other_class, method, instance);
```
So, now that I'm done with `instance`, what do I do with it? Ideally, I'd like to leave the garbage collection up to the VM; when it's done with `instance` it would be fantastic if it also called `c_object_destroy()` on the pointer I provided to it. Is this possible?
A separate, but related question has to do with the scope of Java entities that I create in a method like this; do I have to manually release, say, `class`, `constructor`, or `method` above? The JNI doc is frustratingly vague (in my judgement) on the subject of proper memory management.
|
There are a couple of strategies for reclaiming native resources (objects, file descriptors, etc.)
1. Invoke a JNI method during finalize() which frees the resource. Some people [recommend against implementing finalize](https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize), and basically you can't really be sure that your native resource is ever freed. For resources such as memory this is probably not a problem, but if you have a file for example which needs to be flushed at a predictable time, finalize() probably not a good idea.
2. Manually invoke a cleanup method. This is useful if you have a point in time where you know that the resource must be cleaned up. I used this method when I had a resource which had to be deallocated before unloading a DLL in the JNI code. In order to allow the DLL to later be reloaded, I had to be sure that the object was really deallocated before attempting to unload the DLL. Using only finalize(), I would not have gotten this guaranteed. This can be combined with (1) to allow the resource to be allocated either during finalize() or at the manually called cleanup method. (You probably need a canonical map of WeakReferences to track which objects needs to have their cleanup method invoked.)
3. Supposedly the **PhantomReference** can be used to solve this problem as well, but I'm not sure exactly how such a solution would work.
Actually, I have to disagree with you on the JNI documentation. I find the [JNI specification](http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/jniTOC.html) exceptionally clear on most of the important issues, even if the sections on managing local and global references could have been more elaborated.
|
The JNI spec covers the issue of who "owns" Java objects created in JNI methods [here](http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp16785). You need to distinguish between **local** and **global** references.
When the JVM makes a JNI call out to native code, it sets up a registry to keep track of all objects created during the call. Any object created during the native call (i.e. returned from a JNI interface function) are added to this registry. References to such objects are known as **local references**. When the native method returns to the JVM, all local references created during the native method call are destroyed. If you're making calls back into the JVM during a native method call, the local reference will still be alive when control returns back to the native method. If the JVM invoked from native code makes another call back into the native code, a new registry of local references is created, and the same rules apply.
(In fact, you can implement you're own JVM executable (i.e. java.exe) using the JNI interface, by creating a JVM (thereby receiving a JNIEnv \* pointer), looking up the class given on the command line, and invoking the main() method on it.)
**All references returned from JNI interface methods are local**. This means that under normal circumstances you do not need to manually deallocate references return by JNI methods, since they are destroyed when returning to the JVM. Sometimes you still want to destroy them "prematurely", for example when you lots of local references which you want to delete before returning to the JVM.
Global references are created (from local references) by using the NewGlobalRef(). They are added to a special registry and have to be deallocated manually. Global references are only used for Java object which the native code needs to hold a reference to across multiple JNI calls, for example if you have native code triggering events which should be propagated back to Java. In that case, the JNI code needs to store a reference to a Java object which is to receive the event.
Hope this clarifies the memory management issue a little bit.
|
JNI memory management using the Invocation API
|
[
"",
"java",
"c",
"memory-management",
"java-native-interface",
""
] |
That's basically the question, is there a "right" way to implement `operator<<` ?
Reading [this](http://bytes.com/forum/thread170304.html) I can see that something like:
```
friend bool operator<<(obj const& lhs, obj const& rhs);
```
is preferred to something like
```
ostream& operator<<(obj const& rhs);
```
But I can't quite see why should I use one or the other.
My personal case is:
```
friend ostream & operator<<(ostream &os, const Paragraph& p) {
return os << p.to_str();
}
```
But I could probably do:
```
ostream & operator<<(ostream &os) {
return os << paragraph;
}
```
What rationale should I base this decision on?
*Note*:
```
Paragraph::to_str = (return paragraph)
```
where paragraph's a string.
|
The problem here is in your interpretation of the article you [link](http://bytes.com/forum/thread170304.html).
### Equality
This article is about somebody that is having problems correctly defining the bool relationship operators.
The operator:
* Equality == and !=
* Relationship < > <= >=
These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).
There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.
### Streaming
The stream operators:
* operator << output
* operator >> input
When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.
It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.
```
#include <iostream>
class Paragraph
{
public:
explicit Paragraph(std::string const& init)
:m_para(init)
{}
std::string const& to_str() const
{
return m_para;
}
bool operator==(Paragraph const& rhs) const
{
return m_para == rhs.m_para;
}
bool operator!=(Paragraph const& rhs) const
{
// Define != operator in terms of the == operator
return !(this->operator==(rhs));
}
bool operator<(Paragraph const& rhs) const
{
return m_para < rhs.m_para;
}
private:
friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
std::string m_para;
};
std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
return os << p.to_str();
}
int main()
{
Paragraph p("Plop");
Paragraph q(p);
std::cout << p << std::endl << (p == q) << std::endl;
}
```
|
You can not do it as a member function, because the implicit `this` parameter is the left hand side of the `<<`-operator. (Hence, you would need to add it as a member function to the `ostream`-class. Not good :)
Could you do it as a free function without `friend`ing it? That's what I prefer, because it makes it clear that this is an integration with `ostream`, and not a core functionality of your class.
|
Should operator<< be implemented as a friend or as a member function?
|
[
"",
"c++",
"operator-overloading",
""
] |
I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.
Do you have any idea on how I can make that faster? Any other technique?
```
Dim oCGI As ProcessStartInfo = New ProcessStartInfo()
oCGI.WorkingDirectory = "C:\Program Files\Application\php"
oCGI.FileName = "php-cgi.exe"
oCGI.RedirectStandardOutput = True
oCGI.RedirectStandardInput = True
oCGI.UseShellExecute = False
oCGI.CreateNoWindow = True
Dim oProcess As Process = New Process()
oProcess.StartInfo = oCGI
oProcess.Start()
oProcess.StandardOutput.ReadToEnd()
```
|
You can use the [OutputDataReceived event](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx) to receive data as it's pumped to StdOut.
|
The best solution I have found is:
```
private void Redirect(StreamReader input, TextBox output)
{
new Thread(a =>
{
var buffer = new char[1];
while (input.Read(buffer, 0, 1) > 0)
{
output.Dispatcher.Invoke(new Action(delegate
{
output.Text += new string(buffer);
}));
};
}).Start();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "php-cgi.exe",
RedirectStandardOutput = true,
UseShellExecute = false,
WorkingDirectory = @"C:\Program Files\Application\php",
}
};
if (process.Start())
{
Redirect(process.StandardOutput, textBox1);
}
}
```
|
Redirect Standard Output Efficiently in .NET
|
[
"",
"c#",
".net",
"process",
"cgi",
""
] |
How do I discover classes at runtime in the classpath which implements a defined interface?
ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.
|
There's nothing built into Java 1.5 for this. I implemented it myself; it's not too complicated. However, when we upgrade to Java 6, I will have to replace calls to my implementation with calls to `ServiceLoader`. I could have defined a little bridge between the app and the loader, but I only use it in a few places, and the wrapper itself would be a good candidate for a ServiceLoader.
This is the core idea:
```
public <S> Iterable<S> load(Class<S> ifc) throws Exception {
ClassLoader ldr = Thread.currentThread().getContextClassLoader();
Enumeration<URL> e = ldr.getResources("META-INF/services/" + ifc.getName());
Collection<S> services = new ArrayList<S>();
while (e.hasMoreElements()) {
URL url = e.nextElement();
InputStream is = url.openStream();
try {
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while (true) {
String line = r.readLine();
if (line == null)
break;
int comment = line.indexOf('#');
if (comment >= 0)
line = line.substring(0, comment);
String name = line.trim();
if (name.length() == 0)
continue;
Class<?> clz = Class.forName(name, true, ldr);
Class<? extends S> impl = clz.asSubclass(ifc);
Constructor<? extends S> ctor = impl.getConstructor();
S svc = ctor.newInstance();
services.add(svc);
}
}
finally {
is.close();
}
}
return services;
}
```
Better exception handling is left as an exercise for the reader. Also, the method could be parameterized to accept a ClassLoader of the caller's choosing.
|
`javax.imageio.spi.ServiceRegistry` is the equivalent with prior Java versions. It's available since Java 1.4.
It does not look like a general utility class, but it is. It's even a bit more powerful than `ServiceLoader`, as it allows some control over the order of the returned providers and direct access to the registry.
See <http://docs.oracle.com/javase/7/docs/api/index.html?javax/imageio/spi/ServiceRegistry.html>
|
Is something similar to ServiceLoader in Java 1.5?
|
[
"",
"java",
"reflection",
"plugins",
"service",
""
] |
What arbitrary-precision integers (and or rationals) library are there for compilers running on Microsoft Windows, and which would you recommend?
Please state license type / cost, supported compilers (i.e. GCC and or VC++) for the library.
|
[GMP](http://gmplib.org/).
LGPL. Standard download from official website is designed for GCC. VC++ port is available from [here](http://gladman.plushost.co.uk/oldsite/computing/gmp4win.php).
|
I have not used it, so I'm pointing you here blind:
LibTomMath by Tom St Denis: <http://libtom.org/>
Public Domain license. Website mentions that the library builds out of the box with GCC 2.95 [and up] as well as Visual C++ v6.00 [with SP5] without configuration.
A companion book is available: [http://www.amazon.com/dp/1597491128](https://rads.stackoverflow.com/amzn/click/com/1597491128)
|
C or C++ BigInt library on Microsoft Windows
|
[
"",
"c++",
"c",
"windows",
"biginteger",
""
] |
I've been tasked with the awesome job of generating a look-up table for our application culture information. The columns I need to generate data for are:
* Dot Net Code
* Version
* Culture Name
* Country Name
* Language Name
* Java Country Code
* Java Language Code
* Iso Country Code
* Iso Language Code
I have found the globalization name space, but I'm sure someone out there has asked the same question, or there is a table already available.
Thanks for any help
|
Java uses the 2-letter ISO country and language codes. I recommend getting rid of the "Java Country Code" and "Java Language Code" fields in your lookup table, since they would be redundant.
I assume that wherever you get your ISO [country](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) and [language](http://www.loc.gov/standards/iso639-2/php/code_list.php) codes, you'll find their corresponding names in English. However, the Java [Locale](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html) API will give also you the localized names for the country and language, if you need them. (I.e., what is America called in Japan?)
For example, you can do this:
```
Locale l = Locale.ITALY;
System.out.println(l.getDisplayCountry() + ": " + l.getDisplayLanguage());
System.out.println(l.getDisplayCountry(l) + ": " + l.getDisplayLanguage(l));
```
Which, running in the US English locale prints:
```
Italy: Italian
Italia: italiano
```
Note that you can obtain 3-letter ISO codes from the Locale class, but when constructing them, be sure to only use 2-letter codes.
|
That's strange, the last time I visited this page, someone had beaten me to posting the links to the Java references for Localization.
However, since their post is gone, here's what I was writing before they beat me to it.
Java uses two ISO standards for localization with [java,util.Locale](http://java.sun.com/javase/6/docs/api/java/util/Locale.html).
* 2-letter [ISO-639](http://www.loc.gov/standards/iso639-2/php/English_list.php) for language.
* 2-letter [ISO-3166](http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html) for country.
|
Dot Net and Java Culture Codes
|
[
"",
"java",
".net",
"globalization",
"culture",
""
] |
I'm working the the image upload piece of the [FCKEditor](http://www.fckeditor.net/) and I've got the uploading working properly but am stuck with the server file browser.

You can see in the dialog above has a **Browse Server** button which pops up the following dialog

The problem is that I have no idea which folder the file browser is pointing at.
I've set the **UserFilePath** and **USerFilesAbsolutePath** in the PHP connector config.php to control where my image uploads go.
### How can I configure the file browser so that it starts off pointing at the same folder where my uploads are going?
---
**Edit**
The **ImageBrowserURL** property is *NOT* what I'm looking for. That property is used for having the *Browser Server* button point somewhere other than the default file browser.
My problem is figuring out how to point the default file browser to a specific directory.
|
Please read [this post of mine](http://www.fckeditor.net/forums/viewtopic.php?f=6&t=10432) on FCKeditor forums. Are you having the same problem I had?
|
Is it this?
ImageBrowserURL
(string) Sets the URL of the page called when the user clicks the "Browse Server" button in the "Image" dialog window.
In this way, you can create your custom Image Browser that is well integrated with your system.
See <http://www.clinicaestet.ro/FCKeditor/_docs/contents/012.html>
|
How to set the default location of the FCKEditor file browser?
|
[
"",
"php",
"fckeditor",
""
] |
In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor.
I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java.
A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order.
This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.
|
The Builder Design Pattern might help. Consider the following example
```
public class StudentBuilder
{
private String _name;
private int _age = 14; // this has a default
private String _motto = ""; // most students don't have one
public StudentBuilder() { }
public Student buildStudent()
{
return new Student(_name, _age, _motto);
}
public StudentBuilder name(String _name)
{
this._name = _name;
return this;
}
public StudentBuilder age(int _age)
{
this._age = _age;
return this;
}
public StudentBuilder motto(String _motto)
{
this._motto = _motto;
return this;
}
}
```
This lets us write code like
```
Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.age(16)
.motto("Aloha, Mr Hand")
.buildStudent();
```
If we leave off a required field (presumably name is required) then we can have the Student constructor throw an exception.
And it lets us have default/optional arguments without needing to keep track of any kind of argument order, since any order of those calls will work equally well.
|
Can you encapsulate related parameters inside an object?
e.g., if parameters are like
```
MyClass(String house, String street, String town, String postcode, String country, int foo, double bar) {
super(String house, String street, String town, String postcode, String country);
this.foo = foo;
this.bar = bar;
```
then you could instead have:
```
MyClass(Address homeAddress, int foo, double bar) {
super(homeAddress);
this.foo = foo;
this.bar = bar;
}
```
|
Managing constructors with many parameters in Java
|
[
"",
"java",
""
] |
After using [`array_unique`](http://us.php.net/array_unique), an array without the duplicate values is removed. However, it appears that the keys are also removed, which leaves gaps in an array with numerical indexes (although is fine for an associative array). If I iterate using a for loop, I have to account for the missing indexes and just copy the keys to a new array, but that seems clumsy.
|
`$foo = array_values($foo);` will re-number an array for you
|
Instead of using for loops it sounds like you should use foreach loops. Apparently you don't care about indexes anyway since you are renumbering them.
This loop:
```
for ($i = 0; $i < $loopSize; $i++)
{
process($myArray[$i]);
}
```
turns into
```
foreach($myArray as $key=> $value)
{
process($value);
/** or process($myArray[$key]); */
}
or even more simply
foreach($myArray as $value)
{
process($value);
}
```
|
Loop an array which has gapped numeric keys
|
[
"",
"php",
"arrays",
"loops",
"key",
""
] |
I'm writing an app in C# (.net 3.5) and I have a question about class design:
I'd like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I'd like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety.
How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.
|
Firstly, make your class implement an appropriate interface. That way, clients can test their behaviour without needing real files at all.
Testing the thread safety is hard - I've never seen anything which is really useful on that front, though that's not to say the tools aren't out there.
For unit testing your class, I'd suggest that if possible it should work with a general stream rather than just a file. Then you can embed different test files in your test assembly, and refer to them with [GetManifestResourceStream](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx). I've done this several times in the past, with great success.
|
Use [ReaderWriterLock](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx), which I think fits the problem description.
Following is a quick and dirty implementation. Acquiring locks could be smarter, like trying multiple times before bailout etc. But you get the point:
```
public class MyFooBarClass
{
private static ReaderWriterLock readerWriterLock = new ReaderWriterLock();
private static MemoryStream fileMemoryStream;
// other instance members here
public void MyFooBarClass()
{
if(fileMemoryStream != null)
{
// probably expensive file read here
}
// initialize instance members here
}
public byte[] ReadBytes()
{
try
{
try
{
readerWriterLock.AcquireReaderLock(1000);
//... read bytes here
return bytesRead;
}
finally
{
readerWriterLock.ReleaseReaderLock();
}
}
catch(System.ApplicationException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
public void WriteBytes(bytes[] bytesToWrite)
{
try
{
try
{
readerWriterLock.AcquireWriterLock(1000);
//... write bytes here
}
finally
{
readerWriterLock.ReleaseWriterLock();
}
}
catch(System.ApplicationException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
```
|
Class design: Wrapping up a datafile into a class with respect to thread-safety and testability
|
[
"",
"c#",
"class",
"thread-safety",
"design-patterns",
""
] |
I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function
```
window.clipboardData.getData("Text")
```
Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?
|
Safari supports reading the clipboard during `onpaste` events:
[Information](http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/CopyAndPaste.html#//apple_ref/doc/uid/30001234-176911)
You want to do something like:
```
someDomNode.onpaste = function(e) {
var paste = e.clipboardData && e.clipboardData.getData ?
e.clipboardData.getData('text/plain') : // Standard
window.clipboardData && window.clipboardData.getData ?
window.clipboardData.getData('Text') : // MS
false;
if(paste) {
// ...
}
};
```
|
Online Spreadsheets hook `Ctrl`+`C`, `Ctrl`+`V` events and transfer focus to a hidden TextArea control and either set it contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.
|
Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?
|
[
"",
"javascript",
"cross-browser",
"clipboard",
""
] |
I'd like to have a page in php that normally displays information based on the GET request sent to it. However, I'd like for it to also be able to process certain POST requests. So, how can I tell if any data was sent by POST so I can act on it?
|
Use `$_SERVER['REQUEST_METHOD']` to determine whether your page was accessed via a GET or POST request.
If it was accessed via post then check for any variables in `$_POST` to process.
|
If you want to pass the same variables by both POST and GET then you can always use REQUEST which contains parameters from both POST and GET. However, this is generally seen as a security vulnerability as it means that variables can be more easily spoofed.
If you want to test on whether the request was sent POST or GET then you can either:
```
if($_SERVER['REQUEST_METHOD'] === 'post')
{
// Do one thing
}
elseif($_SERVER['REQUEST_METHOD'] === 'get')
{
// Do another thing
}
```
Or:
```
if(!empty($_POST))
{
// Process POST
}
elseif(!empty($_GET))
{
// Process GET
}
```
|
How do I tell for a php page if someone came by POST or GET?
|
[
"",
"php",
"http",
""
] |
I'm currently looking into options for creating a client API for a RESTfull application. Up until now we have had WCF services to allow all application to connect to the Business Layer and we're growing dissatisfied with it.
We already have most of the infrastructure in place for the web (html and json requests) but we need to access the services from other applications (some will be linked against the main web app models library, others won't be).
I've been reading about WADL [here](http://searchsoa.techtarget.com/tip/0,289483,sid26_gci1265367,00.html) and [here](https://wadl.dev.java.net/wadl2java.html) and it seems like it would be beneficial. We could generate the wadl, the client libraries and use it to check javascript urls.
I would like to know what others have used, what worked and what didn't.
|
A good rest client API is a set of wrappers around curl, wget, or your language specific HTTP libraries. You might need some extra methods or functions to deal with the specifics of your application as well (i.e. specialized XML/JSON parsing), but that should be about it.
|
In the REST architecture:
* The resources link to their description documents, if they have one, not the other way around.
* The resources are not complex (not RPC like), thus there is usually no need for a description document.
* Loose Coupling is king; contracts are both unnecessary and harmful.
* Resources link to each others, removing most of the need for resource discovery services.
|
Creating a REST client API
|
[
"",
"c#",
"asp.net-mvc",
"rest",
"wadl",
""
] |
So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:
```
if(something == true)
DoSomething();
DoSomethingElse();
```
when quickly editing code if you don't put the braces.
What about something like this though:
```
if(something == true)
{ DoSomething(); }
```
That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?
I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:
```
public string Name
{get;set;}
```
Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.
|
When I come across a one-line if statement, I usually skip the curlys and keep everything on the same line:
```
if (something == true) DoSomething();
```
It's quick, easy, and saves space.
|
Instead of:
```
if(something == true)
{ DoSomething(); }
```
Do this:
```
if(something == true) { DoSomething(); }
```
|
Would it be bad form to put braces on the same line as the statement for single line "if" statements?
|
[
"",
"c#",
"language-agnostic",
"coding-style",
""
] |
I have a large project for which I am attempting to use TDD.
I am using [Tut](http://tut-framework.sourceforge.net/) as my test framework, which has its flaws but is sufficient for what I need.
I need to exploit link time test seams, **each test must be in its own executable**. The project for this executable then launches itself as a post build step.
Unfortunately, this means that my Visual Studio Sln is filling up with tests, which is not scalable and also hides the actual important projects.
Does anyone know of a better way of running these tests?
Is it possible to hide projects from a build and yet still have them build?
|
"Is it possible to hide projects from a build and yet still have them build?"
You can make separate solution for test cases.
Then you can set up post build step of your main projects. This post-build should build tests-projects via separate solution and run them. Building test-projects should be done via command line (see e.g. [here](http://www-unix.mcs.anl.gov/mpi/mpich1/docs/mpichntman/node10.htm) for details).
If you need to link your unit tests with some lib-s from main projects, you can use
```
#pragma comment(lib, "libname")
```
See [this MSDN page](http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx) for details.
|
You could try to group your tests into folders (are they called filters?) within your solution in Solution Explorer. This would separate tests from your other projects.
But, otherwise, could you avoid using link time test seams (Yes, I know, its probably too late to suggest this) and use polymorphism to provide your run-time variation and have less test projects?
|
Building and running C++ unit tests in Visual Studio (TDD)
|
[
"",
"c++",
"visual-studio",
"unit-testing",
"visual-studio-2005",
"tdd",
""
] |
I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.
So
```
DataTable dt = new DataTable()
dt = dataset.Table["A"]
```
Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.
Let's say I only want to get columns a3 and a4 then bind it to my datagrid.
How do I do this?
|
Ignore the fact that you have more data than you need. Set `AutoGenerateColumns` to `false`. Create `BoundColumns` for `a3` and `a4`.
|
I'd recommend reading [this](https://web.archive.org/web/20210608183626/https://aspnet.4guysfromrolla.com/articles/040502-1.aspx) article from 4GuysFromRolla for anyone who needs a good understanding of the `DataGrid` Web Control.
Note: Since this question is already answered. I want to clarify what needs to be done, just in case anyone else is wondering.
```
DataSet ds;
//Get Data
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "GetMyData";
command.CommandType = CommandType.StoredProcedure;
ds = connection.ExecuteDataSet();
}
if(ds !=null && ds.Tables.Count > 0)
{
dg.DataSource = ds.Tables[0];
// disable autogeneration of columns
dg.AutoGenerateColumns = false;
//Hide unecessary columns
dg.Columns["a3"].Visible = false;
dg.Columns["a4"].Visible = false;
}
```
|
How do I display only certain columns from a data table?
|
[
"",
"c#",
".net",
"datagrid",
"datatable",
"dataset",
""
] |
I have a form that kicks off a Response.Redirect to download a file once complete. I also want to hide the form and show a 'thank you' panel before the redirect takes place, however it seems the asp.net engine just does the redirect without doing the 2 tasks before in the following code:
```
if (success)
{
lblSuccessMessage.Text = _successMessage;
showMessage(true);
}
else
{
lblSuccessMessage.Text = _failureMessage;
showMessage(false);
}
if(success)
Response.Redirect(_downloadURL);
```
Any idea how i can force the page to update before the Redirect kicks in??
Thanks heaps
Greg
|
```
if (success)
{
lblSuccessMessage.Text = _successMessage;
showMessage(true);
}
else
{
lblSuccessMessage.Text = _failureMessage;
showMessage(false);
}
if(success) {
Threading.Thread.Sleep(200)
Response.Redirect(_downloadURL);
}
```
You can force it to wait before it redirects by making the thread sleep.
The best, and most user friendly option is to let the user continue on their own by adding a button. For instance, you could do the following:
```
if (success)
{
lblSuccessMessage.Text = _successMessage + "<br /><INPUT TYPE='button' VALUE='Continue...' onClick='parent.location='" + _downloadURL + "'/>";
showMessage(true);
}
else
{
lblSuccessMessage.Text = _failureMessage;
showMessage(false);
}
```
|
You need some client side code to do the redirect.
My preference would be to embed some javascript to do the redirect.
So, hide the form, display the message, and (at the crudest level) use a literal control to add some text like this to the page.
```
<script>
location.href = "http://otherServerName/fileToDownload";
</script>
```
You may find that this redirect occurs before your page has had a change to display - in which case, try this in the body tag of your HTML (note the different types of quotes):
```
<body onload='location.href="http://otherServerName/fileToDownload";'>
```
Remember that every post back is actually serving up a new page to the client, not just changing some properties on the current page (even if ASP.NET tries hard to pretend that it's just like a windows form)
Personally I prefer to have a separate page for each stage of the process, rather than trying to do everything in one page by showing/hiding the various bits - but I could be hopelessly out of date.
EDIT: if they have disabled javascript, you could just provide a link to download the file.
|
How to Show/Hide Panels before executing Response.Redirect
|
[
"",
"c#",
"asp.net",
"redirect",
"response.redirect",
""
] |
I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically\_deleted" (a boolean field of the child table)
For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..
How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "`Children.parent_id == Parent.id and Children.logically_deleted == False`", but is it correct to write "and" in this way?)
**Edit:**
I managed to do it in this way
```
children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))
```
but is there a way to use a string as primaryjoin instead?
|
The and\_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the & operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators.
You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.
For logical deletion, it might be better to map the whole class over a select that ignores deleted values:
```
mapper(Something, select([sometable], sometable.c.deleted == False))
```
|
> but is there a way to use a string as primaryjoin instead?
You can use the following:
```
children = relationship("Children", primaryjoin="and_(Parent.id==Children.parent_id, Children.logically_deleted==False)"
```
This worked for me!
|
How to add an automatic filter to a relation with SQLAlchemy?
|
[
"",
"python",
"sqlalchemy",
""
] |
What is the correct (most efficient) way to define the `main()` function in C and C++ — `int main()` or `void main()` — and why? And how about the arguments?
If `int main()` then `return 1` or `return 0`?
|
The return value for `main` indicates how the program exited. Normal exit is represented by a 0 return value from `main`. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, `void main()` is prohibited by the C++ standard and should not be used. The valid C++ `main` signatures are:
```
int main(void)
```
and
```
int main(int argc, char **argv)
```
which is equivalent to
```
int main(int argc, char *argv[])
```
It is also worth noting that in C++, `int main()` can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether `return 0;` should be omitted or not is open to debate. The range of valid C program main signatures is much greater.
Efficiency is not an issue with the `main` function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering `main()` is allowed, but should be avoided.
|
The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).
`main()` should be declared as either:
```
int main(void)
int main(int argc, char **argv)
```
Or equivalent. For example, `int main(int argc, char *argv[])` is equivalent to the second one. In C90, the `int` return type can be omitted as it is a default, but in C99 and newer, the `int` return type may not be omitted.
If an implementation permits it, `main()` can be declared in other ways (e.g., `int main(int argc, char *argv[], char *envp[])`), but this makes the program implementation defined, and no longer strictly conforming.
The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): `0` and `EXIT_SUCCESS` for a successful termination, and `EXIT_FAILURE` for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, `main()` must have an explicit `return` statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from `main()`. If you do, and `main()` finished, there is an implicit `return 0`.
Finally, there is nothing wrong from a standards point of view with calling `main()` *recursively* from a C program.
|
What should main() return in C and C++?
|
[
"",
"c++",
"c",
"return-value",
"program-entry-point",
"return-type",
""
] |
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?
This is how far I got by now:
Script receives image via HTML Form Post and is processed by the following code
```
...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...
```
I found mimetypes.guess\_type, but it does not work for me.
|
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is:
```
Start Marker | JFIF Marker | Header Length | Identifier
0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0"
```
so a quick recogniser would be:
```
def is_jpg(filename):
data = open(filename,'rb').read(11)
if data[:4] != '\xff\xd8\xff\xe0': return False
if data[6:] != 'JFIF\0': return False
return True
```
However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with [PIL](http://www.pythonware.com/products/pil/). eg:
```
from PIL import Image
def is_jpg(filename):
try:
i=Image.open(filename)
return i.format =='JPEG'
except IOError:
return False
```
|
No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.
See <http://docs.python.org/library/imghdr.html>
```
import imghdr
image_type = imghdr.what(filename)
if not image_type:
print "error"
else:
print image_type
```
As you have an image from a stream you may use the stream option probably like this :
```
image_type = imghdr.what(filename, incomming_image)
```
---
Actualy this works for me in Pylons (even if i have not finished everything) :
in the Mako template :
```
${h.form(h.url_for(action="save_image"), multipart=True)}
Upload file: ${h.file("upload_file")} <br />
${h.submit("Submit", "Submit")}
${h.end_form()}
```
in the upload controler :
```
def save_image(self):
upload_file = request.POST["upload_file"]
image_type = imghdr.what(upload_file.filename, upload_file.value)
if not image_type:
return "error"
else:
return image_type
```
|
Python: Check if uploaded file is jpg
|
[
"",
"python",
"google-app-engine",
"image",
"image-processing",
"mime",
""
] |
I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows.
I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.
I can get the free space available by doing:
> cmd.exe /c Z:\ /-c
>
> or
>
> cmd.exe /c \\server\share /-c
and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size.
Any suggestions?
|
One way to do it would be to use fsutil on the command line. It returns something like this:
```
D:\>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number : 0xd49cf9cf9cf9ac5c
Version : 3.1
Number Sectors : 0x0000000004a813ff
Total Clusters : 0x000000000095027f
Free Clusters : 0x00000000002392f5
Total Reserved : 0x0000000000000490
Bytes Per Sector : 512
Bytes Per Cluster : 4096
Bytes Per FileRecord Segment : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length : 0x000000000e70c000
Mft Start Lcn : 0x00000000000c0000
Mft2 Start Lcn : 0x0000000000000010
Mft Zone Start : 0x0000000000624ea0
Mft Zone End : 0x0000000000643da0
```
Multipy your number of sectors times the bytes per sector to get your size.
|
You could do this pretty easily using a JNI call if you are comfortable with that...
If you want a pre-packaged library that you can use with JDK1.5, take a look at the [Apache FileSystemUtils](http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/FileSystemUtils.html)
This just wraps the system call that you describe, but at least it's a standard library that you can use until you are able to use 1.6.
|
Get Drive Size in Java 5
|
[
"",
"java",
"size",
"drive",
""
] |
I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one.
Clone would do, if the namespaces were the same. Is there a nice way to do it?
(The substructure will change later on - but will be kept identical.)
|
Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace.
Consider the following input XML:
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_old">
<child attrib="value">text</child>
</test>
```
Now you need a template that says "copy structure and name of everything you see, but declare a new namespace while you're at it":
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:old="http://tempuri.org/ns_old"
>
<xsl:output method="xml" version="1.0"
encoding="UTF-8" indent="yes" omit-xml-declaration="no"
/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="old:*">
<xsl:element name="{local-name()}" namespace="http://tempuri.org/ns_new">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
```
When you run the above XML through it, this produces:
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_new">
<child attrib="value">text</child>
</test>
```
All your `http://tempuri.org/ns_old` elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.
|
Not sure if this applies, but I've done something similar working with two xml docs in vb.net:
```
Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)
CopyElement(FromE, ToE, Nothing)
End Sub
Private Shared Sub CopyElement(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement, ByVal overAttr As Xml.XmlAttributeCollection)
Dim NewE As Xml.XmlElement
Dim e As Xml.XmlElement
NewE = ToE.OwnerDocument.CreateElement(FromE.Name)
CopyAttributes(FromE, NewE)
If Not overAttr Is Nothing Then
OverrideAttributes(overAttr, NewE)
End If
For Each e In FromE
CopyElement(e, NewE, overAttr)
Next
ToE.AppendChild(NewE)
End Sub
Private Shared Sub CopyAttributes(ByVal FromE As Xml.XmlElement, ByVal ToE As Xml.XmlElement)
Dim a As Xml.XmlAttribute
For Each a In FromE.Attributes
ToE.SetAttribute(a.Name, a.Value)
Next
End Sub
Private Shared Sub OverrideAttributes(ByVal AC As Xml.XmlAttributeCollection, ByVal E As Xml.XmlElement)
Dim a As Xml.XmlAttribute
For Each a In AC
If Not E.Attributes.ItemOf(a.Name) Is Nothing Then
E.SetAttribute(a.Name, a.Value)
End If
Next
End Sub
```
|
How to copy a structure of nodes from one xml to an other with a different namespace?
|
[
"",
"c#",
"xml",
""
] |
What steps do I need to take to get HTML documentation automatically building via the build step in Visual Studio? I have all the comments in place and the comments.xml file being generated, and Sandcastle installed. I just need to know what to add to the post-build step in order to generate the docs.
|
Some changes have been made since this question was asked. Sandcastle no longer includes `SandcastleBuilderConsole.exe`. Instead it uses plain old `MSBuild.exe`.
To integrate this with visual studio here is what I did:
Place this in your Post-build event:
```
IF "$(ConfigurationName)"=="Release" Goto Exit
"$(SystemRoot)\microsoft.net\framework64\v4.0.30319\msbuild.exe" /p:CleanIntermediates=True /p:Configuration=Release "$(SolutionDir)ProjectName\doc\DocumentationProjectName.shfbproj"
:Exit
```
This will cause visual studio to build your documentation, only when you build in "Release" mode. That way you aren't waiting forever when you build in "Debug" mode during development.
A couple notes:
* My system is 64-bit, if yours is not then replace `framework64` with `framework` in the path to `msbuild.exe`.
* The way I have it setup is to document each project in my solution individually. If you have a "Sandcastle Help File Builder" project file which includes several projects together, then you probably want to get rid of `ProjectName\` and move `doc` into the solution directory. In this case you will want to only put the Post-build event commands on the project that is built LAST in your solution. If you put it in the Post-build event for every project then you will be rebuilding your documentation for each project that is built. Needless to say, you'll be sitting there a while. Personally I prefer to document each project individually, but that's just me.
**Installing Sandcastle and "Sandcastle Help File Builder".**
If you don't know how to get Sandcastle and "Sandcastle Help File Builder" setup correctly, then follow these steps:
1. Download and install Sandcastle from <http://sandcastle.codeplex.com/> (if you have a 64 bit system, you will need to add an environment variable. The instructions are [here](http://sandcastle.codeplex.com/wikipage?title=How%20to:%20Install%20Sandcastle&referringTitle=Introduction).
2. Download and install "Sandcastle Help File Builder" from <http://shfb.codeplex.com/> (ignore warnings about MSHelp2 if you get any. You won't be needing it.)
3. Once you have those installed then use "Sandcastle Help File Builder" to create a new documentation project. When it asks you where to save the file, save it in the documentation folder you have in your solution/project.
<http://www.chevtek.com/Temp/NewProject.jpg>
4. After creating a new project you'll need to choose which kind of documentation you want to create. A compiled windows help file, a website, or both.
<http://www.chevtek.com/Temp/DocumentationType.jpg>
5. If you saved the SHFB project file in the directory where you want your documentation to be generated then you can skip this step. But if you want the generated documentation to be placed elsewhere then you need to adjust the output path.
<http://www.chevtek.com/Temp/OutputPath.jpg>
NOTE: One thing to keep in mind about the output path (which frustrated me for an hour) is that when you have website checked as the type of documentation you want, it will overwrite content in its output path. What they neglect to tell you is that SHFB purposely restricted certain folders from being included as part of the output path. Desktop is one such folder. Your output path cannot be on the desktop, not even a sub-folder of desktop. It can't by My Documents either, but it CAN be a subfolder of my documents. If you get errors when building your documentation, try changing the output path and see if that fixes it. See <http://shfb.codeplex.com/discussions/226668?ProjectName=shfb> for details on this.
6. Finally, you will need to add a reference to the project you want to document. If you are doing individual projects like I do, then for each SHFB project file you create, you will reference the corresponding .CSPROJ file. If you have one SHFB project for your entire solution, then you would find the .SLN file for your solution. (sandcastle also works if you reference the compiled DLLs, but since you're integrating it with Visual Studio I find it makes more sense to reference the project/solution files instead. This may also mean that it really doesn't matter which project you do the post-build event on since it's referencing the code instead of the DLLs, but it's better to be safe and put it on the last project that's built)
<http://www.chevtek.com/Temp/AddSource.jpg>
7. Save the project and you can close "Sandcastle Help File Builder". Now all is setup. Just be sure to put the documentation project file in the appropriate folder that the batch commands point to in the Post-build event.
I hope my short tutorial helps you out! It was very hard for me to find any decent tutorials showing me how to use sandcastle, let alone how to integrate it with visual studio. Hopefully future google searches will turn up this question.
|
I recommend you install Sandcastle Help File Builder from [Codeplex](http://www.codeplex.com/SHFB).
You can run this from the command line, e.g. from a Post-Build event. The simplest command line is:
```
<install-path>\SandcastleBuilderConsole.exe ProjectName.shfb
```
Sandcastle is very slow, so I only run it for Release Builds. To do this, create a Post-Build event with a command something like the following, which passes the configuration name to a batch file:
```
CALL "$(ProjectDir)PostBuild.cmd" $(ConfigurationName)
```
Then inside the batch file you can test if the first argument is "Release" and if so run SandcastleBuilderConsole.exe.
|
Generate html documentation automatically during a build with Sandcastle
|
[
"",
"c#",
"visual-studio-2008",
"documentation",
"sandcastle",
""
] |
I am writing controls that work nice with JavaScript, but they have to work even without it. Now testing with selenium works fine for me. But all test with disabled JavaScript (in my browser) won't run with selenium. Is there a way to do automated test for this purpose?
|
[WWW::Mechanize](http://search.cpan.org/perldoc?WWW::Mechanize) and [Test::WWW::Mechanize](http://search.cpan.org/perldoc?Test::WWW::Mechanize) are two Perl modules to do exactly that.
```
use Test::More tests => 5;
use Test::WWW::Mechanize;
my $mech = Test::WWW::Mechanize->new;
# Test you can get http://petdance.com
$mech->get_ok( "http://petdance.com" );
# Test the <BASE> tag
$mech->base_is( 'http://petdance.com/', 'Proper <BASE HREF>' );
# Test the <TITLE>
$mech->title_is( "Invoice Status", "Make sure we're on the invoice page" );
# Test the text of the page contains "Andy Lester"
$mech->content_contains( "Andy Lester", "My name somewhere" );
# Test that all links on the page succeed.
$mech->page_links_ok('Check all links');
```
|
I don't know Selenium, but with the NoScript Firefox extension, you can disable scripts on a per-domain basis. So could you use that to allow Selenium but disable your page's scripts?
|
How can I do automated tests on non JavaScript applications?
|
[
"",
"javascript",
"testing",
"selenium",
""
] |
I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:
```
options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
```
Of course I could use a dictionary, but `options.VERBOSE` is more readable and easier to type than `options['VERBOSE']`.
I *thought* that I should be able to do
```
options = object()
```
, since `object` is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using `object()` doesn't have a `__dict__` member, and so one cannot add attributes to it:
```
options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
```
What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?
|
Given your requirements, I'd say the custom class is your best bet:
```
class options(object):
VERBOSE = True
IGNORE_WARNINGS = True
if options.VERBOSE:
# ...
```
To be complete, another approach would be using a separate module, i.e. `options.py` to encapsulate your option defaults.
`options.py`:
```
VERBOSE = True
IGNORE_WARNINGS = True
```
Then, in `main.py`:
```
import options
if options.VERBOSE:
# ...
```
This has the feature of removing some clutter from your script. The default values are easy to find and change, as they are cordoned off in their own module. If later your application has grown, you can easily access the options from other modules.
This is a pattern that I frequently use, and would heartily recommend if you don't mind your application growing larger than a single module. Or, start with a custom class, and expand to a module later if your app grows to multiple modules.
|
The [collections module](http://docs.python.org/library/collections.html) has grown a *namedtuple* function in 2.6:
```
import collections
opt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')
myoptions=opt(True, False)
>>> myoptions
options(VERBOSE=True, IGNORE_WARNINGS=False)
>>> myoptions.VERBOSE
True
```
A *namedtuple* is immutable, so you can only assign field values when you create it.
In earlier *Python* versions, you can create an empty class:
```
class options(object):
pass
myoptions=options()
myoptions.VERBOSE=True
myoptions.IGNORE_WARNINGS=False
>>> myoptions.IGNORE_WARNINGS,myoptions.VERBOSE
(False, True)
```
|
What is an easy way to create a trivial one-off Python object?
|
[
"",
"python",
""
] |
Is this doable in either IE7 or Firefox?
|
You can do it in both - get the position relative to the document, then subtract the scroll position.
```
var e = document.getElementById('xxx');
var offset = {x:0,y:0};
while (e)
{
offset.x += e.offsetLeft;
offset.y += e.offsetTop;
e = e.offsetParent;
}
if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft))
{
offset.x -= document.documentElement.scrollLeft;
offset.y -= document.documentElement.scrollTop;
}
else if (document.body && (document.body.scrollTop || document.body.scrollLeft))
{
offset.x -= document.body.scrollLeft;
offset.y -= document.body.scrollTop;
}
else if (window.pageXOffset || window.pageYOffset)
{
offset.x -= window.pageXOffset;
offset.y -= window.pageYOffset;
}
alert(offset.x + '\n' + offset.y);
```
|
[Pasting from the answer I gave [here](https://stackoverflow.com/questions/1350581/how-to-get-an-elements-top-position-relative-to-the-browsers-window/18794913#18794913)]
The native `getBoundingClientRect()` method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)
From [this](https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect) MDN page:
*The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left **relative to the top-left of the viewport**.*
You use it like so:
```
var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;
```
|
Is it possible to get the position of div within the browser viewport? Not within the document. Within the window
|
[
"",
"javascript",
"html",
"css",
""
] |
I'm learning C++ and writing little programs as I go along. The following is one such program:
```
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
```
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
```
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
```
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
|
Basically your `cin` stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
```
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
```
`cin >> n` will return a reference to `cin`, which you can test for "good-ness" in a conditional. So basically the the "`while(std::cin >> n)`" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
```
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
```
|
Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear *before* the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.
|
infinite loop in c++
|
[
"",
"c++",
"stream",
"infinite-loop",
"biginteger",
"largenumber",
""
] |
What would be the best hashing algorithm if we had the following priorities (in that order):
1. Minimal hash collisions
2. Performance
It doesn't have to be secure. Basically I'm trying to create an index based on a combination of properties of some objects. **All the properties are strings**.
Any references to c# implementations would be appreciated.
|
Forget about the term "best". No matter which hash algorithm anyone might come up with, unless you have a very limited set of data that needs to be hashed, every algorithm that performs very well on average can become completely useless if only being fed with the right (or from your perspective "wrong") data.
Instead of wasting too much time thinking about how to get the hash more collision-free without using too much CPU time, I'd rather start thinking about "How to make collisions less problematic". E.g. if every hash bucket is in fact a table and all strings in this table (that had a collision) are sorted alphabetically, you can search within a bucket table using binary search (which is only O(log n)) and that means, even when every second hash bucket has 4 collisions, your code will still have decent performance (it will be a bit slower compared to a collision free table, but not that much). One big advantage here is that if your table is big enough and your hash is not too simple, two strings resulting in the same hash value will usually look completely different (hence the binary search can stop comparing strings after maybe one or two characters on average; making every compare very fast).
Actually I had a situation myself before where searching directly within a sorted table using binary search turned out to be faster than hashing! Even though my hash algorithm was simple, it took quite some time to hash the values. Performance testing showed that only if I get more than about 700-800 entries, hashing is indeed faster than binary search. However, as the table could never grow larger than 256 entries anyway and as the average table was below 10 entries, benchmarking clearly showed that on every system, every CPU, the binary search was faster. Here, the fact that usually already comparing the first byte of the data was enough to lead to the next bsearch iteration (as the data used to be very different in the first one to two byte already) turned out as a big advantage.
So to summarize: I'd take a decent hash algorithm, that doesn't cause too many collisions on average and is rather fast (I'd even accept some more collisions, if it's just very fast!) and rather optimize my code how to get the smallest performance penalty once collisions do occur (and they will! They will unless your hash space is at least equal or bigger than your data space and you can map a unique hash value to every possible set of data).
|
As [Nigel Campbell](https://stackoverflow.com/questions/251346/best-hashing-algorithm-in-terms-of-hash-collisions-and-performance#251361) indicated, there's no such thing as the 'best' hash function, as it depends on the data characteristics of what you're hashing as well as whether or not you need cryptographic quality hashes.
That said, here are some pointers:
* Since the items you're using as input to the hash are just a set of strings, you could simply combine the hashcodes for each of those individual strings. I've seen the following pseudo-code suggested to do this, but I don't know of any particular analysis of it:
```
int hashCode = 0;
foreach (string s in propertiesToHash) {
hashCode = 31*hashCode + s.GetHashCode();
}
```
According to [this article](http://www.themissingdocs.net/wordpress/?m=200607), System.Web has an internal method that combines hashcodes using
```
combinedHash = ((combinedHash << 5) + combinedHash) ^ nextObj.GetHashCode();
```
I've also seen code that simply xor's the hashcodes together, but that seems like a bad idea to me (though I again have no analysis to back this up). If nothing else, you end up with a collision if the same strings are hashed in a different order.
* I've used FNV to good effect: <http://www.isthe.com/chongo/tech/comp/fnv/>
* Paul Hsieh has a decent article: <http://www.azillionmonkeys.com/qed/hash.html>
* Another nice article by Bob Jenkins that was originally published in 1997 in Doctor Dobb's Journal (the linked article has updates): <http://burtleburtle.net/bob/hash/doobs.html>
|
Best hashing algorithm in terms of hash collisions and performance for strings
|
[
"",
"c#",
"algorithm",
"hash",
""
] |
I use LINQ to Objects instructions on an ordered array.
Which operations shouldn't I do to be sure the order of the array is not changed?
|
I examined the methods of [System.Linq.Enumerable](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx), discarding any that returned non-IEnumerable results. I checked the remarks of each to determine how the order of the result would differ from order of the source.
Preserves Order Absolutely. You can map a source element by index to a result element
* AsEnumerable
* Cast
* Concat
* Select
* ToArray
* ToList
Preserves Order. Elements are filtered or added, but not re-ordered.
* Distinct
* Except
* Intersect
* OfType
* Prepend (new in .net 4.7.1)
* Skip
* SkipWhile
* Take
* TakeWhile
* Where
* Zip (new in .net 4)
Destroys Order - we don't know what order to expect results in.
* ToDictionary
* ToLookup
Redefines Order Explicitly - use these to change the order of the result
* OrderBy
* OrderByDescending
* Reverse
* ThenBy
* ThenByDescending
Redefines Order according to some rules.
* GroupBy - The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source.
* GroupJoin - GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.
* Join - preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner.
* SelectMany - for each element of source, selector is invoked and a sequence of values is returned.
* Union - When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded.
---
Edit: I've moved Distinct to Preserving order based on this [implementation](https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Enumerable.cs).
```
private static IEnumerable<TSource> DistinctIterator<TSource>
(IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
Set<TSource> set = new Set<TSource>(comparer);
foreach (TSource element in source)
if (set.Add(element)) yield return element;
}
```
|
Are you actually talking about SQL, or about arrays? To put it another way, are you using LINQ to SQL or LINQ to Objects?
The LINQ to Objects operators don't actually change their original data source - they build sequences which are effectively backed by the data source. The only operations which change the ordering are OrderBy/OrderByDescending/ThenBy/ThenByDescending - and even then, those are stable for equally ordered elements. Of course, many operations will filter out some elements, but the elements which are returned will be in the same order.
If you convert to a different data structure, e.g. with ToLookup or ToDictionary, I don't believe order is preserved at that point - but that's somewhat different anyway. (The order of values mapping to the same key is preserved for lookups though, I believe.)
|
Preserving order with LINQ
|
[
"",
"c#",
"arrays",
"linq",
"sorting",
"data-structures",
""
] |
I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?
1)
```
void example()
{
lock (mutex)
{
//...
}
return myData;
}
```
2)
```
void example()
{
lock (mutex)
{
//...
return myData;
}
}
```
Which one should I use?
|
Essentially, which-ever makes the code simpler. Single point of exit is a nice ideal, but I wouldn't bend the code out of shape just to achieve it... And if the alternative is declaring a local variable (outside the lock), initializing it (inside the lock) and then returning it (outside the lock), then I'd say that a simple "return foo" inside the lock is a lot simpler.
To show the difference in IL, lets code:
```
static class Program
{
static void Main() { }
static readonly object sync = new object();
static int GetValue() { return 5; }
static int ReturnInside()
{
lock (sync)
{
return GetValue();
}
}
static int ReturnOutside()
{
int val;
lock (sync)
{
val = GetValue();
}
return val;
}
}
```
(note that I'd happily argue that `ReturnInside` is a simpler/cleaner bit of C#)
And look at the IL (release mode etc):
```
.method private hidebysig static int32 ReturnInside() cil managed
{
.maxstack 2
.locals init (
[0] int32 CS$1$0000,
[1] object CS$2$0001)
L_0000: ldsfld object Program::sync
L_0005: dup
L_0006: stloc.1
L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000c: call int32 Program::GetValue()
L_0011: stloc.0
L_0012: leave.s L_001b
L_0014: ldloc.1
L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
L_001a: endfinally
L_001b: ldloc.0
L_001c: ret
.try L_000c to L_0014 finally handler L_0014 to L_001b
}
method private hidebysig static int32 ReturnOutside() cil managed
{
.maxstack 2
.locals init (
[0] int32 val,
[1] object CS$2$0000)
L_0000: ldsfld object Program::sync
L_0005: dup
L_0006: stloc.1
L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000c: call int32 Program::GetValue()
L_0011: stloc.0
L_0012: leave.s L_001b
L_0014: ldloc.1
L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
L_001a: endfinally
L_001b: ldloc.0
L_001c: ret
.try L_000c to L_0014 finally handler L_0014 to L_001b
}
```
So at the IL level they are [give or take some names] identical (I learnt something ;-p).
As such, the only sensible comparison is the (highly subjective) law of local coding style... I prefer `ReturnInside` for simplicity, but I wouldn't get excited about either.
|
It doesn't make any difference; they're both translated to the same thing by the compiler.
To clarify, either is effectively translated to something with the following semantics:
```
T myData;
Monitor.Enter(mutex)
try
{
myData= // something
}
finally
{
Monitor.Exit(mutex);
}
return myData;
```
|
Should a return statement be inside or outside a lock?
|
[
"",
"c#",
".net",
"multithreading",
"mutex",
""
] |
I am using the ReportViewer control from Visual Studio 2008 in Local Mode with objects as the data source. My classes are mapped to data tables in my database. In the objects, it loads related objects as needed. So it leaves the reference null until you try to use the property, then it tries to load it from the database automatically. The classes use the System.Data.SqlClient namespace.
When I interact with the objects in my Windows Forms application, everything works as expected. But when I pass the object to be used as a Report Data Source and it tries to automatically load the related object, it fails. The code creates a SqlConnection object and when I call GetCommand() on it, the following exception is thrown:
```
[System.Security.SecurityException] {
"Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."
} System.Security.SecurityException
```
I've tried searching for the error, but all the results that show up are for CLR assemblies running on a SQL Server or ASP.Net. I've tried adding the following call in my code (as suggested in the search results) before creating the SqlConnection objects, but it didn't apparently do anything:
```
System.Data.SqlClient.SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
```
Any ideas?
|
I've found the solution. You specify System.Security.Policy.Evidence of you executing assembly (or one that has sufficient rights) to the LocalReport for use during execution.
```
reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);
```
|
In addition to the answer of CuppM.
The `ExecuteReportInCurrentAppDomain` method is deprecated since .NET4, and `LocalReport.SetBasePermissionsForSandboxAppDomain` should be used instead, as ReportViewer is now *always* executed in sandboxed domain:
```
PermissionSet permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions);
```
See details [here](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.localreport.setbasepermissionsforsandboxappdomain.aspx).
|
Report Viewer - Request for the permission of type SqlClientPermission failed
|
[
"",
"c#",
"winforms",
"visual-studio-2008",
"reporting-services",
"sqlclient",
""
] |
Could someone please explain the best way to connect to an Interbase 7.1 database using .NET/C#?
The application will be installed on many end user computers so the less "add-ons" that I will have to package with my application the better.
|
CodeGear offers a free ADO.NET 2.0 driver for registered users of InterBase here:
<http://cc.embarcadero.com/item/25497>
Note that "registered users of InterBase" includes the free InterBase 2007 Developers Edition. The download says that it's for 2007, but it works fine with InterBase 7, and the InterBase team at CodeGear has told me that they have no problem with people using it for that purpose.
I do not recommend using a driver designed for Firebird, as InterBase and Firebird have somewhat different SQL syntaxes, and differ in other features, as well. In particular, I think that using any driver dependent on fbclient.dll with InterBase is outright dangerous.
|
Check this providers:
* [Interbase and Firebird Developer's for Visual Studio .Net](http://www.ibprovider.com/eng/documentation/firebird_adonet/firebird_adonet.html)
* [Firebird .NET Data Provider](http://www.firebirdsql.org/index.php?op=files&id=netprovider)
* [FireBird - InterBase .NET (Mono) Providers](http://www.mono-project.com/Firebird_Interbase)
|
Best way to connect to Interbase 7.1 using .NET C#
|
[
"",
"c#",
".net",
"interbase",
""
] |
Ok, so I want to get a webapp running in tomcat (5.5) to run behind apache 2 (2.2.3 to be precise) serving from the root of the site (i.e. without the context), with static content being served via apache.
So if the app is running under "`/myapp`" on tomcat I want to use apache (plus `mod_rewrite`) to make it behave as if it's running under "`/`" instead.
`Mod_jk` is setup and working ok. I can access the app from "`/myapp`", but I can't quite get the last bit working. Below is the config I've got for `mod_rewrite` to try and get this working. It correctly gets rewrites `/static/` urls to get apache to serve them from the unpacked webapp and if I enable the rewrite log I see that it does attempt to pass through all other requests to `/myapp` via `mod_jk`. However it seems that mod\_jk is not processing the request afterwards.
```
JkMount /myapp/* worker1
RewriteEngine On
# ensure static stuff gets served by apache
RewriteRule ^/static/(.*)$ /var/lib/tomcat5.5/webapps/myapp/static/$1 [L]
# everything else should go through tomcat
RewriteRule ^/(.*)$ /myapp/$1 [L,PT]
```
When I've done this with apache 1 in the past I've had to make sure `mod_jk` get's loaded before `mod_rewrite`, but I can't seem to achieve this under apache 2. Any thoughts? How do other people usually do this?
|
Managed to get this working in the end. It appears that I need to set a JkOption to:
```
JkOptions +ForwardURICompat
```
And then `mod_jk` looks at the rewritten URL. Must admit not 100% sure quite why this works, but I believe it's reverting to an older form of behaviour. If anyone can tell me a better/more correct way of doing this I'd love to know.
|
May be better use Apache for proxy instead of mod\_jk.
Something like this:
ProxyPass /static/ <http://localhost:8080/myapp/static/>
|
How do I get tomcat 5.5 to run behind apache 2 with mod_rewrite passing through requests to mod_jk and stripping app context?
|
[
"",
"java",
"apache",
"tomcat",
"mod-rewrite",
"mod-jk",
""
] |
I'm after some good tips for fluent interfaces in C#. I'm just learning about it myself but keen to hear what others think outside of the articles I am reading. In particular I'm after:
1. when is fluent too much?
2. are there any fluent patterns?
3. what is in C# that makes fluent interfaces more fluent (e.g. extension methods)
4. is a complex fluent interface still a fluent one?
5. refactoring to arrive at a fluent interface or refactoring an existing fluent interface
6. any good examples out there that you have worked with or could recommend?
If you could post one tip or thought, or whatever per post. I want to see how they get voted on, too.
Thank you in advance.
|
On your 4th point;
Yes I think that a complex fluent interface can still be fluent.
I think fluent interfaces are somewhat of a compromise. (although a good one!) There has been much research into using natural language for programming and generally natural language isn't precise enough to express programs.
Fluent interfaces are constructed so that they write like a programming language, only a small subset of what you can express in a natural language is allowed, but they read like a natural language.
If you look at rhino mocks for example the writing part has been complicated compared to a normal library. I took me longer to learn mostly due to the fluent interface but it makes code a lot easier to read. Because programs are usually written once and read a lot more than once this is a good tradeoff.
So to qualify my point a bit. A fluent interface that's complex to write but easy to read can still be fluent.
|
The single biggest challenge I have experienced as a consumer of fluent interfaces is that most of them aren't really fluent intefaces -- instead they are really instances of what I tend to refer to as 'legible interfaces'.
A fluent interface implies that its primary goal is to make it easy to SPEAK it whereas a legible interface implies that its primary goal is to be easy to READ it. Most fluent interfaces only tend to be ridiculously difficult to code with but conversely incredibly easy to READ later by others.
```
Assert().That().This(actual).Is().Equal().To(expected).
Except().If(x => x.GreaterThan(10));
```
...is alot easier to read later than it is to actually compose in code!
|
Tips for writing fluent interfaces in C# 3
|
[
"",
"c#",
"design-patterns",
"fluent-interface",
""
] |
I'm using the contentEditable attribute on a DIV element in Firefox 3.03. Setting it to true allows me to edit the text content of the DIV, as expected.
Then, when I set contentEditable to "false", the div is no longer editable, also as expected.
However the flashing caret (text input cursor) remains visible even though the text is no longer editable. The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.
Has anyone seen this before? Is there any way to force the caret hidden?
(When I either resize the browser or click within another application, and come back, the caret magically disappears.)
|
I've dealt with this and my workaround is clearing the selection when I disable contentEditable:
```
if ($.browser.mozilla) { // replace with browser detection of your choice
window.getSelection().removeAllRanges();
}
```
I am actually removing the "contenteditable" attribute for browsers other than IE, rather than setting it to false:
```
if ($.browser.msie) {
element.contentEditable = false;
}
else {
$(element).removeAttr( 'contenteditable' );
}
```
The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.
|
The style attribute `-moz-user-input` can be used in Firefox to get the functionality `contenteditable=false` working.
The value assigned defines if user input is accepted. The possible values are
```
none : The element does not respond to user input.
enabled : The element can accepts user input. This is default.
disabled : The element does not accept user input.
```
E.g.:
```
// to disallow users to enter input
<asp:TextBox ID="uxFromDate" runat="server" style="-moz-user-input: disabled;"></asp:TextBox>
// to allow users to enter input
<asp:TextBox ID="uxFromDate" runat="server" style="-moz-user-input: enabled ;"></asp:TextBox>
```
Refer to <https://developer.mozilla.org/en/CSS/-moz-user-input> for further reference.
|
Firefox 3.03 and contentEditable
|
[
"",
"javascript",
"firefox",
""
] |
In Groovy, how do I grab a web page and remove HTML tags, etc., leaving only the document's text? I'd like the results dumped into a collection so I can build a word frequency counter.
Finally, let me mention again that I'd like to do this in Groovy.
|
Assuming you want to do this with Groovy (guessing based on the groovy tag), your approaches are likely to be either heavily shell-script oriented or using Java libraries. In the case of shell-scripting I would agree with moogs, using Lynx or Elinks is probably the easiest way to go about it. Otherwise have a look at [HTMLParser](http://htmlparser.sourceforge.net/) and see [Processing Every Word in a File](http://pleac.sourceforge.net/pleac_groovy/filecontents.html) (scroll down to find the relevant code snippet)
You're probably stuck with finding Java libs for use with Groovy for the HTML parsing, as it doesn't appear there are any Groovy libs for it. If you're not using Groovy, then please post the desired language, since there are a multitude of [HTML to text tools](http://www.google.com/search?q=html+to+text) out there, depending on what language you're working in.
|
If you want a collection of tokenized words from HTML then can't you just parse it like XML (needs to be valid XML) and grab all of the text between tags? How about something like this:
```
def records = new XmlSlurper().parseText(YOURHTMLSTRING)
def allNodes = records.depthFirst().collect{ it }
def list = []
allNodes.each {
it.text().tokenize().each {
list << it
}
}
```
|
Strip HTML from a web page and calculate word frequency?
|
[
"",
"java",
"html",
"groovy",
"html-content-extraction",
"text-extraction",
""
] |
Any GOOD libraries available to access SVN from .net application (using C#). The only 3 I found so far that I will be trying out is:
* [SVN#](http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html)
* [SharpSVN](http://sharpsvn.open.collab.net/)
* [NSvn](http://www.hanselman.com/blog/PowerShellAnkhSVNAndSubversion.aspx)
I want to create a very simple SVN client!
|
SharpSvn was desiged for .Net 2.0 and Subversion 1.5 and later. It integrates all subversion dependencies in a single set of dll that is directly usable from .Net (XCopy deployable). One of the other strong points of SharpSvn is that it hides all memory management and transforms Subversion errors in exceptions, and more importantly vice versa. (Makes debugging callbacks very easy)
NSvn was used by AnkhSVN before AnkhSVN 2.0. It moved to SharpSvn after that.
The IronSvn project on Codeplex closed down. (It suggests using SharpSvn).
Svn# and its 2.0 successor Svn.Net are plain wrappers of the Subversion C api. They required the binaries of a subversion release to work. And you must manage the apr pools and some of the apr collection marshalling yourself from managed code. This is the only cross platform solution in this list. (Works just as well on linux)
|
I used SharpSvn. It was easy to integrate and works well for me. If you need some sample code have a look at this project <https://github.com/bhank/SVNCompleteSync>.
|
i have to access/commit/update SVN repository in WPF application using SVN API or libraries
|
[
"",
"c#",
".net",
"svn",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.