text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Parsing a log file with regular expressions I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}):\d{2}:\d{2}),\d{3})\s(?<message>.+)
The log format (which I use for testing the parser) is this:
07/23/08 14:17:31,321 log
message
spanning
multiple
lines
07/23/08 14:17:31,321 log message on one line
When I run the parser right now, I get only the line the log starts on. If I change it to span multiple lines, I get only one result (the whole log file).
@samjudson:
You need to pass the RegexOptions.Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).
I tried that, but then it matches the whole file. I also tried to set the message-group to .+? (non-greedy), but then it matches a single character (which isn't what I'm looking for either).
The problem is that the pattern for the message matches on the date-group as well, so when it doesn't break on a new-line it just goes on and on and on.
I use this regex for the message group now. It works, unless there's a pattern IN the log message which is the same as the start of the log message.
(?<message>(.(?!\d{2}/\d{2}/\d{2}\s\d{2}:\d{2}:\d{2},\d{3}\s\[\d{4}\]))+)
A: This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group:
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/
\d{2}))+)
Note that this requires the use of the RegexOptions.MultiLine flag.
A: You obviously need that "messages lines" can be distinguished from "log lines"; if you allow the message part to start with date/time after a new line, then there is simply no way to determine what is part of a message and what not. So, instead of using the dot, you need an expression that allows anything that does not include a newline followed by a date and time.
Personally, however, I would not use a regular expression to parse the whole log entry. I prefer using my own loop to iterate over each line and use one simple regular expression to determine whether a line is the start of a new entry or not. Also from the point of readability this would have my preference.
A: The problem you have is that you need to terminate the RegEx pattern so it knows when one message ends and then next starts.
When you were running in default mode the newline was working as an implicit terminator.
The problem is if you go into multiline mode there's no terminator so the pattern will gobble up the whole file. Non-greedy matches a few characters as possible which will be just one.
Now, if use the date for the next message as the terminator I think your parser will only get every other line.
Is there something else in the file you could to terminate the pattern?
A: You need to pass the RegexOptions. Singleline flag in to the regular expression, so that "." matches all characters, not just all characters except new lines (which is the default).
A: You might find it a lot easier to parse the file with a proper parser generator - ANTLR can generate one in C#... Context Free parsers only seem hard until you "get" them - after that, they are much simpler and friendlier to use than Regular Expressions...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where do search engines start crawling? What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?
A: Your question can be interpreted in two ways:
Are you asking where search engines start their crawl from in general, or where they start to crawl a particular site?
I don't know how the big players work; but if you were to make your own search engine you'd probably seed it with popular portal sites. DMOZ.org seems to be a popular starting point. Since the big players have so much more data than we do they probably start their crawls from a variety of places.
If you're asking where a SE starts to crawl your particular site, it probably has a lot to do with which of your pages are the most popular. I imagine that if you have one super popular page that lots of other sites link to, then that would be the page that SEs starts will enter from because there are so many more entry points from other sites.
Note that I am not in SEO or anything; I just studied bot and SE traffic for a while for a project I was working on.
A: You can submit your site to search engines using their site submission forms - this will get you into their system. When you actually get crawled after that is impossible to say - from experience it's usually about a week or so for an initial crawl (homepage, couple of other pages 1-link deep from there). You can increase how many of your pages get crawled and indexed using clear semantic link structure and submitting a sitemap - these allow you to list all of your pages, and weight them relative to one another, which helps the search engines understand how important you view each part of site relative to the others.
If your site is linked from other crawled websites, then your site will also be crawled, starting with the page linked, and eventually spreading to the rest of your site. This can take a long time, and depends on the crawl frequency of the linking sites, so the url submission is the quickest way to let google know about you!
One tool I can't recommend highly enough is the Google Webmaster Tool. It allows you to see how often you've been crawled, any errors the googlebot has stumbled across (broken links, etc) and has a host of other useful tools in there.
A: In principle they start with nothing. Only when somebody explicitly tells them to include their website they can start crawling this site and use the links on that site to search more.
However, in practice the creator(s) of a search engine will put in some arbitrary sites they can think of. For example, their own blogs or the sites they have in their bookmarks.
In theory one could also just pick some random adresses and see if there is a website there. I doubt anyone does this though; the above method will work just fine and does not require extra coding just to bootstrap the search engine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How do you implement a "Did you mean"?
Possible Duplicate:
How does the Google “Did you mean?” Algorithm work?
Suppose you have a search system already in your website. How can you implement the "Did you mean:<spell_checked_word>" like Google does in some search queries?
A: Actually what Google does is very much non-trivial and also at first counter-intuitive. They don't do anything like check against a dictionary, but rather they make use of statistics to identify "similar" queries that returned more results than your query, the exact algorithm is of course not known.
There are different sub-problems to solve here, as a fundamental basis for all Natural Language Processing statistics related there is one must have book: Foundation of Statistical Natural Language Processing.
Concretely to solve the problem of word/query similarity I have had good results with using Edit Distance, a mathematical measure of string similarity that works surprisingly well. I used to use Levenshtein but the others may be worth looking into.
Soundex - in my experience - is crap.
Actually efficiently storing and searching a large dictionary of misspelled words and having sub second retrieval is again non-trivial, your best bet is to make use of existing full text indexing and retrieval engines (i.e. not your database's one), of which Lucene is currently one of the best and coincidentally ported to many many platforms.
A: I would suggest looking at SOUNDEX to find similar words in your database.
You can also access google own dictionary by using the Google API spelling suggestion request.
A: You may want to look at Peter Norvig's "How to Write a Spelling Corrector" article.
A: I believe Google logs all queries and identifies when someone makes a spelling correction. This correction may then be suggested when others supply the same first query. This will work for any language, in fact any string of any characters.
A: http://en.wikipedia.org/wiki/N-gram#Google_use_of_N-gram
A: I think this depends on how big your website it. On our local Intranet which is used by about 500 member of staff, I simply look at the search phrases that returned zero results and enter that search phrase with the new suggested search phrase into a SQL table.
I them call on that table if no search results has been returned, however, this only works if the site is relatively small and I only do it for search phrases which are the most common.
You might also want to look at my answer to a similar question:
*
*"Similar Posts" like functionality using MS SQL Server?
A: Google's Dr Norvig has outlined how it works; he even gives a 20ish line Python implementation:
http://googlesystem.blogspot.com/2007/04/simplified-version-of-googles-spell.html
http://www.norvig.com/spell-correct.html
Dr Norvig also discusses the "did you mean" in this excellent talk. Dr Norvig is head of research at Google - when asked how "did you mean" is implemented, his answer is authoritive.
So its spell-checking, presumably with a dynamic dictionary build from other searches or even actual internet phrases and such. But that's still spell checking.
SOUNDEX and other guesses don't get a look in, people!
A: If you have industry specific translations, you will likely need a thesaurus. For example, I worked in the jewelry industry and there were abbreviate in our descriptions such as kt - karat, rd - round, cwt - carat weight... Endeca (the search engine at that job) has a thesaurus that will translate from common misspellings, but it does require manual intervention.
A: Check this article on wikipedia about the Levenshtein distance. Make sure you take a good look at Possible improvements.
A: I was pleasantly surprised that someone has asked how to create a state-of-the-art spelling suggestion system for search engines. I have been working on this subject for more than a year for a search engine company and I can point to information on the public domain on the subject.
As was mentioned in a previous post, Google (and Microsoft and Yahoo!) do not use any predefined dictionary nor do they employ hordes of linguists that ponder over the possible misspellings of queries. That would be impossible due to the scale of the problem but also because it is not clear that people could actually correctly identify when and if a query is misspelled.
Instead there is a simple and rather effective principle that is also valid for all European languages. Get all the unique queries on your search logs, calculate the edit distance between all pairs of queries, assuming that the reference query is the one that has the highest count.
This simple algorithm will work great for many types of queries. If you want to take it to the next level then I suggest you read the paper by Microsoft Research on that subject. You can find it here
The paper has a great introduction but after that you will need to be knowledgeable with concepts such as the Hidden Markov Model.
A: I do it with Lucene's Spell Checker.
A: Soundex is good for phonetic matches, but works best with peoples' names (it was originally developed for census data)
Also check out Full-Text-Indexing, the syntax is different from Google logic, but it's very quick and can deal with similar language elements.
A: Soundex and "Porter stemming" (soundex is trivial, not sure about porter stemming).
A: There's something called aspell that might help:
http://blog.evanweaver.com/files/doc/fauna/raspell/classes/Aspell.html
There's a ruby gem for it, but I don't know how to talk to it from python
http://blog.evanweaver.com/files/doc/fauna/raspell/files/README.html
Here's a quote from the ruby implementation
Usage
Aspell lets you check words and suggest corrections. For example:
string = "my haert wil go on"
string.gsub(/[\w\']+/) do |word|
if !speller.check(word)
# word is wrong
puts "Possible correction for #{word}:"
puts speller.suggest(word).first
end
end
This outputs:
Possible correction for haert:
heart
Possible correction for wil:
Will
A: Implementing spelling correction for search engines in an effective way is not trivial (you can't just compute the edit/levenshtein distance to every possible word). A solution based on k-gram indexes is described in Introduction to Information Retrieval (full text available online).
A: U could use ngram for the comparisment: http://en.wikipedia.org/wiki/N-gram
Using python ngram module: http://packages.python.org/ngram/index.html
import ngram
G2 = ngram.NGram([ "iis7 configure ftp 7.5",
"ubunto configre 8.5",
"mac configure ftp"])
print "String", "\t", "Similarity"
for i in G2.search("iis7 configurftp 7.5", threshold=0.1):
print i[1], "\t", i[0]
U get:
>>>
String Similarity
0.76 "iis7 configure ftp 7.5"
0.24 "mac configure ftp"
0.19 "ubunto configre 8.5"
A: Why not use google's did you mean in your code.For how see here
http://narenonit.blogspot.com/2012/08/trick-for-using-googles-did-you-mean.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "116"
} |
Q: Setting viewstate on postback I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
}
private string YourName
{
get { return (string)ViewState["YourName"]; }
set { ViewState["YourName"] = value; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
YourName = txtName.Text;
}
Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC:
<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>
PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.
A: Page_Load fires before btnSubmit_Click.
If you want to do something after your postback events have fired use Page_PreRender.
//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
The basic order goes:
*
*Page init fires (init cannot access ViewState)
*ViewState is read
*Page load fires
*Any events fire
*PreRender fires
*Page renders
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Generating JavaScript stubs from WSDL I'm looking for a tool to generate a JavaScript stub from a WSDL.
Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP.
I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is.
So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code.
More: The web service I try to use is RPC encoded, not document literal.
A: I had to do this myself in the past and I found this CodeProject article. I changed it up some, but it gave me a good foundation to implement everything I needed. One of the main features it already has is generating the SOAP client based off the WSDL. It also has built in caching of the WSDL for multiple calls.
This article also has a custom implementation of XmlHttpRequest for Ajax calls. This is the part that I didn't use. During that time, I think I was using Prototype javascript library and modified the code in this article to use it's Ajax functions instead. I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.
A: It would probably be an overkill, but NetBeans has this feature.
A: Apache CXF has tools that generate JavaScript clients that talk soap.
Actually, any CXF service can have a javascript client autogenerated by doing a get to the URL with ?js appended. (just like ?wsld produces the wsdl) There are command line tools as well, but the dynamic generated stuff is kind of neat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project The exact error is as follows
Could not load file or assembly 'Microsoft.SqlServer.Replication,
Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
or one of its dependencies. An attempt was made to load a program with
an incorrect format.
I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.
A: Change the value for Platform Target on your web project's property page to Any CPU.
A: I had this in an MVC5 app in Windows 10 against IIS Express. My solution was the following:
*
*Tools =>
*
*Options =>
*
*Projects and Solutions =>
*
*Web Projects =>
*
*Use the 64 bit version of IIS Express for web sites and projects
A: Go to IIS
-> Application Pool -> Advance Settings -> Enable 32-bit Applications
A: The answer by baldy below is correct, but you may also need to enable 32-bit applications in your AppPool.
Source: http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/
Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error:
Could not load file or assembly ChilkatDotNet2 or one of its
dependencies. An attempt was made to load a program with an incorrect
format.
Obviously, the application uses ChilKat components, but it would seem that the version we are using, is only the 32bit version.
To resolve this error, I set my app pool in IIS to allow 32bit applications.
Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below)
Then set "Enable 32-bit Applications" to True.
All done!
A: change it to 32-bit (true) it works
if you get this Length cannot be less than zero. Parameter name: length issue in iis server configuation do the simple thing change the connection string in web.config file like your sql server name and server name and restart iis then try to load the page it works
A: We recently had the issue when trying to run the code from Visual Studio. In that case you need to do
TOOLS > OPTIONS > Projects and Solutions > WEB PROJECTS and check the "Use the 64 bit version of IIS Express for web sites and projects".
A: If Publishing in Visual Studio 2012 when erroring try unchecking the "Procompile during publishing" option in the Publish wizard.
A: I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
A: For those who get this error in an ASP.NET MVC 3 project, within Visual Studio itself:
In an ASP.NET MVC 3 app I'm working on, I tried adding a reference to Microsoft.SqlServer.BatchParser to a project to resolve a problem where it was missing on a deployment server. (Our app uses SMO; the correct fix was to install SQL Server Native Client and a couple other things on the deployment server.)
Even after I removed the reference to BatchParser, I kept getting the "An attempt was made..." error, referencing the BatchParser DLL, on every ASP.NET MVC 3 page I opened, and that error was followed by dozens of page parsing errors.
If this happens to you, do a file search and see if the DLL is still in one of your project's \bin folders. Even if you do a rebuild, Visual Studio doesn't necessarily clear out everything in all your \bin folders. When I deleted the DLL from the bin and built again, the error went away.
A: in windows form application I do this,
Right-click on Project->Properties->Build->Check Prefer 32-bit checkbox.
Thanks all
A: *
*Delete the temp test directory located here
C:\Users(User)\AppData\Local\Temp\VisualStudioTestExplorerExtensions\
*Set all projects to x64 in Visual Studio
*Set the default processor architecture to x64(Test/TestSettings/Default Processor Architecture).
Make sure to clean build the solution file.Hope this helps!
A: Changing the Target Framework in project properties from .NET Framework 4.7.1 to 4.6.2 worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "323"
} |
Q: How can I add reflection to a C++ application? I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?
A: The two reflection-like solutions I know of from my C++ days are:
1) Use RTTI, which will provide a bootstrap for you to build your reflection-like behaviour, if you are able to get all your classes to derive from an 'object' base class. That class could provide some methods like GetMethod, GetBaseClass etc. As for how those methods work you will need to manually add some macros to decorate your types, which behind the scenes create metadata in the type to provide answers to GetMethods etc.
2) Another option, if you have access to the compiler objects is to use the DIA SDK. If I remember correctly this lets you open pdbs, which should contain metadata for your C++ types. It might be enough to do what you need. This page shows how you can get all base types of a class for example.
Both these solution are a bit ugly though! There is nothing like a bit of C++ to make you appreciate the luxuries of C#.
Good Luck.
A: I think you might find interesting the article "Using Templates for Reflection in C++" by Dominic Filion. It is in section 1.4 of Game Programming Gems 5. Unfortunately I dont have my copy with me, but look for it because I think it explains what you are asking for.
A: This question is a bit old now (don't know why I keep hitting old questions today) but I was thinking about BOOST_FUSION_ADAPT_STRUCT which introduces compile-time reflection.
It is up to you to map this to run-time reflection of course, and it won't be too easy, but it is possible in this direction, while it would not be in the reverse :)
I really think a macro to encapsulate the BOOST_FUSION_ADAPT_STRUCT one could generate the necessary methods to get the runtime behavior.
A: And I would love a pony, but ponies aren't free. :-p
http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI is what you're going to get. Reflection like you're thinking about -- fully descriptive metadata available at runtime -- just doesn't exist for C++ by default.
A: Reflection is not supported by C++ out of the box. This is sad because it makes defensive testing a pain.
There are several approaches to doing reflection:
*
*use the debug information (non portable).
*Sprinkle your code with macro's/templates or some other source approach (looks ugly)
*Modify a compiler such as clang/gcc to produce a database.
*Use Qt moc approach
*Boost Reflect
*Precise and Flat Reflection
The first link looks the most promising (uses mod's to clang), the second discusses a number of techniques, the third is a different approach using gcc:
*
*http://www.donw.org/rfl/
*https://bitbucket.org/dwilliamson/clreflect
*https://root.cern.ch/how/how-use-reflex
There is now a working group for C++ reflection. See the news for C++14 @ CERN:
*
*https://root.cern.ch/blog/status-reflection-c
Edit 13/08/17:
Since the original post there have been a number of potential advancements on the reflection. The following provides more detail and a discussion on the various techniques and status:
*
*Static Reflection in a Nutshell
*Static Reflection
*A design for static reflection
However it does not look promising on a standardised reflections approach in C++ in the near future unless there is a lot more interest from the community in support for reflection in C++.
The following details the current status based on feedback from the last C++ standards meeting:
*
*Reflections on the reflection proposals
Edit 13/12/2017
Reflection looks to be moving towards C++ 20 or more probably a TSR. Movement is however slow.
*
*Mirror
*Mirror standard proposal
*Mirror paper
*Herb Sutter - meta programming including reflection
Edit 15/09/2018
A draft TS has been sent out to the national bodies for ballot.
The text can be found here: https://github.com/cplusplus/reflection-ts
Edit 11/07/2019
The reflection TS is feature complete and is out for comment and vote over the summer (2019).
The meta-template programing approach is to be replaced with a simplier compile time code approach (not reflected in the TS).
*
*Draft TS as of 2019-06-17
Edit 10/02/2020
There is a request to support the reflection TS in Visual Studio here:
*
*https://developercommunity.visualstudio.com/idea/826632/implement-the-c-reflection-ts.html
Talk on the TS by the author David Sankel:
*
*http://cppnow.org/history/2019/talks/
*https://www.youtube.com/watch?v=VMuML6vLSus&feature=youtu.be
Edit 17 March 2020
Progress on reflection is being made. A report from '2020-02 Prague ISO C++ Committee Trip Report' can be found here:
*
*https://www.reddit.com/r/cpp/comments/f47x4o/202002_prague_iso_c_committee_trip_report_c20_is/
Details on what is being considered for C++23 can be found here (includes short section on Reflection):
*
*http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0592r4.html
Edit 4th June 2020
A new framework has been released by Jeff Preshing called 'Plywood' that contains a mechanism for runtime reflection. More details can be found here:
*
*https://preshing.com/20200526/a-new-cross-platform-open-source-cpp-framework/
The tools and approach look to be the most polished and easiest to use so far.
Edit July 12 2020
Clang experimental reflection fork : https://github.com/lock3/meta/wiki
Interesting reflection library that uses clang tooling library to extract information for simple reflection with no need to add macro's: https://github.com/chakaz/reflang
Edit Feb 24 2021
Some additional clang tooling approaches:
*
*https://github.com/Celtoys/clReflect
*https://github.com/mlomb/MetaCPP
Edit Aug 25 2021
An ACCU talk online at youtube https://www.youtube.com/watch?v=60ECEc-URP8 is well worth a listen too it talks about current proposals to the standard and an implementation based on clang.
See:
*
*https://github.com/lock3/meta, branch paper/p2320
*Compiler Explorer : https://cppx.godbolt.org/ use the p2320 trunk for the compiler version.
A: Reflection is essentially about what the compiler decided to leave as footprints in the code that the runtime code can query. C++ is famous for not paying for what you don't use; because most people don't use/want reflection, the C++ compiler avoids the cost by not recording anything.
So, C++ doesn't provide reflection, and it isn't easy to "simulate" it yourself as general rule as other answers have noted.
Under "other techniques", if you don't have a language with reflection, get a tool that can extract the information you want at compile time.
Our DMS Software Reengineering Toolkit is generalized compiler technology parameterized by explicit langauge definitions. It has langauge definitions for C, C++, Java, COBOL, PHP, ...
For C, C++, Java and COBOL versions, it provides complete access to parse trees, and symbol table information. That symbol table information includes the kind of data you are likely to want from "reflection". If you goal is to enumerate some set of fields or methods and do something with them, DMS can be used to transform the code according to what you find in the symbol tables in arbitrary ways.
A: EDIT: Updated broken link as of February, the 7th, 2017.
I think noone mentioned this:
At CERN they use a full reflection system for C++:
CERN Reflex. It seems to work very well.
A: The RareCpp library makes for fairly easy and intuitive reflection - all field/type information is designed to either be available in arrays or to feel like array access. It's written for C++17 and works with Visual Studios, g++, and Clang. The library is header only, meaning you need only copy "Reflect.h" into your project to use it.
Reflected structs or classes need the REFLECT macro, where you supply the name of the class you're reflecting and the names of the fields.
class FuelTank {
public:
float capacity;
float currentLevel;
float tickMarks[2];
REFLECT(FuelTank, capacity, currentLevel, tickMarks)
};
That's all there is, no additional code is needed to setup reflection. Optionally you can supply class and field annotations to be able to traverse superclasses or add additional compile-time information to a field (such as Json::Ignore).
Looping through fields can be as simple as...
for ( size_t i=0; i<FuelTank::Class::TotalFields; i++ )
std::cout << FuelTank::Class::Fields[i].name << std::endl;
You can loop through an object instance to access field values (which you can read or modify) and field type information...
FuelTank::Class::ForEachField(fuelTank, [&](auto & field, auto & value) {
using Type = typename std::remove_reference<decltype(value)>::type;
std::cout << TypeToStr<Type>() << " " << field.name << ": " << value << std::endl;
});
A JSON Library is built on top of RandomAccessReflection which auto identifies appropriate JSON output representations for reading or writing, and can recursively traverse any reflected fields, as well as arrays and STL containers.
struct MyOtherObject { int myOtherInt; REFLECT(MyOtherObject, myOtherInt) };
struct MyObject
{
int myInt;
std::string myString;
MyOtherObject myOtherObject;
std::vector<int> myIntCollection;
REFLECT(MyObject, myInt, myString, myOtherObject, myIntCollection)
};
int main()
{
MyObject myObject = {};
std::cout << "Enter MyObject:" << std::endl;
std::cin >> Json::in(myObject);
std::cout << std::endl << std::endl << "You entered:" << std::endl;
std::cout << Json::pretty(myObject);
}
The above could be ran like so...
Enter MyObject:
{
"myInt": 1337, "myString": "stringy", "myIntCollection": [2,4,6],
"myOtherObject": {
"myOtherInt": 9001
}
}
You entered:
{
"myInt": 1337,
"myString": "stringy",
"myOtherObject": {
"myOtherInt": 9001
},
"myIntCollection": [ 2, 4, 6 ]
}
See also...
*
*Reflect Documentation
*Reflect Implementation
*More Usage Examples
A: The information does exist - but not in the format you need, and only if you export your classes. This works in Windows, I don't know about other platforms. Using the storage-class specifiers as in, for example:
class __declspec(export) MyClass
{
public:
void Foo(float x);
}
This makes the compiler build the class definition data into the DLL/Exe. But it's not in a format that you can readily use for reflection.
At my company we built a library that interprets this metadata, and allows you to reflect a class without inserting extra macros etc. into the class itself. It allows functions to be called as follows:
MyClass *instance_ptr=new MyClass;
GetClass("MyClass")->GetFunction("Foo")->Invoke(instance_ptr,1.331);
This effectively does:
instance_ptr->Foo(1.331);
The Invoke(this_pointer,...) function has variable arguments. Obviously by calling a function in this way you're circumventing things like const-safety and so on, so these aspects are implemented as runtime checks.
I'm sure the syntax could be improved, and it only works on Win32 and Win64 so far. We've found it really useful for having automatic GUI interfaces to classes, creating properties in C++, streaming to and from XML and so on, and there's no need to derive from a specific base class. If there's enough demand maybe we could knock it into shape for release.
A: Ponder is a C++ reflection library, in answer to this question. I considered the options and decided to make my own since I couldn't find one that ticked all my boxes.
Although there are great answers to this question, I don't want to use tonnes of macros, or rely on Boost. Boost is a great library, but there are lots of small bespoke C++0x projects out that are simpler and have faster compile times. There are also advantages to being able to decorate a class externally, like wrapping a C++ library that doesn't (yet?) support C++11. It is fork of CAMP, using C++11, that no longer requires Boost.
A: What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes.
First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing int x you will write (int) x. Here are some handy macros to help with typed expressions:
#define REM(...) __VA_ARGS__
#define EAT(...)
// Retrieve the type
#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)
#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)
#define DETAIL_TYPEOF_HEAD(x, ...) REM x
#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),
// Strip off the type
#define STRIP(x) EAT x
// Show the type without parenthesis
#define PAIR(x) REM x
Next, we define a REFLECTABLE macro to generate the data about each field(plus the field itself). This macro will be called like this:
REFLECTABLE
(
(const char *) name,
(int) age
)
So using Boost.PP we iterate over each argument and generate the data like this:
// A helper metafunction for adding const to a type
template<class M, class T>
struct make_const
{
typedef T type;
};
template<class M, class T>
struct make_const<const M, T>
{
typedef typename boost::add_const<T>::type type;
};
#define REFLECTABLE(...) \
static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \
friend struct reflector; \
template<int N, class Self> \
struct field_data {}; \
BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
#define REFLECT_EACH(r, data, i, x) \
PAIR(x); \
template<class Self> \
struct field_data<i, Self> \
{ \
Self & self; \
field_data(Self & self) : self(self) {} \
\
typename make_const<Self, TYPEOF(x)>::type & get() \
{ \
return self.STRIP(x); \
}\
typename boost::add_const<TYPEOF(x)>::type & get() const \
{ \
return self.STRIP(x); \
}\
const char * name() const \
{\
return BOOST_PP_STRINGIZE(STRIP(x)); \
} \
}; \
What this does is generate a constant fields_n that is number of reflectable fields in the class. Then it specializes the field_data for each field. It also friends the reflector class, this is so it can access the fields even when they are private:
struct reflector
{
//Get field_data at index N
template<int N, class T>
static typename T::template field_data<N, T> get_field_data(T& x)
{
return typename T::template field_data<N, T>(x);
}
// Get the number of fields
template<class T>
struct fields
{
static const int n = T::fields_n;
};
};
Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor:
struct field_visitor
{
template<class C, class Visitor, class I>
void operator()(C& c, Visitor v, I)
{
v(reflector::get_field_data<I::value>(c));
}
};
template<class C, class Visitor>
void visit_each(C & c, Visitor v)
{
typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range;
boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));
}
Now for the moment of truth we put it all together. Here is how we can define a Person class that is reflectable:
struct Person
{
Person(const char *name, int age)
:
name(name),
age(age)
{
}
private:
REFLECTABLE
(
(const char *) name,
(int) age
)
};
Here is a generalized print_fields function using the reflection data to iterate over the fields:
struct print_visitor
{
template<class FieldData>
void operator()(FieldData f)
{
std::cout << f.name() << "=" << f.get() << std::endl;
}
};
template<class T>
void print_fields(T & x)
{
visit_each(x, print_visitor());
}
An example of using the print_fields with the reflectable Person class:
int main()
{
Person p("Tom", 82);
print_fields(p);
return 0;
}
Which outputs:
name=Tom
age=82
And voila, we have just implemented reflection in C++, in under 100 lines of code.
A: You can find another library here: http://www.garret.ru/cppreflection/docs/reflect.html
It supports 2 ways: getting type information from debug information and let programmer to provide this information.
I also interested in reflection for my project and found this library, i have not tried it yet, but tried other tools from this guy and i like how they work :-)
A: If you're looking for relatively simple C++ reflection - I have collected from various sources macro / defines, and commented them out how they works. You can download header
files from here:
https://github.com/tapika/TestCppReflect/blob/master/MacroHelpers.h
set of defines, plus functionality on top of it:
https://github.com/tapika/TestCppReflect/blob/master/CppReflect.h
https://github.com/tapika/TestCppReflect/blob/master/CppReflect.cpp
https://github.com/tapika/TestCppReflect/blob/master/TypeTraits.h
Sample application resides in git repository as well, in here:
https://github.com/tapika/TestCppReflect/
I'll partly copy it here with explanation:
#include "CppReflect.h"
using namespace std;
class Person
{
public:
// Repack your code into REFLECTABLE macro, in (<C++ Type>) <Field name>
// form , like this:
REFLECTABLE( Person,
(CString) name,
(int) age,
...
)
};
void main(void)
{
Person p;
p.name = L"Roger";
p.age = 37;
...
// And here you can convert your class contents into xml form:
CStringW xml = ToXML( &p );
CStringW errors;
People ppl2;
// And here you convert from xml back to class:
FromXml( &ppl2, xml, errors );
CStringA xml2 = ToXML( &ppl2 );
printf( xml2 );
}
REFLECTABLE define uses class name + field name with offsetof - to identify at which place in memory particular field is located. I have tried to pick up .NET terminology for as far as possible, but C++ and C# are different, so it's not 1 to 1. Whole C++ reflection model resides in TypeInfo and FieldInfo classes.
I have used pugi xml parser to fetch demo code into xml and restore it back from xml.
So output produced by demo code looks like this:
<?xml version="1.0" encoding="utf-8"?>
<People groupName="Group1">
<people>
<Person name="Roger" age="37" />
<Person name="Alice" age="27" />
<Person name="Cindy" age="17" />
</people>
</People>
It's also possible to enable any 3-rd party class / structure support via TypeTraits class, and partial template specification - to define your own TypeTraitsT class, in similar manner to CString or int - see example code in
https://github.com/tapika/TestCppReflect/blob/master/TypeTraits.h#L195
This solution is applicable for Windows / Visual studio. It's possible to port it to other OS/compilers, but haven't done that one. (Ask me if you really like solution, I might be able to help you out)
This solution is applicable for one shot serialization of one class with multiple subclasses.
If you however are searching for mechanism to serialize class parts or even to control what functionality reflection calls produce, you could take a look on following solution:
https://github.com/tapika/cppscriptcore/tree/master/SolutionProjectModel
More detailed information can be found from youtube video:
C++ Runtime Type Reflection
https://youtu.be/TN8tJijkeFE
I'm trying to explain bit deeper on how c++ reflection will work.
Sample code will look like for example this:
https://github.com/tapika/cppscriptcore/blob/master/SolutionProjectModel/testCppApp.cpp
c.General.IntDir = LR"(obj\$(ProjectName)_$(Configuration)_$(Platform)\)";
c.General.OutDir = LR"(bin\$(Configuration)_$(Platform)\)";
c.General.UseDebugLibraries = true;
c.General.LinkIncremental = true;
c.CCpp.Optimization = optimization_Disabled;
c.Linker.System.SubSystem = subsystem_Console;
c.Linker.Debugging.GenerateDebugInformation = debuginfo_true;
But each step here actually results in function call
Using C++ properties with __declspec(property(get =, put ... ).
which receives full information on C++ Data Types, C++ property names and class instance pointers, in form of path, and based on that information you can generate xml, json or even serialize that one over internet.
Examples of such virtual callback functions can be found here:
https://github.com/tapika/cppscriptcore/blob/master/SolutionProjectModel/VCConfiguration.cpp
See functions ReflectCopy, and virtual function ::OnAfterSetProperty.
But since topic is really advanced - I recommend to check through video first.
If you have some improvement ideas, feel free to contact me.
A: When I wanted reflection in C++ I read this article and improved upon what I saw there. Sorry, no can has. I don't own the result...but you can certainly get what I had and go from there.
I am currently researching, when I feel like it, methods to use inherit_linearly to make the definition of reflectable types much easier. I've gotten fairly far in it actually but I still have a ways to go. The changes in C++0x are very likely to be a lot of help in this area.
A: It looks like C++ still does not have this feature.
And C++11 postponed reflection too ((
Search some macros or make own. Qt also can help with reflection (if it can be used).
A: even though reflection is not supported out-of-the-box in c++, it is not too hard to implement.
I've encountered this great article:
http://replicaisland.blogspot.co.il/2010/11/building-reflective-object-system-in-c.html
the article explains in great detail how you can implement a pretty simple and rudimentary reflection system. granted its not the most wholesome solution, and there are rough edges left to be sorted out but for my needs it was sufficient.
the bottom line - reflection can pay off if done correctly, and it is completely feasible in c++.
A: Check out Classdesc http://classdesc.sf.net. It provides reflection in the form of class "descriptors", works with any standard C++ compiler (yes it is known to work with Visual Studio as well as GCC), and does not require source code annotation (although some pragmas exist to handle tricky situations). It has been in development for more than a decade, and used in a number of industrial scale projects.
A: I would recommend using Qt.
There is an open-source licence as well as a commercial licence.
A: You need to look at what you are trying to do, and if RTTI will satisfy your requirements. I've implemented my own pseudo-reflection for some very specific purposes. For example, I once wanted to be able to flexibly configure what a simulation would output. It required adding some boilerplate code to the classes that would be output:
namespace {
static bool b2 = Filter::Filterable<const MyObj>::Register("MyObject");
}
bool MyObj::BuildMap()
{
Filterable<const OutputDisease>::AddAccess("time", &MyObj::time);
Filterable<const OutputDisease>::AddAccess("person", &MyObj::id);
return true;
}
The first call adds this object to the filtering system, which calls the BuildMap() method to figure out what methods are available.
Then, in the config file, you can do something like this:
FILTER-OUTPUT-OBJECT MyObject
FILTER-OUTPUT-FILENAME file.txt
FILTER-CLAUSE-1 person == 1773
FILTER-CLAUSE-2 time > 2000
Through some template magic involving boost, this gets translated into a series of method calls at run-time (when the config file is read), so it's fairly efficient. I wouldn't recommend doing this unless you really need to, but, when you do, you can do some really cool stuff.
A: What are you trying to do with reflection?
You can use the Boost type traits and typeof libraries as a limited form of compile-time reflection. That is, you can inspect and modify the basic properties of a type passed to a template.
A: EDIT: CAMP is no more maintained ; two forks are available:
*
*One is also called CAMP too, and is based on the same API.
*Ponder is a partial rewrite, and shall be preferred as it does not requires Boost ; it's using C++11.
CAMP is an MIT licensed library (formerly LGPL) that adds reflection to the C++ language. It doesn't require a specific preprocessing step in the compilation, but the binding has to be made manually.
The current Tegesoft library uses Boost, but there is also a fork using C++11 that no longer requires Boost.
A: There is another new library for reflection in C++, called RTTR (Run Time Type Reflection, see also github).
The interface is similar to reflection in C# and it works without any RTTI.
A: There are two kinds of reflection swimming around.
*
*Inspection by iterating over members of a type, enumerating its methods and so on.
This is not possible with C++.
*Inspection by checking whether a class-type (class, struct, union) has a method or nested type, is derived from another particular type.
This kind of thing is possible with C++ using template-tricks. Use boost::type_traits for many things (like checking whether a type is integral). For checking for the existence of a member function, use Templated check for the existence of a class member function? . For checking whether a certain nested type exists, use plain SFINAE .
If you are rather looking for ways to accomplish 1), like looking how many methods a class has, or like getting the string representation of a class id, then I'm afraid there is no Standard C++ way of doing this. You have to use either
*
*A Meta Compiler like the Qt Meta Object Compiler which translates your code adding additional meta information.
*A Framework consisting of macros that allow you to add the required meta-information. You would need to tell the framework all methods, the class-names, base-classes and everything it needs.
C++ is made with speed in mind. If you want high-level inspection, like C# or Java has, there is no way to do that without some additional effort.
A: I did something like what you're after once, and while it's possible to get some level of reflection and access to higher-level features, the maintenance headache might not be worth it. My system was used to keep the UI classes completely separated from the business logic through delegation akin to Objective-C's concept of message passing and forwarding. The way to do it is to create some base class that is capable of mapping symbols (I used a string pool but you could do it with enums if you prefer speed and compile-time error handling over total flexibility) to function pointers (actually not pure function pointers, but something similar to what Boost has with Boost.Function--which I didn't have access to at the time). You can do the same thing for your member variables as long as you have some common base class capable of representing any value. The entire system was an unabashed ripoff of Key-Value Coding and Delegation, with a few side effects that were perhaps worth the sheer amount of time necessary to get every class that used the system to match all of its methods and members up with legal calls: 1) Any class could call any method on any other class without having to include headers or write fake base classes so the interface could be predefined for the compiler; and 2) The getters and setters of the member variables were easy to make thread-safe because changing or accessing their values was always done through 2 methods in the base class of all objects.
It also led to the possibility of doing some really weird things that otherwise aren't easy in C++. For example I could create an Array object that contained arbitrary items of any type, including itself, and create new arrays dynamically by passing a message to all array items and collecting the return values (similar to map in Lisp). Another was the implementation of key-value observing, whereby I was able to set up the UI to respond immediately to changes in the members of backend classes instead of constantly polling the data or unnecessarily redrawing the display.
Maybe more interesting to you is the fact that you can also dump all methods and members defined for a class, and in string form no less.
Downsides to the system that might discourage you from bothering: adding all of the messages and key-values is extremely tedious; it's slower than without any reflection; you'll grow to hate seeing boost::static_pointer_cast and boost::dynamic_pointer_cast all over your codebase with a violent passion; the limitations of the strongly-typed system are still there, you're really just hiding them a bit so it isn't as obvious. Typos in your strings are also not a fun or easy to discover surprise.
As to how to implement something like this: just use shared and weak pointers to some common base (mine was very imaginatively called "Object") and derive for all the types you want to use. I'd recommend installing Boost.Function instead of doing it the way I did, which was with some custom crap and a ton of ugly macros to wrap the function pointer calls. Since everything is mapped, inspecting objects is just a matter of iterating through all of the keys. Since my classes were essentially as close to a direct ripoff of Cocoa as possible using only C++, if you want something like that then I'd suggest using the Cocoa documentation as a blueprint.
A: I would like to advertise the existence of the automatic introspection/reflection toolkit "IDK". It uses a meta-compiler like Qt's and adds meta information directly into object files. It is claimed to be easy to use. No external dependencies. It even allows you to automatically reflect std::string and then use it in scripts. Please look at IDK
A: Reflection in C++ is very useful, in cases there you need to run some method for each member(For example: serialization, hashing, compare). I came with generic solution, with very simple syntax:
struct S1
{
ENUMERATE_MEMBERS(str,i);
std::string str;
int i;
};
struct S2
{
ENUMERATE_MEMBERS(s1,i2);
S1 s1;
int i2;
};
Where ENUMERATE_MEMBERS is a macro, which is described later(UPDATE):
Assume we have defined serialization function for int and std::string like this:
void EnumerateWith(BinaryWriter & writer, int val)
{
//store integer
writer.WriteBuffer(&val, sizeof(int));
}
void EnumerateWith(BinaryWriter & writer, std::string val)
{
//store string
writer.WriteBuffer(val.c_str(), val.size());
}
And we have generic function near the "secret macro" ;)
template<typename TWriter, typename T>
auto EnumerateWith(TWriter && writer, T && val) -> is_enumerable_t<T>
{
val.EnumerateWith(write); //method generated by ENUMERATE_MEMBERS macro
}
Now you can write
S1 s1;
S2 s2;
//....
BinaryWriter writer("serialized.bin");
EnumerateWith(writer, s1); //this will call EnumerateWith for all members of S1
EnumerateWith(writer, s2); //this will call EnumerateWith for all members of S2 and S2::s1 (recursively)
So having ENUMERATE_MEMBERS macro in struct definition, you can build serialization, compare, hashing, and other stuffs without touching original type, the only requirement is to implement "EnumerateWith" method for each type, which is not enumerable, per enumerator(like BinaryWriter). Usually you will have to implement 10-20 "simple" types to support any type in your project.
This macro should have zero-overhead to struct creation/destruction in run-time, and the code of T.EnumerateWith() should be generated on-demand, which can be achieved by making it template-inline function, so the only overhead in all the story is to add ENUMERATE_MEMBERS(m1,m2,m3...) to each struct, while implementing specific method per member type is a must in any solution, so I do not assume it as overhead.
UPDATE:
There is very simple implementation of ENUMERATE_MEMBERS macro(however it could be a little be extended to support inheritance from enumerable struct)
#define ENUMERATE_MEMBERS(...) \
template<typename TEnumerator> inline void EnumerateWith(TEnumerator & enumerator) const { EnumerateWithHelper(enumerator, __VA_ARGS__ ); }\
template<typename TEnumerator> inline void EnumerateWith(TEnumerator & enumerator) { EnumerateWithHelper(enumerator, __VA_ARGS__); }
// EnumerateWithHelper
template<typename TEnumerator, typename ...T> inline void EnumerateWithHelper(TEnumerator & enumerator, T &...v)
{
int x[] = { (EnumerateWith(enumerator, v), 1)... };
}
// Generic EnumerateWith
template<typename TEnumerator, typename T>
auto EnumerateWith(TEnumerator & enumerator, T & val) -> std::void_t<decltype(val.EnumerateWith(enumerator))>
{
val.EnumerateWith(enumerator);
}
And you do not need any 3rd party library for these 15 lines of code ;)
A: You can achieve cool static reflection features for structs with BOOST_HANA_DEFINE_STRUCT from the Boost::Hana library.
Hana is quite versatile, not only for the usecase you have in mind but for a lot of template metaprogramming.
A: If you declare a pointer to a function like this:
int (*func)(int a, int b);
You can assign a place in memory to that function like this (requires libdl and dlopen)
#include <dlfcn.h>
int main(void)
{
void *handle;
char *func_name = "bla_bla_bla";
handle = dlopen("foo.so", RTLD_LAZY);
*(void **)(&func) = dlsym(handle, func_name);
return func(1,2);
}
To load a local symbol using indirection, you can use dlopen on the calling binary (argv[0]).
The only requirement for this (other than dlopen(), libdl, and dlfcn.h) is knowing the arguments and type of the function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "317"
} |
Q: What are the differences between GPL v2 and GPL v3 licenses? In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.
A: In (not entirely) cynical terms, the reason for the v3 license was Microsoft's patent deal with Novell.
In reality, you should always consult a lawyer when dealing with legal issues.
A: This link also highlight the differences between GPLv2 and GPLv3
Content:
GPLv3 of June 29, 2007 contains the basic intent of GPLv2 and is an Open Source license with a strict copyleft (→ What types of licenses are there for Open Source software, and how do they differ?) However, the language of the license text was strongly amended and is much more comprehensive in response to technical and legal changes and international license exchange.
The new license version contains a series of clauses that address questions that were not or were only insufficiently covered in version 2 of the GPL. The most important new regulations are as follows:
a) GPLv3 contains compatibility regulations that make it easier than before to combine GPL code with code that was published under different licenses (→ What is license compatibility?). This concerns in particular code under Apache license v. 2.0.
b) Regulations concerning digital rights management were inserted to keep GPL software from being changed at will because users appealed to the legal regulations to be protected by technical protective measures (such as the DMCA or copyright directive). The effectiveness in practice of the contractual regulations in the GPL has yet to be seen.
c) The GPLv3 contains an explicit patent license, according to which people who license a program under the GPL license both copyrights as well as patents to the extent that this is necessary to use the code licensed by them. A comprehensive patent license is not thereby granted. Furthermore, the new patent clause attempts to protect the user from the consequences of agreements between patent owners and licensees of the GPL that only benefit some of the licensees (corresponding to the Microsoft/Novell deal). The licensees are required to ensure that every user enjoys such advantages (patent license or release from claims), or that no one can profit from them.
d) In contrast to the GPLv2, the GPLv3 clearly states that there is no requirement to disclose the source code in an ASP use of GPL programs as long as a copy of the software is not sent to the client. If the copyleft effect is to be extended to ASP use (→ When does independently developed software have to be licensed under the GPL?), the Affero General Public License, Version 3 (AGPL) must be applied that only differs from the GPLv3 in this regard.
A: The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences:
*
*internationalization: they used new terminology, rather than using language tied to US legal concepts
*patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer)
*“Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software
*DRM: they address digital rights management (which they call digital restrictions management)
*compatibility: they addressed compatibility with some other open source licenses
*termination: they addressed specifically what happens if the license is violated and the cure of violations
I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. GPL 3 is many things, and one of them is that it is a very complex, technical legal document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "207"
} |
Q: How to fetch a Book Title from an ISBN number? I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality:
The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database.
Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.
A: I haven't tried it, but take a look at isbndb
API Description: Introduction
ISBNdb.com's remote access application programming interface (API) is designed to allow other websites and standalone applications use the vast collection of data collected by ISBNdb.com since 2003. As of this writing, in July 2005, the data includes nearly 1,800,000 books; almost 3,000,000 million library records; close to a million subjects; hundreds of thousands of author and publisher records parsed out of library data; more than 10,000,000 records of actual and historic prices.
Some ideas of how the API can be used include:
- Cataloguing home book collections
- Building and verifying bookstores' inventories
- Empowering forums and online communities with more useful book references
- Automated cross-merchant price lookups over messaging devices or phones
Using the API you can look up information by keywords, by ISBN, by authors or publishers, etc. In most situations the API is fast enough to be used in interactive applications.
The data is heavily cross-linked -- starting at a book you can retrieve information about its authors, then other books of these authors, then their publishers, etc.
The API is primarily intended for use by programmers. The interface strives to be platform and programming language independent by employing open standard protocols and message formats.
A: This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving.
First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits. Rather, ISBNs can be either 10 or 13. Ten-digit ISBNs can be expressed as 13-digit ones starting with 978, which means every ISBN currently in existence has both a 10- and a 13-digit form. There are all sorts of libraries available for converting between ISBN10 and ISBN13. Basically, you add 978 to the front and recalculate the checksum digit at the end.
ISBN13 was invented because publishers were running out of ISBNs. In the near future, when 979-based ISBN13s start being used, they will not have an ISBN10 equivalent. To my knowledge, there are no published books with 979-based ISBNs, but they are coming soon. Anyway, the long and short of it is that Amazon uses the ISBN10 form for all 978 ISBN10s. In any case, whether or not Amazon uses ten or thirteen-digit ASINs, you can search Amazon by either just fine.
Personally, I wouldn't put ISBN DB at the top of your list. ISBN DB mines from a number of sources, but it's not as comprehensive as Amazon or Google. Rather, I'd look into Amazon—including the various international Amazons—and then the new Google Book Data API and, after that, the OpenLibrary API. For non-English books, there are other options, like Ozone for Russian books.
If you care about the highest-quality data, or if you have any books published before about 1970, you will want to look into data from libraries, available by Z39.50 protocol and usually in MARC format, or, with a few libraries in Dublin Core, using the SRU/SRW protocol. MARC format is, to a modern programmer, pretty strange stuff. But, once you get it, it's also better data and includes useful fields like the LCCN, DDC, LCC, and LCSH.
LibraryThing runs off a homemade Python library that queries some 680 libraries and converts the many flavors of MARC into Amazon-compatible XML, with extras. We are currently reluctant to release the code, but maybe releasing a service soon.
A: Although the other answers are correct, this one explains the process in a little more detail. This one uses the GOOGLE BOOKS API.
https://giribhatnagar.wordpress.com/2015/07/12/search-for-books-by-their-isbn/
All you need to do is
1.Create an appropriate HTTP request
2.Send it and Receive the JSON object containing detail about the book
3.Extract the title from the received information
The response you get is in JSON. The code given on the above site is for NODE.js but I'm sure it won't be difficult to reproduce that in PHP(or any other language for that matter).
A: Google has it's own API for Google Books that let's you query the Google Book database easily. The protocol is JSON based and you can view the technical information about it here.
You essentially just have to request the following URL :
https://www.googleapis.com/books/v1/volumes?q=isbn:YOUR_ISBN_HERE
This will return you the information about the book in a JSON format.
A: Check out ISBN DB API. It's a simple REST-based web service. Haven't tried it myself, but a friend has had successful experiences with it.
It'll give you book title, author information, and depending on the book, number of other details you can use.
A: Try https://gumroad.com/l/RKxO
I purchased this database about 3 weeks ago for a book citation app I'm making. I haven't had any quality problems and virtually any book I scanned was found. The only problem is that they provide the file in CSV and I had to convert 20 million lines which took me almost an hour! Also, the monthly updates are not delta and the entire database is sent which works for me but might be some work for others.
A: To obtain data for given ISBN number you need to interact with some online service like isbndb.
One of the best sources for bibliographic information is Amazon web service. It provides you with all bibliographic info + book cover.
A: You might want to look into LibraryThing, it has an API that would do what you want and they handle things like mapping multiple ISBNs for different editions of a single "work".
A: As an alternative to isbndb (which seems like the perfect answer) I had the impression that you could pass an ISBN into an Amazon product URL to go straight to the Amazon page for the book. While this doesn't programmatically return the book title, it might have been a useful extra feature in case you wanted to link to Amazon user reviews from your database.
However, this link appears to shows that I was wrong. Actually what Amazon uses is the ASIN number and while this used to be the same as 10-digit ISBN numbers, those are no longer the only kind - ISBNs now have 13 digits (though there is a straight conversion from the old 10-digit type).
But more usefully, the same link does talk about the Amazon API which can convert from ISBN to ASIN and is likely to also let you look up titles and other information. It is primarily aimed at Amazon affiliates, but no doubt it could do the job if for some reason isbndb does not.
Edit: Tim Spalding above points out a few practical facts about ISBNs - I was slightly too pessimistic in assuming that ASINs would not correspond any more.
A: You may also try this database: http://www.usabledatabases.com/database/books-isbn-covers/
It's got more books / ISBN than most web services you can currently find on the web. But it's probably an overkill for your small site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Use of var keyword in C# After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?
For example I rather lazily used var in questionable circumstances, e.g.:-
foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.
More legitimate uses of var are as follows:-
var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.
Interestingly LINQ seems to be a bit of a grey area, e.g.:-
var results = from r in dataContext.SomeTable
select r; // Not *entirely clear* what results will be here.
It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.
It's even worse when it comes to LINQ to objects, e.g.:-
var results = from item in someList
where item != 3
select item;
This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.
There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.
var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
A: Neither of those is absolutely true; var can have both positive and negative effects on readability. In my opinion, var should be used when either of the following is true:
*
*The type is anonymous (well, you don't have any choice here, as it must be var in this case)
*The type is obvious based upon the assigned expression (i.e. var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating())
var has no performance impacts, as it's syntactic sugar; the compiler infers the type and defines it once it's compiled into IL; there's nothing actually dynamic about it.
A: Stolen from the post on this issue at CodingHorror:
Unfortunately, you and everyone else pretty much got it wrong. While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:
MyObject m = new();
Or if you are passing parameters:
Person p = new("FirstName", "LastName);
Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right. This has other advantages over "var", in that it could be used in field declarations as well (there are also some other areas that it could be useful as well, but I won't get into it here).
In the end, it just wasn't intended to reduce redundancy. Don't get me wrong, "var" is VERY important in C# for anonymous types/projections, but the use here is just WAY off (and I've been saying this for a long, long time) as you obfuscate the type that is being used. Having to type it twice is too often, but declaring it zero times is too few.
Nicholas Paldino .NET/C# MVP on June 20, 2008 08:00 AM
I guess if your main concern is to have to type less -- then there isn't any argument that's going to sway you from using it.
If you are only going to ever be the person who looks at your code, then who cares? Otherwise, in a case like this:
var people = Managers.People
it's fine, but in a case like this:
var fc = Factory.Run();
it short circuits any immediate type deductions my brain could begin forming from the 'English' of the code.
Otherwise, just use your best judgment and programming 'courtesy' towards others who might have to work on your project.
A: Using var instead of explicit type makes refactorings much easier (therefore I must contradict the previous posters who meant it made no difference or it was purely "syntactic sugar").
You can change the return type of your methods without changing every file where this method is called. Imagine
...
List<MyClass> SomeMethod() { ... }
...
which is used like
...
IList<MyClass> list = obj.SomeMethod();
foreach (MyClass c in list)
System.Console.WriteLine(c.ToString());
...
If you wanted to refactor SomeMethod() to return an IEnumerable<MySecondClass>, you would have to change the variable declaration (also inside the foreach) in every place you used the method.
If you write
...
var list = obj.SomeMethod();
foreach (var element in list)
System.Console.WriteLine(element.ToString());
...
instead, you don't have to change it.
A: @aku: One example is code reviews. Another example is refactoring scenarios.
Basically I don't want to go type-hunting with my mouse. It might not be available.
A: It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).
C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.
The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...
I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?
A: In your comparison between IEnumerable<int> and IEnumerable<double> you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;
A: I guess it depends on your perspective. I personally have never had any difficulty understanding a piece of code because of var "misuse", and my coworkers and I use it quite a lot all over. (I agree that Intellisense is a huge aid in this regard.) I welcome it as a way to remove repetitive cruft.
After all, if statements like
var index = 5; // this is supposed to be bad
var firstEligibleObject = FetchSomething(); // oh no what type is it
// i am going to die if i don't know
were really that impossible to deal with, nobody would use dynamically typed languages.
A: I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
A: From Eric Lippert, a Senior Software Design Engineer on the C# team:
Why was the var keyword introduced?
There are two reasons, one which
exists today, one which will crop up
in 3.0.
The first reason is that this code is
incredibly ugly because of all the
redundancy:
Dictionary<string, List<int>> mylists = new Dictionary<string, List<int>>();
And that's a simple example – I've
written worse. Any time you're forced
to type exactly the same thing twice,
that's a redundancy that we can
remove. Much nicer to write
var mylists = new Dictionary<string,List<int>>();
and let the compiler figure out what
the type is based on the assignment.
Second, C# 3.0 introduces anonymous
types. Since anonymous types by
definition have no names, you need to
be able to infer the type of the
variable from the initializing
expression if its type is anonymous.
Emphasis mine. The whole article, C# 3.0 is still statically typed, honest!, and the ensuing series are pretty good.
This is what var is for. Other uses probably will not work so well. Any comparison to JScript, VBScript, or dynamic typing is total bunk. Note again, var is required in order to have certain other features work in .NET.
A: To me, the antipathy towards var illustrates why bilingualism in .NET is important. To those C# programmers who have also done VB .NET, the advantages of var are intuitively obvious. The standard C# declaration of:
List<string> whatever = new List<string>();
is the equivalent, in VB .NET, of typing this:
Dim whatever As List(Of String) = New List(Of String)
Nobody does that in VB .NET, though. It would be silly to, because since the first version of .NET you've been able to do this...
Dim whatever As New List(Of String)
...which creates the variable and initializes it all in one reasonably compact line. Ah, but what if you want an IList<string>, not a List<string>? Well, in VB .NET that means you have to do this:
Dim whatever As IList(Of String) = New List(Of String)
Just like you'd have to do in C#, and obviously couldn't use var for:
IList<string> whatever = new List<string>();
If you need the type to be something different, it can be. But one of the basic principles of good programming is reducing redundancy, and that's exactly what var does.
A: Use it for anonymous types - that's what it's there for. Anything else is a use too far. Like many people who grew up on C, I'm used to looking at the left of the declaration for the type. I don't look at the right side unless I have to. Using var for any old declaration makes me do that all the time, which I personally find uncomfortable.
Those saying 'it doesn't matter, use what you're happy with' are not seeing the whole picture. Everyone will pick up other people's code at one point or another and have to deal with whatever decisions they made at the time they wrote it. It's bad enough having to deal with radically different naming conventions, or - the classic gripe - bracing styles, without adding the whole 'var or not' thing into the mix. The worst case will be where one programmer didn't use var and then along comes a maintainer who loves it, and extends the code using it. So now you have an unholy mess.
Standards are a good thing precisely because they mean you're that much more likely to be able to pick up random code and be able to grok it quickly. The more things that are different, the harder that gets. And moving to the 'var everywhere' style makes a big difference.
I don't mind dynamic typing, and I don't mind implict typing - in languages that are designed for them. I quite like Python. But C# was designed as a statically explicitly-typed language and that's how it should stay. Breaking the rules for anonymous types was bad enough; letting people take that still further and break the idioms of the language even more is something I'm not happy with. Now that the genie is out of the bottle, it'll never go back in. C# will become balkanised into camps. Not good.
A: Many time during testing, I find myself having code like this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
Console.WriteLine(something);
Now, sometimes, I'll want to see what the SomeOtherThing itself contains, SomeOtherThing is not the same type that CallMethod() returns. Since I'm using var though, I just change this:
var something = myObject.SomeProperty.SomeOtherThing.CallMethod();
to this:
var something = myObject.SomeProperty.SomeOtherThing;
Without var, I'd have to keep changing the declared type on the left hand side as well. I know it's minor, but it's extremely convenient.
A: For the afficionados that think var saves time, it takes less keystrokes to type:
StringBuilder sb = new StringBuilder();
than
var sb = new StringBuilder();
Count em if you don't believe me...
19 versus 21
I'll explain if I have to, but just try it... (depending on the current state of your intellisense you may have to type a couple more for each one)
And it's true for every type you can think of!!
My personal feeling is that var should never be used except where the type is not known because it reduces recognition readabiltiy in code. It takes the brain longer to recognize the type than a full line. Old timers who understand machine code and bits know exactly what I am talking about. The brain processes in parallel and when you use var you force it to serialize its input. Why would anyone want to make their brain work harder? That's what computers are for.
A: I think the use of var should be coupled with wisely-chosen variable names.
I have no problem using var in a foreach statement, provided it's not like this:
foreach (var c in list) { ... }
If it were more like this:
foreach (var customer in list) { ... }
... then someone reading the code would be much more likely to understand what "list" is. If you have control over the name of the list variable itself, that's even better.
The same can apply to other situations. This is pretty useless:
var x = SaveFoo(foo);
... but this makes sense:
var saveSucceeded = SaveFoo(foo);
Each to his own, I guess. I've found myself doing this, which is just insane:
var f = (float)3;
I need some sort of 12-step var program. My name is Matt, and I (ab)use var.
A: I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;
A: It can certainly make things simpler, from code I wrote yesterday:
var content = new Queue<Pair<Regex, Func<string, bool>>>();
...
foreach (var entry in content) { ... }
This would have be extremely verbose without var.
Addendum: A little time spent with a language with real type inference (e.g. F#) will show just how good compilers are at getting the type of expressions right. It certainly has meant I tend to use var as much as I can, and using an explicit type now indicates that the variable is not of the initialising expression's type.
A: None, except that you don't have to write the type name twice. http://msdn.microsoft.com/en-us/library/bb383973.aspx
A: In most cases, it's just simpler to type it - imagine
var sb = new StringBuilder();
instead of:
StringBuilder sb = new StringBuilder();
Sometimes it's required, for example: anonymous types, like.
var stuff = new { Name = "Me", Age = 20 };
I personally like using it, in spite of the fact that it makes the code less readable and maintainable.
A: I used to think that the var keyword was a great invention but I put a a limit on it this was
*
*Only use var where it is obvious what the type is immediately (no scrolling or looking at return types)
I came to realise this then gave me no benefit whatsoever and removed all var keywords from my code (unless they were specifically required), for now I think that they make the code less readable, especially to others reading your code.
It hides intent and in at least one instance lead to a runtime bug in some code because of assumption of type.
A: We've adopted the ethos "Code for people, not machines", based on the assumption that you spend multiple times longer in maintenance mode than on new development.
For me, that rules out the argument that the compiler "knows" what type the variable is - sure, you can't write invalid code the first time because the compiler stops your code from compiling, but when the next developer is reading the code in 6 months time they need to be able to deduce what the variable is doing correctly or incorrectly and quickly identify the cause of issues.
Thus,
var something = SomeMethod();
is outlawed by our coding standards, but the following is encouraged in our team because it increases readability:
var list = new List<KeyValuePair<string, double>>();
FillList( list );
foreach( var item in list ) {
DoWork( item );
}
A: With LINQ another very good reason to use var is that the compiler can optimize the query much more.
If you use a static list to store the result it will execute where you assign it to the list but with var it can potential merge the original query with later queries in the code to make more optimized queries to the database.
I had an example where I pulled some data in a first query and then looped over and requested more data to print out a table.
LINQ merges these so that the first only pulled the id.
Then in the loop it added an extra join I had not done there to fetch the data I had included in the original.
When tested this proved much more efficient.
Had we not used var it had made the queries exactly as we had written them.
A: It's not bad, it's more a stylistic thing, which tends to be subjective. It can add inconsistencies, when you do use var and when you don't.
Another case of concern, in the following call you can't tell just by looking at the code the type returned by CallMe:
var variable = CallMe();
That's my main complain against var.
I use var when I declare anonymous delegates in methods, somehow var looks cleaner than if I'd use Func. Consider this code:
var callback = new Func<IntPtr, bool>(delegate(IntPtr hWnd) {
...
});
EDIT: Updated the last code sample based on Julian's input
A: Var is not like variant at all. The variable is still strongly typed, it's just that you don't press keys to get it that way. You can hover over it in Visual Studio to see the type. If you're reading printed code, it's possible you might have to think a little to work out what the type is. But there is only one line that declares it and many lines that use it, so giving things decent names is still the best way to make your code easier to follow.
Is using Intellisense lazy? It's less typing than the whole name. Or are there things that are less work but don't deserve criticism? I think there are, and var is one of them.
A: I had the same concern when I started to use var keyword.
However I got used to it over time and not going to go back to explicit variable types.
Visual Studio's compiler\intellisense are doing a very good job on making work with implicitly typed variables much easier.
I think that following proper naming conventions can help you to understand code much better then explicit typing.
It seems to be same sort of questions like "shoud I use prefixes in variable names?".
Stick with good variable names and let the compiler think on variable types.
A: Someone doesn't like criticism of var.. All answers downmodded.. oh well..
@Jon Limjap:
I know. :) What I meant was that the readability is degraded like it is in VB6. I don't like to rely on Intellisense to figure out what type a given variable is. I want to be able to figure it out using the source alone.
Naming conventions doesn't help either - I already use good names. Are we going back to prefixing?
A: I use var whenever possible.
The actual type of the local variable shouldn't matter if your code is well written (i.e., good variable names, comments, clear structure etc.)
A: It's purely a convinience. The compiler will inferre the type (based on the type of the expression on the right hand side)
A: From the discussion on this topic, the outcome appears to be:
Good: var customers = new List<Customer>();
Controversial: var customers = dataAccess.GetCustomers();
Ignoring the misguided opinion that "var" magically helps with refactoring, the biggest issue for me is people's insistence that they don't care what the return type is, "so long as they can enumerate the collection".
Consider:
IList<Customer> customers = dataAccess.GetCustomers();
var dummyCustomer = new Customer();
customers.Add(dummyCustomer);
Now consider:
var customers = dataAccess.GetCustomers();
var dummyCustomer = new Customer();
customers.Add(dummyCustomer);
Now, go and refactor the data access class, so that GetCustomers returns IEnumerable<Customer>, and see what happens...
The problem here is that in the first example you're making your expectations of the GetCustomers method explicit - you're saying that you expect it to return something that behaves like a list. In the second example, this expectation is implicit, and not immediately obvious from the code.
It's interesting (to me) that a lot of pro-var arguments say "i don't care what type it returns", but go on to say "i just need to iterate over it...". (so it needs to implement the IEnumerable interface, implying the type does matter).
A: Well this one is pretty much gonna be opinionated all the way through, but I will try to give my view on it - albeit I think my view is so mixed up that you are probably not gonna get much out of it anyways.
First of all - there's anonymous types, for which you need to use the "var" keyword in order to assign an object with an anonymous type as its class - there's not much discussion here, "var" is needed.
For simpler types however, ints, longs, strings - so forth - I tend to put in the proper types. Mainly because it is a bit of a "lazy man's tool" and I don't see much gain here, very few keystrokes and the possible confusion it could provide later down the road just ain't worth it. Especially the various types for floating point numbers (float, double, decimal) confuse me as I am not firm with the postfixes in the literals - I like to see the type in the source code.
With that said, I tend to use var alot if the type is more complex and/or it is explicitly repeated on the righthand-side of the assignment. This could be a List<string> or etc, such as:
var list = new List<string>();
In a such case, I see no use to repeat the type twice - and especially as you start changing your code and the types change - the generic types might get more and more complicated and as such having to change them twice is just a pain. However of course if you wish to code against an IList<string> then you have to name the type explicitly.
So in short I do the following:
*
*Name the type explicitly when the type is short or cannot be read out of context
*Use var when it has to be used (duh)
*Use var to be lazy when it (in my mind) does not hurt readability
A: I'm fairly new in the C# world, after a decade as a Java professional. My initial thought was along the lines of "Oh no! There goes type safety down the drain". However, the more I read about var, the more I like it.
1) Var is every bit as type safe as an explicitly declared type would be. It's all about compile time syntactic sugar.
2) It follows the principle of DRY (don't repeat yourself). DRY is all about avoiding redundancies, and naming the type on both sides is certainly redundant. Avoinding redundancy is all about making your code easier to change.
3) As for knowing the exact type .. well .. I would argue that you always have a general idea is you have an integer, a socket, some UI control, or whatever. Intellisense will guide you from here. Knowing the exact type often does not matter. E.g. I would argue that 99% of the time you don't care if a given variable is a long or an int, a float or a double. For the last 1% of the cases, where it really matters, just hover the mouse pointer above the var keyword.
4) I've seen the ridiculous argument that now we would need to go back to 1980-style Hungarian warts in order to distinguish variable types. After all, this was the only way to tell the types of variables back in the days of Timothy Dalton playing James Bond. But this is 2010. We have learned to name our variables based upon their usage and their contents and let the IDE guide us as to their type. Just keep doing this and var will not hurt you.
To sum it up, var is not a big thing, but it is a really nice thing, and it is a thing that Java better copy soon. All arguments against seem to be based upon pre-IDE fallacies. I would not hesitate to use it, and I'm happy the R# helps me do so.
A: var is like the dotted spaces in kids' books where kids have to fill it. Except in this case the Compiler will fill it with the right type which is usually written after the = sign.
A: I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:
var orders = cust.Orders;
I don't care if Customer.Orders is IEnumerable<Order>, ObservableCollection<Order> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.
Contrast the above declaration with:
ObservableCollection<Order> orders = cust.Orders;
To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
A: The most likely time you'll need this is for anonymous types (where it is 100% required); but it also avoids repetition for the trivial cases, and IMO makes the line clearer. I don't need to see the type twice for a simple initialization.
For example:
Dictionary<string, List<SomeComplexType<int>>> data = new Dictionary<string, List<SomeComplexType<int>>>();
(please don't edit the hscroll in the above - it kinda proves the point!!!)
vs:
var data = new Dictionary<string, List<SomeComplexType<int>>>();
There are, however, occasions when this is misleading, and can potentially cause bugs. Be careful using var if the original variable and initialized type weren't identical. For example:
static void DoSomething(IFoo foo) {Console.WriteLine("working happily") }
static void DoSomething(Foo foo) {Console.WriteLine("formatting hard disk...");}
// this working code...
IFoo oldCode = new Foo();
DoSomething(oldCode);
// ...is **very** different to this code
var newCode = new Foo();
DoSomething(newCode);
A: After just converting over to the 3.0 and 3.5 frameworks I learned about this keyword and decided to give it a whirl. Before committing any code I had the realization that it seemed backwards, as in going back toward an ASP syntax. So I decided to poke the higher ups to see what they thought.
They said go ahead so I use it.
With that said I avoid using it where the type requires some investigation, like this:
var a = company.GetRecords();
Now it could just be a personal thing but I immediately cant look at that and determine if its a collection of Record objects or a string array representing the name of records. Whichever the case I believe explicit declaration is useful in such an instance.
A: Static typing is about contracts, not source code. The idea there is a need to have the static information on a single line of what "should" be a small method. Common guidelines recommend rarely exceeding 25 lines per method.
If a method is large enough that you can't keep track of a single variable within that method, you are doing something else wrong that would make any criticism of var pale in comparison.
Actually, one of the great arguments for var is that it can make refactoring simpler because you no longer have to worry that you made your declaration overly restrictive (i.e. you used List<> when you should have used IList<>, or IEnumerable<>). You still want to think about the new methods signature, but at least you won't have to go back and change your declarations to match.
A: There is bound to be disagreement near the edge cases, but I can tell you my personal guidelines.
I look at these the criteria when I decide to use var:
*
*The type of the variable is obvious [to a human] from the context
*The exact type of the variable is not particularly relevant [to a human]
[e.g. you can figure out what the algorithm is doing without caring about what kind of container you are using]
*The type name is very long and interrupts the readability of the code (hint: usually a generic)
Conversely, these situations would push me to not use var:
*
*The type name is relatively short and easy to read (hint: usually not a generic)
*The type is not obvious from the initializer's name
*The exact type is very important to understand the code/algorithm
*On class hierarchies, when a human can't easily tell which level of the hierarchy is being used
Finally, I would never use var for native value types or corresponding nullable<> types (int, decimal, string, decimal?, ...). There is an implicit assumption that if you use var, there must be "a reason".
These are all guidelines. You should also think also about the experience and skills of your coworkers, the complexity of the algorithm, the longevity/scope of the variable, etc, etc.
Most of the time, there is no perfect right answer. Or, it doesn't really matter.
[Edit: removed a duplicate bullet]
A: Amazed this hasn't been noted so far, but it is common sense to use var for foreach loop variables.
If you specify a specific type instead, you risk having a runtime cast silently inserted into your program by the compiler!
foreach (Derived d in listOfBase)
{
The above will compile. But the compiler inserts a downcast from Base to Derived. So if anything on the list is not a Derived at runtime, there is an invalid cast exception. Type safety is compromised. Invisible casts are horrible.
The only way to rule this out is to use var, so the compiler determines the type of the loop variable from the static type of the list.
A: I think you may be misunderstanding the usage of var in C#. It is still strong typing, unlike the VB varient type so there is no performance hit from using it or not.
Since there is no effect on the final compiled code it really is a stylist choice. Personally I don't use it since I find the code easier to read with the full types defined, but I can imagine a couple of years down the line that full type declaration will be looked at in the same way as Hungarian notation is now - extra typing for no real benefit over the information that intellisense gives us by default.
A: I think you point out the main problem with var in your question: "I don't have to figure out the type". As other have pointed out, there is a place for var, but if you don't know the type you're dealing with, there's a pretty good chance that you're going to have problems down the road - not in all cases, but there's enough of a smell there so that you should be suspicious.
A: Apart from readability concerns, there is one real issue with the use of 'var'. When used to define variables that are assigned to later in the code it can lead to broken code if the type of the expression used to initialize the variable changes to a narrower type. Normally it would be safe to refactor a method to return a narrower type than it did before: e.g. to replace a return type of 'Object' with some class 'Foo'. But if there is a variable whose type is inferred based on the method, then changing the return type will mean that this variable can longer be assigned a non-Foo object:
var x = getFoo(); // Originally declared to return Object
x = getNonFoo();
So in this example, changing the return type of getFoo would make the assignment from getNonFoo illegal.
This is not such a big deal if getFoo and all of its uses are in the same project, but if getFoo is in a library for use by external projects you can no longer be sure that narrowing the return type will not break some users code if they use 'var' like this.
It was for exactly this reason that when we added a similar type inferencing feature to the Curl programming language (called 'def' in Curl) that we prevent assignments to variables defined using this syntax.
A: var is a placeholder introduced for the anonymous types in C# 3.0 and LINQ.
As such, it allows writing LINQ queries for a fewer amount of columns within, let's say, a collection. No need to duplicate the information in memory, only load what's necessary to accomplish what you need to be done.
The use of var is not bad at all, as it is actually not a type, but as mentioned elsewhere, a placeholder for the type which is and has to be defined on the right-hand side of the equation. Then, the compiler will replace the keyword with the type itself.
It is particularly useful when, even with IntelliSense, the name of a type is long to type. Just write var, and instantiate it. The other programmers who will read your code afterward will easily understand what you're doing.
It's like using
public object SomeObject { get; set; }
instead of:
public object SomeObject {
get {
return _someObject;
}
set {
_someObject = value;
}
}
private object _someObject;
Everyone knows what's the property's doing, as everyone knows what the var keyword is doing, and either examples tend to ease readability by making it lighter, and make it more pleasant for the programmer to write effective code.
A: One specific case where var is difficult: offline code reviews, especially the ones done on paper.
You can't rely on mouse-overs for that.
A: I don't see what the big deal is..
var something = someMethod(); // Type of 'something' not clear <-- not to the compiler!
You still have full intellisense on 'something', and for any ambiguous case you have your unit tests, right? ( do you? )
It's not varchar, it's not dim, and it's certainly not dynamic or weak typing. It is stopping maddnes like this:
List<somethinglongtypename> v = new List<somethinglongtypename>();
and reducing that total mindclutter to:
var v = new List<somethinglongtypename>();
Nice, not quite as nice as:
v = List<somethinglongtypename>();
But then that's what Boo is for.
A: If someone is using the var keyword because they don't want to "figure out the type", that is definitely the wrong reason. The var keyword doesn't create a variable with a dynamic type, the compiler still has to know the type. As the variable always has a specific type, the type should also be evident in the code if possible.
Good reasons to use the var keyword are for example:
*
*Where it's needed, i.e. to declare a reference for an anonymous type.
*Where it makes the code more readable, i.e. removing repetetive declarations.
Writing out the data type often makes the code easier to follow. It shows what data types you are using, so that you don't have to figure out the data type by first figuring out what the code does.
A: I use var extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim.
Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatically not interested in the type a variable has. var takes this much further, true, but I think that the argument remains the same from a readability point of view: The programmer shouldn't actually be interested in the type of the variable but rather in what a variable does. This is why Microsoft also calls type inference “duck typing.”
So, what does a variable do when I declare it using var? Easy, it does whatever IntelliSense tells me it does. Any reasoning about C# that ignores the IDE falls short of reality. In practice, every C# code is programmed in an IDE that supports IntelliSense.
If I am using a var declared variable and get confused what the variable is there for, there's something fundamentally wrong with my code. var is not the cause, it only makes the symptoms visible. Don't blame the messenger.
Now, the C# team has released a coding guideline stating that var should only be used to capture the result of a LINQ statement that creates an anonymous type (because here, we have no real alternative to var). Well, screw that. As long as the C# team doesn't give me a sound argument for this guideline, I am going to ignore it because in my professional and personal opinion, it's pure baloney. (Sorry; I've got no link to the guideline in question.)
Actually, there are some (superficially) good explanations on why you shouldn't use var but I still believe they are largely wrong. Take the example of “searchabililty”: the author claims that var makes it hard to search for places where MyType is used. Right. So do interfaces. Actually, why would I want to know where the class is used? I might be more interested in where it is instantiated and this will still be searchable because somewhere its constructor has to be invoked (even if this is done indirectly, the type name has to be mentioned somewhere).
A: Var, in my opinion, in C# is a good thingtm. Any variable so typed is still strongly typed, but it gets its type from the right-hand side of the assignment where it is defined. Because the type information is available on the right-hand side, in most cases, it's unnecessary and overly verbose to also have to enter it on the left-hand side. I think this significantly increases readability without decreasing type safety.
From my perspective, using good naming conventions for variables and methods is more important from a readability perspective than explicit type information. If I need the type information, I can always hover over the variable (in VS) and get it. Generally, though, explicit type information shouldn't be necessary to the reader. For the developer, in VS you still get Intellisense, regardless of how the variable is declared. Having said all of that, there may still be cases where it does make sense to explicitly declare the type -- perhaps you have a method that returns a List<T>, but you want to treat it as an IEnumerable<T> in your method. To ensure that you are using the interface, declaring the variable of the interface type can make this explicit. Or, perhaps, you want to declare a variable without an initial value -- because it immediately gets a value based on some condition. In that case you need the type. If the type information is useful or necessary, go ahead and use it. I feel, though, that typically it isn't necessary and the code is easier to read without it in most cases.
A: Given how powerful Intellisense is now, I am not sure var is any harder to read than having member variables in a class, or local variables in a method which are defined off the visible screen area.
If you have a line of code such as
IDictionary<BigClassName, SomeOtherBigClassName> nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
Is is much easier or harder to read than:
var nameDictionary = new Dictionary<BigClassName, SomeOtherBigClassName>();
A: I think the key thing with VAR is to only use it where appropriate i.e. when doing things in Linq that it facilitates (and probably in other cases).
If you've got a type for something in the then you should use it - not to do so is simple laziness (as opposed to creative laziness which is generally to be encouraged - good programmers oft work very hard to be lazy and could be considered the source of the thing in the first place).
A blanket ban is as bad as abusing the construct in the first place but there does need to be a sensible coding standard.
The other thing to remember is that its not a VB type var in that it can't change types - it is a strongly typed variable its just that the type is inferred (which is why there are people that will argue that its not unreasonable to use it in, say, a foreach but I'd disagree for reasons of both readability and maintainability).
I suspect this one is going to run and run (-:
Murph
A: Sure, int is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>, var makes things much easier.
A: In our office, our CTO has categorically banned the use of the var keyword, for the same reasons that you have stated.
Personally I find the use of var only valid in new object declarations, since the type of the object is obvious in the statement itself.
For LINQ queries, you can resolve results to:
IEnumerable<TypeReturnedBySelectObject>
A: @erlando, out of curiosity, why do you need to know the variable's type looking at the source code?
In my practice I found that variable type is matter for me only at the time I'm using it in the code.
If I'm trying to do some inappropriate operation on someVar compiler gladly gives me an error\warning.
I really don't care what type someVar has if I understand why it's being used it the given context.
A: I use var in the following situations:
*
*When I have to (result is anonymous)
*When the type is on the same line as the code, e.g.
var emp = new Employee();
Its obvious we want an Employee (because we're creating a new Employee object), so how is
Employee emp = new Employee() any more obvious?
I do NOT use var when the type cannot be inferred, e.g.
var emp = GetEmployee();
Because the return type is not immediately obvious (is at an Employee, an IEmployee, something that has nothing to do with an Employee object at all, etc?).
A: I have to agree with Matt Hamilton.
Var can make your code much more readable and understandable when used with good variable names. But var can also make your code as impossible to read and understand as Perl when used badly.
A list of good and bad uses of var isn't really going to help much either. This is a case for common sense. The larger question is one of readability vs. write-ability. Lots of devs don't care if their code is readable. They just don't want to type as much. Personally I'm a read > write guy.
A: kronoz - in that case (overloads for both) would it matter? If you have two overloads that took the different types you would essentially be saying that either can be passed and do the same thing.
You shouldn't have two overloads that do completely different actions depending on the types passed.
While you might get some confusion in that instance it would still be entirely type safe, you'd just have someone calling the wrong method.
A: I don't understand why people start debates like this. It really serves no purpose than to start flame wars at then end of which nothing is gained. Now if the C# team was trying to phase out one style in favor of the other, I can see the reason to argue over the merits of each style. But since both are going to remain in the language, why not use the one you prefer and let everybody do the same. It's like the use of everybody's favorite ternary operator: some like it and some don't. At the end of the day, it makes no difference to the compiler.
This is like arguing with your siblings over which is your favorite parent: it doesn't matter unless they are divorcing!
A: I find that using the var keyword actually makes the code more readable because you just get used to skipping the 'var' keyword. You don't need to keep scrolling right to figure out what the code is doing when you really don't care about what the specific type is. If I really need to know what type 'item' is below, I just hover my mouse over it and Visual Studio will tell me. In other words, I would much rather read
foreach( var item in list ) { DoWork( item ); }
over and over than
foreach( KeyValuePair<string, double> entry in list ) { DoWork( Item ); }
when I am trying to digest the code. I think it boils down to personal preference to some extent. I would rely on common sense on this one -- save enforcing standards for the important stuff (security, database use, logging, etc.)
-Alan.
A: I think people do not understand the var keyword.
They confuse it with the Visual Basic / JavaScript keyword,
which is a different beast all toghether.
Many people think the var keyword implies
weak typing (or dynamic typing), while in fact c# is and remains strongly typed.
If you consider this in javascript:
var something = 5;
you are allowed to:
something = "hello";
In the case of c#, the compiler would infer the type from the first statement,
causing something to be of type "int", so the second statement would result
in an exception.
People simply need to understand that using the var keyword does not imply
dynamic typing and then decide how far they want to take the use of the var keyword,
knowing it will have absolutely no difference as to what will be compiled.
Sure the var keyword was introduced to support anonymous types,
but if you look at this:
LedDeviceController controller = new LedDeviceController("172.17.0.1");
It's very very verbose, and I'm sure this is just as readable, if not more:
var controller = new LedDeviceController("172.17.0.1");
The result is exactly the same, so yes I use it throughout my code
UPDATE:
Maybe, just maybe... they should have used another keyword,
then we would not be having this discussion... perhaps the "infered" keyword instead of "var"
A: Arriving a bit late at this discussion, but I'd just like to add a thought.
To all those who are against type inference (because that's what we're really talking about here), what about lambda expressions? If you insist on always declaring types explicitly (except for anonymous types), what do you do with lambdas? How does the "Don't make me use mouseover" argument apply to var but not to lambdas?
UPDATE
I've just thought of one argument against 'var' which I don't think anyone has mentioned yet, which is that it 'breaks' "Find all references", which could mean (for example) that if you were checking out usage of a class before refactoring, you would miss all the place where the class was used via var.
A: You can let the compiler (and the fellow who maintains the code next) infer the type from the right hand side of the initializer assignment. If this inference is possible, the compiler can do it so it saves some typing on your part.
If the inference is easy for that poor fellow, then you haven't hurt anything. If the inference is hard, you've made the code harder to maintain and so as a general rule
I wouldn't do it.
Lastly, if you intended the type to be something particular, and your initializer expression actually has a different type, using var means it will be harder for you to find the induced bug. By explicitly telling the compiler what you intend the type to be, when the type isn't that, you would get an immediate diagnostic. By sluffing on the type declaration and using "var", you won't get an error on the initialization; instead, you'll get a type error in some expression that uses the identifier assigned by the var expression, and it will be harder to understand why.
So the moral is, use var sparingly; you generally aren't doing yourself or your downstream fellow maintainer a lot of good. And hope he reasons the same way, so you aren't stuck guessing his intentions because he thought using var was easy. Optimizing on how much you type is a mistake when coding a system with a long life.
A: Sometimes the compiler can also infer what is required "better" than the developer - at least a developer who does not understand what the api he's using requires.
For example - when using linq:
Example 1
Func<Person, bool> predicate = (i) => i.Id < 10;
IEnumerable<Person> result = table.Where(predicate);
Example 2
var predicate = (Person i) => i.Id < 10;
var result = table.Where(predicate);
In the above code - assuming one is using Linq to Nhibernate or Linq to SQL, Example 1 will
bring the entire resultset for Person objects back and then do filter on the client end.
Example 2 however will do the query on the server (such as on Sql Server with SQL) as the compiler is smart enough to work out that the Where function should take a Expression> rather than a Func.
The result in Example 1 will also not be further queryable on the server as an IEnumerable is returned, while in Example 2 the compiler can work out if the result should rather be a IQueryable instead of IEnumerable
A: Deleted for reasons of redundancy.
vars are still initialized as the correct variable type - the compiler just infers it from the context. As you alluded to, var enables us to store references to anonymous class instances - but it also makes it easier to change your code. For example:
// If you change ItemLibrary to use int, you need to update this call
byte totalItemCount = ItemLibrary.GetItemCount();
// If GetItemCount changes, I don't have to update this statement.
var totalItemCount = ItemLibrary.GetItemCount();
Yes, if it's hard to determine a variable's type from its name and usage, by all means explicitly declare its type.
A: In my opinion, there is no problem in using var heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.
Like any other time saver (such as auto properties for example), it is a good idea to understand what it is and how it works before using it everywhere.
A: var is not bad. Remember this. var is not bad. Repeat it. var is not bad. Remember this. var is not bad. Repeat it.
If the compiler is smart enough to figure out the type from the context, then so are you. You don't have to have it written down right there at declaration. And intellisense makes that even less necessary.
var is not bad. Remember this. var is not bad. Repeat it. var is not bad. Remember this. var is not bad. Repeat it.
A: If you know the type, use the type.
If you don't know the type, why not?
If you can't know the type, that's okay -- you've found the only valid use.
And I'm sorry, but if the best you can do is "it makes the code all line up", that's not a good answer. Find a different way to format your code.
A: One good argument why vars should not be used as a mere "typing shortcut", but should instead be used for scenarios they were primarily designed for: Resharper (at least v4.5) cannot find usages of a type if it is represented as a var. This can be a real problem when refactoring or analyzing the source code.
A: what most are ignoring:
var something = new StringBuilder();
isn't normally typed as fast as
StringBuilder something = KEY'TAB'();
A: @erlando,
Talking about refactoring it seems to be much easier to change variable type by assigning instance of new type to one variable rather then changing it in multiple places, isn't it ?
As for code review I see no big issues with var keyword. During code review I prefer to check code logic rather variable types. Of course there might be scenarios where developer can use inappropriate type but I think that number of such cases is so small it wouldn't be a reason for my to stop using var keyword.
So I repeat my question. Why does variable type matter to you?
A: @Keith -
In your comparison between
IEnumerable<int> and
IEnumerable<double> you don't need to
worry - if you pass the wrong type
your code won't compile anyway.
That isn't quite true - if a method is overloaded to both IEnumerable<int> and IEnumerable<double> then it may silently pass the unexpected inferred type (due to some other change in the program) to the wrong overload hence causing incorrect behaviour.
I suppose the question is how likely it is that this sort of situation will come up!
I guess part of the problem is how much confusion var adds to a given declaration - if it's not clear what type something is (despite being strongly typed and the compiler understanding entirely what type it is) someone might gloss over a type safety error, or at least take longer to understand a piece of code.
A: var is essential for anonymous types (as pointed out in one of the previous responses to this question).
I would categorise all other discussion of its pros and cons as "religious war". By that I mean that a comparison and discussion of the relative merits of...
var i = 5;
int j = 5;
SomeType someType = new SomeType();
var someType = new SomeType();
...is entirely subjective.
Implicit typing means that there is no runtime penalty for any variable being declared using the var keyword, so it comes down to being a debate about what makes the developers happy.
A: I don't use var as it goes against the roots of C# - C/C++/Java. Even though it's a compiler trick it makes the language feel like it's less strongly typed. Maybe 20+ years of C have engrained it all into our (the anti-var people's) heads that we should have the type on both the left and right side of the equals.
Having said that I can see its merits for long generic collection definitions and long class names like the codinghorror.com example, but elsewhere such as string/int/bool I really can't see the point. Particularly
foreach (var s in stringArray)
{
}
a saving of 3 characters!
The main annoyance for me is not being able to see the type that the var represents for method calls, unless you hover over the method or F12 it.
A: VS2008 w/resharper 4.1 has correct typing in the tooltip when you hover over "var" so I think it should be able to find this when you look for all usages of a class.
Haven't yet tested that it does that yet though.
A: Depends, somehow it makes the code look 'cleaner', but agree it makes it more unreadable to...
A: It can make code simpler and shorter, especially with complicated generic types and delegates.
Also, it makes variable types easier to change.
A: var is great when you don't want to repeat yourself. For example, I needed a data structure yesterday that was similar to this. Which representation do you prefer?
Dictionary<string, Dictionary<string, List<MyNewType>>> collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();
or
var collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();
Note that there is little ambiguity introduced by using var in this example. However, there are times when it wouldn't be such a good idea. For example, if I used var as in the following,
var value= 5;
when I could just write the real type and remove any ambiguity in how 5 should be represented.
double value = 5;
A: I don't think var per say is a terrible language feature, as I use it daily with code like what Jeff Yates described. Actually, almost everytime I use var is because generics can make for some extremely wordy code. I live verbose code but generics take it a step too far.
That said, I (obviously... ) think var is ripe for abuse. If code gets to 20+ lines in a method with vars littered through out, you will quickly make maintenance a nightmare. Additionally, var in a tutorial is incredibly counter intuitive and generally is a giant no-no in my books.
On the flipside, var is an "easy" feature that new programmers are going to latch onto and love. Then, within a few minutes/hours/days hit a massive roadblock when they start hitting the limits. "Why can't I return var from functions?" That kind of question. Also, adding a pseudo dynamic type to a strongly typed language is something that can easily trip up a new developer. In the long run, I think the var keyword will actually make c# harder to learn for new programmers.
That said, as an experienced programmer I do use var, mostly when dealing with generics ( and obviously anonymous types ). I do hold by my quote, I do believe var will be one of the worst abused c# features.
A: From Essential LINQ:
It is best not to explicitly declare the type of a range variable unless absolutely necessary. For instance, the following code compiles cleanly, but the type could have been inferred by the compiler without a formal declaration:
List<string> list = new List<string> { "LINQ", "query", "adventure" };
var query = from string word in list
where word.Contains("r")
orderby word ascending
select word;
Explicitly declaring the type of a range variable forces a behind-the-scenes call to the LINQ Cast operator. This call may have unintended consequences and may hurt performance. If you encounter performance problems with a LINQ query, a cast like the one shown here is one possible place to begin looking for the culprit. (The one exception to this rule is when you are working with a nongeneric Enumerable, in which case you should use the cast.)
A: You don't have to write out the type name and no this is not less performant as the type is resolved at compile time.
A: First.
var is not a type and not some special feature (like c# 4.0 dynamic). It is just a syntax sugar. You ask compiler to infer the type by the right hand side expression. The only necessary place is anonymous types.
I don't think that using var is neither good or evil, it is coding style. Personally i don't use it, but i don't mind using it by other team members.
A: Eric's answer here...
Namespace scoped aliases for generic types in C#
is related.
Part of the issue is that there is no strongly typed aliasing in C#. So many developers use var as a partial surrogate.
A: It's not wrong, but it can be inappropriate. See all the other responses for examples.
var x = 5; (bad)
var x = new SuperDooperClass(); (good)
var x = from t in db.Something select new { Property1 = t.Field12 }; (better)
A: "The only thing you can really say about my taste is that it is old fashioned, and in time yours will be too." -Tolkien.
A: var is good as it follows the classic DRY rule, and it is especially elegant when you indicate the type in the same line as declaring the variable. (e.g. var city = new City())
A: var is the way to deal with anonymous types, whether from LINQ statements or not. Any other use is heavily dependent on who will read your code and what guidelines are in place.
If you are the only audience or your audience is comfortable with using var or is very familiar with your code then I guess it doesn't matter. If you use it like: var s = new SqlConnection() then it largely doesnt matter and probably improves code readability. If people aren't too picky and its okay for them to do a little work to know the type when its not apparent (which is not needed in most cases, how you use it in the following statements would usually explain everything) then its alright.
But if you have picky, close-minded teammates who love to whine or if your company's design guidelines specifically forbid using var when the type is not obvious then you will most likely meet heavy opposition.
If using var makes your code insanely difficult to read, you will probably get shot by using var even if its probably your app design that is to blame.
If var introduces ambiguity (sort of like your IEnumerable/IEnumerable example), just don't use it and be explicit. But var does have its conveniences and in some cases, IMHO, even improves readabilty by reducing clutter.
A: Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
// z is compiled as an int
var z = 100;
// s is compiled as a string below
var s = "Hello";
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr =
from c in customers
where c.City == "London"
select c;
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
// list is compiled as List
var list = new List<int>();
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
var cannot be used on fields at class scope.
Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
Multiple implicitly-typed variables cannot be initialized in the same statement.
If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.
A: If you are lazy and use var for anything other than anonymous types, you should be required to use Hungarian notation in the naming of such variables.
var iCounter = 0;
lives!
Boy, do I miss VB.
A: Don't use that, makes your code unreadable.
ALWAYS use as strict typing as possible, crutches only makes your life hell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "405"
} |
Q: ActiveX control default property discovery Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!
/EDIT: Without having source to the object itself
A: I don't use VB, but here it goes.
I found Using the Value of a Control, but it's not a programmatic solution.
If you have access to the code, look for
Attribute Value.VB_UserMemId = 0
using Notepad.
A: It depends on when you want to determine this. You could print the "value" of, say, a label control (which has no "value" property) to the debugger like:
debug.print "Value for cmdTest is ["+format(cmdTest)+"]"
Which will give you something like:
Value for cmdTest is [False]
As it turns out, the default value for a command button is it's state (pressed or not), so if you put the code example above in the click event for the control, you will see "True", if you execute it somewhere else, you'll see "False".
For other results, this method will at least show you the sort of property you're looking for. You could use:
debug.print "cmdTest's value is of type ["+TypeName(oObject) +"]"
which tell you the actual type, namely:
cmdTest's value is of type [Boolean]
You could use various methods to narrow things down, such as setting the value and seeing what happens.
A: Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio.
Go to type libraries and find the library the control is housed in, for example CommandButton is stored in Microsoft Forms 2.0 Object Library. Right click the library and select view. Find the coclass representing the control and select it:
As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is:
[id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)]
void Value([in] VARIANT_BOOL rhs);
[id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)]
VARIANT_BOOL Value();
Showing you the default property.
A:
you have access to the code, look for
Unfortunetly I don't have access to the code for most of the controls. However the link is useful for the Microsoft Controls, but I still would like a way to know for other controls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails - recovering database from Production.log We recently lost a database and I want to recover the data from de Production.log.
Every request is logged like this:
Processing ChamadosController#create (for XXX.XXX.XXX.40 at 2008-07-30 11:07:30) [POST]
Session ID: 74c865cefa0fdd96b4e4422497b828f9
Parameters: {"commit"=>"Gravar", "action"=>"create", "funcionario"=>"6" ... (all other parameters go here).
But some stuff to post on de database were in the session. In the request I have the Session ID, and I also have all the session files from the server.
Is there anyway I can, from this Session ID, open de session file and get it's contents?
A: It's probably best to load the session file into a hash -- using the session-id as the key -- and then go through all the log files in chronological order, and parse out the relevant info for each session, and modify your database with it.
*
*I guess you're starting out with an old database backup? Make sure to do this in a separate Rails environment -- e.g. don't do this in production; create and use a separate "recovery" environment / DB.
*think about some sanity checks you can run on the database afterwards, to make sure that the state of the records makes sense
Going forward:
*
*make sure that you do regular backups going forward (e.g. with mysqldump if you use MySQL).
*make sure to set up your database for master/slave replication
hope this helps -- good luck!
A: Have you tried using Marshal#load? I'm not sure how you're generating those session files, but it's quite possible Rails just uses Marshal.
A: A client exactly had the same problem a few weeks ago. I came up with the following solution:
*
*play back the latest backup you have (in our case it was one year
old)
*write a small parser that moves all the requests from production in a temporary database (i chose mongodb for that): i used a rake task and "eval" to create the hash.
*play back the data in the following order
*
*play in the first create of an object, if it does not already exist.
*find the last update (by date) and play it back.
here is the regex for scanning the production.log:
file = File.open("location_of_your_production.log", "rb")
contents = file.read
contents.scan(/(Started POST \"(.*?)\" for (.*?) at (.*?)\n.*?Parameters: \{(.*?)\}\n.*?Completed (.*?) in (.*?)ms)/m).each do |x|
# now you can collect all the important data.
# do the same for GET requests as well, if you need it.
end
In my case, the temporary database speeded up the process of the logfile parsing, so the above noted steps could be taken. Of course, everything that was not sent over production.log will be lost. Also, updates of the objects would send the whole information, it might be different in your case. I could also recreate the image uploads, since the images were sent base64 encoded in the production.log.
good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java serialization with static initialization In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change.
To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.
A: You can find some information about that in the bug 4365406 and in the algorithm for computing serialVersionUID. Basically, when changing the initialization of your static member with System.getProperty(), the compiler introduces a new static property in your class referencing the System class (I assume that the System class was previously unreferenced in your class), and since this property introduced by the compiler is not private, it takes part in the serialVersionUID computation.
Morality: always use explicit serialVersionUID, you'll save some CPU cycles and some headaches :)
A: Automatic serialVersionUID is calculated based on members of a class. These can be shown for a class file using the javap tool in the Sun JDK.
In the case mentioned in the question, the member that is added/removed is the static initialiser. This appears as ()V in class files. The contents of the method can be disassembled using javap -c. You should be able to make out the System.getProperty("foo") call and assignment to MYSTRING. However an assignment with a string literal (or any compile-time constant as defined by the Java Language Specification) is supported directly by the class file, so removing the need for a static initialiser.
A common case for code targeting J2SE 1.4 (use -source 1.4 -target 1.4) or earlier is static fields to old Class instances which appear as class literals in source code (MyClass.class). The Class instance is looked up on demand with Class.forName, and the stored in a static field. It is this static field that disrupts the serialVersionUID. From J2SE 5.0, a variant of the ldc opcode gives direct support for class literals, removing the need for the synthetic field. Again, all this can be shown with javap -c.
A: If I read the spec correctly the automatic serialVersionUID shouldn't change if you change the value of a static of transient field. Take a look at Chapter 5.6 of the Spec.
However, if you think about this a bit - you start by serializing an object that has static int MYINT = 3, when you then deserialize the class you expect to get the same object back, that is, with MYINT = 3. So, if you change the static initialization you would expect the serialVersionUID to change because you can't get the same object back again.
Anyways, keep this in all your serializable classes and you can control the serialVersionUID:
private static final long serialVersionUID = 7526472295622776147L;
A: I updated the question to be more clear. I understand why initialization with a literal changes the serialVersionUID but not why dynamic initialization changes it. If you initialize with a method, the value, of course, may always be different.
Setting the serialVersionUID explicitly is fine in a subsequent version of the class only if you are sure that it is a safe change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Timezone lookup from latitude longitude Is there any library (or even better, web service) available which can convert from a latitude/longitude into a time zone?
A: The Yahoo places API provides timezone information via reverse geolocation.
Check it out.
http://developer.yahoo.com/geo/placefinder/guide/requests.html
A: I looked fairly deeply into this question for a project I am working on. GeoNames.org and EarthTools.com are both good options for many situations but with the following serious flaws:
*
*GeoNames.org finds the time zone by searching for the nearest point in their database that contains a time zone field. This often leads to the wrong result near borders. It is also painfully slow, leading to query times on the order of a couple seconds per request. It also doesn't return a valid time zone if there is no item in their database near the query point. GeoNames also restricts the number of queries that can be made per day, making bulk operations difficult.
*EarthTools.org uses a map and is able to return queries quickly, but it doesn't take into account daylight savings time for most locations, and it returns a raw offset rather than a time zone ID (i.e., they return "GMT-7" instead of "America/Chicago"). Also, I just looked at their page while preparing this post and Google Chrome warned about malware on their site. That is new to me and it may change, but is obviously a cause for concern.
These flaws meant that these existing tools were not suitable for my needs so I rolled my own solution and have published it for general use. You can find it here:
http://www.askgeo.com/
AskGeo is based on a time zone map of the world, so it returns a valid time zone for every valid latitude and longitude. It returns the standard time zone ID (e.g., "America/Los_Angeles") used on Linux and most other operating systems and programming frameworks. It also returns the current offset, taking full account of daylight savings time.
It is extremely easy to use and usage is documented on the main page of the site. The API supports batch queries, so if you need to do a lot of look-ups, please use the batch interface rather than bog down our servers with serial requests. The bulk queries are also much faster, so everybody wins.
When we first launched this, we built it on Google App Engine (GAE) and made it free to all users. This was possible because GAE's prices were so low at that time. Since then, our server load has increased substantially and GAE's prices went way up. Both factors combined led us to switch to Amazon Web Services for hosting and to start charging for commercial use, while keeping the service free for non-profit, non-commercial open source projects, and researchers. For commercial users, we provide 1000 free queries to let potential customers evaluate the API to make sure it meets their needs. See the web site for pricing and terms.
The underlying library was written in Java and due to popular demand, we also released the library under a commercial license. Full documentation of the library and pricing details are on the web site.
I hope this is useful. It certainly was useful for the project I was working on.
A: Eric Muller has made shapefile maps for the timezones of the tz (Olson) database. A few minor caveats, though:
*
*The boundaries used are often unofficial.
*It isn't updated as regularly as the tz database itself, so some newly-formed or -adjusted zones may be missing.
Those aside, however, it seems to be very accurate for most purposes.
A: Project dead :-/
These look pretty promising-
Archive link:
https://web.archive.org/web/20150503145203/http://www.earthtools.org/webservices.htm
A: How much accuracy do you need? Dividing the longitude by 15 would almost be right :p
A: Take a look at Geonames.org
It's a free webservice that allow you to get a lot of informations from a long/lat
They also provide a free (and open source) Java Client for GeoNames Webservices library (library for other language also provided: ruby, python, perl, lisp...)
Here's some info you can get from long/lat: (complete list of webservices here)
*
*Find nearest Address
*Find nearest Intersection
*Find nearby Streets
*Elevation
*Timezone
A: Timezones are now available via Google API
https://developers.google.com/maps/documentation/timezone/
A: DRT Engine takes a latitude, longitude and local datetime and returns a timezone offset. This can be used to establish the timezone of a particular location at a future date.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
} |
Q: How to use 32bit alpha-blended BMP in .Net Is there any way to use this kind of format in .Net (C#)?
I want to use the same skin format that uTorrent uses in my app, but i can't get the transparent background.
Any ideas?
Thanks for your time.
A: You need to do two things:
*
*Copy your bitmap onto the form as background.
*Call the UpdateLayeredWindow (user32.dll) to enable per-pixel alpha transparency.
The code is a liitle bit bulky, but here is a very nice sample application with source code: Per Pixel Alpha Blend in C#
A: The PixelFormat enumeration lists the formats of 'bitmaps' you can create in .Net, so you'd want PixelFormat.Format32bppArgb:
http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx
http://msdn.microsoft.com/en-us/library/3z132tat.aspx
However I'm not entirely sure that the BMP file format supports transparency - so you would have to save the file as perhaps a PNG file instead.
A: While the BMP format does support an alpha channel, Windows ignores it. Luckily, the format is rather simple and you can read it using System.IO.BinaryReader then create a Drawing.Bitmap using the LockBits and UnlockBits methods to write the data to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Recommended Source Control Directory Structure? I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?
A: I found some old questions here on SO that might be interesting for you:
*
*Whats a good standard code layout for a php application
*
*Contains a link to an article on Scalable and Flexible Directory Structure for Web Applications (focus on PHP, though)
*How to structure a java application, in other words: where do I put my classes?
*Structure of Projects in Version Control
A: To expand on what Mendelt Siebenga suggested, I would also add a web directory (for JSP files, WEB-INF, web.xml, etc).
Tests should go in a folder named test that is a sibling of the main src folder - this way your unit test classes can have the same package name as the source code being tested (to ease with situations where you want to test protected methods or classes, for example... see the JUnit FAQ for this, and this question also on Where should I put my test files?).
I haven't had much use for it myself, but a Maven project will also create a resources folder alongside the src folder for non-source code that you want to package/deploy along with the main source code - things such as properties files, resources bundles, etc. Your mileage may vary on this one.
A: I usually have
Project Directory
src - actual source
doc - documentation
lib - libraries referenced from source
dep - installation files for dependencies that don't fit in lib
db - database installation script
In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out.
EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like:
/project
/trunk
/src
/doc
/...
/branches
/feature1
/src
/doc
/...
/feature2
/src
/doc
/...
A: I use Eclipse for creating J2EE web applications and this will create the following project structure:
WebAppName\
\lib
\src
\tests
etc...
I would then create an SVN folder on our trunk called WebAppNameProject. Within this folder I would create folders called WebAppNameSource, Documentation etc. Within the WebAppNameSource folder I would place the project source generated by Eclipse. Thus I would have the following folder structure in SVN:
\svn\trunk\WebAppNameProject
\WebAppNameSource
\lib
\src
\tests
etc...
\Documentation
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Do the vi and emacs implementations for Windows behave like their Unix counterparts? If not, what are the significant differences?
Edit: Daren Thomas asks:
which ones?
I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...
By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.
A: I use GNU emacs built for Windows, and have found very few, if any, differences. There's the option to load your .emacs file from _emacs or .emacs (although .emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...).
You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your .emacs is loaded from. For more information, check the always-excellent EmacsWiki's MsWindowsInstallation page.
A: which ones?
I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...
A: GNU Emacs has long been working natively on Windows as part of the main source, and can be compiled with Visual Studio (you can also find some pre-compiled binaries). As far as I know, there are no significant differences.
A: There are quite a few vi clones (e.g. vim) and also various Emacs implementations (Gnu Emacs vs. XEmacs spring to mind).
These clones differ on Unix themselves and will thus also differ on Windows.
One thing I found with vim is that the directory structure for plugins etc. is very different on Windows - ~/vim.rc translates to %HOME%\vim_rc (or similar, depends on stuff I don't understand), vim tends to save stuff like plugins under C:\Program Files\vim\... instead of ~/.vim/...
A: The Windows versions typically use the same base source code as the "regular", Unix-based versions. There may be sections of the code that are specific to Windows, just as there are sections specific to certain flavours of Unix. In general, though, the Windows versions of these packages will behave identically to the Unix ones, except where this is not possible (for example, gvim in Windows will use Windows GUI elements, of course).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Always including the user in the django template context I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.
In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?
Or will I have to make my own custom shortcuts to setup the context properly?
A: There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" in TEMPLATE_CONTEXT_PROCESSORS and if you're using RequestContext in your views.
if you are using django 1.4 or latest the module has been moved to django.contrib.auth.context_processors.auth
A: @Ryan: Documentation about preprocessors is a bit small
@Staale: Adding user to the Context every time one is calling the template in view, DRY
Solution is to use a preprocessor
A: In your settings add
TEMPLATE_CONTEXT_PROCESSORS = (
'myapp.processor_file_name.user',
)
B: In myapp/processor_file_name.py insert
def user(request):
if hasattr(request, 'user'):
return {'user':request.user }
return {}
From now on you're able to use user object functionalities in your templates.
{{ user.get_full_name }}
A: The hints are in every answer, but once again, from "scratch", for newbies:
authentication data is in templates (almost) by default -- with a small trick:
in views.py:
from django.template import RequestContext
...
def index(request):
return render_to_response('index.html',
{'var': 'value'},
context_instance=RequestContext(request))
in index.html:
...
Hi, {{ user.username }}
var: {{ value }}
...
From here: https://docs.djangoproject.com/en/1.4/topics/auth/#authentication-data-in-templates
This template context variable is not available if a RequestContext is
not being used.
A: In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own context processor.
From the docs:
A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
A: If you can hook your authentication into the Django authentication scheme you'll be able to use request.user.
I think this should just be a case of calling authenticate() and login() based on the contents of your Cookie.
Edit: @Staale - I always use the locals() trick for my context so all my templates can see request and so request.user. If you're not then I guess it wouldn't be so straightforward.
A: @Dave
To use {{user.username}} in my templates, I will then have to use
requestcontext rather than just a normal map/hash: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext
So I guess there are no globals that the template engine checks.
But the RequestContext has some prepopulate classes that I can look into to solve my problems. Thanks.
A: its possible by default, by doing the following steps, ensure you have added the context 'django.contrib.auth.context_processors.auth' in your settings. By default its added in settings.py, so its looks like this
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.auth',)
And you can access user object like this,
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
For more information, refer here http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-data-in-templates
A: Use context_processors. https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-TEMPLATES-OPTIONS
settings.py
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'myapp.functions.test'
],
},
myapp/functions.py
def test(request):
return {'misc': 'misc'}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: XML namespaces and attributes I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...
A: Most of the time, attributes will not be in any namespace. The namespace spec says (emphasis mine):
A default namespace declaration applies to all unprefixed element names within its scope. Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.
There's a reason that most XML vocabularies use non-namespaced attributes:
When your elements have a namespace and those elements have attributes, then there can be no confusion: the attributes belong to your element, which belongs to your namespace. Adding a namespace prefix to the attributes would just make everything more verbose.
So why do namespaced attributes exist?
Because some vocabularies do useful work with mostly attributes, and can do this when mixed in with other vocabularies. The best known example is XLink.
Lastly, W3C XML Schema has an all too easy way (<schema attributeFormDefault="qualified">) of declaring your attributes as being in a namespace, forcing you to prefix them in your documents, even when you use a default namespace.
A: Read up at 6.1 Namespace Scoping and 6.2 Namespace Defaulting on w3c.
Basically:
The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag
However, the text here doesn't seem to explain if means a is foo:a or the default namespace in the context. I would assume that it does not refer to foo:a, but rather the documents default namespace a. Considering this quote at least:
Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration.
Ie. the namespace "foo:" only applies to elements prefixed with foo:
A: Examples to illustrate using the Clark notation, where the namespace prefix is replaced with the namespace URL in curly brackets:
<bar xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
<bar xmlns="http://www.foo.com/" xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
<foo:bar xmlns="http://www.foo.com/" xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
is
<{}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>
<{http://www.foo.com/}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>
<{http://www.foo.com/}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>
A: There's something related to this attributes/namespaces subject that took me some time to understand today when I was working on a XSD.
I'm going to share this experience with you in case anyone ever happens to have the same issues.
In the Schema Document I was working on there were a couple of global attributes referenced by some elements. To simplify things here let's assume this XSD I'm talking about was about a Customer.
Let's call one of these global attributes Id. And the root element using it Customer
My XSD declaration looked like this :
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns="http://schemas.mycompany.com/Customer/V1"
targetNamespace="http://schemas.mycompany.com/Customer/V1"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
My Id attribute declaration looked like this :
<xs:attribute name="Id" type="xs:positiveInteger"/>
And my Customer element used the attribute like this :
<xs:element name="Customer">
<xs:complexType>
<xs:attribute ref="Id" use="required"/>
<!-- some elements here -->
</xs:complexType>
</xs:element>
Now, let's say I wanted to declare a Customer XML document like this :
<?xml version="1.0" encoding="utf-8"?>
<Customer Id="1" xmlns="http://schemas.mycompany.com/Customer/V1">
<!-- ... other elements here -->
</Customer>
I found out that I can't : when the attribute is globally declared, it's not in the same namespace than the element who references it.
I figured out that the only solution with the XSD defined like that was to declare the namespace twice: once without a prefix in order to make it the default namespace for elements, and once with a prefix in order to use it with the attributes. So this is how it would have looked like :
<?xml version="1.0" encoding="utf-8"?>
<Customer cus:Id="1" xmlns="http://schemas.mycompany.com/Customer/V1"
xmlns:cus="http://schemas.mycompany.com/Customer/V1">
<!-- ... other elements here -->
</Customer>
This is so unpractical that I just decided to get rid of all global attributes and declare them them locally. Wich in the case of the example I gave here would have looked like this:
<xs:element name="Customer">
<xs:complexType>
<xs:attribute name="Id" type="xs:positiveInteger" use="required"/>
<!-- some elements here -->
</xs:complexType>
</xs:element>
I found it hard to find some references about what I'm talking about here in the net. I eventually found this post in the Stylus XSD Forum where a guy named Steen Lehmann suggested either to declare the attribute locally or to declare it within an attribute group
"so that the attribute declaration
itself is no longer global"
This last solution has a "hacky" taste, so I just decided to stick with the first solution and declare all my attributes locally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: How do I do monkeypatching in python? I've had to do some introspection in python and it wasn't pretty:
name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)
To get something like
foo.py:22 bar() blah blah
In our debugging output.
I'd ideally like to prepend anything to stderr with this sort of information --
Is it possible to change the behaviour of print globally within python?
A: A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.
A: The python inspect module makes this a lot easier and cleaner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Whats the best way to unit test from multiple threads? this kind of follows on from another question of mine.
Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it?
I am thinking of creating a method which just spawns lots of BackgroundWorker's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc.
Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :)
Edit
Following ajmastrean's post:
I am using a console app to test with Debug.Asserts :)
Update
I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this.
I then followed up on ajmastrean's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
A: In .NET, ThreadPool threads won't return without setting up ManualResetEvents or AutoResetEvents. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such.
Something I have found that works is
*
*Create an array of threads.
*Setup the ThreadStart method of each thread.
*Start each thread.
*Join on all threads (blocks the current thread until all other threads complete or abort)
public static void MultiThreadedTest()
{
Thread[] threads = new Thread[count];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(DoSomeWork());
}
foreach(Thread thread in threads)
{
thread.Start();
}
foreach(Thread thread in threads)
{
thread.Join();
}
}
A: @ajmastrean, since unit test result must be predictable we need to synchronize threads somehow. I can't see a simple way to do it without using events.
I found that ThreadPool.QueueUserWorkItem gives me an easy way to test such use cases
ThreadPool.QueueUserWorkItem(x => {
File.Open(fileName, FileMode.Open);
event1.Set(); // Start 2nd tread;
event2.WaitOne(); // Blocking the file;
});
ThreadPool.QueueUserWorkItem(x => {
try
{
event1.WaitOne(); // Waiting until 1st thread open file
File.Delete(fileName); // Simulating conflict
}
catch (IOException e)
{
Debug.Write("File access denied");
}
});
A: Your idea should work fine. Basically you just want to spawn a bunch of threads, and make sure the ones writing the file take long enough to do it to actually make the readers wait. If all of your threads return without error, and without blocking forever, then the test succeeds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Conditional Display in ASPX Pages on Sharepoint I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
*
*Change the PageParserPath in web.config as per this site
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
*Create all the controls and Wire them up to Events in the .CS File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
A: What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a "Web Part Page" in a document library.
I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature?
I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.
A: So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
A: Thanks so far. I've successfully tried Andrew Connel's solution:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx
Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.
What I was missing:
In the .cs File, it is required to manually add the "protected Button Trigger;" stuff, because there is no automatically generated .designer.cs file when using a class library.
A: Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.
It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to do a sample rate conversion in Windows (and OSX) I am about to write an audio file converter for my side job at the university.
As part of this I would need sample rate conversion. However, my professor said that it would be pretty hard to write a sample rate converter that was both of good quality and fast.
On my research on the subject, I found some functions in the OSX CoreAudio-framework, that could do a sample rate conversion (AudioConverter.h). After all, an OS has to have some facilities to do that for its own audio stack.
Do you know a similar method for C/C++ and Windows, that are either part of the OS or open source?
I am pretty sure that this function exists within DirectX Audio (XAudio2?), but I seem to be unable to find a reference to it in the MSDN library.
A: Try Secret Rabbit Code (= SRC = Sample Rate Conversion ) It's GPL, it's fast and it's high quality. http://www.mega-nerd.com/SRC/license.html
A: If you're worried about quality, check out http://src.infinitewave.ca/. Very good comparisons on different resamplers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do you properly use namespaces in C++? I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
A: Vincent Robert is right in his comment How do you properly use namespaces in C++?.
Using namespace
Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the "org.domain" idiom (because it is supposed one won't use anything else than his/her own domain name).
In C++, you could give a namespace to all the code in your module. For example, for a module MyModule.dll, you could give its code the namespace MyModule. I've see elsewhere someone using MyCompany::MyProject::MyModule. I guess this is overkill, but all in all, it seems correct to me.
Using "using"
Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.
This is evil to do it in a header file because your header will pollute every source including it (it reminds me of macros...), and even in a source file, bad style outside a function scope because it will import at global scope the symbols from the namespace.
The most secure way to use "using" is to import select symbols:
void doSomething()
{
using std::string ; // string is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
std::cout << a << std::endl ;
}
void doSomethingElse()
{
using namespace std ; // everything from std is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
cout << a << endl ;
}
You'll see a lot of "using namespace std ;" in tutorial or example codes. The reason is to reduce the number of symbols to make the reading easier, not because it is a good idea.
"using namespace std ;" is discouraged by Scott Meyers (I don't remember exactly which book, but I can find it if necessary).
Namespace Composition
Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".
In the "Special Edition", at 8.2.8 Namespace Composition, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:
namespace AAA
{
void doSomething() ;
}
namespace BBB
{
void doSomethingElse() ;
}
namespace CCC
{
using namespace AAA ;
using namespace BBB ;
}
void doSomethingAgain()
{
CCC::doSomething() ;
CCC::doSomethingElse() ;
}
You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.
A: I did not see any mention of it in the other answers, so here are my 2 Canadian cents:
On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;
you can write:
namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;
A: @marius
Yes, you can use several namespaces at a time, eg:
using namespace boost;
using namespace std;
shared_ptr<int> p(new int(1)); // shared_ptr belongs to boost
cout << "cout belongs to std::" << endl; // cout and endl are in std
[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]
A: Don't listen to every people telling you that namespaces are just name-spaces.
They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:
namespace ns {
class A
{
};
void print(A a)
{
}
}
If you wanted to print an A object, the code would be this one:
ns::A a;
print(a);
Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.
Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.
namespace ns {
class A
{
};
}
void print(A a)
{
}
And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.
Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.
And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.
If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter
A: You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
A: Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.
A:
Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).
Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.
Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.
Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:
namespace {
const int CONSTANT = 42;
}
This is basically the same as:
static const int CONSTANT = 42;
Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.
A: Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala boost:: .
A: I prefer using a top-level namespace for the application and sub namespaces for the components.
The way you can use classes from other namespaces is surprisingly very similar to the way in java.
You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.
A: Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:
namespace MyNamespace
{
double square(double x) { return x * x; }
}
in a file square.h, and
namespace MyNamespace
{
double cube(double x) { return x * x * x; }
}
in a file cube.h. This defines a single namespace MyNamespace (that is, you can define a single namespace across multiple files).
A: I've used C++ namespaces the same way I do in C#, Perl, etc. It's just a semantic separation of symbols between standard library stuff, third party stuff, and my own code. I would place my own app in one namespace, then a reusable library component in another namespace for separation.
A: Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:
#include "lib/module1.h"
#include "lib/module2.h"
lib::class1 *v = new lib::class1();
I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.
A: Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
Then in code:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked below, you can use as many namespaces as you like.
A: To avoid saying everything Mark Ingram already said a little tip for using namespaces:
Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.
I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.
Sometimes namespaces are used in bigger C++ projects to hide implementation details.
Additional note to the using directive:
Some people prefer using "using" just for single elements:
using std::cout;
using std::endl;
A: In Java:
package somepackage;
class SomeClass {}
In C++:
namespace somenamespace {
class SomeClass {}
}
And using them, Java:
import somepackage;
And C++:
using namespace somenamespace;
Also, full names are "somepackge.SomeClass" for Java and "somenamespace::SomeClass" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren't there though, so you can name your folders and classes independently off packages and namespaces.
A: std :: cout
The
prefix std:: indicates that the
names cout and endl are
defined inside the namespace
named std. Namespaces allow
us to avoidinadvertent collisions
between the names we define
and uses of those same names
inside a library. All the names
defined by the standard library
are in the stdnamespace. Writing std::
cout uses the scope operator
(the ::operator) to saythat we
want to use the name cout
that is defined in the
namespace std.
will show a simpler way to
access names from the library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "240"
} |
Q: Import OLE Object from Access to MySQL I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on this site
and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt.
The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field.
Has anyone had this issue before and how did they resolve it ?
A: Ok so in the interests of airing my dirty code in public here what i came up with.
Note : this is a hack designed to be used once and then thrown away.
This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field.
Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap
Dim oImage As Bitmap = New Bitmap("c:\default.jpg")
Try
If Not IsDBNull(row(columnName)) Then
If row(columnName) IsNot Nothing Then
Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte()))
If mStream.Length > 0 Then
Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte
mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1))
Dim position As Integer = 0
For index As Integer = 0 To b.Length - 3
If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then
position = index
Exit For
End If
Next
If position > 0 Then
Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position)
oImage = New Bitmap(jpgStream)
End If
End If
End If
End If
Catch ex As Exception
Throw New ApplicationException(ex.Message, ex)
End Try
Return oImage
End Function
Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry.
It worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it.
A: As far as I remember, the Microsoft "SQL Server Migration Assistant for Access" will properly migrate OLE Images, but this is only for Access->SQLServer. However, what you can do is use this to migrate to SQLServer Express (free download) and then migrate from SQLServer to MySQL.
A: There's also olefield - Python module to extract data out of OLE object fields in Access. I successfully extracted BMP files with it. It could probably work with jpeg images, but I haven't tried it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: User Interface Testing We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality.
We have non-technical users perform testing, but they often miss parts and allow bugs to slip through.
Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it?
A: You can automate GUI testing using White framework.
Also consider using TDD friendly design, i.e. use MVP/MVC pattern.
I would highly recommend you to read documentation from Microsoft patterns&practies teams.
Especially have a look at the Composite UI application block and CompositeWPF.
These projects specifically designed to give you best practices in GUI apps development including test driven UI.
A: Keep the GUI layer as thin as possible. Michael Feathers article, The Humble Dialog Box, is a classic. Also check out Martin Fowler's Passive View. I have also heard that the "automatic button clickers" are fragile, and that it's easy to spend more time maintaining the test than you spend maintaining the code.
A: In the event that someone finds this useful:
List of GUI testing tools found on Wikipedia.
A: There are GUI testing tools that will click buttons and stuff for you but they're pretty fragile in my experience.
The best thing to do is to keep your UI layer as thin as possible. Your event handler classes should optimally be only one or two lines that call out to other more testable classes. That way you can test your business logic in unit tests without having to actually do a button click.
A: The following book is an introduction to the subject.
There are as many ways as there are developers out there..
http://pragprog.com/titles/idgtr/scripted-gui-testing-with-ruby
A: There are many tools and libraries available that can automate WinForms testing, ranging from open source solutions like White to the expensive commercial solutions such as HP QuickTest Pro. There is also the UIAutomation namespace in .NET if you want to roll your own automation framework. But the real cost of automation is in the time and specialised skills it requires to implement. Maintainability is also one of the most important aspects of automated test design; you dont want to expend excessive resource keeping the automation assets current with your application. There are also lots of factors influencing the decision to automate which will be specific to your specific application and organisation.
Your best bet will be to do some more research on the subject and check out some of the specialised testing sites such as http://www.sqaforums.com.
A: I found this quick and dirty way to test web page layouts in various browsers. It's called browsershots.org. Our client requires support in 5 browsers right now and that takes about a week for full regression testing. This service will deliver screenshots of some 70+ browsers and versions. I print them out and hold up the pages to the light. If they don't line up, there must be a layout problem.
A: I can't really help with organization or best practices, but an NUnit extension appears to be available for forms testing, NUnitForms.
A: I used a trial download similar to this product (http://www.tethyssolutions.com/product.htm) and this product (http://www.mjtnet.com/macro_scheduler.htm) years ago and I was happy with the results. These are pretty cheap solutions and some of these macro recorder products can actually be used for automated testing.
A: A new method available now is using Ruby, via the Ruby gem called win32-autogui. This provides a framework for testing Windows GUI apps. Combine it with Ruby tools RSpec and Cucumber, and it makes for quite a powerful testing framework.
A: How to organize UI testing depends on how you design the test cases.
Automating Windows Forms application in unit test level can use TDD framework, such as NUnit; or use BDD framework, such as NSpec.
Automating Windows Forms applications in functional testing level can use White, CodedUI, or even directly using Windows Automation API 3.0 (UI Automation and MSAA).
Since all these stuffs mentioned above are technologies rather than solutions, it's better to build some fundamental test automation/scripting frameworks based on these technologies before you start to write automated tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: is it possible to concat arguments to a command line using backquotes ? I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.
I know that's possible by using keyword system like that :
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory
but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : ls)
A: No, that will just concatenate the output from ls and the contents of directory.
But you can do this:
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`
A: `ls #{directory}`
isn't very safe because you're going to run into problems with path names that have spaces in them.
It's safer to do something like this:
directory = '/home/paulgreg/'
args = []
args << "/bin/ls"
args << directory
system(*args)
A: Nick is right, but there is no need to assemble the args piecewise:
directory = '/Volumes/Omg a space/'
system('/bin/ls', directory)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Suggestions on how to map from Domain (ORM) objects to Data Transfer Objects (DTO) The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!
The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!
We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).
Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object Person will be mapped to say PersonDTO. I do not want to do this manually since it is a waste.
Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that "cooler" will be suggested.
Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.
Example code:
By @ajmastrean's request I have linked to an example that I have (badly) mocked together. The example has a capture form, capture form controller, domain objects, activerecord repository and an async helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called ActiveRecordAsync on your local machine or just change the .config file.
Basic details of example:
The Capture Form
The capture form has a reference to the contoller
private CompanyCaptureController MyController { get; set; }
On initialise of the form it calls MyController.Load()
private void InitForm ()
{
MyController = new CompanyCaptureController(this);
MyController.Load();
}
This will return back to a method called LoadComplete()
public void LoadCompleted (Company loadCompany)
{
_context.Post(delegate
{
CurrentItem = loadCompany;
bindingSource.DataSource = CurrentItem;
bindingSource.ResetCurrentItem();
//TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
grdEmployees.DataSource = loadCompany.Employees;
}, null);
}
}
this is where the "bad stuff" occurs, since we are using the child list of Company that is set as Lazy load.
The Controller
The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.
public void Load ()
{
new AsyncListLoad<Company>().BeginLoad(LoadCompany, Form.LoadCompleted);
}
The LoadCompany() method simply makes use of the Repository to find a know company.
public Company LoadCompany()
{
return ActiveRecordRepository<Company>.Find(Setup.company.Identifier);
}
The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the ActiveRecordMediator abilities.
A: I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts. I created a number of methods that had signatures like this:
public static T ChangeType<S, T>(this S source) where T : class, new()
The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type. It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary.
Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria:
public static T ChangeType<S, T>(this S source, Action<S, T> additionalOperations) where T : class, new()
... so you could do this for your Person to PersonDTO example:
Person p = new Person( /* set whatever */);
PersonDTO = p.ChangeType<Person, PersonDTO>();
And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code for those types in that order (i.e. copying PersonDTO to Person would also incur a hit to emit the code).
It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here.
Richard
A: use ValueInjecter, with it you can map anything to anything e.g.
*
*object <-> object
*object <-> Form/WebForm
*DataReader -> object
and it has cool features like: flattening and unflattening
the download contains lots of samples
A: You should automapper that I've blogged about here:
http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links
As long as the properties are named the same on both your objects automapper will handle it.
A: My apologies for not really putting the details in here, but a basic OO approach would be to make the DTO a member of the ActiveRecord class and have the ActiveRecord delegate the accessors and mutators to the DTO. You could use code generation or refactoring tools to build the DTO classes pretty quickly from the AcitveRecord classes.
A: Actually I got totally confussed now.
Because you are saying: "We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM)."
*
*Domain objects know and care about DB? Isn't that the whole point of domain objects to contain business logic ONLY and be totally unaware of DB and ORM?....You HAVE to have these objects? You just need to FIX them if they contain all that stuff...that's why I am a bit confused how DTO's come into picture
*Could you provide more details on what problems you're facing with lazy loading?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Mute Specific Application in Vista I am in need of a way to mute a specific application in Vista.
Example: Mute just Firefox, but not all of the other application. Much similar to muting a specific program from within the volume mixer in vista.
If there is a program that will do this, i would appreciate that. Otherwise if there is a way to do this, I will write a small app(Preferrably something .net).
EDIT: I want to automate this procedure, possibly key-map it.
A: I suggest using the built in Mixer in Vista...
Why do you want to use an 3rd party program?
A: Using AutoHotkey, this works even better than expected! Just a fast window flash and BOOM, done.
Src: http://feebdack.com/knob/how_to_mute_a_single_application
#NoEnv ;// Recommended for new scripts
#Persistent ;// Recommended for new scripts
SendMode Input ;// Recommended for new scripts
SetTitleMatchMode 2
;// Set VolumeMute to only silence Media Center
$f3::
MuteMediaCenter()
return
MuteMediaCenter()
{
;// Open mixer
Run sndvol
WinWait Volume Mixer
;// Mute Standard Media Center Process
appName = Chrome
MuteApp(appName)
;// Mute Netflix Media Center Process
appName = Firefox
MuteApp(appName)
WinClose Volume Mixer
}
;// Volume Mixer must exist
MuteApp(appName)
{
;// Find X position & width of textblock with text matching our appName
ControlGetPos, refX, , refW, , % appName, Volume Mixer
;// Find button with left side within the width of the textblock
x = -1
while ( x != "")
{
;// A_Index is current loop iteration→used to find id
tbIDX := (A_Index * 2)
ControlGetPos, x, , , , ToolbarWindow32%tbIDX%, Volume Mixer
diff := x - refX
if (diff > 0 && diff < refW)
{
;// msgbox diff: %diff% refX: %refX% tbIDX: %tbIDX% x: %x% A_Index: %A_Index%
ControlClick, ToolbarWindow32%tbIDX%, Volume Mixer
break
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Store more than 3GB of video-frames in memory, on 32-bit OS At work we have an application to play 2K (2048*1556px) OpenEXR film sequences. It works well.. apart from when sequences that are over 3GB (quite common), then it has to unload old frames from memory, despite the fact all machines have 8-16GB of memory (which is addressable via the linux BIGMEM stuff).
The frames have to he cached into memory to play back in realtime. The OS is a several-year old 32-bit Fedora Distro (not possible to upgradable to 64bit, for the foreseeable future). The per-process limitation is 3GB per process.
Basically, is it possible to cache more than 3GB of data in memory, somehow? My initial idea was to spread the data between multiple processes, but I've no idea if this is possible..
A: One possibility may be to use mmap. You would map/unmap different parts of your data into the same virtual memory region. You could only have one set mapped at a time, but as long as there was enough physical memory, the data should stay resident.
A: How about creating a RAM drive and loading the file into that ... assuming the RAM drive supports the BIGMEM stuff for you.
You could use multiple processes: each process loads a view of the file as a shared memory segment, and the player process then maps the segments in turn as needed.
A: I assume you can modify the application. If so, the easiest thing would be to start the application several times (once for each 3GB chunk of video), have each one hold a chunk of video, and use another program to synchronize them so they each take control of the framebuffer (or other video output) in turn.
The synchronization is going to be a little messy, perhaps, but it can be simplified if each app has its own framebuffer and the sync program points the video controller to the correct framebuffer inbetween frames when switching to the next app.
A: My, what an interesting problem :)
(EDIT: Oh, I just read Rob's ram drive post...I got all excited by the problem...but have a bit more to suggest, so I won't delete)
Would it be possible to...
*
*setup a multi-gigabyte ram disk, and then
*modify the program to do all it's reading from the "disk"?
I'd guess the ram disk part is where all the problem would be, since the size of the ram disk would be OS and file system dependent. You might have to create multiple ram disks and have your code jump between them. Or maybe you could setup a RAID-0 stripe set over multiple ram disks. Or, if there are still OS limitations and you can afford to drop a couple grand (4k?), setup a hardware RAID-0 strip set with some of those new blazing fast solid state drives. Or...
Fun, fun, fun.
Be sure to follow up!
A: @dbr said:
There is a review machine with an absurd fiber-channel-RAID-array that can play 2K files direct from the array easily. The issue is with the artist-workstations, so it wouldn't be one $4000 RAID array, it'd be hundreds..
Well, if you can accept a limit of ~30GB, then maybe a single 36GB SSD drive would be enough? Those go for ~US$1k each I think, and the data rates might be enough. That very well maybe cheaper than a pure RAM approach. There are smaller sizes available, too. If ~60GB is enough you could probably get away with a JBOD array of 2 for double the cost, and skip the RAID controller. Be sure only to look at the higher end SSD options--the low end is filled with glorified memory sticks. :P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP Include function outputting unknown char When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include.
At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: (link no longer working) http://driveefficiently.com/testinclude.php this file consists of only:
<? include("include.inc"); ?>
and include.inc consists of only:
<? echo ("hello, world"); ?>
and yet, the output is: "?hello, world" where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit.
Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
A: Your web server (or your text editor) apparently includes a BOM into the document. I don't see the rogue character in my browser except when I set the site's encoding explicitly to Latin-1. Then, I see two (!) UTF-8 BOMs.
/EDIT: From the fact that there are two BOMs I conclude that the BOM is actually included by your editor at the beginning of the file. What editor do you use? If you use Visual Studio, you've got to say “Save As …” in the File menu and then choose the button “Save with encoding …”. There, choose “UTF-8 without BOM” or something similar.
A: What you are seeing is a UTF-8 Byte Order Mark:
The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8.
Byte Order Mark on Wikipedia
PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM.
You can read more about this problem here
A: It doesn't show up on the rendered page in Firefox or IE but you can see the funny character when you View Source in IE
Is this on a Linux machine? Could you do find & replace with vim or sed to see if you can get rid of the 3F that way?
If it's on Windows, try opening include.inc with Notepad to see if the funny char is visible & can be deleted.
I'd also be curious to see what happens if you copy the code out of the include and just run it by itself.
A: I see hello, world on the page you linked to. No problems that I can see...
I'm using Firefox 3.0.1 and Windows XP. What browser/OS are you running? Perhaps that might be the problem.
A: Character 3F actually is the question mark, it isn't just displaying as one.
I get the same results as Thomas, no question mark showing up.
In theory it could be some problem with a web proxy but I am inclined to suspect a stray question mark in your PHP markup...which perhaps you have fixed by now so we don't see the problem.
A:
I'd also be curious to see what
happens if you copy the code out of
the include and just run it by itself.
Mark: this is on a shared hosting solution, so I can not get shell access to the file. However, as you can see here, there are no characters that shouldn't be there, and running the same file as a script does not produce this char. (The shared hosting company have been of 0 help, continually telling me it is a browser issue).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using Custom MembershipProvider without a Login control in ASP.NET We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated:
*
*User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine.
*An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in.
Here is the code snippet I am using
if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) {
string ticket = Request.QueryString["authenticationToken"];
MyMembershipProvider provider = Membership.Provider as MyMembershipProvider;
if (provider != null) {
if (provider.ValidateUser(ticket))
// Login Success
else
// Login Fail
}
}
A: You can set your own FormsAuthenticationTicket if the validation is successful.
Something like this;
if (provider != null) {
if (provider.ValidateUser(ticket)) {
// Login Success
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, //version
someUserName, //name
DateTime.Now, //issue date
DateTime.Now.AddMinutes(lengthOfSession), //expiration
false, // persistence of login
FormsAuthentication.FormsCookiePath
);
//encrypt the ticket
string hash = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
Response.Cookies.Add(cookie);
Response.Redirect(url where you want the user to land);
} else {
// Login Fail
}
}
A: After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx
EDIT: It is FormsAuthentication.SetAuthCookie:
http://msdn.microsoft.com/en-us/library/twk5762b.aspx
Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx
link text
A: You are right in the case of storing the auth information as a cookie directly. But using a strong hash function (e.g. MD5 + SHA1) is great and secure.
By the way, if you use sessions (which is also just a hash cookie) you could attach auth information to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: C++ libraries to manipulate images Do you know any open source/free software C++ libraries to manipulate images in these formats:
.jpg .gif .png .bmp ? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using steganography.
I am working under Unix.
A: ImageMagick can manipulate about anything and has interfaces for a dozen of languages, including the Magick++ API for C++.
A: @lurks: I assume that you are looking for LSB shifting? I did some stego work a couple of years ago, and that's how it appeared most apps worked. It appears that ImageMagick (suggested by others) allows you to identify and manipulate the LSBs.
A: It takes some setting up, but I'm a fan of Adobe's GIL (now part of Boost).
A: Have you considered GDI?
-- Kevin Fairchild
A: FreeImage is pretty solid. It has a C interface but is more C++-like in its implementation.
A: I like vxl
VXL (the Vision-something-Libraries) is a collection of C++ libraries designed for computer vision research and implementation. It was created from TargetJr and the IUE with the aim of making a light, fast and consistent system. VXL is written in ANSI/ISO C++ and is designed to be portable over many platforms.
A: For .png images you could look into Cairo (and CairoMM). There's also Anti-Grain which people consider very fast.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Is there a way to access web.xml properties from a Java Bean? Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container?
For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example,
*
*a properties file in the classpath,
*a web.xml parameter,
*a system property, or
*some default logic if nothing else is available.
I'd like to be able to do this without injecting any reference to ServletConfig or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container.
This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml.
If I recall correctly, .NET has something like Request.GetCurrentRequest() to get a reference to the currently executing Request - but since this is a Java app I'm looking for something simliar that could be used to gain access to ServletConfig.
A: One way you could do this is:
public class FactoryInitialisingServletContextListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
Properties properties = new Properties();
ServletContext servletContext = event.getServletContext();
Enumeration<?> keys = servletContext.getInitParameterNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = servletContext.getInitParameter(key);
properties.setProperty(key, value);
}
Factory.setServletContextProperties(properties);
}
}
public class Factory {
static Properties _servletContextProperties = new Properties();
public static void setServletContextProperties(Properties servletContextProperties) {
_servletContextProperties = servletContextProperties;
}
}
And then have the following in your web.xml
<listener>
<listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class>
</listener>
If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the _servletContextProperties will be replaced with any context-params specified in the web.xml.
If your application is running outside a web container, then _servletContextProperties will be empty.
A: Have you considered using the Spring framework for this? That way, your beans don't get any extra cruft, and spring handles the configuration setup for you.
A: I think that you will have to add an associated bootstrap class which takes a reference to a ServletConfig (or ServletContext) and transcribes those values to the Factory class. At least this way you can package it separately.
@toolkit : Excellent, most humbled - This is something that I have been trying to do for a while
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Bmp to jpg/png in C# Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
A: var qualityEncoder = Encoder.Quality;
var quality = (long)<desired quality>;
var ratio = new EncoderParameter(qualityEncoder, quality );
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;
bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
A: public static class BitmapExtensions
{
public static void SaveJPG100(this Bitmap bmp, string filename)
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(filename, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJPG100(this Bitmap bmp, Stream stream)
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
A: Provided BitmapExtensions by jestro are great, I used them. However would like to show the corrected version - works for Image parent class which is more convenient as I think and provides a way to supply quality:
public static class ImageExtensions
{
public static void SaveJpeg(this Image img, string filePath, long quality)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
img.Save(filePath, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
public static void SaveJpeg(this Image img, Stream stream, long quality)
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
img.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
return codecs.Single(codec => codec.FormatID == format.Guid);
}
}
A: Fundamentally you won't be able to keep the same quality because jpg is (so far as I'm aware) always lossy even with the highest possible quality settings.
If bit-accurate quality is really important, consider using png, which has some modes which are lossless.
A: Just want to say that JPEG is by nature a lossy format. So in thoery even at the highest settings you are going to have some information loss, but it depends a lot on the image.But png is lossless.
A: I am working on an expense report app, and I am really pleased with the default quality settings for JPG (and PNG) when saving from a Bitmap object.
https://msdn.microsoft.com/en-us/library/9t4syfhh%28v=vs.110%29.aspx
Bitmap finalBitmap = ....; //from disk or whatever
finalBitmap.Save(xpsFileName + ".final.jpg", ImageFormat.Jpeg);
finalBitmap.Save(xpsFileName + ".final.png", ImageFormat.Png);
I'm on .NET 4.6...perhaps the quality has improved in subsequent framework releases.
A: You can try:
Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;
and
Bitmap.CompositingQuality = CompositingQuality.HighQuality;
Which does keep the quality fairly high, but not the highest possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: Is there a class to generate a sample XML document from XSD schema in .NET In Visual Studio you can create a template XML document from an existing schema. The new XML Schema Explorer in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the XmlSampleGenerator article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?
A: some footwork is involved, but you could load the xsd into a DataSet object, iterate over the Tables and add a few rows in each by calling calling NewRow() on each and then adding those rows back into their respective tables.. then save the DataSet out to a file:
DataSet ds = new DataSet();
ds.ReadXmlSchema("c:/xsdfile.xsd");
foreach(DataTable t in ds.Tables)
{
var row = t.NewRow();
t.Rows.Add(row);
}
ds.WriteXml("c:/example.xml");
P.S. A little extra work, but instead of just iterating over each table type and adding empty rows, you could build a nice winform that would allow you to drop in some data for each of the rows. I built something like this in about an hour a few weeks ago.
A: Have you tried http://xsd2code.codeplex.com/????
It worked for me, it can work for you.
A: Directly, none that I can think of, other than third party add-ons. You could utilize the xsd schema definition tool to take your XSD and create a .NET object/class, once you have that, you could, to quote the linked page:
XSD to Classes: Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with System.Xml.Serialization.XmlSerializer to read and write XML code that follows the schema.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Is there a way of getting the process id of my C++ application? Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
A: can you use the getpid() function found in unistd.h ?
osx reference
A: GetProcessPID is what you need. This takes a ProcessSerialNumber, which you can obtain from GetCurrentProcess.
A: Note that you don't actually need to call GetCurrentProcess, you can use the constant kCurrentProcess.
(But getpid is a lot less work if you're not trying to access another process's PID, anyway.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why is my image coming out garbled? I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String customerPath = "\\leetest\\";
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
// Form field. Ignore for now
} else {
BufferedInputStream stream = new BufferedInputStream(item
.openStream());
if (stream == null) {
LOGGER
.error("Something went wrong with fetching the stream for field "
+ name);
}
byte[] bytes = StreamUtils.getBytes(stream);
FileManager.createFile(customerPath, item.getName(), bytes);
stream.close();
}
}
}
} catch (Exception e) {
throw new UploadException("An error occured during upload: "
+ e.getMessage());
}
}
StreamUtils.getBytes(stream) looks like:
public static byte[] getBytes(InputStream src, int buffsize)
throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buff = new byte[buffsize];
while (true) {
int nBytesRead = src.read(buff);
if (nBytesRead < 0) {
break;
}
byteStream.write(buff);
}
byte[] result = byteStream.toByteArray();
byteStream.close();
return result;
}
And finally FileManager.createFile looks like:
public static void createFile(String customerPath, String filename,
byte[] fileData) throws IOException {
customerPath = getFullPath(customerPath + filename);
File newFile = new File(customerPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(fileData);
outputStream.close();
}
Can anyone spot what I'm doing wrong?
Cheers,
Lee
A: One thing I don't like is here in this block from StreamUtils.getBytes():
1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 }
6 byteStream.write(buff);
7 }
At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this:
1 while (true) {
2 int nBytesRead = src.read(buff);
3 if (nBytesRead < 0) {
4 break;
5 } else {
6 byteStream.write(buff, 0, nBytesRead);
7 }
8 }
Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6.
I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.
A: I'd just use commons io Then you could just do an IOUtils.copy(InputStream, OutputStream);
It's got lots of other useful utility methods.
A: Are you sure that the image isn't coming through garbled or that you aren't dropping some packets on the way in.
A: I don't know what difference it makes, but there seems to be a mismatch of method signatures. The getBytes() method called in your doPost() method has only one argument:
byte[] bytes = StreamUtils.getBytes(stream);
while the method source you included has two arguments:
public static byte[] getBytes(InputStream src, int buffsize)
Hope that helps.
A: Can you perform a checksum on your original file, and the uploaded file and see if there is any immediate differences?
If there are then you can look at performing a diff, to determine the exact part(s) of the file that are missing changed.
Things that pop to mind is beginning or end of stream, or endianness.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jQuery tablesorter plugin column width incorrect in IE7 I am using the tablesorter plugin (http://tablesorter.com) and am having a problem with column widths in IE7. It looks fine in Firefox and sometimes in IE7.
Here's a screenshot of the problem:
IE7 View
and here's how it's supposed to look:
Firefox view
A: This is a common layout problem in IE. If you are using CSS to style the columns width, also add the column widths to the td tags. Set the first column to a percentage that will try to suck up most of the space, like 50% or something. The first column width will take everything that it can and the other columns will abide by their static width.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Creating Windows service without Visual Studio So creating a Windows service using Visual Studio is fairly trivial. My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application. I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.
A: Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).
The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.
ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.
Here are some snippets from a service I wrote a few years ago:
set up as service:
SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
{ "ServiceName", ServiceMain },
{ 0, 0 }
};
if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
DWORD err = GetLastError();
if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
return false;
}
ServiceMain:
void WINAPI ServiceMain(DWORD, LPTSTR*)
{
hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);
service handler:
DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
switch (ControlCode)
{
case SERVICE_CONTROL_INTERROGATE :
// update OS about our status
case SERVICE_CONTROL_STOP :
// shut down service
}
return 0;
}
A: Hope this helps:
http://support.microsoft.com/kb/251192
It would seem that you simple need to run this exe against a binary executable to register it as a service.
A: Basically there are some registry settings you have to set as well as some interfaces to implement.
Check out this: http://msdn.microsoft.com/en-us/library/ms685141.aspx
You are interested in the SCM (Service Control Manager).
A: I know I'm a bit late to the party, but I've recently had this same question, and had to struggle through the interwebs looking for answers.
I managed to find this article in MSDN that does in fact lay the groundwork. I ended up combining many of the files here into a single exe that contains all of the commands I need, and added in my own "void run()" method that loops for the entirely life of the service for my own needs.
This would be a great start to someone else with exactly this question, so for future searchers out there, check it out:
The Complete Service Sample
http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Splitting tuples in Python - best practice? I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)
For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job
I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?
Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields
or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
A: This is an old question, but...
I'd suggest using a named tuple in this situation: collections.namedtuple
This is the part, in particular, that you'd find useful:
Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute.
A: Perhaps this is overkill for your case, but I would be tempted to create a "Job" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.
A: I would use a dictionary. You can convert the tuple to a dictionary this way:
values = <querycode>
keys = ["jobid", "label", "username"]
job = dict([[keys[i], values [i]] for i in xrange(len(values ))])
This will first create an array [["jobid", val1], ["label", val2], ["username", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result.
PS still fresh on Python myself, so there might be better ways off doing this.
A: An old question, but since no one mentioned it I'll add this from the Python Cookbook:
Recipe 81252: Using dtuple for Flexible Query Result Access
This recipe is specifically designed for dealing with database results, and the dtuple solution allows you to access the results by name OR index number. This avoids having to access everything by subscript which is very difficult to maintain, as noted in your question.
A: @Staale
There is a better way:
job = dict(zip(keys, values))
A: I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.
For example:
job={}
job['jobid'], job['label'], job['username']=<querycode>
A: With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better.
If you want something with slightly friendlier syntax you might want to take a look at the answers this question about a simple 'struct-like' object. That way you can pass around an object, say job, and access its fields even more easily than a tuple or dict:
job.jobId, job.username = jobId, username
A: If you're using the MySQLdb package, you can set up your cursor objects to return dicts instead of tuples.
import MySQLdb, MySQLdb.cursors
conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)
cur = conn.cursor() # a DictCursor
cur2 = conn.cursor(cursorclass=MySQLdb.cursors.Cursor) # a "normal" tuple cursor
A: How about this:
class TypedTuple:
def __init__(self, fieldlist, items):
self.fieldlist = fieldlist
self.items = items
def __getattr__(self, field):
return self.items[self.fieldlist.index(field)]
You could then do:
j = TypedTuple(["jobid", "label", "username"], job)
print j.jobid
It should be easy to swap self.fieldlist.index(field) with a dictionary lookup later on... just edit your __init__ method! Something like Staale does.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Traditional ASP .NET Web Forms vs MVC As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?
I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site.
A: I agree with Nick: MVC is much closer to the real web paradigm and by using it you'll be confronted with how your website really works. WebForms astracts most of these things away from you and, coming from a PHP background, I found it really anti-intuitive.
I suggest you directly jump to MVC and skip WebForms. As said, you'll be able to get back to it if needed.
A: Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed.
A: ASP.Net Webforms is a completely different abstraction over the base framework than ASP.NET MVC. With MVC you've got more control over what happens under the covers than with ASP.NET Webforms.
In my opinion learning different ways to do things will usually make you a better programmer but in this case there might be better things to learn.
A: ASP.NET MVC is for developers who desire to decouple the client code from the server code. I have wanted to write JavaScript, XHTML, CSS clients that can move from server to server (without regard to server technology). Clients are time-consuming to fit and finish so you would want to use them (and sub-components) for as many servers as possible. Also this decoupling allows your server to support any client technology that supports HTTP and angle-brackets (and/or JSON) like WPF/Silverlight. Without ASP.NET MVC you were forced into a hostile relationship with the entire ASP.NET team---but Scott Guthrie is a cool dude and brings MVC to the table after years of his predecessors (and perhaps Scott himself) almost totally focused on getting Windows Forms programmers to write web applications.
Before ASP.NET MVC, I built ASP.NET applications largely based on ASHX files---HTTP handlers. I can assure you that no "real" Microsoft shop would encourage this behavior. It is easier from a (wise) management perspective to dictate that all your developers use the vendor-recommended way of using the vendor's tools. So IT shops that are one or two years behind will require you to know the pre-MVC way of doing things. This also comes in handy when you have a "legacy" system to maintain.
But, for the green field, it's MVC all the way!
A: It depends on your motivations. If you're going to sell yourself as an ASP.NET developer, you will need both.
If this is just for your own pleasure, then go to MVC.
My personal feeling is that webforms will be around for quite a few years more. So many people have time and energy invested in them. However, I think people will slowly (or maybe not so slowly!) migrate. Webforms was always just a way to get drag-and-drop VB4 morts to think about web development. It kindof worked but it does take away alot of control.
A: IMO, there are more pitfalls in normal web forms scenarios than with just MVC. Viewstate and databinding can be tricky at times.
But for MVC, it's just plain simple form post/render things old-school way. Not that it is bad, it is just different, and cleaner too.
A: I can't really speak technically about MVC vs "traditional" as I have only used the traditional model so far. From what I have read though, I don't think one is vastly superior to the other. I think once you "get it", you can be very productive in both.
Practically though, I would take into consideration that most books, code samples and existing applications out there are written for the "traditional" way. You have more help available and your skills will be more useful for employers with existing applications written in the "traditional" way.
A: If you don't know how or haven't has experience with raw level web request / response and raw html/css rendering then MVC will would be good place to start.
You will then better understand the pros and cons of both webforms and mvc. They will both be around in the future as the both address different needs.
Though I will say webforms is a highly misused and abused platform.
So much of the "look no code" rubbish gives all who use it a bad name.
Put in the time to understand it and use it properly you'll find its a very extensible and robust platform.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Excluding a folder from source control in an ASP.NET website? Right now I'm working with an ASP.NET website that automatically generates images and stores them in a temporary folder. When working on my local system these go going into a temporary folder that gets picked up by Visual Source Safe which then wants to check them in. As such, I am wondering if there is a way to just exclude that particular folder from source control?
I've done a bit of reading and found that there are ways to do this for individual files, but I haven't found anything yet about an entire folder.
A: I think you've found one of the main reasons MS went back to projects in VS2008 and in MVC.
It's been a long time since I've used VSS (mainly because it's really out of date now), but most source providers let you exclude files and folders as a setting of the provider, rather than the project under control.
If you can switch to a Web Project rather than a WebSite then do so, otherwise I'd look at updating your source control provider, as this sort of exclusion is easy with Vault, CSV, SVN, Git, VSTS and so on (to name but a few).
A: Are you using ASP.NET Website or ASP.NET Web Project? The difference is significant enough to solve or promote this problem.
Websites, love to scan the file system and auto checkin.
Projects, checkin only what you tell them to.
Also Visual Source Safe is pretty out dated, most recent source control systems allow you to do what you are asking. SVN and TFS 2008 SP1 do from my experience.
You can also try to right click and pick "Exclude" on the folder, but in the case of a Website I believe this renames the folder.
A: I'm not sure if this is an option for you, but if you exclude your temporary folder from VSS (delete the folder inside VSS using the VSS UI), the files that go into it should not get "picked up" again.
A: I would suggest emptying/deleting your folder from your website. Have your website on startup create/verify the folder, and on shutdown to clean it up and remove anything in it. This can be DEBUG code only (wrap in #if DEBUG) if so needed. Also add a build script to your project that does this every time it is built also.
A: Could you just make your application write to a temporary folder that is outside of your website?
e.g. in C:\tempfiles
VSS shouldn't be able to pick it up then.
A: If you perform operations on a parent project of the temporary folder, you may try cloaking the folder.
http://msdn.microsoft.com/en-us/library/x2398bf5(VS.80).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best way to implement user controls in ASP.NET MVC? Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff.
I'm wondering about how user controls work in ASP.NET MVC. We have tons of .ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer.
What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.
A: To implement a user control you do the following call:
<% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %>
You may also see the older syntax which as of PR5 is not valid anymore
<%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %>
You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.
A: As Nick suggested, you will indeed be able to render your user controls, but obviously the page-cycle, pagestate and postback from traditional ASP Webforms won't work anymore, thus making your controls most likely useless.
I think you'll have to rewrite most of your complex controls to port your website to MVC, while simple controls which, for instance, provide only formatting and have no postback status, should simply work.
The code provided by Nick will simply work in this case.
And about sharing between more projects: I think controls will be more like "reusable HTML-rendering components" that can be shared across a website, rather than "reusable code components" with logic (like WebForms controls). Your web logic will/should be in the pages controllers and not in the HTML controls. Therefore sharing controls across more projects won't be so useful as in the WebForms case.
A: Yeah, you can do RenderPartial. That's a good start. But eventually these guys will need logic and other controller type stuff. Be on the lookout for a subcontroller implementation from the framework team. There should also be something in MvcContrib soon. Or roll your own.
Edit: I just posted about this here: http://mhinze.com/subcontrollers-in-aspnet-mvc/
A: MVC has different page life cycle compare to your user control.
You may consider this to re-write.
The aspx is the view. You still need a re-write, the syntax is different.
JavaScript will work. But I hardly find the WebControls will work. Because MVC does not have viewstate and postback anymore.
For the code behind (aspx.cs) you need to convert that to be a Controller class.
Page_Load method will no longer works. You probable leave it to Index() method.
Model is simply the entity classes that your code behind consume.
Conclusion, it's a total rewrite. Cheers. Happy coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: What is a DSL and where should I use it? I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.
If you've got some background using these things, any chance you could put it in real laymans terms:
*
*What exactly building DSLs means?
*What languages are you using?
*Where using a DSL makes sense?
*What is the benefit of using DSLs?
A: If you use Microsoft Visual Studio, you are already using multiple DSLs -- the design surface for web forms, winforms, etc. is a DSL. The Class Designer is another example.
A DSL is just a set of tools that (at least in theory) make development in a specific "domain" (i.e. visual layout) easier, more intuitive, and more productive.
As far as building a DSL, some of the stuff people like Ayende have written about is related to "text parsing" dsls, letting developers (or end users) enter "natural text" into an application, which parses the text and generates some sort of code or output based on it.
You could use any language to build your own DSL. Microsoft Visual Studio has a lot of extensibility points, and the patterns & practices "Guidance Automation Toolkit" and Visual Studio SDK can assist you in adding DSL functionality to Visual Studio.
A: DSL is just a fancy name and can mean different things:
*
*Rails (the Ruby thing) is sometimes called a DSL because it adds special methods (and overwrites some built-in ones too) for talking about web applications
*ANT, Makefile syntax etc. are also DSLs, but have their own syntax. This is what I would call a DSL.
One important aspect of this hype: It does make sense to think of your application in terms of a language. What do you want to talk about in your app? These should then be your classes and methods:
*
*Define a "language" (either a real syntax as proposed by others on this page or a class hierarchy for your favorite language) that is capable of expressing your problem.
*Solve your problem in terms of that language.
A: DSL are basic compilers for custom languages. A good 'free and open' tool to develop them is available at ANTLR. Recently, I've been looking at this DSL for a state machine language use on a new project . I agree with Tim Howland above, that they can be a good way to let someone else customize your application.
A: FYI, a book on DSLs is in the pipeline as part of Martin Fowler's signature series.
If its of the same standard as the other books in the series, it should be a good read.
More information here
A: DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows.
In other words, instead of making them learn java:
DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO();
for (int id : documentIDS) {
Document myDoc = MyDocumentDAO.loadDoc(id);
if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) {
ReminderService.sendUnreadReminder(myDoc)
}
I can write a DSL that lets me say:
for (document : documents) {
if (document is unread) {
document.sendReminder
}
There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.
A: DSL stands for Domain Specific Language i.e. language designed specifically for solving problems in given area.
For example, Markdown (markup language used to edit posts on SO) can be considered as a DSL.
Personally I find a place for DSL almost in every large project I'm working on. Most often I need some kind of SQL-like query language. Another common usage is rule-based systems, you need some kind of language to specify rules\conditions.
DSL makes sense in context where it's difficult to describe\solve problem by traditional means.
A: DSL is basically creating your own small sublanguage to solve a specific domain problem. This is solved using method chaining. Languages where dots and parentheses are optional help make these expression seem more natural. It can also be similar to a builder pattern.
DSL aren't languages themselves, but rather a pattern that you apply to your API to make the calls be more self explanatory.
One example is Guice, Guice Users Guide http://docs.google.com/View?docid=dd2fhx4z_5df5hw8 has some description further down of how interfaces are bound to implementations, and in what contexts.
Another common example is for query languages. For example:
NewsDAO.writtenBy("someUser").before("someDate").updateStatus("Deleted")
In the implementation, imagine each method returning either a new Query object, or just this updating itself internally. At any point you can terminate the chain by using for example rows() to get all the rows, or updateSomeField as I have done above here. Both will return a result object.
I would recommend taking a look at the Guice example above as well, as each call there returns a new type with new options on them. A good IDE will allow you to complete, making it clear which options you have at each point.
Edit: seems many consider DSLs as new, simple, single purpose languages with their own parsers. I always associate DSL as using method chaining as a convention to express operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Best way to sort an array Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this?
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
var SomeVar : array of TExample;
A: You can add pointers to the elements of the array to a TList, then call TList.Sort with a comparison function, and finally create a new array and copy the values out of the TList in the desired order.
However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer<TExample> implementation for custom sorting orders. Here it is in action for your specific case:
TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct(
function(const Left, Right: TExample): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder);
end));
A: If your need sorted by string then use sorted TStringList and
add record by TString.AddObject(string, Pointer(int_val)).
But If need sort by integer field and string - use TObjectList and after adding all records call TObjectList.Sort with necessary sorted functions as parameter.
A: This all depends on the number of records you are sorting. If you are only sorting less than a few hundred then the other sort methods work fine, if you are going to be sorting more, then take a good look at the old trusty Turbo Power SysTools project. There is a very good sort algorithm included in the source. One that does a very good job sorting millions of records in a efficient manner.
If you are going to use the tStringList method of sorting a list of records, make sure that your integer is padded to the right before inserting it into the list. You can use the format('%.10d',[rec.sortorder]) to right align to 10 digits for example.
A: (I know this is a year later, but still useful stuff.)
Skamradt's suggestion to pad integer values assumes you are going to sort using a string compare. This would be slow. Calling format() for each insert, slower still. Instead, you want to do an integer compare.
You start with a record type:
TExample = record
SortOrder : integer;
SomethingElse : string;
end;
You didn't state how the records were stored, or how you wanted to access them once sorted. So let's assume you put them in a Dynamic Array:
var MyDA: Array of TExample;
...
SetLength(MyDA,NewSize); //allocate memory for the dynamic array
for i:=0 to NewSize-1 do begin //fill the array with records
MyDA[i].SortOrder := SomeInteger;
MyDA[i].SomethingElse := SomeString;
end;
Now you want to sort this array by the integer value SortOrder. If what you want out is a TStringList (so you can use the ts.Find method) then you should add each string to the list and add the SortOrder as a pointer. Then sort on the pointer:
var tsExamples: TStringList; //declare it somewhere (global or local)
...
tsExamples := tStringList.create; //allocate it somewhere (and free it later!)
...
tsExamples.Clear; //now let's use it
tsExamples.sorted := False; //don't want to sort after every add
tsExamples.Capacity := High(MyDA)+1; //don't want to increase size with every add
//an empty dynamic array has High() = -1
for i:=0 to High(MyDA) do begin
tsExamples.AddObject(MyDA[i].SomethingElse,TObject(MyDA[i].SortOrder));
end;
Note the trick of casting the Integer SortOrder into a TObject pointer, which is stored in the TStringList.Object property. (This depends upon the fact that Integer and Pointer are the same size.) Somewhere we must define a function to compare the TObject pointers:
function CompareObjects(ts:tStringList; Item1,Item2: integer): Integer;
begin
Result := CompareValue(Integer(ts.Objects[Item1]), Integer(ts.Objects[Item2]))
end;
Now, we can sort the tsList on .Object by calling .CustomSort instead of .Sort (which would sort on the string value.)
tsExamples.CustomSort(@CompareObjects); //Sort the list
The TStringList is now sorted, so you can iterate over it from 0 to .Count-1 and read the strings in sorted order.
But suppose you didn't want a TStringList, just an array in sorted order. Or the records contain more data than just the one string in this example, and your sort order is more complex. You can skip the step of adding every string, and just add the array index as Items in a TList. Do everything above the same way, except use a TList instead of TStringList:
var Mlist: TList; //a list of Pointers
...
for i:=0 to High(MyDA) do
Mlist.add(Pointer(i)); //cast the array index as a Pointer
Mlist.Sort(@CompareRecords); //using the compare function below
function CompareRecords(Item1, Item2: Integer): Integer;
var i,j: integer;
begin
i := integer(item1); //recover the index into MyDA
j := integer(item2); // and use it to access any field
Result := SomeFunctionOf(MyDA[i].SomeField) - SomeFunctionOf(MyDA[j].SomeField);
end;
Now that Mlist is sorted, use it as a lookup table to access the array in sorted order:
for i:=0 to Mlist.Count-1 do begin
Something := MyDA[integer(Mlist[i])].SomeField;
end;
As i iterates over the TList, we get back the array indexes in sorted order. We just need to cast them back to integers, since the TList thinks they're pointers.
I like doing it this way, but you could also put real pointers to array elements in the TList by adding the Address of the array element instead of it's index. Then to use them you would cast them as pointers to TExample records. This is what Barry Kelly and CoolMagic said to do in their answers.
A: With an array, I'd use either quicksort or possibly heapsort, and just change the comparison to use TExample.SortOrder, the swap part is still going to just act on the array and swap pointers. If the array is very large then you may want a linked list structure if there's a lot of insertion and deletion.
C based routines, there are several here
http://www.yendor.com/programming/sort/
Another site, but has pascal source
http://www.dcc.uchile.cl/~rbaeza/handbook/sort_a.html
A: The quicksort algorithm is often used when fast sorting is required. Delphi is (Or was) using it for List.Sort for example.
Delphi List can be used to sort anything, but it is an heavyweight container, which is supposed to look like an array of pointers on structures. It is heavyweight even if we use tricks like Guy Gordon in this thread (Putting index or anything in place of pointers, or putting directly values if they are smaller than 32 bits): we need to construct a list and so on...
Consequently, an alternative to easily and fastly sort an array of struct might be to use qsort C runtime function from msvcrt.dll.
Here is a declaration that might be good (Warning: code portable on windows only).
type TComparatorFunction = function(lpItem1: Pointer; lpItem2: Pointer): Integer; cdecl;
procedure qsort(base: Pointer; num: Cardinal; size: Cardinal; lpComparatorFunction: TComparatorFunction) cdecl; external 'msvcrt.dll';
Full example here.
Notice that directly sorting the array of records can be slow if the records are big. In that case, sorting an array of pointer to the records can be faster (Somehow like List approach).
A: Use one of the sort alorithms propose by Wikipedia. The Swap function should swap array elements using a temporary variable of the same type as the array elements. Use a stable sort if you want entries with the same SortOrder integer value to stay in the order they were in the first place.
A: TStringList have efficient Sort Method.
If you want Sort use a TStringList object with Sorted property to True.
NOTE: For more speed, add objects in a not Sorted TStringList and at the end change the property to True.
NOTE: For sort by integer Field, convert to String.
NOTE: If there are duplicate values, this method not is Valid.
Regards.
A: If you have Delphi XE2 or newer, you can try:
var
someVar: array of TExample;
list: TList<TExample>;
sortedVar: array of TExample;
begin
list := TList<TExample>.Create(someVar);
try
list.Sort;
sortedVar := list.ToArray;
finally
list.Free;
end;
end;
A: I created a very simple example that works correctly if the sort field is a string.
Type
THuman = Class
Public
Name: String;
Age: Byte;
Constructor Create(Name: String; Age: Integer);
End;
Constructor THuman.Create(Name: String; Age: Integer);
Begin
Self.Name:= Name;
Self.Age:= Age;
End;
Procedure Test();
Var
Human: THuman;
Humans: Array Of THuman;
List: TStringList;
Begin
SetLength(Humans, 3);
Humans[0]:= THuman.Create('David', 41);
Humans[1]:= THuman.Create('Brian', 50);
Humans[2]:= THuman.Create('Alex', 20);
List:= TStringList.Create;
List.AddObject(Humans[0].Name, TObject(Humans[0]));
List.AddObject(Humans[1].Name, TObject(Humans[1]));
List.AddObject(Humans[2].Name, TObject(Humans[2]));
List.Sort;
Human:= THuman(List.Objects[0]);
Showmessage('The first person on the list is the human ' + Human.name + '!');
List.Free;
End;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: What is the best way to calculate Age using Flex? What is the best way to calculate Age using Flex?
A: var userDOB : Date = new Date(year,month-1,day);
var today : Date = new Date();
var diff : Date = new Date();
diff.setTime( today.getTime() - userDOB.getTime() );
var userAge : int = diff.getFullYear() - 1970;
A: I found an answer at the bottom of this page in comments section (which is now offline).
jpwrunyan said on Apr 30, 2007 at 10:10 PM :
By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:
With a slight correction by Fine-Wei Lin, the code reads
private function getYearsOld(dob:Date):uint {
var now:Date = new Date();
var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear);
if (dob.month > now.month || (dob.month == now.month && dob.date > now.date))
{
yearsOld--;
}
return yearsOld;
}
This handles most situations where you need to calculate age.
A: You could also do it roughly the same as discussed here: (translated to AS3)
var age:int = (new Date()).fullYear - bDay.fullYear;
if ((new Date()) < (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--;
A: Here is a little more complex calculation, this calculates age in years and months. Example: User is 3 years 2 months old.
private function calculateAge(dob:Date):String {
var now:Date = new Date();
var ageDays:int = 0;
var ageYears:int = 0;
var ageRmdr:int = 0;
var diff:Number = now.getTime()-dob.getTime();
ageDays = diff / 86400000;
ageYears = Math.floor(ageDays / 365.24);
ageRmdr = Math.floor( (ageDays - (ageYears*365.24)) / 30.4375 );
if ( ageRmdr == 12 ) {
ageRmdr = 11;
}
return ageYears + " years " + ageRmdr + " months";
}
A: Here's a one-liner:
int( now.getFullYear() - dob.getFullYear() + (now.getMonth() - dob.getMonth())*.01 + (now.getDate() - dob.getDate())*.0001 );
A: I found a few problems with the top answer here. I used a couple of answers here to cobble together something which was accurate (for me anyway, hope for you too!)
private function getYearsOld(dob:Date):uint
{
var now:Date = new Date();
var age:Date = new Date(now.getTime() - dob.getTime());
var yearsOld:uint = age.getFullYear() - 1970;
return yearsOld;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I download code using SVN/Tortoise from Google Code? I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys HerdingCode called Witty. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code.
Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code.
On the source page for this project (google code witty source) it gives the following instruction:
Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only
I'm confused as to where I am supposed to enter the above command so that I can download the code.
I have installed SVN and Tortoise (which I know almost nothing about).
Thanks for any help or simply pointing me in the right direction.
...Ed (@emcpadden)
A: Select Tortoise SVN - > Settings - > NetWork
Fill the required proxy if any and then check.
A: Right click on the folder you want to download in, and open up tortoise-svn -> repo-browser.
Enter in the URL above in the next window.
right click on the trunk folder and choose either checkout (if you want to update from SVN later) or export (if you just want your own copy of that revision).
A: Create a folder where you want to keep the code, and right click on it. Choose SVN Checkout... and type http://wittytwitter.googlecode.com/svn/trunk into the URL of repository field.
You can also run
svn checkout http://wittytwitter.googlecode.com/svn/trunk
from the command line in the folder you want to keep it (svn.exe has to be in your path, of course).
A: See my answer to a very similar question here: How to download/checkout a project from Google Code in Windows?
In brief: If you don't want to install anything but do want to download an SVN or GIT repository, then you can use this: http://downloadsvn.codeplex.com
A: After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
A: The manual explains how to checkout code:
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html
A: If you have Tortoise SVN, like I do, take the google link, and ONLY
copy the URL.
Regular-
(svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only)
Modified to URL-
(http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter)
Create a folder, right click the empty space.
You can Browse Repo or just download it all via checkout.
I don't know whether you have to be a Google member or not, but
I signed up just in case.
Have fun with the code.
Misanthropy
A: *
*Download the svn binaries
*unpack them somewhere and add the bin folder to your PATH environment variable
*open a command line console (cmd.exe)
*enter than "svn checkout ...." command there
*
*make sure to first cd to the place where you want to download (i.e checkout) the projects' code.
A: If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
} |
Q: Microsoft T-SQL to Oracle SQL translation I've worked with T-SQL for years but I've just moved to an organisation that is going to require writing some Oracle stuff, probably just simple CRUD operations at least until I find my feet. I'm not going to be migrating databases from one to the other simply interacting with existing Oracle databases from an Application Development perspective. Is there are tool or utility available to easily translate T-SQL into Oracle SQL, a keyword mapper is the sort of thing I'm looking for.
P.S. I'm too lazy to RTFM, besides it's not going to be a big part of my role so I just want something to get me up to speed a little faster.
A: I have to things to mention.
1) When I worked on Oracle 8, you could not do "Select @Result", you had to instead use the dummy table as follows "Select @Result from dual". Not sure if that ridiculousness still exists.
2) In the Oracle world they seem to love cursors and you better read up on them, they use them all the time AFAICS.
Good luck and enjoy,
it is not that different to MS SQL. Thankfully, I do not have to work with it anymore and I am back in the warm comfort of MS tools.
A: If you replace your ISNULL and NVL nonsense with COALESCE, it'll work in T-SQL and PL/SQL!
A: The language difference listed so far are trivial compared to the logical differences. Anyone can lookup NVL. What's hard to lookup is
DDL
In SQL server you manipulate your schema, anywhere, anytime, with little or no fuss.
In Oracle, we don't like DDL in stored procedures so you have jump through hoops. You need to use EXECUTE IMMEDIATE to perform a DDL function.
Temp Tables
IN SQL Server when the logic becomes a bit tough, the common thing is to shortcut the sql and have it resolved to a temp table and then the next step is done using that temp table.
MSSS makes it very easy to do this.
In Oracle we don't like that. By forcing an intermediate result you completely prevent the Optimizer from finding a shortcut for you. BUT If you must stop halfway and persist the intermediate results Oracle wants you to make the temp table in advance, not on the fly.
Locks
In MSSS you worry about locking, you have nolock hints to apply to DML, you have lock escalation to reduce the count of locks.
In Oracle we don't worry about these in that way.
Read Commited
Until recently MSSS didn't fully handle Read Committed isolation so you worried about dirty reads.
Oracle has been that way for decades.
etc
MSSS has no concept of Bitmap indexes, IOT, Table Clusters, Single Table hash clusters, non unique indexes enforcing unique constraints....
A: It's not trivial to map them back and forth, so I doubt there's a tool that does it automatically. But this link might help you out: http://vyaskn.tripod.com/oracle_sql_server_differences_equivalents.htm
A: The most important differences for plain T-SQL are:
*
*NVL replaces ISNULL
*SYSDATE replaces GETDATE()
*CONVERT is not supported
*Identity columns must be replaced with sequences <-- not technically T- or PL/ but just SQL
Note. I assume you do not use the deprecated SQL Server *= syntax for joins
@jodonell: The table you link to is a bit outdated, oracle has become somewhat more standards compliant after 9i supporting things like CASE and ANSI outer joins
A: I have done a few SQL server to oracle migrations. There is no way to migrate without rewriting the backend code. Too many differences between the 2 databases and more importantly differences between the 2 mind sets of the programmers. Many managers think that the 2 are interchangeable, I have had managers ask me to copy the stored procedures from SQL server and compile them in oracle, not a clue! Toad is by far the best tool on the market for supporting an oracle application. SQL developer is ok but was disappointing compared to toad. I hope that oracle will catch their product up to toad one day but it is not there yet. Have a good day :) chances are if you are migrating to oracle it is for a reason and in order to meet that requirement you will need to rewrite the back end code or you will have many issues.
A: I get the impression most answers focus on migrating an entire database or just point to some differences between T-SQL and PL/SQL. I recently had the same problem. The Oracle database exists, but I need to convert a whole load of T-SQL scripts to PL/SQL.
I installed Oracle SQL Developer and ran the Translation Scratch Editor (Tools > Migration > Scratch Editor).
Then, just enter your T-SQL, choose the correct translation in the dropdown-list (it should default to 'T-SQL to PL/SQL'), and convert it.
A: In Oracle SQL Developer, there is a tool called Translation Scratch Editor. You can find it from Tools > Migration.
The Oracle SQL Developer is a free download from Oracle and it is an easy install.
A: If you're doing a one-off conversion, rather than trying to support two versions, you must look at Oracle Migration Workbench. This tool works with Oracle's SQLDeveloper (which you really should have if you are working with Oracle). This does a conversion of the schema, data, and some of the T-SQL to PL/SQL. Knowing both well, I found it did about an 80% job. Good enough to make it worth while to convert the bulk of procedures, and hand convert the remainder "tougher" unknown parts.
A: Not cheap ($995) but this tool works great: http://www.swissql.com/products/sql-translator/sql-converter.html
A: A few people have mentioned here converting back and forward. I do not know of a tool to convert from MSSQL to Oracle, but I used the free MS tool to convert a Oracle db to MSSQL and it worked for me and converted a large db with no problems I can call. It is similar to the Access to MSSQL tool that MS also provide for free. Enjoy
A: jOOQ has a publicly available, free translator, which can be accessed from the website here: https://www.jooq.org/translate
It supports DML, DDL, and a few procedural syntax elements. If you want to run the translation locally via command line, a license can be purchased and the command line works as follows:
$ java -cp jooq-3.11.9.jar org.jooq.ParserCLI -t ORACLE -s "SELECT substring('abcde', 2, 3)"
select substr('abcde', 2, 3) from dual;
See: https://www.jooq.org/doc/latest/manual/sql-building/sql-parser/sql-parser-cli
(Disclaimer, I work for the vendor)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Instance constructor sets a static member, is it thread safe? I am re-factoring some code and am wondering about the use of a lock in the instance constructor.
public class MyClass {
private static Int32 counter = 0;
private Int32 myCount;
public MyClass() {
lock(this) {
counter++;
myCount = counter;
}
}
}
Please confirm
*
*Instance constructors are thread-safe.
*The lock statement prevents access to that code block, not to the static 'counter' member.
If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count?
FYI - This class is not a singleton. Instances must simply be aware of their number.
A: I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock the counter while your are modifying it.
private static int counter = 0;
private static object counterLock = new Object();
lock(counterLock) {
counter++;
myCounter = counter;
}
Because your current code is sort of redundant. Especially being in the constructor where there is only one thread that can call a constructor, unlike with methods where it could be shared across threads and be accessed from any thread that is shared.
From the little I can tell from you code, you are trying to give the object the current count at the time of it being created. So with the above code the counter will be locked while the counter is updated and set locally. So all other constructors will have to wait for the counter to be released.
A: You can use another static object to lock on it.
private static Object lockObj = new Object();
and lock this object in the constructor.
lock(lockObj){}
However, I'm not sure if there are situations that should be handled because of compiler optimization in .NET like in the case of java
A: @ajmastrean
I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process.
i.e.
*
*Make the constructor private.
*Create a static instance method that returns the type.
*In the static instance method, use the lock keyword before instantiating.
*Instantiate a new instance of the type.
*Increment the count.
*Unlock and return the new instance.
EDIT
One problem that has occurred to me, if how would you know when the count has gone down? ;)
EDIT AGAIN
Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D
A: The most efficient way to do this would be to use the Interlocked increment operation. It will increment the counter and return the newly set value of the static counter all at once (atomically)
class MyClass {
static int _LastInstanceId = 0;
private readonly int instanceId;
public MyClass() {
this.instanceId = Interlocked.Increment(ref _LastInstanceId);
}
}
In your original example, the lock(this) statement will not have the desired effect because each individual instance will have a different "this" reference, and multiple instances could thus be updating the static member at the same time.
In a sense, constructors can be considered to be thread safe because the reference to the object being constructed is not visible until the constructor has completed, but this doesn't do any good for protecting a static variable.
(Mike Schall had the interlocked bit first)
A: If you are only incrementing a number, there is a special class (Interlocked) for just that...
http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx
Interlocked.Increment Method
Increments a specified variable and stores the result, as an atomic operation.
System.Threading.Interlocked.Increment(myField);
More information about threading best practices...
http://msdn.microsoft.com/en-us/library/1c9txz50.aspx
A: I think if you modify the Singleton Pattern to include a count (obviously using the thread-safe method), you will be fine :)
Edit
Crap I accidentally deleted!
I am not sure if instance constructors ARE thread safe, I remember reading about this in a design patterns book, you need to ensure that locks are in place during the instantiation process, purely because of this..
A: @Rob
FYI, This class may not be a singleton, I need access to different instances. They must simply maintain a count. What part of the singleton pattern would you change to perform 'counter' incrementing?
Or are you suggesting that I expose a static method for construction blocking access to the code that increments and reads the counter with a lock.
public MyClass {
private static Int32 counter = 0;
public static MyClass GetAnInstance() {
lock(MyClass) {
counter++;
return new MyClass();
}
}
private Int32 myCount;
private MyClass() {
myCount = counter;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Recommendation for 3rd party editing/syntax highlighting control - WinForms I'm looking for a quality WinForms component that supports syntax highlighting, code folding and the like. The key criteria are:
*
*Stability
*Value (price)
*Ability to easily customize syntax to highlight
*Light weight
A: ICSharpCode.TextEditor is free and pretty stable.
As for commercial solution Actipro's SyntaxEditor might be a best choice
A: Enhancing ICSharpCode.TextEditor was trivial compared with Scintilla.Net. Another huge benefit of ICSharpCode.TextEditor is that allows you to customize/build your own Syntax Highlighting, eg: https://github.com/icsharpcode/SharpDevelop/wiki/Syntax-highlighting.
BUT ICSharpCode.TextEditor is not stable, its riddled with AccessViolations: https://www.google.com.au/search?q=icsharpcode.texteditor+accessviolationexception
You can see these AccessViolations first hand by downloading:
http://www.codeproject.com/Articles/30936/Using-ICSharpCode-TextEditor
This build on GitHub behaves better in winforms, but in VSTO it still screams AccessViolations:
https://github.com/KindDragon/ICSharpCode.TextEditor
Same as DigitalRune's version of the ICsharp.TextEditor.
I'd recommend the latest WPF implementation: ICSharp.AvalonEdit.
If you need to host this WPF control in Winforms:
public Form1()
{
InitializeComponent();
ICSharpCode.AvalonEdit.TextEditor te = new ICSharpCode.AvalonEdit.TextEditor();
ElementHost host = new ElementHost();
host.Size = new Size(200, 100);
host.Location = new Point(100, 100);
host.Child = te;
this.Controls.Add(host);
}
Some commercial ones I came across (note I'm not affiliated with these companies):
http://www.actiprosoftware.com/products/controls/windowsforms/syntaxeditor
http://www.qwhale.net/products/editor.htm
A: Try out ScintillaNET it's a .NET WinForms wrapper around the excellent Scintilla control. Scintilla itself is a free source code editor component that is very customisable and has all the features you asked for. See here for a screenshot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I prevent the closing of modal popup window(ModalPopupExtender) on postback? I'm using Microsoft AjaxControlToolkit for modal popup window.
And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?
A: You can call Show() method during postback to prevent the modal popup window from closing
MyModalPopoupExtender.Show()
A: protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// reshow
MyModalPopup.Show()
}
}
A: I guess that works but not in my case. I've a user control that opened in a modal popup and this user control makes postback itself. So in that user control I've no modal popup property.
I guess, I've to create an event for my user control, and the page that opens the modal popup have to reopen it in this event.
A: Was having this same problem keeping a modal open during postbacks.
My solution:
Use EventTarget to determine if the postback is coming from a control in the modal and keep the model open if it is. The postback can come from a control in the modal iff the modal is open.
In the load event for the page control containing the modal. Determine if the postback is from
a child of mine. Determine if it is from the control that is in the modal panel.
Protected Sub Control_Load(sende As Object, e As EventArgs) Handles Me.Load
If IsPostBack Then
Dim eventTarget As String = Page.Request.Params.Get("__EventTarget")
Dim eventArgs As String = Page.Request.Params.Get("__EventArgument")
If Not String.IsNullOrEmpty(eventTarget) AndAlso eventTarget.StartsWith(Me.UniqueID) Then
If eventTarget.Contains("$" + _credentialBuilder.ID + "$") Then
' Postback from credential builder modal. Keep it open.
showCredentialBuilder = True
End If
End If
End If
End Sub
In prerender check my flag and manually show the modal
Protected Sub Control_PreRender(ByVal sende As Object, ByVal e As EventArgs) Handles Me.PreRender
If showCredentialBuilder Then
_mpeCredentialEditor.Show()
End If
End Sub
A: Put you controls inside the update panel. Please see my sample code, pnlControls is control that holds controls that will be displayed on popup:
<asp:Panel ID="pnlControls" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="TestButton" runat="server" Text="Test Button" onclick="TestButton_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
This will do the job for you :)
Best regards,
Gregor Primar
A: Like you prolly already know, the modal popup is clientside only, yeah you can gather informations in it during the postback, but if you do a postback he will hide 100% of the time.
Of course, like other proposed, you can do a .show during the postback, but it depends on what you need to do.
Actually, I don't know why you need a postback, if it's for some validations try to do them clientside.
Could you tell us why you need to do a postback, maybe we could help you better ! :)
A: Following previous case...
In Simple.aspx, user has to enter the name of a company. If user don't remember name of the company, he can click a button which will open a pop up modal window.
what I want to do in the modal window is permit the user to do a search of a list of companies. He can enter a partial name and click search. Matches will be shown in a list below. He can click in an item of the list and return. If company does not exist, he can click a button 'New' to create a new company.
So, as you can see, I want a lot of functionality in this modal window.
Thanks!
JC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Maintain the correct version for a COM dll referenced in a .NET project I want to reference a COM DLL in a .NET project, but I also want to make sure that the interop DLL created will have the correct version (so that patches will know when the DLL must be changed).
If I use TlbImp I can specify the required version with the /asmversion flag but when I add it directly from Visual Studio it gets a version that has nothing to do with the original COM DLL's version.
I tried changing the version in the .vcproj file
<ItemGroup>
<COMReference Include="MYDLLLib">
<Guid>{459F8813-D74D-DEAD-BEEF-00CAFEBABEA5}</Guid>
<!-- I changed this -->
<VersionMajor>1</VersionMajor>
<!-- This too -->
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>tlbimp</WrapperTool>
<Isolated>False</Isolated>
</COMReference>
</ItemGroup>
But then the project failed to build with the following error:
error CS0246: The type or namespace name 'MYDLLLib' could not be found (are you missing a using directive or an assembly reference?)
Is there any way to get this done without creating all my COM references with TlbImp in advance?
If the answer is yes is there a way to specify a build number in addition to the major and minor versions? (e.g 1.2.42.0)
A: The Guid refers to the Guid for the TypeLib not the DLL directly. The version numbers refer to the TypeLib's version not the DLLs.
The version number will come from your idl file, and I believe it only supports a major and minor version and not a build version. Is this version changing when you modify the typelib?
The version numbers will appear in the registry under:
HKEY_CLASSES_ROOT\Typelib\{typelib uuid}\Major.Minor
If the minor version is set to 0 then I believe it will import the 'latest' version that matches the major version, but the major version must be set to something.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Setting include path in PHP intermittently fails I have tried both of :
ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes');
and also :
php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes"
in the .htaccess file.
Both methods actually do work but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.
I'm not even sure where to begin trying to find out what is going on!
@cnote
Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.
The in script version was originally
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
and thus the .:.: was coming from the existing path:
ini_get('include_path')
I tried removing it anyway and the problem persists.
A: Have you tried set_include_path()?. As a benefit this returns false on failure, allowing you to at least catch the occurence and generate some meaningful debug data.
Additionally, you should be using the constant PATH_SEPARATOR as it differs between windows / *nix.
As a specific example:
set_include_path('.' . PATH_SEPARATOR . './app/lib' . PATH_SEPARATOR . get_include_path());
(the get_include_path() on the end means whatever your ini / htaccess path is set to will remain)
A: It turned out the issue was related to a PHP bug in 5.2.5
Setting an "admin_flag" for include_path caused the include path to be empty in some requests, and Plesk sets an admin_flag in the default config for something or other. An update of PHP solved the issue.
http://bugs.php.net/bug.php?id=43677
A: Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cost of Inserts vs Update in SQL Server I have a table with more than a millon rows. This table is used to index tiff images. Each image has fields like date, number, etc. I have users that index these images in batches of 500. I need to know if it is better to first insert 500 rows and then perform 500 updates or, when the user finishes indexing, to do the 500 inserts with all the data. A very important thing is that if I do the 500 inserts at first, this time is free for me because I can do it the night before.
So the question is: is it better to do inserts or inserts and updates, and why? I have defined a id value for each image, and I also have other indices on the fields.
A: Updates in Sql server result in ghosted rows - i.e. Sql crosses one row out and puts a new one in. The crossed out row is deleted later.
Both inserts and updates can cause page-splits in this way, they both effectively 'add' data, it's just that updates flag the old stuff out first.
On top of this updates need to look up the row first, which for lots of data can take longer than the update.
Inserts will just about always be quicker, especially if they are either in order or if the underlying table doesn't have a clustered index.
When inserting larger amounts of data into a table look at the current indexes - they can take a while to change and build. Adding values in the middle of an index is always slower.
You can think of it like appending to an address book: Mr Z can just be added to the last page, while you'll have to find space in the middle for Mr M.
A: Doing the inserts first and then the updates does seem to be a better idea for several reasons. You will be inserting at a time of low transaction volume. Since inserts have more data, this is a better time to do it.
Since you are using an id value (which is presumably indexed) for updates, the overhead of updates will be very low. You would also have less data during your updates.
You could also turn off transactions at the batch (500 inserts/updates) level and use it for each individual record, thus reducing some overhead.
Finally, test this out to see the actual performance on your server before making a final decision.
A: This isn't a cut and dry question. Krishna's and Galegian's points are spot on.
For updates, the impact will be lessened if the updates are affecting fixed-length fields. If updating varchar or blob fields, you may add a cost of page splits during update when the new value surpasses the length of the old value.
A: I think inserts will run faster. They do not require a lookup (when you do an update you are basically doing the equivalent of a select with the where clause). And also, an insert won't lock the rows the way an update will, so it won't interfere with any selects that are happening against the table at the same time.
A: The execution plan for each query will tell you which one should be more expensive. The real limiting factor will be the writes to disk, so you may need to run some tests while running perfmon to see which query causes more writes and causes the disk queue to get the longest (longer is bad).
A: I'm not a database guy, but I imagine doing the inserts in one shot would be faster because the updates require a lookup whereas the inserts do not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Black Box testing software We are about to get a canned package in that has been modified to our needs. I'm part of the team setup to prepare tests for it. It has an Oracle back end and I believe it's written in C++ .NET.
My question is what free or open source testing tools would you recommend.
Thanks
Ken
A: For regression testing of our applications I use a free tool called AutoHotKey http://www.autohotkey.com/. It is simple, batch configurable, and can work for virtually any application you have. Not exactly designed for black box testing, but a good free tool to add to your toolbox.
While there are a few good commercial applications for black box testing of applications (HoloDeck http://www.sisecure.com/holodeck/index.shtml, Cenzic Hailstorm http://www.cenzic.com/), the only open source applications that I know about only test network security (Spike http://www.immunitysec.com/resources-freesoftware.shtml, OWASP WebScarab http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project, and Nikto http://www.cirt.net/nikto2)
A: Value checking. See if only valid dates are exempted, number fields except the full range, ect.
A: What do you expect from such a tool? I don't know of any tool that can arbitrarily test any piece of software.
A: For what is sounds like you already know what it is that you want to check. Being a custom application your best bet would be to devise a test plan and manually test the values that you would like to validate.
A: Agree with the others - since the application has been modified to your needs, you should make sure that it actually is modified to your needs.
If the assembly isn't obfuscated, you can use FxCop to analyze the binaries and see if there are any critical bugs (note - if you're not familiar with fxcop and static analysis, find someone who is before reporting a ton of bugs that won't be fixed).
Beyond that, you're looking at more techniques vs. tools to get the job done.
A: Testing, either functional or non-functional, without reference to the
internal structure of the component or system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is a good markup language to use for tests? I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures):
case:
name: caseN
description: this tests foo to make sure bar happens
expected_results: bar should happen
commands: |
command to run
next command to run
verification: command to see if it worked
Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of?
A: Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. CUnit
A: You might want to check out CPAN. It does for Perl scripts exactly what it sounds like your utility will do for your app.
A: Did you take a look at RSpec?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PDB files for production app and the "Optimize code" flag When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception?
If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?
A: There is no need to include them in your distribution, but you should definitely be building them and keeping them. Otherwise debugging a crash dump is practically impossible.
I would also turn on optimizations. Whilst it does make debugging more difficult the performance gains are usually very non-trivial depending on the nature of the application. We easily see over 10x performance on release vs debug builds for some algorithms.
A: When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize and generate PDBs without a performance hit.
From the C# Language Reference
If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.
A: To answer your first question, you only need to include PDBs for a production release if you need line numbers for your exception reports.
To answer your second question, using the "Optimise" flag with PDBs means that any stack "collapse" will be reflected in the stack trace. I'm not sure whether the actual line number reported can be wrong - this needs more investigation.
To answer your third question, you can have the best of both worlds with a rather neat trick. The major differences between the default debug build and default release build are that when doing a default release build, optimization is turned on and debug symbols are not emitted. So, in four steps:
*
*Change your release config to emit debug symbols. This has virtually no effect on the performance of your app, and is very useful if (when?) you need to debug a release build of your app.
*Compile using your new release build config, i.e. with debug symbols and with optimization. Note that 99% of code optimization is done by the JIT compiler, not the language compiler.
*Create a text file in your app's folder called xxxx.exe.ini (or dll or whatever), where xxxx is the name of your executable. This text file should initially look like:
[.NET Framework Debugging Control]
GenerateTrackingInfo=0
AllowOptimize=1
*With these settings, your app runs at full speed. When you want to debug your app by turning on debug tracking and possibly turning off (CIL) code optimization, just use the following settings:
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0
EDIT According to cateye's comment, this can also work in a hosted environment such as ASP.NET.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Recommendations for Web application performance benchmarks I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance.
Please could someone suggest formal/informal standards for how I can judge the application's performance.
A: Use some tool for stress and load testing. If you're using Java take a look at JMeter. It provides different methods to test you application performance. You should focus on:
*
*Response time: How fast your application is running for normal requests. Test some read/write use case
*Load test: How your application behaves in high traffic times. The tool will submit several requests (you can configure that properly) during a period of time.
*Stress test: Do your application can operate during a long period of time? This test will push your application to the limits
Start with this, if you're interested, there are other kinds of tests.
A: "Specifically, I have to determine the application's performance...."
This comes full circle to the issue of requirements, the captured expectations of your user community for what is considered reasonable and effective. Requirements have a number of components
*
*General Response time, " Under a load of .... The Site shall have a general response time of less than x, y% of the time..."
*Specific Response times, " Under a load of .... Credit Card processing shall take less than z seconds, a% of the time..."
*System Capacity items, " Under a load of .... CPU|Network|RAM|DISK shall not exceed n% of capacity.... "
*The load profile, which is the mix of the number of users and transactions which will take place under which the specific, objective, measures are collected to determine system performance.
You will notice the the response times and other measures are no absolutes. Taking a page from six sigma manufacturing principals, the cost to move from 1 exception in a million to 1 exception in a billion is extraordinary and the cost to move to zero exceptions is usually a cost not bearable by the average organization. What is considered acceptable response time for a unique application for your organization will likely be entirely different from a highly commoditized offering which is a public internet facing application. For highly competitive solutions response time expectations on the internet are trending towards the 2-3 second range where user abandonment picks up severely. This has dropped over the past decade from 8 seconds, to 4 seconds and now into the 2-3 second range. Some applications, like Facebook, shoot for almost imperceptible response times in the sub one second range for competitive reasons. If you are looking for a hard standard, they just don't exist.
Something that will help your understanding is to read through a couple of industry benchmarks for style, form, function.
*
*TPC-C Database Benchmark Document
*SpecWeb2009 Benchmark Design Document
Setting up a solid set of performance tests which represents your needs is a non-trivial matter. You may want to bring in a specialist to handle this phase of your QA efforts.
On your tool selection, make sure you get one that can
*
*Exercise your interface
*Report against your requirements
*You or your team has the skills to use
*You can get training on and will attend with management's blessing
Misfire on any of the four elements above and you as well have purchased the most expensive tool on the market and hired the most expensive firm to deploy it.
Good luck!
A: To test the front-end then YSlow is great for getting statistics for how long your pages take to load from a user perspective. It breaks down into stats for each specfic HTTP request, the time it took, etc. Get it at http://developer.yahoo.com/yslow/
Firebug, of course, also is essential. You can profile your JS explicitly or in real time by hitting the profile button. Making optimisations where necessary and seeing how long all your functions take to run. This changed the way I measure the performance of my JS code. http://getfirebug.com/js.html
A: Really the big thing I would think is response time, but other indicators I would look at are processor and memory usage vs. the number of concurrent users/processes. I would also check to see that everything is performing as expected under normal and then peak load. You might encounter scenarios where higher load causes application errors due to various requests stepping on each other.
If you really want to get detailed information you'll want to run different types of load/stress tests. You'll probably want to look at a step load test (a gradual increase of users on system over time) and a spike test (a significant number of users all accessing at the same time where almost no one was accessing it before). I would also run tests against the server right after it's been rebooted to see how that affects the system.
You'll also probably want to look at a concept called HEAT (Hostile Environment Application Testing). Really this shows what happens when some part of the system goes offline. Does the system degrade successfully? This should be a key standard.
My one really big piece of suggestion is to establish what the system is supposed to do before doing the testing. The main reason is accountability. Get people to admit that the system is supposed to do something and then test to see if it holds true. This is key because because people will immediately see the results and that will be the base benchmark for what is acceptable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Is SQL Server Bulk Insert Transactional? If I run the following query in SQL Server 2000 Query Analyzer:
BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK)
On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?
A: You can rollback the inserts . To do that we need to understand two things first
BatchSize
: No of rows to be inserted per transaction . The Default is entire
Data File. So a data file is in transaction
Say you have a text file which has 10 rows and row 8 and Row 7 has some invalid details . When you Bulk Insert the file without specifying or with specifying batch Size , 8 out of 10 get inserted into the table. The Invalid Row's i.e. 8th and 7th gets failed and doesn't get inserted.
This Happens because the Default MAXERRORS count is 10 per transaction.
As Per MSDN :
MAXERRORS :
Specifies the maximum number of syntax errors allowed in the data
before the bulk-import operation is canceled. Each row that cannot be
imported by the bulk-import operation is ignored and counted as one
error. If max_errors is not specified, the default is 10.
So Inorder to fail all the 10 rows even if one is invalid we need to set MAXERRORS=1 and BatchSize=1 Here the number of BatchSize also matters.
If you specify BatchSize and the invalid row is inside the particular batch , it will rollback the particular batch only ,not the entire data set.
So be careful while choosing this option
Hope this solves the issue.
A: BULK INSERT acts as a series of individual INSERT statements and thus, if the job fails, it doesn't roll back all of the committed inserts.
It can, however, be placed within a transaction so you could do something like this:
BEGIN TRANSACTION
BEGIN TRY
BULK INSERT OurTable
FROM 'c:\OurTable.txt'
WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t',
ROWS_PER_BATCH = 10000, TABLOCK)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
A: As stated in the BATCHSIZE definition for BULK INSERT in MSDN Library (http://msdn.microsoft.com/en-us/library/ms188365(v=sql.105).aspx) :
"If this fails, SQL Server commits or rolls back the transaction for every batch..."
In conclusion is not necessary to add transactionality to Bulk Insert.
A: Try to put it inside user-defined transaction and see what happens. Actually it should roll-back as you described it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Using MySQL on Visual Studio 2008 I am using the ODBC connector to access a MySQL db from Visual Studio 2008 and I'm facing performance problems when dealing with crystal reports and to solve this I need a native connector to visual studio. If someone has had a similar problem and knows a solution or tools (freeware preferable), I would be really grateful.
A: You want Connector/Net
Update: This link should take you to a more recent version:
http://dev.mysql.com/downloads/connector/net/5.2.html
A: Refer the below link: You will get more knowledge:
http://www.codeproject.com/KB/database/MySQLCrystal.aspx
A: You need add reference to Mysql.Data.dll. Put the dll file in Bin folder and right click - add reference. Its sample.
A: Connector/Net is the native provider you are looking for. If you're having trouble using it then you should open a new question asking how to get it working with crystal reports. I don't use crystal reports, so I can't help you there myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: $0 (Program Name) in Java? Discover main class? Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.
A: This is the code I came up with when using the combined responses of jodonnell and John Meagher. It stores the main class in a static variable to reduce overhead of repeated calls:
private static Class<?> mainClass;
public static Class<?> getMainClass() {
if (mainClass != null)
return mainClass;
Collection<StackTraceElement[]> stacks = Thread.getAllStackTraces().values();
for (StackTraceElement[] currStack : stacks) {
if (currStack.length==0)
continue;
StackTraceElement lastElem = currStack[currStack.length - 1];
if (lastElem.getMethodName().equals("main")) {
try {
String mainClassName = lastElem.getClassName();
mainClass = Class.forName(mainClassName);
return mainClass;
} catch (ClassNotFoundException e) {
// bad class name in line containing main?!
// shouldn't happen
e.printStackTrace();
}
}
}
return null;
}
A: Try this:
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName ();
Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out.
Edit: Pulling in @John Meagher's comment, which is a great idea:
To expand on @jodonnell you can also
get all stack traces in the system
using Thread.getAllStackTraces(). From
this you can search all the stack
traces for the "main" Thread to
determine what the main class is. This
will work even if your class is not
running in the main thread.
A: Also from the command line you could run the jps tool. Sounds like a
jps -l
will get you what you want.
A: For access to the class objects when you are in a static context
public final class ClassUtils {
public static final Class[] getClassContext() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext();
};
private ClassUtils() {};
public static final Class getMyClass() { return getClassContext()[2];}
public static final Class getCallingClass() { return getClassContext()[3];}
public static final Class getMainClass() {
Class[] c = getClassContext();
return c[c.length-1];
}
public static final void main(final String[] arg) {
System.out.println(getMyClass());
System.out.println(getCallingClass());
System.out.println(getMainClass());
}
}
Obviously here all 3 calls will return
class ClassUtils
but you get the picture;
classcontext[0] is the securitymanager
classcontext[1] is the anonymous securitymanager
classcontext[2] is the class with this funky getclasscontext method
classcontext[3] is the calling class
classcontext[last entry] is the root class of this thread.
A: System.getProperty("sun.java.command")
A: To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the main Thread to determine what the main class is. This will work even if your class is not running in the main thread.
A: Or you could just use getClass(). You can do something like:
public class Foo
{
public static final String PROGNAME = new Foo().getClass().getName();
}
And then PROGNAME will be available anywhere inside Foo. If you're not in a static context, it gets easier as you could use this:
String myProgramName = this.getClass().getName();
A: Try this :
Java classes have static instance of their own class (java.lang.Class type).
That means if we have a class named Main.
Then we can get its class instance by
Main.class
If you're interested in name only then,
String className = Main.class.getName();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: How do you choose an open-source license? I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?
A: If you are looking for information regarding free and open source licenses a useful comparison chart: http://en.wikipedia.org/wiki/Comparison_of_free_software_licences
A: You could always just use the best one of all, the WTFPL. I use this on most of my school projects since they aren't that great anyways.
A: Wikipedia, of course, has basically all the information you would ever need to know. But the hard part is to know where to start. I'd recommend starting off by reading about the Apache License and the GNU GPL, which are two popular sides to the same story, each offering different freedoms to the people associated with the code.
But here it is in a nutshell: Apache License lets anyone do anything with your code, including taking it and using it in a closed source product. It gives whoever is taking the code the freedom to do what they want with it.
The GNU GPL, on the other hand, allows your code only to be used in a project that is also distributed under the GPL. In this case you might write some code and prevent a proprietary company from using your work. Here, you're giving freedom to the code itself that it will always be used for "free" purposes.
A: I'm slightly surprised to see no mention of the Open Source Initiative as a source of information about which open source licences exist. It probably doesn't do the comparisons, so the other sites are also worth checking.
A: There are lots described here:
http://www.gnu.org/licenses/license-list.html#SoftwareLicenses
The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license. If you don't mind some commercial use, choose another one that's compatible with that.
A: I almost always end up usign MIT or BSD (they're equivalent), since it
*
*Is the most liberal license out there. It just says you're not responsible for any kind of trouble, and optionally forces people to include a copyright notice of your original work in derivatives.
*It allows closed source derivatives, which is something I see as a good thing: companies sometimes don't have the possibility to do their work under the GPL (they may themselves use products or components from a third party with restricted licenses).
That, and the GNU/GPL bunch are generally extremists when you encounter them in the wild.
A: This can create endless discussion, but there is one tenet I would hold to whenever deciding what license to use: DON'T CREATE A NEW ONE!!
No matter how persuasive your legal guy's arguments that, because no current license exactly meets your project's unique needs, you should write your own, or even just "slightly modify" an existing one, treat him like a programmer coming to you arguing that he just HAS to use a GOTO statement because nothing else in the language will work.
Other advice:
*
*Choose one which has major usage (see http://freshmeat.net/stats/#license)
*See David A. Wheeler's discussion of why to choose a license compatible with the GPL - http://www.dwheeler.com/essays/gpl-compatible.html.
A: More pragmatic reasons can also influence your choice of license - if you want to use a GPL library, you must use GPL yourself, or if you intend your software to be part of a larger project then you need to look at their requirements.
A: I've recently begun investigating the type of licensing to apply to a rather substantial piece of work. The number of choices and the content, restrictions (or not) and limitations of all the open-source licenses is bewildering. I've found a couple good links in the answers posted, but I didn't see anything pointing to the Open Source Initiative's alphabetical list of licenses, so I've included it here.
A: We had a similar dilemma. At our company we decided invest lots of time on a framework, with the eventual hope of releasing it to the open source community. The business is built using open source tools (apache, php, etc.), it was time to give back. We decided on an LGPL/MPL dual license. That way, we could incorporate fixes/improvements from the community, while still protecting applications (particularly ours) running on top of it from being forced to go open source as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Customizing Visual Studio I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful?
Update: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts.
Themes
*
*Consolas Font Pack for Visual Studio 2005/2008
*Scott Hanselman's Visual Studio Themes Gallery
*Visual Studio Theme Generator
Free Tools
*
*PowerCommands for Visual Studio 2008
*GhostDoc
*HyperAddin
*RockScroll
*CodeRush XPress
*.NET Reflector - (Not a plugin but still useful)
Paid Tools
*
*Resharper - Free (Open Source), $49 (Academic), $199 (Personal), $349 (Commercial)
*CodeRush with Refactor!™ Pro - $249
A: Make sure you install a custom color theme. These URLs are a good place to start looking for one:
http://www.codinghorror.com/blog/archives/000682.html
http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx
I myself love Oren Ellenbogen's Dark Scheme. Really pleasant to the eyes. Also, make sure to replace the default font with Consolas or Inconsolata (one is Microsoft's, the other is free). They are both awesome.
A: Resharper is definitely a great tool. It has a moderate learning curve but is easy to pick up for some simple things and add mastery later. It is a good price for students and kinda expensive for the rest of us. Resharper is similar to CodeRush, but seems to have a larger following.
PowerCommands is a great set of add-ons that comes free from Microsoft. Things like "Open in Windows Explorer", "Command Prompt Here", and Copy/Paste references.
A discussion regarding add-ins is floating around here somewhere.
For straight-up customization, changing colors is fun, easy, and gives you a big bang for your buck. I prefer a slightly personalized version of Rob Conery's TextMate theme for Visual Studio. Once you get colors you like, you can just export the settings and carry them with you wherever you go.
Related to colors and themes, the Consolas font pack is pretty nifty and easy on the eye.
And like John recommends, a mastery of keyboard shortcuts will pay big dividends.
A: Resharper
A: Master the built-in keyboard shortcuts (links to C# and VB keybinding cheatsheets can be found here)
A: I agree with the customizing of the theme - it makes the environment a whole lot easier to deal with.
You can choose some of the ones from the gallery at Hanselman's site, or create one with this online generator.
A: *
*GhostDoc and HyperAddin provide automatic generation and formatting of XML comments.
*RockScroll is really great for browsing legacy classes or just getting a visual feel for your own code.
*Install TestDriven.NET to get Reflector in your Tools menu (or you could follow these instructions).
A: I have Resharper and SQL Prompt, both are excellent.
A: You could try Resharper from JetBraing (http://www.jetbrains.com/resharper/), the ultimate when it comes to code refactoring. I also use GhostDoc (http://www.roland-weigelt.de/ghostdoc/) for helping me with documentation.
A: I second the vote for Resharper. It really substantially improves the quality of your code. CodeRush is also good, and more visual, either one of them is worth the money (if you can convince your employer to buy them for you :)). You would probably not want to use both at the same time, though, since there is a lot of functional overlap.
There's a cool free add-in that Scott Hanselman links to called "rockscroll", that replaces the scroll bar with a visual view of your code, I find it really helpful.
A: Personally I like having the ide pleasing to the eye. I think I found a link on Hanselman's blog but I switched to Consolas font slightly bigger than normal with a darker theme. Makes all the difference.
A: Customize The Context Menu's
I personally customize the context menu's to remove the ones I don't want and minimize my scroll time. It can also speed up the time taken for the menu's to appear.
To do this go to Tools/Customize and Check the "Context Menus" item. The menu's appear on the top of the main design area. To modify them select the context menu you want and drag and drop items around.
I usually remove items like "Get Version" in Team Foundation Server as I rarely if ever use it and I can use it from Team Explorer if I need to.
Customize the Menu's http://tim.yen.googlepages.com/CustomizeMenus.png/CustomizeMenus-full;init:.png
A: I can't coding without Resharper and GhostDoc, both are very good, i love that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Is there a standard for storing normalized phone numbers in a database? What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently.
Edit: Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like
where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2)
which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field.
[Edit]
People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.
A: First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format.
Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components
*
*C Country code 1-10 digits (right now 4 or less, but that may change)
*A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code)
*E Exchange (prefix, or switch) code 0-10 digits
*L Line number 1-10 digits
With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though.
Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number.
You may also want to handle vanity numbers such as (800) Lucky-Guy, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany.
You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.
A: Here's my proposed structure, I'd appreciate feedback:
The phone database field should be a varchar(42) with the following format:
CountryCode - Number x Extension
So, for example, in the US, we could have:
1-2125551234x1234
This would represent a US number (country code 1) with area-code/number (212) 555 1234 and extension 1234.
Separating out the country code with a dash makes the country code clear to someone who is perusing the data. This is not strictly necessary because country codes are "prefix codes" (you can read them left to right and you will always be able to unambiguously determine the country). But, since country codes have varying lengths (between 1 and 4 characters at the moment) you can't easily tell at a glance the country code unless you use some sort of separator.
I use an "x" to separate the extension because otherwise it really wouldn't be possible (in many cases) to figure out which was the number and which was the extension.
In this way you can store the entire number, including country code and extension, in a single database field, that you can then use to speed up your queries, instead of joining on a user-defined function as you have been painfully doing so far.
Why did I pick a varchar(42)? Well, first off, international phone numbers will be of varied lengths, hence the "var". I am storing a dash and an "x", so that explains the "char", and anyway, you won't be doing integer arithmetic on the phone numbers (I guess) so it makes little sense to try to use a numeric type. As for the length of 42, I used the maximum possible length of all the fields added up, based on Adam Davis' answer, and added 2 for the dash and the 'x".
A: Look up E.164. Basically, you store the phone number as a code starting with the country prefix and an optional pbx suffix. Display is then a localization issue. Validation can also be done, but it's also a localization issue (based on the country prefix).
For example, +12125551212+202 would be formatted in the en_US locale as (212) 555-1212 x202. It would have a different format in en_GB or de_DE.
There is quite a bit of info out there about ITU-T E.164, but it's pretty cryptic.
A: Storage
Store phones in RFC 3966 (like +1-202-555-0252, +1-202-555-7166;ext=22). The main differences from E.164 are
*
*No limit on the length
*Support of extensions
To optimise speed of fetching the data, also store the phone number in the National/International format, in addition to the RFC 3966 field.
Don't store the country code in a separate field unless you have a serious reason for that. Why? Because you shouldn't ask for the country code on the UI.
Mostly, people enter the phones as they hear them. E.g. if the local format starts with 0 or 8, it'd be annoying for the user to do a transformation on the fly (like, "OK, don't type '0', choose the country and type the rest of what the person said in this field").
Parsing
Google has your back here. Their libphonenumber library can validate and parse any phone number. There are ports to almost any language.
So let the user just enter "0449053501" or "04 4905 3501" or "(04) 4905 3501". The tool will figure out the rest for you.
See the official demo, to get a feeling of how much does it help.
A: I personally like the idea of storing a normalized varchar phone number (e.g. 9991234567) then, of course, formatting that phone number inline as you display it.
This way all the data in your database is "clean" and free of formatting
A: KISS - I'm getting tired of many of the US web sites. They have some cleverly written code to validate postal codes and phone numbers. When I type my perfectly valid Norwegian contact info I find that quite often it gets rejected.
Leave it a string, unless you have some specific need for something more advanced.
A: Perhaps storing the phone number sections in different columns, allowing for blank or null entries?
A: Ok, so based on the info on this page, here is a start on an international phone number validator:
function validatePhone(phoneNumber) {
var valid = true;
var stripped = phoneNumber.replace(/[\(\)\.\-\ \+\x]/g, '');
if(phoneNumber == ""){
valid = false;
}else if (isNaN(parseInt(stripped))) {
valid = false;
}else if (stripped.length > 40) {
valid = false;
}
return valid;
}
Loosely based on a script from this page: http://www.webcheatsheet.com/javascript/form_validation.php
A: The Wikipedia page on E.164 should tell you everything you need to know.
A: The standard for formatting numbers is e.164, You should always store numbers in this format. You should never allow the extension number in the same field with the phone number, those should be stored separately. As for numeric vs alphanumeric, It depends on what you're going to be doing with that data.
A: I think free text (maybe varchar(25)) is the most widely used standard. This will allow for any format, either domestic or international.
I guess the main driving factor may be how exactly you're querying these numbers and what you're doing with them.
A: What about storing a freetext column that shows a user-friendly version of the telephone number, then a normalised version that removes spaces, brackets and expands '+'. For example:
User friendly: +44 (0)181 4642542
Normalized: 00441814642542
A: I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.
A:
I find most web forms correctly allow for the country code, area code, then the remaining 7 digits but almost always forget to allow entry of an extension. This almost always ends up making me utter angry words, since at work we don't have a receptionist, and my ext.# is needed to reach me.
I would have to check, but I think our DB schema is similar. We hold a country code (it might default to the US, not sure), area code, 7 digits, and extension.
A: I would go for a freetext field and a field that contains a purely numeric version of the phone number. I would leave the representation of the phone number to the user and use the normalized field specifically for phone number comparisons in TAPI-based applications or when trying to find double entries in a phone directory.
Of course it does not hurt providing the user with an entry scheme that adds intelligence like separate fields for country code (if necessary), area code, base number and extension.
A: I've used 3 different ways to store phone numbers depending on the usage requirements.
*
*If the number is being stored just for human retrieval and won't be used for searching its stored in a string type field exactly as the user entered it.
*If the field is going to be searched on then any extra characters, such as +, spaces and brackets etc are removed and the remaining number stored in a string type field.
*Finally, if the phone number is going to be used by a computer/phone application, then in this case it would need to be entered and stored as a valid phone number usable by the system, this option of course, being the hardest to code for.
A: Where are you getting the phone numbers from? If you're getting them from part of the phone network, you'll get a string of digits and a number type and plan, eg
441234567890 type/plan 0x11 (which means international E.164)
In most cases the best thing to do is to store all of these as they are, and normalise for display, though storing normalised numbers can be useful if you want to use them as a unique key or similar.
A:
User friendly: +44 (0)181 464 2542 normalised: 00441814642542
The (0) is not valid in the international format. See the ITU-T E.123 standard.
The "normalised" format would not be useful to US readers as they use 011 for international access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "100"
} |
Q: LightWindow & IE7, "Line 444 - object does not support this property or method" I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of lightwindow.js, claiming that the object does not support this property or method. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later.
Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow).
These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue:
*
*Moved the call to lightwindow.js to the bottom of the page.
*Changed line 444 to: if (this._getGalleryInfo(link.rel)) {
*Changed line 1157 to: if (this._getGalleryInfo(this.element.rel)) {
*Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a try/catch block, swallowing the exception.
EDIT:
I realised that this broke Firefox. Adding the following as line 445 now makes it work - try { gallery = this._getGalleryInfo(link.rel); } catch (e) { }
It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.
A: Instead of the try..catch maybe you could try using
if( this && this._getGalleryInfo )
{
//use the function
}
you could also check in the same way this.element.rel ( if(this && this.element && this.element.rel) ... ) before using it.
It looks like there's a case that the _getGalleryInfo or this.element.rel has not yet been initialized so it wouldn't exist yet. Check if it exists then if I does use it.
of course i could be completely wrong, the only way to know is by testing it out.
A: I had the same problem with Lightwindow 2.0, IE6, IE7, IE8 (beta); I resolved in the following way for IE6, IE7, IE8 (beta).
Instead of:
if(gallery = this._getGalleryInfo(link.rel))
I put on lines 443 and 1157:
gallery = this._getGalleryInfo(link.rel)
if(gallery)
Hope this will help!
A: I fixed this by changing line 444 to:
var gallery = this._getGalleryInfo(link.rel)
Then changing the subsequent comparison statement to:
if(gallery.length > 0)
{
// Rest of code here...
...which seems to have sorted it in IE6+ and kept it working in Firefox etc.
I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance?
I suspect the ? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure?
HTH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I make Eclipse file search not include svn directories? When I do a file search on eclipse it includes the .svn directories by default. I tried excluding them from the build path but they still appear on file search results.
A: If you install the subclipse plugin then it automatically excludes the .svn directories (plus provides some other cool stuff in the IDE).
http://subclipse.tigris.org/
If it does not work, simply restart Eclipse (sometimes it's needed on a fresh checkout)
A: Following up on Mark Ingram's excellent answer, simply installing the plugin won't get you there -- You'll still need to Share your project in order for the automatic Search filtering to take hold. After you set up the SVN repository location from within the Subeclipse view you may Share your project by doing the following:
*
*From within Package Explorer, right-click the project name
*Select the Team context menu option and then Share Project....
*Step trough the wizard to tie your project to its location in the svn repository
*Once you complete that and the workspace rebuilds you are all set to enjoy filtered search.
A: Excluding the .svn folders by making them derived stops then appearing in the search results, see here.
You have to do it manually for each folder, if you have a lot of .svn folders then it's not ideal.
A: If you are gonig down the plugin route, I tend to prefer subversive over subclipse.
A: Spaceman is right. With Helios, choose Project -> Properties -> Resource -> Resource Filters and then add an exclude filter for type "Folder" with name .svn.
A: Ah - OK. I don't use SubVersion per se, but would this be of any use? It claims it can do what you want...
A: Eclipse import would also contain file of type .java.svn-base, so its better to give as in below image
[[1]: https://i.stack.imgur.com/szDxP.png][1]
A: Click on the drop-down triangle in the top-right corner of the Navigator and choose "Filters..".
By default Eclipse only offers you ".class" and ".".
If you choose ".*" you'll hide .svn files. Obviously all other .something files will also be hidden.
A: You can off course also select ALL the file name patterns to include in the file search dialog
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
} |
Q: Converting latitude/longitude to Alberta 10 TM Projection I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection.
The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.
A: I've used GDAL (http://www.gdal.org) to do this. It supports bindings for many different languages as well.
A: For free GIS libraries, take a look here: http://www.freegis.org/database/?cat=12. Hopefully you can find something that fits your needs.
A: I would seriously consider using a third party dll to do this rather than code it yourself.
I don't know the full details of the 10 TM projection, but I worked on a project that required coordinate conversions between many different coordinate systems to a high degree of accuracy, including UTM and Lat/Long. We found that the maths involved was way too complicated.
Perhaps take a look at the open source PROJ.4:
http://trac.osgeo.org/proj/
They seems to support a huge range of conversions, and so I hope Alberta 10 TM will be covered.
A: Grab PROJ Cartographic Projections library - open source library.
Suggested parameters for 10TM:
+proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27
According to this post you may need to:
change the ellps to GRS80 if your 10TM
data is referenced to the NAD83 datum
(instead of NAD27/clrk66). You may
also need to change the false northing
(y_0) to be -5000000 if your 10TM
coordinates for Alberta are less than
5,000,000 (an AltaLIS "standard").
I should mention that proj.4 is the library to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do.
I also recommend reading Map Projections-A Working Manual (Paperback) by John Snyder if you are into these kinds of things.. it's a classic. :) (fixed the link)
A: Download the opensource GIS application MapWindow
Open the GIS Tools menu
And use their shapefile reprojection tool. Under "National Grids Canada" you can select this Alberta projection.
-Jeff Tiemann
[email protected]
A: You can also use http://code.google.com/p/android-openmap-framework/ which can convert an Android Location to a LatLonPoint, UTMPoint, or MGRSPoint.
A: You can insert your coordinates pairs to Coordinate System Transformation - online service where you can set appropriate input and desired output coordinate system. There are hundreds of coordinate systems - it is possible to simply find appropriate coordinate system using any keyword. You can see editable proj4 text definition for each coordinate system so if you need to modify any projection parametr, you can do it there. Or you can define your own custom projection...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I get the difference between two Dates in JavaScript? I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
A: In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
This should just work
EDIT: Fixed bug pointed by @bdukes
EDIT:
For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
A: If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
So to set your end date to 2 weeks after your start date, do something like this:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
A: Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
A: Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
// This one returns a signed decimal. The sign indicates past or future.
this.getDateDiff = function(date1, date2) {
return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}
// This one always returns a positive decimal. (Suggested by Koen below)
this.getDateDiff = function(date1, date2) {
return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
}
A: JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
A: If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
A: See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
setTimeout(showDiff,1000);
}
for your HTML Code:
<div id="showTime"></div>
A: function compare()
{
var end_actual_time = $('#date3').val();
start_actual_time = new Date();
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time-start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
getTime(diffSeconds);
}
function getTime(seconds) {
var days = Math.floor(leftover / 86400);
//how many seconds are left
leftover = leftover - (days * 86400);
//how many full hours fits in the amount of leftover seconds
var hours = Math.floor(leftover / 3600);
//how many seconds are left
leftover = leftover - (hours * 3600);
//how many minutes fits in the amount of leftover seconds
var minutes = leftover / 60;
//how many seconds are left
//leftover = leftover - (minutes * 60);
alert(days + ':' + hours + ':' + minutes);
}
A: alternative modificitaion extended code..
http://jsfiddle.net/vvGPQ/48/
showDiff();
function showDiff(){
var date1 = new Date("2013/01/18 06:59:00");
var date2 = new Date();
//Customise date2 for your required future time
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var years = Math.floor(diff/(365*24*60*60));
var leftSec = diff - years * 365*24*60*60;
var month = Math.floor(leftSec/((365/12)*24*60*60));
var leftSec = leftSec - month * (365/12)*24*60*60;
var days = Math.floor(leftSec/(24*60*60));
var leftSec = leftSec - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed.";
setTimeout(showDiff,1000);
}
A: Below code will return the days left from today to futures date.
Dependencies: jQuery and MomentJs.
var getDaysLeft = function (date) {
var today = new Date();
var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
getDaysLeft('YYYY-MM-DD');
A: If you use Date objects and then use the getTime() function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
A: this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message
take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears
it will show result of number of years with fraction
function getStudyYears()
{
if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
{
var d1 = document.getElementById('txtFromQualifDate').value;
var d2 = document.getElementById('txtQualifDate').value;
var one_day=1000*60*60*24;
var x = d1.split("/");
var y = d2.split("/");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var dDays = (date2.getTime()-date1.getTime())/one_day;
if(dDays < 365)
{
alert("the date between start study and graduate must not be less than a year !");
document.getElementById('txtQualifDate').value = "";
document.getElementById('txtStudyYears').value = "";
return ;
}
var dMonths = Math.ceil(dDays / 30);
var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
document.getElementById('txtStudyYears').value = dYears;
}
}
A: <html>
<head>
<script>
function dayDiff()
{
var start = document.getElementById("datepicker").value;
var end= document.getElementById("date_picker").value;
var oneDay = 24*60*60*1000;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
document.getElementById("leave").value =diffDays ;
}
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>
A: var getDaysLeft = function (date1, date2) {
var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
var date1='2018-05-18';
var date2='2018-05-25';
var dateDiff = getDaysLeft(date1, date2);
console.log(dateDiff);
A: To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
A: Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
A: function checkdate() {
var indate = new Date()
indate.setDate(dat)
indate.setMonth(mon - 1)
indate.setFullYear(year)
var one_day = 1000 * 60 * 60 * 24
var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
var str = diff + " days are remaining.."
document.getElementById('print').innerHTML = str.fontcolor('blue')
}
A: THIS IS WHAT I DID ON MY SYSTEM.
var startTime=("08:00:00").split(":");
var endTime=("16:00:00").split(":");
var HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));
console.log(HoursInMinutes/60);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "120"
} |
Q: Are there any version control systems for 3d models / 3d data? Well the subject is the question basically. Are there any version control systems out there for 3d models. An open source approach would be preferred of course.
I am looking for functionality along the lines of subversion however more basic systems would be of interest as well. Basic operations like branching / merging / commit should be available in one form or another.
UPDATE: With open source approach I don't mean free but the option of heavily expanding and customizing the system when needed
UPDATE2: I don't know how to describe this in the best way but the format of the 3d model is not that important. We will be using IFC models and mostly CAD programs. The approach Adam Davis describes is probably what I am looking for.
A: Have a look at http://3drepo.org
It's open source revision control framework for 3D assets and highly extensible.
A: This is going to be difficult since most 3D CAD programs do not take into account the possibility of revision, so when you load something and then save it again it may completely re-order the points (there are reasons for this, usually done for performance).
Further, large models represented in a text format are huge files, and will take forever to copy/merge/etc.
There is no current system that will manage this, but there's a really big need in the industry for it.
I would expect such a system would have a model normalizer that converts to and from the desired CAD format and the revision format. It could then handle merges and track changes more easily.
It would also need to output diffs in a form that you could open a "diffed" model in a cad program and the changes are shown in a different color or otherwise highlighted. No one is going to be able to look at a text diff and understand what they're looking at. This diffing program would ultimately need to support understanding that two models are the same even though the 0,0,0 location and rotation are not the same (difficult matching problem) and give the user some interface to allow them to help it when it gets stuck.
You'd probably have to deal with the parts of the model separately (bones, mesh, textures, etc) and have a third file that synchronizes them when converting them to an inclusive model file for use and modification.
It's not a trivial problem... But if you started on something that just handled meshes and open sourced it, you'd probably get a lot of people interested.
A: Although this question is old, it's still in Google's results for 3d version control. Luckily in the years that have passed since the question was asked, Github has started supporting 3d STL files with visual diffs!!
A: Similar to what GingaNinja said, if all you care about is management of binary files at different revisions, most revision control systems will work for you. However, if you are looking for a tool that will display the changes in the actual images, you might be hard pressed to find a recommendation of a tool here. I would start by asking on a graphic artist forums.
A: Although I realize it's a slightly different topic, you might be interested in the answers to the question Version Control for Graphics...
A: There is a diff tool for common 3D formats being released in about a week. It supports dxf/dwg, obj, stl, igs. It may not be perfect since it is still in version 1 but hopefully it can help with your problem. The tool is called Differ3D and it can be found at http://www.blackspiralsoftware.com.
Disclaimer: I work for the company that released this product. We are looking to improve it so any feedback would be welcome.
A: I was under the impression that SVN is perfect for any kind of project that uses text files. So if your model is made up of text files, then it would be fine.
I don't see how binary data would work, as all version control that I know of makes use of diff management, which uses text comparisons.
A: 3d models and data are just data files whether their format is text or binary. Version control systems can handle both since often you check in libraries etc, which are binary files.
I'm not quite sure what you mean by "open source approach". Do you mean a free solution? You can get open source projects which have to pay for, depending on your usage, e.g. Qt.
Subversion or CVS would store text or binary models and are both free. Subversion is preferrable to CVS since it can commit multiple files in change sets. On Windows you can use TortoiseSVN, which is an excellent, free tool set.
A: If you use Subversion you must remember to lock (assuming the files are binary, which nearly all 3D model formats are). Other than Subversion and other OSS like it, you might look at Gridiron Flow- the new content/workflow management software from Gridiron Software. John Nack of Adobe gave it a rave review.
A: DXF is a text-file standard (similarish to XML) but I don't think merging these types of files is a particularly good idea.
If you wanted to perform a Diff operation on 2 AutoCAD files, you can programmatically address individual objects by their "Handle" - a unique hex identifier. Location, rotation, scaling, colour etc are properties of the object. CAD drawings are basically an object database. I don't know of any product that does this. Change tracking is a viable proposition but merging would be a lot more complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Standard way to open a folder window in linux? I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.
On OSX, I can open a window in the finder with
os.system('open "%s"' % foldername)
and on Windows with
os.startfile(foldername)
What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?
This looks like something that could be specified by the freedesktop.org folks (a python module, similar to webbrowser, would also be nice!).
A: os.system('xdg-open "%s"' % foldername)
xdg-open can be used for files/urls also
A: this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.
There might be an function that launches the defaults for kde or gnome in their respective toolkits but I haven't had reason to look for them.
A: You're going to have to do this based on the running window manager. OSX and Windows have a (defacto) standard way because there is only one choice.
You shouldn't need to specify the exact filemanager application, though, this should be possible to do through the wm. I know Gnome does, and it's important to do this in KDE since there are two possible file managers (Konqueror/Dolphin) that may be in use.
I agree that this would be a good thing for freedesktop.org to standardize, although I doubt it will happen unless someone steps up and volunteers to do it.
EDIT: I wasn't aware of xdg-open. Good to know!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Lightweight fuzzy search library Can you suggest some light weight fuzzy text search library?
What I want to do is to allow users to find correct data for search terms with typos.
I could use full-text search engines like Lucene, but I think it's an overkill.
Edit:
To make question more clear here is a main scenario for that library:
I have a large list of strings. I want to be able to search in this list (something like MSVS' intellisense) but it should be possible to filter this list by string which is not present in it but close enough to some string which is in the list.
Example:
*
*Red
*Green
*Blue
When I type 'Gren' or 'Geen' in a text box, I want to see 'Green' in the result set.
Main language for indexed data will be English.
I think that Lucene is to heavy for that task.
Update:
I found one product matching my requirements. It's ShuffleText.
Do you know any alternatives?
A: Lucene is very scalable—which means its good for little applications too. You can create an index in memory very quickly if that's all you need.
For fuzzy searching, you really need to decide what algorithm you'd like to use. With information retrieval, I use an n-gram technique with Lucene successfully. But that's a special indexing technique, not a "library" in itself.
Without knowing more about your application, it won't be easy to recommend a suitable library. How much data are you searching? What format is the data? How often is the data updated?
A: I'm not sure how well Lucene is suited for fuzzy searching, the custom library would be better choice. For example, this search is done in Java and works pretty fast, but it is custom made for such task:
http://www.softcorporation.com/products/people/
A: Soundex is very 'English' in it's encoding - Daitch-Mokotoff works better for many names, especially European (Germanic) and Jewish names. In my UK-centric world, it's what I use.
Wiki here.
A: If you can choose to use a database, I recommend using PostgreSQL and its fuzzy string matching functions.
If you can use Ruby, I suggest looking into the amatch library.
A: You didn't specify your development platform, but if its PHP then suggest you look at the ZEND Lucene lubrary :
http://ifacethoughts.net/2008/02/07/zend-brings-lucene-to-php/
http://framework.zend.com/manual/en/zend.search.lucene.html
As it LAMP its far lighter than Lucene on Java, and can easily be extended for other filetypes, provided you can find a conversion library or cmd line converter - there are lots of OSS solutions around to do this.
A: Try Walnutil - based on Lucene API - integrated to SQL Server and Oracle DBs . You can create any type of index and then use it. For simple search you can use some methods from walnutilsoft, for more complicated search cases you can use Lucene API. See web based example where was used indexes created from Walnutil Tools. Also you can see some code example written on Java and C# which you can use it for creating different type of search.
This tools is free.
http://www.walnutilsoft.com/
A: @aku - links to working soundex libraries are right there at the bottom of the page.
As for Levenshtein distance, the Wikipedia article on that also has implementations listed at the bottom.
A: A powerful, lightweight solution is sphinx.
It's smaller then Lucene and it supports disambiguation.
It's written in c++, it's fast, battle-tested, has libraries for every env and it's used by large companies, like craigslists.org
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Parsing an XML file in C# What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0
A: If you're using .Net 2 then the XmlReader and XmlDocument are about it.
If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement.
A: I haven't benched-marked it myself, but when I've asked about it in the past I've been told that XmlDocument is supposed to be faster. I have my doubts, though, since XmlDocument would need to create a DOM while XmlReader does not.
A: If you use an XmlTextReader class it will technically be faster than using an XmlDocument, which parses the entire file and builds a DOM for you. But you must also consider that fact that with an XmlTextReader, you are just reading one node at a time, so there is the additional overhead of making sense of the data as you read it. If you are going to end up storing everything yourself anyway, using XmlDocument might end up being more efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to display line breaks in SharePoint comment history field We have a SharePoint list setup with history enabled so the Comments field keeps all the past values. When it displays, the Comments field is void of all line breaks. However, when SharePoint e-mails the change to us, the line breaks are in there. The Description field also shows the line breaks.
So, something must be stripping out the line breaks in the read-only view of the Comments field.
Any idea on how to customize that so it retains the formatting in the detail view of the SharePoint list item?
Update: the stock pages with this behavior are
*
*/EditForm.aspx
*/DispForm.aspx
A: What are you using to view the list? A default SharePoint view (AllItems.aspx?), or a DataFormWebPart? Something else?
If you can customize the page that displays this list in SharePoint Designer, make sure this field is set to display "Rich Text" and not just "Plain Text".
If this is the cause of your problem, then another symptom you might see is that certain symbols are displayed as their HTML codes (e.g. "&" as "&").
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Levenshtein distance based methods Vs Soundex As per this comment in a related thread, I'd like to know why Levenshtein distance based methods are better than Soundex.
A: I would suggest using Metaphone, not Soundex. As noted, Soundex was developed in the 19th century for American names. Metaphone will give you some results when checking the work of poor spellers who are "sounding it out", and spelling phonetically.
Edit distance is good at catching typos such as repeated letters, transposed letters, or hitting the wrong key.
Consider the application to decide which will fit your users best—or use both together, with Metaphone complementing the suggestions produced by Levenshtein.
With regard to the original question, I've used n-grams successfully in information retrieval applications.
A: I agree with you on Daitch-Mokotoff, Soundex is biased because the original US census takers wanted 'Americanized' names.
Maybe an example on the difference would help:
Soundex puts addition value in the start of a word - in fact it only considers the first 4 phonetic sounds. So while "Schmidt" and "Smith" will match "Smith" and "Wmith" won't.
Levenshtein's algorithm would be better for finding typos - one or two missing or replaced letters produces a high correlation, while the phonetic impact of those missing letters is less important.
I don't think either is better, and I'd consider both a distance algorithm and a phonetic one for helping users correct typed input.
A: Soundex is rather primitive - it was originally developed to be hand calculated. It results in a key that can be compared.
Soundex works well with western names, as it was originally developed for US census data. It's intended for phonetic comparison.
Levenshtein distance looks at two values and produces a value based on their similarity. It's looking for missing or substituted letters.
Basically Soundex is better for finding that "Schmidt" and "Smith" might be the same surname.
Levenshtein distance is better for spotting that the user has mistyped "Levnshtein" ;-)
A: @Keith:
As I posted on the other question, Daitch-Mokotoff is better for us Europeans (and I'd argue the US).
I've also read the Wiki on Levenshtein. But I don't see why (in real life) it's better for the user than Soundex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Non-Clustered Index on a Clustered Index column improves performance? In SQL Server 2005, the query analyzer has told me many times to create a non-clustered index on a primary ID column of a table which already has a clustered index. After following this recommendation, the query execution plan reports that the query should be faster.
Why would a Non-Clustered index on the same column (with the same sort order) be faster than a Clustered index?
A: I'd guess it would be faster in cases where you don't need the full row data, for example if you're just checking if a row with a given ID does exist. Then a clustered index would be rather huge while a small "one column" index would be much slimmer.
A: A clustered index has all the data for the table while a non clustered index only has the column + the location of the clustered index or the row if it is on a heap (a table without a clustered index). So if you do a count(column) and that column is indexed with a non clustered index SQL server only has to scan the non clustered index which is faster than the clustered index because more will fit on 8K pages
A: A clustered index will generally be faster, but you can only have 1 clustered index. So if the table already has a clustered index on a different column, then a non-clustered index is the best you can do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: What is the best EXIF library for .Net? I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?
A: If you're compiling against v3 of the Framework (or later), then you can load the images using the BitmapSource class, which exposes the EXIF metadata through the Metadata property
A: A new and very fast library is ExifLib - A Fast Exif Data Extractor for .NET 2.0 by Simon McKenzie. I ended up using this one and the code is easy to use and understand. I used it for an app to rename according to the date taken. I wonder how many times such an app has been written.
My tip: Make sure to call Dispose on the ExifReader objects once you've finished with them or the files remain open.
A: I like Atalasoft's DotImage Photo, but its a closed source solution and costs about 600 per dev license.
You can also check out DTools at Codeplex, which is an open source framework designed to supplement the standard Fx. It includes some Exif related classes.
A: the one I have saved in feeddemon for me to check out more when I have time (when is that for a programmer? LOL) is below
ExifTagCollection - EXIF Metadata extraction library
Mike
A: Check out this metadata extractor. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.
A: If you're willing to use an open-source library, may I humbly suggest one of my own creation?
The metadata-extractor project has been alive and well since 2002 for Java, and is now available for .NET.
*
*Open source (Apache 2.0)
*Heavily tested and widely used
*Supports many image types (JPEG, TIFF, PNG, WebP, GIF, BMP, ICO, PCX...)
*Supports many metadata types (Exif, IPTC, XMP, JFIF, ...)
*Supports many manufacturer-specific fields (Canon, Nikon, ...)
*Very fast (fully processes ~400 images totalling 1.33GB in ~3 seconds) with low memory consumption
*Builds for .NET 3.5, .NET 4.0+ and PCL
It's available via NuGet or GitHub.
Sample usage:
IEnumerable<Directory> directories = ImageMetadataReader.ReadMetadata(path);
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.TagName} = {tag.Description}");
A: Several years ago, I started a little JPEG EXIF app with Omar Shahine to work on JPEG EXIF files, called JpegHammer.
He extracted from that project a library and called it PhotoLibrary, it was an easy .NET wrapper for the EXIF 2.2 tags. Unfortunately, the GotDotNet site is gone, CodePlex doesn't have it, Omar's web site links don't work, and I don't have a copy anymore.
But, if you can dig around Google, maybe you'll find it and it'll do the trick for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: What is a tuple useful for? I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?
A: *
*Tuples are used whenever you want to return multiple results from a function.
*Since they're immutable, they can be used as keys for a dictionary (lists can't).
A: Tuples and lists have the same uses in general. Immutable data types in general have many benefits, mostly about concurrency issues.
So, when you have lists that are not volatile in nature and you need to guarantee that no consumer is altering it, you may use a tuple.
Typical examples are fixed data in an application like company divisions, categories, etc. If this data change, typically a single producer rebuilts the tuple.
A: Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it.
a = {}
a[(1,2,"bob")] = "hello!"
a[("Hello","en-US")] = "Hi There!"
I've used this feature primarily to create a dictionary with keys that are coordinates of the vertices of a mesh. However, in my particular case, the exact comparison of the floats involved worked fine which might not always be true for your purposes [in which case I'd probably convert your incoming floats to some kind of fixed-point integer]
A: I find them useful when you always deal with two or more objects as a set.
A: A tuple is a sequence of values. The values can be any type, and they are indexed by integer, so tuples are not like lists. The most important difference is that tuples are immutable.
A tuple is a comma-separated list of values:
t = 'p', 'q', 'r', 's', 't'
it is good practice to enclose tuples in parentheses:
t = ('p', 'q', 'r', 's', 't')
A: The best way to think about it is:
*
*A tuple is a record whose fields don't have names.
*You use a tuple instead of a record when you can't be bothered to specify the field names.
So instead of writing things like:
person = {"name": "Sam", "age": 42}
name, age = person["name"], person["age"]
Or the even more verbose:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Sam", 42)
name, age = person.name, person.age
You can just write:
person = ("Sam", 42)
name, age = person
This is useful when you want to pass around a record that has only a couple of fields, or a record that is only used in a few places. In that case specifying a whole new record type with field names (in Python, you'd use an object or a dictionary, as above) could be too verbose.
Tuples originate from the world of functional programming (Haskell, OCaml, Elm, F#, etc.), where they are commonly used for this purpose. Unlike Python, most functional programming languages are statically typed (a variable can only hold one type of value, and that type is determined at compile time). Static typing makes the role of tuples more obvious. For example, in the Elm language:
type alias Person = (String, Int)
person : Person
person = ("Sam", 42)
This highlights the fact that a particular type of tuple is always supposed to have a fixed number of fields in a fixed order, and each of those fields is always supposed to be of the same type. In this example, a person is always a tuple of two fields, one is a string and the other is an integer.
The above is in stark contrast to lists, which are supposed to be variable length (the number of items is normally different in each list, and you write functions to add and remove items) and each item in the list is normally of the same type. For example, you'd have one list of people and another list of addresses - you would not mix people and addresses in the same list. Whereas mixing different types of data inside the same tuple is the whole point of tuples. Fields in a tuple are usually of different types (but not always - e.g. you could have a (Float, Float, Float) tuple to represent x,y,z coordinates).
Tuples and lists are often nested. It's common to have a list of tuples. You could have a list of Person tuples just as well as a list of Person objects. You can also have a tuple field whose value is a list. For example, if you have an address book where one person can have multiple addresses, you could have a tuple of type (Person, [String]). The [String] type is commonly used in functional programming languages to denote a list of strings. In Python, you wouldn't write down the type, but you could use tuples like that in exactly the same manner, putting a Person object in the first field of a tuple and a list of strings in its second field.
In Python, confusion arises because the language does not enforce any of these practices that are enforced by the compiler in statically typed functional languages. In those languages, you cannot mix different kinds of tuples. For example, you cannot return a (String, String) tuple from a function whose type says that it returns a (String, Integer) tuple. You also cannot return a list when the type says you plan to return a tuple, and vice versa. Lists are used strictly for growing collections of items, and tuples strictly for fixed-size records. Python doesn't stop you from breaking any of these rules if you want to.
In Python, a list is sometimes converted into a tuple for use as a dictionary key, because Python dictionary keys need to be immutable (i.e. constant) values, whereas Python lists are mutable (you can add and remove items at any time). This is a workaround for a particular limitation in Python, not a property of tuples as a computer science concept.
So in Python, lists are mutable and tuples are immutable. But this is just a design choice, not an intrinsic property of lists and tuples in computer science. You could just as well have immutable lists and mutable tuples.
In Python (using the default CPython implementation), tuples are also faster than objects or dictionaries for most purposes, so they are occasionally used for that reason, even when naming the fields using an object or dictionary would be clearer.
Finally, to make it even more obvious that tuples are intended to be another kind of record (not another kind of list), Python also has named tuples:
from collections import namedtuple
Person = namedtuple("Person", "name age")
person = Person("Sam", 42)
name, age = person.name, person.age
This is often the best choice - shorter than defining a new class, but the meaning of the fields is more obvious than when using normal tuples whose fields don't have names.
Immutable lists are highly useful for many purposes, but the topic is far too complex to answer here. The main point is that things that cannot change are easier to reason about than things that can change. Most software bugs come from things changing in unexpected ways, so restricting the ways in which they can change is a good way to eliminate bugs. If you are interested, I recommend reading a tutorial for a functional programming language such as Elm, Haskell or Clojure (Elm is the friendliest). The designers of those languages considered immutability so useful that all lists are immutable there. (Instead of changing a list to add and or remove an item, you make a new list with the item added or removed. Immutability guarantees that the old copy of the list can never change, so the compiler and runtime can make the code perform well by re-using parts of the old list in the new one and garbage-collecting the left-over parts when they are longer needed.)
A: I like this explanation.
Basically, you should use tuples when there's a constant structure (the 1st position always holds one type of value and the second another, and so forth), and lists should be used for lists of homogeneous values.
Of course there's always exceptions, but this is a good general guideline.
A: A list can always replace a tuple, with respect to functionality (except, apparently, as keys in a dict). However, a tuple can make things go faster. The same is true for, for example, immutable strings in Java -- when will you ever need to be unable to alter your strings? Never!
I just read a decent discussion on limiting what you can do in order to make better programs; Why Why Functional Programming Matters Matters
A: A tuple is useful for storing multiple values.. As you note a tuple is just like a list that is immutable - e.g. once created you cannot add/remove/swap elements.
One benefit of being immutable is that because the tuple is fixed size it allows the run-time to perform certain optimizations. This is particularly beneficial when a tupple is used in the context of a return value or a parameter to a function.
A: Use Tuple
*
*If your data should or does not need to be changed.
*Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do
with it is iterate through it.
*If we need an array of elements to be
used as dictionary keys, we can use Tuples. As Lists are mutable,
they can never be used as dictionary keys.
Furthermore, Tuples are immutable, whereas Lists are mutable. By the same token, Tuples are fixed size in nature, whereas Lists are dynamic.
a_tuple = tuple(range(1000))
a_list = list(range(1000))
a_tuple.__sizeof__() # 8024 bytes
a_list.__sizeof__() # 9088 bytes
more information :
https://jerrynsh.com/tuples-vs-lists-vs-sets-in-python/
A: In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes. For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method. A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.
I try to be judicious about this particular use, though. If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.
A: Tuples are used in :
*
*places where you want your sequence of elements to be immutable
*in tuple assignments
a,b=1,2
*in variable length arguments
def add(*arg) #arg is a tuple
return sum(arg)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: How do I handle newlines in JSON? I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
This gives me an error:
unterminated string literal
With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.
When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.
A: You will need to have a function which replaces \n to \\n in case data is not a string literal.
function jsonEscape(str) {
return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}
var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = JSON.parse(jsonEscape(data));
Resulting dataObj will be
Object {count: 1, stack: "sometext\n\n"}
A: This is what you want:
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
You need to escape the \ in your string (turning it into a double-\), otherwise it will become a newline in the JSON source, not the JSON data.
A: well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.
just wrap your text around this class and see the magic :D
<p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.
A: TLDR: A solution to the author's problem.
The json that you have generated is wrong because it contains newlines in one of its values. To generate a json that represents (not contains) newlines in one of its values you can use:
Use String.raw literal:
var data = String.raw`{"count" : 1, "stack" : "sometext\n\n"}`;
or apply JSON.stringify to a javascript object (which is json-like in the first place).
var data = JSON.stringify({"count" : 1, "stack" : "sometext\n\n"});
For some reason all answers inside here focus on how to parse a JSON string representation in JavaScript, which may cause confusion regarding how to represent newlines on actual JSON. The latter is not language-dependent.
Strictly based on the question title :
How do I handle newlines in JSON?
Let's say you parse a JSON file using the following code in node (it could be any language though):
let obj = JSON.parse(fs.readFileSync('file.json'));
console.log(obj.mykey)
Below is the output for each of the possible contents of file.json:
Input 1:
{
"mykey": "my multiline
value"
}
Output 1:
SyntaxError: Unexpected token
Input 2:
{
"mykey": "my multiline\nvalue"
}
Output 2:
my multiline
value
Input 3:
{
"mykey": "my multiline\\nvalue"
}
Output 3:
my multiline\nvalue
Conclusion 1:
To represent a newline inside a json file we should use the \n character. To represent the \n we should use \\n.
How would we define each of the above inputs using JavaScript (instead of input file):
When we need to define a string containing JSON in JavaScript, things change a bit because of the special meaning that \n has also for JavaScript. But also notice how String.raw literal fixes this.
Input1:
let input1 = '{"mykey": "my multiline\nvalue"}'
//OR
let input1 = `{
"mykey": "my multiline
value"
}`;
//(or even)
let input1 = `{
"mykey": "my multiline\nvalue"
}`;
//OR
let input1 = String.raw`{
"mykey": "my multiline
value"
}`;
console.log(JSON.parse(input1).mykey);
//SyntaxError: Unexpected token
//in JSON at position [..]
Input 2:
let input2 = '{"mykey": "my multiline\\nvalue"}'
//OR
let input2 = `{
"mykey": "my multiline\\nvalue"
}`;
//OR (Notice the difference from default literal)
let input2 = String.raw`{
"mykey": "my multiline\nvalue"
}`;
console.log(JSON.parse(input2).mykey);
//my multiline
//value
Input 3:
let input3 = '{"mykey": "my multiline\\\\nvalue"}'
//OR
let input3 = `{
"mykey": "my multiline\\\\nvalue"
}`;
//OR (Notice the difference from default literal)
let input3 = String.raw`{
"mykey": "my multiline\\nvalue"
}`;
console.log(JSON.parse(input3).mykey);
//my multiline\nvalue
Conclusion 2:
To define a json string in javascript the easiest way would be to use String.raw, because it does not require any escaping (Well apart from backtick which is escaped like this String.raw`abc${"`"}def` ).
Of course, the easiest way to create json in javascript, in general, is to convert a javascript object to json (using JSON.stringify).
Important note:
Don't get confused by how chrome/firefox devtools preview variables containing newlines (e.g. when you just write the variable name and press Enter). When previewing objects they always represent newlines of string values like \n. But, when previewing a string (e.g. dataObj.stack) firefox will show a newline as an empty line but chrome will still show it as \n. So, to be safe, you should always preview with console.log(dataObj.stack) to better understand what's actually contained inside the specific variable.
A: You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.
The JavaScript implementation of all major browsers have the unescape command.
Example:
On the server:
response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"
In the browser:
document.getElementById("text1").value = unescape(jsonObject.field1)
A: You might want to look into this C# function to escape the string:
http://www.aspcode.net/C-encode-a-string-for-JSON-JavaScript.aspx
public static string Enquote(string s)
{
if (s == null || s.Length == 0)
{
return "\"\"";
}
char c;
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
string t;
sb.Append('"');
for (i = 0; i < len; i += 1)
{
c = s[i];
if ((c == '\\') || (c == '"') || (c == '>'))
{
sb.Append('\\');
sb.Append(c);
}
else if (c == '\b')
sb.Append("\\b");
else if (c == '\t')
sb.Append("\\t");
else if (c == '\n')
sb.Append("\\n");
else if (c == '\f')
sb.Append("\\f");
else if (c == '\r')
sb.Append("\\r");
else
{
if (c < ' ')
{
//t = "000" + Integer.toHexString(c);
string t = new string(c,1);
t = "000" + int.Parse(tmp,System.Globalization.NumberStyles.HexNumber);
sb.Append("\\u" + t.Substring(t.Length - 4));
}
else
{
sb.Append(c);
}
}
}
sb.Append('"');
return sb.ToString();
}
A: According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:
A string is a sequence of Unicode code points wrapped with quotation marks
(U+0022). All characters may be placed within the quotation marks except for the
characters that must be escaped: quotation mark (U+0022), reverse solidus
(U+005C), and the control characters U+0000 to U+001F. There are two-character
escape sequence representations of some characters.
So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:
*
*\f represents the form feed character (U+000C).
*\n represents the line feed character (U+000A).
As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):
jsonStr = "{ \"name\": \"Multi\\nline.\" }";
A: I used this function to strip newline or other characters in data to parse JSON data:
function normalize_str($str) {
$invalid = array(
'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z',
'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A',
'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E',
'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y',
'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a',
'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i',
'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
"`" => "'", "´" => "'", '"' => ',', '`' => "'",
'´' => "'", '"' => '\"', '"' => "\"", '´' => "'",
"’" => "'",
"{" => "",
"~" => "", "–" => "-", "'" => "'", " " => " ");
$str = str_replace(array_keys($invalid), array_values($invalid), $str);
$remove = array("\n", "\r\n", "\r");
$str = str_replace($remove, "\\n", trim($str));
//$str = htmlentities($str, ENT_QUOTES);
return htmlspecialchars($str);
}
echo normalize_str($lst['address']);
A: As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to dataObj variable without wrapping it with single quotes (tip: eval==evil)
var dataObj = {"count" : 1, "stack" : "sometext\n\n"};
console.log(dataObj);
A: I encountered that problem while making a class in PHP 4 to emulate json_encode (available in PHP 5). Here's what I came up with:
class jsonResponse {
var $response;
function jsonResponse() {
$this->response = array('isOK'=>'KO', 'msg'=>'Undefined');
}
function set($isOK, $msg) {
$this->response['isOK'] = ($isOK) ? 'OK' : 'KO';
$this->response['msg'] = htmlentities($msg);
}
function setData($data=null) {
if(!is_null($data))
$this->response['data'] = $data;
elseif(isset($this->response['data']))
unset($this->response['data']);
}
function send() {
header('Content-type: application/json');
echo '{"isOK":"' . $this->response['isOK'] . '","msg":' . $this->parseString($this->response['msg']);
if(isset($this->response['data']))
echo ',"data":' . $this->parseData($this->response['data']);
echo '}';
}
function parseData($data) {
if(is_array($data)) {
$parsed = array();
foreach ($data as $key=>$value)
array_push($parsed, $this->parseString($key) . ':' . $this->parseData($value));
return '{' . implode(',', $parsed) . '}';
}
else
return $this->parseString($data);
}
function parseString($string) {
$string = str_replace("\\", "\\\\", $string);
$string = str_replace('/', "\\/", $string);
$string = str_replace('"', "\\".'"', $string);
$string = str_replace("\b", "\\b", $string);
$string = str_replace("\t", "\\t", $string);
$string = str_replace("\n", "\\n", $string);
$string = str_replace("\f", "\\f", $string);
$string = str_replace("\r", "\\r", $string);
$string = str_replace("\u", "\\u", $string);
return '"'.$string.'"';
}
}
I followed the rules mentioned here. I only used what I needed, but I figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as I originally thought, but about the / not being escaped. I hope this prevent someone else from the little headache I had figuring out what I did wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "401"
} |
Q: Why does the Bourne shell printf iterate over a %s argument? What's going on here?
printf.sh:
#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" $NAME
Command line session:
$ ./printf.sh
Hello, George
Hello, W.
Hello, Bush
UPDATE: printf "Hello, %s\n" "$NAME" works. For why I'm not using echo, consider
echo.sh:
#! /bin/sh
FILE="C:\tmp"
echo "Filename: $FILE"
Command-line:
$ ./echo.sh
Filename: C: mp
The POSIX spec for echo says, "New applications are encouraged to use printf instead of echo" (for this and other reasons).
A: Your NAME variable is being substituted like this:
printf "Hello, %s\n" George W. Bush
Use this:
#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" "$NAME"
A: is there a specific reason you are using printf or would echo work for you as well?
NAME="George W. Bush"
echo "Hello, "$NAME
results in
Hello, George W. Bush
edit:
The reason it is iterating over "George W. Bush" is because the bourne shell is space delimitted. To keep using printf you have to put $NAME in double quotes
printf "Hello, %s\n" "$NAME"
A: The way I interpret the man page is it considers the string you pass it to be an argument; if your string has spaces it thinks you are passing multiple arguments. I believe ColinYounger is correct by surrounding the variable with quotes, which forces the shell to interpret the string as a single argument.
An alternative might be to let printf expand the variable:
printf "Hello, $NAME."
The links are for bash, but I am pretty sure the same holds for sh.
A: If you want all of those words to be printed out on their own, use print instead of printf
printf takes the formatting specification and applies it to each argument that you pass in. Since you have three arguments {George, W., Bush}, it outputs the string three times using the different arguments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Are you human? (or How to prevent spam) What mechanisms do you know that prevent your site from being abused by anonymous spammers.
For example, let's say that I have a site where people can vote something. But I don't want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work?
A: For a CAPTCHA system, I heartily recommend reCAPTCHA.
Traditional computer-generated CAPTCHAs will eventually be broken by developing a sufficiently intelligent system. For instance, here's someone who claims to break the Google CAPTCHA, formerly considered unbreakable, with a 30% hit rate. reCAPTCHA, by definition, shows you only images that cannot be recognized by optical character recognition.
And at the same time, your users' effort will be directed towards the common good - they help digitize books by recognizing words that cannot be recognized automatically.
See here for further explanation and to try it out.
A:
From Quantum Random Bit Generator Service, via MNeylon
A: *
*Limit the number of votes per IP address per time
*Block anonymizing proxies.
*For voting: How about shuffling the value that has to be returned by the form on a "per session basis". Once "1" means the first item, "2" means the second. Then "77" means the first item, "812" means the second, ... could be some simple maths behind the scene, but it prevents users from just sending the same HTTP query over and over again.
*What's worked for me very well: Use AJAX forms, not simple HTTP forms. Technically it's not much more complicated to fake votes, but I have written a simple blog software and it's only SPAM protection mechanism is to submit the comments via AJAX - no SPAM so far.
A: I'm a fan of the "hidden field" CAPTCHA. I don't remember where I read about it, but the idea is this:
*
*create your form as normal
*add an extra field but hide it (i.e. style="display:none" on the surrounding div or table row)
*after submission, if the field is blank, do the appropriate action (eg send an email); if the field has been filled in, then it's a robot submitter
The only case where this falls down is if the user's browser doesn't handle CSS (or they have it switched off), which is very rare.
A: Charge for votes, like they do on some television "talent" shows, and get spammed all the way to the bank!
Seriously, this is a really tough problem, and someday (maybe soon, if you listen to Ray Kurzweil), computers will do testing to screen out humans. The answers I'm adding to the list have obvious drawbacks, but just for the sake of enumeration: moderation (have humans do the testing), and IP-based tracking (limit the number of votes from a host).
A:
From xkcd
A: The big thing I've noticed is that whatever you do, you want your system to be unique. You want an attacker to have to tailor their automation program for your specific site, rather than just throw a pre-existing script at it that will work almost anywhere. It doesn't even have to be cryptographically secure; it just has to make your site a little different from the norm.
This doesn't mean you can't or shouldn't use something like a pre-built captcha widget. Absolutely do use one of those as a staring point! It just means you have to customize it somewhere so that something extra happens that is outside the norm and will break any pre-existing script that could normally defeat it.
If your site gets big enough that you have attackers targeting it specifically, then your simple little customization probably won't hold up anymore and you might have do something a little more special and think about real cryptography and all that. But that's one of those things that's a "good" problem to have.
A: stackoverflow has a few features that help with this; I think the single most useful step you can take is disabling the ability of anonymous users and new accounts to vote. This way, no one can sign up for hundreds of accounts and use their one vote to overpower other users. I'd say requiring a few posts or membership for a certain period of time are both decent options.
Some would say you could allow one vote per IP address to help address this, but I've played plenty of games where malicious users with a nigh-infinite number of proxies defied IP address-based security. It's a deterrent, but a savvy user will get around it easily.
A: This is the study area of Human Computation.
there is an excellent video from Luis von Ahn here:
http://video.google.com/videoplay?docid=-8246463980976635143
A: There's a few ideas in the answers to the Best non-image based CAPTCHA? question if you haven't seen it already.
A: I normally use a combination of the two: anonmous user is free to browse everything, but if he wants to vote, then he has to register.
In the registration process, depending on the situation, I use an optin thru mail (to complete registration and confirm that at least the mailbox exists) and/or a CAPTCHA.
From that point on you can decide if the user can vonte more than once, or any other rule.
Btw I'm not a fan of the IP-based constraints: there are a lot of situation in which big organization's network use few IP for all their users, so the risk to block users that could vote is high.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Pure Python library to generate Identicons? Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck.
A: I've found two implementations:
http://coderepos.org/share/browser/lang/python/misc/identicon.py
http://code.google.com/p/visicon/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Using different classloaders for different JUnit tests? I have a Singleton/Factory object that I'd like to write a JUnit test for. The Factory method decides which implementing class to instantiate based upon a classname in a properties file on the classpath. If no properties file is found, or the properties file does not contain the classname key, then the class will instantiate a default implementing class.
Since the factory keeps a static instance of the Singleton to use once it has been instantiated, to be able to test the "failover" logic in the Factory method I would need to run each test method in a different classloader.
Is there any way with JUnit (or with another unit testing package) to do this?
edit: here is some of the Factory code that is in use:
private static MyClass myClassImpl = instantiateMyClass();
private static MyClass instantiateMyClass() {
MyClass newMyClass = null;
String className = null;
try {
Properties props = getProperties();
className = props.getProperty(PROPERTY_CLASSNAME_KEY);
if (className == null) {
log.warn("instantiateMyClass: Property [" + PROPERTY_CLASSNAME_KEY
+ "] not found in properties, using default MyClass class [" + DEFAULT_CLASSNAME + "]");
className = DEFAULT_CLASSNAME;
}
Class MyClassClass = Class.forName(className);
Object MyClassObj = MyClassClass.newInstance();
if (MyClassObj instanceof MyClass) {
newMyClass = (MyClass) MyClassObj;
}
}
catch (...) {
...
}
return newMyClass;
}
private static Properties getProperties() throws IOException {
Properties props = new Properties();
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
if (stream != null) {
props.load(stream);
}
else {
log.error("getProperties: could not load properties file [" + PROPERTIES_FILENAME + "] from classpath, file not found");
}
return props;
}
A: This question might be old but since this was the nearest answer I found when I had this problem I though I'd describe my solution.
Using JUnit 4
Split your tests up so that there is one test method per class (this solution only changes classloaders between classes, not between methods as the parent runner gathers all the methods once per class)
Add the @RunWith(SeparateClassloaderTestRunner.class) annotation to your test classes.
Create the SeparateClassloaderTestRunner to look like this:
public class SeparateClassloaderTestRunner extends BlockJUnit4ClassRunner {
public SeparateClassloaderTestRunner(Class<?> clazz) throws InitializationError {
super(getFromTestClassloader(clazz));
}
private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError {
try {
ClassLoader testClassLoader = new TestClassLoader();
return Class.forName(clazz.getName(), true, testClassLoader);
} catch (ClassNotFoundException e) {
throw new InitializationError(e);
}
}
public static class TestClassLoader extends URLClassLoader {
public TestClassLoader() {
super(((URLClassLoader)getSystemClassLoader()).getURLs());
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.mypackages.")) {
return super.findClass(name);
}
return super.loadClass(name);
}
}
}
Note I had to do this to test code running in a legacy framework which I couldn't change. Given the choice I'd reduce the use of statics and/or put test hooks in to allow the system to be reset. It may not be pretty but it allows me to test an awful lot of code that would be difficult otherwise.
Also this solution breaks anything else that relies on classloading tricks such as Mockito.
A: When I run into these sort of situations I prefer to use what is a bit of a hack. I might instead expose a protected method such as reinitialize(), then invoke this from the test to effectively set the factory back to its initial state. This method only exists for the test cases, and I document it as such.
It is a bit of a hack, but it's a lot easier than other options and you won't need a 3rd party lib to do it (though if you prefer a cleaner solution, there probably are some kind of 3rd party tools out there you could use).
A: You can use Reflection to set myClassImpl by calling instantiateMyClass() again. Take a look at this answer to see example patterns for playing around with private methods and variables.
A: If executing Junit via the Ant task you can set fork=true to execute every class of tests in it's own JVM. Also put each test method in its own class and they will each load and initialise their own version of MyClass. It's extreme but very effective.
A: Below you can find a sample that does not need a separate JUnit test runner and works also with classloading tricks such as Mockito.
package com.mycompany.app;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.net.URLClassLoader;
import org.junit.Test;
public class ApplicationInSeparateClassLoaderTest {
@Test
public void testApplicationInSeparateClassLoader1() throws Exception {
testApplicationInSeparateClassLoader();
}
@Test
public void testApplicationInSeparateClassLoader2() throws Exception {
testApplicationInSeparateClassLoader();
}
private void testApplicationInSeparateClassLoader() throws Exception {
//run application code in separate class loader in order to isolate static state between test runs
Runnable runnable = mock(Runnable.class);
//set up your mock object expectations here, if needed
InterfaceToApplicationDependentCode tester = makeCodeToRunInSeparateClassLoader(
"com.mycompany.app", InterfaceToApplicationDependentCode.class, CodeToRunInApplicationClassLoader.class);
//if you want to try the code without class loader isolation, comment out above line and comment in the line below
//CodeToRunInApplicationClassLoader tester = new CodeToRunInApplicationClassLoaderImpl();
tester.testTheCode(runnable);
verify(runnable).run();
assertEquals("should be one invocation!", 1, tester.getNumOfInvocations());
}
/**
* Create a new class loader for loading application-dependent code and return an instance of that.
*/
@SuppressWarnings("unchecked")
private <I, T> I makeCodeToRunInSeparateClassLoader(
String packageName, Class<I> testCodeInterfaceClass, Class<T> testCodeImplClass) throws Exception {
TestApplicationClassLoader cl = new TestApplicationClassLoader(
packageName, getClass(), testCodeInterfaceClass);
Class<?> testerClass = cl.loadClass(testCodeImplClass.getName());
return (I) testerClass.newInstance();
}
/**
* Bridge interface, implemented by code that should be run in application class loader.
* This interface is loaded by the same class loader as the unit test class, so
* we can call the application-dependent code without need for reflection.
*/
public static interface InterfaceToApplicationDependentCode {
void testTheCode(Runnable run);
int getNumOfInvocations();
}
/**
* Test-specific code to call application-dependent code. This class is loaded by
* the same class loader as the application code.
*/
public static class CodeToRunInApplicationClassLoader implements InterfaceToApplicationDependentCode {
private static int numOfInvocations = 0;
@Override
public void testTheCode(Runnable runnable) {
numOfInvocations++;
runnable.run();
}
@Override
public int getNumOfInvocations() {
return numOfInvocations;
}
}
/**
* Loads application classes in separate class loader from test classes.
*/
private static class TestApplicationClassLoader extends URLClassLoader {
private final String appPackage;
private final String mainTestClassName;
private final String[] testSupportClassNames;
public TestApplicationClassLoader(String appPackage, Class<?> mainTestClass, Class<?>... testSupportClasses) {
super(((URLClassLoader) getSystemClassLoader()).getURLs());
this.appPackage = appPackage;
this.mainTestClassName = mainTestClass.getName();
this.testSupportClassNames = convertClassesToStrings(testSupportClasses);
}
private String[] convertClassesToStrings(Class<?>[] classes) {
String[] results = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
results[i] = classes[i].getName();
}
return results;
}
@Override
public Class<?> loadClass(String className) throws ClassNotFoundException {
if (isApplicationClass(className)) {
//look for class only in local class loader
return super.findClass(className);
}
//look for class in parent class loader first and only then in local class loader
return super.loadClass(className);
}
private boolean isApplicationClass(String className) {
if (mainTestClassName.equals(className)) {
return false;
}
for (int i = 0; i < testSupportClassNames.length; i++) {
if (testSupportClassNames[i].equals(className)) {
return false;
}
}
return className.startsWith(appPackage);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: App.config connection string Protection error I am running into an issue I had before; can't find my reference on how to solve it.
Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below:
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
If config.ConnectionStrings.SectionInformation.IsProtected = False Then
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.'
config.Save(ConfigurationSaveMode.Modified, True)
End If
The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is:
Unhandled Exception: System.Configuration.ConfigurationErrorsException:
An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'.
Error message from the provider: Object already exists.
---> System.Security.Cryptography.CryptographicException: Object already exists
A: http://blogs.msdn.com/mosharaf/archive/2005/11/17/protectedConfiguration.aspx#1657603
copy and paste :D
Monday, February 12, 2007 12:15 AM by Naica
re: Encrypting configuration files using protected configuration
Here is a list of all steps I've done to encrypt two sections on my PC and then deploy it to the WebServer. Maybe it will help someone...:
*
*To create a machine-level RSA key container
aspnet_regiis -pc "DataProtectionConfigurationProviderKeys" -exp
*Add this to web.config before connectionStrings section:
<add name="DataProtectionConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
keyContainerName="DataProtectionConfigurationProviderKeys"
useMachineContainer="true" />
Do not miss the <clear /> from above! Important when playing with encrypting/decrypting many times
*Check to have this at the top of Web.Config file. If missing add it:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
*Save and close Web.Config file in VS (very important!)
*In Command Prompt (my local PC) window go to:
C:\WINNT\Microsoft.NET\Framework\v2.0.50727
*Encrypt: (Be aware to Change physical path for your App, or use -app option and give the name o virtual directory for app! Because I used VS on my PC I preferred the bellow option. The path is the path to Web.config file)
aspnet_regiis -pef "connectionStrings" "c:\Bla\Bla\Bla" -prov "DataProtectionConfigurationProvider"
aspnet_regiis -pef "system.web/membership" "c:\Bla\Bla\Bla" -prov "DataProtectionConfigurationProvider"
*To Decrypt (if needed only!):
aspnet_regiis -pdf "connectionStrings" "c:\Bla\Bla\Bla"
aspnet_regiis -pdf "system.web/membership" "c:\Bla\Bla\Bla"
*Delete Keys Container (if needed only!)
aspnet_regiis -pz "DataProtectionConfigurationProviderKeys"
*Save the above key to xml file in order to export it from your local PC to the WebServer (UAT or Production)
aspnet_regiis -px "DataProtectionConfigurationProviderKeys" \temp\mykeyfile.xml -pri
*Import the key container on WebServer servers:
aspnet_regiis -pi "DataProtectionConfigurationProviderKeys" \temp\mykeyfile.xml
*Grant access to the key on the web server
aspnet_regiis -pa "DataProtectionConfigurationProviderKeys" "DOMAIN\User"
See in IIS the ASP.NET user or use:
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name
*Remove Grant access to the key on the web server (Only if required!)
aspnet_regiis -pr "DataProtectionConfigurationProviderKeys" "Domain\User"
*Copy and Paste to WebServer the encrypted Web.config file.
A: So I did get it working.
*
*removed old users account from laptop
*reset app.config to have section not protected
*removed key file from all users machine keys
*ran app and allowed it to protect the section
But all this did was get it working for this user.
NOW I need to know what I have to do to change the code to protect the section so that multiple users on a PC can use the application. Virtual PC here I come (well after vacation to WDW tomorrow through next Wednesday)!
any advice to help pointing me in right direction, as I am not very experienced in this RSA encryption type stuff.
A: I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the .net framework directory in a commadn prompt and run
aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}"
it gave the other user permission to access the RSA encryption key container and it then works for the other user(s).
Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well.
A: Sounds like a permissions issue. The (new) user in question has write permissions to the app.config file? Was the previous user a local admin or power user that could have masked this problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Easy .NET XML Library Following my question regarding a .NET YAML Library... as there doesn't seem to be great support for YAML in .NET, are there and good open source really simple .NET XML libraries. I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys.
Also, preferably something with a license that allows it to be used commercially.
A: isn't the system.xml namespace suficient?
once i had to use it for the simple scenarios that you described and thought that it was a simple and efficient solutions.
take a look at this examples
Reading Node Trees with XmlNodeReader
and the XML Document Object Model (DOM) Reference
A: Can you use the 3.5 framework? Linq to XML is fantastic, and simple.
A: Is XSLT / XPath out of the question? If so, have you considered JSON.Net?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Warning/error "function declaration isn't a prototype" I have a library I created,
File mylib.c:
#include <mylib.h>
int
testlib() {
printf("Hello, World!\n");
return (0);
}
File mylib.h:
#include <stdio.h>
extern int testlib();
In my program, I've attempted to call this library function:
File myprogram.c:
#include <mylib.h>
int
main (int argc, char *argv[]) {
testlib();
return (0);
}
When I attempt to compile this program I get the following error:
In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype
I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)
What is the proper way to declare a function prototype?
A: Quick answer: change int testlib() to int testlib(void) to specify that the function takes no arguments.
A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).
A non-prototype function declaration like
int foo();
is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.
For a function that takes one or more arguments, you can specify the type of each argument in the declaration:
int bar(int x, double y);
Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that a function takes no arguments, but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void keyword:
int foo(void); /* foo takes no arguments */
A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:
int testlib()
{
/* code that implements testlib */
}
This provides a non-prototype declaration for testlib. As a definition, this tells the compiler that testlib has no parameters, but as a declaration, it only tells the compiler that testlib takes some unspecified but fixed number and type(s) of arguments.
If you change () to (void) the declaration becomes a prototype.
The advantage of a prototype is that if you accidentally call testlib with one or more arguments, the compiler will diagnose the error.
(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void) syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the () in C++ and the (void) syntax in C.)
A: In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.
If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.
I suggest removing the extern, it is extraneous and is usually omitted.
A: Try:
extern int testlib(void);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "191"
} |
Q: C++ Compiler Error C2371 - Redefinition of WCHAR I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS.
C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430) :
error C2371: 'WCHAR' : redefinition; different basic types 1>
C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winnt.h(289) :
see declaration of 'WCHAR'
I don't see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this?
A: This is a known bug - see the Microsoft Connect website:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98699
The error doesn't occur if you compile your app as Unicode instead of MBCS.
A: There are a half-dozen posts on various forums around the web about this - it seems to potentially be an issue when odbcss.h is used in the presence of MFC. Most of the answers involve changing the order of included headers (voodoo debugging). The header that includes odbcss.h compiles fine in it's native project, but when it is included in a different project, it gives this error. We even put it in the latter project's stdafx.h, right after the base include for MFC, and still no joy. We finally worked around it by moving it into a cpp file in the original project, which does not use MFC (which should have been done anyway - but it wasn't our code). So we've got a work-around, but no real solution.
A: This error happens when you redeclare a variable of the same name as a variable that has already been declared. Have you looked to see if odbcss.h has declared a variable you already have?
A: does this help?
http://bytes.com/forum/thread602063.html
Content from the thread:
Bruno van Dooren [MVP VC++] but i know the solution of this problem.
it solves by changing project setting of "Treat wchar_t as Built-in
Type" value "No (/Zc:wchar_t-)". But I am using "Xtreme Toolkit
Professional Edition" for making good look & Feel of an application,
when i fix the above problem by changing project settings a new
linking errors come from Xtreme Toolkit Library. So what i do to fix
this problem, in project setting "Treat wchar_t as Built-in Type"
value "yes" and i wrote following statements where i included wab.h
header file. You can change that setting on a per-codefile basis so
that only specific files are compiled with that particular setting. If
you can solve your problems that way it would be the cleanest
solution.
#define WIN16
#include "wab.h"
#undef WIN16
and after that my project is working fine and all the things related to WAB is also working fine. any one guide me, is that the right way
to solve this problem??? and, will this have any effect on the rest of
project?? I wouldn't worry about it. whatever the definition, it is a
16 bit variable in both cases. I agree that it isn't the best looking
solution, but it should work IF WIN16 has no other impact inside the
wab.h file.
--
Kind regards, Bruno van Dooren [email protected]
Remove only "_nos_pam"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does Google Chrome control/contain multiple processes? How does Google Chrome command and control multiple cross platform processes and provide a shared window / rendering area?
Any insights?
A: There is a document called Multi-process Architecture on the Chromium developer site. It might be a good starting place.
A: The source code is online here ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What are the best ways to determine what port an application is using? This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field.
Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.
A: I've always liked the sysinternals app TCPView, which can now be found here. Good luck.
A: netstat -b is a great answer, you may need to use the -a option as well.
Without -a netstat shows active connections, with -a it shows listening ports with no active clients as well.
A: Download currports from here.
It will show you which ports are open and which processes are associated with each port.
Scroll down to:
Download CurrPorts
A: netstat -b
from the command line will display the application name, process owner, address, and port number used for all running applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How can I unit test a Windows Service? .NET Framework: 2.0
Preferred Language: C#
I am new to TDD (Test Driven Development).
First of all, is it even possible to unit test Windows Service?
Windows service class is derived from ServiceBase, which has overridable methods,
*
*OnStart
*OnStop
How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?
At this point, am I even doing a Unit testing? or an Integration test?
I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.
A: I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service.
In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.
A: I would use the windows service class (the one you run when you start/stop the service) sort of like a proxy to your real system. I don't see how the code behind your service should be any different from any other programming. The onStart and onStop methods are simply events being fired, like pushing a button on a GUI.
So your windows service class is a very thin class, comparable to a windows form. It calls your business logic/domain logic, which then does what it's supposed to do. All you have to do is make sure the method(s) you're calling in your onStart and onStop are working like they're supposed to. At least that's what I would do ;-)
A: I have unit tested windows services by not testing the service directly, but rather testing what the service does.
Typically I create one assembly for the service and another for what the service does. Then I write unit tests against the second assembly.
The nice thing about this approach is that your service is very thin. Basically all it does is call methods to do the right work at the right time. Your other assembly contains all the meat of the work your service intends to do. This makes it very easy to test and easy to reuse or modify as needed.
A: Designing for test is a good strategy, as many of the answers point out by recommending that your OnStart and OnStop methods stay very thin by delegating to domain objects.
However, if your tests do need to execute the service methods for some reason, you can use code like this to call them from within a test method (calling OnStart in this example):
serviceInstance.GetType().InvokeMember("OnStart", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, serviceInstance, new object[] {new string[] {}});
A: I would start here. It shows how to start and stop services in C#
A sample to start is is
public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
I have also tested services mostly through console app, simulating what the service would do. That way my unit test is completely automated.
A: Test Window service in automatic power off, shut down conditions
Test window service when network disconnected, connected
Test window service option autostart, manual etc
A: Guy's probably the best answer.
Anyway, if you really want to, you could just invoke in the unit test these two method as described by MSDN documentation but, since they are protected, you'll need to use Reflection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
} |
Q: Java: JApplet, How do you embed it in a webpage? I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead.
How do you embed a JApplet in HTML on a webpage?
A: Here is an example from sun's website:
<applet code="TumbleItem.class"
codebase="examples/"
archive="tumbleClasses.jar, tumbleImages.jar"
width="600" height="95">
<param name="maxwidth" value="120">
<param name="nimgs" value="17">
<param name="offset" value="-57">
<param name="img" value="images/tumble">
Your browser is completely ignoring the <APPLET> tag!
</applet>
A: Although you didn't say so, just in case you were using JSPs, you also have the option of the jsp:plugin tag?
A: Use the <applet> tag. For more info: http://java.sun.com/docs/books/tutorial/deployment/applet/html.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: If you were programming a calendar in HTML would you use Table tags or Div tags? I converted my company's calendar to XSL and changed all the tables to divs. It worked pretty well, but I had a lot of 8 day week bugs to work out initially owing to precarious cross-browser spacing issues. But I was reading another post regarding when to use tables v. divs and the consensus seemed to be that you should only use divs for true divisions between parts of the webpage, and only use tables for tabular data.
I'm not sure I could even have used tables with XSL but I wanted to follow up that discussion of Divs and Tables with a discussion of the ideal way to make a web calendars and maybe a union of the two.
A: I would say that a calendar is a table, therefore making the table the proper markup for its representation.
Edit: Definition 11 for "table" from answers.com says:
An orderly arrangement of data, especially one in which the data are arranged in columns and rows in an essentially rectangular form.
A: A calendar is the perfect reason to use a table! Calendars inherently present tabular data and HTML tables are good at presenting tabular data. And HTML table markup provides nearly all the CSS hooks you need to associate CSS selectors with various parts of the table to dress it up.
I'm all for using DIVs for layout--but stick with tables for tabular data.
Here is a cool article on how to dress up tables with CSS:
http://www.smashingmagazine.com/2008/08/13/top-10-css-table-designs
A: I think this is definitely a case for using tables. The biggest issue when using divs would be box height for each individual day. If you're styling each box with a border, they could look off if the content for one day is longer than another. The additional markup to make it look right would be more than it would take to create it with a table, so I don't think divs are worth the extra effort in this case.
A: Tables are for displaying tabular data. So I would say <table> is ideal.
A: It makes sense to use tables, but if you were to look at Google Calender, they seem to be using div tags. It is possible that using div tags lowers the file size, so in an enterprise environment it might be worth the 'trouble'.
A: Do it up in a table.
Also don't think of it as "divs vs. tables" Think of it as tables vs. a proper semantic tag with meaning. When I author pages I try to use divs as little as possible, in a lot of cases you could be using a paragraph, a list item, etc.
A: You might also consider an ordered list (weeks) of ordered lists (days), or simply one ordered list (days).
There are others who agree that the list approach is a good one.
Others prefer tables.
A: Just came across this thread after posing the same question elsewhere. While I completely agree a calendar is more of a tabular representation of data, I think there's truth in the prolific "it depends" answers. For example, I want to show a floating DIV popup when each day in the calendar is moused over. Using a table, the popup flickers as the cursor moves across the calendar since the popup is only active on the cell border and the day number in the cell itself. Using DIVs, the popup is solid (no flicker) the entire time the cursor mouses over the calendar cell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How to copy the contents of an FTP directory to a shared network path? I have the need to copy the entire contents of a directory on a FTP location onto a shared networked location. FTP Task has you specify the exact file name (not a directory) and File System Task does not allow accessing a FTP location.
EDIT: I ended up writing a script task.
A: Nothing like reviving a really old thread... but there is a solution to this.
To copy the all files from a directory then specify your remote path to be /[directory name]/*
Or for just files and not directories /[directory name]/.
Or specific file types; /[directory name]/*.csv
A: When I need to do this sort of thing I use a batch file to call FTP on the command line and use the mget command. Then I call the batch from the DTS/DTSX package.
A: I've had some similar issues with the FTP task before. In my case, the file names changed based on the date and some other criteria. I ended up using a Script Task to perform the FTP operation.
It looks like this is what you ended up doing as well. I'd be curious if anyone else can come up with a better way to use the FTP task. It's nice to have...but VERY limited.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to escape < and > inside tags I'm trying to write a blog post which includes a code segment inside a <pre> tag. The code segment includes a generic type and uses <> to define that type. This is what the segment looks like:
<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
The resulting HTML removes the <> and ends up like this:
PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;
How do I escape the <> so they show up in the HTML?
A: < and > respectively
A: How about:
< and >
Hope this helps?
A: What rp said, just replace the greater-than(>) and less-than(<) symbols with their html entity equivalent. Here's an example:
<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
This should appear as (this time using exactly the same without the prepended spaces for markdown):
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
A: <pre>></pre>
renders as:
>
So you want:
<pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
which turns out like:
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
A: Use < and > to do < and > inside html.
A: <pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
A: A better way to do is not to have to worry about the character codes at all. Just wrap all your code inside the <pre> tags with the following
<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>
You'll need to have jQuery enabled for it to work, tho.
A: It's probably something specific to your blog software, but you might want to give the following strings a try (remove the underscore character):
&_lt; &_gt;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: How are partial methods used in C# 3.0? I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
A: Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.
A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.
The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.
The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.
*
*In .Net 1 it was auto-generated code in a #region block
*In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer
This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.
In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.
The extra bit here is that code needed to provide methods that developers might want to fill in.
As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.
The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.
Empty methods are not optimised out.
So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.
So that it can do this partial methods always return void.
If you create a new Linq DBML file it will auto-generate a partial class, something like
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);
...
Then in your own partial file you can extend this:
public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}
If you don't extend these methods they get optimised right out.
Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.
The example I mentioned before is one possibility:
//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();
#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif
Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
A: Code generation is one of main reasons they exist and one of the main reasons to use them.
EDIT: Even though that link is to information specific to Visual Basic, the same basic principles are relevant to C#.
A: I see them as lightweight events. You can have a reusable code file (usually autogenerated but not necessarily) and for each implementation, just handle the events you care about in your partial class. In fact, this is how it's used in LINQ to SQL (and why the language feature was invented).
A: Partial methods are very similar in concept to the GoF Template Method behavioural pattern (Design Patterns, p325).
They allow the behaviour of an algorithm or operation to be defined in one place and implemented or changed elsewhere enabling extensibility and customisation. I've started to use partial methods in C# 3.0 instead of template methods because the I think the code is cleaner.
One nice feature is that unimplemented partial methods incur no runtime overhead as they're compiled away.
A: Here is the best resource for partial classes in C#.NET 3.0: http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx
I try to avoid using partial classes (with the exception of partials created by Visual Studio for designer files; those are great). To me, it's more important to have all of the code for a class in one place. If your class is well designed and represents one thing (single responsibility principle), then all of the code for that one thing should be in one place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How do I determine which process is using a serial port? The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware.
There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one.
Is there any way to either:
*
*Find the name/pid of the app/service that is currently using a given serial port or
*Steal the serial port connection from another app.
vb.net preferably, but I'll take a language agnostic answer as well.
A: Sysinternals has a slew of utilities I find very useful and educational for tracking down what processes are doing to the system.
They have a utility that does exactly what you need called Portmon, and give some information on how it works near the bottom of the page. That info and a few well-asked questions will probably give you everything you need to implement it yourself if the utility isn't enough.
-Adam
A: You can use the process explorer tool also from SysInternals to search for open handles. In this case you would want to search for 'Serial' since it uses device names that may not map to com port numbers. (e.g. COM1 is \Device\Serial0 on my system).
If you want to take control of the serial port from another app I think you would need co-operation of the driver.
A: As Rob Walker said, you can find who's using a serial port using Process Explorer. Most of the time, typing Ctrl+F and searching for "serial" will show you who has a serial port open, but I just ran into a situation where my "COM3" serial port's handle appeared as "\Device\VCP0". It may be strange because it was running under VirtualBox with a USB-to-serial connector.
If searching for "serial" and "device\vcp" don't get you any results, you may be able to figure out how serial port handles are named by opening one with a known program. In Process Explorer, display the lower pane with each process's open handles by typing Ctrl+L. Click on the process that you used to open the serial port and look through the lower pane to see which handles look like they might be a serial port. You can open and close the port while you're looking, and the file handle should appear and disappear, as well as being highlighted in green or red. Of course, this is only possible if you have more than one serial port or the serial port you're trying to diagnose isn't always locked by some mystery process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Managing LINQ to SQL .dbml model complexity This question is addressed to a degree in this question on LINQ to SQL .dbml best practices, but I am not sure how to add to a question.
One of our applications uses LINQ to SQL and we have currently have one .dbml file for the entire database which is becoming difficult to manage. We are looking at refactoring it a bit into separate files that are more module/functionality specific, but one problem is that many of the high level classes would have to be duplicated in several .dbml files as the associations can't be used across .dbml files (as far as I know), with the additional partial class code as well.
Has anyone grappled with this problem and what recommendations would you make?
A: Take advantage of the namespace settings. You can get to it in properties from clicking in the white space of the ORM.
This allows me to have a Users table and a User class for one set of business rules and a second (but the same data store) Users table and a User class for another set of business rules.
Or, break up the library, which should also have the affect of changing the namespacing depending on your company's naming conventions. I've never worked on an enterprise app where I needed access to every single table.
A: Past a certain size it probably becomes easier to work with the xml instead of the dbml designer.
A: I have written a tool too! Mine is for scripting changes to dbml files using c# so you can rerun them and not lose changes. See my blog http://www.adverseconditionals.com 4 more details
A: The approach that we've used it to keep 2 .dbml files. One of them holds the Stored Procs and all production DB access is done through this. The other is in a unit test folder and holds tables and their relationships and is used for DB data manipulation and querying for unit tests.
A: I have written a utility to address exactly that problem, I needed a quick app to let you select only the database objects you need. In my case I often needed a complex view, but no tables.
http://www.codeplex.com/SqlMetalInclude/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: SQL Number Formatting I'm looking to use SQL to format a number with commas in the thousands, but no decimal (so can't use Money) - any suggestions?
I'm using SQL Server 2005, but feel free to answer for others as well (like MySQL)
A: With TSQL you could cast to money and convert it will add the .00, but you could use replace or substring to remove.
replace(convert(varchar, cast(column as money), 1), '.00', '')
In SQL 2005 you could use a CLR function as well
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString FormatNumber(SqlInt32 number)
{
return number.Value.ToString("N0");
}
and call it as any other user-defined function
SELECT dbo.FormatNumber(value)
A: In MySQL, the FORMAT() function will do the trick.
A: In Oracle you can specify a format parameter to the to_char function:
TO_CHAR(1234, '9,999') --> 1,234
A: Any specific reason you want this done on the server side? Seems like it is a task better suited for the client/report.
Otherwise, you are storing a number as a string just so you can keep the formatting how you want it -- but you just lost the ability to do even basic arithmetic on it without having to reconvert it to a number.
If you're really determined to do it in SQL and have a justifiable reason for it, I guess my vote is on Scott's method: Value --> Money --> Varchar --> Trim off the decimal portion
-- Kevin Fairchild
A: For SQL Server, you could format the number as money and then delete the right-most three characters.
replace(convert (varchar, convert (money, 109999), 1), '.00','')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where did these hex named folders come from? First off, I am using Windows XP. I have multiple hard drives and it looks like something decided to make some folders on the second one ( which is just a data drive, no os ). These folders all have names like "e69f29f1b1f166d3d30b8c9f7156ba" and "bd92c24cc278614082cd88e7a64b". They contain folders named update, whose "access is denied", so my best guess would be they are Windows updates. So I probably can't get rid of them but could someone at least explain what they are and why they are on the wrong drive?
A: Windows will always use the hard drive with the most space to download windows updates. This is what happened to you.
http://computershopper.com/forums/showthread.php?t=265
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How can I use Linq with a MySql database on Mono? There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono?
Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a Pentium 3 450Mhz, Linux + Mono. I want to rewrite it using Linq (.Net 3.5) mostly as an exercise (I have not yet used Linq).
A: The only (free) linq provider for MySql is DbLinq, and I believe it is a long way from production-ready.
There is also MyDirect.Net which is commercial, but I have heard mixed reviews of it's capability.
I've read that MySql will be implementing the Linq to Entities API for the 5.3 version of the .net connector, but I don't know if there's even a timeline for that. In fact, MySql has been totally silent about Entity Framework support for months.
Addendum: The latest release of the MySql Connector/Net 6.0 has support for the EF according to the release notes. I have no idea how stable/useful this is, so I'd love to hear from anybody who have tried it.
A: According to the Mono roadmap I'm not sure if Linq is available for mono?
At least some of Linq might be available in the very latest release, but Linq to DB is listed for Mono 2.4 (Feb 2009)
A: Not sure about Mono, but I just started using LightSpeed and that supports LINQ-to-MySQL.
A: at this time you cannot use linq to sql, you might look into a third party linq mysql provider or linq to entities. linq to sql only works for sql server databases.
A: LINQ to SQL is simply a ORM layer leveraging the power of expressions to make it easy to construct queries in your code.
If you are just calling adhoc queries for your tool, there is little need to use LINQ, it just adds an extra layer of abstraction to your code.
A: I have tried the tutorial at http://www.primaryobjects.com/CMS/Article100.aspx. This uses dblinq/dbmetal to generate the data context class and classes for each table.
The code failed at the first attempt with an unhandled exception (MySql.Data.Types.MySqlConversionException: Unable to convert MySQL date/time value to System.DateTime"). Googling revealed this should be easily solved by appending "Allow Zero Datetime=True;" to the connection string.
Unfortionately this turned out not to solve my problem. Thinking the MySQL .Net Connector was to blame I executed the SQL generated by dblinq without the linq2sql intermediary layer using the MySQL Connector. This time no exception occured.
Tables which do not have a date column did work with DbLinq.
So, from my experiment I agree with Adam, DbLinq is a long way from production ready.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.