text
stringlengths
8
267k
meta
dict
Q: How did you choose your Visual Studio productivity addon? I'm evaluating Visual Studio productivity addons for my development team, which includes some folks who are very new to C# and some folks who are very experienced. We don't use VB.NET. I personally like ReSharper, but before I suggest something that I personally like, I would like some opinions for and reasoning behind using a different addon. Given the choice between ReSharper, CodeRush, and Visual Assist, which one did you choose and why? For discussion, do you run more than one addon at a time? Or one not on this list? What are your thoughts on these addons? A: Since we are developing in C++ the Visual Assist was the best choice for us. The ReSharper works only with C#, VB and XML. The Refactor++ is nice, but it literally hangs the VS for some minutes upon every massive change in the code. We have also tried different other tools but all of them has no support for the C++. The CodeRush is new for me, I'll evaluate it this weekend (thanks) A: Personally I have tried several, but my preference is two: 1: TestDriven.NET - for simple testing; I tend to use it with Team Coverage which lets me see the coverage directly in the editor, even though the tests are NUnit (not MSTest) based. 2: a tiny add-on that lets me group files the same way the IDE does - simpler than editing the csproj (DependentUpon IIRC) by hand. From here, but there is an (unlinked) updated msi here with better support for choosing which file is the parent (hold [Ctrl] when choosing "Group Items") I've never found I've needed ReSharper etc, but I should give it another try some day... A: I downloaded both resharper and coderush trials. Initially I liked coderush a bit better. It seems a bit more polished and a bit more stable. But eventually I did go with resharper. Mainly because of the unit testing integration. I don't really see why you have to choose for your development team though. In my last company everyone used the tools they liked. We all used VS 2005 and 2008(depending on the project) and svn for versioning as long as everyone used the same coding standards we didn't have much problems. Standardizing is good up to a point but it might be a good idea to give your developers some choice in what tools they want to use. A: I use VSCommands in my everyday coding. I adds great new features to VS and is free :) (visual studio gallery link) A: I too chose VisualAssist X because I work in native C++ so tools like ReSharper don't help me. I made my decision based on input from other preofessional developers I know and respect and on my successful experience using a trial version. CodeRush supports C++ but I didn't know about it until just now. From what I see, it looks similar to VisualAssist X. I'd give them both a try. BTW: If I were you I would only install one of these tools at a time. I don't know if you need to do this but it wouldn't surprise me if they had some unexpected interactions. A: I recommend ReSharper 4.0 with VS 2008. It really offers the best refactoring commands. ReSharper 4.0 has really been improved since it's beta. However, I heard that CodeRush had a better templating model. Personally, I rather have a powerful refactoring tool rather than a templating tool. I suggest ReSharper 4.0 A: Almost everybody on the dev team here has ReSharper installed, however there are a lot of complaints about it slowing down Visual Studio. A: I chose Refactor! Pro a couple of years or so ago because at that time it supported C#, VB, ASP.NET (and now JavaScript and C++). I use all of these languages. ReSharper only supported C# back then. VisualAssist may have been just C++. Plus at the time I was doing VB. Having chosen Refactor! then I'm now comfortable with its UI paradigm and so probably won't switch anytime soon. I'm also now using CodeRush Xpress because I can't afford the full CodeRush right now. (I did try ReSharper briefly back in 2005 when working at a client sit.)
{ "language": "en", "url": "https://stackoverflow.com/questions/166987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java table model design I have a table class that creates modifies a table of items. I want to display those items in a JTable using a table model. To me table model belongs to my GUI package but table needs table model in order to fire changes and table model needs table class in order to display it so I can not separate the two. if you need to do this what would be the class structure you use? or do I have a flow in my thinking and they belong in the same package? A: A TableModel is an adapter. I always write the table model to extends AbstractTableModel and have it as a private inner class of my GUI panel class. You only have to fill in a few methods: getRowCount, getColumnCount and getValueAt Your GUI class should have access to some controller where it can fill in this information from. When your controller finds out about updates to the data, it should inform your GUI class which can then call AbstractTableModel.fireTableDataChanged or other appropriate methods. Never use the DefaultTableModel class because you then have to keep the table model's data in sync with the controller's. As I said, the table model is an adapter which presents the controller's data in a way which the JTable can understand A: For me the tablemodel is part of the widget, that is the GUI. I wouldn't depend on the javax.swing package in my business logic classes. So you will use an adapter or other mechanism to load your tablemodel from the business layer, but this degree of separation can be useful. The decision also depends on the size of the project, and can be a lot more complex than this. E.g. see the jgoodies binding framework and docs for the more abstract cases. A: The model is the bit that holds the data. It should maintain and fire listeners as such models do. Now you might want some kind of delegation within the model to transform the data or adapt the type. So you have your data in a model object that is not necessarily anything to do with javax.swing.table. Then implement a TableModel that delegates to your underlying model. Create a JTable with that TableModel, but no reference to the underlying model. A: I strongly suggest that anyone doing significant table or list driven development take a look at Glazed Lists - I've written custom TableModel and CellRenderers for years, binding with JGoodies, etc... I stumbled across GL about a year agin, and my development has never been the same - the Glazed Lists approach is just astounding. GL has two characteristics that make it my framework of choice for list based data binding and processing: * *Very, very easy to do the normal things you want to do *Makes it possible to do the really, really hard things you may want to do Take a look and see if you aren't impressed. I strongly recommend playing with the sample apps, then watching a few of the screen casts that take you through the actual coding process. A: The table model doesn't need to know anything about the table that it's put in. I put the table model in the model package, and the table in the view package. The controller is responsible for asking the model package for the model, asking the view package for the table, and setting that model in the table.
{ "language": "en", "url": "https://stackoverflow.com/questions/166996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perforce repository monitor for Windows I used to work with Subversion and a system tray tool (SVN Notifier) to monitor the repository so I would immediately see when my local copy was not up-to-date anymore, and I am wondering if some equivalent was available for Perforce (on Windows). A: stimms answer will certainly do exactly as you ask. But if you want to go a little further an alternative would be to use the P4 Review mechanism, where you can get Perforce to send you an email if changes are made to a user specified part of the depot. It will need setting up on the server, but is trivial to do. See the Perforce documentation and website and look for "review daemon". A: If you use the Perforce GUI client, you can setup email notifications for as many folders as you like by going to: * *Connection > Edit Current User... > Reviews tab *Right click each of the locations you're interested in tracking and click "Include Tree" *Click OK This assumes the review daemon has already been setup on the server. See http://public.perforce.com/wiki/Frequently_Asked_Questions#How_do_I_track_changes_to_a_project_I_am_interested_in.3F A: I haven't seen such a thing but it would be pretty trivial to write. Just check to see if the output of p4 sync -n contains any informaiton.
{ "language": "en", "url": "https://stackoverflow.com/questions/167002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need a regular expression to match three character strings I generally stay away from regular expressions because I seldom find a good use for them. But in this case, I don't think I have choice. I need a regex for the following situation. I will be looking at three character strings. It will be a match if the first character is 1-9 or the letters o,n,d (lower or upper) AND the second character is 1,2 or 3 and the third character is 0-9. Can anybody help me out? A: Slight variation on a few other answers. Restrict the input to be exactly the matched text. ^[1-9ondOND][123][0-9]$ A: [1-9ondOND][123][0-9] I omitted the ^ and $ (beginning and end of string markers) because you said you'd have three-character strings, but there's no harm in including them, and they may improve speed, not that that'll be a big deal on such short input. Of course, this assumes you're working in a language and locale where the uppercase equivalent of o, n, and d are O, N, and D. If not, you'll need to tell your regex interpreter to ignore case. The mechanism varies by language/framework. For python, you'd use something like: re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE) The re.match forces a match at the beginning of string, so you wouldn't need the ^ in any case. A: Perl RegEx: /^[1-9ondOND][1-3][0-9]$/ ^ at the start of the string; $ at the end of the string. A: [1-9ond][123][0-9] Here's a useful place to test your RegEx. A: A very late answer, but hope this will help ([1-9]|(?i)(o|n|d))[123][\d] http://regex101.com/r/vE2jT1/1 A: In a PREG-based system (most of them these days): ^(?:[1-9]|[ond])[1-3][0-9]$ Some systems require the start/end markers (PHP, Perl, but not .NET for instance), if yours does, it'd end up something like: /^(?:[1-9]|[ond])[1-3][0-9]$/
{ "language": "en", "url": "https://stackoverflow.com/questions/167003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using nmake with wildcards in the makefile I am attempting to set up an nmake makefile to export our balsamiq mockup files to png files automatically, but I'm afraid I can't make heads nor tails of how to make a generic rule for doing so, without explicitly listing all the files I want exported. This page details the command line syntax for exporting the files, and this page contains an example which looks like it contains a generic rule for .obj files to .exe files. The makefile I have tried so far looks like this: .bmml.png: "C:\Program Files\Balsamiq Mockups\Balsamiq Mockups.exe" export $< $@ But this doesn't work. If I simply run nmake (with some outdated png files), nmake just does this: [C:\Temp] :nmake Microsoft (R) Program Maintenance Utility Version 9.00.30729.01 Copyright (C) Microsoft Corporation. All rights reserved. [C:\Temp] : If I ask it to build one specific file, it does this: [C:\Temp] :nmake "TestFile.png" Microsoft (R) Program Maintenance Utility Version 9.00.30729.01 Copyright (C) Microsoft Corporation. All rights reserved. NMAKE : fatal error U1073: don't know how to make '"TestFile.png"' Stop. [C:\Temp] : Any nmake gurus out there that can set me straight? An example makefile which simply makes .dat files from .txt files by copying them, to experiment with, looks like this: .txt.dat: copy $< $@ this does nothing as well, so clearly I'm not understanding how such generic rules work. Do I need to specify a goal above that somehow lists the files I want? A: NMAKE pattern rules are a lot like GNU make old-school suffix rules. In your case, you had it almost right to begin with, but you were missing the .SUFFIXES declaration. For example: .SUFFIXES: .bmml .png .bmml.png: @echo Building $@ from $< I think this is only part of your solution though, because you also mentioned wanting to avoid explicitly listing all of the files to be converted. Unfortunately, I don't know of a very clean way to do that in NMAKE, since it only expands wildcards in dependency lists, and what you really want in your dependency list is not the list of files that already exist (the *.bmml files), but the list of files that will be created from those files (the *.png files). Nevertheless, I think you can achieve your goal with a recursive NMAKE invocation like this: all: *.bmml $(MAKE) $(**:.bmml=.png) Here, NMAKE will expand *.bmml in the prereq list for all into the list of .bmml files in the directory, and then it will start a new NMAKE instance, specifying the goals to build as that list of files with all instances of .bmml replaced by .png. So, putting it all together: .SUFFIXES: .bmml .png all: *.bmml @echo Converting $(**) to .png... @$(MAKE) $(**:.bmml=.png) .bmml.png: @echo Building $@ from $< If I create files Test1.bmml and Test2.bmml and then run this makefile, I get the following output: Converting Test1.bmml Test2.bmml to .png... Building Test1.png from Test1.bmml Building Test2.png from Test2.bmml Of course, if you have very many of these .bmml files, you may run afoul of command-line length limitations, so watch out for that. In that case, I recommend either explicitly listing the source files, or using a more capable make tool, like GNU make (which is available for Windows in a variety of forms). A: Will this work for you? Put this in MAKEFILE.: export : *.bmml "C:\Program Files\Balsamiq Mockups\Balsamiq Mockups.exe" export $** $(**B).png Then run: nmake /A I don't have Balsamiq so I can't test this but in my case if I have the following MAKEFILE.: export : *.txt copy $** $(**B).dat and run nmake /A in a folder with myFile.txt, it will create myFile.dat.
{ "language": "en", "url": "https://stackoverflow.com/questions/167004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Fast compiler error messages in Eclipse As a new Eclipse user, I am constantly annoyed by how long it takes compiler error messages to display. This is mostly only a problem for long errors that don't fit in the status bar or the "Problems" tab. But I get enough long errors in Java—especially with generics—that this is a nagging issue. (Note: The correct answer to this question is not "get better at using generics." ;-) The ways I have found to display an error are: * *Press Ctrl+. or execute the command "Next Annotation". The next error is highlighted and its associated message appears in the status bar (if it is short enough). The error is also highlighted in the "Problems" tab, if it is open, but the tab is not automatically brought to the top. *Hover the mouse over the error. After a noticeable lag, the error message appears as a "tool tip", along with any associated "Quick Fixes." *Hover the mouse over the error icon on the left side of the editing pane. After a noticeable lag, all of the error messages for that line appear as a "tool tip." Clicking on the icon brings up "Quick Fixes." What I would like is for Ctrl+. to automatically and instantly bring up the complete error message (I don't care where). Is this a configurable option? [UPDATE] @asterite's "Ctrl+. F2" is almost it. How do I make "Next Annotation, then Show Tooltip Description" a macro bound to a single keystroke? A: Well, you can press F2 to display the popup that normally shows javadoc. If there's an error, it will display the error message with available quick fixes. So you can do Ctrl+., F2 repeatedly to achieve what you want. A: Yeah nagging problem. Ctrl+1 brings up the quick fixes if you use it from the same line. Sometimes I have to resort to copying the error message from the problems view :( A: "After a noticeable lag, the error message appears as a "tool tip", along with any associated "Quick Fixes." Dont know if this will help you but you can reduce the lag in the pop up by changing the value of auto activation delay in the in the menu located at: Window>Preferences>Java>>Editor>ContentAssist
{ "language": "en", "url": "https://stackoverflow.com/questions/167007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best practice for creating subversion repositories? Our team (5-10 developers) plans to adopt Subversion for our .NET (Visual Studio) projects/solutions (VisualSVN Server, TortoiseSVN / VisualSVN). What is the best way to organize a new repository tree? Is it okay to use one big repository or is it better to create different repositories for every solution / product line etc.? Our projects can be categorized this way (example): * *Main Product Line * *Main Web App * *Library 1 *Library 2 *... *Windows Client *Another Windows Client *Windows Service *Tools * *Tool A *Tool B *Product Line 2 * *Software 1 *Software 2 *Product Line 3 * *App 1 *App 2 A: * *SVN managment standpoint I prefer 1 repository. *Programmer standpoint I prefer 1 repository. *Server Administrator I prefer 1 repostitory. *Security standpoint it is preferrable not to put all of your eggs in one basket. Your repository structure will be somewhat unique to your business, and it's products. We keep ours in one repository. Our structure somewhat like this. * */ * *Projects * *Project Name * *trunk *branches *tags *Documentation * *Project 1 *Shared Libraries * *Super string class *Small utilities * *vim enhancement X A: We use one big repository, and just have everything structured in subfolders (/project1, /project2 etc) and that seems to work fine. The Apache project has a huge svn repository and it seems to do OK for them! :) In terms of organisation, the structure you gave looks quite reasonable. I think anything goes, pretty much, so long as it's rational (i.e. mixing up every single tool with every single project is probably a bad idea etc). So pick something which works for you (tools/, projects/ etc). Subversion has pretty good support for moving things around in the repository, too, so you can always change if necessary. A: We have a single repo that's structured like that. Anything that is worked on by more than a few people and/or in active development is set up with trunk/ tags/ branch/ under the main folder. We would probably put those the trunk-tags-branch folderset under every subfolder you listed, except maybe a library or two that aren't in active development. A: My source of inspiration: * *Version Control with Subversion *Subversion Repository Layout *Single Repository or Many *Multiple Subversion repositories A: Generally, you want to use a separate repository in any case where you are expecting different access permissions (i.e. some developers should have commit access to one project, but not another, or one project has a public read-only anonymous interface but another doesn't). You want everything in one repository if you don't need that level of access control, especially if you need to be able to copy or move files between projects (i.e. projects might share code). Put your trunk/tags/branch split at whatever level corresponds to a chunk of code you might release as a single package (i.e. think of where you would tag). This isn't critical to get right at first, since these no different internally from any other folder, so you can just move things around later, though of course it's neater not to have that problem. A: Try to keep regularly accessed material (code, scripts) separate from the 'write-once and commit to backup' stuff. Having to checkout/update thousands of jpegs just to change a few lines of code gets dull very quickly. A: We have separate repos for each project; but the main reason is for access reasons plus if the customer wants a copy of their source we can give it to them with history without too much fuss. If you look at the config files in conf it's not that hard to have a universal config file that will work for all of your projects. We do it like this: [general] anon-access = none auth-access = write password-db = ../../conf/passwd authz-db = ../../conf/authz authz: [groups] AOS = nathan,mark [AOS:/] @AOS = rw frew = rw and then of course passwd: [users] frew = password nathan = awesome mark = station A: I am using one repository and many projects as below: Projects Project Name trunk branches tags My only concern is the backup and restore. The SVN backup is done at the repository level, so the restore will restore all projects instead of just one. Jirong
{ "language": "en", "url": "https://stackoverflow.com/questions/167014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Should I use threading and recursion together? I have been tinkering with BSP trees for a while now and am also playing with threads. When adding a triangle to a BSP tree, an opportunity arises to create a new thread for the purposes of processing data in parallel. insert(triangle, bspnode) { .... else if(triangle spans bspnode) { (frontpiece, backpiece) = plane_split(triangle, bspnode) insert(frontpiece, bspnode.front) insert(backpiece, bspnode.back) } .... } The two insert operations above could be executed by two threads, and since they do not modify the same data, cheap synchronization can be used. insert(triangle, bspnode) { .... else if(triangle spans bspnode) { (frontpiece, backpiece) = split(triangle, bspnode) handle = beginthread(insert(backpiece, bspnode.front)) insert(frontpiece, bspnode.back) if(handle) { waitforthread(handle) } else { insert(backpiece, bspnode.front) } } .... } This new method attempts to create a thread to complete the operation in parallel, but should not fail if the thread cannot be created (it will simply revert to the original algorithm). Is this a sound programming practice, or am I using threads improperly? I have not been able to find any literature on this technique. I like that it tends to use my CPU to its fullest (2 cores), and would theoretically scale to any number of processors available. I don't like that it might be horribly wasteful on CPU and memory. A: your best bet would be to create a threadpool, and then use it 'transparently' to add nodes. eg, create 2 threads at program start, have them wait on a semaphore or event. When you have nodes to add, you pop the data onto a queue then trigger the semaphore. This wakes one of the threads which pops the data off the queue and performs the processing. (make sure access to the queue is threadsafe - fully synchronised with a critical section is best). The overall performance of your app is slower as you have more overhead, in copying data to the queue and running the extra threads, but if you used to run on a single core you will now be running on 2. It works best if the threaded processing is expensive. A: Threads are great if some part of the processing is waiting on something external (user input, I/O, some other processing) - the thread that's waiting can continue to wait, while a thread that isn't waiting forges on ahead. However, for processing-intensive tasks, more threads than processors actually creates overhead. It seems like your threads are doing all "CPU work", so I'd stick to one thread per core - test to find the optimal number, though. The biggest overhead created is from context switching (freezing one thread and loading the execution context of the next one), as well as cache misses when threads are doing tasks with different memory (if your thread can use the CPU cache effectively). A: Sure, for example, Quicksort can be programmed multithreaded quite easily and get some large performance gains on multi-core systems, and some small performance losses on non-multithreaded. Just remember that you're adding overhead twice now - once for the stack save on the recursion and once on the thread, so if you're doing a large number of recursions then it could overwhelm a system faster than a non-multithreaded approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/167018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do you right-justify text in an HTML textbox? I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right. A: Apply style="text-align: right" to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right. A: Using inline styles: <input type="text" style="text-align: right"/> or, put it in a style sheet, like so: <style> .rightJustified { text-align: right; } </style> and reference the class: <input type="text" class="rightJustified"/> A: Did you try setting the style: input { text-align:right; } Just tested, this works fine (in FF3 at least): <html> <head> <title>Blah</title> <style type="text/css"> input { text-align:right; } </style> </head> <body> <input type="text" value="2"> </body> </html> You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
{ "language": "en", "url": "https://stackoverflow.com/questions/167027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: Programmatically change keyboard to Dvorak Does anyone know the API call I can use to change the keyboard layout on a windows machine to Dvorak? Doing it through the UI is easy but I'd like to have a script that I can run on new VM's to automate the process. A: You can do this via the registry. Just save it as a .reg file, and open it on the new VM. I believe this should do it for remapping to Dvorak: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "ScanCode Map"=hex:00,00,00,00,00,00,00,00,22,00,00,00,2d,00,30,00,24,00,2e,00,\ 11,00,33,00,33,00,11,00,12,00,20,00,34,00,12,00,1b,00,0d,00,0d,00,1b,00,16,\ 00,21,00,17,00,22,00,20,00,23,00,1a,00,0c,00,2e,00,17,00,23,00,24,00,14,00,\ 25,00,31,00,26,00,35,00,1a,00,30,00,31,00,13,00,18,00,26,00,19,00,2f,00,34,\ 00,28,00,10,00,0c,00,28,00,19,00,13,00,18,00,1f,00,1f,00,27,00,2c,00,35,00,\ 15,00,14,00,22,00,16,00,25,00,2f,00,10,00,2d,00,21,00,15,00,27,00,2c,00,00,\ 00,00,00 And if you want to go back: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "ScanCode Map"=hex:00,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00 A: I may be four years late to the party, but did you ever find this: Intlcfg Command-Line Options I don't have Windows Vista (very bad habit, Windows), but looking at this page and also at Available Language Packs and Default Input Locales I reckon the command you want might well be: intlcfg.exe -inputlocale:0409:00010409 for English (United States) language with United States Dvorak input locale.
{ "language": "en", "url": "https://stackoverflow.com/questions/167031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Multiple database connection I'm trying to understand the best way to get the connection to my databases. At the moment I've got a method which parses the URL (depending on the URL called the application has to connect to a different database, like customer1.example.com will connect to the customer1 database) and calls ActiveRecord::Base.establish_connection(conn_string) where conn_string contains the name of the database. This method (set_db) is called with a before_filter :set_db in my Application controller, so basically for each request I get, the URL is parsed and the application try to do an establish_connection. I was wondering if I can have a connection pool somewhere....do you have any suggestion about that? Is it better to have a Singleton which keep all the connections made and gives back the right one? Thanks! Roberto A: Are the databases on the same server? I have a application where some of the model objects are from one database and others are from a different database. I override the table_name function to specify the database. Won't work if they are different servers but will work for different databases in the same server. class xx < ActiveRecord.base def self.table_name "otherdatabase.table" end It also looks like database pooling may be on the way for an upcomming version of rails. What's New In Edge Rails A: I'm not a Ruby programmer, but generally speaking a connection pool is a good idea. You can make that connection pool a singleton and hand out/take back connections. The pool can check after taking back a connection whether everything is still in order. You should have a distinct life cycle and ownership for each connection so two threads don't use a connection at the same time. Be careful with temporary tables because they belong to one database session. We've had a bug where in high load situations we encountered weird errors. Finally we remembered that we were using temporary tables in our application. In the high load situation database connections broke down and were automatically regenerated by the connection object without the application code knowing it (we had implemented the reconnect, but forgot that it was a problem in such a situation). The temporary table we wanted to read had disappeared. A: First regarding the comment left on your initial post : this has nothing to do with ruby. it has everything to do with the design of rails. with that said, you could probably hijack the ActiveRecord::Base behaviour to keep a hash of connections indexed by a key (in your case the key would be the user name) then intercept establish_connection to check in the pool if the connection is open already that would require that you reopen ActiveRecord base,which makes your change dependant on AR internals. A: I'm not going to cover your question on pooling. However, i'm sure that pooling will help to improve things a lot. I also have a installation where each client has it's own database and codebase is shared among them. Method to parse url is implemented outside Rails in Apache Rewrite configuration because multiple hosts can be mapped to single customer. Also i use customer "key" to access cached files on webserver disk. Rewrite configuration looks something like this: RewriteMap accounts prg:domain_mapper.rb RewriteMap lowercase int:tolower RewriteCond %{HTTP_HOST} ^(.*)$ RewriteCond ${accounts:${lowercase:%1}} ^(.+)$ RewriteRule . - [E=ACCOUNT:%1] RequestHeader set Customer-Key %{ACCOUNT}e And customer key will map directly to database name which will be connected in before_filter method. So far, switching a database connection on Rails side is not an performance issue. Problems are in MySQL configuration and we're facing problems where there are too many databases and too many requests cause too many open databases in MySQL. I'm sure you've been considering migrating issues. It wasn't a problem in the beginning with < 2000 database schemas. Now there's > 15K customer databases (and growing) so we're merging them back into small number of sharded databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/167053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Adding durability to in-memory data structures What are some of the popular techniques you can adopt to add durability to your in-memory data structures (ie) if the process crashes, you can preserve all previously executed operations on that data structure? If my data structure involves just a list of tuples, then I would just store them in a SQL DB and that would give me durability for free. But what if my data structure was a graph or a tree? The one thing I could think of is to explicitly log all operations to disk (append-only log) and in the event of a crash, replay the log to preserve the previous state. If the log becomes too big, then there will be a compaction step. I'm guessing this is what a database engine does internally for durability (checkpointing is what this process is called)? Btw note that this is not a scenario where the entire dataset doesn't fit in memory. A: You might want to try an object prevalence engine. For .NET, you might want to try Bamboo.Prevalence, which is a port of a similar engine called Prevayler for Java. A: I've implemented the "Mrjb" technology in 2 companies' products, which is basically exactly what you've suggested in your question: a "Memory Resident Journal Backed" database, an in-memory data-structure where every change is logged to disk as it happens. And it works great for us! http://www.edval.biz/memory-resident-programming-object-databases I'd be happy to share our real-world experiences with using this in a production context. I love being able to replay an exact sequence of events or roll back to any point in time. A: The word you're looking for is "serialization". A: You could come up with some way to serialize your structure, whether with XML, YAML, JSON, etc. Then you could either store that in the DB, or perhaps put one big try/catch around the main execution point to the program. Then if some uncaught exception happens, which will cause the program to crash, you could serialize your data, ans well as log any error messages, stack traces, etc. A: Yes, you would want to serialize the data to some format - xml, binary, whatever. Depending on the programming languagem this may be built in for you. Java has ObjectStreams, .NET has XmlSerializer and also a BinaryFormatter. A: Any answer to your question will entail doing something like what an ACID database system does. So I would say your best bet is to use an RDBMS to store your application state, updating whenever you have an (application) transaction that must not be lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/167063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Localizing applications on Mac OS I have an application which is supposed to work on both windows and Mac and is localized in Portuguese, Spanish and German. I have an ini file from where the localized strings are read from. But the ini file doesn't work with same encoding for the files on both platforms. For Windows I have to have the file in ANSI format or else the accented letters in the localized strings get messed up and on the Mac the same file should be in Western( Mac OS) encoding or else the same result. Is there any way I can get a single file to work on both platforms? A: (1) There is no such thing as the ANSI format. That's an unfortunate term for what on Windows means "the local codepage". In particular, this means that in Europe the interpretation of bytes 128-255 as "ANSI format" will differ between countries. So, I am strongly inclined to argue that it won't even work on your first platform, let alone both. The solution you will eventually migrate to is Unicode. That works everywhere, with all characters, and the number of a character does not depend on the country or the current date (See introduction of €). A: On Mac you can have your localised resources (text files, etc) inside a .lproj folder and the Cocoa libraries will find the version for the user's language. For example English.lproj, Spanish.lproj etc. It's better if you use this system instead of having your own custom localisation mechanisms. If you're using something other than Cocoa and you need to use your custom localisation stuff for portability reasons, then you can try loading the file specifying the text encoding. On Windows it's usually ISO-8859-1 (also known as Windows Latin 1). Or you can convert your text files to Unicode and read them specifying that it's UTF-8. You're not telling what language or frameworks you are using for this so we can't help you any further without more info. A: gettext is a widely used framework for translation of applications, websites, etc. A: Welcome to a world of pain. I would also recommend switching to Unicode, it will give you a verifiable basis to start with, and make life easier later on
{ "language": "en", "url": "https://stackoverflow.com/questions/167066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Limit with Many to Many Relationship Given a SCHEMA for implementing tags ITEM ItemId, ItemContent TAG TagId, TagName ITEM_TAG ItemId, TagId What is the best way to limit the number of ITEMS to return when selecting with tags? SELECT i.ItemContent, t.TagName FROM item i INNER JOIN ItemTag it ON i.id = it.ItemId INNER JOIN tag t ON t.id = it.TagId is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT. A: My second solution uses a MySQL function GROUP_CONCAT() to combine all tags matching the item into a comma-separated string in the result set. SELECT i.ItemContent, GROUP_CONCAT(t.TagName ORDER BY t.TagName) AS TagList FROM item AS i INNER JOIN ItemTag AS it ON i.id = it.ItemId INNER JOIN tag AS t ON t.id = it.TagId GROUP BY i.ItemId; The GROUP_CONCAT() function is a MySQL feature, it's not part of standard SQL. A: Maybe something like select i.ItemContent, t.TagName from (SELECT ItemId, ItemContent FROM item limit 10) i INNER JOIN ItemTag it ON i.ItemId = it.ItemId --You will miss tagless items here! INNER JOIN tag t ON t.id = it.TagId A: My first suggestion is to use a subquery to generate the list of item ID's and return items matching those item ID's. But this doesn't include the TagName in your result set. I'll submit a separate answer with another solution. SELECT i.ItemContent FROM item AS i WHERE i.id IN ( SELECT it.ItemId FROM ItemTag AS it INNER JOIN tag AS t ON (t.id = it.TagId) WHERE t.TagName IN ('mysql', 'database', 'tags', 'tagging') ); This is a non-correlated subquery, so a good SQL engine should factor it out and run it only once. A: You could also use Distinct/Group By: SELECT DISTINCT TagID, TagName FROM ((TAG T INNER JOIN ITEM_TAG I_T ON T.TagID = I_T.TagID) INNER JOIN ITEM I ON I_T.ItemID = I.ItemID) GROUP BY TagID, TagName
{ "language": "en", "url": "https://stackoverflow.com/questions/167067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# code from desktop to the web If I develop a desktop app using C#, and later want to turn it into a webapp but don't want to use ASP.NET, what are my options? I did a bit of searching and it looks like there doesn't appear to be a good solution to integrate C# code with any scripting language other than running it as a web service and making SOAP calls. Any other ideas? A: Why would you make things so difficult for yourself? The best thing would be to put almost all of your code into an assembly, and just use the winforms app for display purposes. Then, later, you can just reimplement the display logic in asp.net. So, I guess the answer is no. A: AJAX + WebService + plain HTML A: You could embed a webserver in the application. It's quite easy, even with threading so that you can handle simultaneous requests. There's a bunch of examples on the web, here's one at the codeplex: http://www.codeplex.com/webserver A: It would be easy enough to have your application offering a SOAP service, which you could then integrate with a front-end in pretty much any language. If you really want to avoid that then just go for some less recommended but cheap ASP.Net hosting and use that - if the application is a success you can always shift to dedicated hosting later. It's worth spending a bit of money to make your life a whole lot easier and from what you have said there really isn't a lot of point in avoiding ASP.Net if it means you have to do four times as much work. A: How about ASP.NET on Mono? How painful is that realistically? A: I can't leave a comment for your reply about hosting but I've had .net hosting with Lunarpages for ages now and found it to be just about as affordable as linux hosting and with the same perks like php support, unlimited mysql and ms sql dbs etc. To answer the mono question, it's fine but I think Mono only supports up to 3.0 ATM. A: I vote monorail. Keep a nice MVC model.
{ "language": "en", "url": "https://stackoverflow.com/questions/167073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do MembershipProviders in ASP.net MVC affect stylesheet links? I changed the MembershipProvider in my ASP.net MVC website, and now the stylesheet for the login page isn't referenced correctly. Below is a copy of the forms tag in my web.config if that could be the reason. It looks identical though to the one generated by a new project with the exception of the name and timeout attribute. <authentication mode="Forms"> <forms loginUrl="~/Account/Login" name=".ADAuthCookie" timeout="10" /> </authentication> When I visit the page now, the link tag for the CSS looks like this: <link href="../Content/Site.css" rel="stylesheet" type="text/css" /> When it should look like this: <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> A: I haven't used ASP.NET MVC yet myself, but you could try using ResolveClientUrl when writing out the href for your CSS: <link href="<%= ResolveClientUrl("../../content/Site.css") %> rel="stylesheet" type="text/css" /> A: Thanks Ian Oxley. The problem wasn't solved with the ResolveClientUrl though. It had to deal with the web.config file. I had code that looked like this: <authorization> <deny users="?" /> <allow users="*" /> </authorization> I added a location element below the main one and said that anybody could view that content, and it works now. It turns out that files like the CSS file were not viewable until authorized before. That is now fixed. This is what I added: <location path="Content"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location>
{ "language": "en", "url": "https://stackoverflow.com/questions/167074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving existing code to Test Driven Development Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start. I'm using NUnit, and VS 2008, any tips on what sort of classes to start with, what to write tests for, and any tips on generally how to go about moving code across to test based development would be greatly appreciated. A: See the book Working Effectively with Legacy Code by Michael Feathers. In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the codebase is, and how much the various classes and functions depend upon each other. Refactoring without tests will introduce changes in behaviour (i.e. bugs). And purists will say it's not really refactoring because of the lack of tests to check that the behaviour doesn't change. Rather than adding test across the board to your whole application at once, add tests when you work in an area of code. Most likely you'll have to return to these "hotspots" again. Add tests from the bottom up: test little, independent classes and functions for correctness. Add tests from the top down: Test whole subsystems as black boxes to see if their behaviour changes with changes in code. And so you can step through them to find out what's going on. This approach will probably get you the most benefit. Don't be too concerned at first with what the "correct" behaviour is while you are adding tests, look to detect and avoid changes in behaviour. Large, untested systems often have internal behaviours that may seem incorrect, but that other parts of the system depend on. Think about isolating dependencies such as database, filesystem, network, so that they can be swapped out for mock data providers during testing. If the program doesn't have internal interfaces, lines which define the boundary between one subsystem/layer and another, then you may have to try to introduce these, and test at them. Also, automatic mocking frameworks like Rhinomocks or Moq might help mock existing classes here. I haven't really found the need for them in code designed for testability. A: Testable code is easy to spot - by the accompanying tests. If there are some, it must be testable. If there are none - assume the opposite. ;) That said: Test Driven Development (TDD) is not so much a testing strategy as it is a design strategy. The Tests that you write first help in designing the interface of your classes, as well as in getting the scope of your classes (or subsystems for that matter) right. Having the tests that you created during TDD and executing them later makes good tests, but is merely a (very welcome) side effect of that design philosophy. This said, expect some resistance from your code against being tested. Listen to your code and change the interface in order to be easily testable. You'll most likely redesign it when you start writing tests. A: Your DLL provides some sort of service. For every service, what do you have to do before getting this service, what parameters should you pass to get this service, how would you know that the requested service has correctly be executed ? Once you have the answers to those questions, you can write a first test. Such tests would rather be called Characterization tests than unit tests, but would probably be easier to write than unit-tests if the DLL was not developped using TDD. Characterization tests are also discussed in M. Feathers' "Working Effectively with Legacy Code", which is recommended in other responses. Also, be sure to write a failing test before to add any new line of code. A: I call it "Test Driven Reverse Engineering". Start "at the bottom" -- each class can be separately examined and a test written for it. When in doubt, guess. When you're doing ordinary TDD in the forward direction, you treat the test as sacred and assume that the code is probably broken. Sometimes the test is wrong, but your starting-off position is that it's the code. When you're doing TDRE, the code is sacred -- until you can prove that the code has a long-standing bug. In the reverse case, you write tests around the code, tweaking the tests until they work and claim the code works. Then, you can dig into the bad code. Some bad cade will have sensible test cases -- this just needs to be cleaned up. Some bad code, however, will also have a test case that's senseless. This may be a bug, or clumsy design that you may be able to rectify. To judge if the code's actually wrong, you also need to start at the top with overall test cases. Live data that actually works is a start. Also, live data that produces any of the known bugs, also a good place to start. I've written little code generators to turn live data into unittest cases. That way, I have a consistent basis for testing and refactoring. A: Working Effectively with Legacy Code is my bible when it comes to migrating code without tests into a unit-tested environment, and it also provides a lot of insight into what makes code easy to test and how to test it. I also found Test Driven Development by Example and Pragmatic Unit Testing: in C# with NUnit to be a decent introduction to unit testing in that environment. One simple approach to starting TDD is to start writing tests first from this day forward and make sure that whenever you need to touch your existing (un-unit-tested) code, you write passing tests that verify existing behavior of the system before you change it so that you can re-run those tests after to increase your confidence that you haven't broken anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/167079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Detecting Graphic Options in .NET What is the the best of detecting and later altering the screen resolution and multiple desktop within .net I have a small app that while runs at work on my multiple monitor/high(ish) resolution however what I want to be able to detect is the users primary monitor and set the application to that (main objective) and adjust the resolution to ensure the application fits(more for my own curiosity) A: I would never suggest altering a user's resolution unless you're doing something like a full-screen game, you can use System.Windows.Forms.Screen.PrimaryScreen to give you metrics about that main monitor. A: If you're working on a WinForms-based application, in addition to using the Screen metrics described by Bob King, you can also go with layout controls, such as TableLayout and FlowLayout. Layout controls allow you to design your UI to adapt to the screen/window size cleanly. (The WinForms app I'm currently working on does this very well, down to a minimum of 1024x768, up to whatever your heart desires, scaling controls all the way.) Preemptive comment: Yes, TableLayouts do involve a performance hit. However, my experience has been that users tend to be OK with it when shown the benefits. (New monitor: The app still looks great and works!)
{ "language": "en", "url": "https://stackoverflow.com/questions/167084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the proper naming convention for a web service in .NET? I'm creating a webservice, and I want to name it appropriately. Right now my service is named Service as per the /App_Code/Service.cs Should I rename it to something like: com.example.MyWebService.cs? How do I get around the class file not excepting '.' in the file name? A: the "com.example.whatever" namespace thing is java specific. Microsoft recommends that you use Company.Product.etc.. Check out the Naming guidelines at: http://msdn.microsoft.com/en-us/library/ms229002.aspx A: com.example would be the namespace, and not part of the class/service name. You should do: namespace Com.Example { public class MyWebService { // class contents } }
{ "language": "en", "url": "https://stackoverflow.com/questions/167088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is the order of objects returned by FOREACH stable? Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed. A: While the answer is “yes” for all builtin collections and probably any sane collection class out there, the documentation doesn't have any constraints formulated for IEnumerable. Therefore, nothing tells us that every iteration must be stable. I could imagine the following use case: foreach (int i in new Shuffler(1, 2, 3, 4, 5, 6, 7, 8, 9)) Console.WriteLine(i); This might well be implemented as a class that yields a different ordering for each iteration. So – if you also want to consider strange borderline cases, the answer should be “no”. A: While typically, the elements will be returned in the same order, there's absolutely no guarantee. It's entirely dependant on the internal implementation of the collection class. I can see a case for a collection class that's specifically designed to return elements in a random order, for example. In short, unless you know the internal implementation of the collection class, don't assume anything about the order. A: It depends on the collection type. For most collections, the answer is "Yes". However, this is not guaranteed. The docs of a collection type should specify whether or not it does, but as most do, that detail is generally over looked. However, if it is not stable, it would be a tremendous oversight if the docs didn't mention that. A: Linq defines the IOrderedEnumerable interface for this purpose. A: Short answer - yes. Obviously, though, the order of the items in the collection may not be exactly as they were inserted, depending on the type of collection (a dictionary, for example). But you will get the same results each time you iterate over a single, unmodified collection using a foreach loop. A: You can't guarantee this unless you know the concrete implementation of the class you're iterating over. Collections that have a defined element order (e.g. List<T>) will enumerate in a stable order. For collections where the state of the object doesn't change it's highly likely that elements will come back in the same order, e.g. Dictionary<K,V>, although this not guaranteed by the specification. As an example of where this would not be the case, you could imagine a hashtable based dictionary implementation that compacts or resizes the table asynchronously. Such an implementation would not guarantee a stable iteration order. A: Re "unmodified" (NM's reply) - note that many complex containers like Dictionary do not guarantee to preserve order. Sometimes adding an item will make it appear last (giving the impression that order is preserved), and sometimes it will cause the internal buckets to re-organise, giving a completely different order. Things like SortedList<,> etc obviously have their own rules. A: I would say that for most collection it is safe to assume this. It's not beyond the realms of possibility that a certain collection could have the enumerator implemented in a non-deterministic way, but that's probably not going to happen...
{ "language": "en", "url": "https://stackoverflow.com/questions/167096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How do I limit which countries can view my website ( PHP ) In there an easy way to do this in PHP. I want to make sure that only web requests from certain countries are able to access my website. Any ideas? A: Like Gilles, I've used MaxMind's GeoIP stuff for this in the past - configured with the PECL extension for speed. It works reasonably well, but... The requirement for this kind of thing tends to come from somebody that doesn't understand that it is impossible to reliably determine a visitors location in this way. It's very important that the person asking for it be encouraged to understand that it is almost useless. Typical thing that happens with geo-location in this: Client: I want to be able to restrict content by IP Dev: You do know that that is impossible to do reliably? Client: Ah yes, but this company say they will sell me something that will do it Dev: Yes but it isn't accurate and is easy to circumvent and usually indicates a poor business model for internet based content Client: Can you do it? Dev: Whatever... ...Six months later... Client: Some of my visitors have been complaining they can't see my content and some bad people who shouldn't see it have been able to! Dev: /me slaps head It's only one step on from there to "can I have it so that when a user right clicks in their browser a little sign pops up saying 'these images are copyright Idiot Inc.'?" Sorry, obviously in a cynical mood today! A: Both of the answers (geolocation, user agent) will work but can be defeated. Someone can use a proxy server, or change their user agent. Firefox even has a plugin for that purpose. A: if you use the answer of Ben Dowling and the code doesn't work, try this: if (!in_array(substr($country, 0, 2), $allowed_countries)) { instead of: if(!in_array($country, $allowed_countries)) { A: Use an IP geolocation database (some are free) and $_SERVER["REMOTE_ADDR"] to get the visitor's IP address. http://www.maxmind.com/app/geolitecity is a free (less accurate) version of a commercial one. A: There's also a pear package http://pear.php.net/package/Net_Geo A: There are certain classes that can detect the locale of the user agent. Try something like that. Zend Framework has a great class for this Zend_Locale
{ "language": "en", "url": "https://stackoverflow.com/questions/167106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Does static array constness affect shared library layout? Consider these two C++ header cases: Case 1: class Test { public: static int TEST_DATA[]; }; int Test::TEST_DATA[] = { 1, 2, 3, 4 }; Case 2: class Test { public: static int const TEST_DATA[]; }; int const Test::TEST_DATA[] = { 1, 2, 3, 4 }; Is const in the latter case only for self-imposed compile-time checks or does it affect shared library layout on Mac/Linux/Windows? Update: According to the answers, the compiler may put the const stuff on a read-only page. Does Visual C++ on Windows or GCC on Mac or Linux actually place const data on a read-only page? Perhaps I tested the wrong way but on Mac on Intel, the elements of the const version seemed writable. A: The compiler may put the data into a different section of the binary depending on whether it's const or not - that's entirely at the discretion of the compiler. A: The compiler (or, actually, the linker) could place the second into a segment marked as read-only, to trigger a hardware exception if you tried to write to it. Since writing to things not intended to be written to is a vector for security attacks, more systems are securing their read-only data. A: Although there are no guarantees, the const is unlikely to break binary compatibility in the case of an array, so shared libraries should end up with the same layout. Note this would likely not be the case for a single int: struct Test { static int const TEST; }; int const Test::TEST = 7; because TEST is a compile-time constant.
{ "language": "en", "url": "https://stackoverflow.com/questions/167109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing a subset of a dict from within a list This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this: a = {1:'', 2:'', 3:'', 4:''} exclusion = [3, 4, 5] # have to build up a new list or the iteration breaks toRemove = [] for var in a.iterkeys(): if var in exclusion: toRemove.append(var) for var in toRemove: del a[var] This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict. This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this. A: a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion) A: Why not just use the keys method, instead of iterkeys? That way you can do it in one loop because it returns a list, not an iterator. A: You could change your exclusion list to a set, then just use intersection to get the overlap. exclusion = set([3, 4, 5]) for key in exclusion.intersection(a): del a[key] A: Consider dict.pop: for key in exclusion: a.pop(key, None) The None keeps pop from raising an exception when key isn't a key.
{ "language": "en", "url": "https://stackoverflow.com/questions/167120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: C# - IEnumerable to delimited string What is the functional programming approach to convert an IEnumerable<string> to a delimited string? I know I can use a loop, but I'm trying to wrap my head around functional programming. Here's my example: var selectedValues = from ListItem item in checkboxList.Items where item.Selected select item.Value; var delimitedString = ?? .. or could I do this in just the first var assignment (append each result to the previous)? A: string.Join(", ", string[] enumerable) A: var delimitedString = string.Join(",", checkboxList.Items.Where(i => i.Selected).Select(i => i.Value).ToArray()); A: AviewAnew is the best answer, but if what you are looking for is learning how to think in functional, what you should do is use a fold operation (or aggregate as it is called in NET). items.Aggregate((accum, elem) => accum + ", " + elem); A: Here's an example with a StringBuilder. The nice thing is that Append() returns the StringBuilder instance itself. return list.Aggregate( new StringBuilder(), ( sb, s ) => ( sb.Length == 0 ? sb : sb.Append( ',' ) ).Append( s ) ); A: var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y); A: Well, in this case the functional approach might not be best suited, simply because there isn't a LINQ "ForEach", and you don't want to use string concatenation: you want to use StringBuilder. You could use ToArray (an example just appeared above), but I'd be tempted to simply use: StringBuilder sb = new StringBuilder(); foreach(ListViewItem item in checkboxList.SelectedItems) { if(sb.Length > 0) sb.Append(','); sb.Append(item.Text); } string s = sb.ToString(); Not functional programming, but it works... of course, if your source is already a string[] then string.Join is perfect. (LINQ is a great tool, but not necessarily always the best tool for every job) A: Here's a LINQ/functional way of doing it. string[] toDelimit = CallSomeFunction(); return toDelimit.Aggregate((x, y) => x + "," + y); A: This is 3.5 compatible: var selectedValues = String.Join(",", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());
{ "language": "en", "url": "https://stackoverflow.com/questions/167129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to properly use Struts ActionForms, Value Objects, and Entities? I've inherited a large Java app that uses Struts, Spring, and Hibernate. The classes and interfaces I deal with daily are: Struts Actions, Struts ActionForms, Value Objects, Service Interfaces and Implementations, DAO Interfaces and Implementations, and Entities. I'm pretty clear on the how and why of most of these, except I'm unsure about the correct separation of responsibilities between the ActionForms, Value Objects, and Entities. I should also mention that the Domain Model (i.e. all of the entities) doesn't contain much (if any) real business logic. This is essentially a CRUD app and most of the real logic is in the database (yuck!). Anyway, there are several distinct Java related issues that I'm wondering about: 1) It seems there is not much difference between the Entities and the Value Objects (VOs), and a lot of code must be written to transform on into the other when they pass through the service layer in either direction (Struts Actions deal only with VOs, DAOs deal only with Entities). So, VOs and Entities seem somewhat redundant. Why have them both? 2) Where should the VO<->Entity translation code go? The service layer, the Entity, the VO? 3) VOs are placed directly into ActionForms and directly bound to tags in the JSP (e.g. ). Is this a good practice? If not, what's the appropriate design? 4) It is unclear how to properly handle foreign key dependencies in the Value Objects. For example, certain VOs have a type field that, in database terms, represent a foreign key relationship into a type table. In the UI, this translates into a dropdown field that lets the user pick the type, OR a label that simply displays the textual representation of the type (depending on which screen it is). Now, should the VO have a property for the type ID, the textual representation of the type, or both? Who is responsible for translating between the two, and when? 5) The VOs have a field for their database ID. I thought VOs don't have identities? What's up with this? I hope these questions are generic enough to be of general interest. It seems this would come up all the time in this type of architecture. Also, I have the suspicion that this architecture is way to heavy for this app, and if you have suggestions about a better one, go ahead. But I'm mainly interested in the answer to the above questions since a different architecture is a long-term refactoring that I can't do right now. A: 1. Considering the DAO - VO transformation; whether this is usefull depends on how Hibernate is used. If the entire Web request handling is in a single Hibernate session you should not really need separate VO's. If, however, your DAO layer opens a session to retrieve an object and closes the session before you are finished using the DAO you may get trouble with collections and references to other objects. There is a fair chance that those are lazily loaded, meaning that the Session must still be opened when requesting those properties. In short, before you start ditching those VO's have a good, hard look at you database transaction and session boundaries. 3. As for using a VO in a Form; if the VO maps nicely to the JSP I would say why not? I'm either impressed that the data model so closely matches the process it supports, and a bit suspicious that the database has not been normalized (which may or may not pose problems in the future). Going back to 1. If you use DAO's with lazy loading and collections, remember that the database session must also include the JSP phase as the DAO will be read in that phase. *The service layer must have a facility to know which database objects to alter, and the id is designed to do just that. The service layer will have to retrieve the DAO from the database and write the fields from the VO in the DAO, though it obviously does not need to update the id of the DAO with the id of the VO :) *What you need from the request is the id of the foreign key field. As it comes from the client you should probably check in the business logic whether an object with such an id exists. Depending on whether the VO accepts the id of the foreign object or requires an object you should then either: * *set the id, or *get the foreign object as a VO by id using the service layer and put it in your VO, and store it using the service layer Your business layer is responsible for translations as the service layer only deals with object retrieval and storage. And either the text or the id are not objects but identifiers of the objects. The service layer may offer search facilities, but it should not need context information. And if I read your question right your VOs refer to other objects in the database by id. In that case you enter the id. If you get a String from the client you should look it up in the business layer (using the service layer) and put the id of the found object in the VO. Or, if no ID is found, return a decent error message. As a closing note; don't touch the DAO-VO thing unless you know what you're doing REALLY WELL. Hibernate is a powerfull and complex tool which is deceptively easy to use. You can very easily make mistakes and they can be very hard to find. And customers and bosses alike don't seem to appreciate the introduction of bugs in stuff that used to work. By the way; my conservatism in the DAO-VO thing come from fixing problems due to similar problems in EJB2 to Hibernate transitions. The devil is in the details, and changing how you deal with the data layer is a major refactoring even if it looks like a piece of cake. A: 1) No need for separate VO and Entities : some companies mandate such a structure for their project. It might have made sense in a different project and hence it was mandated (I can only guess) 2) Service layer : it is the natural separation from DAO and Action layer, right ? 3) It does NOT hurt however value Objects are bound as long as they are properly validated before sent to DAOs 4) The service layer should be responsible for translating between the two. During load and save time 5) if they don't have identities, then how would you prevent duplication ? I hope these terse answers helped. I'll try and get back and give a longer answer later. A: To answer your last part, use Spring MVC instead of Struts. Then you can just use the same Domain Objects at all layers - the Classes that bind to form parameters are also used in Hibernate, and contain real business logic. For example, in an app I did using Spring MVC, I had a member class. The login, registration, change password, and edit profile forms all were bound to this class. The class also had a hibernate mapping and a good bit of business logic inside (for example, for a social network an "add friend" method).
{ "language": "en", "url": "https://stackoverflow.com/questions/167131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: asp.net frameworks and libraries every developer should know...and use I'm still kinda new in ASP.NET and recently I found out about SubSonic, which I started to use. Now it seems funny and such a waste of time (and nerves) when I look back into times when I was developing without SubSonic and jQuery. And there probably are a lot of libraries and frameworks that speeds up development. Which ones do you use? A: What I like to use, at the moment: * *NHibernate *Autofac *ASP.NET MVC *jQuery A: I only started liking to make websites once I started using the MVC Framework If you're not already doing this, be sure to check Rob Conery's log. He's the father of SubSonic and recently started working for MS in the MVC team.
{ "language": "en", "url": "https://stackoverflow.com/questions/167151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoiding code change with Microsoft SQLServer and Unicode How can you get MSSQL server to accept Unicode data by default into a VARCHAR or NVARCHAR column? I know that you can do it by placing a N in front of the string to be placed in the field but to by quite honest this seems a bit archaic in 2008 and particuarily with using SQL Server 2005. A: The N syntax is how you specify a unicode string literal in SQL Server. N'Unicode string' 'ANSI string' SQL Server will auto convert between the two when possible, using either a column's collation or the database's collation. So if your string literals don't actually contain unicode characters, you do not need to specify the N prefix. But if your string literals do contain unicode characters then using the N prefix is necessary. A: If this is a web application, you could probably get your webserver to use UTF8 as it's default encoding. That way all data back and forth to the browser would be UTF8 which can be inserted into VARCHAR fields. UTF8 is a nice way to make applications that are not aware of Unicode deal with it. A: They really need a way to turn off the need for the N'' prefix. The "it's needed for backwards compatibility" argument makes zero sense to me - sure, make that behavior the default for old apps, but provide an option for me to turn on Unicode strings by default (i.e, no N'' prefix required.) I'm discovering that I need to go and mess with large areas of my app to adapt to Unicode on SQL Server when this is NOT an issue in Oracle and Postgresql. C'mon, Microsoft! A: While you can simply store UTF8 content in a VARCHAR field in MSSQL Server as long as charset translation is not done you should be aware that: * *No management/reporting/data tools outside of your application will be able to understand your non-english characters. *Language specific handling such as sorting a list of names may not be done in the order acceptable for every language. *Must be careful about data truncation. Truncating a multi-byte UTF8 character ususally causes data corruption for the character involved. You should always reject input if it exceeds the field length. *It may not be as easy as you think to disable charset translation..Even if you turn it off in your client driver it can still be overriden in some cases if there is a significant locale difference between client and RDBMS codepage used which instantly leads to data corruption. *If you think this is all you will have to worry about your fooling yourself. In summary while you might be tempted to go down this path its not a good idea. Code change is required when going multi-byte.
{ "language": "en", "url": "https://stackoverflow.com/questions/167152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Logic: Database or Application/2 (constraints check) This is a specific version of this question. I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer: if (exists(obj)) { throw new DuplicateObjectException(); } HibernateSessionFactory.getSession().save(obj); or should I catch the exception thrown by the database layer and triggered when I violate the contraint? try { HibernateSessionFactory.getSession().save(obj); } catch(ConstraintViolationException e) { throw new DuplicateObjectException(); } EDIT: In other words: though the constraint is there to remain (it's good database design anyway, and I can't be sure my app will be the only one accessing the table) shall I rely on the constraint and handle the exception its violation will raise, or I'd better check anyway? EDIT2: Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime A: First, you must have a primary key or unique constraint on the database to enforce this uniqueness properly - no question. Given that the constraint exists, which way should you code in the application? My preference would be to try the insert and catch the exceptions. Because presumably most inserts will succeed, only a few will fails as duplicates (that's what "exception" implies!): it is inefficient to perform an exists check before every insert, when the database is going to be performing its own constraint checking anyway. Also, it is theoretically possible for the exists check to be wrong anyway - if someone else manages to commit a record with the same key value in the small interval between your exists check and your insert. Then, if you don't trap the database exception, you will believe the insert succeeded when in fact it didn't. A: You need to catch the database exception unless you can guarantee that your application is the only one that ever inserts rows (and ever will insert rows) into your database. EDIT: I may have misunderstand the question, but I would still argue that option B (HibernateSessionFactory throws the ConstraintException from the database) is the better option. There's always a small chance that another application could insert something in the sliver of time between your check and the actual function call. In addition, the only way to check for a dupe is to perform an additional query which is just a needless drain on performance. My original understanding of the question was that in option A the dupe check would be performed internally (i.e. by using only the data structures that the program had already created, and with no query until the INSERT). My original answer was in response to this method. A: You check that the object exists solely in application code, and then once satisfied that it does not, blithely save the object. But another concurrent client might insert their own object in the moment between your two lines of code. So you'd get a Duplicate exception anyway, only this time you don't catch it. You must do the save() and catch the exception. Otherwise you have a race condition with other concurrent clients working on the same database. A: In general, I try to avoid coding that relies on errors being thrown because I did something wrong. Sometimes, though, that's all you can do. In your situation, I think you should check first. A: This will break (allowing duplicate entries) if the constraint gets dropped for some reason (typically maintenance work where the DBA neglects to re-enable it). You should check for this situation within the application. However, it is good database design to have the database enforce the constraint (as you have quite rightly pointed out) as others may also be using the database. As a generalisation it is best to assume that applications and databases live in a M:M relationship - this will be the case almost all of the time. A: The exceptions thrown by Hibernate (or any ORM component) tend to be hard to interpret. If the exception has enough information that you can produce an error message that actually helps the user, then just catch the exception, analyze it, and move on. If the exception doesn't have enough information, then you have to check for the error condition, and produce a helpful error message to the user that they're doing something wrong. The question is one of "how opaque is the exception"? Some are pretty opaque. Others have enough that you can parse the message string and figure out what to say to the user. A: Once hibernate throws an exception from the session you must discard the session (see section 11.2.3). So, if you need to check for dups and continue using the same session then you have no choice but to check first in the application. Also there is a possibility with the code in the 1st snippet that another process could insert a record that would cause the duplicate exception to be thrown between the time you check for the duplicate record and the time it actually gets inserted.
{ "language": "en", "url": "https://stackoverflow.com/questions/167154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to copy files from one code project to another I have multiple branches of a project checked out, each under their own directory (pretty standard). src/branch1/some/code/directories src/branch2/some/code/directories I often find myself wanting to copy selected files from one branch to another. An example would be copying cvsignore files, or intellij module files. The pseudocommand for what I'm trying to do is "copy all files under branch1 matching PATTERN to branch2, preserving the relative path of the copied file". This question looks close to what I'm looking for, but I need an OS X/linux/unix solution. A: Use "cp -r --parents" command like this, in branch1 directory find . -name ".cvsignore" -exec cp -r --parents {} ../branch2/ \; OR When in the src/ directory, run this script. You can get the variables from command line parameters if you want. SOURCE="branch1/" TARGET="branch2/" PATTERN=".cvsignore" find $SOURCE -name $PATTERN | while read f ; do FILEPATH=$(dirname $f | cut -d'/' -f2-) FILENAME=$(basename $f) DESTPATH=$TARGET/$FILEPATH; if [ ! -d $DESTPATH ] then mkdir -p $DESTPATH fi cp $f $DESTPATH done
{ "language": "en", "url": "https://stackoverflow.com/questions/167159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What C/C++ functions are most often used incorrectly and can lead to buffer overflows? I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know). I've decided to removing the buffer overflows first, starting with the dangerous functions. What C/C++ functions that are most often used incorrectly and can lead to buffer overflow? For compiler and/or tools used to help look for buffer overrun, I've created another question that deals with this A: Valgrind is your new best friend. valgrind --tool=memcheck --leak-check=full ./a.out A: The question is starting at the wrong end, I'm afraid. It's presuming that buffer overruns happen in other functions. The most common cause is operator++, in my experience, or alternatively a lack of operator!=. The best solution to find a batch of those is /GS in Visual Studio 2005/8. It won't find all of them, but it's a cheap way to reduce the amount of manual work needed. A: Here's some functions that I found that are dangerous: * *gets() - It doesn't check the length of the variable and can overwrite memory if the input is bigger than the variable's buffer. *scanf() - I'm so glad that Visual Studio told me this function is deprecated. This was an easy fix. *strcpy() - If the source's memory space is bigger than the destination's, the data after the destination is overwritten. A: The following link should give you a comprehensive look at security functions in C++ (ones that are post-fixed with '_s' to fix problems like overflows): http://msdn.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx EDIT: This link contains the specific functions that have been replaced: http://msdn.microsoft.com/en-us/library/wd3wzwts(VS.80).aspx EDIT: I should mention these are Microsoft methods, but the link is still useful for identifying functions that were deemed a red flag. A: Unfortunately any array can result in a buffer overflow: uint32_t foo[3]; foo[3] = WALKED_OFF_END_OF_ARRAY; In terms of functions, sprintf will happily walk off the end of the buffer. It can be replaced by snprintf. A: Memcpy() is another dangerous one. Any loop accessing an array is a danger point, because there's no stopping going beyond the end of array. Memory Leaks are caused by allocating memory, and not freeing it. Constructor and destructors should be another strong review point, the latter to make sure any allocated memory is freeded. A: Which version of visual studio are you using? In 2008 with all warnings enabled, all the functions you mention (and more) warn you that they are deprecated. Perhaps you could check that all warnings are turned on and let the compiler do the hard work for you? As a side note, the excellent writing secure code does a great job explaining the different the pitfalls of some of the older functions. A: I have somewhat the same problem on the code base I work on. My advice: be wary of any C functions that look like str*() and mem*(). Also be wary of anything that takes a pointer to a buffer, without a length. Since it seems like you have the chance to use C++ I would in the most egregious cases try to use C++ containers for things: vector, string, map, etc. These make your life a lot easier. Also, automated problem detection tools are wonderful to have. If you can use valgrind I would recommend it. Also Rational Purify is extremely powerful, though not cheap. A: In general, any function that does not check bounds in the arguments. A list would be * *gets() *scanf() *strcpy() *strcat() You should use size limited versions like stncpy, strncat, fgets, etc. Then be careful while giving the size limit; take into consideration the '\0' terminating the string. Also, arrays are NOT bound checked in C or C++. The following example would cause errors. See off by one error int foo[3]; foo[3] = WALKED_OFF_END_OF_ARRAY; edit: Copied answers of @MrValdez , @Denton Gentry A: An additional gotcha in C is the "strncpy()" function. Many people do not realize that it is free to return a string that is not null terminated. A: Basically, anything which accept a pointer and writes to it, without checking the length. So thing like strcpy(), sprintf() etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/167165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: JPA and 2 simple tables I have 2 tables: A s_id(key) name cli type B sa_id(key) s_id user pwd So in Jpa I have: @Entity class A...{ @OneToMany(fetch=FetchType.EAGER) @JoinTable( name="A_B", joinColumns={@JoinColumn(name="a_id", table="a",unique=false)}, inverseJoinColumns={@JoinColumn(name="b_id", table="b", unique=true)} ) Collection<B> getB(){...} } class b is just a basic entity class with no reference to A. Hopefully that is clear. My question is: Do I really need a join table to do such a simple join? Can't this be done with a simple joincolumn or something? A: No you do not need a join table for OneToMany. Look at the @mappedBy annoatation A: You do not need a JoinTable for this. If the class B has no reference to class A then the following will suffice @Entity class A...{ @OneToMany(fetch=FetchType.EAGER) Collection getB(){...} } In most cases though you may want a bidirectional relationship in which case B has a reference to A. In that case you will need to look up the @mappedBy annotation. mentioned by Paul. A: The quick answer is that if you have a Many-to-Many relationship you will need another table. If you have a One-to-Many or a Many-to-One relationship you will not.
{ "language": "en", "url": "https://stackoverflow.com/questions/167193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What C/C++ tools can check for buffer overflows? I've been asked to maintain a large C++ codebase full of memory leaks. While poking around, I found out that we have a lot of buffer overflows that lead to the leaks (how it got this bad, I don't ever want to know). I've decided to removing the buffer overflows first. To make my bug-hunting easier, what tools can be used to check for buffer overruns? A: IBM's Purify will do this, you run your app under it and it will give you a report of all errors (including other ones). To kill memory leaks, use UMDH - run your app, take a snapshot of the memory, run it again, snapshot and then use a diff tool to see the allocations made since the first run through (note you must run your app once, and take snapshots as best you can). A: Check on electric-fence, it is design just for buffer overflow ! It does not slow down the code itself (but slow down allocation/deallocation). It works and linux and windows. It works by adding a segment with no read or write access before and after each allocated space. Trying to access this memory end up as a segmentation fault on UNIX and a memory violation (or something similar) on Windows. A: The problem with /GS is it won't actually scan for bugs. It will just alert you after the fact. It seems like you are looking for a tool which will scan your existing code for potential buffer over/under runs. A good tool for this, and other defects, is the Microsoft PreFAST tool. Information here A: MS: * *UMDH.exe tool: http://support.microsoft.com/kb/268343 */analyze compiler option (free from the latest Microsoft SDK) A: I'm surprised no one's mentioned Application Verifier (free!) on Windows. Visual Leak Detector (mentioned in another answer) is absolutely amazing for tracking many types of memory leak, but Application Verifier is top dog for tracking memory errors like buffer overruns, double frees, and buffer use after free (plus many, many more). Edit: And it's very, very easy to use. A: On Linux I'd use Valgrind. A: My vote goes to Rational Purify. Extremely powerful with a price to match. Makes short work of lots of problems and can really pay for itself. Also, is available on most *nix. Not sure about Windows, though. A: The BoundsChecker component of Compuware's Devpartner does this very well in terms of dynamic execution. For static testing, I'd recommend pc-lint and flex-lint coupled up to Riverblade's visual lint for usability and reporting. If you have been handed a new code base, I'd recommend starting out with static analysis with reasonably loose rules so you catch just the nasty stuff. As the codebase improves you can tightent the rule set. If you need to do this on Windows Mobile / Windows CE, check out Entrek's code snitch Another tool to consider if the code makes it into the field is AQtrace, which basically analyses crashes on user machines and sends you the details. (Just in case all that boundchecking, purifcation, linting, valgrinding etc.. misses something) A: My company, Semantic Designs is looking for beta testers for a runtime memory safety checker (including buffer overruns) that detects all types of memory access violations, even those that valgrind and Purify cannot. This is presently for Windows C programs only, not C++ or other OSes. EDIT June 1, 2011: The CheckPointer tool has gone production. Still C/Windows only. Handle multiple C dialects: MS Visual C, GCC 3/4. EDIT May 5, 2012: CheckPointer now handles C99, including checking calls on the standard C and C99 libraries. A: Consider using more modern data structures as a way of avoiding buffer overflows. Reading into a std::string won't overflow, and std::vectors are much safer than arrays. I don't know what your application is, and it's possible that raw buffers are used because you need the speed, but it's more common that they are used because that's what the original programmers were comfortable with. Searching for memory leaks with the tools mentioned is a good idea, but they may not find all potential leaks, while using standard strings and container classes can eliminate problems you didn't realize you had. A: Visual Studio has a /GS compiler flag that adds buffer overflow protection. Are there any others? A: You can try Visual Leak Detector - I used it myself, and it is the first thing I'd recommend for mem-leak detection. A: I'd recommend the free "leakfinder" tool on the CodeProject by Jochen Kalmbach. See my post for more details on this thread (and the other answers) on this memory leak question A: On Windows for memory leaks/buffer overruns and other runtime error detection you can use: * *Boundschecker from Compuware (http://www.compuware.com/products/devpartner/visualc.htm) *IBM Rational Purify I think they worth their price if you have large projects that need cleanup.
{ "language": "en", "url": "https://stackoverflow.com/questions/167199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: PHP Module for reading torrent files Is there a PHP module that you can use to programmatically read a torrent to find out information about it, Seeders for instance? A: Google comes up with this PHP client on sourceforge and this torrent class on PHP classes. Should be all you need. A: Torrent files are basically nested dictionaries encoded with BEncode. BEncode is a simple encoding and there are a few BDecode PHP classes, like this one. Structure of torrent file is described in BEP0003. Note that torrent files don't contain "Seeders" field that you mention. The list of seeders is dynamic and is managed by tracker server. Having torrent's hash_info and tracker_url (both available from torrent file) you can send scrape-request to the tracker and it will return number of seeders in 'complete' field, see Tracker Scrape Convention. A: I have used these functions in a small website I made once. Think I found them with a php bittorrent tracker called OpenTracker or something, but can't find the website... You wont find the seeders in the torrent file though. The torrent file just contain info about the files, hash codes and lengths etc. And some tracker information I believe. How many seeders and such you will have to get from the tracker. You can read about the protocal at BitTorrent.org. The communication is, I believe, bencoded, so you can use these functions for that as well. Which means you just have to figure out what to send to get what you want back. NOTE: I did not write these three functions. Like I said, I found them in the source of an open source torrent tracker. The functions are not commented, but the function names together with a print_r on the result of a torrent file you know the info inshould be enough to understand how to use them. I added some example code at the bottom to show how I used them. And they worked. function bdecode($str) { $pos = 0; return bdecode_r($str, $pos); } function bdecode_r($str, &$pos) { $strlen = strlen($str); if (($pos < 0) || ($pos >= $strlen)) { return null; } else if ($str{$pos} == 'i') { $pos++; $numlen = strspn($str, '-0123456789', $pos); $spos = $pos; $pos += $numlen; if (($pos >= $strlen) || ($str{$pos} != 'e')) { return null; } else { $pos++; return intval(substr($str, $spos, $numlen)); } } else if ($str{$pos} == 'd') { $pos++; $ret = array(); while ($pos < $strlen) { if ($str{$pos} == 'e') { $pos++; return $ret; } else { $key = bdecode_r($str, $pos); if ($key == null) { return null; } else { $val = bdecode_r($str, $pos); if ($val == null) { return null; } else if (!is_array($key)) { $ret[$key] = $val; } } } } return null; } else if ($str{$pos} == 'l') { $pos++; $ret = array(); while ($pos < $strlen) { if ($str{$pos} == 'e') { $pos++; return $ret; } else { $val = bdecode_r($str, $pos); if ($val == null) { return null; } else { $ret[] = $val; } } } return null; } else { $numlen = strspn($str, '0123456789', $pos); $spos = $pos; $pos += $numlen; if (($pos >= $strlen) || ($str{$pos} != ':')) { return null; } else { $vallen = intval(substr($str, $spos, $numlen)); $pos++; $val = substr($str, $pos, $vallen); if (strlen($val) != $vallen) { return null; } else { $pos += $vallen; return $val; } } } } function bencode($var) { if (is_int($var)) { return 'i' . $var . 'e'; } else if (is_array($var)) { if (count($var) == 0) { return 'de'; } else { $assoc = false; foreach ($var as $key => $val) { if (!is_int($key)) { $assoc = true; break; } } if ($assoc) { ksort($var, SORT_REGULAR); $ret = 'd'; foreach ($var as $key => $val) { $ret .= bencode($key) . bencode($val); } return $ret . 'e'; } else { $ret = 'l'; foreach ($var as $val) { $ret .= bencode($val); } return $ret . 'e'; } } } else { return strlen($var) . ':' . $var; } } Some example usage: # Read a file $content = file_get_contents("file.torrent"); $content_d = bdecode($content); # Check if bdecode succeeded if(empty($content_d)) exit('Something is wrong with the torrent. BDecode failed.'); # Calculate info_hash $info_hash = sha1(bencode($content_d['info']), true); # Calculate length $length = 0; function add_length($value, $key) { global $length; if($key == 'length') $length += $value; } array_walk_recursive($content_d, 'add_length'); A: This library contains a sublibrary which does the job very well: http://www.binpress.com/app/phptracker/177
{ "language": "en", "url": "https://stackoverflow.com/questions/167206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: RSpec Stories and Specs: When to use what? So I want to start using RSpec stories, but I am not sure where writing controller, model and view specs fit in. For example, you have the story "Logging in" with "User provides wrong password" scenario, don't you end up testing the same stuff than controller/model specs (response.should render..., user.should be_nil, etc.) So my question is: for those who are used to doing bdd (or story dd) with RoR, do you still write model/controller specs? If so, how is the workflow you follow ("first story, then narrow to specific specs")? A: If you are starting with stories now (as opposed to having a lot of legacy stories) you may want to look at Cucumber which is the long term replacement for the RSpec story runner. The easiest way of splitting between specs and stories is to use stories for full-stack testing of business requirements and specs for isolated low-level specifications of the components (views, helpers, controllers and models). 'Full stack' can a range from controller/model/database through client simulation with Webrat to in-browser testing with Watir or Selenium. The ultimate 'outside in' BDD way of doing things is to start with stories based on customer requirements and then add in specs for the components you find you need when implementing the stories. Ideally you will fully cover the individual components with specs and have stories for the most important workflows of your users so you can check at the highest level that your app is delivering the functionality you have been asked for. A: I find stories are useful when they test the behaviour the user actually performs or observes - so rather than testing that the "failed login" template is rendered, test that the response contains "failed to log in". IMHO it's better if stories never refer to models, views or controllers directly, although sometimes it's hard to get the steps working without creating model instances manually. As I see it, view, controller and model specs are only part of the picture. They speak the language of implementation ("controller action X should do Y to model Z"), and test that the individual parts of your app each do the right thing. Stories complete the picture by speaking the language of the user ("when I post a comment I should see the comment I posted") and testing that the parts fit together in a way that meets the customer's acceptance criteria. I find a useful workflow is: * *write a story scenario describing the functionality I need to add. *as soon as possible, write steps for that story, so that you can run it (even if all the steps fail). *write a spec for something needed by that story (model may be a good place to start). *write code to make that spec pass. *write more specs and code until the story passes. That way the story can guide you in what your specs need to test. Edit: this is a good article which touches on the relationship between stories and specs. A: Pat Maddox (RSpec core team) thinks that under some assumptions, you can skip controller specs when using Cucumber stories/features Read about his point of view here A: What about skipping view spec if you've got Cucumber+Capybara on it. I tend to find view spec not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/167210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to obtain the sign of a Number in ActionScript 3.0? I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this: var sign = Math.abs(n) / n; But, there is any other way? Better than this? A: That will give you an error if n is zero. The brute force method: function sign(num) { if(num > 0) { return 1; } else if(num < 0) { return -1; } else { return 0; } } Or, for those with a fondness for the conditional operator: function sign(num) { return (num > 0) ? 1 : ((num < 0) ? -1 : 0); } A: You could also do this: var sign = (n>=0)?1:-1; Using what's known as the ternary operator. A: You'll be in trouble if n == 0... how about this: var sign = n < 0 ? -1 : 1; A: I use this: return (number < 0 && -1) || 1; A: If your number fits in 31 bits then you can use: var sign = 1 + 2*(n >> 31); Would be interesting to know if this is any faster! A: Snippet from the code I inherited: function getSign(number:int):int { var tmp:String = new String(number); if (tmp.indexOf(0) == '-') { return -1; } return 1; } PS: Please don't use this code. It is a joke A: //n = your number //nSign = sign of your number nSign = Math.round(Math.sin(n)*-1); /* Math.sin returns a number between -1 and 1. You must round it to get a non-DEC number. That number will be the opposite of what your number is. Multiply it by -1 */ // or you could just do this Math.round(Math.sin(/n/)*-1)
{ "language": "en", "url": "https://stackoverflow.com/questions/167224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Changing the application pool through a Web Deployment Project Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site? A: You can use a CustomAction to modify IIS during deployment, Here is an article how to do it: Modifying Internet Information Services During Deployment with Custom Actions The example in the article is in VB.Net, and does not show explicitly how to change the Application Pool, but it should be easy to figure it out. A: There is a good article describing custom actions here: ScottGu's Blog The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate: Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String) Try Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir)) IISVdir.Properties.Item("AppPoolId").Item(0) = appPool IISVdir.CommitChanges() Catch ex As Exception Throw ex End Try End Sub Private strServer As String = "localhost" Private strRootSubPath As String = "/W3SVC/1/Root" Private strSchema As String = "IIsWebVirtualDir" Public Overrides Sub Install(ByVal stateSaver As IDictionary) MyBase.Install(stateSaver) Try Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString) Catch ex As Exception Throw ex End Try End Sub ...Where APPPOOL is supplied as an argument in the Custom Action.
{ "language": "en", "url": "https://stackoverflow.com/questions/167232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: rsync ignoring --SUFFIX option rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm I run this command without the --backup-dir option and when it copies the file over, it creates a backup with a current timestamp. When I include the --backup-dir option, it makes the backup into the /tmp/ directory but never attaches my suffix. There is nothing in the manual to suggest that you can't use both these options together. I've played around with the order also and nothing seems to fix it. Does anyone have a solution to this? A: the manual says: --backup make backups (see --suffix & --backup-dir) --backup-dir=DIR make backups into hierarchy based in DIR --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir) so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory). As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory. A: You could also use something like this # Backup mkdir -p /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/ rsync -avz /tmp/`date --date=yesterday +\%Y-\%m-\%d`-`date --date=yesterday +\%A`/ /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/ rsync -avz -e ssh root@web1:/path/to/module.pm /tmp/`date +\%Y-\%m-\%d`-`date +\%A`/
{ "language": "en", "url": "https://stackoverflow.com/questions/167233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the best way to tell if your perl's running on -e? The question is not how to tell in a oneliner. If you're writing the code in a one-liner, you know you are. But how does a module, included by -MMy::Module::Name know that it all started from a oneliner. This is mine. It's non-portable though and relies on UNIX standard commands (although, it can be made portable more or less.) my $process_info = `ps $$ | tail -1`; my $is_oneliner = $process_info =~ m/perl.*?\s+-[^\P{IsLower}e]*e[^\P{IsLower}e]*\s+/m ; And if you have a snazzier regex, feel free to improve upon mine. A couple of people have asked why I would want to do this. brian correctly guessed that I wanted to change export behavior based on whether it's a script, which we can assume has had some amount of design, or whether it's a oneliner where the user is trying to do as much as possible in a single command line. This sounds bad, because there's this credo that exporters should respect other packages--sometimes known as "@EXPORT is EVIL!" But it seems to me that it's a foolish consistency when applied to oneliners. After all perl itself goes out of it's way to violate the structure of its language and give you easy loops if you ask for them on the command line, I simply want to extend that idea for my operational/business domain. I even want to apply source filters (gasp!) if it helps. But this question also suggests that I might want to be a good citizen of Perl as well, because I only to break the community guidelines in certain cases. It is quite awesome to be able to create major business-level actions just by changing the command line in a batch scheduler rather than writing a whole new module. The test cycle is much compressed. A: $0 is set to "-e" if you're running from -e. A: Why are you trying to find out if the module was included from the command line? Is there some situation you have where it matters? Are you doing something odd with imports? Tell us what you're trying to do and I can probably come up with a better way to do it :) Okay, you're asking about exporting. What's the problem you're trying to solve? Which way do you want it? Extra or less default exports from the command line? Do you know that you can specify an import list with -M, including an export tag (so, something from %EXPORT_TAGS)? And if you want an empty export list, you can use -m (lowercase m) instead. See the entry for -M/-m in perlrun. You might also be interested in the "modulino" trick where a module file can be both a module and a script. You can either use it as a regular module, in which case you have access to all of its methods, or call it as a script, in which case it runs. I describe it in my "Scripts as Modules" article for The Perl Journal as well as "How a Script Becomes a Module" on Perlmonks. A: In your import(), the line number returned by caller() will be 0 if your module was loaded via -M. This is true whenever -M is used (with -e or not) but I think it is the only case where the line number is 0. A: If you want different export behavior, the "clean" way to do it would be using a different module name. If you really expect to do a lot of one-liner use, you can even give it a short name. E.g. MMN.pm: package MMN; use My::Module::Name '/./'; use Exporter (); @ISA = 'Exporter'; @EXPORT = @My::Module::Name::EXPORT_OK; 1; Note that Exporter has a little known regex feature; you may just want to do perl -MMy::Module::Name=/./ -e ...
{ "language": "en", "url": "https://stackoverflow.com/questions/167238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I wrap a transaction around Membership.CreateUser? I'm using the asp.net SqlMembershipProvider and LinqToSql in a hobby/learning application. I have some user properties that I'm keeping in LinqtoSql, so my flow is: Membership.CreateUser -> MyClass.AddUserDetails. I'd like to wrap the whole thing in a transaction, so if the myclass bit fails I can roll back the membership bit. Any suggestions on how to do so? A: My real life experience (happened more than once): * *Junior programmer writes a site. *During code review, I catch the missing transaction between user creation and profile creation (typically with a custom SqlProvider) *We wrap everything in a DTC transaction. *Nothing works on junior programmer's computer. *Fix DTC on junior programmer's computer. *Deploy to shared hosting environment. *Nothing works in hosting environment. *Argue for 4 hours with hosting company trying to fix their DTC. *Remove transaction because site has to go online. *Pray. I don't really like membership anymore... A: The providers don't explicitly support transactions, I asked for this feature some time ago: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=102268 I think if you use the TransactionScope class it should work, though you will have the overhead of an MSDTC-coordinated transaction. A: You can set the Transaction property of the DataContext to make it participate in a transaction you already have.
{ "language": "en", "url": "https://stackoverflow.com/questions/167242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Stopping a function from been overridden in Delphi How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)? I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need. A: You're right - it's "final". This snippet shows it. (from one of Marco Cantu's books) type TDeriv1 = class (TBase) procedure A; override; final; end; TDeriv2 = class (TDeriv1) procedure A; override; // error: "cannot override a final method" end; Compiling gives: [Pascal Error] Unit1.pas(11): E2352 Cannot override a final method One thing that surprised me: This feature is supported in Win32 Delphi, not just Delphi for .NET A: The keyword is final as you thought. See http://dn.codegear.com/article/34324 and http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7. type TSomeClass = class protected procedure SomeVirtualMethod; virtual; end; TOtherClass = class(TSomeClass) protected procedure SomeVirtualMethod; override; final; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/167247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I access a private key with the ASPNET user account? I'm having some trouble importing and accessing a private key with the ASPNET user. I know that when one imports a private key (.pfx file) manually, in windows, you get an option to mark the key as exportable. Now, as far as I can tell, this is needed in order to retrieve that private key later on. My problem comes in that I'm importing the private key in code, as the ASPNET user, and there doesn't seem to be a way to mark it as exportable, in the way that the windows certificate import wizard does. To clarify, the import works just fine, but when I access the details on the now-imported certificate, there is no private key data. This is the code I'm using to import the certificate, once I have already opened the .pfx file, with the correct password. public void ImportCertificate(X509Certificate2 cert, StoreName name, StoreLocation loc) { X509Store certStore = new X509Store(name, loc); StorePermission permission = new StorePermission(PermissionState.Unrestricted); permission.Flags = StorePermissionFlags.AddToStore; permission.Assert(); certStore.Open(OpenFlags.ReadWrite); certStore.Add(cert); certStore.Close(); } Am I mucking up the permissions or the way I import this private key? Or am I going about this the wrong way entirely? A: I believe you need to set the X509KeyStorageFlags.Exportable flag when you import the certificate. You don't show that code, but there is an overload of the Import method with this signature: public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags); or this one: public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags); Which will let you set it before you import. Otherwise, everything looks good! Richard
{ "language": "en", "url": "https://stackoverflow.com/questions/167252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Watching a table for change in MySQL? Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that? I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements? A: Here's what I do: I've got some triggers set up for the table (insert, delete, update) and those triggers increment a counter in another table. My DB access code keeps a local counter and compares it to the returned value, ultimately sending a bool back to the caller, answering the question IsDataCurrent(). Our programs that use this DB access code either poll or check it on-request and then make the appropriate calls to keep themselves up to date. I'm sure there are other ways to solve this. It worked for me pretty well, though. A: It is possible to trigger behaviour outside the database, if you have control of the host. A) This question's answer suggests writing to a file using 'select into outfile' with some system process watch that file for changes (e.g. inotify-based approach such as node-inotify or even a Grunt-watch might suffice) B) For the brave: The answer to this question points out that if you can install C/C++ add-ons to your database server, you could use a User Defined Function (UDF) to call sys_exec() and thus trigger external processes, or presumably write the actual process directly in the UDF. http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html#qandaitem-B-5-1-11 (I'm researching this at the moment, for an AWS RDS hosted application so unfortunately neither of these options are right for me.) A: In MySQL there's no best way than to poll (you create a specific table to simplify the polling though), in other databases you can have triggers that have impact outside the database. In MySQL triggers can only do stuff inside the database itself (for instance, populating the helper table). A: Another similar approach would be to add add column Last_Modified TIMESTAMP ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP to each table and preface your select queries to compare the last request date/time with the max(Last_Modified). Databases are typically pull sources and not push so you'll still need to programmatically probe for changes no matter what. A: This is just a small improvement to your method. Write a trigger on the table(s) you are watching to update a Last_Changed table. A: For those who are doing this in go. You can enable binlog and read binlog for new insert/update/delete on any table. There is a go package here that does the trick. And here is a sample implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/167254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How do you make a web application in Clojure? I suppose this is a strange question to the huge majority of programmers that work daily with Java. I don't. I know Java-the-language, because I worked on Java projects, but not Java-the-world. I never made a web app from scratch in Java. If I have to do it with Python, Ruby, I know where to go (Django or Rails), but if I want to make a web application in Clojure, not because I'm forced to live in a Java world, but because I like the language and I want to give it a try, what libraries and frameworks should I use? A: Compojure's what I used to build a tiny blogging application. It's modeled on Sinatra, which is a minimal, light-weight web framework for Ruby. I mostly just used the routing, which is just like Sinatra's. It looks like: (GET "/post/:id/:slug" (some-function-that-returns-html :id :slug)) There's no ORM or templating library, but it does have functions that turn vectors into HTML. A: You can also have look at these frameworks (taken from disclojure/projects): * *Cascade *Conjure There is also one more related question on Stack Overflow: Mature Clojure web frameworks? A: There's also "Noir" (http://www.webnoir.org/), which is a new Clojure web framework (so new the docs aren't there yet). Coming from Django/Rails, I dig the simple, straightforward syntax and it's pretty lean. A: Disclaimer: I am the author. I put together a leiningen template which combines luminusweb and chestnut templates. So you get something that you can build clojure code with and clojurescript code for front and backend. Additionally it provides user management plus some simple CRUD generation and some more small nice to haves: https://github.com/sveri/closp A: I'll throw in my two cents for Duct, also from @weavejester, the maintainer of Compojure and Ring. At it's core, it brings Component and the Ring router under one roof. Reasons why I use Duct: * *Excellent philosophical foundation: it encourages you to build your app as a series of small components, and it strikes a nice balance between holding few opinions while providing sane defaults. *Stable path: I speak for myself, but over the years I've felt that the Clojure community has presented one less-than-credible web framework after another. A couple simply felt too experimental (my experience with Om and client-side Pedestal) for "getting things done" (not that they won't prove superior down the road). On the other hand, I feel like @weavejester has brought the same stability and measured progress to Duct that he did to Compojure and Ring, which have been superbly born out in the community. *It's super lightweight, and out of the way of my components. Major features: * *Organizes routes by "endpoints", small components that can you can think of as mini web servers (or, small cross sections of your HTTP routes). *Out-of-the-box support for the Reloaded Workflow. *Perfect integration with Ring and Compojure. *Development and production configurations (something I've found conspicuously missing elsewhere). *Good documentation with examples. Note: It goes without saying, but for the benefit of web development newcomers, like most Clojurey things Duct requires a solid grasp of Clojure the language. I also recommend reading about Component first. On another personal note, I've been using Duct in several production applications for over a year now and am extremely happy with it. A: Consider the Luminus web framework. I have no affiliation but have heard good things from friends I respect. A: My current go-to web library is now yada. If you are just starting out, the introductory server is Compojure. I see it as the apache of web servers in the Clojure world (in which case yada/aleph would be nginx). You could use Luminus as a template. There are variants of it, like compojure-api. I tried ou Pedestal and was globally satisfied with it. I don't claim to master it, but it has a pleasant syntax, feels very cohesive, and looks like it does have great performance. It is also backed by Cognitect (the Clojure/Datomic company where Rich Hickey works). I found Aleph to present an interesting abstraction, and the built-in backpressure seems interesting. I have yet to play with it, but it's definitely on my list. After playing a bit with various web servers, here is my quick Pro/Cons list : Short answer : have a look at Luminus to get started quickly, maybe move on to something else as your needs evolve (Yada maybe). Compojure * *Pros (1): * *easy, lots of templates/examples (ex. Luminous) *Cons (2): * *Not performant (a thread per request), expect performances slightly better than rails *Not simple, the middleware model has inconvenients Pedestal * *Pros (3): * *interceptor model, pleasant syntax to add interceptors to a subset of routes *performant router *supports json/transit/multipart forms transparently out of the box, without asking anything. Very cool ! *Cons (4): * *no websocket support (yet), returning core.async channels would be nice *a bit slow to reload if putting it in a Stuart Sierra's component (I think you are supposed to use the reload interceptor) *no testing facility for async interceptors *requires buy-in (?) Aleph Pro (3): * *Performant *backpressure *Websocket/SSE support when returning a manifold stream Cons (1): * *Low level, do it yourself style (ie. it just gives you a way to make your handlers do something. No router, no nothing). Not really a cons, just be aware of it. Yada Pro (3): * *built on Aleph *content negociation *swagger integration *bidi is quite ok (though I like pedestal router syntax better) Cons (1): * *documentation (although not as bad as nginx-clojure, quickly improving). HttpKit Pro (2): * *Written in Clojure ! (and Java...) *performance looks good (see the 600K concurrent connections post) Cons (2): * *No CORS support *Bugs ? Also, not a lot of recent commits Nginx-Clojure Note : I haven't played with it, mainly because of the lack of documentation. It looks interesting though, and very performant. Pros (2): * *Nginx (performant, offload ssl, restart workers...) *Could this model allow zero-downtime updates ? That would be so awesome ! Cons (1): * *Documentation (improving). Also, I don't want to program in strings embedded in an nginx config file if that is the only way to do it. *Probably complicates a bit the first deployment (?) Immutant Note : I haven't played with it. Pros : * *integrated (caching, messaging, scheduling, wildfly deploy) Cons : * *no http client Catacumba Note : I haven't played with it, although the documentation looks excellent. I am probably going to try it next. There are example chat projects that look interesting, their heavy use of protocols put me off at first as a novice Clojure dev. Pros (6): * *documentation ! Like all funcool projects, the doc is very pleasant to read. *pedestal-like routing syntax *should be performant (on top of Ratpack) *backpressure *websockets, sse, cors, security, ssl... *unique features to dig : postal Cons (2): * *Not completely sure about how pleasant the ct/routes syntax is, and about ditching the Ring spec (supposedly for the async story, but I thought the pedestal guys fixed that) *Not sure how one would integrate swagger etc. *when I tried it, I was not able to make it work straight away Note : a benchmark of Clojure web servers is available, if raw performance is all that matters. A: you can also try Clojure on Coils, http://github.com/zubairq/coils - disclaimer: I am the author A: Another interesting webserver is Http-kit. It has good performance and is ring compliant, and has support for WebSockets as well. It is made mostly in clojure, and lacks some of the strange things in Jetty/Tomcat. It's easy to tinker with. A: Reframe and om.next probably what you are looking for. A: Compojure is no longer a complete framework for developing web applications. Since the 0.4 release, compojure has been broken off into several projects. Ring provides the foundation by abstracting away the HTTP request and response process. Ring will parse the incoming request and generate a map containing all of the parts of the request such as uri, server-name and request-method. The application will then handle the request and based on the request generate a response. A response is represented as a map containing the following keys: status, headers, and body. So a simple application would look like: (def app [req] (if (= "/home" (:uri req)) {:status 200 :body "<h3>Welcome Home</h3>"} {:status 200 :body "<a href='/home'>Go Home!</a>"})) One other part of Ring is the concept of middle-ware. This is code that sits between the handler and the incoming request and/or the outgoing response. Some built in middle-ware include sessions and stacktrace. The session middle-ware will add a :session key to the request map that contains all of the session info for the user making the request. If the :session key is present in the response map, it will be stored for the next request made by the current user. While the stack trace middle-ware will capture any exceptions that occur while processing the request and generate a stack trace that is sent back as the response if any exceptions do occur. Working directly with Ring can be tedious, so Compojure is built on top of Ring abstracting away the details. The application can now be expressed in terms of routing so you can have something like this: (defroutes my-routes (GET "/" [] "<h1>Hello all!</h1>") (GET "/user/:id" [id] (str "<h1>Hello " id "</h1>"))) Compojure is still working with the request/response maps so you can always access them if needed: (defroutes my-routes (GET "*" {uri :uri} {:staus 200 :body (str "The uri of the current page is: " uri)})) In this case the {uri :uri} part accesses the :uri key in the request map and sets uri to that value. The last component is Hiccup which makes generating the html easier. The various html tags are represented as vectors with the first element representing the tag name and the rest being the body of the tag. "<h2>A header</h2>" becomes [:h2 "A Header"]. The attributes of a tag are in an optional map. "<a href='/login'>Log In Page</a>" becomes [:a {:href "/login"} "Log In Page"]. Here is a small example using a template to generate the html. (defn layout [title & body] (html [:head [:title title]] [:body [:h1.header title] body])) (defn say-hello [name] (layout "Welcome Page" [:h3 (str "Hello " name)])) (defn hiccup-routes (GET "/user/:name" [name] (say-hello name))) Here is a link to a rough draft of some documentation currently being written by the author of compojure that you might find helpful: Compojure Doc A: These days Pedestal is a framework worth a look. It's a server-side framework that builds on top of Ring, but also frees the incoming request from the initial thread by being able to pause and resume that particular request (otherwise a slow request actually block that serverthread). Maybe sort of like a JavaBean. Other cool frameworks are hoplon.io and David Nolen's Om (based on React) A: Webjure, a web programming framework for Clojure. Features: Dispatch servlet calls Clojure functions. Dynamic HTML generation. SQL query interface (through JDBC). This answer is meant as a placeholder for Webjure information. A: By far the best Clojure web framework I have yet encountered is Compojure: http://github.com/weavejester/compojure/tree/master It's small but powerful, and has beautifully elegant syntax. (It uses Jetty under the hood, but it hides the Servlet API from you unless you want it, which won't be often). Go look at the README at that URL, then download a snapshot and start playing. A: Arachne is a newcomer web framework. Quoting the site's description: Arachne is a full, highly modular web development framework for Clojure. It emphasizes ease, simplicity, and a solid, scalable design. It has a kickstarter campaign claiming to offer a "getting started" experience similar to Rails. It is developed by a Cognitect. Here is a good discussion about it with the author of Luminus (yogthos). A: I've been using Liberator successfully in production for a while now. It's a great framework if you want just the bare bones e.g. if you're building a RESTful web service or something similar. It's essentially a wrapper for ring and compojure and provides a decision graph when validating incoming requests. It's also extremely fast compared to other more bulky web frameworks. If you want to start somewhere fast and slowly build out then Liberator is a great choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/167262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "219" }
Q: How to prevent multiple database users from overwriting each other's data? If two users are accessing same database table, how do we prevent users from overwriting each other’s data? A: Look at This discussion for a review of different strategies or techniques for database locking in an application. A: There is no straightforward way to do that. You could use transactions to make sure that updates are resolved correctly (i.e. that you do not get partial updates) but you would probably lose the first set of changes as it will be overwritten by the second. Two options you probably have are: * *implement some locking mechanism on the application level (i.e. when someone start editing a record put some flag somewhere which would prevent another user from doing the same) *implement version control so each time someone writes to the database a new record is created. This way both sets of data will be in the database and you could have a logic in your application to merge them or select the one you like A: Well, that depends. When you're editing a table, it's not like opening a file up in MSWord or something. You are issuing commands that specifically add or alter one row or a group of rows at a time, so unless two people are editing the same row, then changes by both users will be preserved. Tables can also be locked, either implicitly while you are performing an operation (or within a transaction), or explicitly if you know exactly what it is you want to prevent edits to. Most databases provide "row-level locking", which means the entire table does not need to be locked for every operation. It gets a lot more complicated when you start thinking about transactions and MVCC. If you let us know a bit more information about what exactly the situation is you're interested in, we can provide you with some more specific assistance. A: The slickest approach that I've ran across is to use an additional field called last_actv_dtm that is updated every time someone modifies the record. Assuming that your application queries the record first you should have the last_actv_dtm for the record that is being modified. Use this SQL to perform the update. UPDATE tab1 SET col1 = ? , col2 = ? , last_actv_dtm = GETDATE() WHERE pkcol = rec.pkcol AND last_actv_dtm = rec.last_actv_dtm; This will only update the row if it has not been modified since the application selected the record. A: This is a big question with no easy answer. It call comes down to how willing are you to block one user while another user is working on it, and how do you prevent deadlocks and lousy performance while it's happening. Also, are you trying to prevent one user from updating the same row as the other, or just updating a different row in the same table? If user A updates the row, and then user B attempts to update the row, should it fail, update, or silently ignore it? Once you define the problem more, you can decide if need table level locks, row level locks, transactions, and whether you need various levels of transaction isolation. A: Some database servers support a construct like the following: SELECT column FROM table WHERE something = 'whatever' FOR UPDATE; Which locks all the rows returned by the select until either a COMMIT or ROLLBACK are issued. MySQL (InnoDB) and Oracle are two databases that support this.
{ "language": "en", "url": "https://stackoverflow.com/questions/167282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get Https URL content I have a https link that requires user login & password. If I run it in FX like this: https://usernameassword@www.example.com/link/sublink it will return the xml data as expected. However, what i'm trying to do, is to automate this process. I try to use file_get_contents() in PHP. I even tried to use AJAX, but still doesn't work. I tried to get the content (XML) either in Server or in the front-end (ajax), but both don't work. Does anyone know what I need to go in order to get the content? Do I need to obtain the SSL certificate? Solution in any ohter languages will be welcome too. A: You should use curl library, also certificate should be verified if you want to prevent man-in-the-middle attacks. Or just ignore it using curl options. A: cURL or wget with SSL support. cURL, you can run either through the compiled PHP library or call the executable from PHP. Wget, you will have to call the executable. A: Use libcurl via its Java bindings.
{ "language": "en", "url": "https://stackoverflow.com/questions/167294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I export the data in a DataGridView data to an Excel spreadsheet? In my Winforms application, I want to export the data from my DataGridView to a Excel spreadsheet. Is it simply a job of looping and outputting the results comma seperated? A: Is it simply a job of looping and outputing the results comma seperated? Yes. It is a simpler way without any dependencies. If you need more control, you can always automate excel from vb.net or from C#.. A: Outputting results comma separated will give you a .csv not an excel spreadsheet; although excel can read a csv, and once open in excel you could save it document as excel file. To actually write a file in the excel format I believe you have to use an Ole Provider or something like that, but I've never bothered, since the workaround of creating a csv and outside of code making it an excel file is simple enough. A: Slightly hacky, but Excel will also open a html file saved with a .xls extension. This has the advantage of being able to include formatting.
{ "language": "en", "url": "https://stackoverflow.com/questions/167297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: non-DB attr_accessor attribute persistence in Rails I have an application in which attr_accessor is being used to keep temporary data for a model which will be passed to a rake task. Seeing there is not a database field for these attributes and they are not being calculated from database data, will the attr_accessor data persist and be available to the rake task? What happens if I need to restart the server - does the data get lost then if it's not saved to database? Or to pull this off, do I need to either save to a temp file or a database field? A: I assume you are asking whether data that is stored in attributes of ActiveRecord objects stemming from Web requests will be available when accessing them via a Rake task? No. They won't. That data won't even be available to the next web request. That data won't even be there if you load the same record twice. class Thing < ActiveRecord::Base attr_accessor :data end #try this in script/console thing = Thing.find(:first) thing.data = "Something" thing = Thing.find(:first) puts thing.data -> nil A: Of course it'll be lost, where do you think data goes when it dies? To a data h(e)aven from where it can always return? I'd like to know what you need the data for, but the ultimate answer is probably that the data belongs into the db, unless it's large binary data such as images, where you should save it in the filesystem. A: It depends on how you are passing your data to the rake task and why. If your trying to do the work out-of-band with the request, meaning not making the user wait until its complete I recommend taking a look at Ryan's excellent screencast here http://railscasts.com/episodes/128-starling-and-workling to learn about job queues. If its some other exotic reason you must use rake like this you could pass the data as command line parameters. This depends on how much data, and its complexity, you need to pass as it might get out of hand quickly. Using Daniel's example from above: thing = Thing.find(:first) thing.data = "Something" rake myraketask thing_id=#{thing.id} data=#{thing.data}
{ "language": "en", "url": "https://stackoverflow.com/questions/167302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to Pivot data using LINQ? I am wondering if it is possible to use LINQ to pivot data from the following layout: CustID | OrderDate | Qty 1 | 1/1/2008 | 100 2 | 1/2/2008 | 200 1 | 2/2/2008 | 350 2 | 2/28/2008 | 221 1 | 3/12/2008 | 250 2 | 3/15/2008 | 2150 into something like this: CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 | 1 | 100 | 350 | 250 2 | 200 | 221 | 2150 A: The neatest approach for this, I think, is to use a lookup: var query = from c in myList group c by c.CustId into gcs let lookup = gcs.ToLookup(y => y.OrderDate.Month, y => y.Qty) select new { CustId = gcs.Key, Jan = lookup[1].Sum(), Feb = lookup[2].Sum(), Mar = lookup[3].Sum(), }; A: Here is a bit more generic way how to pivot data using LINQ: IEnumerable<CustData> s; var groupedData = s.ToLookup( k => new ValueKey( k.CustID, // 1st dimension String.Format("{0}-{1}", k.OrderDate.Month, k.OrderDate.Year // 2nd dimension ) ) ); var rowKeys = groupedData.Select(g => (int)g.Key.DimKeys[0]).Distinct().OrderBy(k=>k); var columnKeys = groupedData.Select(g => (string)g.Key.DimKeys[1]).Distinct().OrderBy(k=>k); foreach (var row in rowKeys) { Console.Write("CustID {0}: ", row); foreach (var column in columnKeys) { Console.Write("{0:####} ", groupedData[new ValueKey(row,column)].Sum(r=>r.Qty) ); } Console.WriteLine(); } where ValueKey is a special class that represents multidimensional key: public sealed class ValueKey { public readonly object[] DimKeys; public ValueKey(params object[] dimKeys) { DimKeys = dimKeys; } public override int GetHashCode() { if (DimKeys==null) return 0; int hashCode = DimKeys.Length; for (int i = 0; i < DimKeys.Length; i++) { hashCode ^= DimKeys[i].GetHashCode(); } return hashCode; } public override bool Equals(object obj) { if ( obj==null || !(obj is ValueKey)) return false; var x = DimKeys; var y = ((ValueKey)obj).DimKeys; if (ReferenceEquals(x,y)) return true; if (x.Length!=y.Length) return false; for (int i = 0; i < x.Length; i++) { if (!x[i].Equals(y[i])) return false; } return true; } } This approach can be used for grouping by N-dimensions (n>2) and will work fine for rather small datasets. For large datasets (up to 1 mln of records and more) or for cases when pivot configuration cannot be hardcoded I've written special PivotData library (it is free): var pvtData = new PivotData(new []{"CustID","OrderDate"}, new SumAggregatorFactory("Qty")); pvtData.ProcessData(s, (o, f) => { var custData = (TT)o; switch (f) { case "CustID": return custData.CustID; case "OrderDate": return String.Format("{0}-{1}", custData.OrderDate.Month, custData.OrderDate.Year); case "Qty": return custData.Qty; } return null; } ); Console.WriteLine( pvtData[1, "1-2008"].Value ); A: Something like this? List<CustData> myList = GetCustData(); var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty) }); GroupBy in Linq does not work the same as SQL. In SQL, you get the key and aggregates (row/column shape). In Linq, you get the key and any elements as children of the key (hierarchical shape). To pivot, you must project the hierarchy back into a row/column form of your choosing. A: I answered similar question using linq extension method: // order s(ource) by OrderDate to have proper column ordering var r = s.Pivot3(e => e.custID, e => e.OrderDate.ToString("MMM-yyyy") , lst => lst.Sum(e => e.Qty)); // order r(esult) by CustID (+) generic implementation (-) definitely slower than Amy B's Can anyone improve my implementation (i.e. the method does the ordering of columns & rows)? A: // LINQPad Code for Amy B answer void Main() { List<CustData> myList = GetCustData(); var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty), //April = g.Where(c => c.OrderDate.Month == 4).Sum(c => c.Qty), //May = g.Where(c => c.OrderDate.Month == 5).Sum(c => c.Qty), //June = g.Where(c => c.OrderDate.Month == 6).Sum(c => c.Qty), //July = g.Where(c => c.OrderDate.Month == 7).Sum(c => c.Qty), //August = g.Where(c => c.OrderDate.Month == 8).Sum(c => c.Qty), //September = g.Where(c => c.OrderDate.Month == 9).Sum(c => c.Qty), //October = g.Where(c => c.OrderDate.Month == 10).Sum(c => c.Qty), //November = g.Where(c => c.OrderDate.Month == 11).Sum(c => c.Qty), //December = g.Where(c => c.OrderDate.Month == 12).Sum(c => c.Qty) }); query.Dump(); } /// <summary> /// -------------------------------- /// CustID | OrderDate | Qty /// -------------------------------- /// 1 | 1 / 1 / 2008 | 100 /// 2 | 1 / 2 / 2008 | 200 /// 1 | 2 / 2 / 2008 | 350 /// 2 | 2 / 28 / 2008 | 221 /// 1 | 3 / 12 / 2008 | 250 /// 2 | 3 / 15 / 2008 | 2150 /// </ summary> public List<CustData> GetCustData() { List<CustData> custData = new List<CustData> { new CustData { CustId = 1, OrderDate = new DateTime(2008, 1, 1), Qty = 100 }, new CustData { CustId = 2, OrderDate = new DateTime(2008, 1, 2), Qty = 200 }, new CustData { CustId = 1, OrderDate = new DateTime(2008, 2, 2), Qty = 350 }, new CustData { CustId = 2, OrderDate = new DateTime(2008, 2, 28), Qty = 221 }, new CustData { CustId = 1, OrderDate = new DateTime(2008, 3, 12), Qty = 250 }, new CustData { CustId = 2, OrderDate = new DateTime(2008, 3, 15), Qty = 2150 }, }; return custData; } public class CustData { public int CustId; public DateTime OrderDate; public uint Qty; } A: This is most efficient way: Check the following approach. Instead of iterating through the customers group each time for each month. var query = myList .GroupBy(c => c.CustId) .Select(g => { var results = new CustomerStatistics(); foreach (var customer in g) { switch (customer.OrderDate.Month) { case 1: results.Jan += customer.Qty; break; case 2: results.Feb += customer.Qty; break; case 3: results.March += customer.Qty; break; default: break; } } return new { CustId = g.Key, results.Jan, results.Feb, results.March }; }); Or this one : var query = myList .GroupBy(c => c.CustId) .Select(g => { var results = g.Aggregate(new CustomerStatistics(), (result, customer) => result.Accumulate(customer), customerStatistics => customerStatistics.Compute()); return new { CustId = g.Key, results.Jan, results.Feb, results.March }; }); Complete solution: using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp { internal class Program { private static void Main(string[] args) { IEnumerable<CustData> myList = GetCustData().Take(100); var query = myList .GroupBy(c => c.CustId) .Select(g => { CustomerStatistics results = g.Aggregate(new CustomerStatistics(), (result, customer) => result.Accumulate(customer), customerStatistics => customerStatistics.Compute()); return new { CustId = g.Key, results.Jan, results.Feb, results.March }; }); Console.ReadKey(); } private static IEnumerable<CustData> GetCustData() { Random random = new Random(); int custId = 0; while (true) { custId++; yield return new CustData { CustId = custId, OrderDate = new DateTime(2018, random.Next(1, 4), 1), Qty = random.Next(1, 50) }; } } } public class CustData { public int CustId { get; set; } public DateTime OrderDate { get; set; } public int Qty { get; set; } } public class CustomerStatistics { public int Jan { get; set; } public int Feb { get; set; } public int March { get; set; } internal CustomerStatistics Accumulate(CustData customer) { switch (customer.OrderDate.Month) { case 1: Jan += customer.Qty; break; case 2: Feb += customer.Qty; break; case 3: March += customer.Qty; break; default: break; } return this; } public CustomerStatistics Compute() { return this; } } } A: Group your data on month, and then project it into a new datatable with columns for each month. The new table would be your pivot table.
{ "language": "en", "url": "https://stackoverflow.com/questions/167304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "186" }
Q: validating and adjusting a treeview label I've got a treeview control, and have caught its after-label-edit event. I want to be able to validate the user's input and adjust it - if for instance it's too long - but I only seem able to cancel the new value, not change it. Any ideas? I don't want to have to open a new form, the user might be renaming a range of these and it shouldn't be too cumbersome. Cheers. A: Can't you get the node being edited from the EventArgs, and manually set its text? If this causes the AfterLabelEdit to be fired again, then you should add a flag to exit it if it comes from a manual edit.
{ "language": "en", "url": "https://stackoverflow.com/questions/167306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get the last possible time of a particular day I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field? A: Add -1 milliseconds to the start of the next day (DateAdd even supports nanoseconds, if you want to get real fine). But most likely you just want to use this value in a comparison, and in that case it's even simpler. Rather than something like this: AND @CompareDate <= [LastTimeforThatday] or this: @compareDate BETWEEN [StartDate] AND [LastTimeforThatday] Do it like this: AND @CompareDate < [BeginningOfNextDay] or this: AND (@CompareDate >= [StartDate] AND @CompareDate < [BeginningOfNextDay]) A: Why back into it? SELECT DATEADD(ms, 86399997, *yourDate*) A: The answer is SELECT DATEADD(ms, -3, '2008-01-24'), the explanation is below. From Marc's blog: But wait, Marc... you said you like to use BETWEEN, but that query doesn't have one... that's because BETWEEN is inclusive, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is: SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0)) So to do the orders due this month as a BETWEEN query, you can use this: SELECT [ID] FROM [dbo].[Orders] WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0) AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0)) Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't. A: SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate()))) I thought you had c# at first.. I will leave this here in case anyone else stumbles across this. DateTime now = DateTime.Now; DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1); You can replace the 'now' variable with whatever day you are trying to figure out A: I was able to use: select {fn curdate()} + ' 23:59:59.000' or select DATEADD(ss,-1,DATEADD(DAY,1,CAST({fn curdate()} as DATETIME))) to get the end of a day
{ "language": "en", "url": "https://stackoverflow.com/questions/167316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How to open a form in a thread and force it to stay open I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here. In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it. using System; using System.Windows.Forms; using System.Threading; namespace UIThreadMarshalling { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var tt = new ThreadTest(); ThreadStart ts = new ThreadStart(tt.StartUiThread); Thread t = new Thread(ts); t.Name = "UI Thread"; t.Start(); Thread.Sleep(new TimeSpan(0, 0, 10)); } } public class ThreadTest { Form _form; public ThreadTest() { } public void StartUiThread() { _form = new Form1(); _form.Show(); } } } A: private void button1_Click(object sender, EventArgs e) { var t = new Thread(RunNewForm); t.Start(); } public static void RunNewForm() { Application.Run(new Form2()); } A: I think your problem is with this thought: "open a form on a separate thread named 'UI thread'" The way windows works is like this (plz note Vista may change some of these realities): There is one important thread called the "Main Thread" or the "UI Thread". This thread is the one that processes windows messages, like "hey the mouse clicked on this pixel." These messages go into a queue, and the main thread processes them when it isn't busy doing something else. So if you make a function call foo() on the main thread, if it takes a long time, no windows messages are processed during that time, and so no user interaction can occur. The main thread also paints the UI on the screen, so long-running foo() will also stop your app from painting. All other threads besides this holy and special main thread are grunt worker threads. These worker threads can do things, but they can never interact directly with the user interface. This reality causes two problems: * *GETTING OFF THE MAIN THREAD: Since you don't want long-running foo() to halt all user interaction, you need to ship that work off to a worker thread. *GETTING BACK TO THE MAIN THREAD: When long-running foo() completes, you probably want to notify the user by doing something in the UI, but you cannot do that in a worker thread, so you need to "get back" to the main thread. So I believe your problem in the above program is very general: Your very goal is incorrect, because it is not supposed to be possible to call _form.Show() in any thread but the holy main thread. A: You cannot open a GUI form in any thread, because it will be missing a message pump. You have to explicitly start a message pump in that thread by invoking Application.Run() in a thread method. Another option is to call a DoEvents() in a loop, if you need to do something else, because after Application.Run() that thread will wait a user to close a form in that point of execution. A: On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open. Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete. Example: public void StartUiThread() { using (Form1 _form = new Form1()) { Application.Run(_form); } } A: I think just calling ShowDialog instead of Show will help. The problem seems to be that the thread finishes just after calling Show, after that the Form get's garbage collected. ShowDialog will halt the thread but still run form-events on it so the thread will keep running until the form is closed. Normally i would do it the other way around. Run the form on the starting thread and start background threads when you want to start long-running background tasks. I also read your other question but couldn't figure out what you're trying to do. MVP-architecture doesn't require you to run your business logic on different threads. Multi threading is hard to do right so I'd only use multiple threads if I really needed them. A: Instead of calling show() on the form which will execute on the form and then just close at the end of the thread execution within function StartUiThread(), you can lock the thread until the form is stopped within the method as you are simply locking the other thread. Ex: public void StartUiThread() { _form = new Form1(); _form.ShowDialog(); //Change Show() to ShowDialog() to wait in thread } This will cause the new thread to wait until the dialog is closed. I do not know if this will solve your problems, but it solved mine.
{ "language": "en", "url": "https://stackoverflow.com/questions/167323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: (Vocal code) Need some help finding text-to-speech addon I am looking for an addon that can say characters vocally. It is for non-commercial use, and it would be nice if it can vocalize more languages, like asian, english etc... I have googled it, but can't seem to find anything for free use. Update: This is for web use A: You could try http://espeak.sourceforge.net/ and make an mp3 of the word, then stream it to a flash application (you could use darwin for the streaming). A: You can convert the text to speech in Java using freetts1.2 API. It is quite simple to use. This link could be useful for you which has an example program. http://learnsharelive.blogspot.com/2011/01/convert-text-to-speech-java-freetts12.html A: What yo uare searching for ist Sphinx4. Some free speech models for other languages can be found here. A: A similar question has been asked regarding Java Text-to-Speech engines. Take a look at the question Java: Text to Speech engines overviewand see if any of the responses are helpful. A: It's unlikely that you'll find an Actionscript 2.0 or 3.0 text to speech codebase, as sound synthesis is only just being introduced in the upcoming Flash Player version 10. Java however has many, try this, this, or even that!
{ "language": "en", "url": "https://stackoverflow.com/questions/167325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Class data responsibilities I have a 'Purchase Order' class. It contains information about a single purchase order. I have a DAO class for database methods. Where should the responsibility reside for the methods that will load and update the purchase order? Should the PurchaseOrder class have '.update', 'insert', 'delete', and '.load' methods that use the DAO class directly, or should the PurchaseOrder class be ignorant of the DAO methods and have a POController class that manages these interactions? The user will only be working on a single PurchaseOrder at a time. Thanks! A: The Purchase Order should be ignorant of the details of its persistence. This is the point of having some sort of data access layer, it handles the management of the object and the object itself can concentrate on just being a purchase order. This also makes the system easier to test, as you can create mock Purchase orders and test the logic of how the system handles them without getting entangled in persistence issues. A: I'd keep it simple by making PurchaseOrder an interface and putting all the DAO code in the implementation, then use a factory. A: It depends on how long you think your application will remain in existence. My company's metal cutting application has been continuously developed since 1985 and has been port through multiple changes in computer architectures. In our case we nearly always shove things behind a interface (or controller class using your terms) because we don't what going to be the state of things 5, 10, 15 years down the line. By using a controller class we can change the underlying APIs without tampering with the levels of business logic and UI tweaks above. These levels represent years of work so it is important to preserve their behavior. Remember the majority of the lifetime your project is going be in maintenance. Anything you do now to make it easier to change the design later will pay off in enormous time savings down the road. A: The PurchaseOrder class should be ignorant of the DAO. The purchaseOrder class should represent the data itself and nothing more. Use a controller or service manager or whatever you want to call it to persist/load PurchaseOrder records using the DAO. This gives you the most flexibility in your design. You have one place for your data model, one place for your business logic (the controller) on how PurchaseOrders are stored/retrieved and one place where its actually persisted. A: Let me walk you through my reasoning: Class methods Basic principle: Persistance is a class behaviour and should be a class method You need separation of concerns, so you put the database nitty-gritty in a DAO class, and use that from the class to implement the methods. First problem: if you need to support different sets of DAOs you need to create them through a Factory. Second problem: not all persistence behaviours are specifically related to an instance of the class. For example List and Search methods: they return Class lists, not classes, and do not depend on an instance. So they are fundamentally static methods. Third problem: you want to support inheritance on this class. As such, the persistence details differ from parent to child. If you have static methods, it's going to be a problem. So you move on to the Controller Basic principle: Persistence methods do not belong to a single class, they are larger and thus they should be separated Separation of concerns is needed again, so you need DAOs. This is a Utility class so methods are all basically static. First problem: you need a Factory to create the DAOs if you want to support more than one persistence method. Second problem: you want to support a hierarchy of Classes so you can't use a static class. You need to generate the Controllers through a Factory. Third problem: you are offering an overcomplicated API to your developers. Example of client code: PurchaseOrder po; PurchaseOrderController poc; poc = PurchaseOrderControllerFactory.Instance.Create(); po = poc.GetPurchaseOrder(42); // do stuff poc.SavePurchaseOrder(po); then I would start from scratch. Start from behaviours Basic principle: Persistence is not a behaviour. Behaviours are larger than persistence. In your system there will be a Purchase Order subsystem. Your user will be able to interact with it only at high level (use case level). So,the methods will implement Purchase Order use cases. These methods will use DAOs, through a factory if needed, to access the database and do whatever they need to do. In short, your PurchaseOrder is basically a DTO, a quick way of passing data around. It should not have behaviours. Example of client code: // It could be a factory if needed. PurchaseOrderSystem pos = new PurchaseOrderSystem(); List<PurchaseOrder> transacted; transacted = pos.TransactPurchaseOrders(john, 23); // Show transacted purchase orders or whatever... A: I would definitely separate the "business logic" (PurchaseOrder) from the database interaction/access. Should you move to a different vendor, etc, you'll have an easier time making changes to the access without potentially interfering with the business implementation, plus you'll have an easier time avoiding adding behavior to the database access layer. A: Personally, I'd create an object that manages the interactions. I can't make a strong case for NOT putting this logic in the PurchaseOrder class itself, but creating this controller object would lead towards more loosely coupled objects. A: The key thing to think about here is what you might want to do in the future. Maybe you want to replace your database with another? That's why you should definitely separate your code for interaction with the database from the class that represents the PO. That's basic separation of responsibility, and I hope you've done that already. Now the question is: do you want a third class (controller) to manage the interaction between the PO and DAO classes? I think that depends on how general you can make the interface to the DAO class. If the DAO interface is general enough that you could write a plug-in replacement for it using a different storage mechanism but without changing the interface, then I would let the PO class interact with it. If not then I would write a controller class. The other thing to think about is the rest of the structure. Where is the save/load initiated from? If you are going to do a lot of manipulations of the PO (save,load, print, send-to-customer) then it probably makes sense to have a controller that does all of those things rather than integrate the functionality into the PO class. It gives you the advantage that you can add PO operations without having to modify the PO class.
{ "language": "en", "url": "https://stackoverflow.com/questions/167330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# Lambda expressions: Why should I use them? I have quickly read over the Microsoft Lambda Expression documentation. This kind of example has helped me to understand better, though: delegate int del(int i); del myDelegate = x => x * x; int j = myDelegate(5); //j = 25 Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method? A: I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created. private ComboBox combo; private Label label; public CreateControls() { combo = new ComboBox(); label = new Label(); //some initializing code combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged); } void combo_SelectedIndexChanged(object sender, EventArgs e) { label.Text = combo.SelectedValue; } thanks to lambda expressions you can use it like this: public CreateControls() { ComboBox combo = new ComboBox(); Label label = new Label(); //some initializing code combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;}; } Much easier. A: You can also find the use of lambda expressions in writing generic codes to act on your methods. For example: Generic function to calculate the time taken by a method call. (i.e. Action in here) public static long Measure(Action action) { Stopwatch sw = new Stopwatch(); sw.Start(); action(); sw.Stop(); return sw.ElapsedMilliseconds; } And you can call the above method using the lambda expression as follows, var timeTaken = Measure(() => yourMethod(param)); Expression allows you to get return value from your method and out param as well var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam)); A: Lambda expression is a concise way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context. It’s is very convenient because that saves us a lot of typing! A: A lambda expression is like an anonymous method written in place of a delegate instance. delegate int MyDelagate (int i); MyDelagate delSquareFunction = x => x * x; Consider the lambda expression x => x * x; The input parameter value is x (on the left side of =>) The function logic is x * x (on the right side of =>) A lambda expression's code can be a statement block instead of an expression. x => {return x * x;}; Example Note: Func is a predefined generic delegate. Console.WriteLine(MyMethod(x => "Hi " + x)); public static string MyMethod(Func<string, string> strategy) { return strategy("Lijo").ToString(); } References * *How can a delegate & interface be used interchangeably? A: Lambda's cleaned up C# 2.0's anonymous delegate syntax...for example Strings.Find(s => s == "hello"); Was done in C# 2.0 like this: Strings.Find(delegate(String s) { return s == "hello"; }); Functionally, they do the exact same thing, its just a much more concise syntax. A: A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class. A: It's a way of taking small operation and putting it very close to where it is used (not unlike declaring a variable close to its use point). This is supposed to make your code more readable. By anonymizing the expression, you're also making it a lot harder for someone to break your client code if it the function is used somewhere else and modified to "enhance" it. Similarly, why do you need to use foreach? You can do everything in foreach with a plain for loop or just using IEnumerable directly. Answer: you don't need it but it makes your code more readable. A: Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL. The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are: // anonymous delegate var evens = Enumerable .Range(1, 100) .Where(delegate(int x) { return (x % 2) == 0; }) .ToList(); // lambda expression var evens = Enumerable .Range(1, 100) .Where(x => (x % 2) == 0) .ToList(); Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects. Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate: void Example(Predicate<int> aDelegate); called like: Example(x => x > 5); becomes: void Example(Expression<Predicate<int>> expressionTree); The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side. A: This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this: List<string> strings = new List<string>(); strings.Add("Good"); strings.Add("Morning") strings.Add("Starshine"); strings.Add("The"); strings.Add("Earth"); strings.Add("says"); strings.Add("hello"); strings.Find(s => s == "hello"); This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this: List<string> strings = new List<string>(); strings.Add("Good"); strings.Add("Morning") strings.Add("Starshine"); strings.Add("The"); strings.Add("Earth"); strings.Add("says"); strings.Add("hello"); private static bool FindHello(String s) { return s == "hello"; } strings.Find(FindHello); EDIT: In C# 2.0, this could be done using the anonymous delegate syntax: strings.Find(delegate(String s) { return s == "hello"; }); Lambda's significantly cleaned up that syntax. A: Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example: using System; using System.Linq; using System.Linq.Expressions; namespace ExpressionTreeThingy { class Program { static void Main(string[] args) { Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime Console.WriteLine(del(5)); //we are just invoking a delegate at this point Console.ReadKey(); } } } This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees. A: Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method. Consider this example: List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" }; string person = people.Find(person => person.Contains("Joe")); versus public string FindPerson(string nameContains, List<string> persons) { foreach (string person in persons) if (person.Contains(nameContains)) return person; return null; } These are functionally equivalent. A: It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on. And it's not really an innovation. LISP has had lambda functions for about 30 years or more. A: The innovation is in the type safety and transparency. Although you don't declare types of lambda expressions, they are inferred, and can be used by code search, static analysis, refactoring tools, and runtime reflection. For example, before you might have used SQL and could get an SQL injection attack, because a hacker passed a string where a number was normally expected. Now you would use a LINQ lambda expression, which is protected from that. Building a LINQ API on pure delegates is not possible, because it requires combining expression trees together before evaluating them. In 2016 most of the popular languages have lambda expression support, and C# was one of the pioneers in this evolution among the mainstream imperative languages. A: The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework. Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object. A: Lambda expression makes tasks much simpler, for example var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var oddNumbers = numbers.Where(x => x % 2 != 0); var sumOfEven = numbers.Where(x => x % 2 == 0).Sum(); In the above code, because we are using lambda, we are getting odd number and sum of even numbers in single line of code. Without lambda, we will have to use if/else or for loop. So it is good to use lambda to simplify code in C#. Some articles on it: https://qawithexperts.com/article/c-sharp/lambda-expression-in-c-with-examples/470 https://exceptionnotfound.net/csharp-in-simple-terms-18-expressions-lambdas-and-delegates http://dontcodetired.com/blog/post/Whats-New-in-C-10-Easier-Lambda-Expressions A: In C# we cannot pass functions as parameters like we do in JavaScript. The workaround is using delegates. When we want to parameterize the behavior instead of a value, we use delegates. Lambdas are practical syntax for writing delegates which makes it very easy to pass around behavior as functions. A: This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.
{ "language": "en", "url": "https://stackoverflow.com/questions/167343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "317" }
Q: How do I see what files were changed between 2 revisions? I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this? Can I do this in tortoise as well? A: Right click the directory containing your repo. Choose SVN Show Log. Control+Click the two revisions. Right click on one and choose Compare Revisions. A: svn diff -r "start_revision_number":"end_revision_number" "url_of_svn_repo" --summarize then just pipe it to grep ^A D or M A: svn log -v -rX:Y . The -v for "verbose" switch will give you detailed output on which files were affected on that revision. Note that "." assumes you are currently in a working copy directory, but you can also use a URL such as "http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c". This information can be found by typing "svn help log", or by reading the SVN Book, available free online. Don't forget to Read The Friendly Manual! A: If you want a concise list of files without the times and commit messages, you can do it like this: svn diff -r X:Y --summarize A: Like this. A: If you are new to source control and SVN you may want to pick up Pragmatic Version Control with SVN. It explains many of the concepts and commands. A: This worked for me on windows * *Go to your folder where you have the repository, *right click and select SVN Show log, *In the dialog box there is a "Show Range" button, click it and fill Start Revision = {your revision} and End Revision = {your revision} *Select the Start and Date range as per your need Note: {your revision}=provide the revision number for atleast one of your file changes. All files associated with that revision should get listed.
{ "language": "en", "url": "https://stackoverflow.com/questions/167371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Any clever way to launch a makefile in Visual Studio only if build succeeded? We have a makefile that is built last in our build process using Visual Studio to launch our unit tests. Unfortunately if the build fails the makefile is still processed and we have extra (annoying) errors. Any way to prevent that? Example Project A : build dummy.exe Project B (makefile) : build command is : run dummy.exe /unittest We want Project B to skip its build command when Project A has build errors. Thanks! A: Set Project B (your makefile project) to be dependant on Project A. This way Project B will always try to build Project A before it builds. A: Go to Project Properties. I assume you already have something in the "Post-Build event command line" box? There is a "Run the post-build event" combobox, set it to "On successful build". Is that what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/167388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Lisp Web Frameworks? What are the popular (ok, popular is relative) web frameworks for the various flavours of LISP? A: For Clojure you can try Compojure. A: Common Lisp A lot of the usual suspects (Hunchentoot, UCW, LoL) have already been mentioned. Franz makes available for Allegro Common Lisp (and ported to other Lisps): * *at a lower level (handling HTTP requests yourself), AllegroServe. *at a higher level (more of a "framework"), WebActions. Both are open source. I tend to use AllegroServe, factoring out utilities as I need them, but some people really like WebActions. I used Araneida for quite some time, and I prefer its style to AllegroServe, but it hasn't been maintained since 2006. A: I've searched quite extensively for a good web framework for Lisp, and I found them all to be somewhat inaccessible. The Architecture of UCW didn't seem very natural to me (I can't remember why; it's been a while since I looked into it), and KPAX isn't maintained anymore (I think). Symbolic web looks very interesting, and I think Weblocks is the most interesting, but Weblocks isn't very well documented and can be pretty intimidating to the newcomer. SymbolicWeb was immature last time I looked, but it may have grow up some since then. The features page looks pretty good today. There are different approaches you could take. If you want a purely lisp approach, then you could: * *If you can read code proficiently and understand continuations, you might try Weblocks with a Hunchentoot backend (Weblocks has a dependency on Hunchentoot that hasn't been abstracted yet). There is supposed to be a real user manual out in a month or two, but as with any OSS project, such commitments are sketchy. *Similarly, you might try SymbolicWeb. [update: nevermind, the project is no more] *roll your own. Seriously - there's cl-who to help with HTML generation, there are javascript and json libraries available, usockets, elephant, cl-sql, hunchentoot, aserve, and lots of utility libraries that you could bake together. If you are ok with a hybrid approach, this is something I'm experimenting with at the moment: I've written a Lisp JSON-RPC backend for Qooxdoo, so I can serve up pure javascript frontends through a superfast http server like Cherokee and let Cherokee farm out connections to as many backend json-rpc servers running in Lisp as I want. Very, very scalable. I'm far from figuring out the kinks and challenges, but it was pretty straight-forward to get working. the json library makes it stupid simple to get the backend working - Qooxdoo itself is actually harder, I think (but I'm not a JS developer, really). I'm also going to be checking out WebActions from allegro, because there's a certain allure to the availability of paid support - not to mention that Allegro may be the best CL implementation available (His Kennyness uses it :-)). A: UnCommonWeb (UCW) is often mentioned http://www.common-lisp.net/project/ucw/ -- it's not REST as is in en-vogue at the moment, more like Smalltalk's SeaSide (but then again, SeaSide is quite en-vogue). A: LeftParen A: Lisp-on-lines is a web application framework built on top of CLSQL and UCW and provides an application development model similar in many ways to Ruby on Rails. Right now it can be found at http://versions.tech.coop/lisp-on-lines/. http://www.cliki.net/lisp-on-lines http://kevin.casa.cavewallarts.com/LISP/LOL/lol.html A: For Clojure you can try Webjure. A: I just discovered a web framework called Clack for common lisp and found it quite easy to get started. See http://clacklisp.org/ Quote from it's web site "Clack is a web application environment for Common Lisp inspired by Python's WSGI and Ruby's Rack." and caveman is a micro web framework based on Clack. A: Another cool (yet far from "popular") thing to look at is SymbolicWeb -- http://groups.google.com/group/symbolicweb A: Re: SymbolicWeb (and its exaggerated demise) SymbolicWeb project page at Gitorious and SymbolicWeb article at Wikipedia. The Google Groups page is definitely dead (and unarchived?,) but the Gitorious tree shows checkins as recently as 29 April 2010. The project page also refers to "some running examples" being "occasionally available" at nostdal.org (which is unreachable as I write this, reinforcing the "occasionally" qualifier :-) .) (Note: I'm not a SymbolicWeb user. I just tracked down the SymbolicWeb links while reading this thread.) A: Restas is another web framework that has seen recent updates: http://restas.lisper.ru/en/ Its overview RESTAS is a Common Lisp web application framework. Its key features are: RESTAS was developed to simplify development of web applications following the REST architectural style. RESTAS is based on the Hunchentoot HTTP server. Web application development with RESTAS is in many ways simpler than with Hunchentoot, but some knowledge of Hunchentoot is required, at least about working with hunchentoot:*request* and hunchentoot:*reply*. Request dispatch is based on a route system. The route system is the key concept of RESTAS and provides unique features not found in other web frameworks. The other key RESTAS concept is its module system, which provides a simple and flexible mechanism for modularized code reuse. Interactive development support. Any RESTAS code (such as the definition of a route, a module or a submodule) can be recompiled at any time when you work in SLIME and any changes you made can be immediately seen in the browser. No web server restart or other complicated actions are needed. SLIME integration. The inner structure of a web application can be investigated with the standard "SLIME Inspector." For example, there is a "site map" and a simple code navigation with this map. Easy to use, pure Lisp web application daemonization facility based on RESTAS and SBCL in Linux without the use of Screen or detachtty. RESTAS is not an MVC framework, although it is not incompatible with the concept. From the MVC point of view, RESTAS provides the controller level. Nevertheless, RESTAS provides an effective and flexible way for separation of logic and representation, because it does not put any constraints on the structure of applications. Separation of model and controller can be effectively performed with Common Lisp facilities, and, hence, doesn't need any special support from the framework. RESTAS does not come with a templating library. cl-closure-template and HTML-TEMPLATE are two good templating libraries that can be used with RESTAS. A: PLT Scheme features a built-in, continuation-based web server. Update: PLT Scheme is now called Racket. A: Hunchentoot is also quite widespread A: What is Weblocks? Weblocks is a continuations-based web framework written in Common Lisp. http://common-lisp.net/project/cl-weblocks/ A: Most (perhaps all) of the well-known Common Lisp web frameworks have already been mentioned, so I'll just add some comments. Hunchentoot is not a "web framework" in the sense that most people mean. It's an HTTP server (an extremely good one). Drew Crampsie's "Lisp on Lines" looks extremely promising, but I'm not sure how far along it is. I've been waiting to hear an announcement. Marco Baringer's UnCommon Web runs on many of the prominent CL implementions: Allegro CL, CMUCL, Clozure CL (formerly known as OpenMCL), GNU clisp, and SBCL. The only major one missing is LispWorks; I don't know if that means it hasn't been tested to work, or is known not to work, or what; but if it runs on all those other dialects, it's probably easy to make it run on any other. A: This question is a bit old but I thought I'd share my recent discovery: the Hop language which is based on Scheme and is quite complete. HOP is a multi-tier programming language for the Web 2.0 and the so-called diffuse Web. It is designed for programming interactive web applications in many fields such as multimedia (web galleries, music players, ...), ubiquitous and house automation (SmartPhones, personal appliance), mashups, office (web agendas, mail clients, ...), etc. HOP features: * *an extensive set of widgets for programming fancy and portable Web GUIs, *full compatibility with traditional Web technologies (JavaScript, HTML, CSS), *HTML5 support, a versatile Web server supporting HTTP/1.0 and HTTP/1.1, *a native multimedia support for enabling ubiquitous Web multimedia applications, *fast WebDAV level 1 support, *an optimizing native code compiler for server code, *an on-the-fly JavaScript compiler for client code, *an extensive set of libraries for the mail, calendars, databases, Telephony, ...
{ "language": "en", "url": "https://stackoverflow.com/questions/167397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: Eclipse for IntelliJ Idea Users I have a coworker who is looking to switch from InteilliJ Idea to Eclipse, and is concerned about not knowing the Eclipse set of commands. I was wondering - would anyone have a link to keyboard mappings that can set Eclipse commands to at least sort of match Idea? Have you made this switch? Any "gotchas", tips, or info we should be aware of? Thanks! A: I went through the experience myself - and result was a series of articles on my blog: * *http://virgo47.wordpress.com/2011/01/30/eclipse-vs-intellij-idea/ *http://virgo47.wordpress.com/2011/02/22/from-intellij-idea-to-eclipse-2/ *http://virgo47.wordpress.com/2011/03/24/from-intellij-idea-to-eclipse-3/ *http://virgo47.wordpress.com/2011/02/28/why-to-synchronize-with-svn-in-eclipse/ *http://virgo47.wordpress.com/2011/04/10/from-intellij-idea-to-eclipse-4/ *http://virgo47.wordpress.com/2011/06/28/from-intellij-idea-to-eclipse-5/ They are all biased towards Idea (obviously) but full of relevant Idea-Eclipse comparisons, keyboard shortcuts, little stories and observations. In generall, they are both very good IDEs, but if IDEA is 100%, Eclipse is 90%, maybe even 95% - with biggest these differences: * *different mindset is needed, Projects, Modules, Workspace may mean different things or are not used at all in one or the other IDE, you have/need Perspectives in Eclipse, not in IDEA, etc... *quality of default Maven/SVN support is better in IDEA (it is also built-in), much smoother and less problems + 3way diff in IDEA is just great, generally Eclipse guys are so scared of merging - and now I understand why *IDEA is far more polished, less graphics glitches and much better default colours for highlighting, etc. *free version of IDEA does NOT have so many things as you can have with Eclipse with all possible free plugins - Eclipse plugin ecosystem is just so big! *IDEA is just way smarter in margin cases when it comes to completion, refactorings, and these other little things where IDEA was the top of the class the whole time since 2000 I was lucky I didn't have to convert in the end because we use Maven projects that work just fine in both IDEs. However I still use Eclipse for other projects (xtext). A: Get the plugin from here. It seems easier to install than the one in Bartosz' answer, plus no 404s... For the lazy: direct link to plugin Drop the plugin jar in eclipse/plugins folder and restart eclipse. Now in preferences dialog under General > Keys you can find "Intellij Idea" key scheme. A: If he definitely want to do this: http://www.jroller.com/ervines/resource/eclipse-intellij-key-bindings.java A: In answer to Bartosz, flash builder is a good reason, until jetbrains comes out with a visual mxml editor. the direct link posted above is outdated, releases are here: http://code.google.com/p/ideakeyscheme/updates/list Update: Found this one too: http://www.bharathganesh.com/idea-prefs.php , although it's pretty light on the description. A: I could list a bunch of tips, gotchas, etc. because I've made the switch several times. I've tried to make the switch to Eclipse several times but couldn't do it and went back to IntelliJ. First tip: Intellj "project" -> Eclipse "workspace" Intellij "module" -> Eclipse "project" Second tip: Eclipse has the concept of "Perspectives" which means it reshuffles around your UI when you're doing different things, like for debugging there's the debug perspective. I don't quite get this, I personally prefer the concept of windows, or the tool windows that dock to the bottom or sides.
{ "language": "en", "url": "https://stackoverflow.com/questions/167400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How can I just get the "Year" portion from the output of timespan( ) in CodeIgniter? I have a "Date of Birth" field, and trying to use the timespan() method to get the age in years. But returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes". Any idea how I can just get the "28 Years" portion? A: I suggest you use PHP's strftime() function. Instead of using the CI's timespan(). echo strftime('%Y', 1226239392); A: There are many ways to do this, with the string in $date, like so: $date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes'; This will give you "28 Years" $yearsPart = substr($date, 0, strpos($date, 'Years') + 5); So will this: $parts = split(', ', $date); $yearsPart = $parts[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/167406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Subversion and revision engineering - what are the best web resources to read about? We are migrationg from CVS to SVN and embracing some kind of revision management in order to enforce order to development/testing/release cycle. We are currently testing, developing and releasing on the same code line, we know its a bad practice and we want to make end to it. What are your experience, know how, suggestions working with source code tree. We are building small/average (2-5 months) custom projects and we have to give early access to customer for review. Requirement creep is common. EDIT: please note, i need not only advice on subversion, but more on how whole devel/test/deploy cycle is reflected in trunk/branches/tags/versions etc A: * *"Branch early, branch often." *All builds should be completely reproducible without having to pour through logs (consider tagging every build) *If you use an issue tracker then require all check-ins to have a (valid) issue ID included in the commit message (add a pre-hook to check this). *Only the build team should be allowed to make production branches (developers should be encouraged to make personal branches for any non-trivial task) *Build continuously and ensure that everyone is aware that breaking the build is a big deal. *Read the whole SVN book, then read it again. You need to know this tool backwards and forwards. Hold training sessions for your developers ("how to create a temporary branch for my work", "how to merge", etc). ... There is an lack of good reading on this subject, but if I had to recommend one book to a shop completely green in SCM it would be "The Build Master" by Vincent Maraia. It's very short on details but easy to read and provides a (very very brief) overview of SCM good-ideas that make great sense once you know them but which for some reason so many shops completely lack. Good luck! A: Subversion makes it easier to branch than CVS (in GIT branches are even cheaper). I recommended that you make branches for major revisions, and have a planned merging of the branches back into the trunk. Be vary careful of going long periods of not merging back into the branch, as you it will become more and more difficult the longer you wait. There are also services out there that provide integrated bug tracking/deployment etc, if you need to get off the ground quickly, and don't want to manage all the server/setup stuff: * *http://beanstalkapp.com/ *http://unfuddle.com/ *http://www.assembla.com/ Some resources: This particular book answered a lot of the questions I had initially: http://www.pragprog.com/titles/svn/pragmatic-version-control-using-subversion Searching Further on stackoverflow: Good branching and merging tutorials for TortoiseSVN? Cal Henderson (developer at Flickr.com) Presentation at FOWA in Miami that I attended: http://cdn4.libsyn.com/carsonsystems/Cal_Henderson.mp3 The Free "Bible" of Subversion (Chapter on Merging): http://svnbook.red-bean.com/en/1.1/ch04.html A: A very good resource for source control : * *Agile-Version-Control
{ "language": "en", "url": "https://stackoverflow.com/questions/167413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is an atomic file rename (with overwrite) possible on Windows? On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow. Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up. The key word here is atomic... the solution must not be able to fail in any way that leaves the operation in an inconsistent state. I've seen a lot of people say this is impossible on win32, but I ask you, is it really? Please provide reliable citations if possible. A: The MSDN documentation avoids clearly stating which APIs are atomic and which are not, but Niall Douglas states in his Cppcon 2015 talk that the only atomic function is SetFileInformationByHandle with FILE_RENAME_INFO.ReplaceIfExists set to true. It's available starting with Windows Vista / 2008 Server. Niall is the author of a highly complicated LLFIO library and is an expert in file system race conditions so I believe if you're writing an algorithm where atomicity is crucial, better be safe than sorry and use the suggested function even though nothing in ReplaceFile's description states it's not atomic. A: See ReplaceFile() in Win32 (http://research.microsoft.com/pubs/64525/tr-2006-45.pdf) A: A fair number of answers but not the one I was expecting... I had the understanding (perhaps incorrectly) that MoveFile could be atomic provided that the proper stars aligned, flags were used, and file system was the same on the source as target. Otherwise, the operation would fall back to a [Copy->Delete]File. Given that; I was also had the understanding that MoveFile -- when it is atomic -- was just setting the file information which also could be done here: setfileinfobyhandle. Someone gave a talk called "Racing the Filesystem" which goes into some more depth about this. (about 2/3rds down they talk about atomic rename) A: Win32 does not guarantee atomic file meta data operations. I'd provide a citation, but there is none - that fact that there's no written or documented guarantee means as much. You're going to have to write your own routines to support this. It's unfortunate, but you can't expect win32 to provide this level of service - it simply wasn't designed for it. A: There is std::rename and starting with C++17 std::filesystem::rename. It's unspecified what happens if destination exists with std::rename: If new_filename exists, the behavior is implementation-defined. POSIX rename, however, is required to replace existing files atomically: This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic. Thankfully, std::filesystem::rename requires that it behaves just like POSIX: Moves or renames the filesystem object identified by old_p to new_p as if by the POSIX rename However, when I tried to debug, it appears that std::filesystem::rename as implemented by VS2019 (as of March 2020) simply calls MoveFileEx, which isn't atomic in some cases. So, possibly, when all bugs in its implementation are fixed, we'll see portable atomic std::filesystem::rename. A: In Windows Vista and Windows Server 2008 an atomic move function has been added - MoveFileTransacted() Unfortunately this doesn't help with older versions of Windows. Interesting article here on MSDN. A: Starting with Windows 10 1607, NTFS does support an atomic superseding rename operation. To do this call NtSetInformationFile(..., FileRenameInformationEx, ...) and specify the FILE_RENAME_POSIX_SEMANTICS flag. Or equivalently in Win32 call SetFileInformationByHandle(..., FileRenameInfoEx, ...) and specify the FILE_RENAME_FLAG_POSIX_SEMANTICS flag. A: you still have the rename() call on Windows, though I imagine the guarantees you want cannot be made without knowing the filesystem you're using - no guarantees if you're using FAT for instance. However, you can use MoveFileEx and use the MOVEFILE_REPLACE_EXISTING and MOVEFILE_WRITE_THROUGH options. The latter has this description in MSDN: Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation. I know that's not necessarily the same as a rename operation, but I think it might be the best guarantee you'll get - if it does that for a file move, it should for a simpler rename.
{ "language": "en", "url": "https://stackoverflow.com/questions/167414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "84" }
Q: Using .Net Framework Source debugging I'm getting a null-object exception deep within XsltCompiledTransform, and I'd like to use the .Net Framework Source debugging feature to see what isn't being initialized, but even after following the directions for enabling it, I can't figure out how to step into the .Transform() method and start spelunking. The tutorials I've found online say you can load the symbols for the framework library by using the Call Stack window while debugging, but this isn't useful when the callstack has yet to contain the library you want to debug. I've also tried loading symbols from the Modules window, but Step-Into still doesn't work. Is the System.Xml.Xslt namespace source even available to step into when debugging? A: If you have trouble fetching the sources on the fly, you might want to try out .NET Mass Downloader As it looks, the sources for XsltCompiledTransform are included.
{ "language": "en", "url": "https://stackoverflow.com/questions/167415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Share auto-incremented primary key between two tables Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor? Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables. I'm using SQL Server 9.0.3068. Thanks! A: I think using a GUID would be the most straightforward way, if I understand you correctly. SELECT NEWID() A: Use a column with GUID (Globally Unique Identifier) type. It's 16 byte and will be always unique for each row. Just be aware that you'll get a significant performance hit comparing to normal integer keys. A: Just configure the identity increment to be >1 e.g. table one uses IDENTITY (1, 10) [1,11,21...] and table two uses IDENTITY (2, 10) [2,12,22...]. This will also give you some room for expansion if needed later. A: Use another table with an ID key of type int default it to 1, called KeyID or whatever. Have a stored procedure retrieve the value, add 1, then update the KeyID, then return this to the stored procedure which is updating your two tables which needs the new unique key. This will ensure the ID is an int, and that it's unique between the set of tables which are using the stored procedure to generate new ID's. A: You can define an IDENTITY column in a third table, use that to generate ID values, but you always roll back any inserts you make into the table (to avoid making it grow). Rolling back the transaction doesn't roll back the fact that the ID was generated. I'm not a regular user of Microsoft SQL Server, so please forgive any syntax gaffes. But something like the following is what I have in mind: CREATE TABLE AlwaysRollback ( id IDENTITY(1,1) ); BEGIN TRANSACTION; INSERT INTO AllwaysRollBack () VALUES (); ROLLBACK TRANSACTION; INSERT INTO RealTable1 (id, ...) VALUES (SCOPE_IDENTITY(), ...); BEGIN TRANSACTION; INSERT INTO AllwaysRollBack () VALUES (); ROLLBACK TRANSACTION; INSERT INTO RealTable2 (id, ...) VALUES (SCOPE_IDENTITY(), ...); A: I don't know what you would call it. If you don't want to use a GUID or a separate table, you could also create a function that looked at the max values of the ids from both tables and added one to the that value (or something like that). You could then call that function in an insert trigger on both tables. A: I am personally a fan of the GUID solution, but here is a viable option. Many solutions to this problem have avoided GUID and used good old integer. This is common also with merge replication situations where many satellite sites merge with a master and key conflicts need to be avoided. If GUID will not work for you, and you absolutely must have int, bigint, or the like, you can always just use an IDENTITY column and have each table with a different value for SEED. Those datatypes have a very wide range, and it is not too hard to split the range into usable segments, especially if all you want is two splits. As an example, basic int has a range from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). This is more than enough for a customer table, for example. Transact-SQL Reference (SQL Server 2000) int, bigint, smallint, and tinyint Example: --Create table with a seed of 1 billion and an increment of 1 CREATE TABLE myTable ( primaryKey int IDENTITY (1000000000, 1), columnOne varchar(10) NOT NULL ) A: If you really need to do this with an int and you have an auto incrementing number, the way i have done this before is to change the id field auto increment function to the sequence of the other table. I am not too sure in ms sql or my sql but in pgsql that means that in the sql you would have this field id integer NOT NULL DEFAULT nextval('table_two_seq'::regclass), where table_two_sequence is the sequence function for the other table. Then test it out by inserting some data. I am really sorry if this wont work in ms sql i try to steer clear of it tbh. Failing that the GUID is the best way as has been mentioned by others. Or when inserting in the code that you use you could put an algorithm in that but it could get messy. Alternatively, think about having the data in one table as this would be a way around it. if you need to you could have a view simulating two tables. Just a thought. Hope i have helped A: Starting with SQL Server 2012 you can declare a sequence object https://msdn.microsoft.com/en-us/library/ff878091.aspx which is exactly what you need. I should be pretty trivial to emulate a sequence object with a table containing the next sequence value and a stored procedure atomically select the value and increment. [You'd liked to use function, but functions can't have side effects.] How about this hack? Create a table (MySequence) with two columns: And Identity column (SequenceValue) and a dummy column (DummyValue) and use this stored procedure to get a new sequence value. The only row in the table will be last sequence value retrieved. CREATE PROCEDURE GetNextValue AS BEGIN DECLARE @value int = null; -- Insert statements for procedure here INSERT into MySequence (DummyValue) Values (null); SET @value = SCOPE_IDENTITY(); DELETE from MySequence where SequenceValue <> @value SELECT @value as Sequence return @value END To use the sequence you'd have to manage the inserts to the target tables--a trigger would probably work.
{ "language": "en", "url": "https://stackoverflow.com/questions/167416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Issue With Python Sockets: How To Get Reliably POSTed data whatever the browser? I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications. The idea is to allow browsers to send messages real time each others via my python program. The trick is to let the "GET messages/..." connection opened waiting for a message to answer back. My problem is mainly on the reliability of what I have via socket.recv... When I POST from Firefox, it is working well. When I POST from Chrome or IE, the "data" I get in Python is empty. Does anybody know about this problem between browsers? Are some browsers injecting some EOF or else characters killing the receiving of "recv"? Is there any solution known to this problem? The server.py in Python: import socket connected={} def inRequest(text): content='' if text[0:3]=='GET': method='GET' else: method='POST' k=len(text)-1 while k>0 and text[k]!='\n' and text[k]!='\r': k=k-1 content=text[k+1:] text=text[text.index(' ')+1:] url=text[:text.index(' ')] return {"method":method,"url":url,"content":content} mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 80 ) ) mySocket.listen ( 10 ) while True: channel, details = mySocket.accept() data=channel.recv(4096) req=inRequest(data) url=req["url"] if url=="/client.html" or url=="/clientIE.html": f=open('C:\\async\\'+url) channel.send ('HTTP/1.1 200 OK\n\n'+f.read()) f.close() channel.close() elif '/messages' in url: if req["method"]=='POST': target=url[10:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"]) print req["content"]+" sent to "+target connected[target].close() channel.close() elif req["method"]=='GET': user=url[10:] connected[user]=channel print user+' is connected' The client.html in HTML+Javascript: <html> <head> <script> var user='' function post(el) { if (window.XMLHttpRequest) { var text=el.value; var req=new XMLHttpRequest(); el.value=''; var target=document.getElementById('to').value } else if (window.ActiveXObject) { var text=el.content; var req=new ActiveXObject("Microsoft.XMLHTTP"); el.content=''; } else return; req.open('POST','messages/'+target,true) req.send(text); } function get(u) { if (user=='') user=u.value var req=new XMLHttpRequest() req.open('GET','messages/'+user,true) req.onload=function() { var message=document.createElement('p'); message.innerHTML=req.responseText; document.getElementById('messages').appendChild(message); get(user); } req.send(null) } </script> </head> <body> <span>From</span> <input id="user"/> <input type="button" value="sign in" onclick="get(document.getElementById('user'))"/> <span>To</span> <input id="to"/> <span>:</span> <input id="message"/> <input type="button" value="post" onclick="post(document.getElementById('message'))"/> <div id="messages"> </div> </body> </html> A: The problem you have is that * *your tcp socket handling isn't reading as much as it should *your http handling is not complete I recommend the following lectures: * *rfc2616 *The sockets Networking API by Stevens See the example below for a working http server that can process posts index = ''' <html> <head> </head> <body> <form action="/" method="POST"> <textarea name="foo"></textarea> <button type="submit">post</button> </form> <h3>data posted</h3> <div> %s </div> </body> </html> ''' bufsize = 4048 import socket import re from urlparse import urlparse class Headers(object): def __init__(self, headers): self.__dict__.update(headers) def __getitem__(self, name): return getattr(self, name) def get(self, name, default=None): return getattr(self, name, default) class Request(object): header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M) def __init__(self, sock): header_off = -1 data = '' while header_off == -1: data += sock.recv(bufsize) header_off = data.find('\r\n\r\n') header_string = data[:header_off] self.content = data[header_off+4:] lines = self.header_re.findall(header_string) self.method, path = lines.pop(0) path, protocol = path.split(' ') self.headers = Headers( (name.lower().replace('-', '_'), value) for name, value in lines ) if self.method in ['POST', 'PUT']: content_length = int(self.headers.get('content_length', 0)) while len(self.content) < content_length: self.content += sock.recv(bufsize) self.query = urlparse(path)[4] acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, ) acceptor.bind(('', 2501 )) acceptor.listen(10) if __name__ == '__main__': while True: sock, info = acceptor.accept() request = Request(sock) sock.send('HTTP/1.1 200 OK\n\n' + (index % request.content) ) sock.close() A: I would recommend using a JS/Ajax library on the client-side just to eliminate the possibility of cross-browser issues with your code. For the same reason I would recommend using a python http server library like SimpleHTTPServer or something from Twisted if the former does not allow low-level control. Another idea - use something like Wireshark to check what's been sent by the browsers. A: Thank you very much Florian, your code is working!!!! I reuse the template and complete the main with my COMET mecanism and it is working much better Chrome and Firefox are working perfectly well IE has still a problem with the "long GET" system When it received the answer to the GET it does not stop to re executing the loop to print the messages. Investigating right now the question Here is my updated code for very basic JQuery+Python cross browser system. The Python program, based on Florian's code: bufsize = 4048 import socket import re from urlparse import urlparse connected={} class Headers(object): def __init__(self, headers): self.__dict__.update(headers) def __getitem__(self, name): return getattr(self, name) def get(self, name, default=None): return getattr(self, name, default) class Request(object): header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M) def __init__(self, sock): header_off = -1 data = '' while header_off == -1: data += sock.recv(bufsize) header_off = data.find('\r\n\r\n') header_string = data[:header_off] self.content = data[header_off+4:] furl=header_string[header_string.index(' ')+1:] self.url=furl[:furl.index(' ')] lines = self.header_re.findall(header_string) self.method, path = lines.pop(0) path, protocol = path.split(' ') self.headers = Headers( (name.lower().replace('-', '_'), value) for name, value in lines ) if self.method in ['POST', 'PUT']: content_length = int(self.headers.get('content_length', 0)) while len(self.content) < content_length: self.content += sock.recv(bufsize) self.query = urlparse(path)[4] acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, ) acceptor.bind(('', 8007 )) acceptor.listen(10) if __name__ == '__main__': while True: sock, info = acceptor.accept() request = Request(sock) m=request.method u=request.url[1:] if m=='GET' and (u=='client.html' or u=='jquery.js'): f=open('c:\\async\\'+u,'r') sock.send('HTTP/1.1 200 OK\n\n'+f.read()) f.close() sock.close() elif 'messages' in u: if m=='POST': target=u[9:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+request.content) connected[target].close() sock.close() elif m=='GET': user=u[9:] connected[user]=sock print user+' is connected' And the HTML with Jquery compacted: <html> <head> <style> input {width:80px;} span {font-size:12px;} button {font-size:10px;} </style> <script type="text/javascript" src='jquery.js'></script> <script> var user=''; function post(el) {$.post('messages/'+$('#to').val(),$('#message').val());} function get(u) { if (user=='') user=u.value $.get('messages/'+user,function(data) { $("<p>"+data+"</p>").appendTo($('#messages'));get(user);}); } </script> </head> <body> <span>From</span><input id="user"/><button onclick="get(document.getElementById('user'))">log</button> <span>To</span><input id="to"/> <span>:</span><input id="message"/><button onclick="post()">post</button> <div id="messages"></div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/167426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a ruler bar in MFC What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app? Would you make it part of the frame or the view? Derive it from CControlBar, or is there a better method? The vertical ruler must also be docked to a pane and not the frame. To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized. A: I would not use control bars. I have no good reason other then (IMOHO) are difficult to get to do what you want - if what you want if something other than a docking toolbar. I would just draw them directly on the View window using GDI calls. I guess I might think about making each ruler its own window, and draw the rulers on their own window. I would then create these two CWnd derived classes in the view and position as child windows. This is good if you want to interact with the mouse on these rulers (easier to sort out what messages are for the rulers). A: I ended up deriving the ruler from CWnd as you suggested and skipping the control bar route. This code works in either case: m_wndSplitter.CreateStatic(this, 1, 3); m_wndLeftPane.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 0)); m_ruler.Create(&m_wndSplitter,WS_CHILD|WS_VISIBLE,m_wndSplitter.IdFromRowCol(0, 1)); m_wndSplitter.CreateView(0, 2, pContext->m_pNewViewClass, CSize(300, 0), pContext); SetActiveView((CScrollView*)m_wndSplitter.GetDlgItem(m_wndSplitter.IdFromRowCol(0, 2)));
{ "language": "en", "url": "https://stackoverflow.com/questions/167427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best vbscript code to add decimal places to all numbers in a string? Example G76 I0.4779 J270 K7 C90 X20 Y30 If a number begins with I J K C X Y and it doesn't have a decimal then add decimal. Above example should look like: G76 I0.4779 J270 K7. C90. X20. Y30. Purpose of this code is to convert CNC code for an older Fanuc OPC controller A: Set RegEx = New RegExp RegEx.Global = True RegEx.Pattern = "([IJKCXY]\d+)([^\.]|$)" newVar = RegEx.Replace (oldString, "$1.$2") Where oldString is the original string, and newVar is the string with the decimals added. A: function convert(str) Set RegEx = New RegExp RegEx.Global = True RegEx.Pattern = "([IJKCXY]\d*\.?\d*)" Set Matches = regEx.Execute(str) For Each Match in Matches if instr(Match.value, ".") = 0 then str = Replace(str, Match.value, Match.value & ".") end if Next convert = str end function A: tloach still answer doesn't work Waynes works but also puts a . after every occurrence of IJKCXY I changed if instr(Match.value, ".") = 0 then To be like if instr(Match.value, ".") = 0 and len(Match.value) > 1 then
{ "language": "en", "url": "https://stackoverflow.com/questions/167432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X? Update: Thanks for the suggestions guys. After further research, I’ve reformulated the question here: Python/editline on OS X: £ sign seems to be bound to ed-prev-word On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell. * *Mac OS X 10.5.5 *Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) *European keyboard (£ is shift-3) When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears. If I’ve already typed some characters, e.g. >>> 1234567890 1234567890 1234567890 ... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line. In a normal bash shell, pressing shift-3 types a “£” as expected. Any idea how I can type a literal “£” in the Python interactive shell? A: Not the best solution, but you could type: pound = u'\u00A3' Then you have it in a variable you can use in the rest of your session. A: In unicode it is 00A003. With the Unicode escape it would be u'\u00a003'. Edit: @ Patrick McElhaney said you might need to use 00A3. A: u'\N{pound sign}' If you are using ipython, put execute pound = u'\N{pound sign}' in your ipythonrc file (in "Section: Python code to execute") this way you will always have "pound" defined as the pound symbol in the interactive shell. A: I'd imagine that the terminal emulator is eating the keystroke as a control code. Maybe see if it has a config file you can mess around with? A: Must be your setup, I can use the £ (Also european keyboard) under IDLE or the python command line just fine. (python 2.5). edit: I'm using windows, so mayby its a problem with the how python works under the mac OS?
{ "language": "en", "url": "https://stackoverflow.com/questions/167439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Does anyone know some cool PL/SQL plugin for IntelliJ Idea? I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy. I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer. A: Have you tried SQL Query Plugin? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure. It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax. A: I've started using the SQL Code Assistant plugin that instantly has recognised my PL/SQL packages and all these PL/SQL constructs (cursors etc) which the out-of-the-box IntelliJ functionality couldn't understand and was marking red. As of now it cannot only recognise dblinks but that's fair enough. Of course you'll have to associate *.sql file types with the plugin but it will intellij-ently inform you after you install/restart the IDE.
{ "language": "en", "url": "https://stackoverflow.com/questions/167440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: trace.axd returns a 404 error On a .Net production server, I am unable to look at the Application trace. The web server returns a 404 error. When copying the files on my local computer, the trace works, making further testing impractical. The trace seems to be correctly set: <trace enabled="true" requestLimit="20" pageOutput="true" traceMode="SortByTime" localOnly="false" /> edit: crap, I was trying to reply to it directly since I lost 2 hours on that and that some googling showed I was not the only one who stumbled there. Apparently I can't accept my own answer :) A: First of all, check whether the trace works whith a minimal trace directive: <trace enabled="true" /> should work in any case. Then check the IIS configuration: an URL rewriting rule might be interfering with the trace.axd url. If this is not the case, check whether the server accepts the .axd extension (Manage IIS>Properties>Home Directory>Configuration: The .axd extension should be present, executed by aspnet_isapi.dll, and not verifying that the file exists)
{ "language": "en", "url": "https://stackoverflow.com/questions/167449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XSLT Abstractions I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience. I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring". For example, with generic HTML and a service side include, many pages can be templated and decomposed to where there are, say, common header, nav, and footer segments, and the page itself is basically the body. The common markup languages, JSP, PHP, ASP, go as far as to allow all of those segments to have dynamic content (such as adding the user name to every header block). JSP goes even farther by allowing you to create Tag files, which can accept arguments to be used when generating the content, and even surround and work on content within the tags themselves. I'm curious similar functionality is done within XSLT. What facilities are there to make reusable block of XSLT for things like creating HTML pages? A: Templates, Includes. Xsl is very different from any other programming language. Its rule based. I recommend you to read something about Xslt and then ask a bit more spedific. A: There are both xsl Include and Import statements that you can use to abstract away portions of the page. XSLT itself is very much the kind of thing that can reproduce tag file type behavior. You edit your xml data files with the tags you want. Meanwhile, your xsl templates are going to know what do to with those tags then they encounter them. A: You can give templates names and then call them via 'call-template' In XSLT 2.0 you can create your own functions (although I find the syntax tortuous) A wonderful area to explore is using XSLT to generate XSLT stylesheets. This lets you automate common conversion scenarios where 90% of the stylesheet is boilerplate. In order to do this you need to become familiar with 'namespace-alias'. Its a great way to expand your knowlege of the language. A: XSL is based on templating. XML data can be "re-used" at three-levels. At the most basic level you can <xsl:for-each /> through XML. Note: For-each in XSL is not looping through the data, it's just matching the data. Also when your "inside" a for-each your inside that "context" of the XML (which is like the concept of "scope" in programming) An example of using and re-using a for-each <xsl:for-each select="/xml/data/here"> ... do some stuff ... </xsl:for-each> <xsl:for-each select="/xml/data/here"> ... do some DIFFERENT stuff ... </xsl:for-each> The for-each nodes are contained within template nodes (2nd level of reuse). There are two types of template nodes: Match and Named. Match template nodes, act like the for-each node mentioned above, but are automatically called by the template engine if any nodes are matched when XSL processing starts. Match template nodes can also be explicitly applied. On the other hand Named template nodes are always explicitly applied and can be thought of as like functions. Example of a Match template which will Always be called (because a root node will always exist) <xsl:template match="/"> ... do some stuff ... </xsl:template> A Match template calling another match template explicitly <xsl:template match="/"> <xsl:apply-templates select="xml/data/too" /> </xsl:template> <xsl:template match="xml/data/too"> ... do something ... </xsl:template> Note: In order for the Match template to work, the XML Node it is matching needs to exist. If it doesn't there is no match, so that template is not called. Example of a Named template <xsl:template name="WriteOut"> ... data with NO Context Here ... </xsl:template> Or calling a Named template from a Matched template <xsl:template match="/"> <xsl:call-template name="WriteOut" /> <xsl:template> Note: You can mix and match where you call matched and named templates from, you just have to watch what context you are in. All of template nodes are held in XSL Stylesheets, and you can include and import various stylesheets. For example you can hold all of the templates dealing with HTML header nodes in one template and all of the templates dealing with the HTML body nodes in another. Then you can create one stylesheet that includes both Header and Body stylesheets. Example of an include node <xsl:include href="header.xsl" /> In conclusion there are three ways to abstracting chunks of data, through for-eaching, through templating or through including stylesheets. A: For my own project, this is how I divided up my pages. There was a template.xsl file which was imported by each of my XSLs. Most pages just had template.xsl, but some pages such as cart, etc. needed their own because of the different kind of data they were parsing. <page title="Home"> <navigation> <!-- something here --> </navigation> <main> <!-- something here --> </main> </page> This is a snippet from my template.xsl. I threw in all the common stuff in here, and then gave the opportunity for my pages to add their own information through call-template. <xsl:template match="/page" name="page"> <html> <head> <title><xsl:value-of select="(@title)" /></title> <xsl:call-template name="css" /> <xsl:call-template name="script" /> </head> <body> <xsl:call-template name="container" /> </body> </html> </xsl:template> An example of how my css tag would respond. Note that it calls css-extended. css only had the the common css' that would apply across all pages. Some pages needed more. Those could override css-extended. Note that is needed because call-template will fail if a page calls a template but doesn't define it anywhere. <xsl:template name="css"> <link rel="stylesheet" type="text/css" href="{$cssPath}reset.css" /> <link rel="stylesheet" type="text/css" href="{$cssPath}style.css" /> <link rel="stylesheet" type="text/css" href="{$cssPath}layout.css" /> <xsl:call-template name="css-extended" /> </xsl:template> <!-- This is meant to be blank. It gets overriden by implementing stylesheets --> <xsl:template name="css-extended" /> My container would work in a similar manner-- common stuff was defined and then each page could just provide an implementation. A default implementation was in the XSL. (in content) <xsl:template name="container"> <div id="container"> <xsl:call-template name="header" /> <xsl:call-template name="content" /> <xsl:call-template name="footer" /> </div> </xsl:template> <xsl:template name="content"> <div id="content"> <div id="content-inner"> <xsl:call-template name="sideBar" /> <xsl:call-template name="main" /> </div> </div> </xsl:template> <xsl:template name="main"> <div id="main"> <xsl:apply-templates select="main" /> <xsl:call-template name="main-extended" /> </div> </xsl:template> <!-- This is meant to be blank. It gets overriden by implementing stylesheets --> <xsl:template name="main-extended" /> <xsl:template name="footer"> <div id="footer"> <div id="footer-inner"> <!-- Footer content here --> </div> </div> </xsl:template> It worked quite beautifully for me. If there are any questions I can answer for you, let me know. A: XSLT is powerful, but it is very different from most programming languages and it is quite limited in what it makes available to you, so things that you have built-in with another language may need some quite complex xsl manipulation to work with. I found the cheatsheet from here useful when I was going through a lot of XSLT work a couple of weeks back. Don't expect that XSLT will do things in a particular way and you probably can find good ways of doing those things, but if you have too much of a set idea about how something should work it's easy to get stuck.
{ "language": "en", "url": "https://stackoverflow.com/questions/167453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Can I connect to SQL Server using Windows Authentication from Java EE webapp? I am currently investigating how to make a connection to a SQL Server database from my Java EE web application using Windows Authentication instead of SQL Server authentication. I am running this app off of Tomcat 6.0, and am utilizing the Microsoft JDBC driver. My connection properties file looks as follows: dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver dbUser = user dbPass = password dbServer = localhost:1433;databaseName=testDb dbUrl = jdbc:sqlserver://localhost:1433 I have zero problems with connecting to a SQL Server database in this fashion when using SQL Server authentication. Is there any way I can retrieve the credentials of the user's Windows Authentication and use that authentication for SQL Server? UPDATE: I know in ASP.net there is a way to set up Windows Authentication for access to the webapp, which is exactly what I am looking for, except I want to pass that token off to SQL Server for access to the database. A: I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not) But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this: jdbc:sqlserver://localhost;integratedSecurity=true; And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver) MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL A: This actually works for me: Per the README.SSO that comes with the jtdsd distribution: In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll. Place this DLL anywhere in the system path (defined by the PATH system variable) and you're all set. I placed it in my jre/bin folder I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name. jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local A: Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver. Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM. A: I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did: * *Install the JTDS driver *Do not use the "domain= " property in the jdbc:jtds:://[:][/][;=[;...]] string *Install the ntlmauth.dll in c:\windows\system32 directory (registration of the dll was not required) on the web server machine. *Change the logon identity for the Apache Tomcat service to a domain User with access to the SQL database server (it was not necessary for the user to have access to the dbo.master). My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003 A: look at http://jtds.sourceforge.net/faq.html#driverImplementation What is the URL format used by jTDS? The URL format for jTDS is: jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]] ... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication. If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).
{ "language": "en", "url": "https://stackoverflow.com/questions/167464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Oracle merge constants into single table In Oracle, given a simple data table: create table data ( id VARCHAR2(255), key VARCHAR2(255), value VARCHAR2(511)); suppose I want to "insert or update" a value. I have something like: merge into data using dual on (id='someid' and key='testKey') when matched then update set value = 'someValue' when not matched then insert (id, key, value) values ('someid', 'testKey', 'someValue'); Is there a better way than this? This command seems to have the following drawbacks: * *Every literal needs to be typed twice (or added twice via parameter setting) *The "using dual" syntax seems hacky If this is the best way, is there any way around having to set each parameter twice in JDBC? A: I would hide the MERGE inside a PL/SQL API and then call that via JDBC: data_pkg.merge_data ('someid', 'testKey', 'someValue'); As an alternative to MERGE, the API could do: begin insert into data (...) values (...); exception when dup_val_on_index then update data set ... where ...; end; A: I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like: merge into data using ( select 'someid' id, 'testKey' key, 'someValue' value from dual ) val on ( data.id=val.id and data.key=val.key ) when matched then update set data.value = val.value when not matched then insert (id, key, value) values (val.id, val.key, val.value); A: I prefer to try the update before the insert to save having to check for an exception. update data set ...=... where ...=...; if sql%notfound then insert into data (...) values (...); end if; Even now we have the merge statement, I still tend to do single-row updates this way - just seems more a more natural syntax. Of course, merge really comes into its own when dealing with larger data sets.
{ "language": "en", "url": "https://stackoverflow.com/questions/167471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Is it possible to have a List as a property on an active record class Is it possible to have a HasMany relationship of a basic type such as String, on an ActiveRecord class, without the need for creating another entity such as (TodoListItem) to hold the value. [ActiveRecord] public class TodoList { [PrimaryKey] public int Id { get { return _id; } set { _id = value; } } [HasMany(typeof(string)] public IList<string> Items { get { return _items; } set { _items= value; } } } Can anyone help? A: Yes, you can do this. You can map a one-to-many relation to a built-in or simple type (value type or string) rather than a persisted type. You'll need to specify the ColumnKey, Table and Element params in the HasMany attribute declaration to get it to wire up properly. You have to have a surrogate key column so the AR can handle updates and cascades, and then Element tells AR which column in the table holds the simple value it will use to make the list. [HasMany(typeof(string), Table="ToDoList_Items", ColumnKey = "ListItemID", Element = "Item")] public IList<string> Items { get; set; } (or something similar - I haven't got a compiler handy on this box to check it; but per the API docs it ought to work.) Speaking of which, if you haven't already had a look, http://api.castleproject.org is kinda indispensible for any work with the Castle stack. A: In ActiveRecord, your types map to a record in a table (by default). It seems like you are confusing how this type should map to your table. The MyClass type should have a definition something like this (excluding the PK settings): [ActiveRecord(Table = "MyTable")] public class MyClass : ActiveRecordBase<MyClass> { [Property] public int Id { get; set; } [Property] public int MyClassId { get; set; } [Property] public string ListItem { get; set; } } Then, to load the list: public void LoadMyClasses() { MyClass[] results = MyClass.FindAll(); } I'd suggest you spend some time with the ActiveRecord documentation (or tutorial) as that should also help clear up any confusion.
{ "language": "en", "url": "https://stackoverflow.com/questions/167485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSThread and UIViewController interaction If I spawn a new thread, and then within it I push a new controller onto my UINavigationController, using code like this... (a) not working -(void)myCallbackInThread { // move on... UIApplication* app = [UIApplication sharedApplication]; [app changeView]; } then I find that the view appears, but does not respond to user input. If I change the code like this (b) working -(void)myCallbackInThread { // move on... UIApplication* app = [UIApplication sharedApplication]; [app performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE]; } Then everything works just fine. Any hints as to why? A: Just found this in the iPhone threading docs If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but it also has the advantage of simplifying the logic for managing your user interface. I still don't see what would actually cause something to display but not be able to receive user input, but I'll follow that guideline in future. A: As the documentation says, "If you’re not sure about a particular graphical operation, plan on doing it from your main thread." A good rule of thumb to follow is that, if a class isn't explicitly documented as being thread-safe, then it's probably not. Additionally, code that's not documented as being thread-safe may not fail fast when used by multiple threads, but may simply exhibit undefined behavior, as you saw. A: In your case, it really depends on what's happening in [app changeView], but the reason it stops responding is most likely that you have no run loop dispatching events on your new, secondary thread (more on this below). In general, however, it is a very bad idea to update the GUI from a secondary thread. As you've already discovered, all of these events should go through the main thread. The main reason that your second example works and not your first is that UIApplication sets up and handles the run loop and event dispatcher for you on the main thread. So, when you call performSelectorInMainThread, the selector gets dispatched to the main run loop which is able to then handle your gui input and other events. The event dispatcher is also run and managed by UIApplication on the main thread. So basically, don't perform any GUI management activities on a secondary thread. Dispatch those to the main thread. And if you need processing on a secondary thread (for things like timers or asynch calls, etc.) then you have to start and manage your own run loop on that thread (see NSRunLoop for more on managing your on run loop). A: Almost none of the UI code in UIKit or AppKit is threadsafe. How it fails is irrelevent, because if you are worrying about how it fails you are doing something that is going to result in all sorts of weird bugs that will subtly change between different OS release anyway. My best advice is to not use things from background threads unless the docs say it is safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/167487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL Server 2005 Using DateAdd to add a day to a date How do I in SQL Server 2005 use the DateAdd function to add a day to a date A: The following query I have used in SQL Server 2008, it may be help you. For add day DATEADD(DAY,20,GETDATE()) *20 is the day quantity A: DECLARE @date DateTime SET @date = GetDate() SET @date = DateAdd(day, 1, @date) SELECT @date A: DECLARE @MyDate datetime -- ... set your datetime's initial value ...' DATEADD(d, 1, @MyDate) A: Select getdate() -- 2010-02-05 10:03:44.527 -- To get all date format select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010 union select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY' Union select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD' Union select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY' Union select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY' Union select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY' Union select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007 Union select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007 union select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010 union select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010 union select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD' union select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205 union select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010 SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14 SELECT convert(varchar, getdate(), 23) -- 2010-02-05 SELECT convert(varchar, getdate(), 24) -- 10:24:20 SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913 SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990 ---================================== -- To get the time select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53 select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223 SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM ----============================================= SELECT getdate()+1 SELECT month(getdate())+1 SELECT year(getdate())+1 A: Try following code will Add one day to current date select DateAdd(day, 1, GetDate()) And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function A: Use the following function: DATEADD(type, value, date) * *date is the date you want to manipulate *value is the integere value you want to add (or subtract if you provide a negative number) *type is one of: *yy, yyyy: year *qq, q: quarter *mm, m: month *dy, y: day of year *dd, d: day *wk, ww: week *dw, w: weekday *hh: hour *mi, n: minute *ss or s: second *ms: millisecond *mcs: microsecond *ns: nanosecond SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day http://msdn.microsoft.com/en-us/library/ms186819.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/167491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: UpdatePanelAnimationExtender - Resize not working This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the Ajax site. I placed a alert() in the tag (line 108) to find the value of 'b._originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %> <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %> <%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %> <h1 style="margin-left:8px">Add/Edit Contest</h1> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /> <div style="text-align:left;width:500px; margin-left:8px"> <div id="PanelContainer"> <asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always"> <ContentTemplate> <div id="background" style="text-align:left; height: 44px;"> <asp:Panel ID="ContestList" runat="server"> <asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5" Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc" HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b" Runat="server" AllowPaging="True" PageSize="10" PagerStyle-NextPageText="Next >>" PagerStyle-PrevPageText="<< Back" > <Columns> <asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&Type=Edit&ContestID={0}" DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" /> <asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" /> <asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" /> </Columns> </asp:datagrid> <div style="text-align:right;"> <asp:ImageButton ID="AddContest" runat="server" ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest" onclick="AddContest_Click" /> </div> </asp:Panel> <asp:Panel ID="FieldsPanel" runat="server"> <p /><b>Title</b> <br /> <asp:TextBox Runat="server" id="TitleText" /> <asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red" ErrorMessage="Please add a title" ControlToValidate="TitleText">*</asp:RequiredFieldValidator> <p /><b>Contest Description</b> <br /> Use HTML tags to format this area. Start paragraphs with &lt;p /&gt; tag, bold items with &lt;b&gt;&lt;/b&gt; tags. Create a line-break between lines with one &lt;br /&gt; tag.<br /> <asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" /> <asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description" ControlToValidate="DescriptionText" ForeColor="Red">*</asp:RequiredFieldValidator> <p /> <b>Contest Start Date</b> <br /> <ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"> <WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /> <MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /> <OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /> <GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/> <TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /> <DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /> <WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /> <SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/> <HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /> </ew:CalendarPopup> &nbsp; <ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"> <TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /> <SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /> </ew:TimePicker> <p/><b>Contest End Date</b> <br /> <ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"> <WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /> <MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /> <OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /> <GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/> <TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /> <DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /> <WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /> <SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/> <HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /> </ew:CalendarPopup> &nbsp; <ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"> <TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /> <SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /> </ew:TimePicker> <p /> <asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm" ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" /> </asp:Panel> <br /> <asp:Label ID="MessageLabel" runat="server" /> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" /> </Triggers> </asp:UpdatePanel> </div> <uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel"> <Animations> <OnUpdating> <Sequence> <%-- Store the original height of the panel --%> <ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" /> <%-- Disable all the controls --%> <Parallel duration="0"> <EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" /> </Parallel> <StyleAction Attribute="overflow" Value="hidden" /> <%-- Do each of the selected effects --%> <Parallel duration=".25" Fps="30"> <FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" /> <Resize Height="0px" /> </Parallel> </Sequence> </OnUpdating> <OnUpdated> <Sequence> <%-- Do each of the selected effects --%> <Parallel duration=".25" Fps="30"> <FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" /> <Length duration="2" fps="40" Property="style" PropertyKey="height" StartValue="10" EndValueScript="$get('animation').offsetHeight" AnimationTarget="animation" /> <%--Also tried the below <Resize HeightScript="$find('animation')._originalHeight" /> --%> </Parallel> <%-- Enable all the controls --%> <Parallel duration="0"> <EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" /> </Parallel> </Sequence> </OnUpdated> </Animations> </uc:UpdatePanelAnimationExtender> </div> A: I'm not sure if this is the only thing--this is only the first thing that jumped out to me: But according to the reference docs, your <Resize Height="0px" /> tag should instead be <Resize Height="0" Unit="px" />. Why is the second <Parallel> Duration shorter then the <Length> Duration?Sorry, not really an answer, just some notes of possible issues I see at first glance. A: After watching Joe Stagner's video, I too tried to implement the ASP.NET AJAX UpdatePanelAnimation Extender, and I too had difficulty implementing the resize animation. My problem was the following: I didn't add a System.Threading.Thread.Sleep(1000) statement to the server-side event handler. Your code example doesn't include your code-behind, so this may be your problem. Here's another guess: It might help if you specify the 'AnimationTarget' attribute on the 'Resize' tags. <Resize AnimationTarget="PanelContainer" Height="0px" /> {...} <Resize AnimationTarget="PanelContainer" HeightScript="$find('animation')._originalHeight" />
{ "language": "en", "url": "https://stackoverflow.com/questions/167502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort gridview by column containing nullable integer? I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception: System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object. How do I customize the sorting or comparison logic to handle the null case? A: The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison: gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting); protected void gridView_Sorting(object sender, GridViewSortEventArgs e) { // Only add custom handling for the sort expression on the // Nullable<int> column if (e.SortExpression == "MySortExpression") { // Convert datasource to a List<T> list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2) { return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp); })); // Bind the sorted list back to the gridview } else { // delegate to the gridview to handle its own sorting } } A: You could also override the null when you bind the data, placing a 0 instead. Your answer is far better. :) You could also make a custom type that overrides the Compare operator. But that would just duplicate (and complicate) what you have above.
{ "language": "en", "url": "https://stackoverflow.com/questions/167509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pros and Cons of Developing on a VM on a PC I recently build myself a semi beef up PC (Q9450, 8GB DDR2 1066, 1TB HDD, Dual 8600GT, Vista Ultimate and Dual 22' Monitors) and I'm evaluating whether i should develop on a VPC/VMWare session on top of Vista or not? One benefit I can see is that I can run the same VM on my Vista laptop so my development environment is the same on any of my machines. I also plan on purchasing a MBP before the end of the year as well. Found a couple of articles online that semi-help Here Any other thoughts would be really appreciated? A: For webdevelopment I like to have the serverpart separeted out into a VM. My current setup is a Macbook Pro with several Debian VM's inside. I like the isolation aspect of it. I can try new software on the servers and have the ability to revert them back if something is messed up. I do the programming via network-share (samba) in Textmate on the host system. A: Another advantage of a VM is having a clean installed base. I use my desktop and laptop for lots of things aside from development. You never know when a piece of software you install is going to conflict, or if the little tweaks and what not you play around with are going to trash your OS. Reinstalling/configuring all your tools so they are exactly the way you want them can take quite some time. If you have a backup of your Development VM Image you can mess up your PC as much as you want but still be able to code without downtime. It also allows you to run Win/Visual Studio/Etc on a box that you would otherwise prefer Linux or MacOS on. You can also make multiple copies of the same Image and use each one for a separate project. Being able to transition between a laptop/desktop/server/remote connection, and always be in the same environment is also very helpful. A: One problem I found (at least when using VMWare Server) is that no matter how fast your machine is, the screen refresh rate is still around ~30hz. That makes for a slightly unpleasant experience after using it for a while. A: Where I'm working at now I use a VM for all of my development because I don't have admin rights to my base copy of XP. Pros: I like using a VM's because it give you some flexibility - you can switch between machines - have programs running on both and have a cool environment to work on. Cons: You have to boot up multiple operating systems. This takes time, memory and resources. Clipboard operations on VM's can be interesting at times. Sometimes copying to clipboard does not work or gets mixed up between VM's. (Using VMWare). File operations can be interesting when you plug in USB drives and other external devices. VM's sometimes do not see the devices, sometimes it does. If your VM image become corrupt - you can easily loose everything in it.... unless it is backed up..... A: It's great for presenting development talks, you can revert to a snapshot and give the talk from the exact same starting point each time. A: Bulk-up your RAM on your future MacBookPro if VMWare will be used. I haven't (yet) and the performance with several other (mac-side) apps open really starts to feel sluggish. All the best. A: I was doing some work with Visual Studio recently with a Windows XP vm on Linux and somehow the guys who made the vm (vmware) made the windows machine actually run faster. We did some time tests to make sure and it wasn't major, but a few things (autocomplete for example) really did pop up faster. A: If you are on Windows, Virtual PC is pretty decent for development work. VMWare Virtual Server is not really designed for use as a desktop and you will get very tired of it with any prolonged use. Sun's VirtualBox is another option competing with Virtual PC. VMWare has a workstation product but it is not free. Typically, I do development on the real desktop (non-virtual) and then deploy or test to virtual machines which I can snapshot and roll back easily. A: For a long time, we were developing on very early versions of Visual Studio 2005 and the associated .Net bits that went along with it. To protect our real machines from the various problems associated with pre-release software, we did all of our development work inside virtual machines. It worked amazingly well. I've been considering moving back to that model as it makes upgrading the physical hardware a snap (not to mention making it easier to deal with hardware failures by just replacing the entire machine): you just copy the VM image over. On my current machine (A Core2Duo with 4GB of RAM), the performance drop when running one VM is almost not noticeable. Running two VMs, however, is painful. I also can't figure out how to get VMWare Server to work across two monitors well. A: I wouldnt want to develop in a VM so much as test things in a VM. For instance, it might be nice to set up a couple VM's to emulate an n-tier architecture, or a client-server setup or finally simply to test code on multiple OSs A: It depends what you are developing and in what language. VM's tend to take a fairly hard hit on disk access, so compiling may slow down significantly, especially for large C/C++ projects. Not sure if this would be such an issue with .NET/Java. If you are doing anything that is graphics intensive (3D, video, etc) then I would steer clear of a VM too. A: I don't know if it is so useful as a development platform unless you are doing something that ties into software you don't want to have installed on your regular working machine or that needs to work around a certain event that you need to be able to reset on a regular basis. It can also be handy when you are working with code that risks crashing your computer as it will at least only crash your VM. It is brilliant for testing different configurations and setups- working with installers and so on, that is where virtualisation really shines as far as I am concerned, being able to roll things back whenever you need to and run through stuff repeatedy is amazingly useful for identifying problems before your end users run into them. A: While doing development at home, I have to VPN into my company to be able to use the collaborative tools that are on the intranet. I also have a desktop + laptop that are hooked together through Synergy. The problem that I have is that our VPN software wants things to be so secure that it will force all network routing through the VPN gateway -- even if I'm using additional NICs to network my desktop and laptop through a separate private network. The end result is that I can't use Synergy between my desktop and laptop and VPN into my company at the same time. The solution suggested to me by a co-worker was to setup a VM instance on my desktop and use that for all my VPN needs. Works like a charm! A: Speaking from personal experience developing java in an Ubuntu VM on Windows 7, I've found this to be quite productive. Mainly because my local IT support on the ground supports Windows 7, so I can do things like access all the local file shares and printers in Windows, and then config my Ubuntu VM to my heart's content. Huge productivity benefits around remote access and desktop sharing. Windows allowed me to very quickly and easily use tools like logmein.com and join.me to access my machine from home and to desktop share the VM with other people in the company (both work seamlessly with the VM in a nearly full screen window). Neither of these services are supported on Linux, and I wouldn't want to deal with all the associated VNC/X setup and network config on Ubuntu. My machine is fairly beefy. Quad core, with 16Gb RAM - 8Gb for the VM. Java dev in the VM is pretty quick.
{ "language": "en", "url": "https://stackoverflow.com/questions/167512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Naked Objects. Good or Bad I have recently been exposed to naked objects. It looks like a pretty decent framework. However I do not see it in widespread use like say, Spring. So why is this framework not getting any mainstream application credit. What are its shortcomings as you see? A: It has been successfully used here in Ireland. I think reasons why it hasnt been more popular are: * *You need a lot of confidence in the toolkits you are using *It makes the GUI a risk factor instead of a no-brainer (both technically and in usability testing) *Its not applicable to the web (as far as I know), which is where most of the focus is as present... A: I've only just seen this. A couple of minor corrections, otherwise most of the comments are very fair. 1) 'The framework only asks your domain objects (POJOs) to be subclassed from AbstractDomainObject thats all the minimum wiring.' Naked Objects does not require the domain objects to be subclassed from AbstractDomainObject, although that is typically the most convenient thing to do. If you don't want to inherit, all you need to do is provide a property of type IDomainObjectContainer, and the framework will then inject an container into your objects when they are created or retrieved. The container has methods for Resolve(), ObjectChanged() and NewTransientInstance(), which are the three minimalist points of contact with the framework that you must use, so that the framework remains in synch with your domain objects. 2) 'Works great for prototyping along with db4o for persistence'. We're quite keen on the idea of working with db4o, but I'm not aware of anyone who has made Naked Objects and db4o play together. If anyone has done this, I'd like to hear more about it. 3) 'The general model of citzen programmer as espoused in the smalltalk and naked object communities ...'. We have never espoused that idea, and I don't agree with it. Naked Objects is NOT about encouraging users to program. I believe firmly in the role of the professional developer - Naked Objects just helps them to write better software and more productively. Richard A: I have played with it last year or so, and concluded it is very easy to work with. The strength of Naked Objectsis that you get a GUI structured according to your data model for free. The disadvantage is that a typical user does not think about his proces as a collection of records. My conclusion was that Naked Objects is really great for an internal application which conceptually deals with records, like an inventory application or bill processing application. If you need anything different adapting the framework to your wishes may just be a lot more work than using a framework written to support the kind of application you want. By the way, there is a Web rendering option; see the demo at Naked Objects Demo. A: Gareth makes some excellent points. There are other issues, such as the fact that it's hard to control the look and feel, and they are counter-intuitive to people who have become used to the window model. There is also something of a modelling issue, in that not all application domains lend themselves well to direct oject representation. The general model of 'citizen programmer' as espoused in the smalltalk and naked object communities also comes to bear as a questionable idea. Most users don't seem to be hugely bothered with changing the functionality themselves, so thinking in objects is not that useful. A: Probably the reason it hasn't gotten more attention is that the J2EE world has become so used to piling on so many layers onto an application, that naked objects comes across as naive. Where are our services? You mean that any naked object gives me immediate access to the database? What if we needed to expose the application with RMI calls? Plus there isn't as much to market, because it puts the burden of developing a successful application squarely on the application developers not the framework developers :) A: I guess NakedObject definitely has its relevance and its more than time that developer community refocuses on what is really paying them: the business. Instead, we mostly spend our time with infrastructure, protocols and all that technical crap. I have seen such miss constructed applications and I even did some myself following the mainstream, teaching you that layering a system is always a good thing to do. The worst thing is that if you ask some developers about what kind of business the company they are working for does, you’ll find at least some who worked for the company for years without gaining a deeper understanding of the business. However, I don’t believe that NakedObject will attract a vast majority of developers (even those who are inspired from DomainDrivenDevelopment) simply because people love to construct UIs and taken that job away from them, directing their work towards businesses needs, is simply not what they want: We are all VB jerks. A: NakedObjects (NO) are good for rapid prototyping. You can concentrate on Domain Model while not paying attention to GUI, DB and other parts of your solution. For production it requires alot of improvements (bugs fixing, data mapping, gui, etc.) in NakedObjects framework itself. So if you need to get some kind of "proof of concept" for your solution, you may use NO. But for production be ready to invest resources into development of NO framework. BTW, recently we are working on creating DnD viewer based on GWT for NO 4.0. A: From my experience using NOF 3.0.3... The good: * *Automagically generates an DnD UI for your domain objects, like what db4o does for persistence. *This is what MVC was always meant to be, according to the MVC pattern creator. *The framework only asks your domain objects (POJOs) to be subclassed from AbstractDomainObject thats all the minimum wiring. *The framework favors convention OVER configuration: lots of annotations no freaking XML config giles. *Works great for prototyping along with db4o for persistence. *Out of the box functionality for Hibernate. *In my case, I required like 30 mins from Download to Hello world app. (IntelliJ IDEA IDE) *Deployment as JNLP, standalone, Web (NOX embedded Jetty or Scimpi flavor) and Eclipse RCP. *The NOF team is ALWAYS there for you when you ask for help in the forums. *The Naked Object Pattern is an awesome idea, do yourself a favor and take your time to grok it. *Theres a lot of usability flaming going on around the Drag and Drop GUI, but if your prospective end users simply can't work with the DnD UI then you are in deep trouble anyway. The bad: * *None that I can think of. The kinda ugly: * *No Swing components allowed, so say goodbye to JGoodies and all your favorite Swing component sets. The UI components are custom made; to get you an idea they look like early 90's VB controls. But there's a SWT port in the works. *The multiline line field for long strings has some issues. (NOF 3.0.3) *DnD UI for images is kinda buggy. *The validation code for getters n setters only fires if the domain object is modified from the UI. (This is probably wrong due to my n00bness, lets hope a NOF committer corrects me) *If an object is modified from a non-ui thread, lets say a b.g. worker, such object will not update its view on screen. This invalidates a use case such as representing a mail queue in real time on the DnD autogenerated UI. (Again) *Veikko A: I've been working on the naked objects approach for over a year now and I haven't even begun to scratch the surface of the possibilities it provides for your system's architecture. To properly utilize it though, it requires that you create a paradigm shift and seek out full OO solutions and revert from resorting to functional duck tapes, because the paradigm seems to work only when you create a design that would allow for high-level development. Having said that, I absolutely love how Django has implemented naked objects within it's Django Models. Most of the things I love about the framework have been, what I come to believe, a direct result of it's models and there are some wows off the top I'd like to share about the architecture: Model fields, that map to table columns, are behaviorally complete objects--they know how they're represented in both the application and database domain, how they're converted between the two and how the information they hold is validated and displayed to the user visually for inputs. All of this utilized with a single line of code in your model. Wow! Managers are attached to models and provide CRUD and any generic operations on collections, such as reusable queries (give me the last five blog posts, most occuring tags, etc.), mass delete\update operations, and business logic performed on instances. Wow! Now consider you have a model that represents a user. Sometimes, you'd only like to have a partial view of all the information a user model holds (when resetting a user's password you may only need need the user's email and his secret question). They've provided a Forms API that exactly displays and manages inputs for only parts of the model data. Allows for any customization of the what/how in handling user input. Wow! The end result is that your models are only used to describe what information you use to describe a particular domain; managers perform all the operations on models; forms are used for creating views and for handling user inputs; controllers (views) are only there for handling HTTP verbs and if they work with models it's solely through managers and forms; views (templates) are there for the presentation (the part that can't be automatically generated). This, imho, is a very clean architecture. Different managers can be used and reused across different models, different forms can be created for models, different views can use different managers. These degrees of separation allow you to quickly design your application. You create a ecosystem of intelligent objects and get a whole application from the way they're interconnected. With the premise that they're loosely coupled (lot's of possibilities for letting them communicate in different ways) and can be easily modified and extended (a few lines for that particular requirement), following the paradigm you really do get an architecture where you a component write once and then reuse it throughout your other projects. It's what MVC should have always been, yet I've often had to write something from scratch even though I did the same thing a few projects ago. A: * *widespread use of technology has no strong correlation to technological quality. *The nakedobject system is difficult to use in combination with type objects: if I'm selling different kinds of products and need different data for different products, it is difficult to constrain the data on the product type. *NO lost momentum when they switched licences. (to GPL+Commercial, not the recent move to Apache) Did you take a look at jmatter? [edit] And another one: it makes it obvious to non-programmers if you can deliver. Spring is very much in the technological domain, NO means a developer has to talk to users. Large organisations don't do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/167517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Best Voice Compression Algorithms/Formats We have some raw voice audio that we need to distribute over the internet. We need decent quality, but it doesn't need to be of musical quality. Our main concern is usability by the consumer (i.e. what and where they can play it) and size of the download. My experience has shown that mp3s do not produce the best compression numbers for voice audio, but I am at a loss for what the best alternatives are. Ultimately we would like to automate the conversion process to allow the consumer to choose the quality vs. size level that they would like. A: You should give Opus a try. Example compression command line: ffmpeg -i x.wav -b:a 32k x.opus A: Start here. As you rightly point out, voice compression is different from general audio compression. You'll find many codecs dedicated to telephony applications, ranging from PCM and ADPCM through later packet based encodings such as CELP used on GSM cellular networks. Still, VOIP voice encoding is slightly different from that due to the medium used. you can find a good, free (unencumbered and open source (BSD)) library for speech encoding/decoding in the Speex software library. Again, which you choose depends on the speech you're encoding and the medium it's being transmitted over. Also note that many libraries have several algorithms they can use depending on the circumstances, and some will even switch on the fly based on conditions of the sound and network. To get more help, narrow your question down. -Adam A: The most frequently used compression formats used in live voice audio (like VoIP telephony) are μ-Law (mu-Law/u-Law is used in the US) and a-Law (used in Europe, etc.) which, unlike Uncompressed PCM, don't support as wide of a frequency range (a smaller range of possible values ignores sounds outside of the necessary spectrum and requires less space to store). For usability sake it is easiest to use mpeg compressions (mp2/3/4) for streaming to standard media players as the algorithms are readily available and typically quite fast and almost all media players should support it, but for voice you might try to specify a lower bitrate or do your conversion from a lower quality file in the first place (WAV can be at several sampling rates and voice requires a much lower sampling rate than music or effects, it's basically like frame-per-second on video). Alternatively you can use Real Media, WMA or other proprietary formats, but this would limit usability since the users would require specific third party software for playback, though WMA has an excellent compression ratio as well as compression options specific to voice audio. A: Assuming your users will be running Windows, there is a WMA speech compression codec that you can use with the Windows Media Encoder SDK. Failing that, you can use ACM to use something like G723/G728, ADPCM, mu-law or a-law, some of which are installed as standard on Windows XP & above. These can be packaged inside WAV files. You'll need to experiment a little to find the right bitrate/quality (probably don't bother with mu-law or a-law). With voice data you can get away with quite low sample rates - e.g. 16000 or 8000, as there isn't much above 4Khz in the human spoken voice. A: I think AMR is one of the best speech codecs. I was using it about a year ago and I remember that quality was very good and size levels were rather small. One drawback, especially in your case is that, as far as I know, it isn't supported by wide range of media players. QuickTime and RealPlayer are two which I know to play .amr files. A: Try speex ... unencumbered by patents, good performance both sizewise and CPU-wise. I've been having good luck using it on iPhone.
{ "language": "en", "url": "https://stackoverflow.com/questions/167533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I declare a multi-column PK in MySQL I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns. A: CREATE TABLE table_name ( c1 INT NOT NULL, c2 INT NOT NULL, PRIMARY KEY (c1, c2) ) A: Try: create table ..... primary key (`id1`, `id2`) ) A: Example: CREATE TABLE `synthesis`.`INV_MasterItemList` ( `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `Customer_ID` INTEGER UNSIGNED NOT NULL, `Model_ID` INTEGER UNSIGNED NOT NULL, `Serial` VARCHAR(45) NOT NULL, PRIMARY KEY (`MasterItemList_ID`), UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`) ) A: An example (from osCommerce) : CREATE TABLE categories_description ( categories_id int DEFAULT '0' NOT NULL, language_id int DEFAULT '1' NOT NULL, categories_name varchar(32) NOT NULL, PRIMARY KEY (categories_id, language_id), KEY idx_categories_name (categories_name) );
{ "language": "en", "url": "https://stackoverflow.com/questions/167542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to know if there is a (compiled in/kernel module) device driver controlling a device on a running linux? How can I know if a device is supported on a running Linux and if so, which device driver controls it? For instance, lspci on a server (PowerEdge 2900) gives: 00:00.0 Host bridge: Intel Corporation 5000X Chipset Memory Controller Hub (rev 12) 00:02.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 2 (rev 12) 00:03.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 3 (rev 12) 00:04.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 4 (rev 12) 00:05.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 5 (rev 12) 00:06.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x8 Port 6-7 (rev 12) 00:07.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 7 (rev 12) 00:08.0 System peripheral: Intel Corporation 5000 Series Chipset DMA Engine (rev 12) 00:10.0 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.1 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.2 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:11.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:13.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:15.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:16.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:1c.0 PCI bridge: Intel Corporation 631xESB/632xESB/3100 Chipset PCI Express Root Port 1 (rev 09) 00:1d.0 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #1 (rev 09) 00:1d.1 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09) 00:1d.2 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09) 00:1d.3 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #4 (rev 09) 00:1d.7 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset EHCI USB2 Controller (rev 09) 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev d9) 00:1f.0 ISA bridge: Intel Corporation 631xESB/632xESB/3100 Chipset LPC Interface Controller (rev 09) 00:1f.1 IDE interface: Intel Corporation 631xESB/632xESB IDE Controller (rev 09) 00:1f.2 IDE interface: Intel Corporation 631xESB/632xESB/3100 Chipset SATA IDE Controller (rev 09) 01:00.0 PCI bridge: Intel Corporation 80333 Segment-A PCI Express-to-PCI Express Bridge 01:00.2 PCI bridge: Intel Corporation 80333 Segment-B PCI Express-to-PCI Express Bridge 02:0e.0 RAID bus controller: Dell PowerEdge Expandable RAID controller 5 04:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 05:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 06:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Upstream Port (rev 01) 06:00.3 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express to PCI-X Bridge (rev 01) 07:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01) 07:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01) 08:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 09:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 0b:02.0 Multimedia audio controller: Creative Labs SB Audigy (rev 03) 0b:02.1 Input device controller: Creative Labs SB Audigy Game Port (rev 03) 0b:02.2 FireWire (IEEE 1394): Creative Labs SB Audigy FireWire Port 10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02) How can I find: * *which device driver (kernel module) controls each device? *which device is controlled by a device driver compiled in the kernel (and not as a module) *which device doesn't have a device driver (compiled in or as a module)? This script (adapted from another in "Linux Kernel in a Nutshell") partially resolves #1: #!/bin/bash for i in $(find /sys/ -name modalias); do echo "----------------------------------" modalias=$(cat $i) echo "$(dirname $i) --> $modalias" /sbin/modprobe --config /dev/null --show-depends $(cat $i) 2>&1 done But there are some problems with it: * *I don't know of an automated way to convert /sys/devices/pci0000:00/0000:00:1e.0/0000:10:0d.0 --> pci:v00001002d0000515Esv00001028sd000001B1bc03sc00i00 to 10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02) *In some cases the devices are internal to the MB and I don't even know a way to find the real name of the device. For example: /sys/devices/platform/dcdbas --> platform:dcdbas /sys/devices/platform/iTCO_wdt --> platform:iTCO_wdt /sys/devices/LNXSYSTM:00 --> acpi:LNXSYSTM: /sys/devices/LNXSYSTM:00/device:00/PNP0C33:00 --> acpi:PNP0C33:PNP0C01: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00 --> acpi:PNP0A08:PNP0A03: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0d/PNP0200:00 --> acpi:PNP0200: and many others. *When the device driver is compiled in (or doesn't exist) the response is FATAL: Module _XXXX_ not found. Indicating there is no module for the device. In some cases the driver is compiled in (e.g.) /sys/devices/platform/serial8250 --> platform:serial8250 FATAL: Module platform:serial8250 not found. /sys/devices/platform/i8042 --> platform:i8042 FATAL: Module platform:i8042 not found. In other cases, the driver just doesn't exist. But I don't know a way to tell the difference. Does anyone know? A: I don't think you can get a 100% clear-cut answer that you can get in Windows device manager. * *A device may be controlled by several kernel modules (say nvidia + agpgart). *A kernel module may control more than one device (usbhid). *You can also have many-to-many relationship (usbcore + usbhid). A: Try HAL device manager, which is also available as "KDE HAL device manager" and "gnome-device-manager". Basically, these are frontends to the Hardware Abstraction Layer (HAL), which reads /sysfs/ et al. It gives information like "info.linux.driver", see the screenshot below: I'm sorry I don't know how to fiddle out this information yourself in sysfs, but it must be somewhere if HAL is able to find it :-) A: lspci -n will give you PCI ids that you can search for on the linux kernel driver database. This will tell you which kernel options to enable. A: Well this is a little late, and maybe at that time (2008) didn't even exists, but lspci -n or better lspci -k should fix the problem; for instance: 04:00.0 Network controller: Broadcom Corporation BCM4312 802.11b/g (rev 01) Kernel driver in use: wl Kernel modules: wl, ssb A: The following script will tell you which dynamically loaded drivers are running, although I would also like an automated way of figuring out which compiled in modules are actually in use also so I could de-bloat my kernel some more. #!/bin/bash /sbin/lsmod | tail -n+2 | cut -d" " -f1 | xargs /sbin/modinfo -n | sort ; I'm not sure how relevent the rest of this is to your question but thought you or others might find it useful. The following code will figure out which .config options control each of the dynamically loaded kernel modules, although I haven't figured out a way to do the same for dynamic modules in the ubuntu lum package yet ( this script is still a work in progress ): #!/usr/bin/perl -w use strict; use Getopt::Long; my ($kernConfigIn, $kernConfigOut, $kernSourceDir, $lumSourceDir, $lumConfigIn, $lumConfigOut, $help); GetOptions( 'ksd=s' => \$kernSourceDir, 'lsd=s' => \$lumSourceDir, 'kci=s' => \$kernConfigIn, 'lci=s' => \$lumConfigIn, 'kco=s' => \$kernConfigOut, 'lco=s' => \$lumConfigOut, 'help' => \$help); if ($help || !$kernSourceDir || !$lumSourceDir ) { Usage($0); } sub Usage { print "usage error\n"; exit; }; my @modules = `/sbin/lsmod | tail -n+2 | cut -d" " -f1 | xargs /sbin/modinfo -n | sort ;`; my @kconfig; foreach my $module (@modules) { my ($package, $path, $modName) = ( $module =~ m/\/((?:kernel)|(?:ubuntu))\/(.*)\/(.*)\.ko/) ; $package eq 'kernel' ? push @kconfig, kernel($package, $path, $modName) : ubuntu($package, $path, $modName); } # kernel package sub kernel { my ($package, $path, $modName) = @_; my $makefile = $kernSourceDir.$path."/Makefile"; # print "$package, $path, $modName\n"; # print "$makefile\n"; my $option; chomp($option = `cat $makefile | sed -n "s/^obj-\\\$(CONFIG_\\([A-Z0-9_]*\\))\\W*+=.*"$modName"\\.o.*/CONFIG_\\1/p"`); print "$option\n"; return $option; } # deal with lum configs sub ubuntu { } There is a script by Andreas Goelzer which with slight modification will turn off all unused kernel modules in your .config which significantly speeds up your compiles. You can find it here: http://andreas.goelzer.de/kernel-config-based-on-lsmod-output
{ "language": "en", "url": "https://stackoverflow.com/questions/167562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NUnit: Running multiple assertions in a single test I have been asked to write a testing application that needs to test a new stored procedure on multiple rows in a database, in essence I want to do something like this: [Test] public void TestSelect() { foreach(id in ids) { DataTable old = Database.call("old_stored_proc",id); DataTable new_ = Database.call("new_stored_proc",id); Assert.AreEqual(old.Rows[0]["column"],ne_.Rows[0]["column"]); } } When I run this test, if 1 row doesn't match the other, the entire test fails; instead I would like to count how many times the assertion was passed and how many times it has failed. Is there a way to do this with NUnit? I realize that NUnit might be overkill and this is a simple task without it...I just wanted to learn it. ;) A: Seems like you are just Asserting the wrong thing. If you want to check all the values and then assert that there are no errors (or show the number of errors) then try this: [Test] public void TestSelect() { int errors = 0; foreach(id in ids) { DataTable old = Database.call("old_stored_proc",id); DataTable new_ = Database.call("new_stored_proc",id); if (old.Rows[0]["column"] != new_.Rows[0]["column"]) { errors++; } } Assert.AreEqual(0, errors, "There were " + errors + " errors."); } A: 1) If the id's are constant and not looked up at test run time, create a separate unit test fixture for each id. That way you will know which id's are actually failing. See here for a write up on the problems with data driven tests: http://googletesting.blogspot.com/2008/09/tott-data-driven-traps.html 2) If you need to dynamically look up the id's making it impossible to create a fixture for each id, use akmad's suggestion with one change. Keep a list of id's where the values are not equal and add the list to the error message. It will be extremely difficult to diagnose a failing test that only states the number of errors, as you won't know what id's cause the errors. 3) I don't know how difficult it would be to do in NUnit, but in PyUnit, when we need to run tests on dynamically generated data, we dynamically create tests fixtures and attach them to the TestCase class so that we have a failed test for each piece of data that does not pass. Though I imagine this would be much more difficult without python's dynamic abilities. A: I know that the question is specifically about NUnit, but interestingly enough, Gallio/MbUnit has a feature which allows to run and catch several assertions at once. [Test] public void MultipleTest() { Assert.Multiple(() => { Assert.IsTrue(blabla); Assert.AreEqual(pik, pok); // etc. } } The Assert.Multiple is catching all the failing assertions and is going to report them at the end of the test. A: I would count the number of rows which do not match and then would write an assertion which will compare this number with 0 and would return the number of non matching strings in the message. you could also use Assert.Greater for this. P.S. In principal you should try to do one assertion per unit test. That's the gist of it. A: Well you could declare a counter and then assert the value of the counter to determine pass/fail Also, you could do the bulk of the work in the test setup, and then just create multiple tests. I'm not clear as to why you need all the assert stmts in the same test. A: Based on the objective you laid out, the entire test should fail if one row doesn't match another. Counting the number of times an assertion passes or fails gives you less information than a comparison of the outcome you expected with the outcome you actually got. A: I recently had the same issue. I combined the idea of counting errors with Yann Trevin's mention of Assert.Multiple into an extension method for IEnumberable that lets me do things like: [Test] public void TestEvenNumbers() { int[] numbers = new int[] { 2, 4, 12, 22, 13, 42 }; numbers.AssertAll((num) => Assert.That((num % 2) == 0, "{0} is an odd number", num)); } Which results in the NUnit output: TestEvenNumbers: 5 of 6 tests passed; 0 inconclusive FAILED: 13: 13 is an odd number Expected: True But was: False Expected: 6 But was: 5 And the solution to the OP's problem would be: [Test] public void TestSelect() { ids.AssertAll(CheckStoredProcedures); } private void CheckStoredProcedures(Id id) { DataTable old = Database.call("old_stored_proc",id); DataTable new_ = Database.call("new_stored_proc",id); Assert.AreEqual(old.Rows[0]["column"], new_.Rows[0]["column"]); } Here is the extension method (note that I used "All" instead of "Multiple" for consistency with Linq terminology): using System; using System.Text; using System.Collections.Generic; using NUnit.Framework; public static class NUnitExtensions { public static void AssertAll<T>(this IEnumerable<T> objects, Action<T> test) { int total = 0; int passed = 0; int failed = 0; int inconclusive = 0; var sb = new StringBuilder(); foreach (var obj in objects) { total++; try { test(obj); passed++; } catch (InconclusiveException assertion) { inconclusive++; string message = string.Format("INCONCLUSIVE: {0}: {1}", obj.ToString(), assertion.Message); Console.WriteLine(message); sb.AppendLine(message); } catch (AssertionException assertion) { failed++; string message = string.Format("FAILED: {0}: {1}", obj.ToString(), assertion.Message); Console.WriteLine(message); sb.AppendLine(message); } } if (passed != total) { string details = sb.ToString(); string message = string.Format("{0} of {1} tests passed; {2} inconclusive\n{3}", passed, total, inconclusive, details); if (failed == 0) { Assert.Inconclusive(message); } else { Assert.AreEqual(total, passed, message); } } } } A: You can use [TestCase()] attribute if a simple hard coded list of IDs. [Test] [TestCase(1234)] [TestCase(5678)] [TestCase(7654)] public void TestSelect(int id) { DataTable old = Database.call("old_stored_proc", id); DataTable new_ = Database.call("new_stored_proc", id); Assert.AreEqual(old.Rows[0]["column"], new_.Rows[0]["column"]); } This will generate three separate tests for each ID and whatever nunit test runner you use will display pass/fail counts. If need to generate a dynamic list of IDs then recommend using [TestCaseSource()] attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/167567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Problems executing compiled 3.5 code on a server which only has the 2.0 framework I can't seem to get my application up and running on my dev server and I'm not sure why. I have compiled my code in VS 2008 with a target framework of 3.5. I am using 3.5 mainly because I have implemented LINQ rather extensively. Compiling and runs local without any problems. The hang up is that my server only has the 2.0 .Net framework and upgrading to 3.5 is apparently not going to happen. I was under the impression after doing some research that as long as I was trying to execute compiled code the server would not need 3.5 installed. Today I am trying to publish to the server and I can't get past this error in my WEB.CONFIG Configuration Error Parser Error Message: Child nodes not allowed. providerOption name="CompilerVersion" value="v3.5"/ EDIT ADD ON QUESTION: I have seen some posts about possibly setting my references to "copy local" which might allow me to run on the 2.0 server. Thoughts? A: You are right in that 3.5 runs on the 2.0 CLR, but 3.5 contains libraries and if you have used any of those, you're out of luck unless you install 3.5 on that server. There are plenty of options for a 3.5 program to not run correctly on only 2.0, so I'd consider downgrading the program, or upgrading the server. Note regarding copy local. Even if you copy all the 3.5 libraries that your app uses, there is no guarantee it'll work and most likely it won't. Even so, distributing the libraries with your app is expressively prohibited by the .NET license. Since you have stated you use LINQ, the only legal way to get your app running is to install the 3.5 license. Or, you can rewrite your app using only 2.0. A: I'm pretty sure that LINQ is one of the things that makes 3.5 a requirement. A lot of the other things, like lambda expressions etc. are just compiler trickery. Because System.Linq is a 3.5 feature, the framework is required to be that version. A good way to determine would be to change the target framework to 2.0 and see if it builds. A: Code compiled against 3.0 or 3.5 may run on the 2.0 framework, but only if you do not use any libraries that are specific to the 3.0+ framework. One good way to find what's causing your code to fail is to switch your target to 2.0 and change things so that it compiles. Since one of your target installations is .NET 2.0, you are going to have to write .NET 2.0 code; this is not unique to .NET. In the past, writing an application that executed in both Win95 and WinNT involved extra work for the developer to carefully make sure the appropriate API was used. Technically, 3.5-targetted code can run on 2.0 with no problems, but there's some gotchas you have to watch for. If anything accesses something that is unavailable in .NET 2.0, that will fail. This doesn't happen when the application starts, it happens when the application tries to make the call. I tested this by making a console application that does a little bit of output, then tries to display a WPF window. The output is made, but the application throws an exception when it tries to display the window on a machine with nothing but .NET 2.0. Another gotcha is that VS 2008 actually comes with the .NET Framework 2.0 SP1, and there are a few types and methods in SP1 that are not in the normal 2.0 Framework. Visual Studio will not flag these methods as unsafe. Finally, if this is a web application, the default web.config file for 3.5-targeted projects is very different than the web.config file for 2.0-targeted projects. Make sure you're distributing a compatible web.config. This is likely the problem you are encountering. A cheap workaround might be to change your target to .NET 2.0, copy that web.config, and use it in this case. Keep in mind that if you are using any 3.0+-specific language features or types your code will still fail, but this should get you past the web.config. A: You're not going to be able to run code targetted to 3.5 on the server unless you get 3.5 installed on it. The problem isn't your code, rather that the required libraries will be missing. A: This is not possible. Although the CLR has not changed (like it did between v1.1 and v2.0) The libraries have. You cannot run a 3.5 app that doesn't have the 3.5 fraework installed. All of the Linq features are made possible by the 3.5 framework. A: One error is in Web.Config. The published Web.Config is setup to allow compilation from .NET 3.5, which is the reason it includes build provider information. Beyond that, your code won't run. By using LINQ, you're referencing assemblies that don't exist in .NET 2.0. A: You can may use of some C# 3 features whilst targeting .NET 2.0. Its the language features which by the time its compilied to IL will run on the 2.0 CLR regardless of whether that CLR is part of a 2.0 or higher framework install. Hence you can use anonymous types, extension methods and Lambda expressions but as soon as you do things like LINQ you then need external libraries that are part of 3.5 If you are only doing LINQ to Object you could add the LINQBridge to your distribution. Another problem you can run into is if you are shipping a web application that includes the source code, such as code behind files, in line code and .cs in the App_Code folder. You can end up shipping C# source code which compiles on the developement machine with C# 3 compilier present but fails to compile on a server only equiped with C# 2. In this case you can't use any new language features either. What's worse is that specifing the .NET 2.0 framework as the target in the Visual Studio doesn't stop you using C# 3 language features. You get no warnings that such syntax will not compile on a 2.0 machine. Hence if you are shipping such a web app, you'll need to compile pretty much everything first. A: I was just going to leave a comment by my rep is not quite there. I agree with the crowd so far and believe that lassevk's answer is the best so please give him the rep for that. One this I wanted you to know about though is that once you install 3.5 on your IIS server (6 or better). When you go to the IIS Manager and right click on your website to access the ASP.Net tab. You will see AFTER the install of the 3.5 Framework that there is no 3.5 option available. It will still show it as 2.0.50727. Don't worry about that, it will still work just fine. Because of this inconsistence (thanks Microsoft) some confusion has been caused. Actually I think this is why you may have thought that 2.0 would run your 3.5 code just fine. Hope this helps and anyone please edit this so it makes more sense. A: You can just copy over the 3.5 dlls onto the server. You can absolutely run 3.5 code on a 2.0 server.
{ "language": "en", "url": "https://stackoverflow.com/questions/167569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can one create package for ClearQuest? I am modifying ClearQuest database schema and I wonder is there a way to create a package for future deployment. If there isn't what are best practices for tracking and deployment of schema modifications? A: In your CQ installation path, look for this "cqload" tool. basically... * *cqoload exportintegration - Exports specific schame versions into a text file *cqload importintegration - Imports the exported text file into a CQ schema What is common practice is you at least have 2 CQ environments, a Dev/QA env, and a Production env. Developers work on the Dev/QA environments (checkout/modify/checkin) until they are happy, QA verified the changes in the same environment. Then the implementor will use cqload commands to transfer the changes to the production environment. Personally I think this workflow is retarded, as it requires so many manual process and it doesnt work properly if you have additional "Packages" upgrade or installation within CQ, e.g. UCM package, etc. Unfortunately I dont think this is gonna change anytime.
{ "language": "en", "url": "https://stackoverflow.com/questions/167572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if table exists in SQL Server I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements. Here are two possible ways of doing it. Which one is the standard/best way of doing it? First way: IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='mytablename') SELECT 1 AS res ELSE SELECT 0 AS res; Second way: IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; MySQL provides the simple SHOW TABLES LIKE '%tablename%'; statement. I am looking for something similar. A: I know it is an old question but I have found this possibility if you plan to call it often. create procedure Table_Exists @tbl varchar(50) as return (select count(*) from sysobjects where type = 'U' and name = @tbl) go A: Just adding here, for the benefit of developers and fellow DBAs a script that receives @Tablename as a parameter (which may or may not contain the schemaname) and returns the info below if the schema.table exists: the_name object_id the_schema the_table the_type [Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes. It raises an error when either you passed an empty string, wrong schema name or wrong table name. this could be inside a procedure and return -1 for example. As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases. This is how I achieved this: PRINT 'THE SERVER IS ' + @@SERVERNAME --select db_name() PRINT 'THE DATABASE IS ' + db_NAME() PRINT '' GO SET NOCOUNT ON GO --=================================================================================== -- @TableName is the parameter -- the object we want to deal with (it might be an indexed view or a table) -- the schema might or might not be specified -- when not specified it is DBO --=================================================================================== DECLARE @TableName SYSNAME SELECT @TableName = 'Facts.FactBackOrder' --=================================================================================== --=================================================================================== DECLARE @Schema SYSNAME DECLARE @I INT DECLARE @Z INT SELECT @TableName = LTRIM(RTRIM(@TableName)) SELECT @Z = LEN(@TableName) IF (@Z = 0) BEGIN RAISERROR('Invalid @Tablename passed.',16,1) END SELECT @I = CHARINDEX('.',@TableName ) --SELECT @TableName ,@I IF @I > 0 BEGIN --=================================================================================== -- a schema and table name have been passed -- example Facts.FactBackOrder -- @Schema = Fact -- @TableName = FactBackOrder --=================================================================================== SELECT @Schema = SUBSTRING(@TABLENAME,1,@I-1) SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I) END ELSE BEGIN --=================================================================================== -- just a table name have been passed -- so the schema will be dbo -- example Orders -- @Schema = dbo -- @TableName = Orders --=================================================================================== SELECT @Schema = 'DBO' END --=================================================================================== -- Check whether the @SchemaName is valid in the current database --=================================================================================== IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN RAISERROR('Invalid Schema Name.',16,1) END --SELECT @Schema as [@Schema] -- ,@TableName as [@TableName] DECLARE @R1 TABLE ( THE_NAME SYSNAME ,THE_SCHEMA SYSNAME ,THE_TABLE SYSNAME ,OBJECT_ID INT ,THE_TYPE SYSNAME ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME) ) ;WITH RADHE_01 AS ( SELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name] ,the_schema=SCHEMA_NAME(O.schema_id) ,the_table=O.NAME ,object_id =o.object_id ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END from sys.objects O where O.is_ms_shipped = 0 AND O.TYPE IN ('U','V') ) INSERT INTO @R1 ( THE_NAME ,THE_SCHEMA ,THE_TABLE ,OBJECT_ID ,THE_TYPE ) SELECT the_name ,the_schema ,the_table ,object_id ,the_type FROM RADHE_01 WHERE the_schema = @Schema AND the_table = @TableName IF (@@ROWCOUNT = 0) BEGIN RAISERROR('Invalid Table Name.',16,1) END ELSE BEGIN SELECT THE_NAME ,THE_SCHEMA ,THE_TABLE ,OBJECT_ID ,THE_TYPE FROM @R1 END A: In SQL Server 2000 you can try: IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME') BEGIN SELECT 1 AS 'res' END A: Looking for a table on a different database: if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable') print 'Exists' A: IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PutSchemaHere' AND TABLE_NAME = 'PutTableNameHere' ) A: Just wanted to mention one situation where it would probably be a little easier to use the OBJECT_ID method. The INFORMATION_SCHEMA views are objects under each database- The information schema views are defined in a special schema named INFORMATION_SCHEMA. This schema is contained in each database. https://msdn.microsoft.com/en-us/library/ms186778.aspx Therefore all tables you access using IF EXISTS (SELECT 1 FROM [database].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='mytablename') SELECT 1 AS res ELSE SELECT 0 AS res; will only reflect what is in [database]. If you wanted to check if tables in another database exist, without dynamically changing the [database] each time, OBJECT_ID will let you do this out of the box. Ex- IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; works just as well as IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; SQL SERVER 2016 Edit: Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the if exists keywords to drop statements. For example, drop table if exists mytablename will do the same thing as OBJECT_ID / INFORMATION_SCHEMA wrappers, in 1 line of code. https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/ A: IF OBJECT_ID('mytablename') IS NOT NULL A: Also note that if for any reason you need to check for a temporary table you can do this: if OBJECT_ID('tempdb..#test') is not null --- temp table exists A: We always use the OBJECT_ID style for as long as I remember IF OBJECT_ID('*objectName*', 'U') IS NOT NULL A: Something important to know for anybody who hasn't found their solution yet: SQL server != MYSQL. If you want to do it with MYSQL, it is quite simple $sql = "SELECT 1 FROM `db_name`.`table_name` LIMIT 1;"; $result = mysql_query($sql); if( $result == false ) echo "table DOES NOT EXIST"; else echo "table exists"; Posting this here because it's the top hit at Google. A: You can use this : IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL BEGIN print 'deleted table'; drop table t END else begin print 'table not found' end Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null) insert into t( name, lastname) values('john','doe'); insert into t( name, lastname) values('rose',NULL); Select * from t 1 john doe 2 rose NULL -- clean drop table t A: I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay. Here is the solution: SELECT COUNT(*) FROM <yourTableNameHere> So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it). The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver.. if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) { // myTable doesn't exist.. } A: IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG = 'Database Name' and TABLE_NAME = 'Table Name' and TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted BEGIN --TABLE EXISTS END ELSE BEGIN --TABLE DOES NOT EXISTS END A: I think the following query works: IF EXISTS (select * from sys.tables WHERE name='mytablename' ) BEGIN print 'table exists in the database' END A: Please see the below approaches, Approach 1: Using INFORMATION_SCHEMA.TABLES view We can write a query like below to check if a Customers Table exists in the current database. IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers') BEGIN PRINT 'Table Exists' END Approach 2: Using OBJECT_ID() function We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database. IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL BEGIN PRINT 'Table Exists' END Approach 3: Using sys.Objects Catalog View We can use the Sys.Objects catalog view to check the existence of the Table as shown below: IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U') BEGIN PRINT 'Table Exists' END Approach 4: Using sys.Tables Catalog View We can use the Sys.Tables catalog view to check the existence of the Table as shown below: IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U') BEGIN PRINT 'Table Exists' END Approach 5: Avoid Using sys.sysobjects System table We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly. IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U') BEGIN PRINT 'Table Exists' END referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/ A: Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in this answer. A: For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version. To check if a table exists use: IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable')) BEGIN --Do Stuff END A: You can use below code IF (OBJECT_ID('TableName') IS NOT NULL ) BEGIN PRINT 'Table Exists' END ELSE BEGIN PRINT 'Table NOT Exists' END Or IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName')) BEGIN PRINT 'Table Exists' END ELSE BEGIN PRINT 'Table NOT Exists' END A: IF EXISTS ( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') AND type in (N'U') ) BEGIN -- Do whatever you need to here. END Here in the above code, the table name is Mapping_APCToFANavigator. A: If you need to work on different databases: DECLARE @Catalog VARCHAR(255) SET @Catalog = 'MyDatabase' DECLARE @Schema VARCHAR(255) SET @Schema = 'dbo' DECLARE @Table VARCHAR(255) SET @Table = 'MyTable' IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG = @Catalog AND TABLE_SCHEMA = @Schema AND TABLE_NAME = @Table)) BEGIN --do stuff END A: IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 ) BEGIN SELECT * FROM dbo.TableName; END GO A: There is one more option to check if the table exists across databases IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name') BEGIN -- do whatever you want END A: If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code: let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema ) where oSchema !=null let o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null where o!=null given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is a A: select name from SysObjects where xType='U' and name like '%xxx%' order by name A: If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked. if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable') print 'Exists' A: -- -- create procedure to check if a table exists DELIMITER $$ DROP PROCEDURE IF EXISTS `checkIfTableExists`; CREATE PROCEDURE checkIfTableExists( IN databaseName CHAR(255), IN tableName CHAR(255), OUT boolExistsOrNot CHAR(40) ) BEGIN SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES WHERE (TABLE_SCHEMA = databaseName) AND (TABLE_NAME = tableName); END $$ DELIMITER ; -- -- how to use : check if table migrations exists CALL checkIfTableExists('muDbName', 'migrations', @output); A: i taking here creating a view as example. Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create IF Object_ID('TestView') IS NOT NULL DROP VIEW TestView GO CREATE VIEW TestView as . . . GO If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end. You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views DECLARE @SQL as varchar(4000) -- set to body of view SET @SQL = 'SELECT X, Y, Z FROM TABLE' IF Object_ID('TestView') IS NULL SET @SQL = 'CREATE VIEW TestView AS ' + @SQL ELSE SET @SQL = 'ALTER VIEW TestView AS ' + @SQL A: consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1. To do this open visual studio and do the following: Right click on t1, then Script table as, then DROP and Create To, then New Query Editor you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one. Thanks A: Run this query to check if the table exists in the database: IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL PRINT 'Table Exists';
{ "language": "en", "url": "https://stackoverflow.com/questions/167576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1387" }
Q: Access to old, no longer available, feed entries I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need. Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas. * *Google AJAX Feed API - will limit you to 250 items *Unofficial Google Reader API - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky. *Spinn3r - Costs a lot of money *Spidering the internet archive at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort *Yahoo! Feed API or Yahoo! Search BOSS - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds. *(thanks to Lou Franco) Bloglines Sync API - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first. *Other search engines/blog search/whatever? This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness? A: Bloglines has an API to sync accounts http://www.bloglines.com/services/api/sync You have to make an account, subscribe to the feed you want to download, but then then you can download based on Date, which can be way in the past. Not sure of the terms. A: The best answer I've found so far, is this: Google reader's unofficial API turns out to have a public access point for their feeds, which means there is no authentication needed. Use is as follows: http://www.google.com/reader/public/atom/feed/{your feed uri here}?n=1000 replace the text in the squigglies (including the squigglies themselves) with the feed URI you're interested in. More information about the precise arguments can be found here: http://blog.martindoms.com/2009/10/16/using-the-google-reader-api-part-2/ but remember to use the /public/ url if you don't want to mess with authentication
{ "language": "en", "url": "https://stackoverflow.com/questions/167577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is there a way to prevent the VB6 compiler from shuffling the contents of files? For reasons unknown, the VB6 compiler often likes to reorder the contents of .vbp files and the control descriptor block at the top of .frm files (The code that describes the properties of controls on the form. Code that you don't see in the IDE but you do see in a text editor and when doing diffs against the previous revision in version control.). This is monumentally annoying and very distracting when comparing revisions of a file. Is there a way to prevent this? A: I don't think there's much you can do about this. I've noticed the same problem: the IDE likes to rearrange things for seemingly no apparent reason. Some things I've noticed: * *When you use the SSTab control, VB likes to rearrange properties for tabs, especially the TabEnabled property. *For project files, it randomly rearranges the order in which files appear and I think I remember seeing cases where similar file types are not always grouped together and end up mixed in with the project properties. You don't have much control over this, unless you run all your VBP's through some type of sanitizer that groups like files together (forms in one group, modules in another group, etc.) and sorts them alphabetically or something, so that they remain consistent. One possible way to handle this could be to write an IDE add-on that automatically does this everytime you save changes to a project file, or come up with some batch process that will just recurse over your source directories and clean up all the VBP's in one go. *The IDE seems to randomly change the case of things; this seems to happen frequently to project references. Sometimes they are output in lower case, and other times they are output in upper case. You can get around this by choosing "Ignore Case" when you diff files in SourceSafe. *Control coordinates, such Top, Left, Height, and Width, can differ between two revisions of the same form. This is due to different developers using different screen resolutions and/or different screen DPI settings while working on the same form. If you aren't doing this already, I highly recommend that you get everyone to develop using the same resolution and same DPI setting. The differing values are caused by rounding errors that occur when logical screen coordinates at different resolutions/DPI settings are converted to twips, the default coordinate space that VB uses for laying out forms. Additionally, while I'm on the topic, make sure everyone has their display set to 96dpi, because if you develop VB forms at 120dpi, there is a really really good chance they won't display correctly on a display set to 96dpi. *There are probably other things I can't remember right now... As for the order of controls being changed in form files, this is normal, and you usually don't want to try rearrange the order of controls by hand if it happens to change from one revision of the form to the next. The order that the controls appear in a form file determines their Z-order on the form. If the order of the controls changes in the .frm file, this will change their relative Z-order on the form, which could lead to unintended results in how your forms are displayed. A: Can you make the .vbp file read-only when you aren't editing it (ie, adding modules, etc)? As far as form files...I can't think of any good way at all to make VB not reorder them. But I have to say that I've never encountered this before. Are you sure that something else isn't going on? It's entirely possible that I just never paid any attention to this in the past, so I'm not saying you are mistaken, just offering my own observations. A: I have noticed that re-opening the form and saving again often restores a consistent order.
{ "language": "en", "url": "https://stackoverflow.com/questions/167580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Visual Studio database project designers I have this huge legacy database that I'm trying to get under source control. I looked around here on stackoverflow and decided to use the Visual Studio 2008 database project, then committing stuff on svn. I successfully imported the schema into the project, but I can't find any way to use the user-friendly table designers with this kind of project. Whenever I open a table, it opens the DDL definition. I need the designers, otherwise I won't get buy-in from the team. Any suggestions/workarounds? A: I'd use Microsoft® Visual Studio Team System 2008 Database Edition GDR. Which scripts every object in it's own file so makes it easy to track in version control. For developers that don't want to use the tool let them develop in Management Studio and then use the Schema Compare tool in Database Edition to automatically extract out the changes from their development database into the project files when they are ready to check-in. You may be able to write some (cunning) Visual Studio macros to do the Schema Compare automatically with the minimum of clicking for developers. A: I found sql server management studio (express free or the full product) easier to use than visual studio database projects. The one good thing i liked about vs was that you could select multiple objects (e.g. all tables) in the server explorer and generate a single script for them. These are not easy to maintain but are good for a quick back up of all objects. Management studio has the table and query designers and also allows execution plans and client statistic to be displayed so you can optimize queries/sps if required. I have only used it with visual source safe for source control which works fine from Management Studio point of view, but vss is not great! (buggy, crashes, corrupts etc.) A: Try opening the Server Explorer (View > Server Explorer). You may need to add a connection and then you can to the database tables, right click them and choose "Show table data". 0nce you're there you get the Query Designer toolbar and you're able to use the table designers.
{ "language": "en", "url": "https://stackoverflow.com/questions/167586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loading Assemblies into separate AppDomain, getting InvalidCastException I'm trying to load assemblies in a separate app domain, but am running into a very strange problem. Here's some code: public static void LoadAssembly(string assemblyPath) { string pathToDll = Assembly.GetCallingAssembly().CodeBase; AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = pathToDll }; AppDomain newDomain = AppDomain.CreateDomain("AssemblyLoader",null,domainSetup); AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap( pathToDll, typeof(AssemblyLoader).FullName); } AssemblyLoader is another class in the same assembly as this one, and it inherits from MarshalByRef, however for some strange reason, I get a cast exception every time I try to run this. I even hardcoded the path to the DLL instead of using GetCallingAssembly().CodeBase yet I keep getting this exception. I understand it's hard to answer a question like this without actually seeing it and having more information, but maybe someone has run into a similar situation and would know the common "gotchas" and what I should look out for. EDIT: The reason I don't want to load it directly is because this is just part of the code. The ultimate goal is that this class will have a method that load assemblies, gets their GUID and some other info about them and stores them in a database for a project I'm working on. Therefore, if I load this assembly in a separate app domain, I can load the others there too and then unload the app domain. No point in having all these assemblies loaded for the duration of the app, if I only need that data. A: (EDIT: after reading the exception given, changing answer completely) It appears the problem is the CreateInstanceFromAndUnwrap call, which uses the LoadFrom semantics of 'pathToDll'. Suzanne Cook detailed the possible sticking point on her blog where your original AppDomain tries to call Load("SomeAssembly, [...]") as opposed to LoadFrom("pathToDll") when trying to resolve the type in question. Her advice was to hook the AssemblyResolve event on the current domain to do the correct LoadFrom in order to get the type. A little bit of targetted googling brings up a possible solution to the problem based on Suzanne's suggestion. A: I don't believe the PrivateBinPath configuration is necessary, beyond that you don't need to use the Path to the DLL, but rather the Assembly's fully qualified name for the first parameter; try: AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap( typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName); A: There's a lot of good information for what you're trying to do here: How to load a .NET assembly for reflection operations and subsequently unload it? A: Check out this article. Using the code in that article I got a cross app-domain object. I abstracted things a bit with generics and have three assemblies. (i.e. 1 defining the interface, 1 defining the plugin implementation, and the main program which tells the generic what to load.) The original articles code is easy to follow.
{ "language": "en", "url": "https://stackoverflow.com/questions/167587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I add Dispose functionality to a C# UserControl? I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this: protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away. A: I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind. A: All Component classes implement a Disposed event. You can add an event handler for that event and clean up things in there. For example, in your UserControl you could add following method: private void OnDispose(object sender, EventArgs e) { // do stuff on dispose } And in constructor (or in Load event handler) add the following line: Disposed += OnDispose; A: In VS 2005 (and 2008) you can update the Dispose method and it will not get removed when you edit the control from the designer. A: In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this. An other approach would be using a partial method (C# 3.0). A: You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten. A: You just need to overload the public void Dispose() method in the Component Class that the user control inherits. make sure you pass the call to the base method as well as doing your dispose functionally or you'll break the functionality unless you fully implement it A: I would think the cleanest way would be to have your control subscribe to its own Disposed() event and do your cleanup in there. A: there is a Unloaded event for the UserControl that you can use to clean up,
{ "language": "en", "url": "https://stackoverflow.com/questions/167602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: Should the Network Service Account receive temp file permissions by default? Recently I was working with generating a PDF from Crystal Reports through a webform. It was failing, which I determined to be caused by the permissions settings on the c:\windows\temp dir. I gave the Network Service account full access to this folder, which promptly fixed the issue. But is there a reason the Network Service account didn't have these permissions by default? Rick Strahl asks this question here. It sounds like there shouldn't be any issues with doing this, but Rick wasn't clear on why the default is set that way. Web Server is Windows Server 2003 A: These days, the default option will tend to be the more secure one. I don't think there's any other reason. I've had the same issue as you, and in my environment just gave the permission and moved on. This post suggests it is the fault of Crystal Reports, which is explicitly referencing %WINDIR%\Temp instead of using an API such as Path.GetTempPath(). In fact I have seen Path.GetTempPath() return %WINDIR%\Temp when running under the Network Service account on Windows 2003. A: This post on creating temp files has comments that support using the windows temp folder. An msdn article on using the Network Service account states that "if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access" This tells me that the default restriction to the temp folder isn't because the temp folder was singled out, but that all other locations besides the IIS root folder are restricted by default. A: %windows%\temp is not for general temp'ing and barfing around. It is crystal clear that Crystal Reports is abusing that directory. This happens a lot when developers are too lazy to boot up their machines with anything but an admin account. Every user (including Network Service) has their own temp space, with full access rights, under Documents & Settings. Winners don't act like CR, and use their own temp spaces. In short, there is nothing wrong with default permissions on win\temp. I believe it is simply meant for Windows' internal workings. (Then again, it would be much better for everyone concerned, if that directory never existed in the first place.)
{ "language": "en", "url": "https://stackoverflow.com/questions/167605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How best to modify my model in Spring MVC if I care about IOC I am building an application using Spring MVC. I want to make certain changes to my Model for every Controller in the application. In particular, I want to insert certain extra data into the model which will be present for all pages of the application. I could do this several ways: just add the data at the end of every Controller, use a subclass of Model that adds my extra data, use a subclass of ModelAndView that wraps my Model, use a subclass of VelocityView that wraps the Model before using it... I'm sure there are other options. But I have an "elegance" constraint: I don't want to write code in each and every Controller, I want this behavior defined in one-and-only-one place. Ideally, it would be controlled by my IOC bean config file. Does anyone have a recommendation of how to achieve this elegantly? A: Aspects are a good approach, but Spring MVC makes it even easier -- you can define a HandlerInterceptor that will be called before or after every time a request is handled. In the HandlerInterceptor postHandle method (in your class that implements the HandlerInterceptor interface) you can add your data to the ModelAndView. You define which handlers should be intercepted in your config file. A: You could take a look at using Aspects. Spring even has an AOP extension that you could use. In brief an aspect would allow you to define code once that would then get "woven" into your classes either when you compile the classes or when they are loaded by the classloader. It's relatively advanced stuff and isn't the most intuitive thing for new programmers to pick up, but it's intended to solve exactly the problem you're referring to. A: I might be wrong, but I suspect that you may have described your requirements incorrectly. You seem to be saying 'I want certain data to be added to my model, for all controllers'. I suspect that you mean 'I want certain data to be available for all views'. If my suspicions are correct, then adding the data to you model is polluting your model and violating the single responsibility principle. This is especially true if the same data is to be added to several models. Be careful that you are not just using your model as a convenient 'carrier' of the data - where the data doesn't really have anything to do with the model. Admittedly, I'm not completely familiar with the Spring MVC way of doing things, but a more detailed example of what you're trying to achieve may allow for a more informed discussion.
{ "language": "en", "url": "https://stackoverflow.com/questions/167609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bindable LINQ vs. continuous LINQ What are the major difference between bindable LINQ and continuous LINQ? •Bindable LINQ: www.codeplex.com/bindablelinq •Continuous LINQ: www.codeplex.com/clinq One more project was added basing on the provided feedback: •Obtics: obtics.codeplex.com A: May I draw your attention to another codeplex project? It's called Obtics and deals with the same issues (http://obtics.codeplex.com). It addresses both the first the second and the additional problem and takes reactivity to a very deep level (has a demonstration with a LINQ based raytracer). It claims full support for all LINQ statements an methods of the Enumerable class. It uses yet another mechanism to create live queries: var theResultSet = ExpressionObserver.Execute( () => from item in theSource where item.Age > 25 select item ).Cascade(); A: Another thing to keep in mind, although BindableLinq requires the ".AsBindable()" call in the LINQ statement, CLINQ requires that you use ContinuousCollection<T> instead of ObservableCollection<T>. After looking at both briefly, I think I'm going to go with bindable LINQ. A: Indeed; the main issue with Continuous LINQ is the inability to use any collection that implements the generic IEnumerable and INotifyCollectionChanged. Bindable LINQ has no problem with using custom collections implementing the two interfaces. A: Their are 2 problems both these packages try to solve: Lack of a CollectionChanged event and Dynamic result sets. There is one additional problem bindable solves, additional automatic event triggers. The First Problem both packages aim to solve is this: Objects returned by a LINQ query do not provide CollectionChanged events. Continuous LINQ automatically does this to all queries, with no change: from item in theSource select item ; Bindable LINQ does this when you add .asBindable to your query Source Object: from item in theSource.AsBindable() select item ; The Second Problem both packages aim to solve is: Result sets returned from a LINQ Query are static. Normally when you do a LINQ Query your result set is unchanged until you do a new query. With these two packages, your result set is updated whenever the source is updated. (bad for performance, good for realtime updates) Example var theSource = new ContinuousCollection<Customer>(); var theResultSet = from item in theSource where item.Age > 25 select item; //theResultSet.Count would equal 0. Because your using Bindable or Continuous LINQ, you could modify theSource, and theResultSet would automatically include the new item. theSource.Add(new Customer("Bob", "Barker" , 35, Gender.Male)); //Age == 35 //theResultSet.Count would now equal 1. The Additional Problem Bindable LINQ offers: (Quoting directly from their own page) contactsListBox.ItemsSource = from c in customers where c.Name.StartsWith(textBox1.Text) select c; Bindable LINQ will detect that the query relies on the Text property of the TextBox object, textBox1. Since the TextBox is a WPF control, Bindable LINQ knows to subscribe to the TextChanged event on the control. The end result is that as the user types, the items in the query are re-evaluated and the changes appear on screen. No additional code is needed to handle events. A: Use bindable LINQ, as it implements IDisposable, and therefore you can control when a query gets disposed. When you dispose it, all the subscriptions to INotifyPropertyChanged will unsubscribe. Continuous LINQ is supposed to solve this problem with weak events, but it doesn't work as far as I was able to test. Hmm... this seems to be a problem with bindable LINQ (the second assert fails): var _source = CreateSource_6People(); //(David, 27), (Mark, 15), (Steve, 30), (Jordan, 43), (Shiva, 30), (Erb, 43) IBindable<int> bindable = _source.AsBindable().Sum(x => x.Age); var agesSum = 27+15+30+43+30+43; Assert.AreEqual(agesSum, bindable.Current); //PASSES _source[0].Age += 1; Assert.AreEqual(agesSum + 1, bindable.Current); //FAILS... DISAPPOINTING A: I think Bindable LINQ and continuous LINQ are about the same: they provides observing for changes in LINQ computation. Implementation and API provided may some differ. It seems my ObservableComputations library covers functionality expected from Bindable LINQ and continuous LINQ and has no problems mentioned in https://stackoverflow.com/a/174924/2663791. That library works with INotifyPropertyChanged and INotifyCollectionChanged interfaces, that makes it possible to operate with ObservableCollection direcly. Using that library you can code like this: using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using IBCode.ObservableComputations; namespace ObservableComputationsExamples { public class Order : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public int Num {get; set;} private decimal _price; public decimal Price { get => _price; set { _price = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Price))); } } public Order(int num, decimal price) { Num = num; _price = price; } } class Program { static void Main(string[] args) { ObservableCollection<Order> orders = new ObservableCollection<Order>(new [] { new Order(1, 15), new Order(2, 15), new Order(3, 25), new Order(4, 27), new Order(5, 30), new Order(6, 75), new Order(7, 80), }); //******************************************** // We start using ObservableComputations here! Filtering<Order> expensiveOrders = orders.Filtering(o => o.Price > 25); checkFiltering(orders, expensiveOrders); // Prints "True" expensiveOrders.CollectionChanged += (sender, eventArgs) => { // see the changes (add, remove, replace, move, reset) here }; // Start the changing... orders.Add(new Order(8, 30)); orders.Add(new Order(9, 10)); orders[0].Price = 60; orders[4].Price = 10; orders.Move(5, 1); orders[1] = new Order(10, 17); checkFiltering(orders, expensiveOrders); // Prints "True" Console.ReadLine(); } static void checkFiltering( ObservableCollection<Order> orders, Filtering<Order> expensiveOrders) { Console.WriteLine(expensiveOrders.SequenceEqual( orders.Where(o => o.Price > 25))); } } } Please, add ObservableComputations library to the list in the question (after Obtics).
{ "language": "en", "url": "https://stackoverflow.com/questions/167622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Migration To Trac We are managing our development with Subversion over HTTPS, Bugzilla, and Mediawiki. Some of our developers have expressed an interest in migrating to Trac, so I have to evaluate what the cost of doing so would be. For both the wiki and bugzilla, we would need to either migrate the existing data into Trac or a way to integrate with trac. Having two apps to create wiki pages or log bugs would not be acceptable. Also, currently each of these applications requires a separate sign on so we would need to map each of these accounts into Trac. So know of any easy methods of importing or integrating these systems with Trac and/or a tutorial for doing so? A: Wiki pages If you could export your pages to text files you could import them using the Trac-Admin: http://trac.edgewall.org/wiki/TracAdmin wiki import command. Some formating clean-up migration might be in order Tickets/Bugs * *This script by Tom Lazar give you ability to synchronize the tickets system with a CSV file. *This gives you an ability to migrate from BugZilla: http://bitten.edgewall.org/wiki/TracImport *You could also check out this resource: http://trac.edgewall.org/wiki/TracSynchronize A: For Bugzilla, Trac has a script bugzilla2trac.py that will automate the process of importing Bugzilla bugs to Trac tickets for you. Of course, Trac doesn't have support for blocking/blockedby tickets out of the box, so if you want to import this data too, you'll have to use the MasterTicketsPlugin and then modify the script yourself (which is what we did when we migrated). A: For MediaWiki there exists a script as well: http://trac.edgewall.org/ticket/5241 It has some bugs, but imports all important information (pages, revisions, images, users). Together with the other mentioned script you should be able to migrate to Trac. A: One thing that is not covered (yet) by the import script is the resolution of bugzilla links of the kind bug X or bug X comment Y. One solution for this is to use the RegexLinkPlugin (http://trac-hacks.org/wiki/RegexLinkPlugin) with the following configuration in the trac.ini file: [regexlink] regex1=\bbug (?P<bug_id_comment>\d+) comment #(?P<commentid>\d+)\b url1=http://your.trac.instance.com/ticket/\g<bug_id_comment>#comment:\g<commentid> regex2=\bbug (?P<bug_id>\d+)\b url2=http://your.trac.instance.com/ticket/\g<bug_id>
{ "language": "en", "url": "https://stackoverflow.com/questions/167628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using ldconfig on Linux Let's say I 've added a library foo.so.1.1.1 to a path that is included in /etc/ld.so.conf When I run ldconfig on the system I get the links foo.so.1.1 and foo.so.1 to foo.so.1.1.1 How can I change the behavior to also get the foo.so link to foo.so.1.1.1? A: Just make the symlink yourself: ln -s /usr/lib/foo.so.1.1.1 /usr/lib/foo.so Note that for applications to use libraries in this manner, they need to be explicitly linked against the unversioned shared object. IE: this is a mechanism to bypass the dynamic loader's version matching system completely. A: ldconfig looks inside all shared objects that it finds, to look for the soname. It then creates a link using that soname as the name of the link. It's conventional (but far from universally done) for the soname to be the name and major version of the library, so your library foo.so.1.1 will have a soname of foo.so.1 and ldconfig will make a link called that. No part of the run-time system looks for or knows anything about the name foo.so. That's used when you link your programs to the library. There's no point in having that link unless you also have all the other development files (headers etc) for the library, so there's no point in ldconfig automatically creating it. And since the name of the link to use is only another convention, and in this case isn't stored inside the file at all, there's no way for ldconfig to know what name to create. Normally this would be created manually, in the install target of the Makefile; when a library is packaged for a linux distribution the link normally lives in the -dev package along with the header files.
{ "language": "en", "url": "https://stackoverflow.com/questions/167635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How to INSERT an array of values in SQL Server 2005? How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration? A: Simple way to concatenate the values into a list and pass it to the sp. In the sp use dbo.Split udf to convert back to resultset (table). Create this function: CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1)) returns @Results TABLE (Items nvarchar(4000)) as begin declare @index int declare @slice nvarchar(4000) select @index = 1 if @String is null return while @index != 0 begin select @index = charindex(@Delimiter,@String) if @index !=0 select @slice = left(@String,@index - 1) else select @slice = @String insert into @Results(Items) values(@slice) select @String = right(@String,len(@String) - @index) if len(@String) = 0 break end return end and then try: select * from dbo.split('a,b,c,d,e,f,g,h,i,j,k,l', ',') A: I construct the list as an xml string and pass it to the stored procs. In SQL 2005, it has enhanced xml functionalities to parse the xml and do a bulk insert. check this post: Passing lists to SQL Server 2005 with XML Parameters A: I understand that you are talking about writing stored procedure to accept array of values With SQL Server 2005 you would need to use XML variable SQL 2008 adds support to table variable as parameters Here you can find good examples of passing a table to a stored procedure as XML and as table variable (SQL Server 2008) A: If your data is already in the database you could use INSERT SELECT syntax. It's slightly different from INSERT VALUES one... INSERT recipient_table (field1, field2) SELECT field1_from, field2_from FROM donor_table WHERE field1_from = 'condition'
{ "language": "en", "url": "https://stackoverflow.com/questions/167643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Will targeting IE8 with conditional comments work? When IE8 is released, will the following code work to add a conditional stylesheet? <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="ie-8.0.css" /> <![endif]--> I've read conflicting reports as to whether this works with the beta. I'm hoping someone can share their experience. Thanks. A: Tools/Compatability view settings uncheck them all A: One thing to note: It does work, BUT if you are loading the page/site local network (e.g. Intranet) it will load in IE7 mode by default! (update - localhost[*] is a special case, that does render in standards mode) This goes against MSFT's original statement of going STANDARDS by default. e.g. http://127.0.0.1/mysite/mypage.php <-- IE8 by default (updated!) http://localhost/mysite/mypage.php <-- IE8 by default (updated!) http://machinename/mysite/mypage.php <-- IE7 by default http://192.168.100.x/mysite/mypage.php <-- IE7 by default http://google.com/ <-- IE8 by default [*] - Scott Dickens [MSFT] noted in a comment here on the IE Blog that localhost was a special scenario in the Intranet (often used to develop Internet sites) thus would render in Standards mode by default. To test what mode a page in IE8 is really rendering in, you can use check the developer tools or use this bookmarklet code (only works in IE8): javascript: var vMode=document.documentMode; var rMode='IE5 Quirks Mode'; if(vMode==8){ rMode='IE8 Standards Mode'; } else if(vMode==7){ rMode='IE7 Strict Mode'; } alert('Rendering in: '+rMode); A: It worked for me – both in quirks mode and in standards compliance mode. However, it does not work when switching to IE8 compatibility mode. A: Thank you for your help. I've discovered the solution, apparently the problem was having each style sheet use its own title attribute. Once I took the title off all but the main style sheet, no prob. This is a weird issue unique to IE8 - and although I've been told its supposed to work that way, something to do with "Stylesheet Preference" - it only serves to create problems since the solution requires you remove the title which could be helpful when scripting, etc - when you need to call the style sheet. In any case, not sure if this is a bug, or its supposed to be that way, but I hope Microsoft investigates further. Thanks A: Why even bother writing a separate stylesheet for IE8? If you've already debugged for IE7, you can force IE8 into compatibility mode, and thus display your code as though IE8 were IE7. All you gotta do is put this RIGHT BELOW the opening head tag. Anywhere else and it won't work. And then that's a half hour or so less work on average per project, no intense debugging for IE8 needed! Even Msn.com does this - kind of ironic, eh? Wrote a blog post about it recently: http://blog.sankhomallik.com/2009/11/16/stop-wasting-time-debugging-on-ie8-when-you-dont-have-to-or-get-ie8-to-behave-like-ie7/ A: IE8 renders pretty nice compared to IE7, I have stylesheets for IE6, IE7 and IE8; at first i thought conditional comments were not working for IE8 after a bit of experimentation i found some rules were not beeing applied by IE8 just because i needed to put the ancestor or parent class first, e.g. i had a class like .niceclass {some:properties;more:properties;} it worked only if i changed it for something like: .parentclass .niceclass {some:properties;more:properties;} or #parentselector .niceclass {some:properties;more:properties;} btw in my IE8-only css i have only one overriding rule, the rest is rendered almost like firefox, though thats not making me leave FF anyway!. A: For my part I wanted to use rounded borders using css. IE8 on Vista does not support such. And since the graphics were so that the rounded borders would show a nice rounded shadow as well, the page looked terrible in IE8. I tried using conditional comments, but to no avail, IE8 would not evaluate the if IE expression and thus would not include the external stylesheet. Then I had a look at putting it into quirks / compatiblity mode, however, this still did not work as the CSS hacks I had used did no longer work for the IE8. Last but least I found a working CSS hack that will render the page correctly when in compatibility mode. * + html #test[id] { color:lime } Now, I do not know if this works for IE7 or below, so you would have at least three different hacks for each IE release you want to support, e.e. * + html #test, html+body #test, * html body #test { color:lime } I wonder what the next regression of the Internet Exploiter will behold for us.
{ "language": "en", "url": "https://stackoverflow.com/questions/167657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to change NSIS Error message about CRCCheck Some of my users are complaining about some odd errors my installers had after downloading them from my web server. This are NSIS installer that when downloaded came crippled or incomplete (usually because of slow Internet connections), the message is very clear "The installer you are trying to use is corrupted or incomplete....." IN ENGLISH!! (Did I mention my users only speak Spanish?). How do I change the language or create custom error messages? I already create the installer in Spanish by using: ; Language files !insertmacro MUI_LANGUAGE "Spanish" Any Idea? A: The CRC check runs before you/nsis can access the langstrings, so the only way to change this message is to recompile the source code. The message was changed several versions ago and now includes a URL to the NSIS wiki, one would think your users would be able to run a translator on that page A: I haven't done an NSIS package since it was referred to as Super Pimp (great name). See if this helps: NSIS Language Table
{ "language": "en", "url": "https://stackoverflow.com/questions/167667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any problems with SVN merge on a multi column ( tab delimited ) text file? I have a multi-column text file ( tab delimited ) that I use for localized text in my project. I picked this format since it can easily be edited by anyone in most text editors (and excel too). My makefile processes it into a bunch of defines and binary data for including directly into my app. Do you know if SVN merge only does line by line merging or can it so sub-line merging too? For example: Original File ( untranslated ) contains: DEFINE ENGLISH GERMAN FRENCH STRING_YES YES *YES* *YES* STRING_NO NO *NO* *NO* Then the french tranlator updates it: DEFINE ENGLISH GERMAN FRENCH STRING_YES YES *YES* OUI STRING_NO NO *NO* NON Then the german tranlator updates it: DEFINE ENGLISH GERMAN FRENCH STRING_YES YES JA *YES* STRING_NO NO NEIN *NO* Then they both merge the results back int SVN, so will they overwrite each others changes or can it handle mulitple changes on a line? A: It is line by line. * *The person who tries to commit later will get 'out of date' error, and when they try to update it, they will get a conflict in changed lines. *Same with the merge. The one who merges later will have to sort out conflicts manually. A: SVN merge is line by line, so in the situation you outline, conflicts would be created and would have to be merged by hand. However, with decent merge tools, the translators themselves could probably handle this - the tools can show differences character by character. TortoiseSVN is the de facto Windows SVN client, which includes TortoiseMerge (screenshot). There are several merge tools in Linux, Meld being my current (gnome) favorite. There are also several Mac clients that I'd expect to have this feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/167670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }