Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?
[System.Text.RegularExpressions.Regex.Replace()](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx "MSDN") is what you seek - IF your tokens are odd enough that you need a regex to find them. [Some kind soul did some performance testing](http://blogs.msdn.com/debuggingtoolbox/archive/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance.aspx), and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.
The only situation in which I've had to do this is sending a templated e-mail. In .NET this is provided out of the box by the [MailDefinition class](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition.aspx). So this is how you create a templated message: ``` MailDefinition md = new MailDefinition(); md.BodyFileName = pathToTemplate; md.From = "test@somedomain.com"; ListDictionary replacements = new ListDictionary(); replacements.Add("<%To%>", someValue); // continue adding replacements MailMessage msg = md.CreateMailMessage("test@someotherdomain.com", replacements, this); ``` After this, msg.Body would be created by substituting the values in the template. I guess you can take a look at MailDefinition.CreateMailMessage() with Reflector :). Sorry for being a little off-topic, but if this is your scenario I think it's the easiest way.
Best way to replace tokens in a large text template
[ "", "c#", ".net", "" ]
I often run into the following problem. I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down. So, I make a push to the live system and get a big, obvious error that there is no `NewColumnX`, ugh. Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great.
In Ruby on Rails, there's a concept of a [migration](https://edgeguides.rubyonrails.org/active_record_migrations.html) -- a quick script to change the database. You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a column). Each migration is numbered, and a table keeps track of your current db version. To *migrate up*, you run a command called "db:migrate" which looks at your version and applies the needed scripts. You can migrate down in a similar way. The migration scripts themselves are kept in a version control system -- whenever you change the database you check in a new script, and any developer can apply it to bring their local db to the latest version.
I'm a bit old-school, in that I use source files for creating the database. There are actually 2 files - project-database.sql and project-updates.sql - the first for the schema and persistant data, and the second for modifications. Of course, both are under source control. When the database changes, I first update the main schema in project-database.sql, then copy the relevant info to the project-updates.sql, for instance ALTER TABLE statements. I can then apply the updates to the development database, test, iterate until done well. Then, check in files, test again, and apply to production. Also, I usually have a table in the db - Config - such as: **SQL** ``` CREATE TABLE Config ( cfg_tag VARCHAR(50), cfg_value VARCHAR(100) ); INSERT INTO Config(cfg_tag, cfg_value) VALUES ( 'db_version', '$Revision: $'), ( 'db_revision', '$Revision: $'); ``` Then, I add the following to the update section: ``` UPDATE Config SET cfg_value='$Revision: $' WHERE cfg_tag='db_revision'; ``` The `db_version` only gets changed when the database is recreated, and the `db_revision` gives me an indication how far the db is off the baseline. I could keep the updates in their own separate files, but I chose to mash them all together and use cut&paste to extract relevant sections. A bit more housekeeping is in order, i.e., remove ':' from $Revision 1.1 $ to freeze them.
Is there a version control system for database structure changes?
[ "", "sql", "database", "oracle", "version-control", "" ]
What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!
There are a couple of things to do in order to keep your session secure: 1. Use SSL when authenticating users or performing sensitive operations. 2. Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish. 3. Have sessions time out 4. Don't use register globals 5. Store authentication details on the server. That is, don't send details such as username in the cookie. 6. Check the `$_SERVER['HTTP_USER_AGENT']`. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here). 7. Lock down access to the sessions on the file system or use custom session handling 8. For sensitive operations consider requiring logged in users to provide their authenication details again
One guideline is to call [session\_regenerate\_id](http://www.php.net/session_regenerate_id) every time a session's security level changes. This helps prevent session hijacking.
PHP Session Security
[ "", "security", "php", "" ]
I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like `play()`, `stop()`, `pause()`, `record()` etc... Then I have workhorse classes that do the video decoding and video encoding. I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine. The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use and to avoid any possible naming conflicts. I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue.
I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure. My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem. I would reference something like a [QTextDocument](http://qt-project.org/doc/qt-4.8/qtextdocument.html) in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation.
You would use a nested class to create a (small) helper class that's required to implement the main class. Or for example, to define an interface (a class with abstract methods). In this case, the main disadvantage of nested classes is that this makes it harder to re-use them. Perhaps you'd like to use your VideoDecoder class in another project. If you make it a nested class of VideoPlayer, you can't do this in an elegant way. Instead, put the other classes in separate .h/.cpp files, which you can then use in your VideoPlayer class. The client of VideoPlayer now only needs to include the file that declares VideoPlayer, and still doesn't need to know about how you implemented it.
Should I use nested classes in this case?
[ "", "c++", "class", "oop", "inner-classes", "" ]
Suppose we have a table A: ``` itemid mark 1 5 2 3 ``` and table B: ``` itemid mark 1 3 3 5 ``` I want to join A\*B on A.itemid=B.itemid both right and left ways. i.e. result: ``` itemid A.mark B.mark 1 5 3 2 3 NULL 3 NULL 5 ``` Is there a way to do it in one query in MySQL?
It's called a full outer join and it's not supported natively in MySQL, judging from its [docs](http://dev.mysql.com/doc/refman/4.1/en/join.html). You can work around this limitation using UNION as described in the comments to the page I linked to. [edit] Since others posted snippets, here you go. You can see explanation on the linked page. ``` SELECT * FROM A LEFT JOIN B ON A.id = B.id UNION ALL SELECT * FROM A RIGHT JOIN B ON A.id = B.id WHERE A.id IS NULL ```
Could do with some work but here is some sql ``` select distinct T.itemid, A.mark as "A.mark", B.mark as "B.mark" from (select * from A union select * from B) T left join A on T.itemid = A.itemid left join B on T.itemid = B.itemid; ``` This relies on the left join, which returns all the rows in the original table (in this case this is the subselect table T). If there are no matches in the joined table, then it will set the column to NULL.
Bidirectional outer join
[ "", "sql", "mysql", "" ]
When using a `Zend_Form`, the only way to validate that an input is not left blank is to do ``` $element->setRequired(true); ``` If this is not set and the element is blank, it appears to me that validation is not run on the element. If I do use `setRequired()`, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the `Zend_Validate_NotEmpty` class, but this is a bit hacky. I would ideally like to be able to use my own class (derived from `Zend_Validate_NotEmpty`) to perform the not empty check.
I did it this way (ZF 1.5): ``` $name = new Zend_Form_Element_Text('name'); $name->setLabel('Full Name: ') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator($MyNotEmpty); ``` so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file): ``` $MyNotEmpty = new Zend_Validate_NotEmpty(); $MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY); ``` hope this helps...
By default, setRequired(true) tells isValid() to add a NonEmpty validation *if one doesn't already exist*. Since this validation doesn't exist until isValid() is called, you can't set the message. The easiest solution is to simply manually add a NonEmpty validation before isValid() is called and set it's message accordingly. ``` $username = new Zend_Form_Element_Text('username'); $username->setRequired(true) ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!'))); ```
Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank
[ "", "php", "zend-framework", "validation", "" ]
I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list: ``` public IList<Customer> GetCustomerByFirstName(string customerFirstName) { return _session.CreateCriteria(typeof(Customer)) .Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName)) .List<Customer>(); } ``` I am calling `Session.Flush()` at the end of the `HttpRequest`, and I get a `HibernateAdoException`. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the `flush`, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing? --- Here's the code from the exception: ``` [SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?] ``` No parameters are showing as being passed.
I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping?
Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have not changed any fields since you read the entity from the database. The following sequence explains why this happens: 1. NHibernate retrieves raw entity's data from DB using ADO.NET 2. NHibernate constructs the entity and sets its properties 3. If DB field contained NULL the property will be set to the defaul value for its type: * properties of reference types will be set to null * properties of integer and floating point types will be set to 0 * properties of boolean type will be set to false * properties of DateTime type will be set to DateTime.MinValue * etc. 4. Now, when transaction is committed, NHibernate compares the value of the property to the original field value it read form DB, and since the field contained NULL but the property contains a non-null value, **NHibernate considers the property dirty, and forces an update of the enity.** Not only this hurts performance (you get extra round-trip to DB and extra update every time you retrieve the entity) but it also may cause hard to troubleshoot errors with DateTime columns. Indeed, when DateTime property is initialized to its default value it's set to 1/1/0001. When this value is saved to DB, ADO.NET's SqlClient can't convert it to a valid SqlDateTime value since the smallest possible SqlDateTime is 1/1/1753!!! The easiest fix is to make the class property use Nullable type, in this case "DateTime?". Alternatively, you could implement a custom type mapper by implementing IUserType with its Equals method properly comparing DbNull.Value with whatever default value of your value type. In our case Equals would need to return true when comparing 1/1/0001 with DbNull.Value. Implementing a full-functional IUserType is not really that hard but it does require knowledge of NHibernate trivia so prepare to do some substantial googling if you choose to go that way.
NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred
[ "", "c#", ".net", "nhibernate", "" ]
I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python. Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.
Personally, I've played with several of the built-in options on an XML-heavy project and have settled on [pulldom](http://docs.python.org/lib/module-xml.dom.pulldom.html) as the best choice for less complex documents. Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure. [Here is a good quick discussion of how to use the API](http://www.prescod.net/python/pulldom.html). What I like: you can handle the parsing in a `for` loop rather than using callbacks. You also delay full parsing (the "pull" part) and only get additional detail when you call `expandNode()`. This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity.
[ElementTree](http://effbot.org/zone/element-index.htm) has a nice pythony API. I think it's even shipped as part of python 2.5 It's in pure python and as I say, pretty nice, but if you wind up needing more performance, then [lxml](http://codespeak.net/lxml/) exposes the same API and uses libxml2 under the hood. You can theoretically just swap it in when you discover you need it.
XML Processing in Python
[ "", "python", "xml", "" ]
I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as: ``` WHERE database.foobar = NULL ``` and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query. Can anyone help me out?
Correct syntax is WHERE database.foobar IS NULL. See <http://msdn.microsoft.com/en-us/library/ms188795.aspx> for more info
Comparison to NULL will be false every time. You want to use IS NULL instead. ``` x = NULL -- always false x <> NULL -- always false x IS NULL -- these do what you want x IS NOT NULL ```
SQLServer Get Results Where Value Is Null
[ "", "sql", "sql-server", "oracle", "" ]
What is the the best JavaScript compressor available? I'm looking for a tool that: * is easy to use * has a high compression rate * Produce reliable end results (doesn't mess up the code)
I recently released [UglifyJS](http://github.com/mishoo/UglifyJS), a JavaScript compressor which is written in JavaScript (runs on the NodeJS [Node.js](http://en.wikipedia.org/wiki/Nodejs) platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any `Node.js` internals). It's a lot faster than both [YUI Compressor](http://developer.yahoo.com/yui/compressor/) and [Google Closure](http://en.wikipedia.org/wiki/Google_Closure_Tools), it compresses better than [YUI](http://en.wikipedia.org/wiki/Yahoo!_UI_Library) on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with"). Other than whitespace removal, UglifyJS also does the following: * changes local variable names (usually to single characters) * joins consecutive var declarations * avoids inserting any unneeded brackets, parens and semicolons * optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or ?/: operators when possible, etc.). * transforms `foo["bar"]` into `foo.bar` where possible * removes quotes from keys in object literals, where possible * resolves simple expressions when this leads to smaller code (1+3\*4 ==> 13) PS: Oh, it can "beautify" as well. ;-)
Revisiting this question a few years later, [UglifyJS](http://github.com/mishoo/UglifyJS), seems to be the best option as of now. As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine. --- Old answer below--- Google released [**Closure Compiler**](https://github.com/google/closure-compiler) which seems to be generating the smallest files so far as seen [here](http://blog.feedly.com/2009/11/06/google-closure-vs-yui-min/) and [here](http://news.ycombinator.com/item?id=924426) Previous to that the various options [were as follow](http://www.julienlecomte.net/blog/2007/08/13/) Basically [Packer](http://dean.edwards.name/packer/) does a better job at initial compression , but if you are going to gzip the files before sending on the wire (which you should be doing) [YUI Compressor](http://www.julienlecomte.net/yuicompressor/) gets the smallest final size. The tests were done on jQuery code btw. * Original jQuery library 62,885 bytes , 19,758 bytes after gzip * jQuery minified with JSMin 36,391 bytes , 11,541 bytes after gzip * jQuery minified with Packer 21,557 bytes , 11,119 bytes after gzip * jQuery minified with the YUI Compressor 31,822 bytes , 10,818 bytes after gzip @[daniel james](https://stackoverflow.com/users/2434/daniel-james) mentions in the comment [compressorrater](http://compressorrater.thruhere.net/) which shows Packer leading the chart in best compression, so I guess ymmv
Best JavaScript compressor
[ "", "javascript", "compression", "" ]
In other words, is this Singleton implementation thread safe: ``` public class Singleton { private static Singleton instance; private Singleton() { } static Singleton() { instance = new Singleton(); } public static Singleton Instance { get { return instance; } } } ```
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. <https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors> The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below. ``` public class Singleton { private static Singleton instance; // Added a static mutex for synchronising use of instance. private static System.Threading.Mutex mutex; private Singleton() { } static Singleton() { instance = new Singleton(); mutex = new System.Threading.Mutex(); } public static Singleton Acquire() { mutex.WaitOne(); return instance; } // Each call to Acquire() requires a call to Release() public static void Release() { mutex.ReleaseMutex(); } } ```
While all of these answers are giving the same general answer, there is one caveat. Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types. ``` class MyObject<T> { static MyObject() { //this code will get executed for each T. } } ``` EDIT: Here is the demonstration: ``` static void Main(string[] args) { var obj = new Foo<object>(); var obj2 = new Foo<string>(); } public class Foo<T> { static Foo() { System.Diagnostics.Debug.WriteLine(String.Format("Hit {0}", typeof(T).ToString())); } } ``` In the console: ``` Hit System.Object Hit System.String ```
Is the C# static constructor thread safe?
[ "", "c#", "multithreading", "singleton", "" ]
The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? ``` public interface ITest { public static String test(); } ``` The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between ``` public interface Foo { public static int bar(); } ``` and ``` public interface Foo { public static int bar() { ... } } ``` The first is impossible for the reasons that [Espo](https://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface#21826) mentions: you don't know which implementing class is the correct definition. Java *could* allow the latter; and in fact, starting in Java 8, it does!
The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.
Why can't I declare static methods in an interface?
[ "", "java", "interface", "methods", "static", "" ]
In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the [`date()`](https://php.net/date) function, the manual reads: ``` string date ( string $format [, int $timestamp = time() ] ) ``` Where `$timestamp` is an optional parameter, and when left blank it defaults to the [`time()`](https://php.net/time) function's return value. How do you go about creating optional parameters like this when defining a custom function in PHP?
Much like the manual, use an equals (`=`) sign in your definition of the parameters: ``` function dosomething($var1, $var2, $var3 = 'somevalue'){ // Rest of function here... } ```
> The default value of the argument must be a constant expression. It can't be a variable or a function call. If you need this functionality however: ``` function foo($foo, $bar = false) { if(!$bar) { $bar = $foo; } } ``` Assuming `$bar` isn't expected to be a boolean of course.
How do you create optional arguments in php?
[ "", "php", "" ]
I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done?
``` foreach(string key in hashTable.Keys) { Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key])); } ```
I like: ``` foreach(DictionaryEntry entry in hashtable) { Console.WriteLine(entry.Key + ":" + entry.Value); } ```
Print out the keys and Data of a Hashtable in C# .NET 1.1
[ "", "c#", "hashtable", ".net-1.1", "" ]
Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model.
The question is super old, but hell: <http://code.google.com/p/formalchemy/> Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic).
I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see [AdminPylon](http://adminpylon.devjavu.com/) and [Restin](http://code.google.com/p/restin/)) but none have really kept up with SQLAlchemy's rapidly developing orm api. Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.
Scaffolding in pylons
[ "", "python", "pylons", "" ]
I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: * Some Photoshop javascript * A Python function * An OSX API that I can call from python
Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.
open up a terminal (Applications->Utilities->Terminal) and type this in: ``` locate InsertFontHere ``` This will spit out every file that has the name you want. Warning: there may be alot to wade through.
How can I find the full path to a font from its display name on a Mac?
[ "", "python", "macos", "fonts", "photoshop", "" ]
I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false. if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed? ``` if ( (condition1) | (condition2) ){ // do this } ``` or would I need to nest two if statements to only check the second condition if the first evaluates to false? ``` if (condition1){ // do this }else if (condition2){ // do this } ``` I am working in PHP, however, I assume that this may be language-agnostic.
For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated. An old trick for doing obfuscated code was to use this to create if statements, such as: ``` a || b(); ``` if "a" is true, "b()" would never be evaluated, so we can rewrite it into: ``` if(!a) b(); ``` and similarly: ``` a && b(); ``` would become ``` if(a) b(); ``` **Please note** that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised". EDIT: As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time. First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason. Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.
Pretty much every language does a short circuit evaluation. Meaning the second condition is only evaluated if it's aboslutely necessary to. For this to work, most languages use the double pipe, ||, not the single one, |. See <http://en.wikipedia.org/wiki/Short-circuit_evaluation>
if statement condition optimisation
[ "", "php", "language-agnostic", "conditional-statements", "" ]
Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.
If you have access to GCC/G++, then the [`-M` option](http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#Preprocessor-Options) will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.
Thanks to KeithB. I looked up the docs for cl.exe (VS2008) and found the /showIncludes flag. From the IDE, this can be set from the property page of any CPP file. ![Screen shot](https://i.stack.imgur.com/3XkHJ.png)
Tool to track #include dependencies
[ "", "c++", "c", "header", "" ]
In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?
The following query will bring back a unique list of tables where `Column_Name` is equal to the column you are looking for: ``` SELECT Table_Name FROM INFORMATION_SCHEMA.COLUMNS WHERE Column_Name = 'Desired_Column_Name' GROUP BY Table_Name ```
``` SELECT Table_Name FROM Information_Schema.Columns WHERE Column_Name = 'YourFieldName' ```
SQL query for a database scheme
[ "", "sql", "sql-server", "" ]
When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?
Not sure what your level of expertise is, but here are the basics. Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it. ``` ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z) ``` There are a couple of points to focus on: * "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem * "int \_\_cdecl does\_not\_exist(void)" - This is the symbol it couldn't find, in this case a function named does\_not\_exist() At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together. If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file. --- In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to [MSDN](http://msdn.microsoft.com/en-us/default.aspx) or ["Microsoft Google"](http://www.google.com/microsoft) and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s [page on MSDN](http://msdn.microsoft.com/en-us/library/ms713418(VS.85).aspx) tells you to use Winmm.lib at the bottom of the page.
One of the common linking errors I've run into is when a function is used differently from how it's defined. If you see such an error you should make sure that every function you use is properly declared in some .h file. You should also make sure that all the relevant source files are compiled into the same lib file. An error I've run into is when I have two sets of files compiled into two separate libraries, and I cross-call between libraries. Is there a failure you have in mind?
Best practices for debugging linking errors
[ "", "c++", "visual-studio", "gcc", "linker", "compilation", "" ]
I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql. How do I specify a port number when I'm trying to connect to a database? It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?
After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection. This option was added GNU Emacs 24.1. > **sql-mysql-login-params** > > List of login parameters needed to connect to MySQL. I added this to my Emacs init file: ``` (setq sql-mysql-login-params (append sql-mysql-login-params '(port))) ``` The default port is 0. If you'd like to set that to the default MySQL port you can customize `sql-port` ``` (setq sql-port 3306) ;; default MySQL port ``` There is a `sql-*-login-params` variable for all the popular RDMS systems in GNU Emacs 24.1. `sql-port` is used for both MySQL and PostreSQL
``` (setq sql-mysql-options (list "-P <port number>")) ```
Specify a Port Number in Emacs sql-mysql
[ "", "sql", "mysql", "emacs", "" ]
What recommendations can you give for a system which must do the following: Load Plugins (and eventually execute them) but have 2 methods of loading these plugins: * Load only authorized plugins (developed by the owner of the software) * Load all plugins And we need to be reasonably secure that the authorized plugins are the real deal (unmodified). However all plugins must be in seperate assemblies. I've been looking at using strong named assemblies for the plugins, with the public key stored in the loader application, but to me this seems too easy to modify the public key within the loader application (if the user was so inclined) regardless of any obfuscation of the loader application. Any more secure ideas?
Basically, if you're putting your code on someone else's machine, there's no absolute guarantee of security. You can look at all kinds of security tricks, but in the end, the code is on their machine so it's out of your control. How much do you stand to lose if the end user loads an unauthorised plugin?
> How much do you stand to lose if the end user loads an unauthorised plugin? Admittedly this won't happen often, but when/if it does happen we lose a lot and I although I understand we will produce nothing 100% secure, I want to make it enough of a hindrance to put people off doing it. The annoying thing about going with a simple dynamic loading with full strong name, is that all it takes is a simple string literal change within the loader app to load any other assembly even though the plugins are signed.
.Net Dynamic Plugin Loading with Authority
[ "", "c#", ".net", "plugins", "assemblies", "dynamics-crm", "" ]
I want a data structure that will allow querying *how many items in last **X** minutes*. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp). So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure? The other part that I'm interested in is *aging* old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program.
A simple linked list can be used for this. Basically you add new items to the end, and remove too old items from the start, it is a cheap data structure. example-code: ``` list.push_end(new_data) while list.head.age >= age_limit: list.pop_head() ``` If the list will be busy enough to warrant chopping off larger pieces than one at a time, then I agree with [dmo](https://stackoverflow.com/users/1807/dmo), use a tree structure or something similar that allows pruning on a higher level.
I think that an important consideration will be the frequency of querying vs. adding/removing. If you will do frequent querying (especially if you'll have a large collection) a B-tree may be the way to go: <http://en.wikipedia.org/wiki/B-tree> You could have some thread go through and clean up this tree periodically or make it part of the search (again, depending on the usage). Basically, you'll do a tree search to find the spot "x minutes ago", then count the number of children on the nodes with newer times. If you keep the number of children under the nodes up to date, this sum can be done quickly.
Aging Data Structure in C#
[ "", "c#", "linq", ".net-3.5", "data-structures", "" ]
I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.
1. This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here. 2. Check out <http://www.harmony-central.com/Computer/Programming> and <http://www.developer.com/java/other/article.php/3071021> for some Java-related info. 3. If you don't know the basic concepts of encoding sound data, then read <http://en.wikipedia.org/wiki/Sampling_rate> 4. The canonical WAVE format is very simple, see <http://www.lightlink.com/tjweber/StripWav/Canon.html>. A header (first 44 bytes) + the wave-data. You don't need any library to implement that. In C/C++, the corresponding data structure would look something like this: ``` typedef struct _WAVstruct { char headertag[4]; unsigned int remnantlength; char fileid[4]; char fmtchunktag[4]; unsigned int fmtlength; unsigned short fmttag; unsigned short channels; unsigned int samplerate; unsigned int bypse; unsigned short ba; unsigned short bipsa; char datatag[4]; unsigned int datalength; void* data; //<--- that's where the raw sound-data goes }* WAVstruct; ``` I'm not sure about Java. I guess you'll have to substitute "struct" with "class" and "void\* data" with "char[] data" or "short[] data" or "int[] data", corresponding to the number of bits per sample, as defined in the field bipsa. To fill it with data, you would use something like that in C/C++: ``` int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result) { result->headertag[0] = 'R'; result->headertag[1] = 'I'; result->headertag[2] = 'F'; result->headertag[3] = 'F'; result->remnantlength = 44 + datalength - 8; result->fileid[0] = 'W'; result->fileid[1] = 'A'; result->fileid[2] = 'V'; result->fileid[3] = 'E'; result->fmtchunktag[0] = 'f'; result->fmtchunktag[1] = 'm'; result->fmtchunktag[2] = 't'; result->fmtchunktag[3] = ' '; result->fmtlength = 0x00000010; result->fmttag = 1; result->channels = channels; result->samplerate = samplerate; result->bipsa = bipsa; result->ba = channels*bipsa / 8; result->bypse = samplerate*result->ba; result->datatag[0] = 'd'; result->datatag[1] = 'a'; result->datatag[2] = 't'; result->datatag[3] = 'a'; result->datalength = datalength; result->data = data; // <--- that's were the data comes in return 0; // an error code, not implemented, yet ...; in Java: return result } ``` Again, I'm not sure about Java but the conversion should be straightforward if you convert the void-pointer to an array corresponding to the bitrate. Then simply write the entire structure to a file to get a playable wave file.
Check out [Frinika](http://frinika.sourceforge.net/). It's a full-featured music workstation implemented in Java (open source). Using the API, you can run midi events through the synthesizer, read the raw sound output, and write it to a WAV file (see source code link below). Additional information: * [Frinika Developer Area](http://frinika.wikispaces.com/DeveloperArea) * [Source code for midi renderer tool](http://frinika.svn.sourceforge.net/viewvc/frinika/frinika/trunk/src/com/frinika/tools/MyMidiRenderer.java?view=markup)
Beginner Digital Synth
[ "", "java", "synthesizer", "" ]
I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off? I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?
> I'm currently using NotePad++. Is > there maybe an IDE that would take > care of the tabs and indenting? I liked [pydev](http://pydev.sourceforge.net/) extensions of eclipse for that.
The answer is no. At least, not until something like the following is implemented: ``` from __future__ import braces ```
Is there a way around coding in Python without the tab, indent & whitespace criteria?
[ "", "python", "" ]
After reading [this question](https://stackoverflow.com/questions/28832/java-and-manually-executing-finalize), I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity.
The short answer: Java garbage collection is a very finely tuned tool. System.gc() is a sledge-hammer. Java's heap is divided into different generations, each of which is collected using a different strategy. If you attach a profiler to a healthy app, you'll see that it very rarely has to run the most expensive kinds of collections because most objects are caught by the faster copying collector in the young generation. Calling System.gc() directly, while technically not guaranteed to do anything, in practice will trigger an expensive, stop-the-world full heap collection. This is *almost always the wrong thing to do*. You think you're saving resources, but you're actually wasting them for no good reason, forcing Java to recheck all your live objects “just in case”. If you are having problems with GC pauses during critical moments, you're better off configuring the JVM to use the concurrent mark/sweep collector, which was designed specifically to minimise time spent paused, than trying to take a sledgehammer to the problem and just breaking it further. The Sun document you were thinking of is here: [Java SE 6 HotSpot™ Virtual Machine Garbage Collection Tuning](http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html) (Another thing you might not know: implementing a finalize() method on your object makes garbage collection slower. Firstly, it will take *two* GC runs to collect the object: one to run finalize() and the next to ensure that the object wasn't resurrected during finalization. Secondly, objects with finalize() methods have to be treated as special cases by the GC because they have to be collected individually, they can't just be thrown away in bulk.)
As far as finalizers go: 1. They are virtually useless. They aren't guaranteed to be called in a timely fashion, or indeed, at all (if the GC never runs, neither will any finalizers). This means you generally shouldn't rely on them. 2. Finalizers are not guaranteed to be idempotent. The garbage collector takes great care to guarantee that it will never call `finalize()` more than once on the same object. With well-written objects, it won't matter, but with poorly written objects, calling finalize multiple times can cause problems (e.g. double release of a native resource ... crash). 3. *Every* object that has a `finalize()` method should also provide a `close()` (or similar) method. This is the function you should be calling. e.g., `FileInputStream.close()`. There's no reason to be calling `finalize()` when you have a more appropriate method that *is* intended to be called by you.
Why do you not explicitly call finalize() or start the garbage collector?
[ "", "java", "garbage-collection", "" ]
I'm trying to parse an INI file using C++. Any tips on what is the best way to achieve this? Should I use the Windows API tools for INI file processing (with which I am totally unfamiliar), an open-source solution or attempt to parse it manually?
You can use the Windows API functions, such as [GetPrivateProfileString()](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilestring) and [GetPrivateProfileInt()](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofileint).
If you need a cross-platform solution, try Boost's [Program Options](http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html) library.
What is the easiest way to parse an INI File in C++?
[ "", "c++", "winapi", "ini", "fileparse", "" ]
I am prototyping some C# 3 collection filters and came across this. I have a collection of products: ``` public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List<MyProduct> { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." } , new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; ``` Now if I use LINQ to filter it works as expected: ``` var d = (from mp in MyProducts where mp.Price < 50d select mp); ``` And if I use the Where extension method combined with a Lambda the filter works as well: ``` var f = MyProducts.Where(mp => mp.Price < 50d).ToList(); ``` **Question:** What is the difference, and why use one over the other?
LINQ turns into method calls like the code you have. In other words, there should be no difference. However, in your two pieces of code you are not calling .ToList in the first, so the first piece of code will produce an enumerable data source, but if you call .ToList on it, the two should be the same.
As mentioned d will be `IEnumerable<MyProduct>` while f is `List<MyProduct>` The conversion is done by the C# compiler ``` var d = from mp in MyProducts where mp.Price < 50d select mp; ``` Is converted to (before compilation to IL and with generics expanded): ``` var d = MyProducts. Where<MyProduct>( mp => mp.Price < 50d ). Select<MyProduct>( mp => mp ); //note that this last select is optimised out if it makes no change ``` Note that in this simple case it makes little difference. Where Linq becomes really valuable is in much more complicated loops. For instance this statement could include group-bys, orders and a few let statements and still be readable in Linq format when the equivalent `.Method().Method.Method()` would get complicated.
When to use an extension method with lambda over LINQtoObjects to filter a collection?
[ "", "c#", "linq", ".net-3.5", "lambda", "" ]
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' `SelectedNode` property because the node is only been right-clicked and not selected.
You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. ``` void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode != null) { myContextMenuStrip.Show(treeView1, e.Location); } } } ```
Here is my solution. Put this line into NodeMouseClick event of the TreeView: ``` ((TreeView)sender).SelectedNode = e.Node; ```
Find node clicked under context menu
[ "", "c#", "winforms", "treeview", "contextmenu", "" ]
What does it mean when you get or create a date in UTC format in JavaScript?
A date represents a specific point in time. This point in time will be called differently in different places. As I write this, it's 00:27 on Tuesday in Germany, 23:27 on Monday in the UK and 18:27 on Monday in New York. To take an example method: getDay returns the day of the week in the local timezone. Right now, for a user in Germany, it would return 2. For a user in the UK or US, it would return 1. In an hour's time, it will return 2 for the user in the UK (because it will then be 00:27 on Tuesday there). The ..UTC.. methods deal with the representation of the time in UTC (also known as GMT). In winter, this is the same timezone as the UK, in summer it's an hour behind the time in the UK. It's summer as I write this. getUTCDay will return 1 (Monday), getUTCHours will return 22, getUTCMinutes will return 27. So it's 22:27 on Monday in the UTC timezone. Whereas the plain get... functions will return different values depending on where the user is, the getUTC.. functions will return those same values no matter where the user is.
getUTC is for converting times to Coordinated Universal Time (UTC, the acronym is ordered differently than what it stands for) which is the standard time based on the time in Greenwich, London. The universal time is calculated using a time offset (in minutes when in JavaScript.) This offset is based on the time zone configured on the client browser's operating system. If you plan on storing dates for users in multiple time zones, this is what you should use.
What do the getUTC* methods on the date object do?
[ "", "javascript", "date", "utc", "" ]
I'm just about to make my first trip into the world of JNI (Java Native Interface) to provide file system change notifications from platform specific C/C++ code to Java. That is unless someone suggest some brilliant library for doing this that I've missed. Being new to JNI I've managed to find much documentation on the interface side of it and library generation side of it, but I've not found much on building the native library. I've got an existing build based on ant for the pre-existing Java source, so I'm trying to work out if I should get ant to call make to create the library or if it's best to get make to call ant after creating the library? Neither option jumps out as being terribly nice, but both seem better than trying to get ant to call a compiler to compile the code and generate the library directly.
I strongly dislike make because of its implicit ruleset and treatment of whitespace. Personally I would use cpp tasks (<http://ant-contrib.sourceforge.net/cpptasks/index.html>) to do my C compilation. They are not as flexible as make but they are also far less complex and it will mean you don't have to burden your developers with learning make.
As a simpler alternative to JNI, try JNA: <https://jna.dev.java.net/>, may solve this hassle for you and be simpler (assuming it can do what you want).
JNI and Java: ant calling make or make calling ant?
[ "", "java", "ant", "makefile", "java-native-interface", "automake", "" ]
I see many user interface control libraries for .NET, but where can I get similar stuff for win32 using simply C/C++? Things like prettier buttons, dials, listviews, graphs, etc. Seems every Win32 programmers' right of passage is to end up writing his own collection. :/ --- No MFC controls please. I only do pure C/C++. And with that said, I also don't feel like adding a multi-megabyte framework to my application just so that I can have a prettier button. --- I apologize for leaving out one tiny detail, and that is that my development is for Windows Mobile. So manifest files are out. I just notice how many developer companies have gone crazy with making pretty looking .NET components and wondered where the equivalent C/C++ Win32 components have gone? I read about how many people ended up writing their own gradient button class, etc. So you would think that there would be some commercial classes for this stuff. It's just weird. I'll take a closer look at QT and investigate its GUI support for such things. This is the challenge when you're the one man in your own uISV. No other developers to help you "get things done".
I've used [Trolltech's Qt framework](http://trolltech.com/products/qt/) in the past and had great success with it: In addition, it's also cross-platform, so in theory you can target Win, Mac, & Linux (provided you don't do anything platform-specific in the rest of your code, of course ;) ) Edit: I notice that you're targeting Windows Mobile; that definitely adds to Qt's strength, as its cross-platform support extends to [WinCE and Embedded Linux](http://trolltech.com/products/qt/features/platforms/index) as well.
I you don't mind using the MFC libraries you should try the [Visual C++ 2008 Feature Pack](http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en)
User Interface Controls for Win32
[ "", "c++", "winapi", "user-interface", "" ]
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this: ``` public String appendWithDelimiter( String original, String addition, String delimiter ) { if ( original.equals( "" ) ) { return addition; } else { return original + delimiter + addition; } } String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," ); ``` I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization. In Ruby, I can do something like this instead, which feels much more elegant: ``` parameterArray = []; parameterArray << "elementName" if condition; parameterArray << "anotherElementName" if anotherCondition; parameterString = parameterArray.join(","); ``` But since Java lacks a join command, I couldn't figure out anything equivalent. So, what's the best way to do this in Java?
### Pre Java 8: Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: [`StringUtils.join(java.lang.Iterable,char)`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char)) --- ### Java 8: Java 8 provides joining out of the box via `StringJoiner` and `String.join()`. The snippets below show how you can use them: [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html) ``` StringJoiner joiner = new StringJoiner(","); joiner.add("01").add("02").add("03"); String joinedString = joiner.toString(); // "01,02,03" ``` --- [`String.join(CharSequence delimiter, CharSequence... elements))`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-) ``` String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06" ``` --- [`String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) ``` List<String> strings = new LinkedList<>(); strings.add("Java");strings.add("is"); strings.add("cool"); String message = String.join(" ", strings); //message returned is: "Java is cool" ```
You could write a little join-style utility method that works on java.util.Lists ``` public static String join(List<String> list, String delim) { StringBuilder sb = new StringBuilder(); String loopDelim = ""; for(String s : list) { sb.append(loopDelim); sb.append(s); loopDelim = delim; } return sb.toString(); } ``` Then use it like so: ``` List<String> list = new ArrayList<String>(); if( condition ) list.add("elementName"); if( anotherCondition ) list.add("anotherElementName"); join(list, ","); ```
What's the best way to build a string of delimited items in Java?
[ "", "java", "string", "algorithm", "" ]
I need to create a backup of a SQL Server 2005 Database that's only the structure...no records, just the schema. Is there any way to do this? EDIT: I'm trying to create a backup file to use with old processes, so a script wouldn't work for my purposes, sorry
Use a 3 step process: 1. Generate a script from the working database 2. Create a new database from that script 3. Create a backup of the new database
Why not just use SQL Management Studio to create a complete script of your database and the objects?
Backup SQL Schema Only?
[ "", "sql", "sql-server", "oracle", "sql-server-2005", "backup", "" ]
I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking.
I believe that you can use [`Monitor.TryEnter()`](http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter%28VS.71%29.aspx). The lock statement just translates to a `Monitor.Enter()` call and a `try catch` block.
Ed's got the right function for you. Just don't forget to call `Monitor.Exit()`. You should use a `try-finally` block to guarantee proper cleanup. ``` if (Monitor.TryEnter(someObject)) { try { // use object } finally { Monitor.Exit(someObject); } } ```
Is there a "try to lock, skip if timed out" operation in C#?
[ "", "c#", "multithreading", "locking", "" ]
Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and [Safari](http://en.wikipedia.org/wiki/Safari_%28web_browser%29). In Firefox, you can use [Firebug's](http://en.wikipedia.org/wiki/Firebug) [logging feature](http://getfirebug.com/logging.html) and [command Line functions](http://getfirebug.com/commandline.html). However, this doesn't help me when I move to other browsers.
For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see [the entry in Apple's Safari development FAQ](http://developer.apple.com/internet/safari/faq.html#anchor14)) or via ``` $ defaults write com.apple.Safari IncludeDebugMenu 1 ``` at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log. For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. [This post on the IE team blog](http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx "Scripting Debugging in Internet Explorer") walks you through installing it and connecting to Internet Explorer. Internet Explorer 8 [looks](http://www.west-wind.com/weblog/posts/271352.aspx) like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl.
[This is the Firebug Lite](http://getfirebug.com/lite.html "Firebug Lite") that @John was referring to that works on IE, Safari and Opera.
Debugging JavaScript in Internet Explorer and Safari
[ "", "javascript", "internet-explorer", "safari", "" ]
I have a medium sized application that runs as a .net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting. I wanted to know what is the best/most practical solution for using web-services in python. Edit: I need to consume a complex soap WS and I have no control over it.
[Jython](http://www.jython.org) and [IronPython](http://www.codeplex.com/IronPython) give access to great Java & .NET SOAP libraries. If you need CPython, [ZSI](http://pywebsvcs.sourceforge.net/) has been flaky for me, but it could be possible to use a tool like [Robin](http://robin.python-hosting.com/) to wrap a good C++ SOAP library such as [gSOAP](http://gsoap2.sourceforge.net/) or [Apache Axis C++](http://ws.apache.org/axis/cpp/index.html)
If I have to expose APIs, I prefer doing it as JSON. Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)
What's the best way to use web services in python?
[ "", "python", "web-services", "soap", "" ]
We have the question [is there a performance difference between `i++` and `++i` **in C**?](/q/24886) What's the answer for C++?
[Executive Summary: Use `++i` if you don't have a specific reason to use `i++`.] For C++, the answer is a bit more complicated. If `i` is a simple type (not an instance of a C++ class), [then the answer given for C ("No there is no performance difference")](https://stackoverflow.com/a/24887/194894) holds, since the compiler is generating the code. However, if `i` is an instance of a C++ class, then `i++` and `++i` are making calls to one of the `operator++` functions. Here's a standard pair of these functions: ``` Foo& Foo::operator++() // called for ++i { this->data += 1; return *this; } Foo Foo::operator++(int ignored_dummy_value) // called for i++ { Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp; } ``` Since the compiler isn't generating code, but just calling an `operator++` function, there is no way to optimize away the `tmp` variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.
Yes. There is. The ++ operator may or may not be defined as a function. For primitive types (int, double, ...) the operators are built in, so the compiler will probably be able to optimize your code. But in the case of an object that defines the ++ operator things are different. The operator++(int) function must create a copy. That is because postfix ++ is expected to return a different value than what it holds: it must hold its value in a temp variable, increment its value and return the temp. In the case of operator++(), prefix ++, there is no need to create a copy: the object can increment itself and then simply return itself. Here is an illustration of the point: ``` struct C { C& operator++(); // prefix C operator++(int); // postfix private: int i_; }; C& C::operator++() { ++i_; return *this; // self, no copy created } C C::operator++(int ignored_dummy_value) { C t(*this); ++(*this); return t; // return a copy } ``` Every time you call operator++(int) you must create a copy, and the compiler can't do anything about it. When given the choice, use operator++(); this way you don't save a copy. It might be significant in the case of many increments (large loop?) and/or large objects.
Is there a performance difference between i++ and ++i in C++?
[ "", "c++", "performance", "oop", "post-increment", "pre-increment", "" ]
Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
You may find the solution in *[SQL User Defined Function to Parse a Delimited String](http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx)* helpful (from [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project)). You can use this simple logic: ``` Declare @products varchar(200) = '1|20|3|343|44|6|8765' Declare @individual varchar(20) = null WHILE LEN(@products) > 0 BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual END END ```
I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function: ``` SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2) ``` PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, and that number specifies which segment of the string to return (working from back to front). ``` SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 3) --return Hello ``` Obvious problem is when the string already contains a period. I still think using a UDF is the best way...any other suggestions?
How do I split a delimited string so I can access individual items?
[ "", "sql", "sql-server", "t-sql", "split", "" ]
I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this? Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal.
[`Enumerable.SequenceEqual`](http://msdn.microsoft.com/en-us/library/bb342073.aspx) > Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T). You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary with the list
As others have suggested and have noted, `SequenceEqual` is order-sensitive. To solve that, you can sort the dictionary by key (which is unique, and thus the sort is always stable) and then use `SequenceEqual`. The following expression checks if two dictionaries are equal regardless of their internal order: ``` dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key)) ``` --- **EDIT:** As pointed out by Jeppe Stig Nielsen, some object have an `IComparer<T>` that is incompatible with their `IEqualityComparer<T>`, yielding incorrect results. When using keys with such an object, you must specify a correct `IComparer<T>` for those keys. For example, with string keys (which exhibit this issue), you must do the following in order to get correct results: ``` dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)) ```
Is there a built-in method to compare collections?
[ "", "c#", ".net", "collections", "" ]
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within `[a-zA-Z0-9'\-]`) How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like.. ``` config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """ config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars']) config['name_parse'] = [ # foo_[s01]_[e01] re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])), # foo.1x09* re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.s01.e01, foo.s01_e01 re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.103* re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.0103* re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), ] ```
Use a subrange of `[\u0000-\uFFFF]` for what you want. You can also use the `re.UNICODE` compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if `UNICODE` is set, `\w` will match the characters `[0-9_]` plus whatever is classified as alphanumeric in the Unicode character properties database. See also <http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html>.
Python's re module doesn't support \p{Letter} or \X. However, the [new regex implementation on PyPI](http://pypi.python.org/pypi/regex) does.
Regex and unicode
[ "", "python", "regex", "unicode", "character-properties", "" ]
I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any *best practices*, tipps or major *DO NOTs* for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...
Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: * `MyProject / src / main / resources / spring /` + ***datasource.xml*** - My single data source bean. + ***persistence.xml*** - My DAOs/Repositories. Depends on `datasource.xml` beans. + ***services.xml*** - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on `persistence.xml` beans. + ***controllers.xml*** - My Spring MVC controllers. Depends on `services.xml` beans. + ***views.xml*** - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: **Clearer architecture** Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. **Helps domain design** If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: * Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to `services.xml`, or put them in their own `transactionPolicy.xml`? Talk it over with your team. Should your transaction policy be pluggable? * Add Acegi/Spring Security beans to your `controllers.xml` file, or create a `security.xml` context file? Do you have different security requirements for different deployments/environments? **Integration testing** You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only `datasource.xml` and `persistence.xml` beans). Specifically, you can annotate an integration test class as such: ``` @ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" }) ``` **Works well with Spring IDE's Beans Graph** Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's [Beans Graph](http://springide.org/project/wiki/BeansGraph). I've used this before to give new team members a high-level overview of our application's organization.
Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core. Best practice? If you're using the standard XML config, manage the size of individual files and comment them judiciously. You may think that you and others will perfectly understand your bean definitions, but in practice they're somewhat harder to come back to than plain old java code. Good luck!
What's your "best practice" for the first Java EE Spring project?
[ "", "java", "spring", "jakarta-ee", "aop", "" ]
I know I need to have (although I don't know why) a `GROUP BY` clause on the end of a SQL query that uses any aggregate functions like `count`, `sum`, `avg`, etc: ``` SELECT count(userID), userName FROM users GROUP BY userName ``` When else would `GROUP BY` be useful, and what are the performance ramifications?
To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: ``` SELECT WidgetCategory, count(*) FROM Widgets GROUP BY WidgetCategory HAVING count(*) > 5 ``` The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
GROUP BY is similar to DISTINCT in that it groups multiple records into one. This example, borrowed from <http://www.devguru.com/technologies/t-sql/7080.asp>, lists distinct products in the Products table. ``` SELECT Product FROM Products GROUP BY Product Product ------------- Desktop Laptop Mouse Network Card Hard Drive Software Book Accessory ``` The advantage of GROUP BY over DISTINCT, is that it can give you granular control when used with a HAVING clause. ``` SELECT Product, count(Product) as ProdCnt FROM Products GROUP BY Product HAVING count(Product) > 2 Product ProdCnt -------------------- Desktop 10 Laptop 5 Mouse 3 Network Card 9 Software 6 ```
How do I use T-SQL Group By
[ "", "sql", "sql-server", "group-by", "" ]
What is the Java equivalent of PHP's `$_POST`? After searching the web for an hour, I'm still nowhere closer.
Your `HttpServletRequest` object has a `getParameter(String paramName)` method that can be used to get parameter values. <http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)>
Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea. I hope this helps you out. ``` <html> <body> <form method="post" action="/myServlet"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" /> </form> </body> </html> ``` Now for the Servlet ``` import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("username"); String password = request.getParameter("password"); .... .... } } ```
Accessing post variables using Java Servlets
[ "", "java", "http", "servlets", "" ]
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? ``` const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21; ```
## Updated answer **Here's an update as of 2016 and [widespread deployment of ES5](http://kangax.github.io/compat-table/es5/) and beyond.** For IE9+ and all other modern ES5+ capable browsers, you can use [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) so the above code just becomes: ``` var size = Object.keys(myObj).length; ``` This doesn't have to modify any existing prototype since `Object.keys()` is now built-in. **Edit**: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them. Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites. `Object.keys` or `Object.getOwnPropertyNames` does not work for symbolic properties. To return them you need to use `Object.getOwnPropertySymbols`. ``` var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 ``` ## Older answer The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be: ``` Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object const myObj = {} var size = Object.size(myObj); ``` There's a sort of convention in JavaScript that you [don't add things to Object.prototype](https://stackoverflow.com/questions/10757455/object-prototype-is-verboten), because it can break enumerations in various libraries. Adding methods to Object is usually safe, though. ---
If you know you don't have to worry about `hasOwnProperty` checks, you can use the [Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method in this way: ``` Object.keys(myArray).length ```
Length of a JavaScript object
[ "", "javascript", "object", "javascript-objects", "" ]
In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can. Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the `bind_params()` or `bind_result()` methods. Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind. Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements. Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).
In PHP you can pass a variable number of arguments to a function or method by using [`call_user_func_array`](http://www.php.net/call_user_func_array). An example for a method would be: ``` call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params); ``` The function will be called with each member in the array passed as its own argument.
The more modern way to bind parameters dynamically is via the splat/spread operator (`...`). Assuming: * you have a non-empty array of values to bind to your query and * your array values are suitably processed as string type values in the context of the query and * your input array is called `$values` Code for PHP5.6 and higher: ``` $stmt->bind_param(str_repeat('s', count($values)), ...$values); ``` In fact, all of the arguments fed to `bind_param()` can be unpacked with the splat/spread operator if you wish -- the data types string just needs to be the first element of the array. ``` array_unshift($values, str_repeat('s', count($values))); $stmt->bind_param(...$values); ```
Variable parameter/result binding with prepared statements
[ "", "php", "mysql", "mysqli", "" ]
I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this ``` LIBRARY "MyLib" EXPORTS Foo Bar ``` with the code defined as this, for example: ``` int Foo(int a); void Bar(int foo); ``` However, what if I want to declare an overloaded method of Foo() like: ``` int Foo(int a, int b); ``` As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ? Edit: To be clear, this is on Windows using Visual Studio 2005 Edit: Marked the non-def (\_\_declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.
In the code itself, mark the functions you want to export using \_\_declspec(dllexport). For example: ``` #define DllExport __declspec(dllexport) int DllExport Foo( int a ) { // implementation } int DllExport Foo( int a, int b ) { // implementation } ``` If you do this, you do not need to list the functions in the .def file. Alternatively, you may be able to use a default parameter value, like: ``` int Foo( int a, int b = -1 ) ``` This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work. Edit (Adam Haile): Corrected to use \_\_declspec as \_\_dllspec was not correct so I could mark this as the official answer...it was close enough. Edit (Graeme): Oops - thanks for correcting my typo!
Function overloading is a C++ feature that relies on name mangling (the cryptic function names in the linker error messages). By writing the mangled names into the def file, I can get my test project to link and run: ``` LIBRARY "TestDLL" EXPORTS ?Foo@@YAXH@Z ?Foo@@YAXHH@Z ``` seems to work for ``` void Foo( int x ); void Foo( int x, int y ); ``` So copy the C++ function names from the error message and write them into your def file. However, the real question is: Why do you want to use a def file and not go with \_\_declspec(dllexport) ? The mangled names are non-portable, I tested with VC++ 2008.
Overloaded functions in C++ DLL def file
[ "", "c++", "c", "dll", "" ]
I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table?
> SELECT LEN(columnName) AS MyLength > FROM myTable
If you want to find out the max there should be a way for you to get the schema of the table. Normally you can do something like [SHOW COLUMNS](http://dev.mysql.com/doc/refman/5.0/en/show-columns.html) in SQL or a [DESCRIBE](http://dev.mysql.com/doc/refman/5.0/en/describe.html) style command. In a mysql shell that can be shortened to: ``` desc tablename; ``` Then if you want to determine the length of a string there is normally a function like [LENGTH](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_length) *(for bytes)* or [CHAR\_LENGTH](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length) *(for characters)*. ``` SELECT *, LENGTH(fieldname) AS len FROM tablename ```
What SQL-server function can I use to get the character or byte length of a nvarchar(max) column?
[ "", "sql", "sql-server", "" ]
Currently we have a project with a standard subversion repository layout of: ./trunk ./branches ./tags However, as we're moving down the road of OSGi and a modular project, we've ended up with: ./trunk/bundle/main ./trunk/bundle/modulea ./trunk/bundle/moduleb ./tags/bundle/main-1.0.0 ./tags/bundle/main-1.0.1 ./tags/bundle/modulea-1.0.0 The 'build' is still quite monolithic in that it builds all modules in sequence, though I'm starting to wonder if we should refactor the build/repository to something more like: ./bundle/main/trunk ./bundle/main/tags/main-1.0.0 ./bundle/main/tags/main-1.0.1 ./bundle/modulea/trunk ./bundle/modulea/tags/modulea-1.0.0 In this pattern I would imagine each module building itself, and storing its binary in a repository (maven, ivy, or another path of the subversion repository itself). Are there guidelines or 'best-practices' over project layouts once one goes modular?
The Subversion book contains two sections on this: * [Repository Layout](http://svnbook.red-bean.com/en/1.4/svn.branchmerge.maint.html#svn.branchmerge.maint.layout) * [Planning Your Repository Organization](http://svnbook.red-bean.com/en/1.4/svn.reposadmin.planning.html#svn.reposadmin.projects.chooselayout) A blog entry on the subject: ["Subversion Repository Layout"](http://blogs.collab.net/subversion/subversion_repo) The short answer, though: while your mileage will vary (every situation is individual), your `/bundle/<project>/(trunk|tags|branches)` scheme is rather common and will likely work well for you.
This is very much up to personal preference, but I find the following structure suitable for large projects consisting of many modules: ``` branches project-name module1 branch-name module2 possibly-another-branch-name branch-name-on-a-higher-level-including-both-modules module1 module2 tags ... (same as branches) trunk project-name module1 module2 ``` I have also often used the structure in large repositories containing many projects, because keeping all projects in the same repository makes cross-referencing projects and sharing code between them—with history—easier. I like to use the structure with root trunk, tags and branches folders from the start because in my experience (with large repositories containing many projects), many sub-projects and modules will never have separate tags or branches, so there is no need to create the folder structure for them. It also makes it easier for the developers to check out the entire trunk of the repository and not get all the tags and branches (which they don't need most of the time). I guess this is a matter of project or company policy though. If you have one repository for each project or a given developer is only likely to work on a single project in the repository at a time the rooted trunk may not make as much sense.
When should a multi-module project to split into separate repository trees?
[ "", "java", "svn", "osgi", "" ]
So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?
I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace. I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on. I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program).
Three points to make here: * Firstly, there is little or NO performance penalty in actually having try-catch blocks in your code. This should not be a consideration when trying to avoid having them in your application. The performance hit only comes into play when an exception is thrown. * When an exception is thrown in addition to the stack unwinding operations etc that take place which others have mentioned you should be aware that a whole bunch of runtime/reflection related stuff happens in order to populate the members of the exception class such as the stack trace object and the various type members etc. * I believe that this is one of the reasons why the general advice if you are going to rethrow the exception is to just `throw;` rather than throw the exception again or construct a new one as in those cases all of that stack information is regathered whereas in the simple throw it is all preserved.
What is the real overhead of try/catch in C#?
[ "", "c#", ".net", "performance", "optimization", "try-catch", "" ]
This question is kind of an add-on to this [question](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why) In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subsequent month thereafter. (simple example, not meant to be real) ``` switch (month) { case 0: add something to month totals case 1: add something to month totals case 2: add something to month totals default: break; } ``` Is there a logical alternative to this in C# without having to write out a ton of if statements? ``` if (month <= 0) add something to month if (month <= 1) add something to month if (month <= 2) add something to month .... etc ```
Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design. Instead, what if you implemented the Specification pattern to see if something matched, and then act on it? ``` foreach(MonthSpecification spec in this.MonthSpecifications) { if(spec.IsSatisfiedBy(month)) spec.Perform(month); } ``` then you can just add up different specs that match what you're trying to do. It's hard to tell what your domain is, so my example might be a little contrived.
In C# switch statements you can fall through cases only if there is no statement for the case you want to fall through ``` switch(myVar) { case 1: case 2: // Case 1 or 2 get here break; } ``` However if you want to fall through with a statement you must use the dreaded GOTO ``` switch(myVar) { case 1: // Case 1 statement goto case 2; case 2: // Case 1 or 2 get here break; } ```
C# switch: case not falling through to other cases limitation
[ "", "c#", "switch-statement", "" ]
We have some input data that sometimes appears with &nbsp characters on the end. The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters. Ltrim and Rtrim don't remove the characters, so we're forced to do something like: ``` UPDATE myTable SET myColumn = replace(myColumn,char(160),'') WHERE charindex(char(160),myColumn) > 0 ``` This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?
[This page](http://www.lazydba.com/sql/1__4390.html) has a sample of how you can remove non-alphanumeric chars: ``` -- Put something like this into a user function: DECLARE @cString VARCHAR(32) DECLARE @nPos INTEGER SELECT @cString = '90$%45623 *6%}~:@' SELECT @nPos = PATINDEX('%[^0-9]%', @cString) WHILE @nPos > 0 BEGIN SELECT @cString = STUFF(@cString, @nPos, 1, '') SELECT @nPos = PATINDEX('%[^0-9]%', @cString) END SELECT @cString ```
This will remove all non alphanumeric chracters ``` CREATE FUNCTION [dbo].[fnRemoveBadCharacter] ( @BadString nvarchar(20) ) RETURNS nvarchar(20) AS BEGIN DECLARE @nPos INTEGER SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString) WHILE @nPos > 0 BEGIN SELECT @BadString = STUFF(@BadString, @nPos, 1, '') SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString) END RETURN @BadString END ``` Use the function like: ``` UPDATE TableToUpdate SET ColumnToUpdate = dbo.fnRemoveBadCharacter(ColumnToUpdate) WHERE whatever ```
T-SQL trim &nbsp (and other non-alphanumeric characters)
[ "", "sql", "sql-server", "" ]
I am writing a batch script in order to beautify JavaScript code. It needs to work on both **Windows** and **Linux**. How can I beautify JavaScript code using the command line tools?
First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at [<http://jsbeautifier.org/>](http://jsbeautifier.org/), because it's what I found first. Downloads its file <https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js> Second, download and install The Mozilla group's Java based Javascript engine, [Rhino](https://www.mozilla.org/rhino/). "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this ``` java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js ``` Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example ``` //original code (function() { ... js_beautify code ... }()); //new code print(global.js_beautify(readFile(arguments[0]))); ``` Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file. You'd invoke the above something like ``` java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js ``` You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.
**UPDATE April 2014**: The beautifier has been rewritten since I answered this in 2010. There is now a python module in there, an npm Package for nodejs, and the jar file is gone. Please read the [project page on github.com](https://github.com/einars/js-beautify/). Python style: ``` $ pip install jsbeautifier ``` NPM style: ``` $ npm -g install js-beautify ``` to use it (this will return the beatified js file on the terminal, the main file remains unchanged): ``` $ js-beautify file.js ``` To **make the changes take effect on the file**, you should use this command: ``` $ js-beautify -r file.js ``` **Original answer** Adding to Answer of @Alan Storm the command line beautifier based on <http://jsbeautifier.org/> has gotten a bit easier to use, because it is now (alternatively) based on the V8 javascript engine (c++ code) instead of rhino (java-based JS engine, packaged as "js.jar"). So you can use V8 instead of rhino. How to use: download jsbeautifier.org zip file from <http://github.com/einars/js-beautify/zipball/master> (this is a download URL linked to a zip file such as <http://download.github.com/einars-js-beautify-10384df.zip>) old (no longer works, jar file is gone) ``` java -jar js.jar name-of-script.js ``` new (alternative) install/compile v8 lib FROM svn, see v8/README.txt in above-mentioned zip file ``` ./jsbeautify somefile.js ``` -has slightly different command line options than the rhino version, -and works great in Eclipse when configured as an "External Tool"
How can I beautify JavaScript code using Command Line?
[ "", "javascript", "command-line-interface", "pretty-print", "multiplatform", "" ]
I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have: ``` <?php if ( !empty($_FILES['file']['tmp_name']) ) { move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']); header('Location: http://www.mywebsite.com/dump/'); exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Dump Upload</title> </head> <body> <h1>Upload a File</h1> <form action="upload.php" enctype="multipart/form-data" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /> Select the File:<br /><input type="file" name="file" /><br /> <input type="submit" value="Upload" /> </form> </body> </html> ``` I'm getting these errors: > Warning: move\_uploaded\_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3 > > Warning: move\_uploaded\_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3 > > Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4 PHP version 4.4.7 Running IIS on a Windows box. This particular file/folder has 777 permissions. Any ideas?
As it's Windows, there is no real 777. If you're using [chmod](https://www.php.net/manual/en/function.chmod.php), check the Windows-related comments. Check that the IIS Account can access (read, write, modify) these two folders: ``` E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\ C:\WINDOWS\Temp\ ```
OMG ``` move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']); ``` Don't do that. `$_FILES['file']['name']` could be `../../../../boot.ini` or any number of bad things. You should never trust this name. You should rename the file something else and associate the original name with your random name. At a minimum use `basename($_FILES['file']['name'])`.
PHP Error - Uploading a file
[ "", "php", "iis", "upload", "" ]
I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people. ``` int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List<int> Primes = new List<int>(); for (int i = 2; i < Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); ``` Maybe I could use multiple `BitArray`s and [BitArray.And()](http://msdn.microsoft.com/en-us/library/system.collections.bitarray.and.aspx) them together?
You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime. Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p\*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until). There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. [The wikipedia page](http://en.wikipedia.org/wiki/Primality_test) is a good introduction.
Parallelisation aside, you don't want to be calculating sqrt(Until) on every iteration. You also can assume multiples of 2, 3 and 5 and only calculate for N%6 in {1,5} or N%30 in {1,7,11,13,17,19,23,29}. You should be able to parallelize the factoring algorithm quite easily, since the Nth stage only depends on the sqrt(n)th result, so after a while there won't be any conflicts. But that's not a good algorithm, since it requires lots of division. You should also be able to parallelize the sieve algorithms, if you have writer work packets which are guaranteed to complete before a read. Mostly the writers shouldn't conflict with the reader - at least once you've done a few entries, they should be working at least N above the reader, so you only need a synchronized read fairly occasionally (when N exceeds the last synchronized read value). You shouldn't need to synchronize the bool array across any number of writer threads, since write conflicts don't arise (at worst, more than one thread will write a true to the same place). The main issue would be to ensure that any worker being waited on to write has completed. In C++ you'd use a compare-and-set to switch to the worker which is being waited for at any point. I'm not a C# wonk so don't know how to do it that language, but the Win32 InterlockedCompareExchange function should be available. You also might try an actor based approach, since that way you can schedule the actors working with the lowest values, which may be easier to guarantee that you're reading valid parts of the the sieve without having to lock the bus on each increment of N. Either way, you have to ensure that all workers have got above entry N before you read it, and the cost of doing that is where the trade-off between parallel and serial is made.
Fastest way to calculate primes in C#?
[ "", "c#", ".net", "performance", "algorithm", "bitarray", "" ]
Let's say that we have an ARGB color: ``` Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. ``` When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is `Color.FromARGB(255, 162, 133, 255);` The solution should work like this: ``` Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); ``` What is `ToRGB`'s implementation?
It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing). In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. ``` alpha=argb.alpha() r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r() g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g() b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() ``` *note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly* **Edited to add:** If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
I know this is an old thread, but I want to add this: ``` Public Shared Function AlphaBlend(ByVal ForeGround As Color, ByVal BackGround As Color) As Color If ForeGround.A = 0 Then Return BackGround If BackGround.A = 0 Then Return ForeGround If ForeGround.A = 255 Then Return ForeGround Dim Alpha As Integer = CInt(ForeGround.A) + 1 Dim B As Integer = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8 Dim G As Integer = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8 Dim R As Integer = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8 Dim A As Integer = ForeGround.A If BackGround.A = 255 Then A = 255 If A > 255 Then A = 255 If R > 255 Then R = 255 If G > 255 Then G = 255 If B > 255 Then B = 255 Return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B)) End Function public static Color AlphaBlend(Color ForeGround, Color BackGround) { if (ForeGround.A == 0) return BackGround; if (BackGround.A == 0) return ForeGround; if (ForeGround.A == 255) return ForeGround; int Alpha = Convert.ToInt32(ForeGround.A) + 1; int B = Alpha * ForeGround.B + (255 - Alpha) * BackGround.B >> 8; int G = Alpha * ForeGround.G + (255 - Alpha) * BackGround.G >> 8; int R = Alpha * ForeGround.R + (255 - Alpha) * BackGround.R >> 8; int A = ForeGround.A; if (BackGround.A == 255) A = 255; if (A > 255) A = 255; if (R > 255) R = 255; if (G > 255) G = 255; if (B > 255) B = 255; return Color.FromArgb(Math.Abs(A), Math.Abs(R), Math.Abs(G), Math.Abs(B)); } ```
Converting ARBG to RGB with alpha blending
[ "", "c#", "colors", "" ]
Should you set all the objects to `null` (`Nothing` in VB.NET) once you have finished with them? I understand that in .NET it is essential to dispose of any instances of objects that implement the `IDisposable` interface to release some resources although the object can still be something after it is disposed (hence the `isDisposed` property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to `null` speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.
Karl is absolutely correct, there is no need to set objects to null after use. If an object implements `IDisposable`, just make sure you call `IDisposable.Dispose()` when you're done with that object (wrapped in a `try`..`finally`, or, a `using()` block). But even if you don't remember to call `Dispose()`, the finaliser method on the object should be calling `Dispose()` for you. I thought this was a good treatment: > [Digging into IDisposable](http://web.archive.org/web/20090311003201/http://msdn.microsoft.com/en-us/magazine/cc163392.aspx) and this > [Understanding IDisposable](http://web.archive.org/web/20090426210049/www.marcclifton.com/tabid/79/Default.aspx) There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: [Jeffrey Richter on the Windows Memory Model](http://www.dotnetrocks.com/default.aspx?showNum=361) and Richters book [CLR via C#](http://amzn.eu/d/aitTG0A) chapter 20 has a great treatment:
Another reason to avoid setting objects to null when you are done with them is that it can actually keep them alive for longer. e.g. ``` void foo() { var someType = new SomeType(); someType.DoSomething(); // someType is now eligible for garbage collection // ... rest of method not using 'someType' ... } ``` will allow the object referred by someType to be GC'd after the call to "DoSomething" but ``` void foo() { var someType = new SomeType(); someType.DoSomething(); // someType is NOT eligible for garbage collection yet // because that variable is used at the end of the method // ... rest of method not using 'someType' ... someType = null; } ``` may sometimes keep the object alive until the end of the method. The [JIT will usually optimized away the assignment to null](http://blogs.msdn.com/clyon/archive/2004/12/01/273144.aspx), so both bits of code end up being the same.
Setting Objects to Null/Nothing after use in .NET
[ "", "c#", ".net", "vb.net", "memory-management", "null", "" ]
I'm looking for a book/site/tutorial on best practices for relational database design, tuning for performance etc. It turns out this kind of resource is a bit difficult to find; there's a lot of "here's normalization, here's ER diagrams, have at it," but not much in the way of real examples. Anyone have any ideas?
Book: [Database Design for Mere Mortals](https://rads.stackoverflow.com/amzn/click/com/0201752840)
Take a look at the [Library of Free Data Models](http://www.databaseanswers.org/data_models/index.htm). There are tons of example database designs, with diagrams that cover real-world scenarios (and some just fun/funny ones as well). I haven't ever used one as-is, but it's often been handy to get an idea of how to approach the problem of mapping the needs of the situation into a data model.
Good Resources for Relational Database Design
[ "", "sql", "database", "performance", "" ]
I have a table with a structure like the following: --- | LocationID | AccountNumber | | --- | --- | | long-guid-here | 12345 | | long-guid-here | 54321 | To pass into another stored procedure, I need the XML to look like this: ``` <root> <clientID>12345</clientID> <clientID>54321</clientID> </root> ``` The best I've been able to do so far was getting it like this: ``` <root clientID="10705"/> ``` I'm using this SQL statement: ``` SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT ``` So far, I've looked at the documentation on [the MSDN page](http://msdn.microsoft.com/en-us/library/ms345137.aspx), but I've not come out with the desired results. --- @KG, Yours gave me this output actually: ``` <root> <Location.LocationMDAccount> <clientId>10705</clientId> </Location.LocationMDAccount> </root> ``` I'm going to stick with the `FOR XML EXPLICIT` from Chris Leon for now.
try ``` SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT ```
Using SQL Server 2005 (or presumably 2008) I find for XML PATH to allow for much easier to maintain SQL than for XML Explicit (particularly once the SQL is longer). In this case: ``` SELECT AccountNumber as "clientID" FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML PATH (''), Root ('root'); ```
SQL Server 2005 For XML Explicit - Need help formatting
[ "", "sql", "xml", "sql-server-2005", "formatting", "for-xml", "" ]
I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts. Is there some way in which MySQL will return an ``` INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd') ``` statement, like what `mysqldump` will return? I don't have access to phpMyAdmin, and I preferably don't want to use `exec`, `system` or `passthru`. See [this question](https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin) for another export method
1) can you run mysqldump from exec or passthru 2) take a look at this: <http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php>
If you can use php-scripts on the server i would recommend [phpmyadmin](http://www.phpmyadmin.net/home_page/index.php). Then you can do this from the web-interface.
MySQL statement that returns a SQL statement?
[ "", "php", "mysql", "export", "" ]
I have the next function: ``` function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } ``` I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. --- `images[i].offsetWidth` returns 111 for an image of 109px width. Is this because 1px each side border?
@Sergio del Amo: Indeed, if you check out my link you'll see that you want `clientWidth` instead. @Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the `clientWidth` change: ``` // width in pixels function setImagesWidth(id, width) { var images = document.getElementById(id).getElementsByTagName("img"); var newWidth = width + "px"; for (var i = 0; i < images.length; ++i) { if (images[i].clientWidth > width) { images[i].style.width = newWidth; } } } ```
Here is, hopefully, enough sample code to give you what you want: ``` var myImage = document.getElementById("myImagesId"); var imageWidth = myImage.offsetWidth; var imageHeight = myImage.offsetHeight; ``` That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :) --- EDIT: Here, I couldn't help myself - is this what you are after? ``` function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { if(images[i].offsetWidth > width) { images[i].style.width= (width + "px"); } } } ```
Real image width with JavaScript
[ "", "javascript", "" ]
How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.
You can use `the Row_Number()` function. Its used as follows: ``` SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ``` From which it will yield a result set with a `RowID` field which you can use to page between. ``` SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 ``` etc
If you're trying to get it in one statement (the total plus the paging). You might need to explore SQL Server support for the partition by clause (windowing functions in ANSI SQL terms). In Oracle the syntax is just like the example above using row\_number(), but I have also added a partition by clause to get the total number of rows included with each row returned in the paging (total rows is 1,262): ``` SELECT rn, total_rows, x.OWNER, x.object_name, x.object_type FROM (SELECT COUNT (*) OVER (PARTITION BY owner) AS TOTAL_ROWS, ROW_NUMBER () OVER (ORDER BY 1) AS rn, uo.* FROM all_objects uo WHERE owner = 'CSEIS') x WHERE rn BETWEEN 6 AND 10 ``` Note that I have where owner = 'CSEIS' and my partition by is on owner. So the results are: ``` RN TOTAL_ROWS OWNER OBJECT_NAME OBJECT_TYPE 6 1262 CSEIS CG$BDS_MODIFICATION_TYPES TRIGGER 7 1262 CSEIS CG$AUS_MODIFICATION_TYPES TRIGGER 8 1262 CSEIS CG$BDR_MODIFICATION_TYPES TRIGGER 9 1262 CSEIS CG$ADS_MODIFICATION_TYPES TRIGGER 10 1262 CSEIS CG$BIS_LANGUAGES TRIGGER ```
Paging SQL Server 2005 Results
[ "", "sql", "sql-server-2005", "paging", "" ]
What's the most efficient way to resize large images in PHP? I'm currently using the [GD](http://en.wikipedia.org/wiki/GD_Graphics_Library) function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall). This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size). Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as [ImageMagick](http://en.wikipedia.org/wiki/ImageMagick)? Right now, the resize code looks something like this ``` function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) { // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size. $img = imagecreatefromjpeg($sourcefile); $width = imagesx( $img ); $height = imagesy( $img ); if ($width > $height) { $newwidth = $thumbwidth; $divisor = $width / $thumbwidth; $newheight = floor( $height / $divisor); } else { $newheight = $thumbheight; $divisor = $height / $thumbheight; $newwidth = floor( $width / $divisor ); } // Create a new temporary image. $tmpimg = imagecreatetruecolor( $newwidth, $newheight ); // Copy and resize old image into new image. imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height ); // Save thumbnail into a file. imagejpeg( $tmpimg, $endfile, $quality); // release the memory imagedestroy($tmpimg); imagedestroy($img); ```
People say that ImageMagick is much faster. At best just compare both libraries and measure that. 1. Prepare 1000 typical images. 2. Write two scripts -- one for GD, one for ImageMagick. 3. Run both of them a few times. 4. Compare results (total execution time, CPU and I/O usage, result image quality). Something which the best everyone else, could not be the best for you. Also, in my opinion, ImageMagick has much better API interface.
Here's a snippet from the php.net docs that I've used in a project and works fine: ``` <? function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) { // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled. // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled". // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting. // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain. // // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero. // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect. // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized. // 2 = Up to 95 times faster. Images appear a little sharp, some prefer this over a quality of 3. // 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled, just faster. // 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images. // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled. if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; } if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) { $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1); imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h); imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality); imagedestroy ($temp); } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); return true; } ?> ``` <http://us.php.net/manual/en/function.imagecopyresampled.php#77679>
Efficient JPEG Image Resizing in PHP
[ "", "php", "image", "gd", "jpeg", "" ]
I would like to be able to display some dynamic text at the mouse cursor location in a win32 app, for instance to give an X,Y coordinate that would move with the cursor as though attached. I can do this during a mousemove event using a TextOut() call for the window at the mouse coordinates and invalidate a rectange around a stored last cursor position to clear up the previous output. However this can suffer from flickering and cause problems with other things being drawn in a window such as tracker boxes. Is there a better way to do this, perhaps using the existing cursor drawing/invalidating mechanism ?
You may want to consider a small transparent window that you move to follow the mouse. In particular, since Windows 2000, [Layered](http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#layered) windows seem to be the weapon of choice (confession: no personal experience there).
You can do this via ToolTips - check out [CToolTipCtrl](http://msdn.microsoft.com/en-us/library/6b4cb3a5(VS.80).aspx). If you want flicker free tracking ToolTips then you will need to derive your own classes from CToolTipCtrl that use the [trackActivate](http://msdn.microsoft.com/en-us/library/bb760421(VS.85).aspx) messages.
How do I display dynamic text at the mouse cursor via C++/MFC in a Win32 application
[ "", "c++", "winapi", "mfc", "" ]
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): ``` typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } ``` And would fill something like this: ``` [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } ``` What is best way to copy `OldStuff` to `NewStuff`, if `OldStuff` was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. ``` GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); ``` Is there better way to accomplish this? --- Would using the `BinaryReader` class offer any performance gains over pinning the memory and using `Marshal.PtrStructure`?
From what I can see in that context, you don't need to copy `SomeByteArray` into a buffer. You simply need to get the handle from `SomeByteArray`, pin it, copy the `IntPtr` data using `PtrToStructure` and then release. No need for a copy. That would be: ``` NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; } ``` Generic version: ``` T ByteArrayToStructure<T>(byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; } ``` Simpler version (requires `unsafe` switch): ``` unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } } ```
Here is an exception safe version of the [accepted answer](https://stackoverflow.com/a/2887/184528): ``` public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct { var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } } ```
Reading a C/C++ data structure in C# from a byte array
[ "", "c#", ".net", "data-structures", "marshalling", "" ]
**My Goal** I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) **Background** I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common `IComponent` interface with a single method `DoStuff()`. Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of `IComponent`. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this 1. Application starts. 2. Check configuration file for components to load. Load them. 3. **For each component, run `DoStuff()` to initialize it and make it live its own life in their own threads.** 4. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in `DoStuff()`. It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. **Problem** When a component tries to fire up a GUI in `DoStuff()` (the exact line of code is when the component runs `Application.Run(theForm)`), the component and hence our system "hangs" at the `Application.Run()` line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. ``` public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } ``` I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. ``` public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } ``` Is it possible to spin off a GUI and return after `Application.Run()`?
**Application.Run** method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an **ApplicationContext** (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: <http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx> Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.
I'm sure this is possible if you hack at it hard enough, but I'd suggest it is not a good idea. 'Windows' (that you see on the screen) are highly coupled to processes. That is, each process which displays any GUI is expected to have a Message Loop, which processes all of the messages which are involved with creating and managing windows (things like 'clicked the button', 'closed the app', 'redraw the screen' and so on. Because of this, it is more or less assumed that if you have any message loop, it must be available for the lifetime of your process. For example windows might send you a 'quit' message, and you need to have a message loop available to handle that, even if you've got nothing on the screen. Your best bet is do it like this: Make a fake form which is never shown which is your 'main app' Start up Call Application.Run and pass in this fake form. Do your work in another thread, and fire events at the main thread when you need to do Gui stuff.
Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
[ "", "c#", ".net", "winforms", "" ]
How do I perform an `IF...THEN` in an `SQL SELECT` statement? For example: ``` SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product ```
The `CASE` statement is the closest to IF in SQL and is supported on all versions of SQL Server. ``` SELECT CAST( CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END AS bit) as Saleable, * FROM Product ``` You only need to use the `CAST` operator if you want the result as a Boolean value. If you are happy with an `int`, this works: ``` SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END as Saleable, * FROM Product ``` `CASE` statements can be embedded in other `CASE` statements and even included in aggregates. SQL Server Denali (SQL Server 2012) adds the [IIF](http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx) statement which is also available in [access](http://www.techonthenet.com/access/functions/advanced/iif.php) (pointed out by [Martin Smith](https://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-an-sql-select/6769805#6769805)): ``` SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product ```
The case statement is your friend in this situation, and takes one of two forms: The simple case: ``` SELECT CASE <variable> WHEN <value> THEN <returnvalue> WHEN <othervalue> THEN <returnthis> ELSE <returndefaultcase> END AS <newcolumnname> FROM <table> ``` The extended case: ``` SELECT CASE WHEN <test> THEN <returnvalue> WHEN <othertest> THEN <returnthis> ELSE <returndefaultcase> END AS <newcolumnname> FROM <table> ``` You can even put case statements in an order by clause for really fancy ordering.
How do I perform an IF...THEN in an SQL SELECT?
[ "", "sql", "sql-server", "t-sql", "if-statement", "case", "" ]
Every time I create an object that has a collection property I go back and forth on the best way to do it? 1. public property with a getter that returns a reference to private variable 2. explicit get\_ObjList and set\_ObjList methods that return and create new or cloned objects every time 3. explicit get\_ObjList that returns an IEnumerator and a set\_ObjList that takes IEnumerator Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List? If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks? And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property? The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has [enumeration concerns](http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx) Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better. Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?
How you expose a collection depends entirely on how users are intended to interact with it. **1)** If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question): ``` private readonly Collection<T> myCollection_ = new ...; public Collection<T> MyCollection { get { return this.myCollection_; } } ``` This strategy is used for the `Items` collections on the WindowsForms and WPF `ItemsControl` controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items. WPF also exposes some settable collections to allow users to display a collection of items they control, such as the `ItemsSource` property on `ItemsControl` (option #3 from the original question). However, this is not a common use case. **2)** If users will only be reading data maintained by the object, then you can use a readonly collection, as [Quibblesome](https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065) suggested: ``` private readonly List<T> myPrivateCollection_ = new ...; private ReadOnlyCollection<T> myPrivateCollectionView_; public ReadOnlyCollection<T> MyCollection { get { if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ } return this.myPrivateCollectionView_; } } ``` Note that `ReadOnlyCollection<T>` provides a live view of the underlying collection, so you only need to create the view once. If the internal collection does not implement `IList<T>`, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator: ``` public IEnumerable<T> MyCollection { get { foreach( T item in this.myPrivateCollection_ ) yield return item; } } ``` This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection. **3)** Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question): ``` private T[] myArray_; public T[] GetMyArray( ) { T[] copy = new T[this.myArray_.Length]; this.myArray_.CopyTo( copy, 0 ); return copy; // Note: if you are using LINQ, calling the 'ToArray( )' // extension method will create a copy for you. } ``` You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding `SetMyArray( T[] array )` method, or use a custom indexer: ``` public T this[int index] { get { return this.myArray_[index]; } set { // TODO: validate new value; raise change event; etc. this.myArray_[index] = value; } } ``` (of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :)
I usually go for this, a public getter that returns System.Collections.ObjectModel.ReadOnlyCollection: ``` public ReadOnlyCollection<SomeClass> Collection { get { return new ReadOnlyCollection<SomeClass>(myList); } } ``` And public methods on the object to modify the collection. ``` Clear(); Add(SomeClass class); ``` If the class is supposed to be a repository for other people to mess with then I just expose the private variable as per method #1 as it saves writing your own API, but I tend to shy away from that in production code.
How to expose a collection property?
[ "", "c#", ".net", "architecture", "" ]
I have something like this: ``` barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); ``` Now, how would you stop that animation (the `DoubleAnimation`)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...
To stop it, call `BeginAnimation` again with the second argument set to `null`.
When using storyboards to control an animation, make sure you set the second parameter to true in order to set the animation as controllable: ``` public void Begin( FrameworkContentElement containingObject, **bool isControllable** ) ```
How to stop an animation in C# / WPF?
[ "", "c#", "wpf", "" ]
I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order. I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough. I could do this: ``` select timefield from entries where uid = ? order by timefield; ``` and look at every 150th row. Or I could do 20 separate queries and use `limit 1` and `offset`. But there must be a more efficient solution...
Michal Sznajder almost had it, but you can't use column aliases in a WHERE clause in SQL. So you have to wrap it as a derived table. I tried this and it returns 20 rows: ``` SELECT * FROM ( SELECT @rownum:=@rownum+1 AS rownum, e.* FROM (SELECT @rownum := 0) r, entries e) AS e2 WHERE uid = ? AND rownum % 150 = 0; ```
Something like this came to my mind ``` select @rownum:=@rownum+1 rownum, entries.* from (select @rownum:=0) r, entries where uid = ? and rownum % 150 = 0 ``` I don't have MySQL at my hand but maybe this will help ...
Distribution of table in time
[ "", "sql", "mysql", "" ]
I am getting the following error: > Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: ``` <?php include("../includes/connect.php"); $query = "SELECT * from story"; $result = mysql_query($query) or die(mysql_error()); echo "<h1>Delete Story</h1>"; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>'; echo '<br /><i>'.$row[2].'</i>'; } } else { echo "No stories available."; } ?> ``` The `connect.php` file contains my MySQL connect calls that are working fine with my `INSERT` queries in another portion of the software. If I comment out the `$result = mysql_query` line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
> And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error?
Change the include() to require(). **If the "connect.php" file can't be require()d, the script will fail** with a fatal error, whereas **include() only generates a warning**. If the username you're passing to mysql\_connect() isn't "apache", an incorrect path to the connect script is the most common way to get this type of error.
MySQL/Apache Error in PHP MySQL query
[ "", "php", "mysql", "apache", "" ]
What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language.
The name reflection is used to describe code which is able to inspect other code in the same system (or itself). For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. So, to give you a code example of this in Java (imagine the object in question is foo) : ``` Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); ``` One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. There are some good reflection examples to get you started at <http://docs.oracle.com/javase/tutorial/reflect/index.html> And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. **Update from a comment:** > The ability to inspect the code in the system and see object types is > not reflection, but rather Type Introspection. Reflection is then the > ability to make modifications at runtime by making use of > introspection. The distinction is necessary here as some languages > support introspection, but do not support reflection. One such example > is C++
> **Reflection** is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime. For example, all objects in Java have the method `getClass()`, which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an `Object`) - this might seem trivial, but such reflection is not possible in less dynamic languages such as `C++`. More advanced uses lets you list and call methods, constructors, etc. Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files. Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.
What is reflection and why is it useful?
[ "", "java", "reflection", "terminology", "" ]
Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far?
Use [backtracking](http://www.cs.bu.edu/teaching/alg/maze/) by keeping a stack of previous direction decisions.
The simplest (to implement) algorithm would be to just keep a stack of locations you've been at, and the route you took from each, unless backtracking gives you that information. To go back, just pop off old locations from the stack and check for more exits from that location until you find an old location with an untested exit. By consistently testing the exits in the same order each time, if you know that backtracking to a location comes from down (ie. last time you were at the old location you went down), then you simply pick the next direction after *down*. I am not entirely sure what you mean by *going back too far* though, I would assume you would want to go back to the previous place you have untested routes, is that not what you want? Note that unless you try to keep track of the path from the starting point to your current location, and avoiding those squares when you try to find new routes, you might end up going in circle, which would eventually make the stack too large. A simple recursive method which marks the path it takes and never enters areas that are marked can easily do this. Also, if your *thing* that moves through the maze is slightly smarter than just being able to move, and hit (stop at) walls, in that it can see from its current point in all directions, I have other algorithms that might help.
How to traverse a maze programmatically when you've hit a dead end
[ "", "c#", "artificial-intelligence", "maze", "" ]
Actually, this question seems to have two parts: * How to implement pattern matching? * How to implement [send and receive](http://erlang.org/doc/reference_manual/expressions.html#6.9) (i.e. the Actor model)? For the pattern matching part, I've been looking into various projects like [App](http://members.cox.net/nelan/app.html) and [Prop](http://www.cs.nyu.edu/leunga/papers/research/prop/prop.html). These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The [Felix](http://felix-lang.org/) language also seems to support pattern matching pretty well, but isn't really C++. As for the [Actor model](http://en.wikipedia.org/wiki/Actor_model), there are existing implementations like ACT++ and [Theron](http://theron.ashtonmason.net/), but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers]. Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching. Right now, I can use the following code to send a message: ``` (new Message(this)) ->set("foo", "bar") ->set("baz", 123) ->send(recipient); ``` And the following to do simple pattern matching (`qDebug` and `qPrintable` are Qt-specific): ``` receive_and_match(m) match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); } or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); } or_match_ignore end_receive ``` However, this looks a bit hackish to me, and isn't very robust. How would you do it? Did I miss any existing work?
One of the important things about erlang is how the features are used to make robust systems. The send/recieve model is no-sharing, and explicitly copying. The processes themselves are lightweight threads. If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads. If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety. Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want. Although if you are not careful you end up with xml over pipes :) Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet. The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
> As for the Actor model, there are > existing implementations like ACT++ > and Theron, but I couldn't find > anything but papers on the former, and > the latter is single-threaded only. As the author of Theron, I was curious why you believe it's single-threaded? > Personally, I've implemented actors > using threading and a thread-safe > message queue That's how Theron is implemented.. :-) Ash
How would you implement Erlang-like send and receive in C++?
[ "", "c++", "erlang", "" ]
I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be. What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense: ![form design](https://i.stack.imgur.com/bVRJB.png) Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a *lot* of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?
A tidier way is to create separate forms for each 'pane' and, in each form constructor, set ``` this.TopLevel = false; this.FormBorderStyle = FormBorderStyle.None; this.Dock = DockStyle.Fill; ``` That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control. Perhaps the main form could use a `SplitContainer` with a static `TreeView` in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using `Hide/Show` or `BringToFront/SendToBack` methods. ``` SeparateForm f = new SeparateForm(); MainFormSplitContainer.Panel2.Controls.Add(f); f.Show(); ```
Greg Hurlman wrote: > Why not just show/hide the proper container when a node is selected in the grid? Have the containers all sized appropriately in the same spot, and hide all but the default, which would be preselected in the grid on load. Unfortunately, that's what I'm trying to avoid. I'm looking for an easy way to handle the interface during design time, with minimal reformatting code needed to get it working during run time. I like Duncan's answer because it means the design of each node's interface can be kept *completely* separate. This means I don't get overlap on the snapping guidelines and other design time advantages.
How to create a tree-view preferences dialog type of interface in C#?
[ "", "c#", "user-interface", "" ]
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly?
If you use JavaScript to open the popup, you can use something like this: ``` var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED } ```
I tried a number of the examples above, but I could not get them to work with Chrome. This simple approach seems to work with Chrome 39, Firefox 34, Safari 5.1.7, and IE 11. Here is the snippet of code from our JS library. ``` openPopUp: function(urlToOpen) { var popup_window=window.open(urlToOpen,"myWindow","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=400, height=400"); try { popup_window.focus(); } catch (e) { alert("Pop-up Blocker is enabled! Please add this site to your exception list."); } } ```
How can I detect if a browser is blocking a popup?
[ "", "javascript", "html", "popup", "" ]
I discovered [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming) more than 5 years ago and got a huge kick out of reading [Modern C++ Design](https://rads.stackoverflow.com/amzn/click/com/0201704315) but I never found an opertunity to use it in real life. Have *you* ever used this technique in real code? > Contributors to [Boost](http://www.boost.org/) need not apply ;o)
I once used template metaprogramming in C++ to implement a technique called "symbolic perturbation" for dealing with degenerate input in geometric algorithms. By representing arithmetic expressions as nested templates (i.e. basically by writing out the parse trees by hand) I was able to hand off all the expression analysis to the template processor. Doing this kind of thing with templates is more efficient than, say, writing expression trees using objects and doing the analysis at runtime. It's faster because the modified (perturbed) expression tree is then available to the optimizer at the same level as the rest of your code, so you get the full benefits of optimization, both within your expressions but also (where possible) between your expressions and the surrounding code. Of course you could accomplish the same thing by implementing a small DSL (domain specific language) for your expressions and the pasting the translated C++ code into your regular program. That would get you all the same optimization benefits and also be more legible -- but the tradeoff is that you have to maintain a parser.
I've found policies, described in Modern C++ Design, really useful in two situations: 1. When I'm developing a component that I expect will be reused, but in a slightly different way. Alexandrescu's suggestion of using a policy to reflect a design fits in really well here - it helps me get past questions like, "I could do this with a background thread, but what if someone later on wants to do it in time slices?" Ok fine, I just write my class to accept a ConcurrencyPolicy and implement the one I need at the moment. Then at least I know the person who comes behind me can write and plug in a new policy when they need it, without having to totally rework my design. Caveat: I have to reign myself in sometimes or this can get out of control -- remember the [YAGNI](http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it "YAGNI") principle! 2. When I'm trying to refactor several similar blocks of code into one. Usually the code will be copy-pasted and modified slightly because it would have had too much if/else logic otherwise, or because the types involved were too different. I've found that policies often allow for a clean one-fits-all version where traditional logic or multiple inheritance would not.
Does anyone use template metaprogramming in real life?
[ "", "c++", "templates", "template-meta-programming", "" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. ## Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: * [Tkinter](http://wiki.python.org/moin/TkInter) - based on [Tk GUI toolkit](http://www.tcl.tk/). > De-facto standard GUI library for python, free for commercial projects. * [WxPython](http://www.wxpython.org/) - based on [WxWidgets](http://www.wxwidgets.org/). > Popular, and free for commercial projects. * [Qt](https://www.qt.io) using the [PyQt bindings](https://riverbankcomputing.com/software/pyqt/intro) or [Qt for Python](https://www.qt.io/qt-for-python). > The former is not free for commercial projects. The latter is less mature, but can be used for free. > > Qt itself supposedly supports `Android` and `iOS` as well, but achiving same with it's bindings should be tricky. * [Kivy](https://github.com/kivy/kivy) written in Python for Python (update 2023). > Supposedly supports `Android` and `iOS` as well. > **Note** that users of `WxWidgets` (hence `WxPython` users), often need to use `WxQt` as well, because `WxWidgets`'s own GUI is not yet at `Qt`'s level (at time of writting). Complete list is at <http://wiki.python.org/moin/GuiProgramming> ## Stand-alone/ single executables **For all platforms:** * [PyInstaller](https://www.pyinstaller.org/) - The most active (which could also be used with `PyQt`) * [fbs](https://build-system.fman.io) - if you chose Qt above (commercial, with free plan) **For Windows:** * [py2exe](http://www.py2exe.org/) - used to be the most popular **For Linux:** * [Freeze](http://wiki.python.org/moin/Freeze) - works the same way like py2exe but targets Linux platform **For MacOS:** * [py2app](https://pythonhosted.org/py2app/) - again, works like py2exe but targets Mac OS
Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use. <http://www.pyinstaller.org/> Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.
Create a directly-executable cross-platform GUI app using Python
[ "", "python", "user-interface", "deployment", "tkinter", "release-management", "" ]
For parsing player commands, I've most often used the [split](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29) method to split a string by delimiters and then to then just figure out the rest by a series of `if`s or `switch`es. What are some different ways of parsing strings in Java?
I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this: 1. Read in the string * Split the string into tokens * Use a dictionary to convert synonyms to a common form * For example, convert "hit", "punch", "strike", and "kick" all to "hit" * Perform actions on an unordered, inclusive base * **Unordered** - "punch the monkey in the face" is the same thing as "the face in the monkey punch" * **Inclusive** - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action.
I really like regular expressions. As long as the command strings are fairly simple, you can write a few regexes that could take a few pages of code to manually parse. I would suggest you check out <http://www.regular-expressions.info> for a good intro to regexes, as well as specific examples for Java.
What are the different methods to parse strings in Java?
[ "", "java", "string", "parsing", "" ]
I'm absolutely stunned by the fact that MS just couldn't get it right to navigate to the definition of a method, when you're combining C# and VB projects in one solution. If you're trying to navigate from VB to C#, it brings up the "Object Explorer", and if from C# to VB, it generates a metadata file. Honestly, what is so complicated about jumping between different languages, especially if they're supposedly using the same CLR? Does anyone know why this is, or if there's any workaround? Did they get it right in VS 2008? --- @Keith, I am afraid you may be right about your answer. I am truly stunned that Microsoft screwed this up so badly. Does anyone have any ideas for a workaround? --- @Mladen Mihajlovic - that's exactly the situation I'm describing. Try it out yourself; project references don't make a shred of difference.
This is general to both languages. * F12 in VB.Net always takes you to the object browser * F12 in C# always takes you to a meta-data definition This is a deliberate mechanism to try and match expected behaviour for upgrading users. The C# way gives you the right information, but the VB way is what users of VBA or VB6 will expect. The behaviour is the same in VS2008. These are the rules for external projects, both should take you to the code if it is in the same solution. --- You're quite right - VB projects treat C# projects as external and vice versa - you can't navigate from code in one to the other. I've tested this in the latest VS2008 and it's still an issue. It also fails to get complete meta-data. Add a method to your C# code and it won't appear in VB's intellisense until you compile the C# assembly. This is similar to how components appear in the toolstrip, so I figure the normal navigate to code functionality is a feature of code with a common compilers, and everything else uses some kind of reflection. As long as you're still building a PDB it should be able to find the files, I guess it doesn't because they need it to support release builds too. It couldn't find the line of code without the PDB lookups.
Make sure that your reference is to the VB *project* and not just a DLL file.
Intellisense in Visual Studio 2005 between C# and VB - can't navigate to definitions
[ "", "c#", "vb.net", "visual-studio", "intellisense", "" ]
I have a class with a bunch of properties that look like this: ``` public string Name { get { return _name; } set { IsDirty = true; _name = value; } } ``` It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour: ``` [MakesDirty] public string Name { get; set; } ```
**No. Not without writing considerably more (arcane?) code than the original version** (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with. MS has the same need for [raising events when a property is changed](http://msdn.microsoft.com/en-us/library/ms229614.aspx). INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet does ``` set { _name = value; NotifyPropertyChanged("Name"); } ``` If it was possible, I'd figure those smart guys at MS would already have something like that in place..
You could try setting up a code snippet to make it easy to create those.
c# properties with repeated code
[ "", "c#", "properties", "attributes", "" ]
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts?
SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail. > The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window Try capturing the focus with [SetCapture](http://msdn.microsoft.com/en-us/library/ms646262.aspx) prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.
> What is the difference between SetForeGroundWindow, SetActiveWindow, and BringWindowToTop? It appears as if they all do the same thing. According to MSDN, SetForeGroundWindow will activate the window and direct keyboard focus to it. This attempts to work even when your process is in the background. SetActiveWindow does the same thing as SetForeGroundWindow, but it doesn't do anything if your application isn't the frontmost application. Finally, BringWindowToTop only brings the window to the top, and doesn't change the keyboard focus.
Bringing Window to the Front in C# using Win32 API
[ "", "c#", "winapi", "" ]
I'd love to know if there is such a thing as a Gecko.NET ;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to `navigateto(fancy_url);`). I'd love to use Firefox or WebKit. Anybody tried this? **UPDATE**: Please bear in mind that although it is possible to embed Gecko using the mentioned controls, it is still impossible to **print** while using Gecko. **UPDATE March 2010**: It’s still not possible to print natively using GeckoFX, however a couple of methods exist that *may* be enough, depending upon what you’re trying to do. See: <http://geckofx.org/viewtopic.php?id=796> for more information. **UPDATE October 2013**: I am no longer doing Windows development so I have no interest in this, but seems like the development of Gecko can be found here: <https://bitbucket.org/geckofx> and it seems to be recently updated. Leaving this here for future Windows devs ;) **UPDATE January 2017**: I have gotten an email from a company called [TeamDev](http://www.teamdev.com). They created a Chromium-based .NET browser component called "DotNetBrowser" which can be used to display modern web pages in Windows Forms applications. To quote the email directly: > Here are some details about the component, which might be helpful: 1. DotNetBrowser is based on Chromium, thus supporting HTML5, CSS3, JS and the latest web standards. The underlying Chromium version of the library is regularly updated. 2. The component is suitable for WPF as well as Windows Forms desktop applications, and works both for C# and VB.NET. 3. The library is licensed commercially, however free licences are provided for Open Source and academic projects. **Disclaimer:** *I have not used this DotNetBrowser for I no longer do Windows Development but may be worth checking if you're looking for a solution to this.*
<http://code.google.com/p/geckofx/> This is a nice .NET-wrapped version of Gecko
It certainly is possible. All you need to do is register the Mozilla ActiveX control (mozctlx.dll I believe), and you can drag it onto your form as any ActiveX control. The programming interface is similar (though not identical) to the IE one, and you can even use the Microsoft.MSHTML.dll managed library for control in some cases. I believe this is packaged with Firefox. If not, you can get just the embeddable bits from Mozilla as well. Just do a Google search for Mozilla ActiveX control or Mozilla Embedding C# and that should take you down the right path.
Is it possible to Embed Gecko or Webkit in a Windows Form just like a WebView?
[ "", "c#", ".net", "winforms", "webkit", "gecko", "" ]
C++ 0x has template aliases (sometimes referred to as template typedefs). See [here](http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates). Current spec of C++ does not. What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
> What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ? The canonical way is to use a metafunction like thus: ``` template <typename T> struct my_string_map { typedef std::map<std::string, T> type; }; // Invoke: my_string_map<int>::type my_str_int_map; ``` This is also used in the STL (`allocator::rebind<U>`) and in many libraries including Boost. We use it extensively in a [bioinformatical library](http://www.seqan.de/dddoc/html/index.html). It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides. (EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)
> ``` > template <typename T> > struct my_string_map : public std::map<std::string,T> > { > }; > ``` You shouldn't inherit from classes that do not have a virtual destructor. It's related to destructors in derived classes not being called when they should be and you could end up with unallocated memory. That being said you could \*\*\*\*\*probably\*\*\*\*\* get away with it in the instance above because you're not adding any more data to your derived type. Note that this is not an endorsement. I still advice you **don't** do it. The fact that you *can* do it doesn't mean you *should*. EDIT: Yes, this is a reply to ShaChris23's post. I probably missed something because it showed up above his/her message instead of below.
Template typedefs - What's your work around?
[ "", "c++", "templates", "type-safety", "" ]
1. Is it possible to capture Python interpreter's output from a Python script? 2. Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into?
If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation: ``` python script_a.py | python script_b.py ``` This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on [standard streams](http://en.wikipedia.org/wiki/Standard_streams) on Wikipedia. If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication): ``` import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() ``` See the Python [subprocess](http://docs.python.org/lib/module-subprocess.html) module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard [file objects](http://docs.python.org/lib/bltin-file-objects.html). For use with pipes, reading from standard input as [lassevk](https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939) suggested you'd do something like this: ``` import sys x = sys.stderr.readline() y = sys.stdin.readline() ``` sys.stdin and sys.stdout are standard file objects as noted above, defined in the [sys](http://docs.python.org/lib/module-sys.html) module. You might also want to take a look at the [pipes](http://docs.python.org/lib/module-pipes.html) module. Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into [polling](http://docs.python.org/lib/poll-objects.html) which unfortunately does not work in windows, but I'm sure there's some alternative out there.
I think I can point you to a good answer for the first part of your question. > *1.  Is it possible to capture Python interpreter's output from a Python > script?* The answer is "*yes*", and personally I like the following lifted from the examples in the *[PEP 343 -- The "with" Statement](http://www.python.org/dev/peps/pep-0343/)* document. ``` from contextlib import contextmanager import sys @contextmanager def stdout_redirected(new_stdout): saved_stdout = sys.stdout sys.stdout = new_stdout try: yield None finally: sys.stdout.close() sys.stdout = saved_stdout ``` And used like this: ``` with stdout_redirected(open("filename.txt", "w")): print "Hello world" ``` A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file: ``` with stdout_redirected(open("filename.txt", "w")): print "Hello world" print "screen only output again" with stdout_redirected(open("filename.txt", "a")): print "Hello world2" ``` Of course, the above could also be extended to also redirect `sys.stderr` to the same or another file. Also see this [answer](https://stackoverflow.com/a/16571630/355230) to a related question.
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
[ "", "python", "windows", "cmd", "" ]
By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome.
Rather than using `Ctrl` + `K`, `X` you can also just type `prop` and then hit `Tab` twice.
Visual Studio also has a feature that will generate a Property from a private variable. If you right-click on a variable, in the context menu that pops up, [click on the "Refactor" item, and then choose *Encapsulate Field...*](https://stackoverflow.com/questions/3017/how-can-we-generate-getters-and-setters-in-visual-studio/29917170#29917170). This will create a getter/setter property for a variable. I'm not too big a fan of this technique as it is a little bit awkward to use if you have to create a lot of getters/setters, and it puts the property directly below the private field, which bugs me, because I usually have all of my private fields grouped together, and this Visual Studio feature breaks my class' formatting.
How can we generate getters and setters in Visual Studio?
[ "", "c#", "visual-studio", "setter", "getter", "" ]
I'm using [PopBox](http://www.c6software.com/Products/PopBox/) for magnifying thumbnails on my page. But I want my website to work even for users which turned javascript off. I tried to use the following HTML code: ``` <a href="image.jpg"> <img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/> </a> ``` Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work. How do I do that?
Just put the onclick on the a-tag: ``` <a href="image.jpg onclick="Pop()"; return false;"><img ...></a> ``` Make sure to return `false` either at the end of the function (here `Pop`) or inline like in the above example. This prevents the user from being redirected to the link by the `<a>`'s default behaviour.
Put the onclick event onto the link itself, and return false from the handler if you don't want the default behavior to be executed (the link to be followed)
Unobtrusive Javascript: Removing links if Javascript is enabled
[ "", "javascript", "" ]
We have an issue using the `PEAR` libraries on `Windows` from `PHP`. Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in `Mail.php`. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files: ``` require_once('Mail.php'); ``` Rather than: ``` require_once('/path/to/pear/Mail.php'); ``` This causes issues in the administration module of the site, where there is a `mail.php` file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include `Mail.php` we "accidentally" include mail.php. Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively? We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing. > (We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5))
having 2 files with the same name in the include path is not a good idea, rename your files so the files that you wrote have different names from third party libraries. anyway for your current situation I think by changing the order of paths in your include path, you can fix this. PHP searches for the files in the include paths, one by one. when the required file is found in the include path, PHP will stop searching for the file. so in the administration section of your application, if you want to include the PEAR Mail file, instead of the mail.php that you wrote, change your include path so the PEAR path is before the current directory. do something like this: ``` <?php $path_to_pear = '/usr/share/php/pear'; set_include_path( $path_to_pear . PATH_SEPARATOR . get_include_path() ); ?> ```
As it's an OS level thing, I don't believe there's an easy way of doing this. You could try changing your include from `include('Mail.php');` to `include('./Mail.php');`, but I'm not certain if that'll work on a Windows box (not having one with PHP to test on).
Including files case-sensitively on Windows from PHP
[ "", "php", "windows", "apache", "pear", "" ]
I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB. My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page. How do you check your URL's for SQL Injection attacks?
I think it depends on what level you're looking to check/prevent SQL Injection at. At the top level, you can use URLScan or some Apache Mods/Filters (somebody help me out here) to check the incoming URLs to the web server itself and immediately drop/ignore requests that match a certain pattern. At the UI level, you can put some validators on the input fields that you give to a user and set maximum lengths for these fields. You can also white list certain values/patterns as needed. At the code level, you can use parametrized queries, as mentioned above, to make sure that string inputs go in as purely string inputs and don't attempt to execute T-SQL/PL-SQL commands. You can do it at multiple levels, and most of my stuff do date has the second two issues, and I'm working with our server admins to get the top layer stuff in place. Is that more along the lines of what you want to know?
I don't. Instead, I use parametrized SQL Queries and rely on the database to clean my input. I know, this is a novel concept to PHP developers and MySQL users, but people using real databases have been doing it this way for years. For Example (Using C#) ``` // Bad! SqlCommand foo = new SqlCommand("SELECT FOO FROM BAR WHERE LOL='" + Request.QueryString["LOL"] + "'"); //Good! Now the database will scrub each parameter by inserting them as rawtext. SqlCommand foo = new SqlCommany("SELECT FOO FROM BAR WHERE LOL = @LOL"); foo.Parameters.AddWithValue("@LOL",Request.QueryString["LOL"]); ```
How do you check your URL for SQL Injection Attacks?
[ "", "sql", "sql-server", "" ]
I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?
I really like [log4php](http://logging.apache.org/log4php/) for logging, even though it's not yet out of the incubator. I use log4net in just about everything, and have found the style quite natural for me. With regard to system crashes, you can log the error to multiple destinations (e.g., have appenders whose threshold is CRITICAL or ERROR that only come into play when things go wrong). I'm not sure how fail-safe the existing appenders are--if the database is down, how does that appender fail?--but you could quite easily write your own appender that will fail gracefully if it's unable to log.
You could use [set\_error\_handler](http://www.php.net/manual/en/function.set-error-handler.php) to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if the database handler triggered the exception however. You could also use [error\_log](http://www.php.net/manual/en/function.error-log.php) to log your errors. It has a choice of message destinations including: > Quoted from [error\_log](http://www.php.net/manual/en/function.error-log.php) > > 1. PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error\_log configuration directive is set to. This is the default option. > 2. Sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra\_headers is used. > 3. Appended to the file destination . A newline is not automatically added to the end of the message string. *Edit: Does markdown have a noparse tag for underscores?*
How do I log uncaught exceptions in PHP?
[ "", "php", "exception", "error-handling", "error-logging", "" ]
I'm trying to find a simple way to change the colour of the text and background in `listview` and `treeview` controls in WTL or plain Win32 code. I really don't want to have to implement full owner drawing for these controls, simply change the colours used. I want to make sure that the images are still drawn with proper transparency. Any suggestions?
Have a look at the following macros: [ListView\_SetBkColor](http://msdn.microsoft.com/en-us/library/bb775063%28VS.85%29.aspx) [ListView\_SetTextColor](http://msdn.microsoft.com/en-us/library/bb775116%28VS.85%29.aspx>) [TreeView\_SetBkColor](http://msdn.microsoft.com/en-us/library/bb760036%28VS.85%29.aspx) [TreeView\_SetTextColor](http://msdn.microsoft.com/en-us/library/bb760131%28VS.85%29.aspx)
There are also appropriate methods of the `CListViewCtrl` and `CTreeViewCtrl` wrapper classes: * GetBkColor * SetBkColor
Simplest way to change listview and treeview colours
[ "", "c++", "winapi", "wtl", "" ]
How do I call a function, using a string with the function's name? For example: ``` import foo func_name = "bar" call(foo, func_name) # calls foo.bar() ```
Given a module `foo` with method `bar`: ``` import foo bar = getattr(foo, 'bar') result = bar() ``` [`getattr`](https://docs.python.org/library/functions.html#getattr) can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
* Using [`locals()`](http://docs.python.org/library/functions.html#locals), which returns a dictionary with the current local symbol table: ``` locals()["myfunction"]() ``` * Using [`globals()`](http://docs.python.org/library/functions.html#globals), which returns a dictionary with the global symbol table: ``` globals()["myfunction"]() ```
Calling a function of a module by using its name (a string)
[ "", "python", "object", "reflection", "" ]
What are attributes in .NET, what are they good for, and how do I create my own attributes?
Metadata. Data about your objects/methods/properties. For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately. ``` public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject .SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject .SomeDate; } } } ``` Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components. However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so: ``` [Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } ``` Tells the designer not to list this in the available properties in the Properties window at design time for example. You *could* also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods. ``` public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } ``` Declaring them is easy, just make a class that inherits from Attribute. ``` public class DisplayOrderAttribute : Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } ``` And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you. **NOTE:** Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly). So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them.
Many people have answered but no one has mentioned this so far... Attributes are used heavily with reflection. Reflection is already pretty slow. It is *very worthwhile* marking your custom attributes as being `sealed` classes to improve their runtime performance. It is also a good idea to consider where it would be appropriate to use place such an attribute, and to attribute your attribute (!) to indicate this via [`AttributeUsage`](http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspx). The list of available attribute usages might surprise you: * Assembly * Module * Class * Struct * Enum * Constructor * Method * Property * Field * Event * Interface * Parameter * Delegate * ReturnValue * GenericParameter * All It's also cool that the AttributeUsage attribute is part of the AttributeUsage attribute's signature. Whoa for circular dependencies! ``` [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute ```
What are attributes in .NET?
[ "", "c#", ".net", "glossary", ".net-attributes", "" ]
I'm taking the leap: my PHP scripts will ALL fail gracefully! At least, that's what I'm hoping for...` I don't want to wrap (practically) every single line in `try...catch` statements, so I think my best bet is to make a custom error handler for the beginning of my files. I'm testing it out on a practice page: ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); echo($imAFakeVariable); ``` This works fine, returning: > Sorry, an error has occurred on line 17. The function that caused the > error says Undefined variable: imAFakeVariable. However, this setup doesn't work for undefined functions. ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); imAFakeFunction(); ``` This returns: > Fatal error: Call to undefined function: imafakefunction() in > /Library/WebServer/Documents/experimental/errorhandle.php on line 17 Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?
`set_error_handler` is designed to handle errors with codes of: `E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE`. This is because `set_error_handler` is meant to be a method of reporting errors thrown by the *user* error function `trigger_error`. However, I did find this comment in the manual that may help you: > "The following error types cannot be handled with a user defined function: `E_ERROR`, `E_PARSE`, `E_CORE_ERROR`, `E_CORE_WARNING`, `E_COMPILE_ERROR`, `E_COMPILE_WARNING`, and most of `E_STRICT` raised in the file where `set_error_handler()` is called." > > This is not exactly true. `set_error_handler()` can't handle them, but `ob_start()` can handle at least `E_ERROR`. > > ``` > <?php > > function error_handler($output) > { > $error = error_get_last(); > $output = ""; > foreach ($error as $info => $string) > $output .= "{$info}: {$string}\n"; > return $output; > } > > ob_start('error_handler'); > > will_this_undefined_function_raise_an_error(); > > ?> > ``` Really though these errors should be silently reported in a file, for example. Hopefully you won't have many `E_PARSE` errors in your project! :-) As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.
I guess you needs to use `register_shutdown_function` also For example: ``` register_shutdown_function( array( $this, 'customError' ));. function customError() { $arrStrErrorInfo = error_get_last(); print_r( $arrStrErrorInfo ); } ```
How to catch undefined functions with set_error_handler in PHP
[ "", "php", "" ]
I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
If you mean you want them back as a string, in that format; ``` SELECT CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) FROM customers ``` [Here are the other format options](http://msdn.microsoft.com/en-us/library/ms187928.aspx)
``` select datepart(month,getdate()) -- integer (1,2,3...) ,datepart(year,getdate()) -- integer ,datename(month,getdate()) -- string ('September',...) ```
Get month and year from a datetime in SQL Server 2005
[ "", "sql", "sql-server", "" ]
I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it. Is it bad? Are there unintended consequences of doing so? ``` public interface Foo { Bar GetBar(); } public struct Fubar : Foo { public Bar GetBar() { return new Bar(); } } ```
There are several things going on in this question... It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: <https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface> In general, structs should be used for objects that have value-type semantics. By implementing an interface on a struct you can run into boxing concerns as the struct is cast back and forth between the struct and the interface. As a result of the boxing, operations that change the internal state of the struct may not behave properly.
Since no one else explicitly provided this answer I will add the following: **Implementing** an interface on a struct has no negative consequences whatsoever. Any *variable* of the interface type used to hold a struct will result in a boxed value of that struct being used. If the struct is immutable (a good thing) then this is at worst a performance issue unless you are: * using the resulting object for locking purposes (an immensely bad idea any way) * using reference equality semantics and expecting it to work for two boxed values from the same struct. Both of these would be unlikely, instead you are likely to be doing one of the following: ### Generics Perhaps many reasonable reasons for structs implementing interfaces is so that they can be used within a **generic** context with *[constraints](http://msdn.microsoft.com/en-us/library/d5x73970.aspx)*. When used in this fashion the variable like so: ``` class Foo<T> : IEquatable<Foo<T>> where T : IEquatable<T> { private readonly T a; public bool Equals(Foo<T> other) { return this.a.Equals(other.a); } } ``` 1. Enable the use of the struct as a type parameter * so long as no other constraint like `new()` or `class` is used. 2. Allow the avoidance of boxing on structs used in this way. Then this.a is NOT an interface reference thus it does not cause a box of whatever is placed into it. Further when the c# compiler compiles the generic classes and needs to insert invocations of the instance methods defined on instances of the Type parameter T it can use the [constrained](http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained.aspx) opcode: > If thisType is a value type and thisType implements method then ptr is passed unmodified as the 'this' pointer to a call method instruction, for the implementation of method by thisType. This avoids the boxing and since the value type is implementing the interface is *must* implement the method, thus no boxing will occur. In the above example the `Equals()` invocation is done with no box on this.a1. ### Low friction APIs Most structs should have primitive-like semantics where bitwise identical values are considered equal2. The runtime will supply such behaviour in the implicit `Equals()` but this can be slow. Also this implicit equality is *not* exposed as an implementation of `IEquatable<T>` and thus prevents structs being used easily as keys for Dictionaries unless they explicitly implement it themselves. It is therefore common for many public struct types to declare that they implement `IEquatable<T>` (where `T` is them self) to make this easier and better performing as well as consistent with the behaviour of many existing value types within the CLR BCL. All the primitives in the BCL implement at a minimum: * `IComparable` * `IConvertible` * `IComparable<T>` * `IEquatable<T>` (And thus `IEquatable`) Many also implement `IFormattable`, further many of the System defined value types like DateTime, TimeSpan and Guid implement many or all of these as well. If you are implementing a similarly 'widely useful' type like a complex number struct or some fixed width textual values then implementing many of these common interfaces (correctly) will make your struct more useful and usable. ## Exclusions Obviously if the interface strongly implies *mutability* (such as `ICollection`) then implementing it is a bad idea as it would mean that you either made the struct mutable (leading to the sorts of errors described already where the modifications occur on the boxed value rather than the original) or you confuse users by ignoring the implications of the methods like `Add()` or throwing exceptions. Many interfaces do NOT imply mutability (such as `IFormattable`) and serve as the idiomatic way to expose certain functionality in a consistent fashion. Often the user of the struct will not care about any boxing overhead for such behaviour. ## Summary When done sensibly, on immutable value types, implementation of useful interfaces is a good idea --- ### Notes: 1: Note that the compiler may use this when invoking virtual methods on variables which are *known* to be of a specific struct type but in which it is required to invoke a virtual method. For example: ``` List<int> l = new List<int>(); foreach(var x in l) ;//no-op ``` The enumerator returned by the List is a struct, an optimization to avoid an allocation when enumerating the list (With some interesting [consequences](http://www.eggheadcafe.com/software/aspnet/31702392/c-compiler-challenge--s.aspx)). However the semantics of foreach specify that if the enumerator implements `IDisposable` then `Dispose()` will be called once the iteration is completed. Obviously having this occur through a boxed call would eliminate any benefit of the enumerator being a struct (in fact it would be worse). Worse, if dispose call modifies the state of the enumerator in some way then this would happen on the boxed instance and many subtle bugs might be introduced in complex cases. Therefore the IL emitted in this sort of situation is: ``` <pre> IL_0001: newobj System.Collections.Generic.List<System.Int32>..ctor IL_0006: stloc.0 IL_0007: nop IL_0008: ldloc.0 IL_0009: callvirt System.Collections.Generic.List<System.Int32>.GetEnumerator IL_000E: stloc.2 IL_000F: br.s IL_0019 IL_0011: ldloca.s 02 IL_0013: call System.Collections.Generic.List<System.Int32>.get_Current IL_0018: stloc.1 IL_0019: ldloca.s 02 IL_001B: call System.Collections.Generic.List<System.Int32>.MoveNext IL_0020: stloc.3 IL_0021: ldloc.3 IL_0022: brtrue.s IL_0011 IL_0024: leave.s IL_0035 IL_0026: ldloca.s 02 IL_0028: constrained. System.Collections.Generic.List<>.Enumerator IL_002E: callvirt System.IDisposable.Dispose IL_0033: nop IL_0034: endfinally </pre> ``` Thus the implementation of `IDisposable` does not cause any performance issues and the (regrettable) mutable aspect of the enumerator is preserved should the Dispose method actually do anything! 2: double and float are exceptions to this rule where NaN values are not considered equal.
Is it safe for structs to implement interfaces?
[ "", "c#", "interface", "struct", "" ]
We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation. Therefore, we've been looking at some alternative memory allocation mechanisms that may help us and I'm hoping someone can tell me the best one: 1) Use Windows [Low-fragmentation Heap](http://msdn.microsoft.com/en-us/library/aa366750.aspx) 2) jemalloc - as used in [Firefox 3](http://en.wikipedia.org/wiki/Mozilla_Firefox_3) 3) Doug Lea's [malloc](http://g.oswego.edu/) Our server process is developed using cross-platform C++ code, so any solution would be ideally cross-platform also (do \*nix operating systems suffer from this type of memory fragmentation?). Also, am I right in thinking that LFH is now the default memory allocation mechanism for Windows Server 2008 / Vista?... Will my current problems "go away" if our customers simply upgrade their server os?
First, I agree with the other posters who suggested a resource leak. You really want to rule that out first. Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all **free** blocks) and also the total number of blocks that it is divided over. If the average free block size is relatively small compared to the total free space in the heap, then you do have a fragmentation problem. Alternatively, if you can dump the size of the largest free block and compare that to the total free space, that will accomplish the same thing. The largest free block would be small relative to the total ***free*** space available across all blocks if you are running into fragmentation. To be very clear about the above, in all cases we are talking about ***free*** blocks in the heap, not the allocated blocks in the heap. In any case, if the above conditions are not met, then you *do* have a leak situation of some sort. So, once you have ruled out a leak, you could consider using a better allocator. ***Doug Lea's malloc*** suggested in the question is a very good allocator for general use applications and very robust *most* of the time. Put another way, it has been time tested to work very well for most any application. However, no algorithm is ideal for *all* applications and any management algorithm approach can be broken by the right pathelogical conditions against it's design. *Why are you having a fragmentation problem?* - Sources of fragmentation problems are *caused* by the behavior of an application and have to do with greatly different allocation lifetimes in the same memory arena. That is, some objects are allocated and freed regularly while other types of objects persist for extended periods of time all in the same heap.....think of the longer lifetime ones as poking holes into larger areas of the arena and thereby preventing the coalesce of adjacent blocks that have been freed. To address this type of problem, the best thing you can do is logically divide the heap into sub arenas where the lifetimes are more similar. In effect, you want a transient heap and a persistent heap or heaps that group things of similar lifetimes. Some others have suggested another approach to solve the problem which is to attempt to make the allocation sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation - which is in effect the wasted space you have by allocating more memory in the block than you need. Additionally, with a good heap allocator, like Doug Lea's, making the block sizes more similar is unnecessary because the allocator will already be doing a power of two size bucketing scheme that will make it completely unnecessary to artificially adjust the allocation sizes passed to malloc() - in effect, his heap manager does that for you automatically much more robustly than the application will be able to make adjustments.
I think you’ve mistakenly ruled out a memory leak too early. Even a tiny memory leak can cause a severe memory fragmentation. Assuming your application behaves like the following: Allocate 10MB Allocate 1 byte Free 10MB (oops, we didn’t free the 1 byte, but who cares about 1 tiny byte) This seems like a very small leak, **you will hardly notice it when monitoring just the total allocated memory size**. But this leak eventually will cause your application memory to look like this: . . Free – 10MB . . [Allocated -1 byte] . . Free – 10MB . . [Allocated -1 byte] . . Free – 10MB . . This leak will not be noticed... until you want to allocate 11MB Assuming your minidumps had full memory info included, I recommend using [DebugDiag](http://www.microsoft.com/downloadS/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&displaylang=en) to spot possible leaks. In the generated memory report, **examine carefully the allocation count (not size)**.
How to solve Memory Fragmentation
[ "", "c++", "windows", "memory", "" ]
I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that? I am using Java 1.5.
You can add a shutdown hook to your application by doing the following: ``` Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { // what you want to do } })); ``` This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block. Please note the [caveats](https://stackoverflow.com/questions/63687/calling-function-when-program-exits-in-java#63886) though!
Adding a shutdown hook [addShutdownHook(java.lang.Thread)](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)) is probably what you look for. There are problems with that approach, though: * you will lose the changes if the program aborts in an uncontrolled way (i.e. if it is killed) * you will lose the changes if there are errors (permission denied, disk full, network errors) So it might be better to save settings immediately (possibly in an extra thread, to avoid waiting times).
Calling function when program exits in java
[ "", "java", "events", "" ]
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data? In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write `Fraction<int> frac = new Fraction<int>(1,2)` and/or `Fraction<double> frac = new Fraction<double>(0.1, 1.0)`. Unfortunately there is no interface representing the four basic operations (+,-,\*,/). Has anybody found a workable, feasible way of implementing this?
Here is a way to abstract out the operators that is relatively painless. ``` abstract class MathProvider<T> { public abstract T Divide(T a, T b); public abstract T Multiply(T a, T b); public abstract T Add(T a, T b); public abstract T Negate(T a); public virtual T Subtract(T a, T b) { return Add(a, Negate(b)); } } class DoubleMathProvider : MathProvider<double> { public override double Divide(double a, double b) { return a / b; } public override double Multiply(double a, double b) { return a * b; } public override double Add(double a, double b) { return a + b; } public override double Negate(double a) { return -a; } } class IntMathProvider : MathProvider<int> { public override int Divide(int a, int b) { return a / b; } public override int Multiply(int a, int b) { return a * b; } public override int Add(int a, int b) { return a + b; } public override int Negate(int a) { return -a; } } class Fraction<T> { static MathProvider<T> _math; // Notice this is a type constructor. It gets run the first time a // variable of a specific type is declared for use. // Having _math static reduces overhead. static Fraction() { // This part of the code might be cleaner by once // using reflection and finding all the implementors of // MathProvider and assigning the instance by the one that // matches T. if (typeof(T) == typeof(double)) _math = new DoubleMathProvider() as MathProvider<T>; else if (typeof(T) == typeof(int)) _math = new IntMathProvider() as MathProvider<T>; // ... assign other options here. if (_math == null) throw new InvalidOperationException( "Type " + typeof(T).ToString() + " is not supported by Fraction."); } // Immutable impementations are better. public T Numerator { get; private set; } public T Denominator { get; private set; } public Fraction(T numerator, T denominator) { // We would want this to be reduced to simpilest terms. // For that we would need GCD, abs, and remainder operations // defined for each math provider. Numerator = numerator; Denominator = denominator; } public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b) { return new Fraction<T>( _math.Add( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(b.Numerator, a.Denominator)), _math.Multiply(a.Denominator, b.Denominator)); } public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b) { return new Fraction<T>( _math.Subtract( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(b.Numerator, a.Denominator)), _math.Multiply(a.Denominator, b.Denominator)); } public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b) { return new Fraction<T>( _math.Multiply(a.Numerator, b.Denominator), _math.Multiply(a.Denominator, b.Numerator)); } // ... other operators would follow. } ``` If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the `MathProvider<T>` implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction. **Edit:** Fixed definitions of add and subtract for `Fraction<T>`. Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: <http://conal.net/papers/beautiful-differentiation/>
I believe this answers your question: <http://www.codeproject.com/KB/cs/genericnumerics.aspx>
Creating a Math library using Generics in C#
[ "", "c#", "generics", "interface", "math", "" ]
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning [sips](http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows?
ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the `ps:alpha` delegate in ImageMagick, just adjusted to use JPEG as output): ``` gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT ``` where `$OUTPUT` and `$INPUT` are the output and input filenames. Adjust the `72x72` to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.) This is good for two reasons: 1. You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions. 2. ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step. Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the `-sDEVICE=jpeg` to `-sDEVICE=png16m`.
You can use ImageMagick's convert utility for this, see some examples in [http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html](https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html) : > ``` > Convert taxes.pdf taxes.jpg > ``` > > Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0, > taxes.jpg.1 > > I can also convert these JPEGS to a thumbnail as follows: > > ``` > convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg > ``` > > I can even convert the PDF directly to a jpeg thumbnail as follows: > > ``` > convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg > ``` > > This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two > pages.
Get a preview JPEG of a PDF on Windows?
[ "", "python", "windows", "image", "pdf", "" ]