text
stringlengths
8
267k
meta
dict
Q: Using emacs tramp vs. rsync for remote development I have been doing some remote development using emacs tramp and found that it was quite slow. Every time I save a file, it takes about 10 seconds to complete the save. So, now I am using rsync to transfer the files remotely and it works much faster, it takes about a second plus the local saves from emacs are instant. Are there any configuration options within tramp to get it to run as fast as rsync does on the command line? Are there any advantages to using tramp instead of rsync even though I am seeing such poor performance? A: If you're using tramp for ssh/scp functionality, you'll find opening a persistent SSH connection will make tramp operations a lot faster: they'll reuse the existing connection rather than creating a fresh one each time, cutting out a great deal of cryptographic overhead without affecting security. See this article on the SSH ControlMaster functionality. A: A couple of answers have mentioned enabling ControlMaster to keep a persistent ssh connection open (which avoids the expensive connection set-up / hand-shaking otherwise needed for each Tramp operation over ssh), but you don't need to configure anything outside of Emacs to use this -- if you look at the tramp-methods variable you will see there are existing methods which enable ControlMaster. Specifically, the rsyncc and scpc methods. Both sides of the connection need to support ControlMaster, of course (for instance Cygwin cannot do so, which is a shame for Windows users*), but I would suggest setting one of those as your tramp-default-method. Not having a persistent connection makes extended Tramp usage pretty painful, but with one it's incredibly usable (to the point where, given a reasonably fast connection, you can almost forget that it's happening). In answer to the final part of your question, yes, there are very good reasons to use Tramp instead of rsyncing the files manually. The primary one is that shell commands can be executed directly on the remote server, and you don't even have to think about it, as Emacs takes care of the details. For instance, from a remote-file buffer, M-x shell RET opens a shell on the remote server, and commands like M-x rgrep RET and M-x find-grep-dired RET will run the find + grep on the remote server. I believe that this applies in general to functions which invoke shell commands. For me, that's more than enough reason to use Tramp (unless installing Emacs on the remote server and using your local display was an option in which case, for long-term usage, I would consider doing that instead). (*) When using Windows I used to host a Linux VM locally and run Emacs inside that (with Cygwin providing the X display) for the sole reason of using ControlMaster for Tramp ( https://stackoverflow.com/a/3049375/324105 ). A: Are you aware of the section in the tramp documentation on gnu.org that mentions using rsync? It says, in part: 5.3 External transfer methods The external transfer methods operate through multiple channels, using the remote shell connection for many actions while delegating file transfers to an external transfer utility. This saves the overhead of encoding and decoding that multiplexing the transfer through the one connection has with the inline methods. ... rsync — ssh and rsync Using the ssh command to connect securely to the remote machine and the rsync command to transfer files is almost identical to the scp method. While rsync performs much better than scp when transferring files that exist on both hosts, this advantage is lost if the file exists only on one side of the connection. The rsync based method may be considerably faster than the rcp based methods when writing to the remote system. Reading files to the local machine is no faster than with a direct copy. This method supports the ‘-p’ hack. A: While tramp can be configured to use a large number of transport method, I suppose you're using ssh to connect to the remote server. I believe most of the time it takes to complete the operation comes from setting up a connection and authenticating. If you're using a new enough version of OpenSSH, this can be helped by using the connection sharing feature, see ControlMaster in ssh_config(5). I suggest you try ControlMaster auto and see if that improves the situation. A: Since you said earlier that you have a problem on a particular server, check the sshd config file on the problem machine. It's probably something like /etc/ssh/sshd_config. Look for a config option named "UseDNS". Set that to "No." See if that doesn't speed things up for you. If so, then ssh is probably timing out waiting on a reverse dns lookup that you likely don't care about. A: Recently I've come to embrace sshfs so that the remote files are locally editable. Works well for Linux, Mac and Unix systems and puts the ssh parts in one command rather than every access. And exists entirely in User space. A: If you are using the ssh method, you can try the sftp method instead, which (I believe) opens a persistent sftp connection to the remote ssh server. Also, if you are using GNOME, you can add sftp to tramp-gvfs-methods to have TRAMP connect to sftp servers using GNOME's GVFS, which may or may not be faster/more convenient.
{ "language": "en", "url": "https://stackoverflow.com/questions/148578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Has anyone written a thread-safe BindingList? I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own? A: I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a lock: void AddItemToList(object o) { lock(myBindingList) { myBindingList.Add(o); } } Look at the lock statement docs for more info. A: Only just found this post... do you mean like this?
{ "language": "en", "url": "https://stackoverflow.com/questions/148587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .NET Timers: Whats is the best way to be notified in X seconds? Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks. The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed? Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds? A: just use a normal timer and disable it after it has elapsed once. that should solve your problem. both, system.threading.timer and system.timers.timer support this. A: Spin off a new BackgroundWorker, sleep, close. var worker = new BackgroundWorker(); worker.DoWork += delegate { Thread.Sleep(30000); DoStuff(); } worker.RunWorkerAsync(); A: This constructor for the System.Threading.Timer allows you to specify a period. If you set this parameter to -1, it will disable periodic signaling and only execute once. public Timer( TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period ) A: You can use a System.Timers.Timer with AutoReset = true, or a System.Threading.Timer with an infinite period (System.Threading.Timeout.Infinite = -1) to execute a timer once. In either case, you should Dispose your timer when you've finished with it (in the event handler for a Timers.Timer or the callback for a Threading.Timer) if you don't have a recurring interval. A: just set it to tick after X seconds, and in the code of the tick, do: timer.enabled = false; worked for me. A: If you want an accurate time measure, you should consider doubling the timer frequency and using DateTime.Now to compare with your start time. Timers and Thread.Sleep aren't necessarily exact in their time measurements.
{ "language": "en", "url": "https://stackoverflow.com/questions/148594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Accessing constant values from an Apache Velocity template? Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template? I would like to be able to write something like this: #if ($a lt Long.MAX_VALUE) but this is apparently not the right syntax. A: Velocity can only use anything it finds in its context, after e.g. context.put("MaxLong", Long.MAX_VALUE); You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's Property lookup rules). The best thing to do is add the value you want to check against explicitly in your context. Edit October 6 on second sight, it seems to be possible to access static members. See the velocity Developer guide - Support for "Static Classes" for more information. I have not tried this out, though. A: There are a number of ways. 1) You can put the values directly in the context. 2) You can use the FieldMethodizer to make all public static fields in a class available. 3) You can use a custom Uberspect implementation that includes public static fields in the lookup order. 4) You can use the FieldTool from VelocityTools. I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/148601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Migrating MediaWiki Sites over to Windows Sharepoint Services Wiki Had anybody found a way to migrate MediaWiki pages over to WSS Wikis? We just put up Sharepoint 2007 and while it appears to meet our needs, it doesn't appear to be any tool provided by Microsoft to migrate MediaWiki pages over to WSS wikis. A: Create aspx File and add template of wikipage Library page in source and then migrate as Wikipage library of sharepoint 2007 or 2010 A: There is no such tool provided by Microsoft at this time. There is one being developed though in the SharePoint Community Kit. Wiki Import/Export Tool The EWE team is at a very early stage of designing an import/export tool for the SharePoint wiki. The goal is for this tool to be able to import from other wiki products such as FlexWiki, MediaWiki, and TWiki, and Confluence and also from Word and OneNote as well as to export to Word via HTML (per page) and MHTML (entire wiki) formats. For this CKS 2.0 pre-release, the EWE team is making available a fairly stable build of the FlexWiki Import Tool, for which the source code was graciously donated by Michael Cheng, a developer in the SharePoint product group. This is a one-off tool that will ultimately be converted to a plug-in for the Wiki Import/Export Tool, so if you’re currently using FlexWiki, please test the tool and provide feedback. A: I've managed to get Twiki into SharePoint. The biggest problem is programmatically creating the topics/pages inside SharePoint. I've documented my findings here : sites.google.com/site/sharepointwikiuploader Might save some time. A: There is a commercial tool for this: Metalogix Migration Manager for Blogs and Wikis Haven't testes it yet, but will post my experience when I do. A: I created a php script that reads an xml file created by Mediawiki's dumpBackup.php and dumps out text suitable for pasting into new Sharepoint wiki pages. I posted it in a google code project. In combination with Grant Traynor's method this could solve the problem. A: You can't expect even remotely similar functionality from such imported pages. See http://wikiworks.com/enterprise-mediawiki-vs-sharepoint.html for an explanation of why you might want to reconsider this kind of migration. You will lose 1. reliable infinite versioning and archiving 2. easy multi-author editing 3. all the capabilities of mediawiki extensions, over 2000 at last count. In some businesses, e.g. insurance, law firms or accounting, losing 1. could have legal implications. If your intent however is to simply make pages visible in SharePoint that are maintained in MediaWiki, then, you can do that by configuring SharePoint to search within the mediawiki - addressed by some other questions here on StackExchange.
{ "language": "en", "url": "https://stackoverflow.com/questions/148619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to get master-master replication with Subversion? Seems like a simple problem: * *I have an SVN repo inside our firewall. *I have an SVN repo outside our firewall. *I have users inside, and outside, the firewall. (no VPN isn't an option :( that'd be too easy) *machines inside the firewall CAN talk to the outside SVN server. But not the other way. *the outside SVN is a temporary thing - the main repo will always be inside. I want to somehow (from inside, most likely) take all the changes in one, and apply them to the other. And vice versa. Sounds simple, and I assume that the likes GIT can do this, but we are using SVN. Anyone done this? I don't mind it being a manual process - there are only a couple of external people, and they don't need updates to-the-minute, two or three times a day would do. I believe apache.org does this, but I can't find docs on HOW they do this. There are a couple of products out there which do it (well, one), but I'd love to know if anyone has a nice, clean way to do it without them. svnsync does this, just only in one direction (master-slave) Happy to have it run on windows, Linux or Mac, as we have all of them. Windows and Mac preferred though. Help! :) :) [update] after 12 months of messing around (and not needing this in the end), the correct answer is, in my opinion, correct. Use git - have one repo which pulls from SVN-A, then push to a new git repo, then push from there to SVN-B. Should work :) A: I'd recommend SVK or git-svn. Both of these let you create an external mirror of your svn repository, and allow the external devs to make commits directly to the external mirror. You can then pull and push changes from this external mirror to your internal master repo. git-svn would (I think) require the external developers to use git. I prefer it, but I'd be reluctant to push this on others. SVK, however, allows the external developers to continue using svn. Since the internal repo is only accessible internally, an internal account or user would have to handle the periodic syncronization (a cron job would probably work). Here's an extended howto on the SVK wiki: UsingSVKAsARepositoryMirroringSystem A: Simplicity is usually the best way, and it sounds like you already have a simple solution: Use the SVN Repository outside the firewall. You've already said machines inside the firewall can reach it, and obviously machines outside can reach it... so that's everyone, so what justification do you have for a second SVN repository inside the firewall? If it's just as a back-up, then just back-up the one on the outside. Let me know if I'm missing part of your requirements. Another thought... if you have both internal and external SVN instances... what is to stop them both giving out the same changelist ID at the same time, for different purposes? If you're seeking a de-centralised solution you should look towards GIT rather than SVN. A: One of the features of the Enterprise Edition of VisualSVN Server is Multisite Repository Replication that does exactly what you are looking for. The feature is based on VisualSVN Distributed File System (VDFS) technology which was designed to enable transparent Subversion repository replication across geographically distributed sites. Some of the notable features of VDFS: * *All distributed VDFS Subversion repositories are writable, *VDFS enables transparent bidirectional data replication, *VDFS supports replication authorization rules and advanced authentication mechanisms such as Integrated Windows Authentication (NTLM/Negotiate) with secure SSL/TLS encryption. *All VDFS repositories contain the same dataset, *Repository replication over WAN with VDFS is up to x10 faster than replication based on write-through proxy, *VDFS configuration is done via a graphical interface without any complicated steps. It's worth noting that VDFS follows the classic master-slave replication model which has significant advantages over master-master replication model because it's more suitable for replicating Subversion repositories with FSFS fs-type backend. VDFS technology is much more reliable than master-master replication solutions for SVN. * *VisualSVN Server | Multisite Repository Configuration, *Comparing VDFS with master-master replication solutions. A: Hmm...keeping two repos in sync with each other is non-trivial, I think. It would involve basically turning SVN into Mercurial or Git. A: One thing you could try is to replicate the repo at file level. I am using FolderShare (http://www.foldershare.com - runs on Windows and Mac) for a similar scenario, though I am replicating it only for backup purposes and have not tried to connect using SVN to the replica. A: http://wandisco.com/subversion/multisite/ Subversion MultiSite leverages WANdisco's unique replication technology to immediately synchronize Subversion repositories connected over a wide area network (WAN). Users at every location experience local area network (LAN) speed performance for both read and write operations. Subversion MultiSite also provides continuous hot backup and self-healing capabilities that automate disaster recovery, so that downtime is virtually eliminated.
{ "language": "en", "url": "https://stackoverflow.com/questions/148625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Customizing AntRunner output I'm using Eclipse's AntRunner to build a set of plugins, but I'm having trouble in configuring the logging behavior. Specifically, I'd like AntRunner not to display empty tasks. Anybody knows how to do this? A: The solution is to pass the following JVM options: java -jar ... -logger org.apache.tools.ant.NoBannerLogger
{ "language": "en", "url": "https://stackoverflow.com/questions/148641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression to filter files in OpenFileDialog I would like to know how to filter files in a open file dialog (in winforms) based on a regular expression. Files have all same extensions (.xml). Big files are split up into several files with the same name only to be separated with _1 ... We only want to show the files without _1 (first data file) the open file dialog has a property filter but i dont know how to specify this in our filename format, hence the regular expression. Thankx, Niki A: I don't think you can do it with the OpenFileDialog's Filter property, which just filters list of files based on extension. I think you'll have to let the user choose an xml file, validate and then pop up the dialog again if its a _1 file. You can subscribe to the FileOK event and slot in this validation in there. You can use regular expressions to validate the filename here. That's the best that can be done.. I guess. A: The OpenFileDialogEx described in this CodeProject article is an extension of the standard OpenFileDialog. The primary intention of that extension is to modify the display of the dialog, but there are some additional bells and whistles. For example, OFDEx adds a few events, for File changed, Folder change, etc. Someone pointed out that the CDN_INCLUDEITEM notification seems like it would satisfy the desire to filter the list of files shown in the dialog,. It seems like it would, but it does not. The CDN_INCLUDEITEM does not do what you might think or want. According to this MSDN Mag article, If you create your dialog with OFN_ENABLEINCLUDENOTIFY, Windows sends your hook procedure a CDN_INCLUDEITEM notification for every item it adds to the open list. If you return FALSE, Windows excludes the item. The problem is, Windows doesn't notify you for ordinary files, only pseudo-objects like namespace extensions. When you read the documentation through a magnifying glass, the print is perfectly clear: "The dialog box always includes items that have both the SFGAO_FILESYSTEM and SFGAO_FILESYSANCESTOR attributes, regardless of the value returned by CDN_INCLUDEITEM." Apparently the Redmondtonians added CDN_INCLUDEITEM for their own purposes, which didn't include filtering ordinary file names. In other words, in response to CDN_INCLUDEITEM, you cannot return FALSE for regular files, to exclude them from the dialog. In contrast to the doc which says, the response from the CDN_INCLUDEITEM is ignored for regular files, in my experience, the CDN_INCLUDEITEM is not even sent for regular files, at least not on my Vista machine. So is it possible to exclude files dynamically? Well, yes, in C++; In response to the CDN_FOLDERCHANGED message, you can get and set the contents of the CListCtrl that contains the files. I haven't figured out how to set this list in C#. A: The OpenFileDialog does not support this. An alternative is to use a 3rd party control like FileView which lets you filter items using any criteria you wish such as regular expressions. A: You should be able to do it with the following filter: Data Files|*_1.xml A: I'm not sure how to do it in C# with WinForms, but in C++, what you would do is install a custom hook procedure and listen for the CDN_INCLUDEITEM notification. Then, you check each filename against your regex. See http://msdn.microsoft.com/en-us/library/ms646960(VS.85).aspx#_win32_Filters.
{ "language": "en", "url": "https://stackoverflow.com/questions/148642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle: is there a tool to trace queries, like Profiler for sql server? i work with sql server, but i must migrate to an application with Oracle DB. for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle? A: GI Oracle Profiler v1.2 It's a Tools for Oracle to capture queries executed similar to the SQL Server Profiler. Indispensable tool for the maintenance of applications that use this database server. you can download it from the official site iacosoft.com A: Try PL/SQL Developer it has a nice user friendly GUI interface to the profiler. It's pretty nice give the trial a try. I swear by this tool when working on Oracle databases. http://www.allroundautomations.com/plsqldev.html?gclid=CM6pz8e04p0CFQjyDAodNXqPDw A: Seeing as I've just voted a recent question as a duplicate and pointed in this direction . . . A couple more - in SQL*Plus - SET AUTOTRACE ON - will give explain plan and statistics for each statement executed. TOAD also allows for client side profiling. The disadvantage of both of these is that they only tell you the execution plan for the statement, but not how the optimiser arrived at that plan - for that you will need lower level server side tracing. Another important one to understand is Statspack snapshots - they are a good way for looking at the performance of the database as a whole. Explain plan, etc, are good at finding individual SQL statements that are bottlenecks. Statspack is good at identifying the fact your problem is that a simple statement with a good execution plan is being called 1 million times in a minute. A: The Catch is Capture all SQL run between two points in time. Like the way SQL Server also does. There are situations where it is useful to capture the SQL that a particular user is running in the database. Usually you would simply enable session tracing for that user, but there are two potential problems with that approach. * *The first is that many web based applications maintain a pool of persistent database connections which are shared amongst multiple users. *The second is that some applications connect, run some SQL and disconnect very quickly, making it tricky to enable session tracing at all (you could of course use a logon trigger to enable session tracing in this case). A quick and dirty solution to the problem is to capture all SQL statements that are run between two points in time. The following procedure will create two tables, each containing a snapshot of the database at a particular point. The tables will then be queried to produce a list of all SQL run during that period. If possible, you should do this on a quiet development system - otherwise you risk getting way too much data back. * *Take the first snapshot Run the following sql to create the first snapshot: create table sql_exec_before as select executions,hash_value from v$sqlarea / *Get the user to perform their task within the application. *Take the second snapshot. create table sql_exec_after as select executions, hash_value from v$sqlarea / *Check the results Now that you have captured the SQL it is time to query the results. This first query will list all query hashes that have been executed: select aft.hash_value from sql_exec_after aft left outer join sql_exec_before bef on aft.hash_value = bef.hash_value where aft.executions > bef.executions or bef.executions is null; / This one will display the hash and the SQL itself: set pages 999 lines 100 break on hash_value select hash_value, sql_text from v$sqltext where hash_value in ( select aft.hash_value from sql_exec_after aft left outer join sql_exec_before bef on aft.hash_value = bef.hash_value where aft.executions > bef.executions or bef.executions is null; ) order by hash_value, piece / 5. Tidy up Don't forget to remove the snapshot tables once you've finished: drop table sql_exec_before / drop table sql_exec_after / A: I found an easy solution Step1. connect to DB with an admin user using PLSQL or sqldeveloper or any other query interface Step2. run the script bellow; in the S.SQL_TEXT column, you will see the executed queries SELECT S.LAST_ACTIVE_TIME, S.MODULE, S.SQL_FULLTEXT, S.SQL_PROFILE, S.EXECUTIONS, S.LAST_LOAD_TIME, S.PARSING_USER_ID, S.SERVICE FROM SYS.V_$SQL S, SYS.ALL_USERS U WHERE S.PARSING_USER_ID=U.USER_ID AND UPPER(U.USERNAME) IN ('oracle user name here') ORDER BY TO_DATE(S.LAST_LOAD_TIME, 'YYYY-MM-DD/HH24:MI:SS') desc; The only issue with this is that I can't find a way to show the input parameters values(for function calls), but at least we can see what is ran in Oracle and the order of it without using a specific tool. A: You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks. See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955 Go to Instance -> sessions and watch the SQL Tab of each session. There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache. A: Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data. Oracle provides the 'explain plan' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table). The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is: explain plan for <sql query> The analysis of that data is left for another question, or your further research. A: There is a commercial tool FlexTracer which can be used to trace Oracle SQL queries A: alter system set timed_statistics=true --or alter session set timed_statistics=true --if want to trace your own session -- must be big enough: select value from v$parameter p where name='max_dump_file_size' -- Find out sid and serial# of session you interested in: select sid, serial# from v$session where ...your_search_params... --you can begin tracing with 10046 event, the fourth parameter sets the trace level(12 is the biggest): begin sys.dbms_system.set_ev(sid, serial#, 10046, 12, ''); end; --turn off tracing with setting zero level: begin sys.dbms_system.set_ev(sid, serial#, 10046, 0, ''); end; /*possible levels: 0 - turned off 1 - minimal level. Much like set sql_trace=true 4 - bind variables values are added to trace file 8 - waits are added 12 - both bind variable values and wait events are added */ --same if you want to trace your own session with bigger level: alter session set events '10046 trace name context forever, level 12'; --turn off: alter session set events '10046 trace name context off'; --file with raw trace information will be located: select value from v$parameter p where name='user_dump_dest' --name of the file(*.trc) will contain spid: select p.spid from v$session s, v$process p where s.paddr=p.addr and ...your_search_params... --also you can set the name by yourself: alter session set tracefile_identifier='UniqueString'; --finally, use TKPROF to make trace file more readable: C:\ORACLE\admin\databaseSID\udump> C:\ORACLE\admin\databaseSID\udump>tkprof my_trace_file.trc output=my_file.prf TKPROF: Release 9.2.0.1.0 - Production on Wed Sep 22 18:05:00 2004 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. C:\ORACLE\admin\databaseSID\udump> --to view state of trace file use: set serveroutput on size 30000; declare ALevel binary_integer; begin SYS.DBMS_SYSTEM.Read_Ev(10046, ALevel); if ALevel = 0 then DBMS_OUTPUT.Put_Line('sql_trace is off'); else DBMS_OUTPUT.Put_Line('sql_trace is on'); end if; end; / Just kind of translated http://www.sql.ru/faq/faq_topic.aspx?fid=389 Original is fuller, but anyway this is better than what others posted IMHO A: This is an Oracle doc explaining how to trace SQL queries, including a couple of tools (SQL Trace and tkprof) link A: Apparently there is no small simple cheap utility that would help performing this task. There is however 101 way to do it in a complicated and inconvenient manner. Following article describes several. There are probably dozens more... http://www.petefinnigan.com/ramblings/how_to_set_trace.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/148648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "95" }
Q: What is the least amount of code needed to update one list with another list? Suppose I have one list: IList<int> originalList = new List<int>(); originalList.add(1); originalList.add(5); originalList.add(10); And another list... IList<int> newList = new List<int>(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); How can I update originalList so that: * *If the int appears in newList, keep *If the int does not appear in newList, remove *Add any ints from newList into originalList that aren't there already Thus - making the contents of originalList: { 1, 5, 7, 11 } The reason I'm asking is because I have an object with a collection of children. When the user updates this collection, instead of just deleting all children, then inserting their selections, I think it would be more efficient if I just acted on the children that were added or removed, rather than tearing down the whole collection, and inserting the newList children as if they are all new. EDIT - Sorry - I wrote a horrible title... I should have written 'least amount of code' instead of 'efficient'. I think that threw off alot of the answers I've gotten. They are all great... thank you! A: originalList = newList; Or if you prefer them being distinct lists: originalList = new List<int>(newList); But, either way does what you want. By your rules, after updating, originalList will be identical to newList. UPDATE: I thank you all for the support of this answer, but after a closer reading of the question, I believe my other response (below) is the correct one. A: If you use some LINQ extension methods, you can do it in two lines: originalList.RemoveAll(x => !newList.Contains(x)); originalList.AddRange(newList.Where(x => !originalList.Contains(x))); This assumes (as do other people's solutions) that you've overridden Equals in your original object. But if you can't override Equals for some reason, you can create an IEqualityOperator like this: class EqualThingTester : IEqualityComparer<Thing> { public bool Equals(Thing x, Thing y) { return x.ParentID.Equals(y.ParentID); } public int GetHashCode(Thing obj) { return obj.ParentID.GetHashCode(); } } Then the above lines become: originalList.RemoveAll(x => !newList.Contains(x, new EqualThingTester())); originalList.AddRange(newList.Where(x => !originalList.Contains(x, new EqualThingTester()))); And if you're passing in an IEqualityOperator anyway, you can make the second line even shorter: originalList.RemoveAll(x => !newList.Contains(x, new EqualThingTester())); originalList.AddRange(newList.Except(originalList, new EqualThingTester())); A: Sorry, wrote my first response before I saw your last paragraph. for(int i = originalList.length-1; i >=0; --i) { if (!newList.Contains(originalList[i]) originalList.RemoveAt(i); } foreach(int n in newList) { if (!originaList.Contains(n)) originalList.Add(n); } A: If you are not worried about the eventual ordering, a Hashtable/HashSet will likely be the fastest. A: LINQ solution: originalList = new List<int>( from x in newList join y in originalList on x equals y into z from y in z.DefaultIfEmpty() select x); A: My initial thought was that you could call originalList.AddRange(newList) and then remove the duplicates - but i'm not sure if that would be any more efficient than clearing the list and repopulating it. A: List<int> firstList = new List<int>() {1, 2, 3, 4, 5}; List<int> secondList = new List<int>() {1, 3, 5, 7, 9}; List<int> newList = new List<int>(); foreach (int i in firstList) { newList.Add(i); } foreach (int i in secondList) { if (!newList.Contains(i)) { newList.Add(i); } } Not very clean -- but it works. A: There is no built in way of doing this, the closest I can think of is the way DataTable handles new and deleted items. What @James Curran suggests is merely replace the originalList object with the newList object. It will dump the oldList, but keep the variable (i.e. the pointer is still there). Regardless, you should consider if optimising this is time well spent. Is the majority of the run time spent copying values from one list to the next, it might be worth it. If it's not, but rather some premature optimising you are doing, you should ignore it. Spend time polishing the GUI or profile the application before you start optimising is my $.02. A: This is a common problem developers encounter when writing UIs to maintain many-to-many database relationships. I don't know how efficient this is, but I wrote a helper class to handle this scenario: public class IEnumerableDiff<T> { private delegate bool Compare(T x, T y); private List<T> _inXAndY; private List<T> _inXNotY; private List<T> _InYNotX; /// <summary> /// Compare two IEnumerables. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="compareKeys">True to compare objects by their keys using Data.GetObjectKey(); false to use object.Equals comparison.</param> public IEnumerableDiff(IEnumerable<T> x, IEnumerable<T> y, bool compareKeys) { _inXAndY = new List<T>(); _inXNotY = new List<T>(); _InYNotX = new List<T>(); Compare comparer = null; bool hit = false; if (compareKeys) { comparer = CompareKeyEquality; } else { comparer = CompareObjectEquality; } foreach (T xItem in x) { hit = false; foreach (T yItem in y) { if (comparer(xItem, yItem)) { _inXAndY.Add(xItem); hit = true; break; } } if (!hit) { _inXNotY.Add(xItem); } } foreach (T yItem in y) { hit = false; foreach (T xItem in x) { if (comparer(yItem, xItem)) { hit = true; break; } } if (!hit) { _InYNotX.Add(yItem); } } } /// <summary> /// Adds and removes items from the x (current) list so that the contents match the y (new) list. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="compareKeys"></param> public static void SyncXList(IList<T> x, IList<T> y, bool compareKeys) { var diff = new IEnumerableDiff<T>(x, y, compareKeys); foreach (T item in diff.InXNotY) { x.Remove(item); } foreach (T item in diff.InYNotX) { x.Add(item); } } public IList<T> InXAndY { get { return _inXAndY; } } public IList<T> InXNotY { get { return _inXNotY; } } public IList<T> InYNotX { get { return _InYNotX; } } public bool ContainSameItems { get { return _inXNotY.Count == 0 && _InYNotX.Count == 0; } } private bool CompareObjectEquality(T x, T y) { return x.Equals(y); } private bool CompareKeyEquality(T x, T y) { object xKey = Data.GetObjectKey(x); object yKey = Data.GetObjectKey(y); return xKey.Equals(yKey); } } A: if your using .Net 3.5 var List3 = List1.Intersect(List2); Creates a new list that contains the intersection of the two lists, which is what I believe you are shooting for here.
{ "language": "en", "url": "https://stackoverflow.com/questions/148662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Local variables with Delegates This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated. //The constructor public Page_Index() { //create a local value string currentValue = "This is the FIRST value"; //use the local variable in a delegate that fires later this.Load += delegate(object sender, EventArgs e) { Response.Write(currentValue); }; //change it again currentValue = "This is the MODIFIED value"; } The value that is output is the second value "Modified". What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later? [Edit]: Given some of the comments, changing the original sentence some... A: currentValue is no longer a local variable: it is a captured variable. This compiles to something like: class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); } } ... public Page_Index() { Foo foo = new Foo(); foo.currentValue = "This is the FIRST value"; this.Load += foo.SomeMethod; foo.currentValue = "This is the MODIFIED value"; } Jon Skeet has a really good write up of this in C# in Depth, and a separate (not as detailed) discussion here. Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers. This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured. A: I suppose more the question I am asking is that how is it working with a local variable [MG edit: "Ack - ignore this..." was added afterwards] That is the point; it really isn't a local variable any more - at least, not in terms of how we normally think of them (on the stack etc). It looks like one, but it isn't. And for info, re "not good practice" - anonymous methods and captured variables are actually an incredibly powerful tool, especially when working with events. Feel free to use them, but if you are going down this route, I would recommend picking up Jon's book to make sure you understand what is actually happening. A: You need to capture the value of the variable within the closure/delegate, else it can be modified, like you saw. Assign currentValue to a variable local (inside) to the delegate.
{ "language": "en", "url": "https://stackoverflow.com/questions/148669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Why is the fact that Microsoft decided to support jQuery such a big deal? I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC. There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests. I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product. A: Its the first time MS is shipping an open source component they didn't write with one of their products. This doesn't seem like a big deal, but its almost nuclear in its implications. Think about it... They are saying "we support this." In an OSS product, MS has no control over the code. So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS. I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water. A: its mainly because JQuery is excellent. Now MS "supports" it, lots of people who never heard of it, were instructed not to use it because it was "open source", or were instructed not to use it because it was "not Microsoft" all can now start writing brilliant browser-based code. That's all a good thing. Its a sorry state of affairs in the computer industry where lots of people cannot use a lot of software, but that's the way it is. A: A big aspect of it is syntax. jQuery has a different meaning for $() than does prototype and ASP.NET AJAX. This is going to force javascript libraries to work out compatibility -- first by Microsoft, then by everyone else. This will be a definite plus for web designers cross-platform. UPDATE: I just the announcement on John Resig's blog: As part of Microsoft's official release, it means the Microsoft is going to be DOCUMENTING jQuery! jQuery's docs right now are "OK for an OSS project" (i.e., they don't suck that badly), but with the MSDN team of tech writers on it, we should have something truly useful. UPDATE2 (in response to the comments): That is nonsense, and shows an anti-MSFT bias more than anything else. Of parts of jQuery that are the best documented (the core functions), that documentation is roughly equal to the level given in the MSDN. So, how could one be "quite good" and the other "suck"? If the rest of the jQuery documentation (notably the plugins, and this includes the "official" plugins like "UI"), it's just dreadful. Take for example UI/Tabs, which shows a big block of HTML without explaining which parts are required and which are for just styling the demo. And doesn't mention (or in some releases even include) the more-or-less required CSS file. Or, how 'bout UI/Autocomplete which is in the latest relese, but completely missing from the UI docs (and differs in some subtle, but important ways from the stand-alone Autocomplete on which it was based). A: Like it or not, Microsoft is one of the biggest player in the software industry, so anything it does is a big deal. And in this case, it seems to be a good thing. A: It is. We definitely need better intellisense for Javascript. A: The significance of Microsoft shipping jQuery with ASP.Net, even though it's open source, has little or nothing to do with Microsoft supporting outside open source software and nearly everything to do with establishing a de-facto javascript framework standard. Consider: there are currently at least 1/2 dozen javascript toolkits out there that are all very nice. These toolkits represent a huge improvement over traditional javascript development. They add power and help smooth over browser incompatibilities. Eventually you'll have a hard time finding a web project that doesn't use one. One day they might even be baked into your browser to save page load times. Every web developer owes it to themselves to learn one, and most understand this. But which one? As I said, there are several out there that are an excellent technical choice. How do you choose? The problem is that you're not really qualified to judge on the technical merits unless you learn them all, and who has time for that? In this case it's much easier and safer to just follow the crowd. Failing a clear technical superiority, most developers will want to pick the toolkit that gets the most adoption among other like-minded developers, for four reasons: * *It guarantees the skill will be useful later *They'll be able to find help and support for it when they need it. *They trust their peers to do a good job picking the framework that is technically superior, or at least technically competent. *Because the different options are all mainly open source, the most popular should also over time become the best technical choice. So what we have is a situation where everyone is waiting to see which framework everyone else picks. Frankly, the lack of a clear winner among the various toolkits has hurt adoption; I know it's prevented me personally from taking the plunge. Until now. Now ASP.Net developers have a clear choice. If you use ASP.Net, you probably want to take the time to learn jQuery. Not Prototype. Not MooTools. Not something else. Your natural choice is jQuery. Those other tools are nice as well, but for better or worse jQuery just got a huge leg up here, and this really is a popularity contest. jQuery's emerging popularity among other platforms as well means it's quickly becoming the de-facto javascript framework standard. Very soon you'll have a hard time calling yourself a web developer if you don't know jQuery, and a lot of people will look back and say that this was the tipping point. So the real significance here has little to do with the whole "Microsoft using open source" thing. As far as I'm concerned it doesn't matter as much whether jQuery is open source, though it may help in the long run. What does matter is that this will cause a significant number of developers to start using it, possibly enough to create a hegemony. And that's what this space has really needed. We can finally start moving forward again in advancing client-side web development. A: You have a 500 Pound Gorilla whose official company politics always stood against open source suddenly deciding to actively include and support an Open Source component for technical reasons. jQuery is not some legal requirement put on them by US or EU Anti-Trust lawsuits. It's not forced on Microsoft through some standard or some "must-support" component. They are more or less solely choosing it for technical reasons instead of doing their usual "We reinvent the wheel, make it not as good as the free solutions and also not make it open source". It's like the pope advertising condoms, it's like the Washington Wizards winning the NBA Title, it's like republicans voting for a 700 billion $ program, it's like the OPEC supporting solar and wind energy... it's something that seemed unthinkable before, even keeping in mind that Microsoft has some of the best talent working for them. In fact, most of the people I look up to are working at Microsoft now. I can only imagine how much discussion and persuation work was needed to make this happen, and I lift my hat for the people within Microsoft who have proven that reason can succeed sometimes. A: It is a huge deal! The fact that MS is leveraging a technology that it didn't develop is a big step. Also, the fact they aren't buying it out or consuming it is a very big step as well. Personally, I have found using jQuery to be a big help while I've been developing ASP.NET MVC. It has helped me to simplify my Views where if I didn't have jQuery my Views would have been too complicated. I think this is a great stop in the right direction. A: For those who already use jQuery alongside ASP.NET, it means that we can look forward to better tools support for it in the future (eg intellisense support in Visual Studio) and more importantly it means (hopefully) that Microsoft won't do anything with ASP.NET that breaks jQuery. Whether or not this is a toe in the water in terms of embracing (co-opting?) open source solutions within Microsoft tools or a one-off remains to be seen. A: @Code Trawler - This issue is very much tied to the Microsoft division involved in the effort. MS Dev Div has been extremely Open Source friendly and has hired numerous people from the Open Source community in the past couple of years. A move to fork JQuery would only further alienate the development community and would likely alienate many of their recent OS hires as well. This would be a PR nightmare. A: If you work at a place that does not allow OSS because of lack of support this is huge since now it has that nice microsoft stamp of approval that helps win over business folk in a way that a developer at the company never could. A: Bear in mind that Jquery is released by MS under the MIT license. This means, assuming I understand the terms of the MIT license correctly, that they could in future alter jquery arbitarily and close it off, presumably after its mass acceptance as part of Visual Studio. Edit: OK, I'm being modded down. Can someone please post and explain why they think my supposition here is false. Am I misunderstanding the MIT license?
{ "language": "en", "url": "https://stackoverflow.com/questions/148670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: How do I refresh the relationships in a dataset? I a working in VisualStudio 2005. I have a dataset with sevaral datatables in it already. I had to modify the database to add a new foreign key that I forgot about. How do I get visual studio to recognize the new relationship? A: .Net does not load FK relationships into your DataSet automatically - however, you can add them yourself with a DataRelation*. *this may not be true if you are using LINQ - if you are, I am unsure. A: Right-click on the DataSet page, and select Add->Relation? If you've defined it in your database, you can always re-drag the affected table back into the Dataset then re-enter your Queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/148672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Play a sound, wait for it to finish and then do something? I'm writing a Windows Forms application which is supposed to play three sound files and at the end of each sound file, it's to change the source of an image. I can get it to play the sounds using System.Media.SoundPlayer. However, it seems to play the sound in a different thread, continuing on. The net effect of this is that only the last sound is played and all the images are changed. I've tried Thread.Sleep, but it sleeps the whole GUI and after the sleep period everything happens at once and the last sound it played. UPDATE I thought PlaySynch was working, but it seems to freeze my GUI which is less than ideal. What else can I do? A: Did you try SoundPlayer.PlaySync Method? From the help: The PlaySync method uses the current thread to play a .wav file, preventing the thread from handling other messages until the load is complete. A: Instead of using the Play method, use the PlaySync method. A: Use this code: [DllImport("WinMM.dll")] public static extern bool PlaySound(byte[]wfname, int fuSound); // flag values for SoundFlags argument on PlaySound public static int SND_SYNC = 0x0000; // Play synchronously (default). public static int SND_ASYNC = 0x0001; // Play asynchronously. public static int SND_NODEFAULT = 0x0002; // Silence (!default) if sound not found. public static int SND_MEMORY = 0x0004; // PszSound points to a memory file. public static int SND_LOOP = 0x0008; // Loop the sound until next sndPlaySound. public static int SND_NOSTOP = 0x0010; // Don't stop any currently playing sound. public static int SND_NOWAIT = 0x00002000; // Don't wait if the driver is busy. public static int SND_ALIAS = 0x00010000; // Name is a registry alias. public static int SND_ALIAS_ID = 0x00110000; // Alias is a predefined ID. public static int SND_FILENAME = 0x00020000; // Name is file name. public static int SND_RESOURCE = 0x00040004; // Name is resource name or atom. public static int SND_PURGE = 0x0040; // Purge non-static events for task. public static int SND_APPLICATION = 0x0080; // Look for application-specific association. private Thread t; // used for pausing private string bname; private int soundFlags; //----------------------------------------------------------------- public void Play(string wfname, int SoundFlags) { byte[] bname = new Byte[256]; //Max path length bname = System.Text.Encoding.ASCII.GetBytes(wfname); this.bname = bname; this.soundFlags = SoundFlags; t = new Thread(play); t.Start(); } //----------------------------------------------------------------- private void play() { PlaySound(bname, soundFlags) } public void StopPlay() { t.Stop(); } public void Pause() { t.Suspend(); // Yeah, I know it's obsolete, but it works. } public void Resume() { t.Resume(); // Yeah, I know it's obsolete, but it works. } A: What you probably want to do is do an async sound, but then disable your UI in such a way that it doesn't respond to user response. Then once the sound is played, you re-enable your UI. This would allow you to still paint the UI as normal. A: I figured out how to do it. I used PlaySynch, but I did the playing in a separate thread to the code the draws the UI. The same thread also updates the UI after each file is played.
{ "language": "en", "url": "https://stackoverflow.com/questions/148676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Tool Comparison: Visual Assist X and Resharper .NET developers out there! Need your opinion here! I am now using Visual Assist X, a decent piece of software, indeed. But the .NET bloggers seem to prefer Resharper more. I might want to consider a switch over, but before that I want your guys opinion first. A: C/C++ = Visual Assist X. For me, C# = ReSharper + Visual Assist X. Needless to say, ReSharper is much more powerful for C# development, than VA. But there are some features, like ability to show just methods in suggestions list, or highlight nearest scope that are in VA, but no equivalent in R#. I use both. Looks like they live pretty well together: i use default settings for VA, and i had to select ReSharper-->Options-->IntelliSense-->General-->Visual Studio to enable VA version of IntelliSense instead of ReSharper's one. I also customized identifiers colors in ReSharper, now they look like VA default colors, but show additional information (like Mutable Local Variables are bold). A: I know you only asked for a comparison of Resharper vs. Visual Assist but if you are doing .NET development you may also want to consider "Refactor! Pro". I remember using VA years ago when doing Visual C++ development (and earlier than that the infamous CodeWiz) but with .NET development I get the impression that the majority of developers seem to use either ReSharper or Refactor!. Refactor! also integrates with a code-generation tool called "CodeRush" and I've seen them both used very effectively together with Testdriven.Net (check out the Summer of NHibernate screencasts). Personally I use Resharper and I am very pleased with how much it has increased my productivity but I'm sure you'll get equal benefit with Refactor!. A: Resharper is much better for C# code (and supposedly VB.Net, but I haven't tried that). Unfortunately there is no support for C/C++, so if you need that, you might want to keep Visual Assist around. They don't coexist very well, unfortunately, so you may need to unload one, then load the other, when switching between C/C++ and C#. To see the magic of Resharper, I would recommend watching the "Resharper Jedi" video.
{ "language": "en", "url": "https://stackoverflow.com/questions/148678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Unloading classes in java? I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We also have version problems if we don't load the classes dynamically at run time from the AppServer library. Now, I just hit a problem where I need to talk to two different AppServers and found that depending on whose classes I load first I might break badly... Is there any way to force the unloading of the class without actually killing the JVM? Hope this makes sense A: You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control. If possible, I suggest using your own ClassLoader so you can unload. A: Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders. A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow: * *The program starts and the real "main"-class is loaded by this proxy classloader. *Every class that then is normally loaded (i.e. not through another classloader implementation which could break the hierarchy) will be delegated to this class loader. *The proxy classloader delegates java.x and sun.x to the system classloader (these must not be loaded through any other classloader than the system classloader). *For every class that is replaceable, instantiate a classloader (which really loads the class and does not delegate it to the parent classloader) and load it through this. *Store the package/name of the classes as keys and the classloader as values in a data structure (i.e. Hashmap). *Every time the proxy classloader gets a request for a class that was loaded before, it returns the class from the class loader stored before. *It should be enough to locate the byte array of a class by your class loader (or to "delete" the key/value pair from your data structure) and reload the class in case you want to change it. Done right there should not come a ClassCastException or LinkageError etc. For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want. A: Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes. As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance. A: The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo. One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server. This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it. If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file. And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own. If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class. I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well. A: I wrote a custom classloader, from which it is possible to unload individual classes without GCing the classloader. Jar Class Loader A: Classloaders can be a tricky problem. You can especially run into problems if you're using multiple classloaders and don't have their interactions clearly and rigorously defined. I think in order to actually be able to unload a class youlre going go have to remove all references to any classes(and their instances) you're trying to unload. Most people needing to do this type of thing end up using OSGi. OSGi is really powerful and surprisingly lightweight and easy to use, A: If you're live watching if unloading class worked in JConsole or something, try also adding java.lang.System.gc() at the end of your class unloading logic. It explicitly triggers Garbage Collector.
{ "language": "en", "url": "https://stackoverflow.com/questions/148681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "191" }
Q: iSeries Export to CSV Is there an iSeries command to export the data in a table to CSV format? I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program. A: You can use CPYTOIMPF and specify the TOSTMF option to place a CSV file on the IFS. Example: CPYTOIMPF FROMFILE(DBFILE) TOSTMF('/outputfile.csv') STMFCODPAG(*PCASCII) RCDDLM(*CRLF) A: If you want the data to be downloaded directly to a PC, you can use the "Data Transfer from iSeries" function of IBM iSeries Client Access to create a .CSV file. In the file output details dialog, set the file type to Comma Separated Variable (CSV). You can save the transfer description to be reused later. A: You could use a trigger. The iSeries Client Access software wont do since that is a windows application, what I understand is that you need the data to be exported each time that the file is written. Check this link to know more about triggers. A: You are going to need FTP to perform that action. If your iSeries shop uses ZMOD/FTP your shortest solution is a few lines of code away -- 3 lines to be exact -- the three lines are to Start FTP, Put DBF, and finally, End FTP. IF you don't use ZMOD/FTP: - You could use native FTP/400 to accomplish what you need to do, but it is quite involved!!! - you may probably need to use an RPGLE program to parse, format, and move, data into a "flatfile", then use native FTP/400 to FTP the file out - and yes, a CL will need as a wrapper! A: You can do it all in one very simple CL program: * *CPYTOIMPF the file TOSTMF -> the cvs file will be in the IFS *FTP the file elsewhere (to a server or a PC) It works like a charm
{ "language": "en", "url": "https://stackoverflow.com/questions/148689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to bind from a ContentTemplate to the surrounding custom Control? I've got the following user control: <TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" > <TabItem.Header> <!-- This works --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> </TabItem.Header> <TabItem.ContentTemplate> <DataTemplate> <!-- This binds to "Self" in the surrounding window's namespace --> <TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/> This custom TabItem defines a DependencyProperty 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the TabItem's DataTemplate. But due to strange interactions, the TextBlock within the DataTemplate gets bound to the parent container of the TabItem, which also is called "Self", but defined in another Xaml file. Question Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate? What I already tried * *TemplateBinding: Tries to bind to the ContentPresenter within the guts of the TabItem. *FindAncestor, AncestorType={x:Type TabItem}: Doesn't find the TabItem parent. This doesn't work either, when I specify the MyTabItem type. *ElementName=Self: Tries to bind to a control with that name in the wrong scope (parent container, not TabItem). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container. I assume I could replace the whole ControlTemplate to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the TabItem without having to maintain the whole ControlTemplate, I'm very reluctant to do so. Edit Meanwhile I have found out that the problem is: TabControls can't have (any) ItemsTemplate (that includes the DisplayMemberPath) if the ItemsSource contains Visuals. There a thread on MSDN Forum explaining why. Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help! A: What appears to be the problem is that you are using a ContentTemplate without actualy using the content property. The default DataContext for the ContentTemplate's DataTemplate is the Content property of TabItem. However, none of what I said actually explains why the binding doesn't work. Unfortunately I can't give you a definitive answer, but my best guess is that it is due to the fact that the TabControl reuses a ContentPresenter to display the content property for all tab items. So, in your case I would change the code to look something like this: <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" /> If ShortLabel is a more complex object and not just a string then you would want to indroduce a ContentTemplate: <TabItem x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" Content="{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}"> <TabItem.ContentTemplate> <DataTemplate TargetType="{x:Type ComplexType}"> <TextBlock Text="{Binding Property}" /> </DataTemplate> </TabItem.ContentTemplate> </TabItem> A: Try this. I'm not sure if it will work or not, but <TabItem x:Name="Self" x:Class="App.MyTabItem" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:App" > <TabItem.ContentTemplate> <DataTemplate> <TextBlock Text="{Binding Path=ShortLabel}"/> </DataTemplate> </TabItem.ContentTemplate> </TabItem> If it doesn't work, try sticking this attribute in the <TabItem/>: DataContext="{Binding RelativeSource={RelativeSource self}}"
{ "language": "en", "url": "https://stackoverflow.com/questions/148704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: User Control Public Shared Variables in ASP.NET 1.1 Not Working As Expected Let's say I have a web form that includes some user controls. The title tag for my "main" web form is generated in one of the user controls. Passing this data to the web form is currently done like this. Public Sub SetPageValues(ByVal sTitle As String, ByVal sKeywords As String, ByVal sDesc As String) MySystem.Web.UI.Main.PageSettings(sKeywords, sDesc, sTitle) End Sub Main is the name of the web form. Here's the sub that sets that values in Main. Public Shared Sub PageSettings(ByVal strKeywords As String, ByVal strDesc As String, ByVal strTitle As String) Dim _lblTitle As System.Web.UI.webcontrols.Literal = lblTitle Dim _lblMetaDesc As System.Web.UI.webControls.Literal = lblMetaDesc Dim _lblMetaKeywords As System.Web.UI.WebControls.Literal = lblMetaKeywords Dim _lblMetatitle As System.Web.UI.WebControls.Literal = lblMetaTitle _lblTitle.Text = strTitle _lblMetaDesc.Text = "<meta name=""description"" content=""" + strDesc + """>" _lblMetaKeywords.Text = "<meta name=""keywords"" content=""" + strKeywords + """>" _lblMetatitle.Text = "<meta name=""title"" content=""" + strTitle + """>" End Sub After all of this we are running pooled memory and recycle it every 400 minutes, however, page titles get corrupted and display incorrectly. Does anyone have any ideas other than moving to a new version .net? By making properties in the user control, the values can now be passed correctly. A: Personally, here's what I would do. First - Change the TITLE to an HTML.GenericControl On the ASPX side, it would look like this: <title runat="server" id="title" /> Then, I'd modify the META tags to also be html generic controls <meta name="description" content="description" id="description" runat="server" /> <meta name="keywords" content="keys" id="keywords" runat="server" /> At that point, you can modify the values like this: title.InnerText = "This Title" keywords.Attributes("content") = "key,word" description.Attributes("content") = "A demonstration of Setting title and meta tags"
{ "language": "en", "url": "https://stackoverflow.com/questions/148723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC input validation I'm currently working on a blog application in ASP.NET MVC. I can't quite figure out how to handle my input validation! As far as I understand the view itself cannot know about input validation!? So how am I going to do this? A: Scott Guthrie has written something about ASP.NET MVC Preview 5, and form posting: ASP.NET MVC Preview 5 and Form Posting Scenarios It's a big post, but it walks you through a Form posting validation thingy. Remark that this is not the only way to do it, but it is a way.
{ "language": "en", "url": "https://stackoverflow.com/questions/148725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Scrollable JDesktopPane? I'd like to add scrolling capability to a javax.swing.JDesktopPane. But wrapping in a javax.swing.JScrollPane does not produce the desired behavior. Searching the web shows that this has been an issue for quite some time. There are some solutions out there, but they seem to be pretty old, and I'm not not completely satisfied with them. What actively maintained solutions do you know? A: I've used JavaWorld's solution by creating my own JScrollableDesktopPane. A: Javaworld's JScrollableDesktopPane is no longer available on their website. I managed to scrounge up some copies of it but none of them work. A simple solution I've derived can be achieved doing something like the following. It's not the prettiest but it certainly works better than the default behavior. public class Window extends Frame { JScrollPane scrollContainer = new JScrollPane(); JDesktopPane mainWorkingPane = new JDesktopPane(); public Window() { scrollContainer.setViewportView(mainWorkingPane); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent evt) { revalidateDesktopPane(); } }); } private void revalidateDesktopPane() { Dimension dim = new Dimension(0,0); Component[] com = mainWorkingPane.getComponents(); for (int i=0 ; i<com.length ; i++) { int w = (int) dim.getWidth()+com[i].getWidth(); int h = (int) dim.getHeight()+com[i].getHeight(); dim.setSize(new Dimension(w,h)); } mainWorkingPane.setPreferredSize(dim); mainWorkingPane.revalidate(); revalidate(); repaint(); } } The idea being to wrap JDesktopPane in a JScrollPane, add a resize listener on the main Frame and then evaluate the contents of the JDesktopPane on resize (or adding new elements). Hope this helps someone out there. A: I've found this : http://www.javaworld.com/javaworld/jw-11-2001/jw-1130-jscroll.html?page=1 It's a nice tutorial with lots of explanations and infos on Swing & so, which permits to create a JscrollableDesktopPane with lots of stuff. You will need to modify a bit some parts of code to fulfill your requirements. Enjoy !
{ "language": "en", "url": "https://stackoverflow.com/questions/148728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to set/change/remove focus style on a Button in C#? I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel. However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus. On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still exist, just not display in the way it does now. Any suggestions? :-) A: Another option (although a bit hacktastic) is to attach an event-handler to the button's GotFocus event. In that event-handler, pass a value of False to the button's NotifyDefault() method. So, for instance: void myButton_GotFocus(object sender, EventArgs e) { myButton.NotifyDefault(false); } I'm assuming this will work every time, but I haven't tested it extensively. It's working for me for now, so I'm satisfied with that. A: Is this the effect you are looking for? public class NoFocusCueButton : Button { protected override bool ShowFocusCues { get { return false; } } } You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus. A: I had the same issue with the annoying double border, and stumbled across this thread looking for an answer... The way I solved this was to set the BorderSize to 0 then draw my own border in OnPaint Note: Not the entire button, just the border A simple example would be: public class CustomButton : Button { public CustomButton() : base() { // Prevent the button from drawing its own border FlatAppearance.BorderSize = 0; FlatStyle = System.Windows.Forms.FlatStyle.Flat; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Draw Border using color specified in Flat Appearance Pen pen = new Pen(FlatAppearance.BorderColor, 1); Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); e.Graphics.DrawRectangle(pen, rectangle); pen.Dispose(); } } In my case, this is how I made a button that mimics a ToolStripButton, where the border is only visible when you hover over the button: public class ToolButton : Button { private bool ShowBorder { get; set; } public ToolButton() : base() { // Prevent the button from drawing its own border FlatAppearance.BorderSize = 0; // Set up a blue border and back colors for the button FlatAppearance.BorderColor = Color.FromArgb(51, 153, 255); FlatAppearance.CheckedBackColor = Color.FromArgb(153, 204, 255); FlatAppearance.MouseDownBackColor = Color.FromArgb(153, 204, 255); FlatAppearance.MouseOverBackColor = Color.FromArgb(194, 224, 255); FlatStyle = System.Windows.Forms.FlatStyle.Flat; // Set the size for the button to be the same as a ToolStripButton Size = new System.Drawing.Size(23, 22); } protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); // Show the border when you hover over the button ShowBorder = true; } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); // Hide the border when you leave the button ShowBorder = false; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // The DesignMode check here causes the border to always draw in the Designer // This makes it easier to place your button if (DesignMode || ShowBorder) { Pen pen = new Pen(FlatAppearance.BorderColor, 1); Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1); e.Graphics.DrawRectangle(pen, rectangle); pen.Dispose(); } } // Prevent Text from being set on the button (since it will be an icon) [Browsable(false)] public override string Text { get { return ""; } set { base.Text = ""; } } [Browsable(false)] public override ContentAlignment TextAlign { get { return base.TextAlign; } set { base.TextAlign = value; } } } A: Make a custom button: public partial class CustomButton: Button { public ButtonPageButton() { InitializeComponent(); this.SetStyle(ControlStyles.Selectable, false); } } That'll get rid of that annoying border! ;-) A: There is another way which works well for flat styled buttons. Don't use buttons but labels. As you are completely replacing the UI for the button it does not matter whether your use a button control or a label. Just handle the click in the same way. This worked for me, although not great practice it is a good hack and as long as you name the button obviously (and comment the source) other coders will pick up the idea. Ryan A: The second border which gets added is the Windows standard "default button" border. You may have noticed that if you tab through most dialog boxes with multiple buttons (such as any Control Panel properties window), the original "double-bordered" button becomes "normal," and the in-focus button becomes "double-bordered." This isn't necessarily focus at work, but rather a visual indication of the action undertaken by hitting the Enter key. It sounds, to me, like you don't really care about that internal working. You want the display to not have two borders -- totally understandable. The internal working is to explain why you're seeing this behavior. Now ... To try and fix it. The first thing I'd try -- and bear in mind, I haven't validated this -- is a hack. When a button receives focus (thereby getting the double-border), turn off your single border. You might get the effect you want, and it's pretty simple. (Hook into the Focus event. Even better, subclass Button and override OnFocus, then use that subclass for your future buttons.) However, that might introduce new, awkward visual side effects. In that vein -- and because hacks are rarely the best answer -- I have to "officially" recommend what others have said: Custom paint the button. Although the code here may be overkill, this link at CodeProject discusses how to do that (VB link; you'll need translate). You should, in a full-on custom mode, be able to get rid of that second border completely. A: Certainly you can draw the button yourself. One of the state flags is focused. So on the draw event if the flag is focused go ahead and draw the button how you like, otherwise just pass it on to the base method. A: Consider implementing your own drawing code for the button. That way you have full control. In the past, I've implemented my own Control derivative that custom paints my button and implements all the button characteristics for my purposes, but you should be able to override the button's painting and do it yourself, thereby controlling how it draws in every state, including when focused. A: If you have a textbox and a button then on textchange event of textbox write button1.focus(); It will work. A: You can also create an invisible button and make it active whenever you press another button. A: I've had good luck merely setting the Focusable property of the button to be false: <Button HorizontalAlignment="Left" Margin="0,2" Command="{Binding OpenSuspendedJobCommand, Mode=OneWay}" Focusable="False" Style="{StaticResource ActionButton}" Content="Open Job..." /> A: Set the FocusVisualStyle dependency property to null in your style, and the dotted border will be gone. From MSDN: Styling for Focus in Controls, and FocusVisualStyle Windows Presentation Foundation (WPF) provides two parallel mechanisms for changing the visual appearance of a control when it receives keyboard focus. The first mechanism is to use property setters for properties such as IsKeyboardFocused within the style or template that is applied to the control. The second mechanism is to provide a separate style as the value of the FocusVisualStyle property; the "focus visual style" creates a separate visual tree for an adorner that draws on top of the control, rather than changing the visual tree of the control or other UI element by replacing it. This topic discusses the scenarios where each of these mechanisms is appropriate. The extra border you see is defined by the FocusVisualStyle and not in the control template, so you need to remove or override the style to remove the border.
{ "language": "en", "url": "https://stackoverflow.com/questions/148729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Intercept Windows Vista shutdown event in C# I want to be able to intercept the shutdown event in C# for Windows Vista. Due to the advanced security features with Vista, any applications that are running after the shutdown command is called are halted and displayed in a list, prompting the user to do something with them. Does anybody know how to overcome this and what events I need to be using in Vista. Thanks. A: You can use WPF's application object and subscribe to its SessionEnding event. You can then look at the SessionEndingCancelEventArgs.ReasonSessionEnding enumeration to determine exactly why the session is ending (LogOff or Shutdown). A: What you may want to look at is here - Application Shutdown Changes in Windows Vista. Basically, for what you want, it all revolves around WM_QUERYENDSESSION. Note that this is exposed in the .net framework - instead you will need to use native functions (p/invoke) and hook the wndproc in your code to respond to the windows message. For an example (showing a reason to not shutdown), you can see Windows Vista - ShutdownBlockReasonCreate in C#. A: System.Environment.HasShutdownStarted A: Use the event Application.SessionEnding for WPF. A: The SessionEnding / SessionEnded events on Microsoft.Win32.SystemEvents might be what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/148733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to detect if any specific drive is a hard drive? In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy? A: DriveInfo.DriveType should work for you. DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" File type: {0}", d.DriveType); } A: Check System.IO.DriveInfo class and DriveType property. A: The method GetDrives() returns a DriveInfo class which has a property DriveType that corresponds to the enumeration of System.IO.DriveType: public enum DriveType { Unknown, // The type of drive is unknown. NoRootDirectory, // The drive does not have a root directory. Removable, // The drive is a removable storage device, // such as a floppy disk drive or a USB flash drive. Fixed, // The drive is a fixed disk. Network, // The drive is a network drive. CDRom, // The drive is an optical disc device, such as a CD // or DVD-ROM. Ram // The drive is a RAM disk. } Here is a slightly adjusted example from MSDN that displays information for all drives: DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}, Type {1}", d.Name, d.DriveType); }
{ "language": "en", "url": "https://stackoverflow.com/questions/148742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: What is the difference between a framework and a library? What is the difference between a framework and a library? I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development. A: A library implements functionality for a narrowly-scoped purpose whereas a framework tends to be a collection of libraries providing support for a wider range of features. For example, the library System.Drawing.dll handles drawing functionality, but is only one part of the overall .NET framework. A: A library performs specific, well-defined operations. A framework is a skeleton where the application defines the "meat" of the operation by filling out the skeleton. The skeleton still has code to link up the parts but the most important work is done by the application. Examples of libraries: Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math. Operations are self-contained. Examples of frameworks: Web application system, Plug-in manager, GUI system. The framework defines the concept but the application defines the fundamental functionality that end-users care about. A: I think library is a set of utilities to reach a goal (for example, sockets, cryptography, etc). Framework is library + RUNTIME ENVIRONMENT. For example, ASP.NET is a framework: it accepts HTTP requests, create page object, invoke life cycle events, etc. Framework does all this, you write a bit of code which will be run at a specific time of the life cycle of current request! A: Libraries are for ease of use and efficiency.You can say for example that Zend library helps us accomplish different tasks with its well defined classes and functions.While a framework is something that usually forces a certain way of implementing a solution, like MVC(Model-view-controller)(reference). It is a well-defined system for the distribution of tasks like in MVC.Model contains database side,Views are for UI Interface, and controllers are for Business logic. A: From Web developer perspective: * *Library can be easily replaceable by another library. But framework cannot. If you don't like jquery date picker library, you can replace with other date picker such as bootstrap date picker or pickadate. If you don't like AngularJS on which you built your product, you cannot just replace with any other frameworks. You have to rewrite your entire code base. *Mostly library takes very less learning curve compared to Frameworks. Eg: underscore.js is a library, Ember.js is a framework. A: Your interpretation sounds pretty good to me... A library could be anything that's compiled and self-contained for re-use in other code, there's literally no restriction on its content. A framework on the other hand is expected to have a range of facilities for use in some specific arena of application development, just like your example, MVC. A: I think you pinned down quite well the difference: the framework provides a frame in which we do our work... Somehow, it is more "constraining" than a simple library. The framework is also supposed to add consistency to a set of libraries. A: Library - Any set of classes or components that can be used as the client deems fit to accomplish a certain task. Framework - mandates certain guidelines for you to "plug-in" into something bigger than you. You merely provide the pieces specific to your application/requirements in a published-required manner, so that 'the framwework can make your life easy' A: I don´t remember the source of this answer (I guess I found it in a .ppt in the internet), but the answer is quite simple. A Library and a Framework are a set of classes, modules and/or code (depending of the programing language) that can be used in your applications and helps you to solve an especific "problem". That problem can be log or debuging info in an application, draw charts, create an specific file format (html, pdf, xls), connect to a data base, create a part of an application or a complete application or a code applied to a Design Pattern. You can have a Framework or a Library to solve all these problems and many more, normaly the frameworks helps you to solve more complex or bigger problems, but that a consecuence of their main difference, not a main definition for both. The main difference betwen a Library and a Framework is the dependency betwen their own code, in oder words to use a Framework you need to use almost all the classes, modules or code in the FW, but to use a Library you can use one or few classes, modules or code in the lib in your own application This means that if a Framework has, for example has 50 classes in order to use the framework in an app you need to use, let said, 10-15 or more classes in your code, because that is how is designed a Framework, some classes (objects of that classes) are inputs/parameters for methods in other classes in the framework. See the .NET framework, Spring, or any MVC framework. But for example a log library, you can just use a Log class in your code, and helps you to solve the "logging problem", that doesn´t mean that the log library doesn't have more classes in his code, like classes to handle files, handle screen outputs, or even data bases, but you never touch/use that classes in your code, and that is the reason of why is a library and not a framework. And also there are more categories than Frameworks and Libraries, but that is off topic. A: I like Cohens answer, but a more technical definition is: Your code calls a library. A framework calls your code. For example a GUI framework calls your code through event-handlers. A web framework calls your code through some request-response model. This is also called inversion of control - suddenly the framework decides when and how to execute you code rather than the other way around as with libraries. This means that a framework also have a much larger impact on how you have to structure your code. A: Actually these terms can mean a lot of different things depending the context they are used. For example, on Mac OS X frameworks are just libraries, packed into a bundle. Within the bundle you will find an actual dynamic library (libWhatever.dylib). The difference between a bare library and the framework on Mac is that a framework can contain multiple different versions of the library. It can contain extra resources (images, localized strings, XML data files, UI objects, etc.) and unless the framework is released to public, it usually contains the necessary .h files you need to use the library. Thus you have everything within a single package you need to use the library in your application (a C/C++/Objective-C library without .h files is pretty useless, unless you write them yourself according to some library documentation), instead of a bunch of files to move around (a Mac bundle is just a directory on the Unix level, but the UI treats it like a single file, pretty much like you have JAR files in Java and when you click it, you usually don't see what's inside, unless you explicitly select to show the content). Wikipedia calls framework a "buzzword". It defines a software framework as A software framework is a re-usable design for a software system (or subsystem). A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.. So I'd say a library is just that, "a library". It is a collection of objects/functions/methods (depending on your language) and your application "links" against it and thus can use the objects/functions/methods. It is basically a file containing re-usable code that can usually be shared among multiple applications (you don't have to write the same code over and over again). A framework can be everything you use in application development. It can be a library, a collection of many libraries, a collection of scripts, or any piece of software you need to create your application. Framework is just a very vague term. Here's an article about some guy regarding the topic "Library vs. Framework". I personally think this article is highly arguable. It's not wrong what he's saying there, however, he's just picking out one of the multiple definitions of framework and compares that to the classic definition of library. E.g. he says you need a framework for sub-classing. Really? I can have an object defined in a library, I can link against it, and sub-class it in my code. I don't see how I need a "framework" for that. In some way he rather explains how the term framework is used nowadays. It's just a hyped word, as I said before. Some companies release just a normal library (in any sense of a classical library) and call it a "framework" because it sounds more fancy. A: I think that the main difference is that frameworks follow the "Hollywood principle", i.e. "don't call us, we'll call you." According to Martin Fowler: A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client. A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points. A: I forget where I saw this definition, but I think it's pretty nice. A library is a module that you call from your code, and a framework is a module which calls your code. A: Library: It is just a collection of routines (functional programming) or class definitions(object oriented programming). The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes or routines normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works. Framework: In framework, all the control flow is already there, and there are a bunch of predefined white spots that we should fill out with our code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions. Library,Framework and your Code image representation: KeyDifference: The key difference between a library and a framework is “Inversion of Control”. When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you. Source. Relation: Both of them defined API, which is used for programmers to use. To put those together, we can think of a library as a certain function of an application, a framework as the skeleton of the application, and an API is connector to put those together. A typical development process normally starts with a framework, and fill out functions defined in libraries through API. A: A framework can be made out of different libraries. Let's take an example. Let's say you want to cook a fish curry. Then you need ingredients like oil, spices and other utilities. You also need fish which is your base to prepare your dish on (This is data of your application). all ingredients together called a framework. Now you gonna use them one by one or in combination to make your fish curry which is your final product. Compare that with a web framework which is made out of underscore.js, bootstrap.css, bootstrap.js, fontawesome, AngularJS etc. For an example, Twitter Bootstrap v.35. Now, if you consider only one ingredient, like say oil. You can't use any oil you want because then it will ruin your fish (data). You can only use Olive Oil. Compare that with underscore.js. Now what brand of oil you want to use is up to you. Some dish was made with American Olive Oil (underscore.js) or Indian Olive Oil (lodash.js). This will only change the taste of your application. Since they serve almost the same purpose, their use depends on the developer's preference and they are easily replaceable. Framework: A collection of libraries that provide unique properties and behavior to your application. (All ingredients) Library: A well-defined set of instructions that provide unique properties and behavior to your data. (Oil on Fish) Plugin : A utility build for a library (ui-router -> AngularJS) or many libraries in combination (date-picker -> bootstrap.css + jQuery) without which your plugin might now work as expected. P.S. AngularJS is an MVC framework but a JavaScript library. Because I believe Library extends default behavior of native technology (JavaScript in this case). A: What is a Library? A library is a collection of code blocks (could be in the form of variables, functions, classes, interfaces etc.) that are built by developers to ease the process of software development for other developers that find its relevance. What is a Framework? With reference to the definition of a library, we could define a framework as a tool that helps a developer solve a large range of domain-specific problems by providing the developer with necessary libraries in a controlled development environment. A: This is how I think of it (and have seen rationalized by others): A library is something contained within your code. And a framework is a container for your application. A: I will try to explain like you're five. ( No programming term was being used. ) Let's imagine that you had opened a burger restaurant in your city a while ago. But you feel it's so hard to make a burger as a beginner. You were thinking about an easy way to make burgers for customers. Someone told you that If you use framework, you can make bugger easily. and you got to know that there are McDonald Burger Framework and BurgerKing Burger Framework. If you use McDonald Burger Framework, It's so easy to make Big Mac burger. (but you cannot make Whopper.) If you use BurgerKing Burger Framework, It's so easy to make Whopper Burger. (however, you cannot make Big Mac) Anyway, In the end, they are all burgers. An important thing here is, you have to follow their framework's rule to make burgers. otherwise, you feel even harder to make it or won't be able to make it. And you also heard that there is something called Simple Burger-Patty Library. If you use this Library, you can make whatever burger patty so easily (X2 speed). It doesn't really matter if you use McDonald Burger Framework or BurgerKing Burger Framework. Either way, you can still use this Simple Burger-Patty Library. (Even you can use this Library without frameworks.) Do you see the difference between Framework vs Library now? Once you started using McDonald Burger Framework. It would not be easy to switch to BurgerKing Burger Framework. Since you have to change the whole kitchen. If you start to build Web Application using Java Spring Framework, It would be hard(maybe impossible) to change to Ruby on Rails Framework later. But Library, It would be much easier to switch others. or you can just not to use it. A: As I've always described it: A Library is a tool. A Framework is a way of life. A library you can use whatever tiny part helps you. A Framework you must commit your entire project to. A: Based on the definitions given in the book Design Patterns by Erich Gamma et al.: * *library: a set of related procedures and classes making up a reusable implementation; *framework: a set of cooperating classes with template methods making up a reusable specification. It sets the control flow and allows to hook into that flow for tailoring the framework to a specific problem by overriding in a subclass the hook methods called by the template methods in the framework classes. Problem-specific code can use libraries and implement frameworks. A: Library vs Framework Martin Fowler - InversionOfControl Library and Framework are external code towards yours code. It can be file(e.g. .jar), system code(part of OS) etc. Library is a set of helpful code. Main focus is on your code. Library solves a narrow range of tasks. For example - utilities, sort, modularisation your code ->(has) Library API Framework or Inversion of Control(IoC) container[About] is something more. Framework solves a wide range of tasks(domain specific), you delegates this task to framework. IoC - your code depends on framework logic, events... As a result framework calls your code. It forces your code to stick to it's rules(implement/extend protocol/interface/contract), pass lambdas... For example - Tests, GUI, DI frameworks... your code ->(has) and ->(implements) Framework API [iOS Library vs Framework] [DIP vs DI vs IoC] A: Really it depends on what definition you give to the terminology. There's probably a lot of different definitions out there. I think the following are nice explanations based on what I believe this terminology refers to: Deterministic Library A deterministic library holds functions that are deterministic based on either a) function input or b) state that is somehow maintained across function calls. Should logic be dependency-injected into a deterministic library, such logic must conform to a concrete specification such that the output of the library is not affected. Example: A collision-detection library which for some reason depends on a sorting function to aid in these calculations. This sorting function can be configured for optimization purposes (e.g. through dependency-injection, compile-time linkage, etc), but must always conform to the same input/output mapping, so that the library itself remains deterministic. Indeterministic Library An indeterministic library can hold indeterministic functions by communicating with other external indeterministic libraries that it somehow gained access to. I generally refer to indeterministic libraries as services. Example: A poker library which depends on a random-number generator service for shuffling the deck. This is probably a bad example, because, for architectural purposes, we should push the indeterministic aspect of this library to the outside. The poker library could instead become deterministic and unit-testable by taking in a pre-shuffled deck of cards, and it's now the responsibility of the user of this library to shuffle the deck randomly if they so wish. Framework A framework is in-between a deterministic and indeterministic library. Any logic that is dependency-injected into a framework must be deterministic for the lifetime of that function instance, but different function instances of varying logic can be injected on separate executions of framework functions. Example: Functions that operate on lists such as map, filter, sort, reduce, that expect to take in functions that are deterministic but can have varying logic for different executions. Note that this requirement only exists if these list operations advertise themselves as deterministic. In most languages, list operations wouldn't have this constraint. The core logic of such frameworks are deterministic, but are allowed to accept indeterministic logic at the risk of the user. This is generally a messy scenario to deal with, because output can vary widely due to implementation details of the framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/148747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1027" }
Q: Silverlight and Rails Hopefully this will not spark a religious war... We have a web based app in RoR based on an earlier version we build in .net 2.0. So we currently have both .net and RoR skills in house. We want to add a RIA app that interfaces with the rails web app. This should be capable of running offine, with some (perhaps relational) persistence. Considering our inhouse experience we leaning toward leveraging the sliverlight framework over the likes of Flex etc. Would appreciate any thoughts you might have. Thanks Dominic A: If you need the application to run offline you will want to use a pure client technology. So instead of Silverlight vs Flex you are looking at WPF vs AIR. Silverlight and Flex are thin client technologies so neither would fit into RoR very well, unless you used RoR to build web services. A: A choice between Flex/Silverlight should depend on your skills and what you want the RIA to do. There's a fair comparison here: http://extremeblue.wordpress.com/2008/04/28/flex-vs-silverlight-my-views/ But I think you should also look at "pure" javascript solutions like ExtJS or JQuery. We've had good experiences with both those libraries + RoR. JS is hot right now. Javascript engines are getting seriously quick and it's a lovely language (in some ways). Offline persistance can be implemented through Google Gears or Adobe Air. A: Go with SilverLight. It's way cool. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/148752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a list of the common show routines in Vxworks? In the vxWorks shell, there are a number of routines you can use to display information about the system. These routines are usually referred to as show routines because they tend to have the form of "xxxShow". Is there a list of these routines available? A: I work with VxWorks 5.5 and use the symbol lookup function "lkup" to find functions and/or variables that I may be interested in. Execute the following command where ">" is the VxWorks shell prompt. > lkup "Show" This will output a list of symbols that include the "Show" in their name, including all of the "Show" functions. The lkup command is interactive and will prompt you if there is more than one console screen worth of symbols before continuing. A: There is no comprehensive list of all the show routines available. This will depend on your kernel configuration and what components are included. Here are a few show routines that I have found useful in the past. adrSpaceShow(details 0, 1) - Show details of the Address Space, including physical address, User Region address and kernel virtual mapping. envShow(taskId) - Show environment for a given task iosDevShow - Show loaded I/O Devices iosDrvShow - Show I/O Device Driver Function Table iosFdShow - show open File Descriptors memShow - show memory usage statistics moduleShow - show downloaded modules objShowAll - show the list of all the objects in the system (semaphores, tasks, msgQs, etc...) objShow (objectId) - show detailed information about an object
{ "language": "en", "url": "https://stackoverflow.com/questions/148764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to shift items in an array? I have an array of items that are time sensitive. After an amount of time, the last item needs to fall off and a new item is put at the beginning. What is the best way to do this? A: Probably the easiest way to do this with an array is to use a circular index. Rather than always looking at array[n], you would reference array[cIndex] (where cIndex referrs to the item in the array being indexed (cIndex is incremented based on the arraySize (cIndex % arraySize)). When you choose to drop the oldest item in the array, you would simply reference the element located at ((cIndex + (arraySize - 1)) % arraySize). Alternatively, you could use a linkedList approach. A: Use a Queue instead. A: I would suggest using a queue, just a special instance of an array or list. When your timed event occurs, pop the last item from the queue, and then push your new item on. A: By using a Queue, preferably one implemented using a linked-list. A: Have a look at using a Queue rather than a simple array. A: A queue would work if there a fixed number of items. Given that the 'amount of time' is known, how about a SortedDictionary with a DateTime key and override the Add method to remove all items with keys that are too old. A: LinkedList<T> has AddFirst and RemoveLast members that should work perfectly. EDIT: Looking at the Queue docs, it seems they use an internal array. As long as the implementation uses a circular-array type algorithm performance should be fine. A: In csharp 3 you can do: original = new[] { newItem }.Concat( original.Take(original.Count() - 1)).ToArray() But you are probably better off using a specialised datastructure A: Queue is great for FIFO arrays. For generic array handling, use List(T)'s Insert(0, x) and RemoveAt(0) methods to put or remove items in front of the list, for example. A: Technically you need a deque. A queue has items pushed and popped off one end only. A deque is open at both ends. Most languages will allow array manipulation, just remove the first element and put another one on the end. Alternatively you can shift every element, by looping. Just replace each element (starting from the oldest) with its neighbour. Then place the new item in the last element. If you know that your deque won't go above a certain size, then you can make it circular. You'll need two pointers to tell you where the two ends are though. Adding and removing items, will increase/decrease your pointers accordingly. You'll have to detect a buffer overflow condition (i.e. your pointers 'cross'). And you'll have to use modular arithmetic so your pointers go in a circle around the array. Or you could time stamp each element in the array and remove them when they become too 'old'. You can either do this by keeping a separate array indexed in the same way, or by having an array of two element arrays, with the time stamp stored in one of the sub-elements. A: If you're looking for the fastest way of doing this, it's going to be a circular array: you keep track of your current position in the array (ndx), and the end of the array (end), so when you insert an item, you implicitly eliminate the oldest item. A circular array is the fastest implementation of a fixed-size queue that I know of. For example, in C/C++ it would look like this for ints (quitting when you get a 0): int queue[SIZE]; int ndx=0; // start at the beginning of the array int end=SIZE-1; int newitem; while(1){ cin >> newitem; if(!newitem) // quit if it's a 0 break; if(ndx>end) // need to loop around the end of the array ndx=0; queue[ndx] = newitem; ndx++ } Lots of optimization could be done, but if you want to built it yourself, this is the fastest route. If you don't care about performance, use a shipped Queue object because it should be generalized. It may or may not be optimized, and it may not support a fixed size list, so be sure to check the documentation on it before using.
{ "language": "en", "url": "https://stackoverflow.com/questions/148786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the impact of having namespaces in multiple DLLs? I've inherited a VB.net project that generates 2 DLLS: one for the web app, and another for the "business layer". This is for a sub-app of a larger web site. (Using VS2005). The problem is that that something doesn't smell right with the DLL & namespace structure, and I'd like to know if there are any performance impacts. The main web app is "Foo", and generates Foo.dll. Foo.dll contains namespace App.Foo, which contains the classes for all the pages, user controls, etc. There's also a project "FooLib" that generates FooLib.dll. FooLib.dll also contains an App.Foo namespace, which contains a bunch of class definitions. There are a few other namespaces like App.Foo.Data, App.Foo.Logic, etc. Is there anything wrong with this? How does the runtime find a class across multiple DLLs? A: There's nothing wrong with this, the only possible issues may be that 1) developers seeing "App.Foo.Something" may not know which assembly to look in 2) if the same name is used in both, apps compiling against (in c# at least) will get errors about ambiguous type names. As for the runtime, types are specified by assembly and name - the namespace is just part of the typename. So the runtime will have no issue finding the type - when you compile the information about what assembly to find it in is compiled in. A: When your program is compiled the full type name is included along with "evidence". This evidence includes the name of the assembly and versioning information. Otherwise it wouldn't know if you wanted the 1.0 or the 1.1 or the 2.0 version of the class. This same system allows it to find different classes in the same namespace in different assemblies. As far as performance goes, there's not a huge effect. On the beneficial side it means that some of your stuff could be loaded at different times and that's usually the desired effect. Namespaces are about packaging functionality in a way that makes it easy to find. Assemblies are about packaging functionality in a way that is efficient to load. Sometimes they're not the same. A: No, there's nothing wrong with this. Consider, I use a number of custom class libraries, and nearly every one of them has the following namespace structure: .Web.UI.Controls. Which is similar (and suggested by MS as best practice) to System.Web.UI.Controls.. The thing is that the Compiler will know that there is the right namespace in as many DLLs as you assign (it will search for it across both DLLs). The only reason I'd hesitate at making them the exact same in this way is because of possible DEVELOPER confusion. The other reason is in case each namespace has a class named the exact same thing--and this will toss an compiler error until it is resolved with a fully named Namespace declaration. Which is part of the reason why you can Alias namespaces. Aliasing will cure both concepts. The structure for it looks like this: using Foo.App.Foo; using FooLib = FooLib.App.Foo; So, if you then have a Bar class in both Foo.App.Foo and FooLib.App.Foo, to access the application version you would use: bar x = new bar(); For the Library version you'd use: FooLib.bar x = new FooLib.bar(); A: No there is nothing wrong with overlayed namespaces. Take a look at the .net framework itself where many namespaces are overlayed. A: Namespaces are not present at the IL level. The runtime find a class from a pseudo fully qualified name, that is, the name of the type prefixed by its namespace. I don't think there is a technical problem to do that, in fact the .NET Framework itself sometimes uses same namespaces accross several physical assemblies. Namespace are not first class citizen in the .NET world, and I regret that.
{ "language": "en", "url": "https://stackoverflow.com/questions/148790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the standard SQL Query to retrieve the intersection of tables? Selecting the union: select * from table1 union select * from table1_backup What is the query to select the intersection? A: In SQL Server intersect select * from table1 intersect select * from table1_backup A: SELECT * FROM table1 WHERE EXISTS (SELECT * FROM table1_backup WHERE table1.pk = table1_backup.pk) works A: For questions like this, I tend to go back to this visual resource: A Visual Explanation of SQL Joins A: inner join i think: suppose T1 and T2 have the same structure: select T1.* from T1 inner join T2 on T1.pkField = T2.pkField A: "intersect" is also part of standard SQL. Inner join gives a different answer. A: here is a solution for mySQL: CREATE TABLE table1( id INT(10), fk_id INT(10), PRIMARY KEY (id, fk_id), FOREIGN KEY table1(id) REFERENCES another_table(id), FOREIGN KEY table1(fk_id) REFERENCES other_table(id) ); SELECT table1.* FROM table1 as t0 INNER JOIN table1 as a ON (t0.id = a.id and fk_id=1) INNER JOIN table1 as b ON (t0.id = b.id and fk_id=2) INNER JOIN table1 as c ON (t0.id = c.id and fk_id=3) ORDER BY table1.id; Basically you have an table of mathematical subsets (ie. 1={1, 2 ,3}, 2={3, 4, 2}, ... , n={1, 4, 7}) with an attribute id, which is the set number, and fk_ id, which references a PRIMARY KEY of a table of elements, the superset (meaning possible values for the numbers in the curly braces). For those not mathematically inclined, let's pretend you have a table, 'other_ table', which is a list of items, and another table, 'another_ table', which is a list of transaction numbers, and both tables form a many-to-many relationship, thus producing 'table1'. now let's pretend you wanted to know the id's in 'another_ table' which had items 1, 2, and 3. that's the query to do it. A: An intersect on two identical tables a and b can be done in this manner: SELECT a.id, a.name FROM a INNER JOIN b USING (id, name) A: select distinct * from (select * from table1 union select * from table1_backup) A: subqueries?! really? to get the intersection of table1 and table2: SELECT * FROM table1, table2 WHERE table1.pk=table2.pk;
{ "language": "en", "url": "https://stackoverflow.com/questions/148795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to deploy complex SQL solutions through an installer? Part of the setup routine for the product I'm working on installs a database update utility. The utility checks the current version of the users database and (if necessary) executes a series of SQL statements that upgrade the database to the current version. Two key features of this routine: * *Once initiated, it runs without user interaction *SQL operations preserve the integrity of the users data The goal is to keep the setup/database routine as simple as possible for the end user (the target audience is non-technical). However, I find that in some cases, these two features are at odds. For example, I want to add a unique index to one of my tables - yet it's possible that existing data already breaks this rule. I could: * *Silently choose what's "right" for the user and discard (or archive) data; or *Ask the user to understand what a unique index is and get them to choose what data goes where Neither option sounds appealing to me. I could compromise and not create a unique index at all, but that would suck. I wonder what others do in this situation? A: Check out SQL Packager from Red-Gate. I have not personally used it, but these guys make good tools overall and this seems to do what you're looking for. It let's you modify the script to customize the install: http://www.red-gate.com/products/SQL_Packager/index.htm A: You never throw a users data out. One possible option is to try and create the unique index. If the index creation fails, let them know it failed, tell them what they need to research, and provide them a script they can run if they find they have a data error that they choose to fix up.
{ "language": "en", "url": "https://stackoverflow.com/questions/148798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find unused attributes/methods in Visual C++ 2008 Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated. Thanks, Florian Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications. A: Try PC-Lint. It's pretty good at finding redundant code. I haven't tried version 9 yet. Version 8 does take some time to configure. Try the online interactive demo. A: I have not personally used their productivity tools (I use their windows control suit), but it looks like DevExpress has a C++ refactor'er called Refactor! for C++. I didn't immediately spot the features that you are looking for, but maybe they have it? A: The tricky bit is that many functions in C++ have to exist, even if they are not called. Boost especially will cause this, but even the regular STL code can do this. And your code has to play along. You might define a copy ctor because std::vector formally requires it. But if you don't instantiate any std::vector member that actually does copy a T, your copy ctor will remain unused. Even if they don't have to, they often exist for safety. For example, declaring a private copy constructor can prevent an object from unintended copying. Without the private declaration, the compiler would define a public, memberwise copy ctor for you. Now, is this "unused" and do you want to be warned about them? A: Coverage Validator can show unused C++ code (but not attributes). It does it dynamically so you have to 'exersize' the app to get the results: http://successfulsoftware.net/2008/03/10/coverage-validator/ A: PC-Lint is very powerful, but hard to lean. Of course that pretty well describes C and C++ doesn't it? Another tool I think is excellent is Whole Tomato's Visual Assist X which integrates right into the IDE. There are some big gotchas in C++ when searching for unreferenced code: templates, callbacks, and message handlers may be critical to your project but are never directly called. For example the handler for a thread is not called directly, but is a parameter when you create a new thread. The "On_buttonpress" type messages in MFC or WTL projects will also show up as un-called methods. Once you find them you can configure PC-Lint to ignore these, but the first time through its a lot of work. A: nDepend will do it, along with cleaning your house and taking the dog for a walk. There's a nagware version available for free. The following code query language statement will get you a list of unused methods WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE MethodCa == 0 AND !IsPublic AND !IsEntryPoint AND !IsExplicitInterfaceImpl AND !IsClassConstructor AND !IsFinalizer
{ "language": "en", "url": "https://stackoverflow.com/questions/148807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Get a list of files on server with ASP.NET using a picker Is there a component available list FileUpload which shows files on the server, not the client? I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload. A: Nope. There's not. That said, you can use a listbox, and load the files into it. public sub file_DatabindListbox(directoryPath as string) for each fName as string in io.directory(directorypath).getfilenames() dim li as new listitem li.text = io.path.getfilename(fName) li.value = fName myFileListbox.Items.Add(li) next end sub A: You cannot browse through the folders of your server in the same way that you would with the FileUpload components, because... well all the files are located on the server and the "clean dialog" that you refer to is client side. You can write you own code to list the files in a dropdown. But if your files are located in multiple folder and you would like to keep some structure, a TreeView might do the trick with something like this: protected void Page_Load(object sender, EventArgs e) { SetChildFolders(trvFiles.Nodes, @"C:\MyFolder"); } private void SetChildFolders(TreeNodeCollection nodes, string path) { foreach (string directory in Directory.GetDirectories(path)) { DirectoryInfo dirInfo = new DirectoryInfo(directory); TreeNode node = new TreeNode(dirInfo.Name, dirInfo.FullName); SetChildFolders(node.ChildNodes, dirInfo.FullName); SetChildFiles(node.ChildNodes, dirInfo.FullName); trvFiles.Nodes.Add(node); } } private void SetChildFiles(TreeNodeCollection nodes, string path) { foreach (string file in Directory.GetFiles(path)) { FileInfo fileInfo = new FileInfo(file); nodes.Add(new TreeNode(fileInfo.Name, fileInfo.FullName)); } } You can ofcourse style the treeview in many many ways.
{ "language": "en", "url": "https://stackoverflow.com/questions/148817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to emulate C# as-operator in Java There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException? A: Here's an implementation of as, as suggested by @Omar Kooheji: public static <T> T as(Class<T> clazz, Object o){ if(clazz.isInstance(o)){ return clazz.cast(o); } return null; } as(A.class, new Object()) --> null as(B.class, new B()) --> B A: In java 8 you can also use stream syntax with Optional: Object o = new Integer(1); Optional.ofNullable(o) .filter(Number.class::isInstance) .map(Number.class::cast) .ifPresent(n -> System.out.print("o is a number")); A: I'd think you'd have to roll your own: return (x instanceof Foo) ? (Foo) x : null; EDIT: If you don't want your client code to deal with nulls, then you can introduce a Null Object interface Foo { public void doBar(); } class NullFoo implements Foo { public void doBar() {} // do nothing } class FooUtils { public static Foo asFoo(Object o) { return (o instanceof Foo) ? (Foo) o : new NullFoo(); } } class Client { public void process() { Object o = ...; Foo foo = FooUtils.asFoo(o); foo.doBar(); // don't need to check for null in client } } A: You can use the instanceof keyword in place of C#'s is, but there is nothing like as. Example: if(myThing instanceof Foo) { Foo myFoo = (Foo)myThing; //Never throws ClassCastException ... } A: You could write a static utility method like this. I don't think it's terribly readable, but it's the best approximation of what you're trying to do. And if you use static imports it wouldn't be too bad in terms of readability. package com.stackoverflow.examples; public class Utils { @SuppressWarnings("unchecked") public static <T> T safeCast(Object obj, Class<T> type) { if (type.isInstance(obj)) { return (T) obj; } return null; } } Here's a test case that demonstrates how it works (and that it does work.) package com.stackoverflow.examples; import static com.stackoverflow.examples.Utils.safeCast; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import org.junit.Test; public class UtilsTest { @Test public void happyPath() { Object x = "abc"; String y = safeCast(x, String.class); assertNotNull(y); } @Test public void castToSubclassShouldFail() { Object x = new Object(); String y = safeCast(x, String.class); assertNull(y); } @Test public void castToUnrelatedTypeShouldFail() { Object x = "abc"; Integer y = safeCast(x, Integer.class); assertNull(y); } } A: I'm speculating you could propably creas an as operator something like as<T,Type> (left, right) which evaluates to if (typeof(left) == right) return (right)left else return null I'm not sure how you'd do it, I'm a c# at the moment and my Java hat has gotten a bit dusty since I left university.
{ "language": "en", "url": "https://stackoverflow.com/questions/148828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: Will .Net 4.0 include a new CLR or keep with version 2.0 Will .Net 4.0 use a new version of the CLR (v2.1, 3.0) or will it stick with the existing v2.0? Supplementary: Is it possibly going to keep with CLR v2.0 and add DLR v1.0? Update: Whilst this might look like a speculative question which cannot be answered, the VS team appear to be releasing more and more info on VS10 and .Net 4.0 so this may very soon not be the case. (Info available here -> http://msdn.microsoft.com/en-us/vstudio/products/cc948977.aspx) A: Yes, .NET 4.0 will introduce a new version of the CLR (which will also be at 4.0). The DLR will essentially become a part of the core framework, but it will still sit on top of the CLR. A: 4.0 is going to be another side by side release from what I have read. http://blogs.msdn.com/wenlong/archive/2008/09/07/net-4-0-wf-wcf-and-oslo.aspx A: To state it yet another way - according to Microsoft's Visual Studio 2010 and .NET Framework 4 Training Kit - 4.0 will stand on it's own (i.e., will not sit on top of 2.0 like 3.0 or 3.5 did). Brand new framework and brand new CLR. As far as the DLR goes it sits on top of the BCL just like Linq, WinForms and WPF does (i.e., DLR -> BCL -> CLR) To see the PowerPoint slide detailing this click on "Overview" (right-hand side) -> "Lap Around the .NET Framework 4" then click the PowerPoint slide of the same name. Look at the second and third slides.
{ "language": "en", "url": "https://stackoverflow.com/questions/148833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How can I update an application over the network in .NET? I need to install some .NET software on several PC's. This software needs to check each time it is restarted to see if a newer version exists on the server. The end users will have basic user rights and therefore cannot copy files to the 'Program Files' directory. If a newer version exists, the application closes, an updater program copies the file from the server, then it restarts the application. However, I wanted to build my updater so it would be application independent. I.e. I'd send an id to the updater to tell it which application to update. Then I wanted to make it still work if the file server name was changed. I think I can do all this using a service, with admin rights, to copy the files. * *Is there a class that does this kind of thing already? *Am I on the right track when I am thinking of using an installed service? A: The .NET Framework has a built-in feature called clickonce, that does precisely what you want. A: Look at ClickOnce deployment. It covers just about everything you asked for. It doesn't do the update app by ID thing, but it does make sure each app is update to date without you having to write any update code per app. And it won't automatically handle file-server name changes, but you can point your links around as needed. A: The Application Updater Block has worked for me. A: 1) Depends on the .NET version you're using. >=2.0 You can deploy smart apps which can check a network path for an updated version, then it will update if necessary. 2) If you're stuck at 1.1 (Like me :-( ), either a service or a scheduled task that runs on login will work just fine, that's what we do here. We keep a few DB tables that track who has the most recent version of what. -Ian
{ "language": "en", "url": "https://stackoverflow.com/questions/148834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I configure Apache 2.2 for Ruby on Rails in Windows? I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows? All the tutorials I've found seem out of date and are for older versions of Apache/Rails. Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps? A: I'm new to RoR and have been attempting the same thing on Windows Server 2008, here are some additional notes on getting mongrel going as a service: if you get compilation errors when installing mongrel_service: gem install mongrel_service try using a binary instead by specifying your platform: gem install mongrel_service --platform x86-mswin32 Additionally, to actually install the service you need to run this command in your RoR's app directory: mongrel_rails service::install --name MyApp -e production -p 3001 -a 0.0.0.0 (or to remove: mongrel_rails service::remove --name MyApp ) Then you should be able to start/stop the app "MyApp" in your windows services control panel. Hope that helps someone. A: At the moment Mongrel does not work properly with Ruby 1.9 and will throw a "msvcrt-ruby18.dll not found" error when executing the command mongrel_rails. Thin in this case seems to be the only option for now. A: EDIT: At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks. You could also look at proxying to Thin in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here! Configuring Apache + Mongrel on Windows is not significantly different from *nix. Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this: LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so <VirtualHost localhost:80> ServerName www.myapp.comm DocumentRoot "C:/web/myapp/public" ProxyPass / http://www.myapp.com:3000/ ProxyPassReverse / http://www.myapp.com:3000/ ProxyPreserveHost On </VirtualHost> Stick this in your httpd.conf (or httpd-vhost.conf if you're including it). It assumes you're going to run mongrel on port 3000, your Rails root is in C:\web\myapp, and you'll access the app at www.myapp.com. To run the rails app in production mode: mongrel_rails start -p 3000 -e production And away you go (actually mongrel defaults to port 3000 so you could skip -p 3000 if you want). The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the mongrel_service gem. Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info. A: I just wanted to add this article to the list. It explains how to have Apache serve ruby files without the need to install any other applications. http://editrocket.com/articles/ruby_apache_windows.html A: You might want to try Bitnami RubyStack
{ "language": "en", "url": "https://stackoverflow.com/questions/148838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: ASP.net MVC with Ajax Does anybody know of an up to date tutorial on using Ajax with ASP.net MVC? Most of what I can find seems to talk about older versions of MVC and I suspect that this is an area where there has been a lot of change of late. A: Stephen Walter just blogged about this: http://weblogs.asp.net/stephenwalther/archive/2008/09/22/asp-net-mvc-application-building-forums-6-ajax.aspx A: Stephen Walter's post "ASP.NET MVC Application Building: Forums #6 – Ajax" seems to be focused on Microsoft ASP.NET AJAX. A quick search on google for "ASP.NET MVC jquery" brings up several resources on non-MS javascript. I lean towards the non-MS AJAX demos & tutorials as they show platform-agnostic patterns and practices. A: If you're looking for form-releated Ajax support in MVC, check out Scott Hanselman's post: http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx It seems there isn't currently good support for end-to-end validation with Ajax forms. Most articles I've read use a combination of a client-side library and server-side data annotations. I'm hoping the full beta release of MVC will include better support. Also, be sure to note that Microsoft will be including jQuery as an officially supported library for Ajax development. Scott Guthrie annoinced this at: http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/148839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Caching in urllib2? Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own? A: If you don't mind working at a slightly lower level, httplib2 (https://github.com/httplib2/httplib2) is an excellent HTTP library that includes caching functionality. A: This ActiveState Python recipe might be helpful: http://code.activestate.com/recipes/491261/ A: You could use a decorator function such as: class cache(object): def __init__(self, fun): self.fun = fun self.cache = {} def __call__(self, *args, **kwargs): key = str(args) + str(kwargs) try: return self.cache[key] except KeyError: self.cache[key] = rval = self.fun(*args, **kwargs) return rval except TypeError: # incase key isn't a valid key - don't cache return self.fun(*args, **kwargs) and define a function along the lines of: @cache def get_url_src(url): return urllib.urlopen(url).read() This is assuming you're not paying attention to HTTP Cache Controls, but just want to cache the page for the duration of the application A: I've always been torn between using httplib2, which does a solid job of handling HTTP caching and authentication, and urllib2, which is in the stdlib, has an extensible interface, and supports HTTP Proxy servers. The ActiveState recipe starts to add caching support to urllib2, but only in a very primitive fashion. It fails to allow for extensibility in storage mechanisms, hard-coding the file-system-backed storage. It also does not honor HTTP cache headers. In an attempt to bring together the best features of httplib2 caching and urllib2 extensibility, I've adapted the ActiveState recipe to implement most of the same caching functionality as is found in httplib2. The module is in jaraco.net as jaraco.net.http.caching. The link points to the module as it exists at the time of this writing. While that module is currently part of the larger jaraco.net package, it has no intra-package dependencies, so feel free to pull the module out and use it in your own projects. Alternatively, if you have Python 2.6 or later, you can easy_install jaraco.net>=1.3 and then utilize the CachingHandler with something like the code in caching.quick_test(). """Quick test/example of CacheHandler""" import logging import urllib2 from httplib2 import FileCache from jaraco.net.http.caching import CacheHandler logging.basicConfig(level=logging.DEBUG) store = FileCache(".cache") opener = urllib2.build_opener(CacheHandler(store)) urllib2.install_opener(opener) response = opener.open("http://www.google.com/") print response.headers print "Response:", response.read()[:100], '...\n' response.reload(store) print response.headers print "After reload:", response.read()[:100], '...\n' Note that jaraco.util.http.caching does not provide a specification for the backing store for the cache, but instead follows the interface used by httplib2. For this reason, the httplib2.FileCache can be used directly with urllib2 and the CacheHandler. Also, other backing caches designed for httplib2 should be usable by the CacheHandler. A: I was looking for something similar, and came across "Recipe 491261: Caching and throttling for urllib2" which danivo posted. The problem is I really dislike the caching code (lots of duplication, lots of manually joining of file paths instead of using os.path.join, uses staticmethods, non very PEP8'sih, and other things that I try to avoid) The code is a bit nicer (in my opinion anyway) and is functionally much the same, with a few additions - mainly the "recache" method (example usage can be seem here, or in the if __name__ == "__main__": section at the end of the code). The latest version can be found at http://github.com/dbr/tvdb_api/blob/master/cache.py, and I'll paste it here for posterity (with my application specific headers removed): #!/usr/bin/env python """ urllib2 caching handler Modified from http://code.activestate.com/recipes/491261/ by dbr """ import os import time import httplib import urllib2 import StringIO from hashlib import md5 def calculate_cache_path(cache_location, url): """Checks if [cache_location]/[hash_of_url].headers and .body exist """ thumb = md5(url).hexdigest() header = os.path.join(cache_location, thumb + ".headers") body = os.path.join(cache_location, thumb + ".body") return header, body def check_cache_time(path, max_age): """Checks if a file has been created/modified in the [last max_age] seconds. False means the file is too old (or doesn't exist), True means it is up-to-date and valid""" if not os.path.isfile(path): return False cache_modified_time = os.stat(path).st_mtime time_now = time.time() if cache_modified_time < time_now - max_age: # Cache is old return False else: return True def exists_in_cache(cache_location, url, max_age): """Returns if header AND body cache file exist (and are up-to-date)""" hpath, bpath = calculate_cache_path(cache_location, url) if os.path.exists(hpath) and os.path.exists(bpath): return( check_cache_time(hpath, max_age) and check_cache_time(bpath, max_age) ) else: # File does not exist return False def store_in_cache(cache_location, url, response): """Tries to store response in cache.""" hpath, bpath = calculate_cache_path(cache_location, url) try: outf = open(hpath, "w") headers = str(response.info()) outf.write(headers) outf.close() outf = open(bpath, "w") outf.write(response.read()) outf.close() except IOError: return True else: return False class CacheHandler(urllib2.BaseHandler): """Stores responses in a persistant on-disk cache. If a subsequent GET request is made for the same URL, the stored response is returned, saving time, resources and bandwidth """ def __init__(self, cache_location, max_age = 21600): """The location of the cache directory""" self.max_age = max_age self.cache_location = cache_location if not os.path.exists(self.cache_location): os.mkdir(self.cache_location) def default_open(self, request): """Handles GET requests, if the response is cached it returns it """ if request.get_method() is not "GET": return None # let the next handler try to handle the request if exists_in_cache( self.cache_location, request.get_full_url(), self.max_age ): return CachedResponse( self.cache_location, request.get_full_url(), set_cache_header = True ) else: return None def http_response(self, request, response): """Gets a HTTP response, if it was a GET request and the status code starts with 2 (200 OK etc) it caches it and returns a CachedResponse """ if (request.get_method() == "GET" and str(response.code).startswith("2") ): if 'x-local-cache' not in response.info(): # Response is not cached set_cache_header = store_in_cache( self.cache_location, request.get_full_url(), response ) else: set_cache_header = True #end if x-cache in response return CachedResponse( self.cache_location, request.get_full_url(), set_cache_header = set_cache_header ) else: return response class CachedResponse(StringIO.StringIO): """An urllib2.response-like object for cached responses. To determine if a response is cached or coming directly from the network, check the x-local-cache header rather than the object type. """ def __init__(self, cache_location, url, set_cache_header=True): self.cache_location = cache_location hpath, bpath = calculate_cache_path(cache_location, url) StringIO.StringIO.__init__(self, file(bpath).read()) self.url = url self.code = 200 self.msg = "OK" headerbuf = file(hpath).read() if set_cache_header: headerbuf += "x-local-cache: %s\r\n" % (bpath) self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf)) def info(self): """Returns headers """ return self.headers def geturl(self): """Returns original URL """ return self.url def recache(self): new_request = urllib2.urlopen(self.url) set_cache_header = store_in_cache( self.cache_location, new_request.url, new_request ) CachedResponse.__init__(self, self.cache_location, self.url, True) if __name__ == "__main__": def main(): """Quick test/example of CacheHandler""" opener = urllib2.build_opener(CacheHandler("/tmp/")) response = opener.open("http://google.com") print response.headers print "Response:", response.read() response.recache() print response.headers print "After recache:", response.read() main() A: This article on Yahoo Developer Network - http://developer.yahoo.com/python/python-caching.html - describes how to cache http calls made through urllib to either memory or disk. A: @dbr: you may need to add also https responses caching with : def https_response(self, request, response): return self.http_response(request,response)
{ "language": "en", "url": "https://stackoverflow.com/questions/148853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Adding rows to datagridview with existing columns I have a DataGridView with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears. What am I doing wrong? The code is as follows: foreach (SaleItem item in this.Invoice.SaleItems) { DataGridViewRow row = new DataGridViewRow(); gridViewParts.Rows.Add(row); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; row.Cells["colQuantity"] = cellQuantity; DataGridViewCell cellDescription = new DataGridViewTextBoxCell(); cellDescription.Value = item.Part.Description; row.Cells["colDescription"] = cellDescription; DataGridViewCell cellCost = new DataGridViewTextBoxCell(); cellCost.Value = item.Price; row.Cells["colUnitCost1"] = cellCost; DataGridViewCell cellTotal = new DataGridViewTextBoxCell(); cellTotal.Value = item.Quantity * item.Price; row.Cells["colTotal"] = cellTotal; DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell(); cellPartNumber.Value = item.Part.Number; row.Cells["colPartNumber"] = cellPartNumber; } Thanks! A: Just to extend this question, there's also another way to add a row to a DataGridView, especially if the columns are always the same: object[] buffer = new object[5]; List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { buffer[0] = item.Quantity; buffer[1] = item.Part.Description; buffer[2] = item.Price; buffer[3] = item.Quantity * item.Price; buffer[4] = item.Part.Number; rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, buffer); } gridViewParts.Rows.AddRange(rows.ToArray()); Or if you like ParamArrays: List<DataGridViewRow> rows = new List<DataGridViewRow>(); foreach (SaleItem item in this.Invoice.SaleItems) { rows.Add(new DataGridViewRow()); rows[rows.Count - 1].CreateCells(gridViewParts, item.Quantity, item.Part.Description, item.Price, item.Quantity * item.Price, item.Part.Number ); } gridViewParts.Rows.AddRange(rows.ToArray()); The values in the buffer need to be in the same order as the columns (including hidden ones) obviously. This is the fastest way I found to get data into a DataGridView without binding the grid against a DataSource. Binding the grid will actually speed it up by a significant amount of time, and if you have more then 500 rows in a grid, I strongly recommend to bind it instead of filling it by hand. Binding does also come with the bonus that you can keep the Object in tact, f.e. if you want to operate on the selected row, you can do this is the DatagridView is bound: if(gridViewParts.CurrentRow != null) { SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem); // You can use item here without problems. } It is advised that your classes which get bound do implement the System.ComponentModel.INotifyPropertyChanged interface, which allows it to tell the grid about changes. A: Edit: oops! made a mistake on the second line of code. - fixed it. Sometimes, I hate defining the datasource property. I think that whenever you create and set a new row for "row", for some weird reason,the old value get disposed. try not using an instance to hold the rows you create : int i; i = gridViewParts.Rows.Add( new DataGridViewRow()); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; gridViewParts.Rows[i].Cells["colQuantity"] = cellQuantity; It seems like cells work fine with the cell instances. I have no idea why it is different for rows though. More testings may be required...
{ "language": "en", "url": "https://stackoverflow.com/questions/148854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Using P/Invoke correctly I need to call an external dll from c#. This is the header definition: enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 }; LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode ); I've added the enum and the call in C#: public enum WatchMode { WATCH_MODE_SYSTEM = 0, WATCH_MODE_APPLICATION = 1 } [DllImport("AdsWatchdog.dll")] internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode); This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to GetHandle which returns the hHandle mentioned above. I've tried to change the param to an int (ref int watchmode) but get the same error. Doesn anyone know how I can PInvoke the above call? A: You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte signed integer. In the C# world long is a 8 byte signed integer. You should change your C# signature to take an int. ffpf is wrong in saying that you should use an IntPtr here. It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int. If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash. A: The Managed, Native, and COM Interop Team released the PInvoke Interop Assistant on codeplex. Maybe it can create the proper signature. http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120
{ "language": "en", "url": "https://stackoverflow.com/questions/148856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the opposite of 'parse'? I have a function, parseQuery, that parses a SQL query into an abstract representation of that query. I'm about to write a function that takes an abstract representation of a query and returns a SQL query string. What should I call the second function? A: generateQuery, possibly? createQuery? A: Take your pick * *Generate *Dump *Serialize *Emit They each have slightly different connotations. A: The opposite of parse is serialize A: Maybe prettyPrintQuery? A: compose, construct, generate, render,condense, reduce, toSQL, toString depending on the nature of the class and its related operators A: A traditional compiler has two parts: a parser and a code generator. So you could call it "Generate". Of course, it's a little bit different here because the compiler isn't writing source code. (unless it's a precompiler). A: Possibly Format(). or ToSQL() in your instance? A: unParse()? Just kidding, I would go with toQueryString() A: flatten? The parsed query object perhaps represents a condition hierarchy, which you are "flattening" back into a 1 dimensional string. But given that you're going from object to string, really just use toString or toSQL() or something like that. Besides, if you designed it well and are using the right app, you can rename it later and just stick stuff in the comments on what it does. A: I'd say serialize and deserialize, instead of parse and ... A: I would go for ToString(), since you can usually chain-nest them (opposite functions, that let you pass from Class1 to Class2 and vice-versa) DateTime.Parse( DateTime.Parse( myDate.ToString() ).ToString() ); Serialize() looks like a nice choice, but it already has an opposite in Deserialize(). In your specific scenario, as other pointed out, ToSql() is another good choice. A: I'd use render > a = 'html': { 'head': {'title': 'My Page'}, 'body': { 'h1': 'Hello World', 'p': 'This is a Paragraph' } } > b = render(a) > console.log(b) <html> <head> <title>My Page</title> </head> <body> <h1>Hello World</h1> <p>This is a Paragraph</p> </body> </html> Which is IMHO, the opposite to parse() > c = parse(b) { 'html': { 'head': { 'title': 'My Page' } 'body': { 'h1': 'Hello World', 'p': 'This is a Paragraph' } } A: In compiler terminology, the opposite is "unparse". Specifically, parsing turns a stream of tokens into abstract syntax trees, while unparsing turns abstract syntax trees into a stream of tokens. A: Compose? When parsing a query you break it into its constituent parts (tokens, etc.), the reverse would be composing the parts into a string query. A: +1 for Generate, but tack on what you're generating, i.e. GenerateSQL() A: I voted for 'compose' but if you don't like that I would also suggest 'build' A: What about asSQL() or even more asQuery()? A: INHO Serialize, synthesize are good options. Also, as you have named parseQuery, i will go with codeQuery A: I usually use "parse" as a conversion method and, therefore, i can't find a opposite word for "convert". (you can't "deconvert" something, as "unconvert" is a type of conversion itself). thinking this way, the best solution (for me) is having two "parse" methods that receive different arguments. Example (Java): public class FooBarParser{ public Foo parse(Bar bar); public Bar parse(Foo foo); } A: To complement your existing naming, composeQuery looks best. But in the general case, the opposite of parse is ǝsɹɐd A: I think the verb you want is 'compose'. A: I would use one of these: * *ToString() *ToSQL() *Render() A: deparse Deparse is to parse, as: * *decompile is to compile *decompose is to compose *deserialize is to serialize *degroovy is to groovy :) ;) Parsing / deparsing is not change of structure, but conversion. Precise conversion between equivalent text and abstract-syntax-tree formats, maintaining all relationships & structure. "Compose" means change of structure, so is not quite right. It suggests combining from separate independent parts (usually for the first time). Just as "decompose" suggests splitting into independent parts. They change form, not just format. A quick search show's the term's used within: * *Perl: http://perldoc.perl.org/B/Deparse.html *R: http://www.hep.by/gnu/r-patched/r-lang/R-lang_98.html *Common Lisp: http://www.clisp.org/impnotes/dffi.html#c-type-parse *PostgreSQL: http://doxygen.postgresql.org/deparse_8c.html *Eclipse: http://www.eclipse.org/forums/index.php/t/201883/ *Unix Korn Shell: http://www.sourcecodebrowser.com/ksh/93tplus-p/deparse_8c.html A: I think "serialize" is probably the word you want. It means to produce a textual representation of data that can be exported (and imported) from the program. A: The antonym of 'analyze' is 'synthesize'. A: ToQueryString() A: Definitely Render. A: I would call it constructQuery. A: generate or emit, possibly. A: Just to add some stuff. Surely parse is a two way word. You can parse an abstract into a query. You can parse a query into an abstract. The question should be, what do you name the latter part of the method, and because in this instance you're parsing an abstract to make a query you'd call it parseAbstract. To answer the question, parsing has no opposite. A: writeQuery. Parse is the act of reading it from a string and creating the object (let's say 'actual') representation. The opposite would be writing the object into a string. A: .GetSqlQuery() would be my choice A: I believe the answer you're looking for is: "Don't parse SQL or assemble SQL in the first place. Use an Object/Relational Mapper and stop wasting your employer's money by solving problems that have already been solved for quite some time."
{ "language": "en", "url": "https://stackoverflow.com/questions/148857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "147" }
Q: How do I move a TFS file with c# API? I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created. I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line) does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#? A: Here's a quick and dirty code sample that should get you most of the way there. using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.VersionControl.Client; public void MoveFile( string tfsServer, string oldPath, string newPath ) { TeamFoundationServer server = TeamFoundationServerFactory.GetServer( tfsServer, new UICredentialsProvider() ); server.EnsureAuthenticated(); VersionControlServer vcserver = server.GetService( typeof( VersionControlServer ); string currentUserName = server.AuthenticatedUserName; string currentComputerName = Environment.MachineName; Workspace[] wss = vcserver.QueryWorkspaces(null, currentUserName, currentComputerName); foreach (Workspace ws in wss) { foreach ( WorkingFolder wf in wfs ) { bool bFound = false; if ( wf.LocalItem != null ) { if ( oldPath.StartsWith( wf.LocalItem ) ) { bFound = true; ws.PendRename( oldPath, newPath ); break; } } if ( bFound ) break; } } } A: Its pretty simple :). Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace(); workspace.PendRename( oldPath, newPath ); Then you need CheckIn it of course. Use a "workspace.GetPendingChanges()" and "workspace.CheckIn()" methods to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/148867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to exclude a certain member from a MDX call that gets all descendants of a member at a higher level In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level. DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE) I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change. A: When returning members for your hierarchy simply use "-" to exclude a member you don't want. This is how I exclude unknown members: select {[Module].[Hierarchy].[Module].Members - [Module].[Hierarchy].[Module].[Unknown]} on rows, {[Date].[Month-day].[Day Of Month].Members - [Date].[Month-day].[Day Of Month].[Unknown]} on columns from [StatsView] where {[Measures].[Maintainability Index]} A: The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say: EXCEPT( {DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)}, {DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)} ) This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this: EXCEPT({the set i want}, {a set of members i dont want}) You shouldnt need to worry about the third (optional) argument: http://msdn.microsoft.com/en-us/library/ms144900.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/148875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Why does my .NET application crash when run from a network drive? My .NET application fails when run from a network drive even when the very same executable runs perfectly fine from a local hard drive? I tried checking for "Full trust" like so: try { // Demand full trust permissions PermissionSet fullTrust = new PermissionSet( PermissionState.Unrestricted ); fullTrust.Demand(); // Perform normal application logic } catch( SecurityException ) { // Report that permissions were not full trust MessageBox.Show( "This application requires full-trust security permissions to execute." ); } However, this isn't helping, by which I mean the application starts up and the catch block is never entered. However, a debug build shows that the exception thrown is a SecurityException caused by an InheritanceDemand. Any ideas? A: If this is .NET 2.0 or greater, ClickOnce was created to really help with this deployment stuff. I only deploy to network shares using that. A: It indeed has to do with the fact the apps on a network location are less trusted then on your local hdd (due to the default policy of the .NET framework). If I'm not mistaken Microsoft finally corrected this annoyance in .NET 3.5 SP1 (after a lot of developers complaining). I google'd it: .NET Framework 3.5 SP1 Allows managed code to be launched from a network share! A: Did you try Using CasPol to Fully Trust a Share? A: You may have already done this, but you can use CasPol.exe to enable FullTrust for a specified network share. For example cd c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 CasPol.exe -m -ag 1.2 -url file:///N:/your/network/path/* FullTrust More info here. A: This is security built in by microsoft into the .net framework. It's a way of stopping malware to be run locally with full priviliges, so you cannot change this programmatically in the code. What you need to do is increase the trust of specific assemblies. You do this in the .NET Framework Configuration (Control Panel->Administrative Tools), and has to be done on each computer. As with any security measures, it's a pain-in-the-ass, but will help the world to be less infected etc... A: All I had to do was mark the files Read Only (possibly unrelated) and give all permissions except Full Control to Authenticated Users. I was encountering this issue before I did that, when I had the network share only setup for Domain Users. I discovered this workaround because neither the admin shares (\server\C$) nor my own PC's shares had this problem. Edit: App is targeting .NET 3.5, no SP1 here (version 3.5.7283)
{ "language": "en", "url": "https://stackoverflow.com/questions/148879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I append a large amount of rich content (images, formatting) quickly to a control without using tons of CPU? I am using wxWidgets and Visual C++ to create functionality similar to using Unix "tail -f" with rich formatting (colors, fonts, images) in a GUI. I am targeting both wxMSW and wxMAC. The obvious answer is to use wxTextCtrl with wxTE_RICH, using calls to wxTextCtrl::SetDefaultStyle() and wxTextCtrl::WriteText(). However, on my 3ghz workstation, compiled in release mode, I am unable to keep tailing a log that grows on average of 1 ms per line, eventually falling behind. For each line, I am incurring: * *Two calls to SetDefaultStyle() *Two calls two WriteText() *A call to Freeze() and Thaw() the widget When running this, my CPU goes to 100% on one core using wxMSW after filling up roughly 20,000 lines. The program is visibly slower once it reaches a certain threshold, falling further behind. I am open to using other controls (wxListCtrl, wxRichTextCtrl, etc). A: Have you considered limiting the amount of lines in the view? When we had a similar issue, we just made sure never more than 10,000 lines are in the view. If more lines come in at the bottom we remove lines at the top. This was not using WxWidgets, it was using a native Cocoa UI on Mac, but the issue is the same. If a styled text view (with colors, formatting and pretty printing) grows to large, appending more data at the bottom becomes pretty slow. A: Sounds like the control you are using is simply not built for the amount of data you are throwing at it. I would consider building a custom control. Here's some things you could take into account: * *When a new line comes in, you don't need to re-render the previous lines... they don't change and the layout won't change due to the new data. *Try to only keep the visible portion plus a few screens of look-back in memory at a time. This would make it a little lighter... but you will have to do your own scroll management if you want the user to be able to scroll back further than your look-back and make it all appear to be seamless. *Don't necessarily update one line at a time. When there is new data, grab it all and update. If you get 10 lines really quickly, and you update the screen all at once, you might save on some of the overhead of doing it line by line. Hope this helps. A: Derive from wxVListBox. From the docs: wxVListBox is a listbox-like control with the following two main differences from a regular listbox: it can have an arbitrarily huge number of items because it doesn't store them itself but uses OnDrawItem() callback to draw them (so it is a Virtual listbox) and its items can have variable height as determined by OnMeasureItem() (so it is also a listbox with the lines of Variable height).
{ "language": "en", "url": "https://stackoverflow.com/questions/148881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using events rather than exceptions to implement error handling I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } This looked superficially rather odd, especially as the code that calls this needs to hook into the events (there are four or five different ones!). The developer tells me that this way they can refer to the properties of the allocated resource in the error handling code, and that responsibility for cleaning up after the error is kept by this tier. Which makes some kind of sense. The alternative might be something like resource = AllocateLotsOfMemory(); if (SomeCondition()) { BigObject temporary = resource.StatusProperty; resource.FreeLotsOfMemory(); throw new OddException(temporary); } My questions are: * *As this "BigObject" is freed when the exception object is released, do we need this pattern? *Has anyone else experience of this pattern? If so, what pitfalls did you find? What advantages are there? Thanks! A: It seems odd to me too. There are a few advantages - such as allowing multiple "handlers" but the semantics are significantly different to normal error handling. In particular, the fact that it doesn't automatically get propagated up the stack concerns me - unless the error handlers themselves throw an exception, the logic is going to keep going as if everything was still okay when it should probably be aborting the current operation. Another way of thinking about this: suppose the method is meant to return a value, but you've detected an error early. What value do you return? Exceptions communicate the fact that there is no appropriate value to return... A: If you think in terms of "Errors" and "Warnings", I've had lots of luck when reserving events for the "Warning" category and Exceptions for the "Errors" category. The rationale here is that events are optional. No one is holding a gun to your head forcing you to handle them. That's probably okay for warnings, but when you have genuine errors you want to make sure they are taken a little more seriously. Exceptions must be handled, or they'll bubble up and create a nasty message for the user. With regards to your Big Object question: you definitely don't be passing big objects around, but that doesn't mean you can't pass references to big objects around. There's a lot of power in the ability to do that. As an addendum, there's nothing stopping from from raising an event in addition to the exception, but again: if you have a genuine error you want something to force the client developer to handle it. A: This looks really odd to me, firstly IDisposable is your friend, use it. If you are dealing with errors and exceptional situations you should be using exceptions, not events, as its much simpler to grasp, debug and code. So it should be using(var resource = AllocateLotsOfMemory()) { if(something_bad_happened) { throw new SomeThingBadException(); } } A: 1) is it needed? no pattern is absolutely necessary 2) Windows Workflow Foundation does this with all the results from the Workflow Instances running inside the hosted runtime. Just remember that exceptions can happen when trying to raise that event, and you might want to do your cleanup code on a Dispose or a finally block depending on the situation to ensure it runs. A: To be honest, events signaling errors strikes me as scary. There's a disagreement between camps around returning status codes and throwing exceptions. To simplify (greatly) : The status code camp says that throwing exceptions places detecting and handling the error too far from the code causing the error. The exception throwing cap says that users forget to check status codes and exceptions enforce error handling. Errors as events seems like the worst of both approaches. The error cleanup is completely separate from the code causing the error, and notification of error is completely voluntary. Ouch. To me, if the method did not fulfill it's implicit or explicit contract (it didn't do what it was supposed to do), an exception is the apropriate response. Throwing the information you need in the exception seems reasonable in this case. A: Take a look at this post by Udi Dahan. Its an elegant approach for dispatching domain events. The previous poster is correct in saying that you should not be using an event mechanism to recover from fatal errors, but it is a very useful pattern for notification in loosely coupled systems: public class DomainEventStorage<ActionType> { public List<ActionType> Actions { get { var k = string.Format("Domain.Event.DomainEvent.{0}.{1}", GetType().Name, GetType().GetGenericArguments()[0]); if (Local.Data[k] == null) Local.Data[k] = new List<ActionType>(); return (List<ActionType>) Local.Data[k]; } } public IDisposable Register(ActionType callback) { Actions.Add(callback); return new DomainEventRegistrationRemover(() => Actions.Remove(callback) ); } } public class DomainEvent<T1> : IDomainEvent where T1 : class { private readonly DomainEventStorage<Action<T1>> _impl = new DomainEventStorage<Action<T1>>(); internal List<Action<T1>> Actions { get { return _impl.Actions; } } public IDisposable Register(Action<T1> callback) { return _impl.Register(callback); } public void Raise(T1 args) { foreach (var action in Actions) { action.Invoke(args); } } } And to consume: var fail = false; using(var ev = DomainErrors.SomethingHappened.Register(c => fail = true) { //Do something with your domain here } A: The first snippet should probably be resource = AllocateLotsOfMemory(); if (SomeCondition()) { try { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); return; } finally { resource.FreeLotsOfMemory(); } } otherwise you won't free your resources when the event handler throws an exception. As Mike Brown said, the second snippet also has a problem if resource.FreeLotsOfMemory() messes with the contents of resource.StatusProperty instead of setting it to null. A: We have a base Error object and ErrorEvent that we use with the command pattern in our framework to handle non-critical errors (e.g. validation errors). Like exceptions, people can listen for the base ErrorEvent or a more specific ErrorEvent. Also there's a significant difference between your two snippets. if resource.FreeLotsOfMemory() clears out the StatusProperty value rather than just setting it to null, your temporary variable will be holding an invalid object when OddException is created and thrown. The rule of thumb is that Exceptions should only be thrown in non-recoverable situations. I really wish C# supported a Throws clause that's the only thing I really miss from Java. A: Another major problem with this approach are concurrency concerns. With traditional error handling, locks will be released as control moves up the call stack to the error handler in a controlled manner. In this scheme, all locks will still be held when the event is invoked. Any blocking that occurs within the error handler (and you might expect some if there's logging) would be a potential source of deadlocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/148882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Is there a better way to do optional function parameters in JavaScript? I've always handled optional parameters in JavaScript like this: function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } Is there a better way to do it? Are there any cases where using || like that is going to fail? A: Loose type checking Easy to write, but 0, '', false, null and undefined will be converted to default value, which might not be expected outcome. function myFunc(requiredArg, optionalArg) { optionalArg = optionalArg || 'defaultValue'; } Strict type checking Longer, but covers majority of cases. Only case where it incorrectly assigns default value is when we pass undefined as parameter. function myFunc(requiredArg, optionalArg) { optionalArg = typeof optionalArg !== 'undefined' ? optionalArg : 'defaultValue'; } Checking arguments variable Catches all cases but is the most clumsy to write. function myFunc(requiredArg, optionalArg1, optionalArg2) { optionalArg1 = arguments.length > 1 ? optionalArg1 : 'defaultValue'; optionalArg2 = arguments.length > 2 ? optionalArg2 : 'defaultValue'; } ES6 Unfortunately this has very poor browser support at the moment function myFunc(requiredArg, optionalArg = 'defaultValue') { } A: If you're using defaults extensively, this seems much more readable: function usageExemple(a,b,c,d){ //defaults a=defaultValue(a,1); b=defaultValue(b,2); c=defaultValue(c,4); d=defaultValue(d,8); var x = a+b+c+d; return x; } Just declare this function on the global escope. function defaultValue(variable,defaultValue){ return(typeof variable!=='undefined')?(variable):(defaultValue); } Usage pattern fruit = defaultValue(fruit,'Apple'); *PS you can rename the defaultValue function to a short name, just don't use default it's a reserved word in javascript. A: I am used to seeing a few basic variations on handling optional variables. Sometimes, the relaxed versions are useful. function foo(a, b, c) { a = a || "default"; // Matches 0, "", null, undefined, NaN, false. a || (a = "default"); // Matches 0, "", null, undefined, NaN, false. if (b == null) { b = "default"; } // Matches null, undefined. if (typeof c === "undefined") { c = "default"; } // Matches undefined. } The falsy default used with variable a is, for example, used extensively in Backbone.js. A: With ES2015/ES6 you can take advantage of Object.assign which can replace $.extend() or _.defaults() function myFunc(requiredArg, options = {}) { const defaults = { message: 'Hello', color: 'red', importance: 1 }; const settings = Object.assign({}, defaults, options); // do stuff } You can also use defaults arguments like this function myFunc(requiredArg, { message: 'Hello', color: 'red', importance: 1 } = {}) { // do stuff } A: If you need to chuck a literal NULL in, then you could have some issues. Apart from that, no, I think you're probably on the right track. The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive. function myFunction (argArray) { var defaults = { 'arg1' : "value 1", 'arg2' : "value 2", 'arg3' : "value 3", 'arg4' : "value 4" } for(var i in defaults) if(typeof argArray[i] == "undefined") argArray[i] = defaults[i]; // ... } A: Ideally, you would refactor to pass an object and merge it with a default object, so the order in which arguments are passed doesn't matter (see the second section of this answer, below). If, however, you just want something quick, reliable, easy to use and not bulky, try this: A clean quick fix for any number of default arguments * *It scales elegantly: minimal extra code for each new default *You can paste it anywhere: just change the number of required args and variables *If you want to pass undefined to an argument with a default value, this way, the variable is set as undefined. Most other options on this page would replace undefined with the default value. Here's an example for providing defaults for three optional arguments (with two required arguments) function myFunc( requiredA, requiredB, optionalA, optionalB, optionalC ) { switch (arguments.length - 2) { // 2 is the number of required arguments case 0: optionalA = 'Some default'; case 1: optionalB = 'Another default'; case 2: optionalC = 'Some other default'; // no breaks between cases: each case implies the next cases are also needed } } Simple demo. This is similar to roenving's answer, but easily extendible for any number of default arguments, easier to update, and using arguments not Function.arguments. Passing and merging objects for more flexibility The above code, like many ways of doing default arguments, can't pass arguments out of sequence, e.g., passing optionalC but leaving optionalB to fall back to its default. A good option for that is to pass objects and merge with a default object. This is also good for maintainability (just take care to keep your code readable, so future collaborators won't be left guessing about the possible contents of the objects you pass around). Example using jQuery. If you don't use jQuery, you could instead use Underscore's _.defaults(object, defaults) or browse these options: function myFunc( args ) { var defaults = { optionalA: 'Some default', optionalB: 'Another default', optionalC: 'Some other default' }; args = $.extend({}, defaults, args); } Here's a simple example of it in action. A: If you're using the Underscore library (you should, it's an awesome library): _.defaults(optionalArg, 'defaultValue'); A: I don't know why @Paul's reply is downvoted, but the validation against null is a good choice. Maybe a more affirmative example will make better sense: In JavaScript a missed parameter is like a declared variable that is not initialized (just var a1;). And the equality operator converts the undefined to null, so this works great with both value types and objects, and this is how CoffeeScript handles optional parameters. function overLoad(p1){ alert(p1 == null); // Caution, don't use the strict comparison: === won't work. alert(typeof p1 === 'undefined'); } overLoad(); // true, true overLoad(undefined); // true, true. Yes, undefined is treated as null for equality operator. overLoad(10); // false, false function overLoad(p1){ if (p1 == null) p1 = 'default value goes here...'; //... } Though, there are concerns that for the best semantics is typeof variable === 'undefined' is slightly better. I'm not about to defend this since it's the matter of the underlying API how a function is implemented; it should not interest the API user. I should also add that here's the only way to physically make sure any argument were missed, using the in operator which unfortunately won't work with the parameter names so have to pass an index of the arguments. function foo(a, b) { // Both a and b will evaluate to undefined when used in an expression alert(a); // undefined alert(b); // undefined alert("0" in arguments); // true alert("1" in arguments); // false } foo (undefined); A: The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter. function PaulDixonSolution(required, optionalArg){ optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg; console.log(optionalArg); }; PaulDixonSolution("required"); PaulDixonSolution("required", "provided"); PaulDixonSolution("required", null); PaulDixonSolution("required", false); The result is: defaultValue provided null false Those last two are potentially bad. Instead try: function bulletproof(required, optionalArg){ optionalArg = optionalArg ? optionalArg : "defaultValue";; console.log(optionalArg); }; bulletproof("required"); bulletproof("required", "provided"); bulletproof("required", null); bulletproof("required", false); Which results in: defaultValue provided defaultValue defaultValue The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null. A: I tried some options mentioned in here and performance tested them. At this moment the logicalor seems to be the fastest. Although this is subject of change over time (different JavaScript engine versions). These are my results (Microsoft Edge 20.10240.16384.0): Function executed Operations/sec Statistics TypeofFunction('test'); 92,169,505 ±1.55% 9% slower SwitchFuntion('test'); 2,904,685 ±2.91% 97% slower ObjectFunction({param1: 'test'}); 924,753 ±1.71% 99% slower LogicalOrFunction('test'); 101,205,173 ±0.92% fastest TypeofFunction2('test'); 35,636,836 ±0.59% 65% slower This performance test can be easily replicated on: http://jsperf.com/optional-parameters-typeof-vs-switch/2 This is the code of the test: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> Benchmark.prototype.setup = function() { function TypeofFunction(param1, optParam1, optParam2, optParam3) { optParam1 = (typeof optParam1 === "undefined") ? "Some default" : optParam1; optParam2 = (typeof optParam2 === "undefined") ? "Another default" : optParam2; optParam3 = (typeof optParam3 === "undefined") ? "Some other default" : optParam3; } function TypeofFunction2(param1, optParam1, optParam2, optParam3) { optParam1 = defaultValue(optParam1, "Some default"); optParam2 = defaultValue(optParam2, "Another default"); optParam3 = defaultValue(optParam3, "Some other default"); } function defaultValue(variable, defaultValue) { return (typeof variable !== 'undefined') ? (variable) : (defaultValue); } function SwitchFuntion(param1, optParam1, optParam2, optParam3) { switch (arguments.length - 1) { // <-- 1 is number of required arguments case 0: optParam1 = 'Some default'; case 1: optParam2 = 'Another default'; case 2: optParam3 = 'Some other default'; } } function ObjectFunction(args) { var defaults = { optParam1: 'Some default', optParam2: 'Another default', optParam3: 'Some other default' } args = $.extend({}, defaults, args); } function LogicalOrFunction(param1, optParam1, optParam2, optParam3) { optParam1 || (optParam1 = 'Some default'); optParam2 || (optParam1 = 'Another default'); optParam3 || (optParam1 = 'Some other default'); } }; </script> A: Landed to this question, searching for default parameters in EcmaScript 2015, thus just mentioning... With ES6 we can do default parameters: function doSomething(optionalParam = "defaultValue"){ console.log(optionalParam);//not required to check for falsy values } doSomething(); //"defaultValue" doSomething("myvalue"); //"myvalue" A: During a project I noticed I was repeating myself too much with the optional parameters and settings, so I made a class that handles the type checking and assigns a default value which results in neat and readable code. See example and let me know if this works for you. var myCar = new Car('VW', {gearbox:'automatic', options:['radio', 'airbags 2x']}); var myOtherCar = new Car('Toyota'); function Car(brand, settings) { this.brand = brand; // readable and adjustable code settings = DefaultValue.object(settings, {}); this.wheels = DefaultValue.number(settings.wheels, 4); this.hasBreaks = DefaultValue.bool(settings.hasBreaks, true); this.gearbox = DefaultValue.string(settings.gearbox, 'manual'); this.options = DefaultValue.array(settings.options, []); // instead of doing this the hard way settings = settings || {}; this.wheels = (!isNaN(settings.wheels)) ? settings.wheels : 4; this.hasBreaks = (typeof settings.hasBreaks !== 'undefined') ? (settings.hasBreaks === true) : true; this.gearbox = (typeof settings.gearbox === 'string') ? settings.gearbox : 'manual'; this.options = (typeof settings.options !== 'undefined' && Array.isArray(settings.options)) ? settings.options : []; } Using this class: (function(ns) { var DefaultValue = { object: function(input, defaultValue) { if (typeof defaultValue !== 'object') throw new Error('invalid defaultValue type'); return (typeof input !== 'undefined') ? input : defaultValue; }, bool: function(input, defaultValue) { if (typeof defaultValue !== 'boolean') throw new Error('invalid defaultValue type'); return (typeof input !== 'undefined') ? (input === true) : defaultValue; }, number: function(input, defaultValue) { if (isNaN(defaultValue)) throw new Error('invalid defaultValue type'); return (typeof input !== 'undefined' && !isNaN(input)) ? parseFloat(input) : defaultValue; }, // wrap the input in an array if it is not undefined and not an array, for your convenience array: function(input, defaultValue) { if (typeof defaultValue === 'undefined') throw new Error('invalid defaultValue type'); return (typeof input !== 'undefined') ? (Array.isArray(input) ? input : [input]) : defaultValue; }, string: function(input, defaultValue) { if (typeof defaultValue !== 'string') throw new Error('invalid defaultValue type'); return (typeof input === 'string') ? input : defaultValue; }, }; ns.DefaultValue = DefaultValue; }(this)); A: You can use some different schemes for that. I've always tested for arguments.length: function myFunc(requiredArg, optionalArg){ optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg; ... -- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ... And then Paul provided one failing scenario !-) A: In ECMAScript 2015 (aka "ES6") you can declare default argument values in the function declaration: function myFunc(requiredArg, optionalArg = 'defaultValue') { // do stuff } More about them in this article on MDN. This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly. EDIT (2019-06-12): Default parameters are now widely supported by modern browsers. All versions of Internet Explorer do not support this feature. However, Chrome, Firefox, and Edge currently support it. A: Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar... /** * Updates an object's properties with other objects' properties. All * additional non-falsy arguments will have their properties copied to the * destination object, in the order given. */ function extend(dest) { for (var i = 1, l = arguments.length; i < l; i++) { var src = arguments[i] if (!src) { continue } for (var property in src) { if (src.hasOwnProperty(property)) { dest[property] = src[property] } } } return dest } /** * Inherit another function's prototype without invoking the function. */ function inherits(child, parent) { var F = function() {} F.prototype = parent.prototype child.prototype = new F() child.prototype.constructor = child return child } ...this can be made a bit nicer. function Field(kwargs) { kwargs = extend({ required: true, widget: null, label: null, initial: null, helpText: null, errorMessages: null }, kwargs) this.required = kwargs.required this.label = kwargs.label this.initial = kwargs.initial // ...and so on... } function CharField(kwargs) { kwargs = extend({ maxLength: null, minLength: null }, kwargs) this.maxLength = kwargs.maxLength this.minLength = kwargs.minLength Field.call(this, kwargs) } inherits(CharField, Field) What's nice about this method? * *You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass undefined when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested. *When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when CharField calls Field's constructor). *Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will always be used. A: I find this to be the simplest, most readable way: if (typeof myVariable === 'undefined') { myVariable = 'default'; } //use myVariable here Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference. insin's answer is much more advanced, but much more useful for big functions! EDIT 11/17/2013 9:33pm: I've created a package for Node.js that makes it easier to "overload" functions (methods) called parametric. A: Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } Or an alternative idiom: optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; Use whichever idiom communicates the intent best to you! A: This is what I ended up with: function WhoLikesCake(options) { options = options || {}; var defaultOptions = { a : options.a || "Huh?", b : options.b || "I don't like cake." } console.log('a: ' + defaultOptions.b + ' - b: ' + defaultOptions.b); // Do more stuff here ... } Called like this: WhoLikesCake({ b : "I do" }); A: Folks - After looking at these and other solutions, I tried a number of them out using a snippet of code originally from W3Schools as a base. You can find what works in the following. Each of the items commented out work as well and are that way to allow you to experiment simply by removing individual comments. To be clear, it is the "eyecolor" parameter that is not being defined. function person(firstname, lastname, age, eyecolor) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.eyecolor = eyecolor; // if(null==eyecolor) // this.eyecolor = "unknown1"; //if(typeof(eyecolor)==='undefined') // this.eyecolor = "unknown2"; // if(!eyecolor) // this.eyecolor = "unknown3"; this.eyecolor = this.eyecolor || "unknown4"; } var myFather = new person("John", "Doe", 60); var myMother = new person("Sally", "Rally", 48, "green"); var elem = document.getElementById("demo"); elem.innerHTML = "My father " + myFather.firstname + " " + myFather.lastname + " is " + myFather.age + " with " + myFather.eyecolor + " eyes.<br/>" + "My mother " + myMother.firstname + " " + myMother.lastname + " is " + myMother.age + " with " + myMother.eyecolor + " eyes."; A: function Default(variable, new_value) { if(new_value === undefined) { return (variable === undefined) ? null : variable; } return (variable === undefined) ? new_value : variable; } var a = 2, b = "hello", c = true, d; var test = Default(a, 0), test2 = Default(b, "Hi"), test3 = Default(c, false), test4 = Default(d, "Hello world"); window.alert(test + "\n" + test2 + "\n" + test3 + "\n" + test4); http://jsfiddle.net/mq60hqrf/ A: Here is my solution. With this you can leave any parameter you want. The order of the optional parameters is not important and you can add custom validation. function YourFunction(optionalArguments) { //var scope = this; //set the defaults var _value1 = 'defaultValue1'; var _value2 = 'defaultValue2'; var _value3 = null; var _value4 = false; //check the optional arguments if they are set to override defaults... if (typeof optionalArguments !== 'undefined') { if (typeof optionalArguments.param1 !== 'undefined') _value1 = optionalArguments.param1; if (typeof optionalArguments.param2 !== 'undefined') _value2 = optionalArguments.param2; if (typeof optionalArguments.param3 !== 'undefined') _value3 = optionalArguments.param3; if (typeof optionalArguments.param4 !== 'undefined') //use custom parameter validation if needed, in this case for javascript boolean _value4 = (optionalArguments.param4 === true || optionalArguments.param4 === 'true'); } console.log('value summary of function call:'); console.log('value1: ' + _value1); console.log('value2: ' + _value2); console.log('value3: ' + _value3); console.log('value4: ' + _value4); console.log(''); } //call your function in any way you want. You can leave parameters. Order is not important. Here some examples: YourFunction({ param1: 'yourGivenValue1', param2: 'yourGivenValue2', param3: 'yourGivenValue3', param4: true, }); //order is not important YourFunction({ param4: false, param1: 'yourGivenValue1', param2: 'yourGivenValue2', }); //uses all default values YourFunction(); //keeps value4 false, because not a valid value is given YourFunction({ param4: 'not a valid bool' }); A: * *arg || 'default' is a great way and works for 90% of cases *It fails when you need to pass values that might be 'falsy' * *false *0 *NaN *"" For these cases you will need to be a bit more verbose and check for undefined *Also be careful when you have optional arguments first, you have to be aware of the types of all of your arguments A: In all cases where optionalArg is falsy you will end up with defaultValue. function myFunc(requiredArg, optionalArg) { optionalArg = optionalArg || 'defaultValue'; console.log(optionalArg); // Do stuff } myFunc(requiredArg); myFunc(requiredArg, null); myFunc(requiredArg, undefined); myFunc(requiredArg, ""); myFunc(requiredArg, 0); myFunc(requiredArg, false); All of the above log defaultValue, because all of 6 are falsy. In case 4, 5, 6 you might not be interested to set optionalArg as defaultValue, but it sets since they are falsy. A: Correct me if I'm wrong, but this seems like the simplest way (for one argument, anyway): function myFunction(Required,Optional) { if (arguments.length<2) Optional = "Default"; //Your code } A: Those ones are shorter than the typeof operator version. function foo(a, b) { a !== undefined || (a = 'defaultA'); if(b === undefined) b = 'defaultB'; ... } A: function foo(requiredArg){ if(arguments.length>1) var optionalArg = arguments[1]; } A: I suggest you to use ArgueJS this way: function myFunc(){ arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'}) //do stuff, using arguments.requiredArg and arguments.optionalArg // to access your arguments } You can also replace undefined by the type of the argument you expect to receive, like this: function myFunc(){ arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'}) //do stuff, using arguments.requiredArg and arguments.optionalArg // to access your arguments } A: It seems that the safest way - to deal with all \ any falsy types of supplied arguments before deciding to use the default - is to check for the existence\presence of the optional argument in the invoked function. Relying on the arguments object member creation which doesn't even get created if the argument is missing, regardless of the fact that it might be declared, we can write your function like this: function myFunc(requiredArg, optionalArg){ optionalArg = 1 in arguments ? optionalArg : 'defaultValue'; //do stuff } Utilizing this behavior: We can safely check for any missing values on arguments list arbitrarily and explicitly whenever we need to make sure the function gets a certain value required in its procedure. In the following demo code we will deliberately put a typeless and valueless undefined as a default value to be able to determine whether it might fail on falsy argument values, such as 0 false etc., or if it behaves as expected. function argCheck( arg1, arg2, arg3 ){ arg1 = 0 in arguments || undefined; arg2 = 1 in arguments || false; arg3 = 2 in arguments || 0; var arg4 = 3 in arguments || null; console.log( arg1, arg2, arg3, arg4 ) } Now, checking few falsy argument-values to see if their presence is correctly detected and therefore evaluates to true: argCheck( "", 0, false, null ); >> true true true true Which means -they didn't fail the recognition of/as expected argument values. Here we have a check with all arguments missing, which according to our algo should acquire their default values even if they're falsy. argCheck( ); >> undefined false 0 null As we can see, the arguments arg1, arg2, arg3 and the undeclared arg4, are returning their exact default values, as ordered. Because we've now made sure that it works, we can rewrite the function which will actually be able to use them as in the first example by using: either if or a ternary condition. On functions that have more than one optional argument, - a loop through, might have saved us some bits. But since argument names don't get initialized if their values are not supplied, we cannot access them by names anymore even if we've programmatically written a default value, we can only access them by arguments[index] which useless code readability wise. But aside from this inconvenience, which in certain coding situations might be fully acceptable, there's another unaccounted problem for multiple and arbitrary number of argument defaults. Which may and should be considered a bug, as we can no longer skip arguments, as we once might have been able to, without giving a value, in a syntax such as: argCheck("a",,22,{}); because it will throw! Which makes it impossible for us to substitute our argument with a specific falsy type of our desired default value. Which is stupid, since the arguments object is an array-like object and is expected to support this syntax and convention as is, natively or by default! Because of this shortsighted decision we can no longer hope to write a function like this: function argCheck( ) { var _default = [undefined, 0, false, null ], _arg = arguments; for( var x in _default ) { x in _arg ? 1 : _arg[x] = _default[x]; } console.log( _arg[0],_arg[1],_arg[2],_arg[3] ); } in which case, we would be able to write each default value of a desired type in arguments row and be able to at least access them by args.index. For instance this function call would yield: argCheck(); >>undefined 0 false null as defined in our default array of arguments values. However the following is still possible: argCheck({}) >>Object { } 0 false null argCheck({}, []) >>Object { } Array [ ] false null But regretfully not: argCheck("a",,,22); >>SyntaxError: expected expression, got ',' Which would otherwise be logging: >>a 0 false 22 but that's in a better world! However - for the original question - the topmost function will do just fine. e.g.: function argCheck( arg, opt ) { 1 in arguments ? 1 : opt = "default"; console.log( arg, opt ); } p.s.: sorry for not preserving the types of chosen defaults in my argument inputs while writing them.
{ "language": "en", "url": "https://stackoverflow.com/questions/148901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "859" }
Q: How do I properly branch post-commit and revert the trunk in svn? I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later? Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later? A: To be honest, I copy my changes off, revert trunk, branch, then commit my changes to the branch. The main reason being ease of merge later (if you later merge from the trunk to the branch at branch point, the merge will contain a revert of your initial changes). This may not be the "correct" way, as you can always skip revisions when merging, but it is normally much less of a headache for me later on. Disclaimer: I'm no svn guru, so it may be easier for me because I'm doing it wrong - but I do use svn quite a lot. A: There's nothing wrong with following Philip's method, other than it leaves some "cruft" in the revision history. If you wanted to removed them for tidiness sake, and the revisions are at HEAD you could remove them from the repository by following these instructions. Update: Philip's method is better than the one suggested in the question for the reasons he stated. Mine and Philip's methods would be similar, except that insead of reverting the trunk I propose removing the revisions from the revision history. (as I said, this can only be done if all the revisions you want to remove are at the HEAD of the repository.) A: I think Philips method would be something like the following, assuming the last "good" revision was at 100 and you are now at 130, to create the new branch: svn copy -r100 svn://repos/trunk svn://repos/branches/newbranch svn merge -r 100:130 svn://repos/trunk svn://repos/branches/newbranch Note the idea is to preserve the changes made in those revisions so you can apply them back to trunk. To revert trunk: svn merge -r130:100 . svn ci -m 'reverting to r100 (undoing changes in r100-130)' . (It wouldn't matter which order you performed these in, so you could revert trunk before creating the branch.) Then you could switch to the new branch you created in the repo: svn switch svn://repos/branches/newbranch workdir A: I don't have svn available right here but this is how I would try to do it : Determine the point in history where you started committing bad stuff (say revision "100" while you are at "130") svn copy trunk branch # create your branch while preserving history svn copy trunk@100 trunk #replace current revision with revision 100 This should bypass the bad history without adding a reverse merge (actually you are bypassing the history of the trunk between 100 and 130 but you kept a link to that history in the branch and accessing trunk while forcing the rev will still yield the correct history) Then svn switch branch workdir this should work if you want to completely remove the changes from trunk. If there are small ones you want to keep you can cherry pick them again from branch to trunk (if you use svn 1.5 it will track merge points and avoid spurious conflicts)
{ "language": "en", "url": "https://stackoverflow.com/questions/148902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is the DLR going to be capable of compiling client-side code? Is the DLR intended to be used to compile code exclusively prior to distribution or will it potentially be used to compile client-side Javascript in a JIT fashion? A: The CLR already compiles and JITs code, and from what I gather the DLR will be built entirely on top of the CLR. So I guess the answer is 'neither'.
{ "language": "en", "url": "https://stackoverflow.com/questions/148903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Returning form, querystring, cookie values by priority in ASP.NET MVC I'm wondering why query string is preferred when getting values from user request. Where? 1) Code of System.Web.Mvc.DefaultModelBinder looks like this (only part of it): HttpRequestBase request = controllerContext.HttpContext.Request; if (request != null) { if (request.QueryString != null) { values = request.QueryString.GetValues(modelName); attemptedValue = request.QueryString[modelName]; } if ((values == null) && (request.Form != null)) { invariantCulture = CultureInfo.CurrentCulture; values = request.Form.GetValues(modelName); attemptedValue = request.Form[modelName]; } } 2) If I have a method in controller with this signature: public ActionResult Save(int? x, string y) {... the parameters (x, y) are bound to values from query string, not from form. I would expect that values from Request.From have higher priority than from Request.QueryString. Edit: I see that the second case is caused by the first one (DefaultModelBinder), am I right? What's the motivation behind? A: Consistency probably. The query string has been the default since the original ASP model. If you want to get data the form you have always needed to get the values from there explicitly if the same names are also on the querystring.
{ "language": "en", "url": "https://stackoverflow.com/questions/148906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which Dependency Injection Tool Should I Use? I am thinking about using Microsoft Unity for my Dependency Injection tool in our User Interface. Our Middle Tier already uses Castle Windsor, but I am thinking I should stick with Microsoft. Does anyone have any thoughts about what the best Dependency Injection tool is? * *Autofac *Castle MicroKernel/Windsor *PicoContainer.NET *Puzzle.NFactory *Spring.NET *StructureMap *Ninject *Unity *Simple Injector *NauckIT.MicroKernel *WINTER4NET *ObjectBuilder A: Having recently spiked the use of 6 of these (Windsor, Unity, Spring.Net, Autofac, Ninject, StructureMap) I can offer a quick summary of each, our selection criteria and our final choice. Note: we did not look at PicoContainer.Net as one of our team considered the .Net port to be quite poor from the Java version. We also did not look at ObjectBuilder, as Unity is built on top of ObjectBuilder2 and was considered to be a superior choice by default. Firstly, I can say that more or less all of them are all pretty similar and it really comes down to what really works best for you, and your specific requirements. Our requirements included: Requirements * *Constructor based injection (we intend not to use property, field or method injection) *Programmable configuration (not XML) *container hierarchies (one per application, per request and per session to more implicitly bind component lifetimes scope to container) *component lifetime management (for more granular scoping eg transient / singleton) *injection from interface to type or concrete instance (eg ILogger -> typeof(FileLogger) or ILogger -> new FileLogger() ) *advanced component creation / "creaton event mechanism" for pre/post initialisation *correct disposal of IDisposable components on container tear down *well documented and/or online information readily available Note: whilst performance was a requirement it was not factored in the selection as it seemed that all containers reviewed were similar according to this benchmark Test Each container was used in a typical Asp.Net webforms project (as this was our target application type). We used a single simple page with with a single simple user control, each inheriting from a base page / base control respectively. We used 1 container on the BasePage for a "per request" scope container and 1 on the global.asax for an "application" scope and attempted to chain them together so dependencies could be resolved from both containers. Each web application shared a contrived set of domain objects simulating multi-levels of dependency, scope type (singleton/transient) and also of managed and unmanaged classes (IDisposable required). The "top level" dependency components were manually injected from the methods on the BasePage. Results Windsor - Satisfied all the criteria and has a good case history, blogger community and online documentation. Easy to use and probably the defacto choice. Advanced component creation through Factory facility. Also allowed chaining of individually created containers. Spring.Net - Verbose and unhelpful documentation and no-obvious / easy for programmable configuration. Did not support generics. Not chosen Ninject - Easy to use with good clear documentation. Powerful feature set fulfilling all our requirements except container hierarchies so unfortunately was not chosen. StructureMap - Poorly documented, although had quite an advanced feature set that met all of our requirements, however there was no built-in mechanism for container hierarchies although could be hacked together using for loops see here The lambda expression fluent interface did seem a little over complicated at first, although could be encapsulated away. Unity - Well documented, easy to use and met all our selection criteria and has an easy extension mechanism to add the pre/post creation eventing mechanism we required. Child containers had to be created from a parent container. Autofac - Well documented and relatively easy to use, although lambda expression configuration does seem a little over complicated however, again, can be easily encapsulated away. Component scoping is achieved through a "tagging" mechanism and all components are configured up front using a builder which was a little inconvenient. Child containers were created from a parent and assigned components from a "tag". Allowed generic injection. Conclusion Our final choice was between Windsor and Unity, and this time around we chose Unity due to its ease of use, documentation, extension system and with it being in "production" status. A: I started using Autofac a year ago and haven't looked back since.. A: I'm an Autofac fan, but both Windsor and Unity will do a good job (though Windsor is more capable than unity and doesn't require attributing your code). There's plenty of good non technical reasons for sticking to a single container in a system though. A: Use what works. Most have features that are unique to them, and almost all are more feature-rich than Unity. If unity is all that you need, you can certainly use it. Using Microsoft's unity just because it's from Microsoft is a poor way to make a decision. Think about what you need and why, and choose the one that fits your needs. However, I second the notion of sticking to a single container if possible. A: I've been using the Managed Extensibility Framework and found it quite easy to work with. It's been integrated into .NET 4. A: Sticking to one container is not really important, if your system has been designed with the IoC/DI in mind. With the proper approach you can easily change the IoC library down the road. And, of course, the container has to provide enough flexibility to support common widely used scenarios (lifecycle management, proper container nesting, XML and code configuration, interception, fast resolution). I'd recommend to pick between Castle (widely used and have a lot of integration libraries) and Autofac (lightweight, fast and has proper container nesting, but is not that widely used) There is a comprehensive list of IoC containers by Hanselman PS: You do not want to use Unity A: Here is a good article which compares .NET IoC containers. http://blog.ashmind.com/index.php/2008/08/19/comparing-net-di-ioc-frameworks-part-1/ A: Unless you already have experience and a personal preferance for a particular sub-technology utilized by one of the possible IoC container solutions, they all function well and I don't see any one in particular with a "killer function" that makes it stand out from the others. Unity is probably the best fit for solutions already utilizing the P&P Enterprise Library 4.x... A: IoC Container Benchmark - Performance comparison has performance and features comparison tables for 20+ products and keep them up-to-date. The conclusion from the article: SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try! Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.
{ "language": "en", "url": "https://stackoverflow.com/questions/148908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Send query results to Excel from ASP.NET website We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel. What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button. A: Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from here //for demo purpose, lets create a small datatable & populate it with dummy data System.Data.DataTable workTable = new System.Data.DataTable(); //The tablename specified here will be set as the worksheet name of the generated Excel file. workTable.TableName = "Customers"; workTable.Columns.Add("Id"); workTable.Columns.Add("Name"); System.Data.DataRow workRow; for (int i = 0; i <= 9; i++) { workRow = workTable.NewRow(); workRow[0] = i; workRow[1] = "CustName" + i.ToString(); workTable.Rows.Add(workRow); } //...and lets put DataTable2ExcelString to work string strBody = DataTable2ExcelString(workTable); Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); Response.AppendHeader("Content-disposition", "attachment; filename=my.xls"); Response.Write(strBody); A: If you create a page that is just a table with the results and set the page's content type to "application/vnd.ms-excel", then the output will be in Excel. Response.ContentType = "application/vnd.ms-excel"; If you want to force a save, you would do something like the following: Response.AddHeader("Content-Disposition", "attachment; filename=somefilename.xls"); A: I got a utils function that does this already. Once you put it into a datatable, you can export it with the Response using public static void DataTabletoXLS(DataTable DT, string fileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "utf-16"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; string tab = ""; foreach (DataColumn dc in DT.Columns) { HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", "")); tab = "\t"; } HttpContext.Current.Response.Write("\n"); int i; foreach (DataRow dr in DT.Rows) { tab = ""; for (i = 0; i < DT.Columns.Count; i++) { HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", "")); tab = "\t"; } HttpContext.Current.Response.Write("\n"); } HttpContext.Current.Response.End(); } A: I'd recommend using a filehandler (.ashx) The only issue is creating the excel file from the DataTable. There are a lot of third party products that will do this for you (e.g. Infragistics provides a component that does just this). One thing I highly recommend against is using the Excel interop on your server...it's very heavyweight and isn't supported. A: Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user. //write the column headers for (int cIndex = 1; cIndex < 1 + columns; cIndex++) sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption); if (rows > 0) { //select the range where the data will be pasted Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]); //Convert the datatable to an object array object[,] workingValues = new object[rows, columns]; for (int rIndex = 0; rIndex < rows; rIndex++) for (int cIndex = 0; cIndex < columns; cIndex++) workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString(); r.Value2 = workingValues; } A: I would use a handler for the .xls file extension and a free component to convert the DataTable to native xls format. The component from this site http://www.csvreader.com/ does more that the URL implies. The newest version of excel will complain about an HTML formatted XLS file. Also keep in mind the size of the data being returned. Your web server should use compression for this extension and your code should check if the number of rows returned is greater than what excel can display in one worksheet; multiple sheets may be required. http://www.mrexcel.com/archive2/23600/26869.htm A: Kindly use this code to resolve your problem.This code will convert excel sheet to text format.Hope this will solve your problem grdSrcRequestExport.RenderControl(oHtmlTextWriter); string s = ""; s=oStringWriter.ToString().Replace("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">", ""); s="<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=us-ascii\"><meta name=ProgId content=Excel.Sheet><meta name=Generator content=\"Microsoft Excel 11\"><table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'>"+s.ToString()+"</table></body></html>"; //Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(); Response.Write(s);
{ "language": "en", "url": "https://stackoverflow.com/questions/148945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Does mysqldump --password really do what it says? I'm trying to use mysqldump to dump a schema, and it mostly works but I ran into one curiosity: the -p or --password option seems like it is doing something other than setting the password (as the man page and --help output say it should). Specifically, it looks like it's doing what is indicated here: http://snippets.dzone.com/posts/show/360 - that is, setting the database to dump. To support my somewhat outlandish claim, I can tell you that if I do not specify the --password (or -p) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the --password option is dumped (or an error is given in the usual case that a password not matching any database name was specified). Here's a transcript: $ mysqldump -u test -h myhost --no-data --tables --password lose Enter password: -- MySQL dump 10.10 mysqldump: Got error: 1044: Access denied for user 'test'@'%' to database 'lose' when selecting the database So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using expect??? I'm using mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486). A: From man mysqldump: --password[=password], -p[password] The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, you are prompted for one. Specifying a password on the command line should be considered insecure. See Section 6.6, "Keeping Your Password Secure". Syntactically, you are not using the --password switch correctly. As such, the command line parser is seeing your use of "lose" as a stand-alone argument which mysqldump interprets as the database name as it would if you were to attempt a simpler command like mysqldump lose To correct this, try using --password=lose or -plose or simply use -p or --password and type the password when prompted. A: Try placing a '=' in between --password lose like: --password=lose If you use -p, then there can be no space between the -p and the password, i.e. '-plose'. A: I am not sure if it works for the --password version, but if you use -p you can specify the password immediately afterwards (the key is not to include a space): mysqldump -pmypassword ... A: Did you try --password=whatever-password-is ? Perhaps I'm missing the question, but that is what I do to run the tool. A: Another option is to create the file ~/.my.cnf (permissions need to be 600). Add this to the .my.cnf file [client] password=lose This lets you connect as a MySQL user who requires a password without having to actually enter the password. You don't even need the -p or --password. Very handy for scripting mysql & mysqldump commands. A: I found that this happens if your password has special characters in it. The mysql password here has a ! in it, so I have to do ==password='xxx!xxxx' for it to work corrrectly. Note the ' marks. A: If you use the -p or --password without an argument, you will get a prompt, asking to insert a password. If you want to indicate a password on the command line, you must use -pYOURPASSWORD or --password=YOURPASSWORD. Notice that there is no space after -p, and there is an "=" sign after --password. In your example, mysqldump asks for a password, and then treats "lose" as the database name. If that was your password, you should have included a "=" A: The -p option does not require an argument. You just put -p or --password to indicate that you're going to use a password to access the database. The reason it's dumping the database named whatever you put after -p is that the last argument for mysqldump should be the name of the database you want to dump (or --all-databases if you want them all). @Nathan's answer is also true. You can specify the password immediately following the -p switch (useful in scripts and such where you can't enter it by hand after executing the command). A: --password[=password] Here is the documentation A: Maybe your user "test" doesn't have the permission to access your "lose" database?
{ "language": "en", "url": "https://stackoverflow.com/questions/148951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Yui, how to remove the margins for a 2 column layout? I want the 2 columns to touch ie. remove the margins, how can I do this? My code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>testing</TITLE> <!-- css --> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css"> <!-- js --> <script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/utilities/utilities.js"></script> <style> .yui-b { background-color: #eeeeee; } </style> </HEAD> <BODY> <div id="doc3" class="yui-t1"> <!-- change class to change preset --> <div id="hd">header</div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> bd.main </div> </div> <div class="yui-b">bd.other</div> </div> <div id="ft">footer</div> </div> </BODY> </HTML> A: Add a class to the right column and set margin-left to 0. If that doesn't work you might have to increase the width by 1 or 2%. You can use firebug to check the applied styles and change them on the fly. A: Notice that you're using YUI (Yahoo UI). Look for the YUI reset.css. Every browser has potentially different margin, padding, font-size defaults. You should really start every web app with a reset.css file like that to bring everything to a common denominator. Otherwise you might find you "fix" the issue, only for it to appear again when viewed from another machine / platform. Should hopefully start you off with all block elements having no margins or padding and then you can rather add margins and padding back in where you need it. A: Notice that you're using YUI (Yahoo UI).
{ "language": "en", "url": "https://stackoverflow.com/questions/148955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keeping GUIs responsive during long-running tasks Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. Here's a good discussion of how to do this in wxPython. To summarize, there are 3 ways: * *Use threads *Use wxYield *Chunk the work and do it in the IDLE event handler Which method have you found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome. A: Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run. Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have. Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units! A: I think delayedresult is what you are looking for: http://www.wxpython.org/docs/api/wx.lib.delayedresult-module.html See the wxpython demo for an example. A: Threads. They're what I always go for because you can do it in every framework you need. And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks. A: Threads or processes depending on the application. Sometimes it's actually best to have the GUI be it's own program and just send asynchronous calls to other programs when it has work to do. You'll still end up having multiple threads in the GUI to monitor for results, but it can simplify things if the work being done is complex and not directly connected to the GUI. A: Threads - Let's use a simple 2-layer view (GUI, application logic). The application logic work should be done in a separate Python thread. For Asynchronous events that need to propagate up to the GUI layer, use wx's event system to post custom events. Posting wx events is thread safe so you could conceivably do it from multiple contexts. Working in the other direction (GUI input events triggering application logic), I have found it best to home-roll a custom event system. Use the Queue module to have a thread-safe way of pushing and popping event objects. Then, for every synchronous member function, pair it with an async version that pushes the sync function object and the parameters onto the event queue. This works particularly well if only a single application logic-level operation can be performed at a time. The benefit of this model is that synchronization is simple - each synchronous function works within it's own context sequentially from start to end without worry of pre-emption or hand-coded yielding. You will not need locks to protect your critical sections. At the end of the function, post an event to the GUI layer indicating that the operation is complete. You could scale this to allow multiple application-level threads to exist, but the usual concerns with synchronization will re-appear. edit - Forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the GUI code. The modularity helps if you ever decide to use a different framework or use provide a command-line version of the app. To do this, you will need an intermediate event dispatcher (application level -> GUI) that is implemented by the GUI layer. A: Working with Qt/C++ for Win32. We divide the major work units into different processes. The GUI runs as a separate process and is able to command/receive data from the "worker" processes as needed. Works nicely in todays multi-core world. A: This answer doesn't apply to the OP's question regarding Python, but is more of a meta-response. The easy way is threads. However, not every platform has pre-emptive threading (e.g. BREW, some other embedded systems) If possibly, simply chunk the work and do it in the IDLE event handler. Another problem with using threads in BREW is that it doesn't clean up C++ stack objects, so it's way too easy to leak memory if you simply kill the thread. A: I use threads so the GUI's main event loop never blocks. A: For some types of operations, using separate processes makes a lot of sense. Back in the day, spawning a process incurred a lot of overhead. With modern hardware this overhead is hardly even a blip on the screen. This is especially true if you're spawning a long running process. One (arguable) advantage is that it's a simpler conceptual model than threads that might lead to more maintainable code. It can also make your code easier to test, as you can write test scripts that exercise these external processes without having to involve the GUI. Some might even argue that is the primary advantage. In the case of some code I once worked on, switching from threads to separate processes led to a net reduction of over 5000 lines of code while at the same time making the GUI more responsive, the code easier to maintain and test, all while improving the total overall performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/148963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Encrypting Salary value in ASP .NET 2.0 and SQL Server 2005 I have an ASP .NET 2.0 website connected to a SQL Server 2005 database. The site is pretty simple and stores information about staff, including salary. What is the best way to encrypt the salary value so no-one (including myself) can ever see what it is, except for the authorised staff using the web-app? I don't want to encrypt / decrypt on the SQL Server because I could just run SQL Profiler to view the information, so I assume the encrypt/decrypt happens in the BLL on the web server? Also, do I need SSL to stop someone sniffing HTTP responses between the browser and the web server? Many thanks! Anthony A: SSL is probably your best bet to keep someone from sniffing, but be aware that it is still possible. As for the other bit, SQL Server 2005 supports table-level encryption out of the box. Here's an article on it. You could create a SALARY table that is linked to an employee and keep that table encrypted. A: Developers of the webapp could still access the salary figures -- it's all a matter of trust. To counter that, you could switch to the model where the encryption/decryption happens on the client-side, but this is more cumbersome and still not 100% secure. Security is always a trade-off with convenience. You should use TLS/SSL (i.e., HTTPS) so that eavesdropping on the HTTP traffic is harder to perform. An attack you may consider, is replacing your own encrypted salary figure with that of the person you are interested in, then calling up the accounting department and asking what your current salary figure is. One way to negate the attack is to have the contents of the encrypted salary field reference the person it belongs to. A: There are many encryption methods you could use here in your code. Make sure you choose one that takes a key and a "salt" (as opposed to just using the same key each time). If you use the same key (without a salt) each time you encrypt a salary, then two employees with the same salary will display the same encrypted value in the database, compromising the security of the salary info. You could use each employee's unique ID as the salt. A: You definitely need SSL to prevent sniffing of the sensitive web traffic (not to mention logins), but that doesn't solve your server-side encryption problem. To make it impossible for you as the developer to access the data is a tough nut to crack. In order for it to really work, all the encryption/decryption needs to be done only on machines that you have no access to. Theoretically you would have to make some sort of browser extension that decrypts the salary data on the client machines. Your employer would have to trust you enough to not put a backdoor into the client-side code (or at least hold the possibility of a code audit over your head). In most cases, it is easier to trust the developer to not disclose the data. It's a good idea to keep it on a need-to-know basis, but ultimately some people need to know. (For instance, accounting people see salary data all the time.) A: You definitely want to use SSL for the transportation security. You could also setup IPSec for the transportation between the web server and database server. As for securing in the database, SQL Server 2005 has several encryption functions: 1) EncryptByAsymKey - http://msdn.microsoft.com/en-us/library/ms186950.aspx 2) EncryptByKey - http://msdn.microsoft.com/en-us/library/ms174361.aspx 3) EncryptByPassPhrase - http://msdn.microsoft.com/en-us/library/ms190357.aspx 4) EncryptByCert - http://msdn.microsoft.com/en-us/library/ms188061.aspx Obviously, all of these have an associated decrypt function. You can store the key or whatever you choose on the web server (in the machine.config or web.config or somewhere) and then pass it to your stored procedures (or along with your sql somehow) for the encryption.
{ "language": "en", "url": "https://stackoverflow.com/questions/148964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Windows batch files: .bat vs .cmd? As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some gotcha awaiting me by using the wrong suffix? A: everything working in a batch should work in a cmd; cmd provides some extensions for controlling the environment. also, cmd is executed by in new cmd interpreter and thus should be faster (not noticeable on short files) and stabler as bat runs under the NTVDM emulated 16bit environment A: From this news group posting by Mark Zbikowski himself: The differences between .CMD and .BAT as far as CMD.EXE is concerned are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL only on errors. In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be: * *left alone at its non-0 value in a .bat file *reset to 0 in a .cmd file. A: Here is a compilation of verified information from the various answers and cited references in this thread: *command.com is the 16-bit command processor introduced in MS-DOS and was also used in the Win9x series of operating systems. *cmd.exe is the 32-bit command processor in Windows NT (64-bit Windows OSes also have a 64-bit version). cmd.exe was never part of Windows 9x. It originated in OS/2 version 1.0, and the OS/2 version of cmd began 16-bit (but was nonetheless a fully fledged protected mode program with commands like start). Windows NT inherited cmd from OS/2, but Windows NT's Win32 version started off 32-bit. Although OS/2 went 32-bit in 1992, its cmd remained a 16-bit OS/2 1.x program. *The ComSpec env variable defines which program is launched by .bat and .cmd scripts. (Starting with WinNT this defaults to cmd.exe.) *cmd.exe is backward compatible with command.com. *A script that is designed for cmd.exe can be named .cmd to prevent accidental execution on Windows 9x. This filename extension also dates back to OS/2 version 1.0 and 1987. Here is a list of cmd.exe features that are not supported by command.com: * *Long filenames (exceeding the 8.3 format) *Command history *Tab completion *Escape character: ^ (Use for: \ & | > < ^) *Directory stack: PUSHD/POPD *Integer arithmetic: SET /A i+=1 *Search/Replace/Substring: SET %varname:expression% *Command substitution: FOR /F (existed before, has been enhanced) *Functions: CALL :label Order of Execution: If both .bat and .cmd versions of a script (test.bat, test.cmd) are in the same folder and you run the script without the extension (test), by default the .bat version of the script will run, even on 64-bit Windows 7. The order of execution is controlled by the PATHEXT environment variable. See Order in which Command Prompt executes files for more details. References: * *cmd.exe *command.com wikipedia: Comparison of command shells A: I believe if you change the value of the ComSpec environment variable to %SystemRoot%system32\cmd.exe(CMD) then it doesn't matter if the file extension is .BAT or .CMD. I'm not sure, but this may even be the default for WinXP and above. A: .cmd and .bat file execution is different because in a .cmd errorlevel variable it can change on a command that is affected by command extensions. That's about it really. A: No - it doesn't matter in the slightest. On NT the .bat and .cmd extension both cause the cmd.exe processor to process the file in exactly the same way. Additional interesting information about command.com vs. cmd.exe on WinNT-class systems from MS TechNet (http://technet.microsoft.com/en-us/library/cc723564.aspx): This behavior reveals a quite subtle feature of Windows NT that is very important. The 16-bit MS-DOS shell (COMMAND.COM) that ships with Windows NT is specially designed for Windows NT. When a command is entered for execution by this shell, it does not actually execute it. Instead, it packages the command text and sends it to a 32-bit CMD.EXE command shell for execution. Because all commands are actually executed by CMD.EXE (the Windows NT command shell), the 16-bit shell inherits all the features and facilities of the full Windows NT shell. A: RE: Apparently when command.com is invoked is a bit of a complex mystery; Several months ago, during the course of a project, we had to figure out why some programs that we wanted to run under CMD.EXE were, in fact, running under COMMAND.COM. The "program" in question was a very old .BAT file, that still runs daily. We discovered that the reason the batch file ran under COMMAND.COM is that it was being started from a .PIF file (also ancient). Since the special memory configuration settings available only through a PIF have become irrelevant, we replaced it with a conventional desktop shortcut. The same batch file, launched from the shortcut, runs in CMD.EXE. When you think about it, this makes sense. The reason that it took us so long to figure it out was partially due to the fact that we had forgotten that its item in the startup group was a PIF, because it had been in production since 1998. A: Still, on Windows 7, BAT files have also this difference : If you ever create files TEST.BAT and TEST.CMD in the same directory, and you run TEST in that directory, it'll run the BAT file. C:\>echo %PATHEXT% .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC C:\Temp>echo echo bat > test.bat C:\Temp>echo echo cmd > test.cmd C:\Temp>test C:\Temp>echo bat bat C:\Temp> A: These answers are a bit too long and focused on interactive use. The important differences for scripting are: * *.cmd prevents inadvertent execution on non-NT systems. *.cmd enables built-in commands to change Errorlevel to 0 on success. Not that exciting, eh? There used to be a number of additional features enabled in .cmd files, called Command Extensions. However, they are now enabled by default for both .bat and .cmd files under Windows 2000 and later. Bottom line: in 2012 and beyond, I recommend using .cmd exclusively. A: Since the original post was regarding the consequences of using the .bat or .cmd suffix, not necessarily the commands inside the file... One other difference between .bat and .cmd is that if two files exist with the same file name and both those extensions, then: * *entering filename or filename.bat at the command line will run the .bat file *to run the .cmd file, you have to enter filename.cmd A: a difference: .cmd files are loaded into memory before being executed. .bat files execute a line, read the next line, execute that line... you can come across this when you execute a script file and then edit it before it's done executing. bat files will be messed up by this, but cmd files won't. A: The extension makes no difference. There are slight differences between COMMAND.COM handling the file vs CMD.EXE.
{ "language": "en", "url": "https://stackoverflow.com/questions/148968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "870" }
Q: Visual Studio keyboard-shortcut for automatically adding the 'using' statement What is the keyboard-shortcut that expands the menu, from the little red line, and offers the option to have the necessary using statement appended to the top of the file? A: * *Context Menu key (one one with the menu on it, next to the right Windows key) *Then choose "Resolve" from the menu. That can be done by pressing "s". A: Ctrl + . shows the menu. I find this easier to type than the alternative, Alt + Shift + F10. This can be re-bound to something more familiar by going to Tools > Options > Environment > Keyboard > Visual C# > View.QuickActions A: Alt + Shift + F10 will show the menu associated with the smart tag. A: I can highly recommend checking out the Visual Studio plugin ReSharper. It has a QuickFix feature that does the same (and a lot more). But ReSharper doesn't require the cursor to be located on the actual code that requires a new namespace. Say, you copy/paste some code into the source file, and just a few clicks of Alt + Enter, and all the required usings are included. Oh, and it also makes sure that the required assembly reference is added to your project. Say for example, you create a new project containing NUnit unit tests. The first class you write, you add the [TestFixture] attribute. If you already have one project in your solution that references the NUnit DLL file, then ReSharper is able to see that the TestFixtureAttribute comes from that DLL file, so it will automatically add that assembly reference to your new project. And it also adds required namespaces for extension methods. At least the ReSharper version 5 beta does. I'm pretty sure that Visual Studio's built-in resolve function doesn't do that. On the down side, it's a commercial product, so you have to pay for it. But if you work with software commercially, the gained productivity (the plug in does a lot of other cool stuff) outweighs the price tag. Yes, I'm a fan ;) A: In Visual Studio 2010 you will find the keyboard command to resolve namespaces in a command called View.ShowSmartTag. Mine was also mapped to Shift + Alt + F10 which is a lot of hassle - so I usually remap that promptly. On Pete commenting on ReSharper - yes, for anyone with the budget, ReSharper makes life an absolute pleasure. The fact that it is intelligent enough to resolve dependencies outside the current references, and add them both as usings and references will not only save you countless hours, but also make you forget where all framework classes reside ;-) That is how easy it makes development life... Then we have not even started on ReSharper refactorings yet. DevExpress' CodeRush offers no assistance on this regard; or nothing that is obvious to me - and DevExpress under non-expert mode is quite forthcoming in what it wants to do for you :-) Last comment - this IDE feature of resolving dependencies is so mature and refined in the Java IDE world that the bulk of the Internet samples don't even show the imports (using) any more. This said, Microsoft now finally has something to offer on this regard, but it is also clear to me that Microsoft development (for many of us) has now come full circle - the focus went from source, to visual designers right back to focus being on source again - meaning that the time you spend in a source code view / whether it is C#, VB or XAML is on the up and the amount of dragging and dropping onto 'forms' is on the down. With this basic assumption, it is simple to say that Microsoft should start concentrating on making the editor smarter, keyboard shortcuts easier, and code/error checking and evaluation better - the days of a dumb editor leaving you to google a class to find out in which library it resides are gone (or should be in any case) for most of us. A: It's ctrl + . when, for example, you try to type List you need to type < at the end and press ctrl + . for it to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/148977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "260" }
Q: Passing a function to another function in Actionscript 3 I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time. ex. function A: add(new Array("hello", some function)); function B: public function b(args:Array) { var myString = args[0]; var myFunc = args[1]; } A: This is very easy in ActionScript: function someFunction(foo, bar) { ... } function a() { b(["hello", someFunction]); } function b(args:Array) { var myFunc:Function = args[1]; myFunc(123, "helloworld"); } A: Simply pass the function name as an argument, no, just like in AS2 or JavaScript? function functionToPass() { } function otherFunction( f:Function ) { // passed-in function available here f(); } otherFunction( functionToPass ); A: You can do the following: add(["string", function():void { trace('Code...'); }]); ...or... ... add(["string", someFunction]); ... private function someFunction():void { trace('Code...'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/148982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Recursion in an XML schema? I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree. XML example: <?xml version="1.0" encoding="utf-8"?> <node> <attribute/> <node> <attribute/> <node/> </node> </node> Which is the best way to validate it? Recursion? A: if you need a recursive type declaration, here is an example that might help: <xs:schema id="XMLSchema1" targetNamespace="http://tempuri.org/XMLSchema1.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema1.xsd" xmlns:mstns="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" > <xs:element name="node" type="nodeType"></xs:element> <xs:complexType name="nodeType"> <xs:sequence minOccurs="0" maxOccurs="unbounded"> <xs:element name="node" type="nodeType"></xs:element> </xs:sequence> </xs:complexType> </xs:schema> As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired. A: XSD does indeed allow for recursion of elements. Here is a sample for you <xsd:element name="section"> <xsd:complexType> <xsd:sequence> <xsd:element ref="title"/> <xsd:element ref="para" maxOccurs="unbounded"/> <xsd:element ref="section" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> </xsd:element> As you can see the section element contains a child element that is of type section. A: The other solutions work great for making root elements recursive. However, in order to make a non-root element recursive without turning it into a valid root element in the process, a slightly different approach is needed. Let's say you want to define an XML message format for exchanging structured data between nodes in a distributed application. It contains the following elements: * *<message> - the root element; *<from> - the message's origin; *<to> - the message's destination; *<type> - the data structure type encoded in the message; *<data> - the data contained in the message. In order to support complex data types, <data> is a recursive element. This makes possible to write messages as below, for sending e.g. a geometry_msgs/TwistStamped message to a flying drone specifying its linear and angular (i.e. rotating) speeds: <?xml version="1.0" encoding="utf-8"?> <message xmlns="https://stackoverflow.com/message/1.0.0"> <from>controller:8080</from> <to>drone:8080</to> <type>geometry_msgs/TwistStamped</type> <data name="header"> <data name="seq">0</data> <data name="stamp"> <data name="sec">1</data> <data name="nsec">0</data> </data> <data name="frame_id">base_link</data> </data> <data name="twist"> <data name="linear"> <data name="x">1.0</data> <data name="y">0</data> <data name="z">1.0</data> </data> <data name="angular"> <data name="x">0.3</data> <data name="y">0</data> <data name="z">0</data> </data> </data> </message> We can easily write an XML schema to validate this format: <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://stackoverflow.com/message/1.0.0" elementFormDefault="qualified" xmlns="https://stackoverflow.com/message/1.0.0" > <xs:element name="data"> <xs:complexType mixed="true"> <xs:sequence> <xs:element ref="data" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> </xs:complexType> </xs:element> <xs:element name="message"> <xs:complexType> <xs:sequence> <xs:element name="from" type="xs:string"/> <xs:element name="to" type="xs:string"/> <xs:element name="type" type="xs:string"/> <xs:element ref="data" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> The problem with the schema above is that it makes <data> a root element, which means it also validates the document below: <?xml version="1.0" encoding="utf-8"?> <data xmlns="https://stackoverflow.com/message/1.0.0" name="twist"> <data name="header"> <data name="seq">0</data> <data name="stamp"> <data name="sec">1</data> <data name="nsec">0</data> </data> <data name="frame_id">base_link</data> </data> <data name="twist"> <data name="linear"> <data name="x">1.0</data> <data name="y">0</data> <data name="z">1.0</data> </data> <data name="angular"> <data name="x">0.3</data> <data name="y">0</data> <data name="z">0</data> </data> </data> </data> In order to avoid this side-effect, instead of defining the <data> element directly at the global level, we first define a data type, then define a data element of that type inside message: <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://stackoverflow.com/message/1.0.0" elementFormDefault="qualified" xmlns="https://stackoverflow.com/message/1.0.0" > <xs:complexType name="data" mixed="true"> <xs:sequence> <xs:element name="data" type="data" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> </xs:complexType> <xs:element name="message"> <xs:complexType> <xs:sequence> <xs:element name="from" type="xs:string"/> <xs:element name="to" type="xs:string"/> <xs:element name="type" type="xs:string"/> <xs:element name="data" type="data" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Notice that we end up having to define the <data> element twice — once inside the data type, and again inside <element> — but apart a little work duplication this is of no consequence.
{ "language": "en", "url": "https://stackoverflow.com/questions/148988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Archiving VMware images on ESXi Is there a way to compress a VMWare image on a ESXi server for archival purposes? A: What is wrong with simply using your faviourite archiver/compressor utility? A: veeam fastscp to copy it to your management station. after that treat as you like... A: I concur with @Sec - I use .tar.gz or .tar.bz2.
{ "language": "en", "url": "https://stackoverflow.com/questions/148999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rhino Mocks, MbUnit: Best way to check if object has raised an event I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? Best I could come up with (I am certain it gets better than this): public void MyCallback(object sender, EventArgs e) { _flag = true;} [Test] public void DoSomethingRaisesEvent() { _flag = false; using(_mocks.Record()) { Expect.Call(delegeate { _obj.DoSomething();}); } using(_mocks.Playback()) { _obj = new SomethingDoer(); _obj.SomethingWasDoneEvent += new EventHandler(MyHandler); Assert.IsTrue(_flag); } } A: I found this article by Phil Haack on how to test events using anonymous delegates Here is the code, ripped directly from his blog for those too lazy to click through: [Test] public void SettingValueRaisesEvent() { bool eventRaised = false; Parameter param = new Parameter("num", "int", "1"); param.ValueChanged += delegate(object sender, ValueChangedEventArgs e) { Assert.AreEqual("42", e.NewValue); Assert.AreEqual("1", e.OldValue); Assert.AreEqual("num", e.ParameterName); eventRaised = true; }; param.Value = "42"; //should fire event. Assert.IsTrue(eventRaised, "Event was not raised"); } A: I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks In any case, here is another way I like to deal with events: [Test] public void MyEventTest() { IEventRaiser eventRaiser; mockView = _mocks.CreateMock<IView>(); using (_mocks.Record()) { mockView.DoSomethingEvent += null; eventRaiser = LastCall.IgnoreArguments(); } using (_mocks.Playback()) { new Controller(mockView, mockModel); eventRaiser.Raise(mockView, EventArgs.Empty); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/149008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSCoder vs NSDictionary, when do you use what? I'm trying to figure out how to decide when to use NSDictionary or NSCoder/NSCoding? It seems that for general property lists and such that NSDictionary is the easy way to go that generates XML files that are easily editable outside of the application. When dealing with custom classes that holds data or possibly other custom classes nested inside, it seems like NSCoder/NSCoding would be the better route since it will step through all the contained object classes and encode them as well when an archive command is used. NSDictionary seems like it would take more work to get all the properties or data characteristics to a single level to be able to save it, where as NSCoder/NSCoding would automatically encode nested custom classes that implement the NSCoding interface. Outside of it being binary data and not editable outside of your application is there a real reason to use one over the other? And along those lines is there an indicator of which way you should lean between the two? Am I missing something obvious? A: Apple's documentation on object graphs has this to say: Mac OS X serializations store a simple hierarchy of value objects, such as dictionaries, arrays, strings, and binary data. The serialization only preserves the values of the objects and their position in the hierarchy. Multiple references to the same value object might result in multiple objects when deserialized. The mutability of the objects is not maintained. … Mac OS X archives store an arbitrarily complex object graph. The archive preserves the identity of every object in the graph and all the relationships it has with all the other objects in the graph. When unarchived, the rebuilt object graph should, with few exceptions, be an exact copy of the original object graph. The way I interpret this is that, if you want to store simple values, serialization (using an NSDictionary, for example) is a fine way to go. If you want to store an object graph of arbitrary types, with uniqueness and mutability preserved, using archives (with NSCoder, for example) is your best bet. You may also want to read Apple's Archives and Serializations Programming Guide for Cocoa, of which the aforelinked page on object graphs is a part, as it covers this topic well. A: I am NOT a big fan of using NSCoding/NSCoder/NSArchiver (we need to pick a name!) to serialise an object graph to a file. Archives created in this way are incredibly fragile. If you save an object of class Foo then by golly you need to make sure when you load the data back in you have a class Foo in your application. This makes NSCoder based serialisation difficult from the perspective of sharing files with other applications or even forwards compatibility with your future application. A: I forgot to list what I would recommend. NSCoding can be ok in certain situations: if you're just doing something quick and simple (although you do have to write a lot of code - two methods per class to be serialised). It can also be ok if you're not worried about compatibility with other applications. Export/import via property lists (perhaps using the NSPropertyListSerializaion class) is a fine solution. XML based plists are easy to create and edit. Main advantage to plists is that you're not tying the file format to just your application. You can also create your own XML based file format and read/write to it using NSXMLDocument API and friends. This really isn't much more work than using property lists. A: I think you're a bit confused, NSDictionary is a data structure, it also happens to implement the NSCoding protocol. So in essence, you could either put all your data into a NSDictionary and have that encode itself later on, or you can implement the NSCoding protocol and encode your object tree using the NSCoder API. Based on the type of NSCoder object passed in to the encodeWithCoder: method, is the output of your encoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/149021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What does the POP3 CAPA UIDL command do? What does the POP3 CAPA UIDL command do? A: The UIDL capability indicates that the optional UIDL command is supported. POP3 servers may assign a unique number to each incoming mail message. This allows mail to be left on the server after it has been downloaded to the user. Both the mail client and the POP server must support this feature. A: According to the POP3 RFC the UIDL command will give you a Unique ID for a message. The RFC goes on to say: The unique-id of a message is an arbitrary server-determined string, consisting of one to 70 characters in the range 0x21 to 0x7E, which uniquely identifies a message within a maildrop and which persists across sessions. The POP3 Exensions RFC says that the CAPA command allows you to query the capabilities of the server. So the CAPA UIDL command is used to see if a server supports unique IDs. A: It checks if the pop3 server understands (has the CAPAbility) the UIDL command. The response should be "+OK" or "-ERR" depending on wether the server supports the UIDL command. The UIDL command returns (if supported) an uniqe identify for each message, so a client can identify messages reliably. See also: rfc2449(CAPA) and rfc1939(POP3). A: CAPA is one command. UIDL is another command. You can try them out using telnet to port 110 of the POP server ( telnet:pop.example.com:110 ). After telnet establishes the TCP connection the POP server should send something like "+OK The Microsoft Exchange POP3 service is ready." You can type "CAPA" and hit return, then the POP server should respond with a list of capabilities that it supports (in that state of the session, that is prior to logging in). You can log in by sending "user @name@ and hit return, where @name@ would be changed to your POP account name. You then type "pass @pw@" and hit return, where @pw@ is your password. This sends you password over the network in the clear so someone sniffing the link could easily see your password. Your POP server may require other more secure login. (Don't type in the double quotes in the example above). Assuming that went well, you can try "CAPA" again now that the session has been established and is in a different state. The list of capabilities may be the same or different depending on the server configuration. At this point you can type "STAT" and hit return. The POP server should return "+OK @x@ @y@" where @x@ is the number of messages and @y@ is the length in bytes of all the messages. Now you can try typing "UIDL" and hit return. the POP server will return a list with "@n@ @uid@" where @n@ is the message number and @uid@ is a unique identifier assigned by the POP server. Type QUIT and hit return to end the session and close the TCP connection. A: UIDL is the Unique ID listing capability described in RFC 1939. It means the server supports generating unique IDs for each message to make it easier for the client to handle messages left on the server. A: Gives the unique identifier for a message on the POP3 server. Possible responses: +OK or -ERR
{ "language": "en", "url": "https://stackoverflow.com/questions/149024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: When should I write a Linux kernel module? Some people want to move code from user space to kernel space in Linux for some reason. A lot of times the reason seems to be that the code should have particularly high priority or simply "kernel space is faster". This seems strange to me. When should I consider writing a kernel module? Are there a set of criterias? How can I motivate keeping code in user space that (I believe) belong there? A: I'm not sure the question is the right way around. There should be a good reason to move things to kernel space. If there aren't any reasons, don't do it. For one thing, debugging is made harder, and the effect of bugs is far worse (crash/panic instead of simple coredump). A: Basically, I agree with rpj. Code has to be in user-space, unless it's REALLY necessary. But, to emphasize your question, which condition? Some people claims that driver has to be in the kernel, which is not true. Some drivers are not timing sensitive, in fact lots of drivers are like that. For example, the framer, RTC timer, i2c devices, etc. Those drivers can be easily moved to user space. There are even some file-systems that are written in user-space. You should move to kernel space where the overhead, eg. user-kernel swap, becomes unacceptable for your code to work properly. But there are lots of way to deal with this. For example, the /dev/mem provides a good way to access your physical memory, just like you do it from the kernel space. When people talk about going to RTOS, I'm usually skeptical. These days, the processor is so powerful, that most of the time, the real-time aspect becomes negligible. But even, let's say, you're dealing with SONET, and you need to do a protection switching within 50ms (actually even less, since the 50ms constrains applies to the whole ring), you still can do the switching very fast, IF your hardware supports it. Lots of framer these days can give you a hardware support that reduces the amount of writes that you need to do. Your job is basically responds to the interrupt as quickly as possible. And Linux is not bad at all. The interrupt latency I got was less 1ms, even if I have tons of other interrupts running (eg. IDE, ethernet, etc.). And if that's still not enough, then maybe your hardware design is wrong. Some things are better left on the hardware. And when I said hardware, I mean ASIC, FPGA, Network Processor, or other advanced logic. A: Code running in the kernel accesses memory, peripherals, system functions in ways that are different from userspace code and thus has the ability to be more efficient. Not to mention the reduced security restrictions for kernel code. However, all this usually comes at a cost, such as increasing the possibility of opening the kernel up to security threats, locking up the OS, complicating the debugging, and so forth. A: Rule of thumb: try your absolute best to keep your code in user-space. If you don't think you can, spend as much time researching alternatives to kernel code as you would writing the code (ie: a long time), and then try again to implement it in user-space. If you still can't, research more to ensure you're making the right choice, then very cautiously move into the kernel. As others have said, there are very few circumstances that dictate writing kernel modules and debugging kernel code can be quite hellish, so steer clear at all costs. As far as concrete conditions you should check for when considering writing kernel-mode code, here are a few: Does it need access to extremely low-level resources, such as interrupts? Is your code defining a new interface/driver for hardware that cannot be built on top of currently exported functionality? Does your code require access to data structures or primitives that are not exported out of kernel space? Are you writing something that will be primarily used by other kernel subsystems, such as a scheduler or VM system (even here it isn't entirely necessary that the subsystem be kernel-mode: Mach has strong support for user-mode virtual memory pagers, so it can definitely be done)? A: There are very limited reasons to put stuff into the kernel. If you're writing device drivers it's ok. Any standard application: never. The drawbacks are huge. Debugging gets harder, errors become more frequent and hard to find. You might compromise security and stability. You might have to adapt to kernel changes more frequently. It becomes impossible to port to other UNIX OSs. The closest I've ever come to the kernel was a custom filesystem (with mysql in the background) and even for that we used FUSE (where the U stands for userspace). A: If your people want really high priority, determinism, low latency etc, the right way to go is to use some real-time version of Linux (or other OS). Also look at the preemptible kernel options etc. Exactly what you should do depends on the requirements, but to put the code in kernel modules is not likely the right solution, unless you are interfacing some hardware directly. A: Another reason to not move code into kernel space is that when you use it in production or commercial situations, you will have to publish that code due to the GPL agreement. A situation that many software companies don't want to come into. :) A: As general rule. Think on what you want to know and if that is something you would see in an operating system development book or class then it has a good chance to belong into the kernel. If not, keep it out of the kernel. If you have a very good reason to break that rule, be sure, you will have enough knowledge to know it by yourself or you will be working with someone that has that knowledge. Yes, might sound harsh, but this exactly what I meant, if you don't know, then be almost sure the answer is no, don't do it in the kernel. Moving your development to kernel space opens a giant can of worms that you must be sure to be able to handle. A: If you're asking such a question, then you shouldn't go to the kernel layer. Basically just wondering means you don't need to. The time of the context switch is so negligible that it doesn't matter anyway these days. A: If you just need lower latency, higher throughput, etc., it is probably cheaper to buy a faster computer than to develop kernel code. Kernel modules may be faster (due to less context switches, less system call overhead, and less interruptions), and certainly do run at very high priority. If you want to export a small amount of fairly simple code into kernel space, this might be OK. That is, if a small piece of code is found to be crucial to performance, and is the sort of code that would benefit from being placed in kernel mode, then it may be justified to place it there. But moving large parts of your program into kernel space should be avoided unless all other options are completely exhausted. Aside from the difficulty of doing so, the performance benefit is not likely to be very large.
{ "language": "en", "url": "https://stackoverflow.com/questions/149032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Best way to store currency values in C++ I know that a float isn't appropriate to store currency values because of rounding errors. Is there a standard way to represent money in C++? I've looked in the boost library and found nothing about it. In java, it seems that BigInteger is the way but I couldn't find an equivalent in C++. I could write my own money class, but prefer not to do so if there is something tested. A: I would suggest that you keep a variable for the number of cents instead of dollars. That should remove the rounding errors. Displaying it in the standards dollars/cents format should be a view concern. A: You can try decimal data type: https://github.com/vpiotr/decimal_for_cpp Designed to store money-oriented values (money balance, currency rate, interest rate), user-defined precision. Up to 19 digits. It's header-only solution for C++. A: You say you've looked in the boost library and found nothing about there. But there you have multiprecision/cpp_dec_float which says: The radix of this type is 10. As a result it can behave subtly differently from base-2 types. So if you're already using Boost, this should be good to currency values and operations, as its base 10 number and 50 or 100 digits precision (a lot). See: #include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> int main() { float bogus = 1.0 / 3.0; boost::multiprecision::cpp_dec_float_50 correct = 1.0 / 3.0; std::cout << std::setprecision(16) << std::fixed << "float: " << bogus << std::endl << "cpp_dec_float: " << correct << std::endl; return 0; } Output: float: 0.3333333432674408 cpp_dec_float: 0.3333333333333333 *I'm not saying float (base 2) is bad and decimal (base 10) is good. They just behave differently... ** I know this is an old post and boost::multiprecision was introduced in 2013, so wanted to remark it here. A: Know YOUR range of data. A float is only good for 6 to 7 digits of precision, so that means a max of about +-9999.99 without rounding. It is useless for most financial applications. A double is good for 13 digits, thus: +-99,999,999,999.99, Still be careful when using large numbers. Recognize the subtracting two similar results strips away much of the precision (See a book on Numerical Analysis for potential problems). 32 bit integer is good to +-2Billion (scaling to pennies will drop 2 decimal places) 64 bit integer will handle any money, but again, be careful when converting, and multiplying by various rates in your app that might be floats/doubles. The key is to understand your problem domain. What legal requirements do you have for accuracy? How will you display the values? How often will conversion take place? Do you need internationalization? Make sure you can answer these questions before you make your decision. A: Whatever type you do decide on, I would recommend wrapping it up in a "typedef" so you can change it at a different time. A: It depends on your business requirements with regards to rounding. The safest way is to store an integer with the required precision and know when/how to apply rounding. A: Don't store it just as cents, since you'll accumulate errors when multiplying for taxes and interest pretty quickly. At the very least, keep an extra two significant digits: $12.45 would be stored as 124,500. If you keep it in a signed 32 bit integer, you'll have $200,000 to work with (positive or negative). If you need bigger numbers or more precision, a signed 64 bit integer will likely give you all the space you'll need for a long time. It might be of some help to wrap this value in a class, to give you one place for creating these values, doing arithmetic on them, and formatting them for display. This would also give you a central place to carry around which currency it being stored (USD, CAD, EURO, etc). A: Having dealt with this in actual financial systems, I can tell you you probably want to use a number with at least 6 decimal places of precision (assuming USD). Hopefully since you're talking about currency values you won't go way out of whack here. There are proposals for adding decimal types to C++, but I don't know of any that are actually out there yet. The best native C++ type to use here would be long double. The problem with other approaches that simply use an int is that you have to store more than just your cents. Often financial transactions are multiplied by non-integer values and that's going to get you in trouble since $100.25 translated to 10025 * 0.000123523 (e.g. APR) is going cause problems. You're going to eventually end up in floating point land and the conversions are going to cost you a lot. Now the problem doesn't happen in most simple situations. I'll give you a precise example: Given several thousand currency values, if you multiply each by a percentage and then add them up, you will end up with a different number than if you had multiplied the total by that percentage if you do not keep enough decimal places. Now this might work in some situations, but you'll often be several pennies off pretty quickly. In my general experience making sure you keep a precision of up to 6 decimal places (making sure that the remaining precision is available for the whole number part). Also understand that it doesn't matter what type you store it with if you do math in a less precise fashion. If your math is being done in single precision land, then it doesn't matter if you're storing it in double precision. Your precision will be correct to the least precise calculation. Now that said, if you do no math other than simple addition or subtraction and then store the number then you'll be fine, but as soon as anything more complex than that shows up, you're going to be in trouble. A: Store the dollar and cent amount as two separate integers. A: Look in to the relatively recent Intelr Decimal Floating-Point Math Library. It's specifically for finance applications and implements some of the new standards for binary floating point arithmetic (IEEE 754r). A: Integers, always--store it as cents (or whatever your lowest currency is where you are programming for.) The problem is that no matter what you do with floating point someday you'll find a situation where the calculation will differ if you do it in floating point. Rounding at the last minute is not the answer as real currency calculations are rounded as they go. You can't avoid the problem by changing the order of operations, either--this fails when you have a percentage that leaves you without a proper binary representation. Accountants will freak if you are off by a single penny. A: The biggest issue is rounding itself! 19% of 42,50 € = 8,075 €. Due to the German rules for rounding this is 8,08 €. The problem is, that (at least on my machine) 8,075 can't be represented as double. Even if I change the variable in the debugger to this value, I end up with 8,0749999.... And this is where my rounding function (and any other on floating point logic that I can think of) fails, since it produces 8,07 €. The significant digit is 4 and so the value is rounded down. And that is plain wrong and you can't do anything about it unless you avoid using floating point values wherever possible. It works great if you represent 42,50 € as Integer 42500000. 42500000 * 19 / 100 = 8075000. Now you can apply the rounding rule above 8080000. This can easily be transformed to a currency value for display reasons. 8,08 €. But I would always wrap that up in a class. A: I would recommend using a long int to store the currency in the smallest denomination (for example, American money would be cents), if a decimal based currency is being used. Very important: be sure to name all of your currency values according to what they actually contain. (Example: account_balance_cents) This will avoid a lot of problems down the line. (Another example where this comes up is percentages. Never name a value "XXX_percent" when it actually contains a ratio not multiplied by a hundred.) A: The solution is simple, store to whatever accuracy is required, as a shifted integer. But when reading in convert to a double float, so that calculations suffer fewer rounding errors. Then when storing in the database multiply to whatever integer accuracy is needed, but before truncating as an integer add +/- 1/10 to compensate for truncation errors, or +/- 51/100 to round. Easy peasy. A: The GMP library has "bignum" implementations that you can use for arbitrary sized integer calculations needed for dealing with money. See the documentation for mpz_class (warning: this is horribly incomplete though, full range of arithmetic operators are provided). A: One option is to store $10.01 as 1001, and do all calculations in pennies, dividing by 100D when you display the values. Or, use floats, and only round at the last possible moment. Often the problems can be mitigated by changing order of operations. Instead of value * .10 for a 10% discount, use (value * 10)/100, which will help significantly. (remember .1 is a repeating binary) A: I'd use signed long for 32-bit and signed long long for 64-bit. This will give you maximum storage capacity for the underlying quantity itself. I would then develop two custom manipulators. One that converts that quantity based on exchange rates, and one that formats that quantity into your currency of choice. You can develop more manipulators for various financial operations / and rules. A: This is a very old post, but I figured I update it a little since it's been a while and things have changed. I have posted some code below which represents the best way I have been able to represent money using the long long integer data type in the C programming language. #include <stdio.h> int main() { // make BIG money from cents and dollars signed long long int cents = 0; signed long long int dollars = 0; // get the amount of cents printf("Enter the amount of cents: "); scanf("%lld", &cents); // get the amount of dollars printf("Enter the amount of dollars: "); scanf("%lld", &dollars); // calculate the amount of dollars long long int totalDollars = dollars + (cents / 100); // calculate the amount of cents long long int totalCents = cents % 100; // print the amount of dollars and cents printf("The total amount is: %lld dollars and %lld cents\n", totalDollars, totalCents); } A: As other answers have pointed out, you should either: * *Use an integer type to store whole units of your currency (ex: $1) and fractional units (ex: 10 cents) separately. *Use a base 10 decimal data type that can exactly represent real decimal numbers such as 0.1. This is important since financial calculations are based on a base 10 number system. The choice will depend on the problem you are trying to solve. For example, if you only need to add or subtract currency values then the integer approach might be sensible. If you are building a more complex system dealing with financial securities then the decimal data type approach may be more appropriate. As another answer points out, Boost provides a base 10 floating point number type that serves as a drop-in replacement for the native C++ floating-point types, but with much greater precision. This might be convenient to use if your project already uses other Boost libraries. The following example shows how to properly use this decimal type: #include <iostream> #include <boost/multiprecision/cpp_dec_float.hpp> using namespace std; using namespace boost::multiprecision; int main() { std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::max_digits10) << std::endl; double d1 = 1.0 / 10.0; cpp_dec_float_50 dec_incorrect = 1.0 / 10.0; // Incorrect! We are constructing our decimal data type from the binary representation of the double value of 1.0 / 10.0 cpp_dec_float_50 dec_correct(cpp_dec_float_50(1.0) / 10.0); cpp_dec_float_50 dec_correct2("0.1"); // Constructing from a decimal digit string. std::cout << d1 << std::endl; // 0.1000000000000000055511151231257827021181583404541015625 std::cout << dec_incorrect << std::endl; // 0.1000000000000000055511151231257827021181583404541015625 std::cout << dec_correct << std::endl; // 0.1 std::cout << dec_correct2 << std::endl; // 0.1 return 0; } Notice how even if we define a decimal data type but construct it from a binary representation of a double, then we will not obtain the precision that we expect. In the example above, both the double d1 and the cpp_dec_float_50 dec_incorrect are the same because of this. Notice how they are both "correct" to about 17 decimal places which is what we would expect of a double in a 64-bit system. Finally, note that the boost multiprecision library can be significantly slower than the fastest high precision implementations available. This becomes evident at high digit counts (about 50+); at low digit counts the Boost implementation can be comparable other, faster implementations. Sources: * *https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html *https://www.boost.org/doc/libs/1_80_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/caveats.html A: go ahead and write you own money (http://junit.sourceforge.net/doc/testinfected/testing.htm) or currency () class (depending on what you need). and test it. A: Our financial institution uses "double". Since we're a "fixed income" shop, we have lots of nasty complicated algorithms that use double anyway. The trick is to be sure that your end-user presentation does not overstep the precision of double. For example, when we have a list of trades with a total in trillions of dollars, we got to be sure that we don't print garbage due to rounding issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/149033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: JMS message receiver filtering by JMSCorrelationID How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed. Here's the code that I'm currently using to put the message in the queue: /** * publishResponseToQueue publishes Requests to the Queue. * * @param jmsQueueFactory -Name of the queue-connection-factory * @param jmsQueue -The queue name for the request * @param response -A response object that needs to be published * * @throws ServiceLocatorException -An exception if a request message * could not be published to the Topic */ private void publishResponseToQueue( String jmsQueueFactory, String jmsQueue, Response response ) throws ServiceLocatorException { if ( logger.isInfoEnabled() ) { logger.info( "Begin publishRequestToQueue: " + jmsQueueFactory + "," + jmsQueue + "," + response ); } logger.assertLog( jmsQueue != null && !jmsQueue.equals(""), "jmsQueue cannot be null" ); logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""), "jmsQueueFactory cannot be null" ); logger.assertLog( response != null, "Request cannot be null" ); try { Queue queue = (Queue)_context.lookup( jmsQueue ); QueueConnectionFactory factory = (QueueConnectionFactory) _context.lookup( jmsQueueFactory ); QueueConnection connection = factory.createQueueConnection(); connection.start(); QueueSession session = connection.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE ); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setJMSCorrelationID(response.getID()); objectMessage.setObject( response ); session.createSender( queue ).send( objectMessage ); session.close(); connection.close(); } catch ( Exception e ) { //XC3.2 Added/Modified BEGIN logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " + "Response to the Queue - " + e.getMessage() ); throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " + "- Could not publish the " + "Response to the Queue - " + e.getMessage() ); //XC3.2 Added/Modified END } if ( logger.isInfoEnabled() ) { logger.info( "End publishResponseToQueue: " + jmsQueueFactory + "," + jmsQueue + response ); } } // end of publishResponseToQueue method A: BTW while its not the actual question you asked - if you are trying to implement request response over JMS I'd recommend reading this article as the JMS API is quite a bit more complex than you might imagine and doing this efficiently is much harder than it looks. In particular to use JMS efficiently you should try to avoid creating consumers for a single message etc. Also because the JMS API is so very complex to use correctly and efficiently - particularly with pooling, transactions and concurrent processing - I recommend folks hide the middleware from their application code such as via using Apache Camel's Spring Remoting implementation for JMS A: Hope this will help. I used Open MQ. package com.MQueues; import java.util.UUID; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.QueueConnection; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; import com.sun.messaging.BasicQueue; import com.sun.messaging.QueueConnectionFactory; public class HelloProducerConsumer { public static String queueName = "queue0"; public static String correlationId; public static String getCorrelationId() { return correlationId; } public static void setCorrelationId(String correlationId) { HelloProducerConsumer.correlationId = correlationId; } public static String getQueueName() { return queueName; } public static void sendMessage(String threadName) { correlationId = UUID.randomUUID().toString(); try { // Start connection QueueConnectionFactory cf = new QueueConnectionFactory(); QueueConnection connection = cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); BasicQueue destination = (BasicQueue) session.createQueue(threadName); MessageProducer producer = session.createProducer(destination); connection.start(); // create message to send TextMessage message = session.createTextMessage(); message.setJMSCorrelationID(correlationId); message.setText(threadName + "(" + System.currentTimeMillis() + ") " + correlationId +" from Producer"); System.out.println(correlationId +" Send from Producer"); producer.send(message); // close everything producer.close(); session.close(); connection.close(); } catch (JMSException ex) { System.out.println("Error = " + ex.getMessage()); } } public static void receivemessage(final String correlationId) { try { QueueConnectionFactory cf = new QueueConnectionFactory(); QueueConnection connection = cf.createQueueConnection(); QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); BasicQueue destination = (BasicQueue) session.createQueue(getQueueName()); connection.start(); System.out.println("\n"); System.out.println("Start listen " + getQueueName() + " " + correlationId +" Queue from receivemessage"); long now = System.currentTimeMillis(); // receive our message String filter = "JMSCorrelationID = '" + correlationId + "'"; QueueReceiver receiver = session.createReceiver(destination, filter); TextMessage m = (TextMessage) receiver.receive(); System.out.println("Received message = " + m.getText() + " timestamp=" + m.getJMSTimestamp()); System.out.println("End listen " + getQueueName() + " " + correlationId +" Queue from receivemessage"); session.close(); connection.close(); } catch (JMSException ex) { System.out.println("Error = " + ex.getMessage()); } } public static void main(String args[]) { HelloProducerConsumer.sendMessage(getQueueName()); String correlationId1 = getCorrelationId(); HelloProducerConsumer.sendMessage(getQueueName()); String correlationId2 = getCorrelationId(); HelloProducerConsumer.sendMessage(getQueueName()); String correlationId3 = getCorrelationId(); HelloProducerConsumer.receivemessage(correlationId2); HelloProducerConsumer.receivemessage(correlationId1); HelloProducerConsumer.receivemessage(correlationId3); } } A: The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver. QueueReceiver receiver = session.createReceiver(myQueue, "JMSCorrelationID='theid'"); then receiver.receive() or receiver.setListener(myListener); A: String filter = "JMSCorrelationID = '" + msg.getJMSMessageID() + "'"; QueueReceiver receiver = session.createReceiver(queue, filter); Here the receiver will get the messages for which JMSCorrelationID is equal to MessageID. this is very helpful in request/ response paradigm. or you can directly set this to any value: QueueReceiver receiver = session.createReceiver(queue, "JMSCorrelationID ='"+id+"'";); Than you can do either receiver.receive(2000); or receiver.setMessageListener(this);
{ "language": "en", "url": "https://stackoverflow.com/questions/149037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Is there a way to define which fields in the model are editable in the admin app? Assume the following: models.py class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) admin.py class EntryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering). Thoughts? A: For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not. Consider this example: def save(self): from django.template.defaultfilters import slugify if not self.slug: self.slug = slugify(self.title) super(Your_Model_Name,self).save() A: I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets, and than overriding the save method to copy the slug from the tile, and potentially slugifying it... A: This Django Snippet does what you want by defining a custom Read-Only Widget. So you define a custom editor for the field which in fact doesn't allow any editing. A: This snippet gives you an AutoSlugField with exactly the behavior you are seeking, and adding it to your model is a one-liner. A: In addition to overriding save to provide the generated value you want, you can also use the exclude option in your ModelAdmin class to prevent the field from being displayed in the admin: class EntryAdmin(admin.ModelAdmin): exclude = ('slug',)
{ "language": "en", "url": "https://stackoverflow.com/questions/149040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Would you start learning Smalltalk? My questions is simple! * *Would you start learning Smalltalk if you had the time? Why? Why not? *Do you already know Smalltalk? Why would you recommend Smalltalk? Why not? Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is Seaside. Maybe someone has made the same transition before? EDIT: Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: Episode 52: Randal Schwartz on Seaside (among other things) A: I do not know Ruby.. Smalltalk is a pure OO language. If you feel the need to really understand OO, and not just the simulated OO of most popular 'OO' languages (like C++, Java, etc), then I would recommend that you play with smalltalk. In smalltalk everything is an object, with attributes, behavior and meta. In the simulations you have data types that you use in your objects. I would say play with it, you will only benefit. A: I'm totally in your shoes. Im using RoR and looking into Smalltalk land. Here's some pros & cons I find important: Pros: * *Mature & stable environment *Fast development cycle *Makes you think more and write less Cons: * *Requires different thinking *Still didn't quite grasp it It's quite funny how I got to know about Smalltalk. It was this one thing that keept popping up in Google results when searching for Lisp and Erlang stuff. One day I checked it out and was amazed with nice windows environment. Few moments later I've found Aida/Web framework. I was hooked and started learning Smalltalk through web development with this framework. Still not quite there, but it's so damn interesting I just can't sit still... :-) I'm having fun again. A: If you like Ruby you'll probably like Smalltalk. IIRC Seaside has been ported to the Gemstone VM, which is part of their Gemstone/S OODBMS. This has much better thread support than Ruby, so it is a better back-end for a high-volume system. This might be a good reason to take a close look at it. Reasons to learn Smalltalk: * *It's a really, really nice programming environment. Once you've got your head around it (it tends to be a bit of a culture shock for people used to C++ or Java) you'll find it to be a really good environment to work in. Even a really crappy smalltalk like the Old Digitalk ones I used is a remarkably pleasant system to use. Many of the old XP and O-O guru types like Kent Beck and Martin Fowler cut their teeth on Smalltalk back in the day and can occasionally be heard yearning for the good old days in public (Thanks to Frank Shearer for the citation, +1) - Agile development originated on this platform. *It's one of the most productive development platforms in history. *Several mature implementations exist and there's a surprisingly large code base out there. At one point it got quite trendy in financial market circles where developer productivity and time-to-market is quite a big deal. Up until the mid 1990s it was more or less the only game in town (With the possible exception of LISP) if you wanted a commercially supported high-level language that was suitable for application development. *Deployment is easy - just drop the image file in the appropriate directory. *Not really a reason, but the Gang of Four Book uses Smalltalk for quite a few of their examples. Reasons not to learn Smalltalk: * *It's something of a niche market. You may have trouble finding work. However if you are producing some sort of .com application where you own the servers this might not be an issue. *It's viewed as a legacy system by many. There is relatively little new development on the platform (although Seaside seems to be driving a bit of a renaissance). *It tends not to play nicely with traditional source control systems (at least as of the early-mid 90's when I used it). This may or may not still be the case. *It is somewhat insular and likes to play by itself. Python or Ruby are built for integration from the ground up and tend to be more promiscuous and thus easier to integrate with 3rd party software. However, various other more mainstream systems suffer from this type of insularity to a greater or lesser degree and that doesn't seem to impede their usage much. A: Would not start learning it if I had the time. Why not? Because it would be more productive and lucrative financially to learn C# or Java. On the other hand if your a hobbyist, and would like to go on an archeological dig, then I'd suggest spending some time looking at the What, When, Why and how of smalltalk by researching Alan Kay. Fascinating story and an incredible person (after all, he earned the Turning Award). Then maybe play with squeak a little to get a feeling for the language. After this you might have a newly found respect/understanding of blocks, closures, and Object Oriented principles. I know and use Smalltalk, have for about 15 years, still maintaining it, and would not recommend Smalltalk to a friend. Why not? Employment is a good thing to have and keep getting. Although you can learn a lot from Smalltalk you can't easily turn that into gainfully being employed in this day and age. Also, you appeared to be excited over Seaside and I would assume the Seaside/GemStone partnership. I've used GemStone for quite some time and the two together are very appealing. I hope they can get the market share and momentum required to be successful. A: Don't! If you really start learning it, you might not want to programm in something else anymore ever. This may be not true, if you are a lisp programmer. A: Absolutely, learn Smalltalk! This is 2015 and Smalltalk is on the rise again, thanks to Pharo. Pharo is FREE. Pharo is evolving quickly into a powerful enterprise tool. At Version 4.0, and soon to be 5.0, it has matured a great deal in just four years! Then there's Amber, which is Smalltalk for the web. It's also FREE and evolving quickly. Despite Smalltalk's reputation, this is not your father's Smalltalk. Modern Smalltalk is exciting and promising. It's true that Smalltalk jobs are not (yet) plentiful. But if enough of you aggregate to a new wave of Smalltalkers, then the industry will adapt to it and we'll see wider adoption of Smalltalk in business. The question is, do you have the vision? A: Well, since you mentioned me by name, I feel I should chime in. As I said in that podcast interview, and as I have repeatedly demonstrated in my blog at http://MethodsAndMessages.vox.com/, this is "the year of smalltalk". And having now done Smalltalk advocacy for the past ten months, I can see that it really is happening. More customers are turning to Smalltalk and Seaside, and the Smalltalk vendors are all working hard to capture this new influx of attention. More larger Smalltalk conferences are being planned. More job postings are being posted. More blog postings are being made. If you turn to Smalltalk today, you are not alone. There are many others who are out there as well. Edit Well, a number of years later, I'm now recommending Dart instead. It's a great language originated by Google but now owned by an ECMA committee. It runs serverside in node.js style, but also clientside in modern browsers by transpiling to JavaScript. Lots of good books, blogs, help channels, IDE support, public live pastebin. I think it's definitely got legs... enough so that I'm writing courseware to teach it onsite or online, and I'm pretty sure there's a book or two in the works from me. And Gilad Bracha, an old-time Smalltalker is a major contributor to the design, so there's a lot of Smalltalk in Dart. A: I was taught Smalltalk in one of the first graduate college level Object-Orient Programming courses (circa 1988). The teacher thought it best to start was a "pure" OO langauge,before moving on to a more trendy one (we did a bit of C++ at the end of the semester). By that measure, it's still best to start with pure OO, although these days we have Java & C#, both of which are "nearly-pure" OO -- close enough that you can get by ignoring the non-OO features of them, and limiting yourself to the Pure-OO subset of the langauges. A: I've been a software engineer for quite a few years now. I've heard people bring up Smalltalk a few times, and certainly Smalltalk has been around since about 1980, but it's one of those languages that's never seemed to make it into the software mainstream. Sort of like Objective C, CLIPS, PL/I, etc--something you may have heard of, but something that most folks have never programmed in. I probably wouldn't take the time to learn Smalltalk unless I needed to for a particular job. I looked at some Smalltalk tutorials and examples briefly a few years back, and it looks like it has some clear advantages for certain aspects of OO programming (like the message concept seems cool). But sadly, it is not mainstream, and doesn't seem to be gaining much momentum. A: If you want a better understanding of Extreme Programming (and even Scrum) I'd say yes. Why impatient Java programmers need to learn Smalltalk: http://www.dafydd.net/archive/2010/why-smalltalk-isnt-just-another-language/ A: Smalltalk is a good language to learn, and the great thing is that it only takes a day to do it. It's a lot more than just an academic language. People are building huge, scalable, replicable applications handling billions of dollars. They just don't talk about it much. See, for instance, GemStone and Orient Overseas Container Lines: A Shipping Industry Case Study. Seaside is a good reason to learn Smalltalk, but I don't think you'll find it orders of magnitude better than Rails. The thing that convinced me was GemStone. I really like Gemstone's GLASS (GemStone, Linux, Apache, Smalltalk, Seaside). The killer part of that is GemStone, which handles all the object persistence for you mostly without you thinking about it. Seeing some of their demos and hearing about what people are doing with GemStone reset my idea of what "big application" meant. The part that bugs me the most about Rails is the object-relational mapping. That's nothing against Ruby because it sucks just as hard in GLORP (which handles ActiveRecord for Smalltalk), or Perl, or anything else. Mapping objects to database tables is just painful. With GemStone, thinking about the database disappears, so the work with the database disappears too. It's like a huge stone (or a troop of monkeys) is taken off my back. A: This thread has become very actual for me. I'm planning for a Software migration to a web-application. It's a database based software. I'm especially checking the alternatives 1) Rails 2) Seaside If I can get the figures for the Gemstone/S as Database, I'll consider that also. So for me it means I have to learn Smalltalk (better) than before. Because it could be that it will be my work for the next 15 years. You would (and should not) work with software you don't like for that long ;-). I've the impression Gemstone/S is one of the "killer" applications. But persistence of Objects still is a very difficult field.... A: 1) Yes! It's always good to learn a language. If you are going to learn a language, make it a powerful, influential language that can be learnt easily and quickly. Smalltalk remains a pre-eminent language and environment for learning OO concepts. It is all objects, all the way down. This makes for a really consistent approach to working. Integers are instances of Class Integer. Strings are a collection of character objects. Classes are singleton instance objects for the class they define. Control structures work by sending get messages to instances of Class Boolean. Even anonymous methods (blocks of code, aka blocks) are objects. Everything is done by sending a message to an object. The syntax can be fitted on a postcard. The clarity of the concepts and their implementation in Smalltalk mean that you can develop ways of thought which transfer directly into Java, Ruby and C#. I expect it's true for Python, too. It's so good for making the concepts clear that a major UK University used Smalltalk to train 5,000 people a year in object-oriented computing. Squeak 5, has just been released. It has gained major performance increases from its new Cog/Spur VM, which features with progressive garbage-collection. Pharo 4 has a lovely clean-looking desktop theme. The next version, Pharo 5, will be released soon. It will move to using the Cog/Spur VM, it will have about 5,000 classes in the release, and additional packages of classes are readily available from the net via the Configuration Browser tool. Squeak 5 is performant even on first-gen Raspberry Pis, and is almost 50% faster on the new $5 Raspberry Pi zero. $99 buys you a Raspberry Pi 2, screen and case - running a mature, fully feature-complete IDE. Leading edge research is being done on co-ordinated, distributed OO systems in Smalltalk (e.g. Naiad and Spoon). Some of the world's largest corporate databases are run on Smalltalk - including tracking of 60% of the world's shipping containers, and trading systems in the world's largest bank. You can use Smalltalk as a sort of super-powered CoffeeScript, writing in Amber Smalltalk and transpiling to JavaScript, running in the browser. Squeak, Pharo, and Amber are all Free, Open-source, open-licenced languages and environments. Squeak and Pharo provide write-once, run anywhere facilities for MacOS, Windows and Linux. (Possibly RiscOS, too). Dolphin Smalltalk is targetted firmly at native Windows look-and-feel, and lets you compile closed .exes of your finished work for distribution to end users. Further development of Dolphin by the vendor has stopped, but it is completely functional, and, like all Smalltalks, designed to be massively extensible. (Did I mention that Pharo now has 5,000 classes, compared to Squeak's 3,000? Pharo is a fork of Squeak 3.9) **There is a How-to guide for installing and starting Squeak, Amber, Pharo, Cuis and Dolphin at: ** http://beginningtosmalltalk.blogspot.co.uk/2015/11/how-to-get-smalltalk-up-and-running.html The Seaside web framework runs on Squeak and on Pharo. It's a wonderful mature tool, as is the more traditional AidaWeb framework. VisualAge, VisualWorks and Gemstone all provide enterprise-grade robust systems. Gemstone provides an infinitely scalable object database with transactions and persistence. 2) Yes - I do already use it. I learnt it via the Open University, and was immediately productive in Ruby (a copy of the Pickaxe book and the library reference by my side). It helped me enormously with Java, and with Xerox Moo-code. I have just returned to it to write apps to control manage and distribute responsive, massively multi-platform mobile apps. I expect that soon I'll be re-writing my JavaScript mobile apps using Amber, too. A: I don't really know what you're looking for. If you are looking for a different language to write in, I'd think that would depend heavily on the libraries available. I know neither Ruby nor Smalltalk, but it seems likely that the most efficient way to write Ruby on Rails-sorts of applications may not be Smalltalk. If you are looking to learn the ideas behind Ruby, this might be a very good move. I don't have anything quantitative, but I always felt better about using tools (such as language systems) if I knew more than just the tools, if I kmew the ideas behind them or how they worked. If you want to learn different sorts of object-oriented languages, you might well want to learn Smalltalk (if it differs significantly from Ruby), something like Java or C++, and perhaps also the Common Lisp Object System. If you just want to learn something different, Smalltalk may well be a good choice. I'd also suggest Common Lisp, and other people will doubtless have other suggestions (can you get a good Forth system nowadays?). A: > couldn't find a Smalltalk development environment that didn't cost both arms and a leg Google - free smalltalk Cincom Smalltalk, Squeak, GNU Smalltalk A: Learning Smalltalk will give you a grounding in object oriented software development from the perspective of the man who invented OO (Alan Kay). The idea of a overlapping windowing environment came from Smalltalk. A stumbling block to learning Smalltalk is that it is a message passing system with a strange syntax for flow control like: i < 60 ifTrue: [ self walk ] It has a very mature class library that has a consistency I've not seen too many places. The class library in all environments (even commercial Smalltalks) has available source which allows you to learn from the masters of the language. When programming Smalltalk, I always ask the question how is it done in the environment. Smalltalk is generally implemented in an image which is a live environment for all the objects in your system. The interactive debugger really seperates Smalltalk from Ruby. Seaside is the web development framework and has given Smalltalk a new spotlight. It is a continuation based environment that allows for intra-hit debugging and a smooth Rich Client type development experience (top application flow can be designed in a single method). It's integration with script.aculo.us has been done in such a way that it is easily called from within Smalltalk. A: Nigel, one quote I have is this: Although it's now a long time since I did anything with it, I nominate Smalltalk, I still haven't come across anything quite like it for being able to transfer thoughts into computer code. It's not just the language: It's the wonderful browser environment, the libraries, and the culture of writing clear, well-designed code as quickly as anything else can crank out spaghetti. When the participants at JavaOne were extolling how Java was so much more productive than anything else, I needed a brown paper bag. Oh well, back to sorting out my classpaths... -- Martin Fowler (Software Development Magazine, Jan 2001) I found it here. A: Would disagree with the poster who reckons you wouldn’t use Smalltalk for large apps – that’s precisely where it shines. But I have created fairly groovy (note lowercase) prototype apps in under a week too. I learned OO in ST starting in 92, incredibly glad I did so. It gave me a real background in OO. Thinking in classes. No types. ST has a real emphasis on messaging. If you want to know something send an object a message and get an answer. IMHO, the ethos and the IDE really encourage you to do the right thing with your coupling and cohesion. In my Java day job, I’m stuck with files, generics, IDE’s like eclipse that are orders of magnitude less productive that any ST IDE. I was using ST the only time I finished a development ahead of schedule. In fact it was so productive, and we got so much reuse I had to be moved off to another project, as I had nothing to do! (Ok, maybe I could have spent time learning to estimate...) Download squeak, find a good book and play. Only downside is that if your day gig is using Java or C#, you’ll end up wishing you could use ST. You’d get home sooner. Chris Brooks A: I recommend everybody to learn Lisp (Scheme) or Smalltalk. Smalltalks have wonderful IDEs which you dont want to miss once you got over the culture shock. And yes, there are more than one free ones: Squeak, Dolphin, Smalltalk/X, and Visualworks (Non-Comercial). Lisp may be even cleaner in its mathematic foundation, though. regards PS: actually I recommend learning both ! A: Yes, I'm interested in it. Tried to start once already, but couldn't find a Smalltalk development environment that didn't cost both arms and a leg.
{ "language": "en", "url": "https://stackoverflow.com/questions/149042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: In SQL Server Management Studio can I search for assets across multiple databases? My everyday IDE is Eclipse which has a wonderful Open Resource feature (CTRL+SHIFT+R or Navigate > Open Resource) which allows the user to search for files/resources across multiple projects. I can't find a similar feature in SQL Server Management Studio, is there one? A: You can search for objects in a sql database using the Information Schema Views http://msdn.microsoft.com/en-us/library/ms186778.aspx There's one for tables, columns, functions, sprocs, etc. select * from INFORMATION_SCHEMA.routines where ROUTINE_DEFINITION like '%xp%_' A: I believe this is what you are looking for: http://www.red-gate.com/products/sql-development/sql-search/ It is completely free, and completely awesome. (source: red-gate.com) A: No. There is no default mechanism in SMS to be able to search across projects. A: You could use sp_MSforeachdb like so: sp_MSforeachdb 'SELECT * FROM ?.INFORMATION_SCHEMA.routines WHERE ROUTINE_TYPE = ''PROCEDURE''' The above will select all procedures across all databases and return them in different result sets. Using different views, you can also select tables, columns and so forth. A: I hope someone has a better answer to this than I do. In the past, I've used a CURSOR to search through all the databases and insert results into a temp table. I could then select from the temp table and show the results. I don't have this code laying around anymore. If no one comes up with a better answer, I'll come back and edit this with some real code. I would think that there'd be a DMV for this. Anyone? A: I made the following CLR stored proc to search all tables and all columns in a database with explicit parallelism. Maybe it does what you want. It doesn't search stored procs or functions, but you can look for values, column names, table names, etc, and it returns results in XML rows. Please note that this shouldn't be used in the day to day, but it's useful for occasional auditing or forensics/DBA tasks, and its definitely fast... Searches all tables on AdventureWorks in 2 seconds flat hosted on a modest desktop PC. https://pastebin.com/RRTrt8ZN /* This script creates a CLR stored procedure and its assembly on a database that will let you search for keywords separated by a space on all columns of all tables of all types except 'binary', 'varbinary', 'bit', 'timestamp', 'image', 'sql_variant', and 'hierarchyid'. This was made as a CLR stored proc to take advantage of explicit parallelism to make the search a lot faster. Be aware that this will use many cores so only use this for occasional DBA work. This has the potential to cause a DDoS type of situation if broad searches with many results are hammered into the server, since each request can try to parallelize its search. An optional parameter exists to limit parallelism to a set number of cores. You can also set filters on the tables or columns to search, including logical operators OR, AND, NOT, and parenthesis (see examples below). Results are returned as XML rows. To install you need owner rights. Also, because SQL Server doesn't allow secondary CLR threads access to the stored procedure context, we extract the connection string from the first context connection we make. This works fine, but only if you are connected with a trusted connection (using a Windows account). ------------------------------------------------------------------ -- CLR access must be enabled on the instance for this to work. -- ------------------------------------------------------------------ -- sp_configure 'show advanced options', 1; -- -- GO -- -- RECONFIGURE; -- -- GO -- -- sp_configure 'clr enabled', 1; -- -- GO -- -- RECONFIGURE; -- -- GO -- ------------------------------------------------------------------ ----------------------------------------------------------------------------------- -- Database needs to be flagged trustworthy to be able to access CLR assemblies. -- ----------------------------------------------------------------------------------- -- ALTER DATABASE [AdventureWorks] SET TRUSTWORTHY ON; -- ----------------------------------------------------------------------------------- Example usages: --------------- Using all available processors on the server: EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael' Limiting the server to 4 concurrent threads: EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @maxDegreeOfParallelism = 4 Using logical operators in search terms: EXEC [dbo].[SearchAllTables] @valueSearchTerm = '(john or michael) and not jack', @tablesSearchTerm = 'not contact' Limiting search to table names and/or column names containing some search terms: EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @tablesSearchTerm = 'person contact', @columnsSearchTerm = 'address name' Limiting search results to the first row of each table where the terms are found: EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @getOnlyFirstRowPerTable = 1 Limiting the search to the schema only automatically returns only the first row for each table: EXEC [dbo].[SearchAllTables] @tablesSearchTerm = 'person contact' Only return the search queries: EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john michael', @tablesSearchTerm = 'person contact', @onlyOutputQueries = 1 Capturing results into temporary table and sorting: CREATE TABLE #temp (Result NVARCHAR(MAX)); INSERT INTO #temp EXEC [dbo].[SearchAllTables] @valueSearchTerm = 'john'; SELECT * FROM #temp ORDER BY Result ASC; DROP TABLE #temp; */
{ "language": "en", "url": "https://stackoverflow.com/questions/149054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to format numbers as currency strings I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this: "$ 2,500.00" How can I do this? A: The YUI codebase uses the following formatting: format: function(nData, oConfig) { oConfig = oConfig || {}; if(!YAHOO.lang.isNumber(nData)) { nData *= 1; } if(YAHOO.lang.isNumber(nData)) { var sOutput = nData + ""; var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : "."; var nDotIndex; // Manage decimals if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) { // Round to the correct decimal place var nDecimalPlaces = oConfig.decimalPlaces; var nDecimal = Math.pow(10, nDecimalPlaces); sOutput = Math.round(nData*nDecimal)/nDecimal + ""; nDotIndex = sOutput.lastIndexOf("."); if(nDecimalPlaces > 0) { // Add the decimal separator if(nDotIndex < 0) { sOutput += sDecimalSeparator; nDotIndex = sOutput.length-1; } // Replace the "." else if(sDecimalSeparator !== "."){ sOutput = sOutput.replace(".",sDecimalSeparator); } // Add missing zeros while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) { sOutput += "0"; } } } // Add the thousands separator if(oConfig.thousandsSeparator) { var sThousandsSeparator = oConfig.thousandsSeparator; nDotIndex = sOutput.lastIndexOf(sDecimalSeparator); nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length; var sNewOutput = sOutput.substring(nDotIndex); var nCount = -1; for (var i=nDotIndex; i>0; i--) { nCount++; if ((nCount%3 === 0) && (i !== nDotIndex)) { sNewOutput = sThousandsSeparator + sNewOutput; } sNewOutput = sOutput.charAt(i-1) + sNewOutput; } sOutput = sNewOutput; } // Prepend prefix sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput; // Append suffix sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput; return sOutput; } // Still not a number. Just return it unaltered else { return nData; } } It would need editing as the YUI library is configurable, like replacing oConfig.decimalSeparator with ".". A: Patrick Desjardins (ex Daok)'s example worked well for me. I ported it over to CoffeeScript if anyone is interested. Number.prototype.toMoney = (decimals = 2, decimal_separator = ".", thousands_separator = ",") -> n = this c = if isNaN(decimals) then 2 else Math.abs decimals sign = if n < 0 then "-" else "" i = parseInt(n = Math.abs(n).toFixed(c)) + '' j = if (j = i.length) > 3 then j % 3 else 0 x = if j then i.substr(0, j) + thousands_separator else '' y = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_separator) z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else '' sign + x + y + z A: Here's another attempt, just for fun: function formatDollar(num) { var p = num.toFixed(2).split("."); return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) { return num + (num != "-" && i && !(i % 3) ? "," : "") + acc; }, "") + "." + p[1]; } And some tests: formatDollar(45664544.23423) // "$45,664,544.23" formatDollar(45) // "$45.00" formatDollar(123) // "$123.00" formatDollar(7824) // "$7,824.00" formatDollar(1) // "$1.00" formatDollar(-1345) // "$-1,345.00 formatDollar(-3) // "$-3.00" A: Works for all current browsers Use toLocaleString to format a currency in its language-sensitive representation (using ISO 4217 currency codes). (2500).toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2}) Example South African Rand code snippets for avenmore: console.log((2500).toLocaleString("en-ZA", {style: "currency", currency: "ZAR", minimumFractionDigits: 2})) // -> R 2 500,00 console.log((2500).toLocaleString("en-GB", {style: "currency", currency: "ZAR", minimumFractionDigits: 2})) // -> ZAR 2,500.00 A: A minimalistic approach that just meets the original requirements: function formatMoney(n) { return "$ " + (Math.round(n * 100) / 100).toLocaleString(); } @Daniel Magliola: You're right. The above was a hasty, incomplete implementation. Here's the corrected implementation: function formatMoney(n) { return "$ " + n.toLocaleString().split(".")[0] + "." + n.toFixed(2).split(".")[1]; } A: tggagne is correct. My solution below is not good due to float rounding. And the toLocaleString function lacks some browser support. I'll leave the below comments for archival purposes of what not to do. :) Date.prototype.toLocaleString() (Old Solution) Use Patrick Desjardins' solution instead. This is a terse solution that uses toLocaleString(), which has been supported since JavaScript version 1.0. This example designates the currency to U.S. Dollars, but could be switched to pounds by using 'GBP' instead of 'USD'. var formatMoney = function (value) { // Convert the value to a floating point number in case it arrives as a string. var numeric = parseFloat(value); // Specify the local currency. return numeric.toLocaleString('USD', { style: 'currency', currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 }); } See Internationalization and localization, Currencies for additional details. A: I think you want: f.nettotal.value = "$" + showValue.toFixed(2); A: A function to handle currency output, including negatives. Sample Output: $5.23 -$5.23 function formatCurrency(total) { var neg = false; if(total < 0) { neg = true; total = Math.abs(total); } return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString(); } A: Another way: function centsToDollaString(x){ var cents = x + "" while(cents.length < 4){ cents = "0" + cents; } var dollars = cents.substr(0,cents.length - 2) var decimal = cents.substr(cents.length - 2, 2) while(dollars.length % 3 != 0){ dollars = "0" + dollars; } str = dollars.replace(/(\d{3})(?=\d)/g, "$1" + ",").replace(/^0*(?=.)/, ""); return "$" + str + "." + decimal; } A: http://code.google.com/p/javascript-number-formatter/: * *Short, fast, flexible yet stand-alone. Only 75 lines including MIT license info, blank lines & comments. *Accept standard number formatting like #,##0.00 or with negation -000.####. *Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol. *Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid. *Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK. *Auto number rounding. *Simple interface, just supply mask & value like this: format( "0.0000", 3.141592) UPDATE This is my home-grown pp utilities for most common tasks: var NumUtil = {}; /** Petty print 'num' wth exactly 'signif' digits. pp(123.45, 2) == "120" pp(0.012343, 3) == "0.0123" pp(1.2, 3) == "1.20" */ NumUtil.pp = function(num, signif) { if (typeof(num) !== "number") throw 'NumUtil.pp: num is not a number!'; if (isNaN(num)) throw 'NumUtil.pp: num is NaN!'; if (num < 1e-15 || num > 1e15) return num; var r = Math.log(num)/Math.LN10; var dot = Math.floor(r) - (signif-1); r = r - Math.floor(r) + (signif-1); r = Math.round(Math.exp(r * Math.LN10)).toString(); if (dot >= 0) { for (; dot > 0; dot -= 1) r += "0"; return r; } else if (-dot >= r.length) { var p = "0."; for (; -dot > r.length; dot += 1) { p += "0"; } return p+r; } else { return r.substring(0, r.length + dot) + "." + r.substring(r.length + dot); } } /** Append leading zeros up to 2 digits. */ NumUtil.align2 = function(v) { if (v < 10) return "0"+v; return ""+v; } /** Append leading zeros up to 3 digits. */ NumUtil.align3 = function(v) { if (v < 10) return "00"+v; else if (v < 100) return "0"+v; return ""+v; } NumUtil.integer = {}; /** Round to integer and group by 3 digits. */ NumUtil.integer.pp = function(num) { if (typeof(num) !== "number") { console.log("%s", new Error().stack); throw 'NumUtil.integer.pp: num is not a number!'; } if (isNaN(num)) throw 'NumUtil.integer.pp: num is NaN!'; if (num > 1e15) return num; if (num < 0) throw 'Negative num!'; num = Math.round(num); var group = num % 1000; var integ = Math.floor(num / 1000); if (integ === 0) { return group; } num = NumUtil.align3(group); while (true) { group = integ % 1000; integ = Math.floor(integ / 1000); if (integ === 0) return group + " " + num; num = NumUtil.align3(group) + " " + num; } return num; } NumUtil.currency = {}; /** Round to coins and group by 3 digits. */ NumUtil.currency.pp = function(amount) { if (typeof(amount) !== "number") throw 'NumUtil.currency.pp: amount is not a number!'; if (isNaN(amount)) throw 'NumUtil.currency.pp: amount is NaN!'; if (amount > 1e15) return amount; if (amount < 0) throw 'Negative amount!'; if (amount < 1e-2) return 0; var v = Math.round(amount*100); var integ = Math.floor(v / 100); var frac = NumUtil.align2(v % 100); var group = integ % 1000; integ = Math.floor(integ / 1000); if (integ === 0) { return group + "." + frac; } amount = NumUtil.align3(group); while (true) { group = integ % 1000; integ = Math.floor(integ / 1000); if (integ === 0) return group + " " + amount + "." + frac; amount = NumUtil.align3(group) + " " + amount; } return amount; } A: Intl.NumberFormat var number = 3500; alert(new Intl.NumberFormat().format(number)); // → "3,500" if in US English locale Or PHP's number_format in JavaScript. A: We can also use numeraljs Numbers can be formatted to look like currency, percentages, times, or even plain old numbers with decimal places, thousands, and abbreviations. And you can always create a custom format. var string = numeral(1000).format('0,0'); // '1,000' A: This answer meets the following criteria: * *Does not depend on an external dependency. *Does support localization. *Does have tests/proofs. *Does use simple and best coding practices (no complicated regex's and uses standard coding patterns). This code is built on concepts from other answers. Its execution speed should be among the better posted here if that's a concern. var decimalCharacter = Number("1.1").toLocaleString().substr(1,1); var defaultCurrencyMarker = "$"; function formatCurrency(number, currencyMarker) { if (typeof number != "number") number = parseFloat(number, 10); // if NaN is passed in or comes from the parseFloat, set it to 0. if (isNaN(number)) number = 0; var sign = number < 0 ? "-" : ""; number = Math.abs(number); // so our signage goes before the $ symbol. var integral = Math.floor(number); var formattedIntegral = integral.toLocaleString(); // IE returns "##.00" while others return "##" formattedIntegral = formattedIntegral.split(decimalCharacter)[0]; var decimal = Math.round((number - integral) * 100); return sign + (currencyMarker || defaultCurrencyMarker) + formattedIntegral + decimalCharacter + decimal.toString() + (decimal < 10 ? "0" : ""); } These tests only work on a US locale machine. This decision was made for simplicity and because this could cause of crappy input (bad auto-localization) allowing for crappy output issues. var tests = [ // [ input, expected result ] [123123, "$123,123.00"], // no decimal [123123.123, "$123,123.12"], // decimal rounded down [123123.126, "$123,123.13"], // decimal rounded up [123123.4, "$123,123.40"], // single decimal ["123123", "$123,123.00"], // repeat subset of the above using string input. ["123123.123", "$123,123.12"], ["123123.126", "$123,123.13"], [-123, "-$123.00"] // negatives ]; for (var testIndex=0; testIndex < tests.length; testIndex++) { var test = tests[testIndex]; var formatted = formatCurrency(test[0]); if (formatted == test[1]) { console.log("Test passed, \"" + test[0] + "\" resulted in \"" + formatted + "\""); } else { console.error("Test failed. Expected \"" + test[1] + "\", got \"" + formatted + "\""); } } A: Here is the short and best one to convert numbers into a currency format: function toCurrency(amount){ return amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); } // usage: toCurrency(3939920.3030); A: The code from Jonathan M looked too complicated for me, so I rewrote it and got about 30% on Firefox v30 and 60% on Chrome v35 speed boost (http://jsperf.com/number-formating2): Number.prototype.formatNumber = function(decPlaces, thouSeparator, decSeparator) { decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces; decSeparator = decSeparator == undefined ? "." : decSeparator; thouSeparator = thouSeparator == undefined ? "," : thouSeparator; var n = this.toFixed(decPlaces); if (decPlaces) { var i = n.substr(0, n.length - (decPlaces + 1)); var j = decSeparator + n.substr(-decPlaces); } else { i = n; j = ''; } function reverse(str) { var sr = ''; for (var l = str.length - 1; l >= 0; l--) { sr += str.charAt(l); } return sr; } if (parseInt(i)) { i = reverse(reverse(i).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator)); } return i + j; }; Usage: var sum = 123456789.5698; var formatted = '$' + sum.formatNumber(2, ',', '.'); // "$123,456,789.57" A: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat Example: Using locales This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var number = 123456.789; // German uses comma as decimal separator and period for thousands console.log(new Intl.NumberFormat('de-DE').format(number)); // → 123.456,789 // Arabic in most Arabic speaking countries uses real Arabic digits console.log(new Intl.NumberFormat('ar-EG').format(number)); // → ١٢٣٤٥٦٫٧٨٩ // India uses thousands/lakh/crore separators console.log(new Intl.NumberFormat('en-IN').format(number)); A: toLocaleString is good, but it doesn't work in all browsers. I usually use currencyFormatter.js (https://osrec.github.io/currencyFormatter.js/). It's pretty lightweight and contains all the currency and locale definitions right out of the box. It's also good at formatting unusually formatted currencies, such as the INR (which groups numbers in lakhs, crores, etc.). Also, there aren't any dependencies! OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); // Returns ₹ 25,34,234.00 OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); // Returns 2.534.234,00 € OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); // Returns 2 534 234,00 € A: just use the native javascript Intl you just use the options to format its value const number = 1233445.5678 console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number)); mozilla documentation link A: Take a look at the JavaScript Number object and see if it can help you. * *toLocaleString() will format a number using location specific thousands separator. *toFixed() will round the number to a specific number of decimal places. To use these at the same time the value must have its type changed back to a number because they both output a string. Example: Number((someNumber).toFixed(1)).toLocaleString() EDIT One can just use toLocaleString directly and its not necessary to recast to a number: someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}); Multiple numbers If you need to frequently format numbers similarly you can create a specific object for reuse. Like for German (Switzerland): const money = new Intl.NumberFormat('de-CH', { style:'currency', currency: 'CHF' }); const percent = new Intl.NumberFormat('de-CH', { style:'percent', maximumFractionDigits: 1, signDisplay: "always"}); which than can be used as: money.format(1234.50); // output CHF 1'234.50 percent.format(0.083); // output +8.3% Pretty nifty. A: Ok, based on what you said, I'm using this: var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1); var AmountWithCommas = Amount.toLocaleString(); var arParts = String(AmountWithCommas).split(DecimalSeparator); var intPart = arParts[0]; var decPart = (arParts.length > 1 ? arParts[1] : ''); decPart = (decPart + '00').substr(0,2); return '£ ' + intPart + DecimalSeparator + decPart; I'm open to improvement suggestions (I'd prefer not to include YUI just to do this :-) ) I already know I should be detecting the "." instead of just using it as the decimal separator... A: This might work: function format_currency(v, number_of_decimals, decimal_separator, currency_sign){ return (isNaN(v)? v : currency_sign + parseInt(v||0).toLocaleString() + decimal_separator + (v*1).toFixed(number_of_decimals).slice(-number_of_decimals)); } No loops, no regexes, no arrays, no exotic conditionals. A: A quicker way with regexp: Number.prototype.toMonetaryString = function() { var n = this.toFixed(2), m; //var = this.toFixed(2).replace(/\./, ','); For comma separator // with a space for thousands separator while ((m = n.replace(/(\d)(\d\d\d)\b/g, '$1 $2')) != n) n = m; return m; } String.prototype.fromMonetaryToNumber = function(s) { return this.replace(/[^\d-]+/g, '')/100; } A: There is no equivalent of "formatNumber" in JavaScript. You can write it yourself or find a library that already does this. A: Here is a mootools 1.2 implementation from the code provided by XMLilley... Number.implement('format', function(decPlaces, thouSeparator, decSeparator){ decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces; decSeparator = decSeparator === undefined ? '.' : decSeparator; thouSeparator = thouSeparator === undefined ? ',' : thouSeparator; var num = this, sign = num < 0 ? '-' : '', i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + '', j = (j = i.length) > 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : ''); }); A: I based this heavily on the answer from VisioN: function format (val) { val = (+val).toLocaleString(); val = (+val).toFixed(2); val += ""; return val.replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1" + format.thousands); } (function (isUS) { format.decimal = isUS ? "." : ","; format.thousands = isUS ? "," : "."; }(("" + (+(0.00).toLocaleString()).toFixed(2)).indexOf(".") > 0)); I tested with inputs: [ "" , "1" , "12" , "123" , "1234" , "12345" , "123456" , "1234567" , "12345678" , "123456789" , "1234567890" , ".12" , "1.12" , "12.12" , "123.12" , "1234.12" , "12345.12" , "123456.12" , "1234567.12" , "12345678.12" , "123456789.12" , "1234567890.12" , "1234567890.123" , "1234567890.125" ].forEach(function (item) { console.log(format(item)); }); And got these results: 0.00 1.00 12.00 123.00 1,234.00 12,345.00 123,456.00 1,234,567.00 12,345,678.00 123,456,789.00 1,234,567,890.00 0.12 1.12 12.12 123.12 1,234.12 12,345.12 123,456.12 1,234,567.12 12,345,678.12 123,456,789.12 1,234,567,890.12 1,234,567,890.12 1,234,567,890.13 Just for fun. A: I like the shortest answer by VisionN except when I need to modify it for a number without a decimal point ($123 instead of $123.00). It does not work, so instead of quick copy/paste I need to decipher the arcane syntax of the JavaScript regular expression. Here is the original solution n.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); I'll make it a bit longer: var re = /\d(?=(\d{3})+\.)/g; var subst = '$&,'; n.toFixed(2).replace(re, subst); The re part here (search part in string replace) means * *Find all digits (\d) *Followed by (?= ...) (lookahead) *One or more groups (...)+ *Of exactly three digits (\d{3}) *Ending with a dot (\.) *Do it for all occurrences (g) The subst part here means: * *Every time there is a match, replace it with itself ($&), followed by a comma. As we use string.replace, all other text in the string remains the same and only found digits (those that are followed by 3, 6, 9, etc. other digits) get an additional comma. So in a number, 1234567.89, digits 1 and 4 meet the condition (1234567.89) and are replaced with "1," and "4," resulting in 1,234,567.89. If we don't need the decimal point in dollar amount at all (i.e., $123 instead of $123.00), we may change the regular expression like this: var re2 = /\d(?=(\d{3})+$)/g; It relies on the end of line ($) instead of a dot (\.) and the final expression will be (notice also toFixed(0)): n.toFixed(0).replace(/\d(?=(\d{3})+$)/g, '$&,'); This expression will give 1234567.89 -> 1,234,567 Also instead of end of line ($) in the regular expression above, you may opt for a word boundary as well (\b). My apology in advance if I misinterpreted any part of the regular expression handling. A: Many of the answers had helpful ideas, but none of them could fit my needs. So I used all the ideas and build this example: function Format_Numb(fmt){ var decimals = isNaN(decimals) ? 2 : Math.abs(decimals); if(typeof decSgn === "undefined") decSgn = "."; if(typeof kommaSgn === "undefined") kommaSgn= ","; var s3digits = /(\d{1,3}(?=(\d{3})+(?=[.]|$))|(?:[.]\d*))/g; var dflt_nk = "00000000".substring(0, decimals); //-------------------------------- // handler for pattern: "%m" var _f_money = function(v_in){ var v = v_in.toFixed(decimals); var add_nk = ",00"; var arr = v.split("."); return arr[0].toString().replace(s3digits, function ($0) { return ($0.charAt(0) == ".") ? ((add_nk = ""), (kommaSgn + $0.substring(1))) : ($0 + decSgn); }) + ((decimals > 0) ? (kommaSgn + ( (arr.length > 1) ? arr[1] : dflt_nk ) ) : "" ); } // handler for pattern: "%<len>[.<prec>]f" var _f_flt = function(v_in, l, prec){ var v = (typeof prec !== "undefined") ? v_in.toFixed(prec) : v_in; return ((typeof l !== "undefined") && ((l=l-v.length) > 0)) ? (Array(l+1).join(" ") + v) : v; } // handler for pattern: "%<len>x" var _f_hex = function(v_in, l, flUpper){ var v = Math.round(v_in).toString(16); if(flUpper) v = v.toUpperCase(); return ((typeof l !== "undefined") && ((l=l-v.length) > 0)) ? (Array(l+1).join("0") + v) : v; } //...can be extended..., just add the function, for example: var _f_octal = function( v_in,...){ //-------------------------------- if(typeof(fmt) !== "undefined"){ //...can be extended..., just add the char, for example "O": MFX -> MFXO var rpatt = /(?:%([^%"MFX]*)([MFX]))|(?:"([^"]*)")|("|%%)/gi; var _qu = "\""; var _mask_qu = "\\\""; var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){ var f; if(typeof $1 !== "undefined"){ switch($2.toUpperCase()){ case "M": f = "_f_money(v)"; break; case "F": var n_dig0, n_dig1; var re_flt =/^(?:(\d))*(?:[.](\d))*$/; $1.replace(re_flt, function($0, $1, $2){ n_dig0 = $1; n_dig1 = $2; }); f = "_f_flt(v, " + n_dig0 + "," + n_dig1 + ")"; break; case "X": var n_dig = "undefined"; var re_flt = /^(\d*)$/; $1.replace(re_flt, function($0){ if($0 != "") n_dig = $0; }); f = "_f_hex(v, " + n_dig + "," + ($2=="X") + ")"; break; //...can be extended..., for example: case "O": } return "\"+"+f+"+\""; } else if(typeof $3 !== "undefined"){ return _mask_qu + $3 + _mask_qu; } else { return ($4 == _qu) ? _mask_qu : $4.charAt(0); } }); var cmd = "return function(v){" + "if(typeof v === \"undefined\")return \"\";" // null returned as empty string + "if(!v.toFixed) return v.toString();" // not numb returned as string + "return \"" + str + "\";" + "}"; //...can be extended..., just add the function name in the 2 places: return new Function("_f_money,_f_flt,_f_hex", cmd)(_f_money,_f_flt,_f_hex); } } First, I needed a C-style format-string-definition that should be flexible, but very easy to use and I defined it in following way; patterns: %[<len>][.<prec>]f float, example "%f", "%8.2d", "%.3f" %m money %[<len>]x hexadecimal lower case, example "%x", "%8x" %[<len>]X hexadecimal upper case, example "%X", "%8X" Because there isn't any need to format others than to euro for me, I implemented only "%m". But it's easy to extend this... Like in C, the format string is a string containing the patterns. For example, for euro: "%m €" (returns strings like "8.129,33 €") Besides the flexibility, I needed a very fast solution for processing tables. That means that, when processing thousands of cells, the processing of format string must not be done more than once. A call like "format( value, fmt)" is not acceptable for me, but this must be split into two steps: // var formatter = Format_Numb( "%m €"); // simple example for Euro... // but we use a complex example: var formatter = Format_Numb("a%%%3mxx \"zz\"%8.2f°\" >0x%8X<"); // formatter is now a function, which can be used more than once (this is an example, that can be tested:) var v1 = formatter(1897654.8198344); var v2 = formatter(4.2); ... (and thousands of rows) Also for performance, _f_money encloses the regular expression; Third, a call like "format( value, fmt)" is not acceptable because: Although it should be possible to format different collections of objects (for example, cells of a column) with different masks, I don't want to have something to handle format strings at the point of processing. At this point I only want to use formatting, like in for( var cell in cells){ do_something( cell.col.formatter( cell.value)); } What format - maybe it's defined in an .ini file, in an XML for each column or somewhere else ..., but analyzing and setting formats or dealing with internationalizaton is processed in totally another place, and there I want to assign the formatter to the collection without thinking about performance issues: col.formatter = Format_Numb( _getFormatForColumn(...) ); Fourth, I wanted an "tolerant" solution, so passing, for example, a string instead of a number should return simply the string, but "null" should return en empty string. (Also formatting "%4.2f" must not cut something if the value is too big.) And last, but not least - it should be readable and easy extendable, without having any effects in performance... For example, if somebody needs "octal values", please refer to lines with "...can be extended..." - I think that should be a very easy task. My overall focus lay on performance. Each "processing routine" (for example, _f_money) can be encapsulated optimized or exchanged with other ideas in this or other threads without change of the "prepare routines" (analyze format strings and creation of the functions), which must only be processed once and in that sense are not so performance critical like the conversion calls of thousands of numbers. For all, who prefer methods of numbers: Number.prototype.format_euro = (function(formatter){ return function(){ return formatter(this); }}) (Format_Numb( "%m €")); var v_euro = (8192.3282).format_euro(); // results: 8.192,33 € Number.prototype.format_hex = (function(formatter){ return function(){ return formatter(this); }}) (Format_Numb( "%4x")); var v_hex = (4.3282).format_hex(); Although I tested some, there may be a lot of bugs in the code. So it's not a ready module, but just an idea and a starting point for non-JavaScript experts like me. The code contains many and little modified ideas from a lot of Stack Overflow posts; sorry I can't reference all of them, but thanks to all the experts. A: I had a hard time finding a simple library to work with date and currency, so I created my own: https://github.com/dericeira/slimFormatter.js Simple as that: var number = slimFormatter.currency(2000.54); A: Because every problem deserves a one-line solution: Number.prototype.formatCurrency = function() { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\d)(?=(\d{3})+$)/g, '$1,') : t + '.' + c; }, '$'); } This is easy enough to change for different locales. Just change the '$1,' to '$1.' and '.' to ',' to swap , and . in numbers. The currency symbol can be changed by changing the '$' at the end. Or, if you have ES6, you can just declare the function with default values: Number.prototype.formatCurrency = function(thou = ',', dec = '.', sym = '$') { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\d)(?=(\d{3})+$)/g, '$1' + thou) : t + dec + c; }, sym); } console.log((4215.57).formatCurrency()) $4,215.57 console.log((4216635.57).formatCurrency('.', ',')) $4.216.635,57 console.log((4216635.57).formatCurrency('.', ',', "\u20AC")) €4.216.635,57 Oh and it works for negative numbers too: console.log((-6635.574).formatCurrency('.', ',', "\u20AC")) -€6.635,57 console.log((-1066.507).formatCurrency()) -$1,066.51 And of course you don't have to have a currency symbol: console.log((1234.586).formatCurrency(',','.','')) 1,234.59 console.log((-7890123.456).formatCurrency(',','.','')) -7,890,123.46 console.log((1237890.456).formatCurrency('.',',','')) 1.237.890,46 A: Numeral.js - a JavaScript library for easy number formatting by @adamwdraper numeral(23456.789).format('$0,0.00'); // = "$23,456.79" A: The following is concise, easy to understand, and doesn't rely on any overly complicated regular expressions. function moneyFormat(price, sign = '$') { const pieces = parseFloat(price).toFixed(2).split('') let ii = pieces.length - 3 while ((ii-=3) > 0) { pieces.splice(ii, 0, ',') } return sign + pieces.join('') } console.log( moneyFormat(100), moneyFormat(1000), moneyFormat(10000.00), moneyFormat(1000000000000000000) ) Here is a version with more options in the final output to allow formatting different currencies in different locality formats. // higher order function that takes options then a price and will return the formatted price const makeMoneyFormatter = ({ sign = '$', delimiter = ',', decimal = '.', append = false, precision = 2, round = true, custom } = {}) => value => { const e = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000] value = round ? (Math.round(value * e[precision]) / e[precision]) : parseFloat(value) const pieces = value .toFixed(precision) .replace('.', decimal) .split('') let ii = pieces.length - (precision ? precision + 1 : 0) while ((ii-=3) > 0) { pieces.splice(ii, 0, delimiter) } if (typeof custom === 'function') { return custom({ sign, float: value, value: pieces.join('') }) } return append ? pieces.join('') + sign : sign + pieces.join('') } // create currency converters with the correct formatting options const formatDollar = makeMoneyFormatter() const formatPound = makeMoneyFormatter({ sign: '£', precision: 0 }) const formatEuro = makeMoneyFormatter({ sign: '€', delimiter: '.', decimal: ',', append: true }) const customFormat = makeMoneyFormatter({ round: false, custom: ({ value, float, sign }) => `SALE:$${value}USD` }) console.log( formatPound(1000), formatDollar(10000.0066), formatEuro(100000.001), customFormat(999999.555) ) A: I use the library Globalize (from Microsoft): It's a great project to localize numbers, currencies and dates and to have them automatically formatted the right way according to the user locale! ...and despite it should be a jQuery extension, it's currently a 100% independent library. I suggest you all to try it out! :) A: Intl.NumberFormat JavaScript has a number formatter (part of the Internationalization API). // Create our number formatter. const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', // These options are needed to round to whole numbers if that's what you want. //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1) //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501) }); console.log(formatter.format(2500)); /* $2,500.00 */ Use undefined in place of the first argument ('en-US' in the example) to use the system locale (the user locale in case the code is running in a browser). Further explanation of the locale code. Here's a list of the currency codes. Intl.NumberFormat vs Number.prototype.toLocaleString A final note comparing this to the older .toLocaleString. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) does not actually support locales: it uses the system locale. So when debugging old browsers, be sure that you're using the correct version (MDN suggests to check for the existence of Intl). There isn't any need to worry about this at all if you don't care about old browsers or just use the shim. Also, the performance of both is the same for a single item, but if you have a lot of numbers to format, using Intl.NumberFormat is ~70 times faster. Therefore, it's usually best to use Intl.NumberFormat and instantiate only once per page load. Anyway, here's the equivalent usage of toLocaleString: console.log((2500).toLocaleString('en-US', { style: 'currency', currency: 'USD', })); /* $2,500.00 */ Some notes on browser support and Node.js * *Browser support is no longer an issue nowadays with 98% support globally, 99% in the US and 99+% in the EU *There is a shim to support it on fossilized browsers (like Internet Explorer 8), should you really need to *Node.js before v13 only supports en-US out of the box. One solution is to install full-icu, see here for more information *Have a look at CanIUse for more information A: javascript-number-formatter (formerly at Google Code) * *Short, fast, flexible yet stand-alone. *Accept standard number formatting like #,##0.00 or with negation -000.####. *Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol. *Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid. *Accept any redundant/foolproof formatting. ##,###,##.# or 0#,#00#.###0# are all OK. *Auto number rounding. *Simple interface, just supply mask & value like this: format( "0.0000", 3.141592). *Include a prefix & suffix with the mask (excerpt from its README) A: A shorter method (for inserting space, comma or point) with a regular expression: Number.prototype.toCurrencyString = function(){ return this.toFixed(2).replace(/(\d)(?=(\d{3})+\b)/g, '$1 '); } n = 12345678.9; alert(n.toCurrencyString()); A: +1 to Jonathan M for providing the original method. Since this is explicitly a currency formatter, I went ahead and added the currency symbol (defaults to '$') to the output, and added a default comma as the thousands separator. If you don't actually want a currency symbol (or thousands separator), just use "" (empty string) as your argument for it. Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) { // check the args and supply defaults: decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces; decSeparator = decSeparator == undefined ? "." : decSeparator; thouSeparator = thouSeparator == undefined ? "," : thouSeparator; currencySymbol = currencySymbol == undefined ? "$" : currencySymbol; var n = this, sign = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "", j = (j = i.length) > 3 ? j % 3 : 0; return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : ""); }; A: The main part is inserting the thousand-separators, and that could be done like this: <script type="text/javascript"> function ins1000Sep(val) { val = val.split("."); val[0] = val[0].split("").reverse().join(""); val[0] = val[0].replace(/(\d{3})/g, "$1,"); val[0] = val[0].split("").reverse().join(""); val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0]; return val.join("."); } function rem1000Sep(val) { return val.replace(/,/g, ""); } function formatNum(val) { val = Math.round(val*100)/100; val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00"; var dec = val.indexOf("."); return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3); } </script> <button onclick="alert(ins1000Sep(formatNum(12313231)));"> A: There is a JavaScript port of the PHP function "number_format". I find it very useful as it is easy to use and recognisable for PHP developers. function number_format (number, decimals, dec_point, thousands_sep) { var n = number, prec = decimals; var toFixedFix = function (n,prec) { var k = Math.pow(10,prec); return (Math.round(n*k)/k).toString(); }; n = !isFinite(+n) ? 0 : +n; prec = !isFinite(+prec) ? 0 : Math.abs(prec); var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep; var dec = (typeof dec_point === 'undefined') ? '.' : dec_point; var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); // Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0; var abs = toFixedFix(Math.abs(n), prec); var _, i; if (abs >= 1000) { _ = abs.split(/\D/); i = _[0].length % 3 || 3; _[0] = s.slice(0,i + (n < 0)) + _[0].slice(i).replace(/(\d{3})/g, sep+'$1'); s = _.join(dec); } else { s = s.replace('.', dec); } var decPos = s.indexOf(dec); if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) { s += new Array(prec-(s.length-decPos-1)).join(0)+'0'; } else if (prec >= 1 && decPos === -1) { s += dec+new Array(prec).join(0)+'0'; } return s; } (Comment block from the original, included below for examples & credit where due) // Formats a number with grouped thousands // // version: 906.1806 // discuss at: http://phpjs.org/functions/number_format // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfix by: Michael White (http://getsprink.com) // + bugfix by: Benjamin Lupton // + bugfix by: Allan Jensen (http://www.winternet.no) // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) // + bugfix by: Howard Yeend // + revised by: Luke Smith (http://lucassmith.name) // + bugfix by: Diogo Resende // + bugfix by: Rival // + input by: Kheang Hok Chin (http://www.distantia.ca/) // + improved by: davook // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: Jay Klehr // + improved by: Brett Zamir (http://brett-zamir.me) // + input by: Amir Habibi (http://www.residence-mixte.com/) // + bugfix by: Brett Zamir (http://brett-zamir.me) // * example 1: number_format(1234.56); // * returns 1: '1,235' // * example 2: number_format(1234.56, 2, ',', ' '); // * returns 2: '1 234,56' // * example 3: number_format(1234.5678, 2, '.', ''); // * returns 3: '1234.57' // * example 4: number_format(67, 2, ',', '.'); // * returns 4: '67,00' // * example 5: number_format(1000); // * returns 5: '1,000' // * example 6: number_format(67.311, 2); // * returns 6: '67.31' // * example 7: number_format(1000.55, 1); // * returns 7: '1,000.6' // * example 8: number_format(67000, 5, ',', '.'); // * returns 8: '67.000,00000' // * example 9: number_format(0.9, 0); // * returns 9: '1' // * example 10: number_format('1.20', 2); // * returns 10: '1.20' // * example 11: number_format('1.20', 4); // * returns 11: '1.2000' // * example 12: number_format('1.2000', 3); // * returns 12: '1.200' A: Please try the below code "250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); Ans: 250,000 A: Patrick Desjardins' answer looks good, but I prefer my JavaScript code simple. Here's a function I just wrote to take a number in and return it in currency format (minus the dollar sign): // Format numbers to two decimals with commas function formatDollar(num) { var p = num.toFixed(2).split("."); var chars = p[0].split("").reverse(); var newstr = ''; var count = 0; for (x in chars) { count++; if(count%3 == 1 && count != 1) { newstr = chars[x] + ',' + newstr; } else { newstr = chars[x] + newstr; } } return newstr + "." + p[1]; } A: function getMoney(A){ var a = new Number(A); var b = a.toFixed(2); // Get 12345678.90 a = parseInt(a); // Get 12345678 b = (b-a).toPrecision(2); // Get 0.90 b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00 a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00 // If Internet Explorer (our number ends in .00) if(a < 1 && a.lastIndexOf('.00') == (a.length - 3)) { a = a.substr(0, a.length-3); // Delete the .00 } return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90 } alert(getMoney(12345678.9)); This works in Firefox and Internet Explorer. A: String.prototype.toPrice = function () { var v; if (/^\d+(,\d+)$/.test(this)) v = this.replace(/,/, '.'); else if (/^\d+((,\d{3})*(\.\d+)?)?$/.test(this)) v = this.replace(/,/g, ""); else if (/^\d+((.\d{3})*(,\d+)?)?$/.test(this)) v = this.replace(/\./g, "").replace(/,/, "."); var x = parseFloat(v).toFixed(2).toString().split("."), x1 = x[0], x2 = ((x.length == 2) ? "." + x[1] : ".00"), exp = /^([0-9]+)(\d{3})/; while (exp.test(x1)) x1 = x1.replace(exp, "$1" + "," + "$2"); return x1 + x2; } alert("123123".toPrice()); //123,123.00 alert("123123,316".toPrice()); //123,123.32 alert("12,312,313.33213".toPrice()); //12,312,313.33 alert("123.312.321,32132".toPrice()); //123,312,321.32 A: CoffeeScript for Patrick's popular answer: Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) -> n = this c = decimalPlaces d = decimalChar t = thousandsChar c = (if isNaN(c = Math.abs(c)) then 2 else c) d = (if d is undefined then "." else d) t = (if t is undefined then "," else t) s = (if n < 0 then "-" else "") i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + "" j = (if (j = i.length) > 3 then j % 3 else 0) s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "") A: There are already good answers. Here's a simple attempt for fun: function currencyFormat(no) { var ar = (+no).toFixed(2).split('.'); return [ numberFormat(ar[0] | 0), '.', ar[1] ].join(''); } function numberFormat(no) { var str = no + ''; var ar = []; var i = str.length -1; while(i >= 0) { ar.push((str[i-2] || '') + (str[i-1] || '') + (str[i] || '')); i = i-3; } return ar.reverse().join(','); } Then run some examples: console.log( currencyFormat(1), currencyFormat(1200), currencyFormat(123), currencyFormat(9870000), currencyFormat(12345), currencyFormat(123456.232) ) A: I want to contribute with this: function toMoney(amount) { neg = amount.charAt(0); amount = amount.replace(/\D/g, ''); amount = amount.replace(/\./g, ''); amount = amount.replace(/\-/g, ''); var numAmount = new Number(amount); amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) { return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c; }); if(neg == '-') return neg + amount; else return amount; } This allows you to convert numbers in a text box where you are only supposed to put numbers (consider this scenario). This is going to clean a textbox where there are only supposed to be numbers, even if you paste a string with numbers and letters or any character <html> <head> <script language=="Javascript"> function isNumber(evt) { var theEvent = evt || window.event; var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode(key); if (key.length == 0) return; var regex = /^[0-9\-\b]+$/; if (!regex.test(key)) { theEvent.returnValue = false; if (theEvent.preventDefault) theEvent.preventDefault(); } } function toMoney(amount) { neg = amount.charAt(0); amount = amount.replace(/\D/g, ''); amount = amount.replace(/\./g, ''); amount = amount.replace(/\-/g, ''); var numAmount = new Number(amount); amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) { return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c; }); if(neg == '-') return neg + amount; else return amount; } function clearText(inTxt, newTxt, outTxt) { inTxt = inTxt.trim(); newTxt = newTxt.trim(); if(inTxt == '' || inTxt == newTxt) return outTxt; return inTxt; } function fillText(inTxt, outTxt) { inTxt = inTxt.trim(); if(inTxt != '') outTxt = inTxt; return outTxt; } </script> </head> <body> $ <input name=reca2 id=reca2 type=text value="0" onFocus="this.value = clearText(this.value, '0', '');" onblur="this.value = fillText(this.value, '0'); this.value = toMoney(this.value);" onKeyPress="isNumber(event);" style="width:80px;" /> </body> </html> A: Here's a straightforward formatter in vanilla JavaScript: function numberFormatter (num) { console.log(num) var wholeAndDecimal = String(num.toFixed(2)).split("."); console.log(wholeAndDecimal) var reversedWholeNumber = Array.from(wholeAndDecimal[0]).reverse(); var formattedOutput = []; reversedWholeNumber.forEach( (digit, index) => { formattedOutput.push(digit); if ((index + 1) % 3 === 0 && index < reversedWholeNumber.length - 1) { formattedOutput.push(","); } }) formattedOutput = formattedOutput.reverse().join('') + "." + wholeAndDecimal[1]; return formattedOutput; } A: I wanted a vanilla JavaScript solution that automatically returned the decimal portion. function formatDollar(amount) { var dollar = Number(amount).toLocaleString("us", "currency"); // Decimals var arrAmount = dollar.split("."); if (arrAmount.length==2) { var decimal = arrAmount[1]; if (decimal.length==1) { arrAmount[1] += "0"; } } if (arrAmount.length==1) { arrAmount.push("00"); } return "$" + arrAmount.join("."); } console.log(formatDollar("1812.2"); A: Number.prototype.toFixed This solution is compatible with every single major browser: const profits = 2489.8237; profits.toFixed(3) // Returns 2489.824 (rounds up) profits.toFixed(2) // Returns 2489.82 profits.toFixed(7) // Returns 2489.8237000 (pads the decimals) All you need is to add the currency symbol (e.g. "$" + profits.toFixed(2)) and you will have your amount in dollars. Custom function If you require the use of , between each digit, you can use this function: function formatMoney(number, decPlaces, decSep, thouSep) { decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces, decSep = typeof decSep === "undefined" ? "." : decSep; thouSep = typeof thouSep === "undefined" ? "," : thouSep; var sign = number < 0 ? "-" : ""; var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces))); var j = (j = i.length) > 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSep : "") + i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) + (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : ""); } document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); }); <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p> Use it like so: (123456789.12345).formatMoney(2, ".", ","); If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you. (123456789.12345).formatMoney(2); If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney method: d = d == undefined ? "," : d, t = t == undefined ? "." : t, Custom function (ES6) If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead: function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") { try { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); } catch (e) { console.log(e) } }; document.getElementById("b").addEventListener("click", event => { document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); }); <label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p> A: There is a built-in function, toFixed, in JavaScript: var num = new Number(349); document.write("$" + num.toFixed(2)); A: Below is the Patrick Desjardins (alias Daok) code with a bit of comments added and some minor changes: /* decimal_sep: character used as decimal separator, it defaults to '.' when omitted thousands_sep: char used as thousands separator, it defaults to ',' when omitted */ Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep) { var n = this, c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator) /* According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function] the fastest way to check for not defined parameter is to use typeof value === 'undefined' rather than doing value === undefined. */ t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value sign = (n < 0) ? '-' : '', // Extracting the absolute value of the integer part of the number and converting to string i = parseInt(n = Math.abs(n).toFixed(c)) + '', j = ((j = i.length) > 3) ? j % 3 : 0; return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); } And here some tests: // Some tests (do not forget parenthesis when using negative numbers and number with no decimals) alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney()); // Some tests (do not forget parenthesis when using negative numbers and number with no decimals) alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3)); The minor changes are: * *moved a bit the Math.abs(decimals) to be done only when is not NaN. *decimal_sep can not be empty string any more (a some sort of decimal separator is a must) *we use typeof thousands_sep === 'undefined' as suggested in How best to determine if an argument is not sent to the JavaScript function *(+n || 0) is not needed because this is a Number object JSFiddle A: function CurrencyFormatted(amount) { var i = parseFloat(amount); if(isNaN(i)) { i = 0.00; } var minus = ''; if(i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if(s.indexOf('.') < 0) { s += '.00'; } if(s.indexOf('.') == (s.length - 2)) { s += '0'; } s = minus + s; return s; } From WillMaster. A: I suggest the NumberFormat class from Google Visualization API. You can do something like this: var formatter = new google.visualization.NumberFormat({ prefix: '$', pattern: '#,###,###.##' }); formatter.formatValue(1000000); // $ 1,000,000 A: Short and fast solution (works everywhere!) (12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67 The idea behind this solution is replacing matched sections with first match and comma, i.e. '$&,'. The matching is done using lookahead approach. You may read the expression as "match a number if it is followed by a sequence of three number sets (one or more) and a dot". TESTS: 1 --> "1.00" 12 --> "12.00" 123 --> "123.00" 1234 --> "1,234.00" 12345 --> "12,345.00" 123456 --> "123,456.00" 1234567 --> "1,234,567.00" 12345.67 --> "12,345.67" DEMO: http://jsfiddle.net/hAfMM/9571/ Extended short solution You can also extend the prototype of Number object to add additional support of any number of decimals [0 .. n] and the size of number groups [0 .. x]: /** * Number.prototype.format(n, x) * * @param integer n: length of decimal * @param integer x: length of sections */ Number.prototype.format = function(n, x) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')'; return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,'); }; 1234..format(); // "1,234" 12345..format(2); // "12,345.00" 123456.7.format(3, 2); // "12,34,56.700" 123456.789.format(2, 4); // "12,3456.79" DEMO / TESTS: http://jsfiddle.net/hAfMM/435/ Super extended short solution In this super extended version you may set different delimiter types: /** * Number.prototype.format(n, x, s, c) * * @param integer n: length of decimal * @param integer x: length of whole part * @param mixed s: sections delimiter * @param mixed c: decimal delimiter */ Number.prototype.format = function(n, x, s, c) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', num = this.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); }; 12345678.9.format(2, 3, '.', ','); // "12.345.678,90" 123456.789.format(4, 4, ' ', ':'); // "12 3456:7890" 12345678.9.format(0, 3, '-'); // "12-345-679" DEMO / TESTS: http://jsfiddle.net/hAfMM/612/ A: If amount is a number, say -123, then amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); will produce the string "-$123.00". Here's a complete working example. A: As usually, there are multiple ways of doing the same thing, but I would avoid using Number.prototype.toLocaleString since it can return different values based on the user settings. I also don't recommend extending the Number.prototype - extending native objects prototypes is a bad practice since it can cause conflicts with other people code (e.g. libraries/frameworks/plugins) and may not be compatible with future JavaScript implementations/versions. I believe that regular expressions are the best approach for the problem, here is my implementation: /** * Converts number into currency format * @param {number} number Number that should be converted. * @param {string} [decimalSeparator] Decimal separator, defaults to '.'. * @param {string} [thousandsSeparator] Thousands separator, defaults to ','. * @param {int} [nDecimalDigits] Number of decimal digits, defaults to `2`. * @return {string} Formatted string (e.g. numberToCurrency(12345.67) returns '12,345.67') */ function numberToCurrency(number, decimalSeparator, thousandsSeparator, nDecimalDigits){ //default values decimalSeparator = decimalSeparator || '.'; thousandsSeparator = thousandsSeparator || ','; nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits; var fixed = number.toFixed(nDecimalDigits), //limit/add decimal digits parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); //separate begin [$1], middle [$2] and decimal digits [$4] if(parts){ //number >= 1000 || number <= -1000 return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : ''); }else{ return fixed.replace('.', decimalSeparator); } } A: This might be a little late, but here's a method I just worked up for a coworker to add a locale-aware .toCurrencyString() function to all numbers. The internalization is for number grouping only, not the currency sign - if you're outputting dollars, use "$" as supplied, because $123 4567 in Japan or China is the same number of USD as $1,234,567 is in the US. If you're outputting euro, etc., then change the currency sign from "$". Declare this anywhere in your HTML <head> section or wherever necessary, just before you need to use it: Number.prototype.toCurrencyString = function(prefix, suffix) { if (typeof prefix === 'undefined') { prefix = '$'; } if (typeof suffix === 'undefined') { suffix = ''; } var _localeBug = new RegExp((1).toLocaleString().replace(/^1/, '').replace(/\./, '\\.') + "$"); return prefix + (~~this).toLocaleString().replace(_localeBug, '') + (this % 1).toFixed(2).toLocaleString().replace(/^[+-]?0+/,'') + suffix; } Then you're done! Use (number).toCurrencyString() anywhere you need to output the number as currency. var MyNumber = 123456789.125; alert(MyNumber.toCurrencyString()); // alerts "$123,456,789.13" MyNumber = -123.567; alert(MyNumber.toCurrencyString()); // alerts "$-123.57" A: accounting.js is a tiny JavaScript library for number, money and currency formatting. A: Number(value) .toFixed(2) .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") A: Here's the best JavaScript money formatter I've seen: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) { var n = this, decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces, decSeparator = decSeparator == undefined ? "." : decSeparator, thouSeparator = thouSeparator == undefined ? "," : thouSeparator, sign = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "", j = (j = i.length) > 3 ? j % 3 : 0; return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : ""); }; It was reformatted and borrowed from here: How to format numbers as currency strings You'll have to supply your own currency designator (you used $ above). Call it like this (although note that the arguments default to 2, comma, and period, so you don't need to supply any arguments if that's your preference): var myMoney = 3543.75873; var formattedMoney = '$' + myMoney.formatMoney(2, ',', '.'); // "$3,543.76" A: Here are some solutions and all pass the test suite. The test suite and benchmark are included. If you want copy and paste to test, try this gist. Method 0 (RegExp) It is based on VisioN's answer, but it fixes if there isn't a decimal point. if (typeof Number.prototype.format === 'undefined') { Number.prototype.format = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split('.'); a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,'); return a.join('.'); } } Method 1 if (typeof Number.prototype.format === 'undefined') { Number.prototype.format = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split('.'), // Skip the '-' sign head = Number(this < 0); // Skip the digits that's before the first thousands separator head += (a[0].length - head) % 3 || 3; a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&'); return a.join('.'); }; } Method 2 (Split to Array) if (typeof Number.prototype.format === 'undefined') { Number.prototype.format = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split('.'); a[0] = a[0] .split('').reverse().join('') .replace(/\d{3}(?=\d)/g, '$&,') .split('').reverse().join(''); return a.join('.'); }; } Method 3 (Loop) if (typeof Number.prototype.format === 'undefined') { Number.prototype.format = function (precision) { if (!isFinite(this)) { return this.toString(); } var a = this.toFixed(precision).split(''); a.push('.'); var i = a.indexOf('.') - 3; while (i > 0 && a[i-1] !== '-') { a.splice(i, 0, ','); i -= 3; } a.pop(); return a.join(''); }; } Usage Example console.log('======== Demo ========') console.log( (1234567).format(0), (1234.56).format(2), (-1234.56).format(0) ); var n = 0; for (var i=1; i<20; i++) { n = (n * 10) + (i % 10)/100; console.log(n.format(2), (-n).format(2)); } Separator If we want custom a thousands separator or decimal separator, use replace(): 123456.78.format(2).replace(',', ' ').replace('.', ' '); Test suite function assertEqual(a, b) { if (a !== b) { throw a + ' !== ' + b; } } function test(format_function) { console.log(format_function); assertEqual('NaN', format_function.call(NaN, 0)) assertEqual('Infinity', format_function.call(Infinity, 0)) assertEqual('-Infinity', format_function.call(-Infinity, 0)) assertEqual('0', format_function.call(0, 0)) assertEqual('0.00', format_function.call(0, 2)) assertEqual('1', format_function.call(1, 0)) assertEqual('-1', format_function.call(-1, 0)) // Decimal padding assertEqual('1.00', format_function.call(1, 2)) assertEqual('-1.00', format_function.call(-1, 2)) // Decimal rounding assertEqual('0.12', format_function.call(0.123456, 2)) assertEqual('0.1235', format_function.call(0.123456, 4)) assertEqual('-0.12', format_function.call(-0.123456, 2)) assertEqual('-0.1235', format_function.call(-0.123456, 4)) // Thousands separator assertEqual('1,234', format_function.call(1234.123456, 0)) assertEqual('12,345', format_function.call(12345.123456, 0)) assertEqual('123,456', format_function.call(123456.123456, 0)) assertEqual('1,234,567', format_function.call(1234567.123456, 0)) assertEqual('12,345,678', format_function.call(12345678.123456, 0)) assertEqual('123,456,789', format_function.call(123456789.123456, 0)) assertEqual('-1,234', format_function.call(-1234.123456, 0)) assertEqual('-12,345', format_function.call(-12345.123456, 0)) assertEqual('-123,456', format_function.call(-123456.123456, 0)) assertEqual('-1,234,567', format_function.call(-1234567.123456, 0)) assertEqual('-12,345,678', format_function.call(-12345678.123456, 0)) assertEqual('-123,456,789', format_function.call(-123456789.123456, 0)) // Thousands separator and decimal assertEqual('1,234.12', format_function.call(1234.123456, 2)) assertEqual('12,345.12', format_function.call(12345.123456, 2)) assertEqual('123,456.12', format_function.call(123456.123456, 2)) assertEqual('1,234,567.12', format_function.call(1234567.123456, 2)) assertEqual('12,345,678.12', format_function.call(12345678.123456, 2)) assertEqual('123,456,789.12', format_function.call(123456789.123456, 2)) assertEqual('-1,234.12', format_function.call(-1234.123456, 2)) assertEqual('-12,345.12', format_function.call(-12345.123456, 2)) assertEqual('-123,456.12', format_function.call(-123456.123456, 2)) assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2)) assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2)) assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2)) } console.log('======== Testing ========'); test(Number.prototype.format); test(Number.prototype.format1); test(Number.prototype.format2); test(Number.prototype.format3); Benchmark function benchmark(f) { var start = new Date().getTime(); f(); return new Date().getTime() - start; } function benchmark_format(f) { console.log(f); time = benchmark(function () { for (var i = 0; i < 100000; i++) { f.call(123456789, 0); f.call(123456789, 2); } }); console.log(time.format(0) + 'ms'); } // If not using async, the browser will stop responding while running. // This will create a new thread to benchmark async = []; function next() { setTimeout(function () { f = async.shift(); f && f(); next(); }, 10); } console.log('======== Benchmark ========'); async.push(function () { benchmark_format(Number.prototype.format); }); next(); A: I found this from: accounting.js. It's very easy and perfectly fits my need. // Default usage: accounting.formatMoney(12345678); // $12,345,678.00 // European formatting (custom symbol and separators), can also use options object as second parameter: accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99 // Negative values can be formatted nicely: accounting.formatMoney(-500000, "£ ", 0); // £ -500,000 // Simple `format` string allows control of symbol position (%v = value, %s = symbol): accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP // Euro currency symbol to the right accounting.formatMoney(5318008, {symbol: "€", precision: 2, thousand: ".", decimal : ",", format: "%v%s"}); // 1.008,00€ A: A simple option for proper comma placement by reversing the string first and basic regexp. String.prototype.reverse = function() { return this.split('').reverse().join(''); }; Number.prototype.toCurrency = function( round_decimal /*boolean*/ ) { // format decimal or round to nearest integer var n = this.toFixed( round_decimal ? 0 : 2 ); // convert to a string, add commas every 3 digits from left to right // by reversing string return (n + '').reverse().replace( /(\d{3})(?=\d)/g, '$1,' ).reverse(); }; A: Here's mine... function thousandCommas(num) { num = num.toString().split('.'); var ints = num[0].split('').reverse(); for (var out=[],len=ints.length,i=0; i < len; i++) { if (i > 0 && (i % 3) === 0) out.push(','); out.push(ints[i]); } out = out.reverse() && out.join(''); if (num.length === 2) out += '.' + num[1]; return out; } A: I like it simple: function formatPriceUSD(price) { var strPrice = price.toFixed(2).toString(); var a = strPrice.split(''); if (price > 1000000000) a.splice(a.length - 12, 0, ','); if (price > 1000000) a.splice(a.length - 9, 0, ','); if (price > 1000) a.splice(a.length - 6, 0, ','); return '$' + a.join(""); } A: Please find in the below code what I have developed to support internationalization. It formats the given numeric value to language specific format. In the given example I have used ‘en’ while have tested for ‘es’, ‘fr’ and other countries where in the format varies. It not only stops the user from keying characters, but it formats the value on tab out. I have created components for Number as well as for Decimal format. Apart from this, I have created parseNumber(value, locale) and parseDecimal(value, locale) functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used the jQuery validator plugin in the below shared code. HTML: <tr> <td> <label class="control-label"> Number Field: </label> <div class="inner-addon right-addon"> <input type="text" id="numberField" name="numberField" class="form-control" autocomplete="off" maxlength="17" data-rule-required="true" data-msg-required="Cannot be blank." data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123" data-rule-numberExceedsMaxLimit="en" data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123" onkeydown="return isNumber(event, 'en')" onkeyup="return updateField(this)" onblur="numberFormatter(this, 'en', 'Invalid character(s) found. Please enter valid characters.')"> </div> </td> </tr> <tr> <td> <label class="control-label"> Decimal Field: </label> <div class="inner-addon right-addon"> <input type="text" id="decimalField" name="decimalField" class="form-control" autocomplete="off" maxlength="20" data-rule-required="true" data-msg-required="Cannot be blank." data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00" data-rule-decimalExceedsMaxLimit="en" data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00" onkeydown="return isDecimal(event, 'en')" onkeyup="return updateField(this)" onblur="decimalFormatter(this, 'en', 'Invalid character(s) found. Please enter valid characters.')"> </div> </td> </tr> JavaScript: /* * @author: dinesh.lomte */ /* Holds the maximum limit of digits to be entered in number field. */ var numericMaxLimit = 13; /* Holds the maximum limit of digits to be entered in decimal field. */ var decimalMaxLimit = 16; /** * * @param {type} value * @param {type} locale * @returns {Boolean} */ parseDecimal = function(value, locale) { value = value.trim(); if (isNull(value)) { return 0.00; } if (isNull(locale)) { return value; } if (getNumberFormat(locale)[0] === '.') { value = value.replace(/\./g, ''); } else { value = value.replace( new RegExp(getNumberFormat(locale)[0], 'g'), ''); } if (getNumberFormat(locale)[1] === ',') { value = value.replace( new RegExp(getNumberFormat(locale)[1], 'g'), '.'); } return value; }; /** * * @param {type} element * @param {type} locale * @param {type} nanMessage * @returns {Boolean} */ decimalFormatter = function (element, locale, nanMessage) { showErrorMessage(element.id, false, null); if (isNull(element.id) || isNull(element.value) || isNull(locale)) { return true; } var value = element.value.trim(); value = value.replace(/\s/g, ''); value = parseDecimal(value, locale); var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 } ); if (numberFormatObj.format(value) === 'NaN') { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } element.value = numberFormatObj.format(value); return true; }; /** * * @param {type} element * @param {type} locale * @param {type} nanMessage * @returns {Boolean} */ numberFormatter = function (element, locale, nanMessage) { showErrorMessage(element.id, false, null); if (isNull(element.id) || isNull(element.value) || isNull(locale)) { return true; } var value = element.value.trim(); var format = getNumberFormat(locale); if (hasDecimal(value, format[1])) { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } value = value.replace(/\s/g, ''); value = parseNumber(value, locale); var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 0, maximumFractionDigits: 0 } ); if (numberFormatObj.format(value) === 'NaN') { showErrorMessage(element.id, true, nanMessage); setFocus(element.id); return false; } element.value = numberFormatObj.format(value); return true; }; /** * * @param {type} id * @param {type} flag * @param {type} message * @returns {undefined} */ showErrorMessage = function(id, flag, message) { if (flag) { // only add if not added if ($('#'+id).parent().next('.app-error-message').length === 0) { var errorTag = '<div class=\'app-error-message\'>' + message + '</div>'; $('#'+id).parent().after(errorTag); } } else { // remove it $('#'+id).parent().next(".app-error-message").remove(); } }; /** * * @param {type} id * @returns */ setFocus = function(id) { id = id.trim(); if (isNull(id)) { return; } setTimeout(function() { document.getElementById(id).focus(); }, 10); }; /** * * @param {type} value * @param {type} locale * @returns {Array} */ parseNumber = function(value, locale) { value = value.trim(); if (isNull(value)) { return 0; } if (isNull(locale)) { return value; } if (getNumberFormat(locale)[0] === '.') { return value.replace(/\./g, ''); } return value.replace( new RegExp(getNumberFormat(locale)[0], 'g'), ''); }; /** * * @param {type} locale * @returns {Array} */ getNumberFormat = function(locale) { var format = []; var numberFormatObj = new Intl.NumberFormat(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 } ); var value = numberFormatObj.format('132617.07'); format[0] = value.charAt(3); format[1] = value.charAt(7); return format; }; /** * * @param {type} value * @param {type} fractionFormat * @returns {Boolean} */ hasDecimal = function(value, fractionFormat) { value = value.trim(); if (isNull(value) || isNull(fractionFormat)) { return false; } if (value.indexOf(fractionFormat) >= 1) { return true; } }; /** * * @param {type} event * @param {type} locale * @returns {Boolean} */ isNumber = function(event, locale) { var keyCode = event.which ? event.which : event.keyCode; // Validating if user has pressed shift character if (keyCode === 16) { return false; } if (isNumberKey(keyCode)) { return true; } var numberFormatter = [32, 110, 188, 190]; if (keyCode === 32 && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) { return true; } if (numberFormatter.indexOf(keyCode) >= 0 && getNumberFormat(locale)[0] === getFormat(keyCode)) { return true; } return false; }; /** * * @param {type} event * @param {type} locale * @returns {Boolean} */ isDecimal = function(event, locale) { var keyCode = event.which ? event.which : event.keyCode; // Validating if user has pressed shift character if (keyCode === 16) { return false; } if (isNumberKey(keyCode)) { return true; } var numberFormatter = [32, 110, 188, 190]; if (keyCode === 32 && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) { return true; } if (numberFormatter.indexOf(keyCode) >= 0 && (getNumberFormat(locale)[0] === getFormat(keyCode) || getNumberFormat(locale)[1] === getFormat(keyCode))) { return true; } return false; }; /** * * @param {type} keyCode * @returns {Boolean} */ isNumberKey = function(keyCode) { if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) { return true; } var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189]; if (keys.indexOf(keyCode) !== -1) { return true; } return false; }; /** * * @param {type} keyCode * @returns {JSON@call;parse.numberFormatter.value|String} */ getFormat = function(keyCode) { var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}'; var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.numberFormatter) { if (jsonObject.numberFormatter.hasOwnProperty(key) && keyCode === parseInt(jsonObject.numberFormatter[key].key)) { return jsonObject.numberFormatter[key].value; } } return ''; }; /** * * @type String */ var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}'; /** * * @param {type} value * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String} */ getShiftCharSpecificNumber = function(value) { var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.shiftCharacterNumberMap) { if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key) && value === jsonObject.shiftCharacterNumberMap[key].char) { return jsonObject.shiftCharacterNumberMap[key].number; } } return ''; }; /** * * @param {type} value * @returns {Boolean} */ isShiftSpecificChar = function(value) { var jsonObject = JSON.parse(jsonString); for (var key in jsonObject.shiftCharacterNumberMap) { if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key) && value === jsonObject.shiftCharacterNumberMap[key].char) { return true; } } return false; }; /** * * @param {type} element * @returns {undefined} */ updateField = function(element) { var value = element.value; for (var index = 0; index < value.length; index++) { if (!isShiftSpecificChar(value.charAt(index))) { continue; } element.value = value.replace( value.charAt(index), getShiftCharSpecificNumber(value.charAt(index))); } }; /** * * @param {type} value * @param {type} element * @param {type} params */ jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) { value = parseInt(parseNumber(value, params)); if (value.toString().length > numericMaxLimit) { showErrorMessage(element.id, false, null); setFocus(element.id); return false; } return true; }, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.'); /** * * @param {type} value * @param {type} element * @param {type} params */ jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) { value = parseFloat(parseDecimal(value, params)).toFixed(2); if (value.toString().substring( 0, value.toString().lastIndexOf('.')).length > numericMaxLimit || value.toString().length > decimalMaxLimit) { showErrorMessage(element.id, false, null); setFocus(element.id); return false; } return true; }, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.'); /** * @param {type} id * @param {type} locale * @returns {boolean} */ isNumberExceedMaxLimit = function(id, locale) { var value = parseInt(parseNumber( document.getElementById(id).value, locale)); if (value.toString().length > numericMaxLimit) { setFocus(id); return true; } return false; }; /** * @param {type} id * @param {type} locale * @returns {boolean} */ isDecimalExceedsMaxLimit = function(id, locale) { var value = parseFloat(parseDecimal( document.getElementById(id).value, locale)).toFixed(2); if (value.toString().substring( 0, value.toString().lastIndexOf('.')).length > numericMaxLimit || value.toString().length > decimalMaxLimit) { setFocus(id); return true; } return false; }; A: Taking a few of the best rated answers, I combined and made an ECMAScript 2015 (ES6) function that passes ESLint. export const formatMoney = ( amount, decimalCount = 2, decimal = '.', thousands = ',', currencySymbol = '$', ) => { if (typeof Intl === 'object') { return new Intl.NumberFormat('en-AU', { style: 'currency', currency: 'AUD', }).format(amount); } // Fallback if Intl is not present. try { const negativeSign = amount < 0 ? '-' : ''; const amountNumber = Math.abs(Number(amount) || 0).toFixed(decimalCount); const i = parseInt(amountNumber, 10).toString(); const j = i.length > 3 ? i.length % 3 : 0; return ( currencySymbol + negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, `$1${thousands}`) + (decimalCount ? decimal + Math.abs(amountNumber - i) .toFixed(decimalCount) .slice(2) : '') ); } catch (e) { // eslint-disable-next-line no-console console.error(e); } return amount; }; A: after converting PHP number_format() to javascript this work for me function number_format(number, decimals = 0, dec_point = ".",thousands_sep = ",") { number = (number + '').replace(/[^0-9+\-Ee.]/g, ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), s = '', toFixedFix = function(n, prec) { var k = Math.pow(10, prec); return '' + (Math.round(n * k) / k).toFixed(prec); }; // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, thousands_sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec_point); }
{ "language": "en", "url": "https://stackoverflow.com/questions/149055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2393" }
Q: How to remove trailing whitespace of all files recursively? How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders. Also, I want to to be able to modify the file directly, and not just print everything to stdout. A: Here is an OS X >= 10.6 Snow Leopard solution. It Ignores .git and .svn folders and their contents. Also it won't leave a backup file. (export LANG=C LC_CTYPE=C find . -not \( -name .svn -prune -o -name .git -prune \) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//' ) The enclosing parenthesis preserves the L* variables of current shell – executing in subshell. A: ex Try using Ex editor (part of Vim): $ ex +'bufdo!%s/\s\+$//e' -cxa **/*.* Note: For recursion (bash4 & zsh), we use a new globbing option (**/*.*). Enable by shopt -s globstar. You may add the following function into your .bash_profile: # Strip trailing whitespaces. # Usage: trim *.* # See: https://stackoverflow.com/q/10711051/55075 trim() { ex +'bufdo!%s/\s\+$//e' -cxa $* } sed For using sed, check: How to remove trailing whitespaces with sed? find Find the following script (e.g. remove_trail_spaces.sh) for removing trailing whitespaces from the files: #!/bin/sh # Script to remove trailing whitespace of all files recursively # See: https://stackoverflow.com/questions/149057/how-to-remove-trailing-whitespace-of-all-files-recursively case "$OSTYPE" in darwin*) # OSX 10.5 Leopard, which does not use GNU sed or xargs. find . -type f -not -iwholename '*.git*' -print0 | xargs -0 sed -i .bak -E "s/[[:space:]]*$//" find . -type f -name \*.bak -print0 | xargs -0 rm -v ;; *) find . -type f -not -iwholename '*.git*' -print0 | xargs -0 perl -pi -e 's/ +$//' esac Run this script from the directory which you want to scan. On OSX at the end, it will remove all the files ending with .bak. Or just: find . -type f -name "*.java" -exec perl -p -i -e "s/[ \t]$//g" {} \; which is recommended way by Spring Framework Code Style. A: I ended up not using find and not creating backup files. sed -i '' 's/[[:space:]]*$//g' **/*.* Depending on the depth of the file tree, this (shorter version) may be sufficient for your needs. NOTE this also takes binary files, for instance. A: Instead of excluding files, here is a variation of the above the explicitly white lists the files, based on file extension, that you want to strip, feel free to season to taste: find . \( -name *.rb -or -name *.html -or -name *.js -or -name *.coffee -or \ -name *.css -or -name *.scss -or -name *.erb -or -name *.yml -or -name *.ru \) \ -print0 | xargs -0 sed -i '' -E "s/[[:space:]]*$//" A: I ended up running this, which is a mix between pojo and adams version. It will clean both trailing whitespace, and also another form of trailing whitespace, the carriage return: find . -not \( -name .svn -prune -o -name .git -prune \) -type f \ -exec sed -i 's/[:space:]+$//' \{} \; \ -exec sed -i 's/\r\n$/\n/' \{} \; It won't touch the .git folder if there is one. Edit: Made it a bit safer after the comment, not allowing to take files with ".git" or ".svn" in it. But beware, it will touch binary files if you've got some. Use -iname "*.py" -or -iname "*.php" after -type f if you only want it to touch e.g. .py and .php-files. Update 2: It now replaces all kinds of spaces at end of line (which means tabs as well) A: This works well.. add/remove --include for specific file types : egrep -rl ' $' --include *.c * | xargs sed -i 's/\s\+$//g' A: Ruby: irb Dir['lib/**/*.rb'].each{|f| x = File.read(f); File.write(f, x.gsub(/[ \t]+$/,"")) } A: 1) Many other answers use -E. I am not sure why, as that's undocumented BSD compatibility option. -r should be used instead. 2) Other answers use -i ''. That should be just -i (or -i'' if preffered), because -i has the suffix right after. 3) Git specific solution: git config --global alias.check-whitespace \ 'git diff-tree --check $(git hash-object -t tree /dev/null) HEAD' git check-whitespace | grep trailing | cut -d: -f1 | uniq -u -z | xargs -0 sed --in-place -e 's/[ \t]+$//' The first one registers a git alias check-whitespace which lists the files with trailing whitespaces. The second one runs sed on them. I only use \t rather than [:space:] as I don't typically see vertical tabs, form feeds and non-breakable spaces. Your measurement may vary. A: I use regular expressions. 4 steps: * *Open the root folder in your editor (I use Visual Studio Code). *Tap the Search icon on the left, and enable the regular expression mode. *Enter " +\n" in the Search bar and "\n" in the Replace bar. *Click "Replace All". This removes all trailing spaces at the end of each line in all files. And you can exclude some files that don't fit with this need. A: Use: find . -type f -print0 | xargs -0 perl -pi.bak -e 's/ +$//' if you don't want the ".bak" files generated: find . -type f -print0 | xargs -0 perl -pi -e 's/ +$//' as a zsh user, you can omit the call to find, and instead use: perl -pi -e 's/ +$//' **/* Note: To prevent destroying .git directory, try adding: -not -iwholename '*.git*'. A: Two alternative approaches which also work with DOS newlines (CR/LF) and do a pretty good job at avoiding binary files: Generic solution which checks that the MIME type starts with text/: while IFS= read -r -d '' -u 9 do if [[ "$(file -bs --mime-type -- "$REPLY")" = text/* ]] then sed -i 's/[ \t]\+\(\r\?\)$/\1/' -- "$REPLY" else echo "Skipping $REPLY" >&2 fi done 9< <(find . -type f -print0) Git repository-specific solution by Mat which uses the -I option of git grep to skip files which Git considers to be binary: git grep -I --name-only -z -e '' | xargs -0 sed -i 's/[ \t]\+\(\r\?\)$/\1/' A: In Bash: find dir -type f -exec sed -i 's/ *$//' '{}' ';' Note: If you're using .git repository, try adding: -not -iwholename '.git'. A: This worked for me in OSX 10.5 Leopard, which does not use GNU sed or xargs. find dir -type f -print0 | xargs -0 sed -i.bak -E "s/[[:space:]]*$//" Just be careful with this if you have files that need to be excluded (I did)! You can use -prune to ignore certain directories or files. For Python files in a git repository, you could use something like: find dir -not -path '.git' -iname '*.py' A: Ack was made for this kind of task. It works just like grep, but knows not to descend into places like .svn, .git, .cvs, etc. ack --print0 -l '[ \t]+$' | xargs -0 -n1 perl -pi -e 's/[ \t]+$//' Much easier than jumping through hoops with find/grep. Ack is available via most package managers (as either ack or ack-grep). It's just a Perl program, so it's also available in a single-file version that you can just download and run. See: Ack Install A: This is what works for me (Mac OS X 10.8, GNU sed installed by Homebrew): find . -path ./vendor -prune -o \ \( -name '*.java' -o -name '*.xml' -o -name '*.css' \) \ -exec gsed -i -E 's/\t/ /' \{} \; \ -exec gsed -i -E 's/[[:space:]]*$//' \{} \; \ -exec gsed -i -E 's/\r\n/\n/' \{} \; Removed trailing spaces, replaces tabs with spaces, replaces Windows CRLF with Unix \n. What's interesting is that I have to run this 3-4 times before all files get fixed, by all cleaning gsed instructions.
{ "language": "en", "url": "https://stackoverflow.com/questions/149057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "139" }
Q: How to display a non-ascii filename in the file download box in browsers? There doesn't seem to be an accepted way of sending down a header parameter in non ascii format. The header for file download usually looks like Content-disposition: attachment; filename="theasciifilename.doc" Except if you smash a utf8 encoded string in the filename parameter, Firefox will handle it fine, whereas IE will throw up. There is a document on CodeProject that explains a method for encoding the filename. This document encodes Bản Kiểm Kê.doc to B%e1%ba%a3n%20Ki%e1%bb%83m%20K%c3%aa.doc by hex encoding the bytes. Problem #1: the first character in that string: ả has a value of ả -- encode that number in Hex and you get %a3%1e. How did this guy get %e1%ba%a3? (I'm obviously missing something simple here) Problem #2: While IE acknowledges this encoding, Firefox doesn't! What to do? A: The specs basically don't permit anything other than US-ASCII. HTTP headers are US-ASCII. HTTP's payload defaults to ISO 8859-1 but that refers to the content body, not the headers. Arguably the Right Thing to do would be to use MIME's technique for encoding non-ASCII data in headers, as described in RFC 2047, but I have no idea whether browsers actually support that. EDIT: Whoops, no, RFC 2047 section 5 explicitly says that the encoded form is not permitted in Content-Disposition. Looks like you're out of luck - there is no standard. EDIT 2: There is a standard - RFC 2231 defines how this is now supposed to work. It has support from some browsers, but is not supported in IE. I found some test cases which demonstrate how it works and what browser support is available. A: Answer to question #1: You are confusing Unicode and UTF-8. The hex value of 'ả' is 0xA31E however that is not a UTF-8 character. In UTF-8 that character requries three bytes, 0xE1 0xBA 0xA3. URL encoding is poorly defined for non-ascii encodings but %e1%ba%a3 is the valid UTF-8 encoding to use for that character. A: For Problem #2 you need to URL encode the file name for both Internet Explorer and Firefox. The only difference is that you need to use the format of RFC 2231 in Firefox. This applies to Firefox 3 and Internet Explorer 7. A: In the link you've got above, e1 ba a3 is the UTF-8 encoding of the character mentioned, not the character code. A: Answer (sort of) to problem #2: Since you've discovered that the naming scheme in one browser does not work in the other, your only solution is to do it differently for each browser, similar to the example here. In case the link goes away, the solution is basically: 1. If browser is IE URL encode filename 2. Generate Content-disposition header Of course determining if the browser is IE by User-agent (which is about the only way you can do it) is fraught with all sorts of the usual peril. As North American centric as this sounds, if it is important that this work in a large number of browsers you do not control which may have the User-agent blocked, or modified, then simply avoid UTF-8 encoded characters in the filename and always use "Download" or something. A: Unfortunately, there currently is no single way that would work in all User Agents. See http://greenbytes.de/tech/tc2231/ for test cases, then complain to Microsoft, Google and Apple.
{ "language": "en", "url": "https://stackoverflow.com/questions/149058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: StackTrace in Flash / ActionScript 3.0 I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace: public function PrintStackTrace() { try { throw new Error('StackTrace'); } catch (e:Error) { trace(e.getStackTrace()); } } I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know. Thanks! A: From Flash Player 11.5 the stack traces are also available in the non-debugger versions of the players as well. A: Use the Flex DeBugger (FDB) that comes with the Flex SDK. It's a command-line debugger that allows you to debug .swf, even ones online (if it's a debug version). It allows you to set break-points, print/change variables, and dump the stack, and does not require you to add any extra code. A very useful tool that you shouldn't be without! The fdb options you will need are 'break' and to specify the class and line where you want execution to halt, and 'bt' or 'info stack' to give you a backtrace of the stack. You can also display almost everything about the application while it runs. A: As far as I know, the only way to make the stack trace available to your own code is via the getStackTrace() method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it: var tempError:Error = new Error(); var stackTrace:String = tempError.getStackTrace(); Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of Capabilities.isDebugger if you want. A: @hasseg is right. You can also preserve the stacktrace information in release version (not debug) by providing the -compiler.verbose-stacktraces=true when compiling your SWF. A: I've put together this little function: public static function getStackTrace() : String { var aStackTrace : Array = new Error().getStackTrace().split("\n"); aStackTrace.shift(); aStackTrace.shift(); return "Stack trace: \n" + aStackTrace.join("\n"); } I have this function in a custom "Debug" class I use with my apps when developing. The two shift() calls remove the first two lines: The first one is just the string "Error" and the second line refers to this function itself, so it's not useful. You can even remove the third line if you wish (it refers to the line where you place the call to the getStackTrace() function) by adding another shift() call, but I left it to serve as a starting point of the "stack trace". A: var tempError:Error = new Error(); var stackTrace:String = tempError.getStackTrace(); write this stackTrace string into any file so that you can see the logs of your program at run mode also. So you need not to run it in debugger mode only. Write it into uncaughtexception event of application, so it will execute lastly. A: As of Flash 11.5, stack traces work in the release version of Flash. However, that doesn't mean this is no longer an issue. If your application is set to use a compiler older than 11.5 in Flash Builder --> Project properties --> ActionScript Compiler, you won't have stack traces. Additionally, on that same page you can see your AIR SDK version. If you're using v3.4 or older, you won't see stack traces. If this is your issue, all your developers should update their AIR SDK by following the instructions here. A: The getStackTrace method returns the stack trace only on the debug flash player (https://www.adobe.com/support/flashplayer/debug_downloads.html), on the release player returns null. Make sure you have the debug player installed and running. The -compiler.verbose-stacktraces=true only adds the line number to the debug stack trace. Sample test: https://gist.github.com/pipeno/03310d3d3cae61460ac6c590c4f355ed
{ "language": "en", "url": "https://stackoverflow.com/questions/149073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Can Multiple Indexes Work Together? Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index. Now suppose I perform a query such as SELECT * FROM sometable WHERE foo='hello' AND bar='world'; My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'. So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is O(n) where n is the number of rows where bar is 'world'. However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be O(m) where m is the number of rows where foo is 'hello'. So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting bar='world' first in the WHERE clause? A: Eli, In a comment you wrote: Unfortunately, I have a table with lots of columns each with their own index. Users can query any combination of fields, so I can't efficiently create indexes on each field combination. But if I did only have two fields needing indexes, I'd completely agree with your suggestion to use two indexes. – Eli Courtwright (Sep 29 at 15:51) This is actually rather crucial information. Sometimes programmers outsmart themselves when asking questions. They try to distill the question down to the seminal points but quite often over simplify and miss getting the best answer. This scenario is precisely why bitmap indexes were invented -- to handle the times when unknown groups of columns would be used in a where clause. Just in case someone says that BMIs are for low cardinality columns only and may not apply to your case. Low is probably not as small as you think. The only real issue is concurrency of DML to the table. Must be single threaded or rare for this to work. A: Yes, you can give "hints" with the query to Oracle. These hints are disguised as comments ("/* HINT */") to the database and are mainly vendor specific. So one hint for one database will not work on an other database. I would use index hints here, the first hint for the small table. See here. On the other hand, if you often search over these two fields, why not create an index on these two? I do not have the right syntax, but it would be something like CREATE INDEX IX_BAR_AND_FOO on sometable(bar,foo); This way data retrieval should be pretty fast. And in case the concatenation is unique hten you simply create a unique index which should be lightning fast. A: First off, I'll assume that you are talking about nice, normal, standard b*-tree indexes. The answer for bitmap indexes is radically different. And there are lots of options for various types of indexes in Oracle that may or may not change the answer. At a minimum, if the optimizer is able to determine the selectivity of a particular condition, it will use the more selective index (i.e. the index on bar). But if you have skewed data (there are N values in the column bar but the selectivity of any particular value is substantially more or less than 1/N of the data), you would need to have a histogram on the column in order to tell the optimizer which values are more or less likely. And if you are using bind variables (as all good OLTP developers should), depending on the Oracle version, you may have issues with bind variable peeking. Potentially, Oracle could even do an on the fly conversion of the two b*-tree indexes to bitmaps and combine the bitmaps in order to use both indexes to find the rows it needs to retrieve. But this is a rather unusual query plan, particularly if there are only two columns where one column is highly selective. A: So is Oracle smart enough to search efficiently here? The simple answer is "probably". There are lots'o' very bright people at each of the database vendors working on optimizing the query optimizer, so it's probably doing things that you haven't even thought of. And if you update the statistics, it'll probably do even more. A: Oracle will almost certainly use the most selective index to drive the query, and you can check that with the explain plan. Furthermore, Oracle can combine the use of both indexes in a couple of ways -- it can convert btree indexes to bitmaps and perform a bitmap ANd operation on them, or it can perform a hash join on the rowid's returned by the two indexes. One important consideration here might be any correlation between the values being queried. If foo='hello' accounts for 80% of values in the table and bar='world' accounts for 10%, then Oracle is going to estimate that the query will return 0.8*0.1= 8% of the table rows. However this may not be correct - the query may actually return 10% of the rwos or even 0% of the rows depending on how correlated the values are. Now, depending on the distribution of those rows throughout the table it may not be efficient to use an index to find them. You may still need to access (say) 70% or the table blocks to retrieve the required rows (google for "clustering factor"), in which case Oracle is going to perform a ful table scan if it gets the estimation correct. In 11g you can collect multicolumn statistics to help with this situation I believe. In 9i and 10g you can use dynamic sampling to get a very good estimation of the number of rows to be retrieved. To get the execution plan do this: explain plan for SELECT * FROM sometable WHERE foo='hello' AND bar='world' / select * from table(dbms_xplan.display) / Contrast that with: explain plan for SELECT /*+ dynamic_sampling(4) */ * FROM sometable WHERE foo='hello' AND bar='world' / select * from table(dbms_xplan.display) / A: I'm sure you can also have Oracle display a query plan so you can see exactly which index is used first. A: The best approach would be to add foo to bar's index, or add bar to foo's index (or both). If foo's index also contains an index on bar, that additional indexing level will not affect the utility of the foo index in any current uses of that index, nor will it appreciably affect the performance of maintaining that index, but it will give the database additional information to work with in optimizing queries such as in the example. A: It's better than that. Index Seeks are always quicker than full table scans. So behind the scenes Oracle (and SQL server for that matter) will first locate the range of rows on both indices. It will then look at which range is shorter (seeing that it's an inner join), and it will iterate the shorter range to find the matches with the larger of the two. A: You can provide hints as to which index to use. I'm not familiar with Oracle, but in Mysql you can use USE|IGNORE|FORCE_INDEX (see here for more details). For best performance though you should use a combined index.
{ "language": "en", "url": "https://stackoverflow.com/questions/149078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Recovery from optical media ignoring read errors I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive. The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times. The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer? The question is mainly about Linux, but any Win32 pointers will be more than welcome too. A: man readom, a program that comes with cdrecord: -noerror Do not abort if the high level error checking in readom found an uncorrectable error in the data stream. -nocorr Switch the drive into a mode where it ignores read errors in data sectors that are a result of uncorrectable ECC/EDC errors before reading. If readom completes, the error recovery mode of the drive is switched back to the remembered old mode. ... retries=# Set the retry count for high level retries in readom to #. The default is to do 128 retries which may be too much if you like to read a CD with many unreadable sectors. A: The best tool avaliable is dd_rhelp. Just dd_rhelp /dev/cdrecorder /home/myself/DVD.img ,take a cup of tea and watch the nice graphics. The dd_rhelp rpm package info: dd_rhelp uses ddrescue on your entire disc, and attempts to gather the maximum valid data before trying for ages on badsectors. If you leave dd_rhelp work for infinite time, it has a similar effect as a simple dd_rescue. But because you may not have this infinite time, dd_rhelp jumps over bad sectors and rescue valid data. In the long run, it parses all your device with dd_rescue. You can Ctrl-C it whenever you want, and rerun-it at will, dd_rhelp resumes the job as it depends on the log files dd_rescue creates. In addition, progress is shown in an ASCII picture of your device being rescued. I've used it a lot myself and Is very, very realiable. You can install it from DAG to Red Hat like distributions. A: Since dd was suggested, I should note that I know of the existence and have used sg_dd, but my question was not about commands (1) or (1m), but about system calls (2) or libraries (3). EDIT Another linux command-line utility that is of help, is sdparm. The following flag seems to disable hardware retries: sudo sdparm --set=RRC=0 /dev/sr0 where /dev/sr0 is the device for the optical drive in my case. A: While checking whether hdparm could modify the number of retries (doesn't seem so), I thought that, depending on the type of error, lowering the CD-ROM speed could potentially reduce the number of read errors, which could actually increase the average read speed. However, if some sectors are completely unreadable, then even lowering the CD-ROM speed won't help. A: Since you are asking about driver level access, you should look into SCSI commands, or perhaps an ASPI like API. On windows VSO software (developers of blindread/blindwrite below) have developed a much better API, Patin-Couffin, that provides locked low level access: http://en.wikipedia.org/wiki/Patin-Couffin That might get you started. However, at the end of the day, the drive is interfaced with SCSI commands, even if it's actually USB, SATA, ATA, IDE, or otherwise. You might also look up terms related to ATAPI, which was one of the first specifications for this CD-ROM SCSI layer interface. I'd be surprised if you couldn't find a suitable linux library or example of dealing with the lower level commands using the above search terms and concepts. Older answer: Blindread/blindwrite was developed in the heyday of cd-rom protection schemes often using intentionally bad sectors or error information to verify the original CD. It will allow you to set a whole slew of parameters, including retries. Keep in mind that the CD-ROM drive itself determines how many times to retry, and I'm not sure that this is settable via software for many (most?) CD-ROM drives. You can copy the disk to ISO format, ignoring the errors, and then use ISO utilities to read the data. -Adam A: Take a look at the ASPI interface. Available on both windows and linux. A: dd(1) is your friend. dd if=/dev/cdrom of=image bs=2352 conv=noerror,notrunc The drive may still retry a bit, but I don't think you'll get any better without modifying firmware.
{ "language": "en", "url": "https://stackoverflow.com/questions/149092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Capturing the Click event in an Excel spreadsheet How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column. A: Check out the Worksheet_SelectionChange event. In that event you could use Intersect() with named ranges to figure out if a specific range were clicked. Here's some code that might help you get started. Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) If Not Intersect(Target, Range("SomeNamedRange")) Is Nothing Then 'Your counting code End If End Sub A: Use the Worksheet.SelectionChange event to trap this. A: Worksheet SelectionChange event would do it. Note that this fires every time user clicks a new cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/149102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Crystal Reports vs ReportViewer Pros/Cons? We have been designing our reports around Crystal Reports in VS2008 for our web application and I just discovered the Microsoft provided ReportViewer control. I've searched around a bit but cannot find a good breakdown of the pros and cons of each method of producing reports. I'm looking for pros and cons regarding: * *Ease of development *Ease of deployment *Ability to export data *Ease of support and finding help on the web A: I can say that the more I use Crystal Reports (and that has been for more than 9 years), the more I want to move away from it. The only reason why you would want to stay there, is if you have a lot of CR reports already up and running. Crystal Reports is the "one-stop shop" that the user see as the "heaven made" reporting engine and turns out to be overbloated, crowded with bugs and license reqs. It's very powerful, but at a price; it is complex and not always does what you want. There are better alternatives out there. A: Well, I can answer for one side. I have used ReportViewer aka Client Side Reporting. I can tell you its easy to use, easy to deploy and easy to develop. If you can create SQL Reporting Services reports, you can create these. They can take any kind of datasource so you have full control. Here is an excellent book on Client Side reporting. There are built in PDF and Excel exports available but you can add your own export handling also. You can use in winforms, Asp.Net in your own services. You can do really anything you can imagine with them. For Crystal Reports, I do not know much about them. A: We've been using crystal report for our reporting, there is always the issue of portability since you have to package the crystal runtime with your application. also, with client side reporting much of its power is not utilized. reportviewer is simple and easy and full of features you'll need.
{ "language": "en", "url": "https://stackoverflow.com/questions/149118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Changing/Adding controls to the windows Open/Save common dialog Is there a way of changing/adding to the windows Open/Save common dialog to add extra functionality? At work we have an area on a server with hundreds of 'jobfolders'- just ordinary windows folders created/managed automatically by the database application to house information about a job (emails/scanned faxes/Word docs/Spreadsheets/Photos etc) The folders are named by the job Number. I would like to expand the standard open/save dialog with a combobox which searches for jobfolders based on tags from the database, so that whatever my users are doing they can easily find their way to the correct jobfolder to find/save their work Connecting to the database and providing the functionality to search is no problem, but is there a way to add a combobox control (ideally with a keypress/keydown event) to the dialog? Or Create my own dialog and have it called/used in place of the standard one? i.e. from ANY app my dialog would be called allowing easy access to the jobfolders. If they are in outlook they can find a jobfolder quickly, if there are using Notepad they can still find the folder easily. This would mean a new unified way of finding jobfolders from any app. Ideally someone would know a way using VB/VB.net/C# but I'm guessing, if its possible, its probably going to be C++. A: Like Mark Ransom said, you can do it with the OFN ENABLETEMPLATE and OFN ENABLEHOOK flags. You then specify a Dialog Resource to the lpTemplateName data member of the OPENFILENAME structure. Getting the placement of your controls right takes a bit of trial and error. The hook procedure that you write will receive window messages specific to that dialog - you're particularly interested in the WM_NOTIFY messages - there's a bunch of special ones (CDN INITDONE, CDN FOLDERCHANGE, etc). I've created some pretty elaborate ones a few times, I wish I could include a screenshot. A: The relevant Microsoft documentation for the Windows API is here: http://msdn.microsoft.com/en-us/library/ms646960(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx Look particularly at the OFN_ENABLETEMPLATE and OFN_ENABLEHOOK flags. As you say, this information is mostly relevant when you're working in C/C++. A: Your program can set the starting folder, so if you know the job number (and therefor the name of the folder), you can set the dialog to start out with the correct folder already opened. Beyond that I don't think you can do much without writing an entire shell extension for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/149119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SQL Server 2000: "subquery returned more than one value" on an update statement I'm trying to do a simple update. I've done this kind of thing thousands of times. update articles set department = 60 where type = 'Top Story' Today I get a strange error. Describe Error: Failed to retrieve execution plan: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. Warnings: ---> W (1): The statement has been terminated. <--- 1559 record(s) affected There is no subquery in the update statement. What's going on? A: Most likely there is a trigger on the table, and the error is occurring in the trigger, not in your actual SQL statement. I would further bet that the trigger assumes the insert or delete special tables will only ever have a single row (which is in fact not the case in mass updates, like the one you're executing), causing the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/149124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Request.UrlReferrer null? In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page A (the page the user wants to view) redirect to page B (the login page), the Request.UrlReferrer object is null. Background: If a user isn't logged in, I redirect to the Login page (B in this scenario). After login, I would like to return them to the page they were requesting before they were forced to log in. UPDATE: A nice quick solution seems to be: //if user not logged in Response.Redirect("..MyLoginPage.aspx?returnUrl=" + Request.ServerVariables["SCRIPT_NAME"]); Then, just look at QueryString on login page you forced them to and put the user where they were after successful login. A: UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable. I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing. Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that. UPDATE: As mentioned in the comments, it is probably a good idea to restrict the redirect from the GET parameter to only work for domain-less relative links, refuse directory patterns (../), etc. So still sanity check the redirect; if you follow the standard "don't use any user-supplied input blindly" rule you should be safe. A: The problem could be related on how you redirect the user to some other page. Anyways, the referer url is nothing you should take as absolute rule - a client can fake it easily. A: What you're looking for is best done with a query string variable (e.g. returnURL or originURL). Referrer is best used for data mining operations as it's very unreliable. See the way ASP.Net does redirection with logins for an example. A: If you use the standard Membership provider, and set the Authorization for the directory/page, the code will automatically set a query parameter of ReturnUrl and redirect after a successfull login.If you don't want to use the Membership provider pattern, I would suggest manually doing the query string parameter thing as well. HTTP referrers are not very reliable.
{ "language": "en", "url": "https://stackoverflow.com/questions/149130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Is there a way to update VS' CSS validation to 3.0? I'm getting warnings about CSS3.0 properties like text-overflow. Is there a way to validate against 3.0? HTML5 and CSS3 support is coming to VS2010 in SP1. Link And now its here. http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210/view/Reviews/0?showReviewForm=True A: To turn off validation in VS2008 I had to go to Tools > Options > Text Editor > CSS > CSS Specific and uncheck "Detect errors". A: Try this: http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210/view/Reviews/0?showReviewForm=True! I've just installed it on my computer and works fine on Visual Studio 2010 sp1 A: Apparently, you can define your own Visual Studio Intellisense schema for CSS. I’m not sure if VS will then validate against that, or only use it for code completion. Might be worth making a minimal one and seeing if it gets used for validation. Custom CSS Intellisense Schema in Visual Studio 2005 and 2008 I don’t know of an easy way to validate against CSS 3 yet though. CSS 3 is a large, modular spec, and most of it is very much still in flux, despite some decent browser support for some properties. http://www.w3.org/Style/CSS/current-work A: I do not believe so. But you can turn the validation off if you want. Go to Tools > Options. Expand Text Editor > HTML > Validation. This screen shows all the different validation targets. Uncheck Show Errors if you want to turn the validation off.
{ "language": "en", "url": "https://stackoverflow.com/questions/149131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How can one iterate over stored procedure results from within another stored procedure....without cursors? I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario: I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table. How do I do this without the use of cursors? Should be an easy one for you sql gurus! A: You could also change your stored proc to a user-defined function that returns a table with your uniqueidentifiers. You can joing directly to the UDF and treat it like a table which avoids having to create the extra temp table explicitly. Also, you can pass parameters into the function as you're calling it, making this a very flexible solution. CREATE FUNCTION dbo.udfGetUniqueIDs () RETURNS TABLE AS RETURN ( SELECT uniqueid FROM dbo.SomeWhere ) GO UPDATE dbo.TargetTable SET a.FlagColumn = 1 FROM dbo.TargetTable a INNER JOIN dbo.udfGetUniqueIDs() b ON a.uniqueid = b.uniqueid Edit: This will work on SQL Server 2000 and up... A: This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example: CREATE TABLE #t (uniqueid int) INSERT INTO #t EXEC p_YourStoredProc UPDATE TargetTable SET a.FlagColumn = 1 FROM TargetTable a JOIN #t b ON a.uniqueid = b.uniqueid DROP TABLE #t A: Insert the results of the stored proc into a temporary table and join this to the table you want to update: INSERT INTO #WorkTable EXEC usp_WorkResults UPDATE DataTable SET Flag = Whatever FROM DataTable INNER JOIN #WorkTable ON DataTable.Ket = #WorkTable.Key A: Use temporary tables or a table variable (you are using SS2005). Although, that's not nest-able - if a stored proc uses that method then you can't dumpt that output into a temp table. A: If you upgrade to SQL 2008 then you can pass table parameters I believe. Otherwise, you're stuck with a global temporary table or creating a permanent table that includes a column for some sort of process ID to identify which call to the stored procedure is relevant. How much room do you have in changing the stored procedure that generates the IDs? You could add code in there to handle it or have a parameter that lets you optionally flag the rows when it is called. A: An ugly solution would be to have your procedure return the "next" id each time it is called by using the other table (or some flag on the existing table) to filter out the rows that it has already returned A: You can use a temp table or table variable with an additional column: DECLARE @MyTable TABLE ( Column1 uniqueidentifer, ..., Checked bit ) INSERT INTO @MyTable SELECT [...], 0 FROM MyTable WHERE [...] DECLARE @Continue bit SET @Continue = 1 WHILE (@Continue) BEGIN SELECT @var1 = Column1, @var2 = Column2, ... FROM @MyTable WHERE Checked = 1 IF @var1 IS NULL SET @Continue = 0 ELSE BEGIN ... UPDATE @MyTable SET Checked = 1 WHERE Column1 = @var1 END END Edit: Actually, in your situation a join will be better; the code above is a cursorless iteration, which is overkill for your situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/149132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Database independence in Unix/C We have a system written in C and running under Solaris & Linux that uses the Sybase CT-library to access a Sybase database. We generate the table-definitions, indexes, stored procedures and C-code from an in-house developed DDL to reduce the amount of work and errors. We would like to achieve database independence, so we can add (as a first start) Oracle support. We're thinking about ODBC or ESQL/C, but having no experience with them. What solution would you suggest (preferably a cheap and easy one, of course). Is it possible to have a single source solution? A: I would highly recommend SQLAPI++ (with the downside, perhaps, that it is a C++ library). There is also unixODBC, though I have never used it in code -- only touched upon it while researching for portable database APIs. POCO also provides a uniform, portable API (though, again, in C++) for database operations, but last I checked it, that part of POCO was only in the initial stages of development. A: ODBC will help you write a more portable system, but you will have to be careful to develop your SQL properly if you wish to leverage the underlying database, as the SQL itself may well not be 100% portable across databases, even with the different ODBC drivers. A: iodbc http://www.firstsql.com/iodbc/ or unix odbc http://www.unixodbc.org/ Are probably among the "most portable" choices. Regards Friedrich A: ODBC is going to give you far more portability options over ESQL/C. A: I've been using iODBC to access SQL Server and mysql and have had pretty good results so far. I think it would work for Oracle as well, but that would depend on the ODBC driver and haven't had to try it so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/149136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loading animated gif from JAR file into ImageIcon I'm trying to create a ImageIcon from a animated gif stored in a jar file. ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif"))); The image loads, but only the first frame of the animated gif. The animation does not play. If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works: ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif"); How can I load an animated gif into an ImageIcon from a jar file? EDIT: Here is a complete test case, why doesn't this display the animation? import javax.imageio.ImageIO; import javax.swing.*; public class AnimationTest extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { AnimationTest test = new AnimationTest(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }); } public AnimationTest() { super(); try { JLabel label = new JLabel(); ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif"))); label.setIcon(imageIcon); imageIcon.setImageObserver(label); add(label); pack(); } catch (Exception e) { e.printStackTrace(); } } } A: This reads gif animation from inputStream InputStream in = ...; Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in)); A: You have to use getClass().getResource(imgName); to get a URL to the image file. Check out this tutorial from Real's HowTo. EDIT: Once the image is loaded you have to set the ImageObserver property to get the animation to run. A: Since this thread was just linked from a more current thread that had little to do with animated GIFs but got dragged OT, I thought I'd add this trivial source that 'works for me'. import javax.swing.*; import java.net.URL; class AnimatedGifInLabel { public static void main(String[] args) throws Exception { final URL url = new URL("http://i.stack.imgur.com/OtTIY.gif"); Runnable r = new Runnable() { public void run() { ImageIcon ii = new ImageIcon(url); JLabel label = new JLabel(ii); JOptionPane.showMessageDialog(null, label); } }; SwingUtilities.invokeLater(r); } } A: Hopefully it's not too late for this. I managed to get the animated gif inside my JPanel this way: private JPanel loadingPanel() { JPanel panel = new JPanel(); BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS); panel.setLayout(layoutMgr); ClassLoader cldr = this.getClass().getClassLoader(); java.net.URL imageURL = cldr.getResource("img/spinner.gif"); ImageIcon imageIcon = new ImageIcon(imageURL); JLabel iconLabel = new JLabel(); iconLabel.setIcon(imageIcon); imageIcon.setImageObserver(iconLabel); JLabel label = new JLabel("Loading..."); panel.add(iconLabel); panel.add(label); return panel; } Some points of this approach: 1. The image file is within the jar; 2. ImageIO.read() returns a BufferedImage, which doesn't update the ImageObserver; 3. Another alternative to find images that are bundled in the jar file is to ask the Java class loader, the code that loaded your program, to get the files. It knows where things are. So by doing this I was able to get my animated gif inside my JPanel and it worked like a charm.
{ "language": "en", "url": "https://stackoverflow.com/questions/149153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Patterns for Multithreaded Network Server in C# Are there any templates/patterns/guides I can follow for designing a multithreaded server? I can't find anything terribly useful online through my google searches. My program will start a thread to listen for connections using TcpListener. Every client connection will be handled by it's own IClientHandler thread. The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it. I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online. I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect. Thanks. A: Take a look at this previous question: How do you minimize the number of threads used in a tcp server application? It's not strictly C# specific, but it has some good advice. A: Oddly enough you may find something on a Computer Science Assignment, CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns. Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#. * *Acceptor/ Connector *Monitor Object *Thread Safe Interface *Wrapper Facade *Scoped Locking *Strategized Locking *Reactor *Half Sync/Half-Async *Leaders/Followers Altough you can get the whole list of nice readings on the main page.
{ "language": "en", "url": "https://stackoverflow.com/questions/149163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How can I limit the maximum number of running processes within Microsoft Windows? I'm looking for a way to limit the maximum number of running processes in Windows Server 2003. Is there a registry key somewhere that controls it? If so, which one is it? A: if you are talking about processes as in the items listed in task manager, then there is no way to do it natively, and you can do it with a program, but there should be no real valid reason to do so. If you are talking about making your application only ever launch one EXE no matter how many times it is called, then you are looking for singleton-ing. Example for .NET at: http://www.thescarms.com/dotnet/SingleInstance.aspx --EDIT For another language, google for "singleton" and your language. If you are asking about something else, please elaborate. A: Domestic retail Windows has no intrinsic way of limiting the number of processes (other than exhausting available resources) Windows Starter Editions achieved process capping with a modified version of Windows- Starter ed. is only available in emerging markets however.
{ "language": "en", "url": "https://stackoverflow.com/questions/149189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PowerShell functions return behavior I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function: function Return-True { return $true } and then some sample code to invoke it: PS C:\> Return-True True PS C:\> Return-True -eq $false True PS C:\> (Return-True) -eq $false False Ideas? Comments? A: The second line is not doing a boolean evaluation. Look at what happens if you do the same thing with strings. PS C:\> function Return-True { return "True string" } PS C:\> Return-True True string PS C:\> Return-True -eq "False string" True string PS C:\> (Return-True) -eq "False string" False The second line is simply returning the value of the function, and not doing a comparison. I'm not sure exactly why this behavior is happening, but it makes the behavior easier to see than when using boolean values that are being converted to the strings "True" and "False". A: If you use PowerShell V2's editor, you would see that -eq in the first example is blue, because it is an argument and -eq in the second example is gray because it is an operator Also in V2, you can be strict about arguments, with CmdletBinding and param function Return-True { [CmdletBinding()] param() return $true } Return-True -eq $false Return-True -eq $false Return-True : A parameter cannot be found that matches parameter name 'eq'. At line:7 char:16 + Return-True -eq <<<< $false + CategoryInfo : InvalidArgument: (:) [Return-True], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Return-True A: When PowerShell sees the token Return-True it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function Return-True. You can see this in action if you do: PS > function Return-True { "The arguments are: $args"; return $true } PS > Return-True -eq $false The arguments are: -eq False True That's why all of the following return 'True', because all you are seeing is the result of calling Return-True with various arguments: PS > Return-True -eq $false True PS > Return-True -ne $false True PS > Return-True -eq $true True PS > Return-True -ne $true True Using (Return-True) forces PowerShell to evaluate the function (with no arguments).
{ "language": "en", "url": "https://stackoverflow.com/questions/149191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: sane backup strategy for webapps I'm doing a webapp and need a backup plan. Here's what I've got so far: * *nightly encrypted backup of the SQL database to Amazon S3 and my external drive (incremental if possible, not overly familiar with PostgreSQL yet, but that's another thread) *nightly backup of my Mercurial repo (which includes Apache configs, deploy scripts, etc) to S3 (w/ local backups via Time Machine) Should I add anything else, or will this cover it? For a gauge of how critical the data is/would be, it's a project management app along the lines of Basecamp. A: Weekly full backup of your database as well as nightly incremental ones as well perhaps? It means that if one of your old incremental backups gets corrupted then you have lost less than a week of data. Also, ensure you have a backup test plan to ensure your backups work. There are a lot of horror stories going around about this, from companies that have been doing backups for years, never testing them and then finding out none of them are any good once they need them. (I've also been at a company like this. Thankfully I spotted the backups weren't working before they were required and fixed the problems). A: One of the best strategies that worked for me in the past was to have the "backup" process just be the same as the install process, i.e. we fully scripted in linux the server configuration, application creation, database setup, etc etc so a install would look like: ./install.sh [server] [application name] and the backup/recovery ./install [server] [application name] -database [database backup file] In terms of backup the database was backed up fully (MySQL database), by a cronjob This pretty much ensured that the recovery was tested every time a new instance was deployed, and the scripts ended up being used also to move instances when hardware needed replacement, or when a given server was a getting too much load from a customer. This was the setup for a Saas enterprise application that I worked a few years back, so we had full control of the servers. A: I would if you can change from a incremental back up to a differential. If you have a incremental then you would have to apply the weekly full backup and then every incremental following that. If one of your incrementals fails early in the week, then all your subsequent backups will fail too. However if you use a differential then each differential contains all the changes since the last back up. so even if one of the back ups failed earlier in the week you would still be able to recover fully if you have a sucessful recent backup. I hope i am explaining this well! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/149195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I commit only parts of my code using SVN or Mercurial? I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me. I heard Git supports this, please let me know if this is correct. A: Check out TortoiseHG, which will do hunk selection and let you commit different changes to one file as to different commits. It will even let you commit all changes to some files together with partial changes to other files in one commit. http://tortoisehg.bitbucket.io/ A: I asked a similar question just a little while ago, and the resulting answer of using the hgshelve extension was exactly what I was looking for. Before you do a commit, you can put changes from different files (or hunks of changes within a file) on the "shelf" and then commit the things you want. Then you can unshelve the changes you didn't commit and continue working. I've been using it the past few days and like it a lot. Very easy to visualize and use. A: Mercurial can do this with the record extension. It'll prompt you for each file and each diff hunk. For example: % hg record diff --git a/prelim.tex b/prelim.tex 2 hunks, 4 lines changed examine changes to 'prelim.tex'? [Ynsfdaq?] @@ -12,7 +12,7 @@ \setmonofont[Scale=0.88]{Consolas} % missing from xunicode.sty \DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i} -\else +\else foo \usepackage[pdftex]{graphicx} \fi record this change to 'prelim.tex'? [Ynsfdaq?] @@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End: + +foo \ No newline at end of file record this change to 'prelim.tex'? [Ynsfdaq?] n Waiting for Emacs... After the commit, the remaining diff will be left behind: % hg di diff --git a/prelim.tex b/prelim.tex --- a/prelim.tex +++ b/prelim.tex @@ -1281,3 +1281,5 @@ %% Local variables: %% mode: latex %% End: + +foo \ No newline at end of file Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too. Update: Also try the crecord extension, which provides a curses interface to hunk/line selection. A: Mercurial now provides an option --interactive (or -i) to the commit command, which enables this functionality right out of the box. This works directly from the command-line so it's perfect if you are a command-line enthusiast! Running > hg commit -i begins an interactive session which allows examination, editing and recording of individual changes to create a commit. This behaves very similarly to the --patch and --interactive options for the git add and git commit commands. A: Yes, git allows you to do this. The git add command has a -p (or --patch) option that allows you to review your changes hunk-by-hunk, select which to stage (you can also refine the hunks or, edit the patches in place). You can also use the interactive mode to git-add (git add -i) and use the "p" option. Here's a screencast on interactive adding which also demonstrates the patch feature of git add. A: I would recommend not working like this. If you have to sets of changes, set A which is ready to check in and set B which is not ready yet, how can you be sure that only checking in set A will not break your build/tests? You may miss some lines, forget about lines in a different file, or not realize a dependency that A has on B breaking the build for others. Your commits should be discreet atomic changes that don't break the build for you or others on you team. If you are partially committing a file you are greatly increasing the chances you will break the build for others without knowing about it until you've got some unhappy coworker knocking on your door. The big question is, why do you feel the need to work this way?
{ "language": "en", "url": "https://stackoverflow.com/questions/149198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Can we create an application with its own Web.config and Forms Authentication section inside another application using Forms Authentication? I have an application that uses Forms Authentication to authenticate one type of user. There is a section in this application that needs to be authenticated for another type of user using a different table in the database. The problem happens if the second type of user's session times out, she is taken to the login page defined in the Forms Authentication section of the main Web.Config instead of the login page for the second type of user. I am looking for solutions to this problem. One idea is to create an application in IIS for the section and create a Web.Config for the folder and add another Forms Authentication section. In my experiments, it seems this doesn't work. Am I missing something obvious? Any insights? A: IIRC, the authentication works per folder. So you should be able to do it if all of the pages that require the 2nd type of authentication live in a specific sub-folder with it's own config. Not 100% sure on this, though, so if someone more knowledgeable can contradict me I'll just delete the response. A: You may need to double check me on the syntax, but the top level web.config can have any number of tags. <location>...</location> Inside you can specify separate config parameters for whatever folder/file you want. Look here for a reference. EDIT: Apoligies, I neglected to format the code properly A: You cannot have an <authentication> section inside of a <location> tag, so you must have the subfolder set up as an IIS (and ASP.NET) application of it's own. So, you should be able to run the subsection on it's own. I think 500.19 is the "can't read or parse web.config" error - does it have details? You may need to turn on remote errors (or check Event Viewer) to see them. If you're still having issues, post a snippet of web.config. As an aside - I've never been a fan of nested apps, and would probably prefer having your normal Login.aspx page handle it either with as a MemberOf or perhaps redirecting to a SpecialUserLogin.aspx or something. Nested apps are a PITA to setup and test, IME (for instance - I don't think you can even get it working under Cassini - though you can do 2 separate projects for it, and combine when you deploy). A: Yes you can. The Web.config files have a tree-like inheriting arhitecture with override capabilities. Meaning you can modify the settings inside a sub-folder by placing a web.config file there and specifying different configuration settings. A: The way I understand this problem, you have two solutions and the first is to look at Roles and the whole Provider Model would be a great place to start. Otherwise, the best bet would be to separate the application into two parts, breaking out the second user type area and then including it back into the main project via a Virtual Directory. Just remember that Virtual Directories inherit their permissions from the parent directories web.config, so you will need to use the <Location>tags to remove authentication for the virtual directory and then within the virtual directories web.config define your new forms authentication. This works well if you need Windows Authentication (NTLM) under Forms Authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/149200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to determine whether a XML attribute exists in Flex I have a XML response from an HTTPService call with the e4x result format. <?xml version="1.0" encoding="utf-8"?> <Validation Error="Invalid Username/Password Combination" /> I have tried: private function callback(event:ResultEvent):void { if(event.result..@Error) { // error attr present } else { // error attr not present } } This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks. EDIT: I have also tried to compare the attribute to null and an empty string without such success... A: I like this method because a.) it's painfully simple and b.) Ely Greenfield uses it. ;) if("@property" in node){//do something} A: You can check this in the following way: if (undefined == event.result.@Error) or dynamically if (undefined == event.result.@[attributeName]) Note that in your example, the two dots will retrieve all descendants on all levels so you'll get a list as a result. If there are no Error attributes, you'll get an empty list. That's why it will never equal null. A: Assuming that in your example event.result is an XML object the contents of which are exactly as you posted, this should work (due to the fact that the Validation tag is the root tag of the XML): var error:String = event.result.@Error; if (error != "") // error else // no error The above example will assume that an existing Error attribute with an empty value should be treated as a "no-error" case, though, so if you want to know if the attribute actually exists or not, you should do this: if (event.result.hasOwnProperty("@Error")) // error else // no error A: I like to use the following syntax to check because it's easy to read, less typing and it nearly tied as the fastest method: if ("@style" in item) // do something To assign a value back to that attribute when you don't know the name of it before hand use the attribute method: var attributeName:String = "style"; var attributeWithAtSign:String = "@" + attributeName; var item:XML = <item style="value"/>; var itemNoAttribute:XML = <item />; if (attributeWithAtSign in itemNoAttribute) { trace("should not be here if attribute is not on the xml"); } else { trace(attributeName + " not found in " + itemNoAttribute); } if (attributeWithAtSign in item) { item.attribute(attributeName)[0] = "a new value"; } All of the following are ways to test if an attribute exists gathered from the answers listed on this question. Since there were so many I ran each in the 11.7.0.225 debug player. The value on the right is the method used. The value on the left is the lowest time in milliseconds it takes when running the code one million times. Here are the results: 807 item.hasOwnProperty("@style") 824 "@style" in item 1756 item.@style[0] 2166 (undefined != item.@["style"]) 2431 (undefined != item["@style"]) 3050 XML(item).attribute("style").length()>0 Performance Test code: var item:XML = <item value="value"/>; var attExists:Boolean; var million:int = 1000000; var time:int = getTimer(); for (var j:int;j<million;j++) { attExists = XML(item).attribute("style").length()>0; attExists = XML(item).attribute("value").length()>0; } var test1:int = getTimer() - time; // 3242 3050 3759 3075 time = getTimer(); for (var j:int=0;j<million;j++) { attExists = "@style" in item; attExists = "@value" in item; } var test2:int = getTimer() - time; // 1089 852 991 824 time = getTimer(); for (var j:int=0;j<million;j++) { attExists = (undefined != item.@["style"]); attExists = (undefined != item.@["value"]); } var test3:int = getTimer() - time; // 2371 2413 2790 2166 time = getTimer(); for (var j:int=0;j<million;j++) { attExists = (undefined != item["@style"]); attExists = (undefined != item["@value"]); } var test3_1:int = getTimer() - time; // 2662 3287 2941 2431 time = getTimer(); for (var j:int=0;j<million;j++) { attExists = item.hasOwnProperty("@style"); attExists = item.hasOwnProperty("@value"); } var test4:int = getTimer() - time; // 900 946 960 807 time = getTimer(); for (var j:int=0;j<million;j++) { attExists = item.@style[0]; attExists = item.@value[0]; } var test5:int = getTimer() - time; // 1838 1756 1756 1775 A: You have found the best way to do it: event.result.attribute("Error").length() > 0 The attribute method is the preferred way to retrieve attributes if you don't know if they are there or not. A: I have figured out a solution, I'm still interested if there is a better way to do this... This will work: private function callback(event:ResultEvent):void { if(event.result.attribute("Error").length()) { // error attr present } else { // error attr not present } } A: Here you go: if(event.result.@error[0]){ //exists } Easy, eh? :) A: May be you can try this way if (undefined == event.result.@[attributeName]);
{ "language": "en", "url": "https://stackoverflow.com/questions/149206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: AVI Animations for GUI I need to get some AVI animations for use with the Borland VCL TAnimate component, to display during operations such as 'online update', 'burning cd' and a few others. I have only come across the glyFX Animation Pack so far. Can anybody recomend other places to get nice avi animations? A: You could consider using GIF animations instead of AVIs. There are a lots of them on the Web. There are also some free Delphi components working with animated GIFs, look TGIFImage for Delphi for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/149210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Determining available bandwidth What is the best way to determine available bandwidth in .NET? We have users that access business applications from various remote access points, wired and wireless and at times the bandwidth can be very low based on where the user is. When the applications appear to be running slow, the issue could be due to low bandwidth and not some other issue. I would like to be able to run some kind of service that would warn users whenever the available bandwidth dips below a specific threshold. Any thoughts? A: Not beyond the obvious of downloading a file of a known size and timing how long it takes. the disadvantage of that is that you'd need to waste a lot of bandwidth to do it. Also, if you wanted to alert when throughput drops below a threshold, you'll have to run the test more-or-less continuously. IMHO, I'd live with poor performance in some locations, given that you can't do anything about it if it does occur. Sorry. A: There's no easy way to measure bandwidth without actually using it - which of course will starve the applications. A couple of points to bear in mind though: 1) Is it actually bandwidth that's the problem, or latency? You can measure latency in a less intrusive manner than bandwidth. 2) Are the applications all run from the same server (or at least the same network)? You may find that users will have a good connection to some areas of the net but not others. (It's likely that the last mile will be the limiting factor, but it's not always the case.) A: If you're transferring data, simply measure it. You could also download a reference object from somewhere if you want to make it independent of the speed of your server. A: Without knowing the exact nature of your connection, or how its used, there are two options that I am aware of. MultinetGetConnectionPerformance (http://msdn.microsoft.com/en-us/library/aa385342(VS.85).aspx) System Event Notification Service (http://msdn.microsoft.com/en-us/library/aa377538(VS.85).aspx) Neither are direct .NET classes, but can be implemented in .NET very easily. Take a look at both of them and see if they will work for you. Roy
{ "language": "en", "url": "https://stackoverflow.com/questions/149211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are hypothetical indexes? Does anybody know what hypothetical indexes are used for in sql server 2000? I have a table with 15+ such indexes, but have no idea what they were created for. Can they slow down deletes/inserts? A: hypothetical indexes are usually created when you run index tuning wizard, and are suggestions, under normal circumstances they will be removed if the wizard runs OK. If some are left around they can cause some issues, see this link for ways to remove them. A: Not sure about 2000, but in 2005 hypothetical indexes and database objects in general are objects created by DTA (Database Tuning Advisor) You can check if an index is hypothetical by running this query: SELECT * FROM sys.indexes WHERE is_hypothetical = 1 If you have given the tuning advisor good information on which to base it's indexing strategy, then I would say to generally trust its results, but if you should of course examine how it has allocated these before you trust it blindly. Every situation will be different. A: A google search for "sql server hypothetical indexes" returned the following article as the first result. Quote: Hypothetical indexes and database objects in general are simply objects created by DTA (Database Tuning Advisor) A: Hypothetical indexes are those generated by the Database Tuning Advisor. Generally speaking, having too many indexes is not a great idea and you should examine your query plans to prune those which are not being used. A: From sys.indexes: is_hypothetical bit 1 = Index is hypothetical and cannot be used directly as a data access path. Hypothetical indexes hold column-level statistics. 0 = Index is not hypothetical. They could be also created manually with undocumented WITH STATISTICS_ONLY: CREATE TABLE tab(id INT PRIMARY KEY, i INT); CREATE INDEX MyHypIndex ON tab(i) WITH STATISTICS_ONLY = 0; /* 0 - withoud statistics -1 - generate statistics */ SELECT name, is_hypothetical FROM sys.indexes WHERE object_id = OBJECT_ID('tab'); db<>fiddle demo
{ "language": "en", "url": "https://stackoverflow.com/questions/149213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to move asp.net/ajax control BEFORE page loading? I have an Panel control that I need to maintain position across postbacks. I am able to do this by maintaining a cookie which is read each time the page is loaded to get the position of the Panel before the page is loaded. The problem is, the page is loaded, then repositioned which causes this brief flash where the control is at its default location and jumps to the location it was at prior to postback. Is there a way to prevent this? I want the control to move to its position first, THEN have it displayed to prevent this "flash". *edit: I am adding a DragPanel ajax control extender to reposition this. I have a pageLoad that is called and the Panel is repositioned after pageLoad is called. There's gotta be a really simple solution to this. A: Could you register the function that positions the panel in the pageLoad event of the ASP.NET client-side library? This link may be helpful: ASP.NET AJAX Client Life-Cycle Events A: Because you're storing the panel's location in a cookie, you could update the panel's location during the server side postback event. A: Since you already have code to reposition the panel during pageLoad, you can add code on server side to hide the panel when IsPostback. On pageLoad, you'll need to add step to set panel.style.display='' after panel after reposition.
{ "language": "en", "url": "https://stackoverflow.com/questions/149227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Merging big files in C# I have 7-8 xml files. Each one is approximately 50 MB in size. What is the best way to merge files programmatically in C# without getting System.OutOfMemory Exception? So far I have tried reading each file in a StringBuilder and than putting it in an array of string builder but I still get system.outofmemoery exception. Any help?? Thank you, -Nimesh A: The thing about stringbuilder is you're still trying to keep the entire contents in memory. You want to only keep a small portion in memory at a time, and that means using filestreams. Don't read an entire file into memory, open a stream on it and keep reading from the stream. The problem with xml is that you can't just append them to each other: you'll break the tag nesting. So you need to know something about the structure of your xml files so that you can have an idea of what to do at each file boundry. If you have something that works in theory with StringBuilder, but only fails in practice because of memory constraints, you should be able to translate the StringBuilder's .Append() and .AppendLine() method calls into .Write() and .WriteLine() calls for a filestream. A: The details of what you need to merge are indeed vital. However, to start you off: you're likely to want an XmlReader for each of the input files, and an XmlWriter for the output file. That will let you stream both the input and the output. Another alternative would be to use XStreamingElement from LINQ to XML. I don't have any experience of this, but it may well be a simpler API to use. (The rest of LINQ to XML is certainly nicer than the DOM API.) A: Please, define "merge". If you want just to concatenate the files, then use StreamReader, and read line by line. If you want actually to produce a new valid xml, then go with XmlTextReader. It does not read the whole file in memory. A: Personally, when I have to deal with XML files (forced by threat of physical violence usually), I do this: * *Load each file into a .NET DataSet via DataSet.ReadXML() *Combine the information (via DataSet queries). *Write out the combined DataSet to XML via DataSet.WriteXML() Then I aggressively delete the orginal XML file and wipe the sectors where it existed on the disk to remove the taint. :-) A: It depends what you mean by merge, since you haven't posted any information about the schema. In the simplest case of homogeneous simple elements in a single collection, you would just merge directly to a new file on disk avoiding much in-memory work, ensuring that the outer containing elements are stripped off and added around the collection. A: Not sure what you mean by merge in this case. Do you mean simple concatenation of the files, or are you inspectng the content? for example, file1.xml <items> <item id="1"> <name>Widget</name> </item> <item id="2"> <name>Widget 2</name> </item> </items> file2.xml <items> <item id="3"> <name>Widget</name> </item> <item id="4"> <name>Widget 2</name> </item> </items> could be combined as <items> <item id="1"> <name>Widget</name> </item> <item id="2"> <name>Widget 2</name> </item> </items> <items> <item id="3"> <name>Widget</name> </item> <item id="4"> <name>Widget 2</name> </item> </items> which is quite trivial, or as <items> <item id="1"> <name>Widget</name> </item> <item id="2"> <name>Widget 2</name> </item> <item id="3"> <name>Widget</name> </item> <item id="4"> <name>Widget 2</name> </item> </items> Which is less so, given the amounts of data you are talking about. Which do you mean? A: Merge them within the file system by invoking "copy a.xml + b.xml" command or by invoking the windows filesystem APIs used by the "copy" command.
{ "language": "en", "url": "https://stackoverflow.com/questions/149233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Edit php.ini with .htaccess I'm slowly getting back into PHP, and now I run into a problem, I want to install some web software on our host and I need to have either the latest Zend (which they don't have) or IonCube on the server and IonCube requires enable_dl to be on in the php.ini. Now a colleague of mine thinks I can update this via an .htaccess file on the server. So I created a s.htaccess on my machine as Windows doesn't like emptiness before the file extension. So I added the line php_flag enable_dl On to the file uploaded it and renamed the file to just .htaccess on the server. When I refresh the file is gone, when I keep it as s.htaccess it's fine but my php info still shows it as Off. What n00b mistake am I making? A: The documentation says that this can only be set in the php.ini (not in .htaccess). You can see this by looking at the table where it says "PHP_INI_SYSTEM", which means - "Entry can be set in php.ini or httpd.conf". A: Unix way to hide files is prepending it with a dot. The file is there, but it's just hidden. Your ftp-software should have a setting for showing hidden files. IIRC you can rename the file to .htaccess through cmd in windows. The .htaccess only has effect in the current dir and sub directories. This might also be (because of security) one of those settings that is only setable through php.ini
{ "language": "en", "url": "https://stackoverflow.com/questions/149236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Not Nil shortcut in Delphi What delphi function asserts that an object is not nil? A: Assigned(AObject) will tell you if an object is nil or not. Perhaps worth mentioning is the fact that if you free an object using AObject.Free the Assigned will still return true. So make sure you free the object using FreeAndNil(AObject). A: if Assigned(MyObject) then ... A: Like knight_killer pointed out above, you use the Assert() function, asserting that Assigned(obj) is true. Of course, like in most compiled languages, assertions are not executed (or even included in the compiler output) unless you've specifically enabled them, so you should not rely on assertions for release mode builds. You can, of course, simply check against nil, a la Assert(obj <> nil). However, Assigned() produces the exact same compiler output and has the added benefit that it works on pointers to class methods too (which are in reality a pair of pointers, one to the method, and the other one to the class instance), so using Assigned() is a good habit to pick up. A: Not sure what you mean but Assert(Assigned(MyObject)); is pretty short and easy to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/149262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }