text
stringlengths
8
267k
meta
dict
Q: Xcode: 'Generics are not supported in -source 1.3' compiler error? just a quick question: I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: dictionary = new ArrayList<String>(); I get the following error: generics are not supported in -source 1.3. I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0_13. Thank you. A: Java support in Xcode is obsolete and unmaintained; it's the only bit of Xcode that still uses the "old" build system inherited from Project Builder. Even Apple suggests using Eclipse instead. For Java, both Eclipse and NetBeans work quite well on the Mac; if you want to try native Mac programming, use Objective-C and Cocoa, for which Xcode is fine. That said, the problem is that javac is targeting Java 1.3, which doesn't have generics. You can modify the javac reference in the Ant buildfile (build.xml) as follows: <target name="compile" depends="init" description="Compile code"> <mkdir dir="${bin}"/> <javac deprecation="on" srcdir="${src}" destdir="${bin}" source="1.3" target="1.2" Change "source" and "target" to "1.5". A: Generics are introduced in Java 5, so you can't use generics with -source 1.3 option. A: The build.xml file is placed in /Developer/Library/XCode/Project Templates/Java/Java Tool/build.xml (replace Java Tool with your own kind of project). If you look for source="XX" target="YY" in line 30, and change XX and YY to your preferred values, things go better, much as explained in the previous posts. Cheers, Pieter
{ "language": "en", "url": "https://stackoverflow.com/questions/109948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How should I organize my ASP.Net themes and common CSS files I am currently working on a project where a programmer who fancied themselves a graphic designer attempted their hand at ASP.Net themes. The CSS is pretty bad, but that is another question altogether. What I really need help with is the best way to organize ASP.Net Themes and the CSS that lies within them. Imagine that there is a directory structure that looks something like this: * *Themes * *Theme A * *StyleA.css *Common.css *Theme B * *StyleB.css *Common.css *Theme C * *StyleC.css *Common.css Each theme has a common stylesheet in it. Unfortunately the author of those style sheets managed to change only a few things here and there in each copy of Common.css. Eventually I will evaluate whether or not those changes are even necessary, but some major cleanup needs to happen first. For now just assume that the changes, ever so small, are necessary for things to look right with each theme. I would like to know what the best practices are for using themes while also needing some common styles across your application. I want to minimize the number of AppTurns in the page load, but I really want to consolidate common styles into one place in a way that maintains the ease of themes. A: You should just include the standard/common css in the website and include it in the head of the masterpage instead of placing it in themes. A: I have written a small article about that: http://www.sambeauvois.be/blog/2010/01/dont-repeat-your-common-css-between-your-different-themes/ I'll complete it with more information later A: Yes, just reference the common CSS file directly instead of putting it in the theme folders. A: But what if you have a webpage in a sub folder that uses the masterpage? Won't the page to the css file be wrong then?
{ "language": "en", "url": "https://stackoverflow.com/questions/109970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why should I use RSpec or shoulda with Rails? I am setting up a rails app and I just finished making some unit tests and my friend said that apparently fixtures are no longer cool and people are now using RSpec or shoulda. I was wondering what the actual benefits are to use these other toolkits. Any information at all is appreciated. -fREW A: There are two different things here: The first thing is what framework to use for writing tests/specs. Here you can choose between Test::Unit, RSpec, Shoulda and so on. The choice is whether you want to do traditional TDD (Test::Unit) or whether you prefer the alternative ways of thinking about specifiying behaviour advocated by developers like David Chemlinsky (RSpec and to some extent Shoulda). The second thing is how to handle test data. There are Rails fixtures and alternatives desgined with other goals such as the FixtureReplacement plugin. Before Rails 2.0 fixtures had significant and well-documented pratical problems. Many of the practical issues were fixed in Rails 2.0. However fixtures can lead to inadvertent test coupling and some of the alternatives try to avoid this. A: RSpec is way more powerful because it's far easier to both read and write tests in. It's also very elegant when using mocks and stubs, a concept which will become extremely useful once you start using them in your tests. Try it in a simple test app (NON RAILS!) and you'll see how elegant your specs are versus the equivalent standard testing. A: Check out Josh Susser's The Great Test Framework Dance-off for a comparison of the popular Ruby testing frameworks. A: I personally prefer Shoulda to RSpec. I find that Shoulda has less magic syntax than RSpec. My problem with RSpec is that yeah it's very readable when I read it aloud, but when I get to writing it, hmmmm, I'm never sure how a given assertion should be written. Prag Dave explains the problem better than me. He also likes Shoulda and has a few examples. A: If you are building a large application and don't have a team that are all really good at writing decoupled code that can be well-tested with black box tests and are prepared to fully embrace using/debugging lots of mocks & stubs, don't go down the Factory road. Wherever you read about how Awesome Factories Are you'll see a little caveat about how factories might not be feasible in a large application because they are a little slower than fixtures. But "a little slower" is really orders of magnitude slower. Factories are not significantly easier to code than fixtures that use labels for ids, so long as you keep the fixtures organized. And in some cases factories are harder to debug. Just tonight I converted a single factory to fixtures, and the runtime of the test file that used it went from 65 seconds to 15 seconds, even though only about 15% of the tests in that test file use that factory. If you use minitest you can run your tests in random order; this will quickly reveal any data coupling between tests. (not sure if rspec has the option to randomize test order) A: RSpec and similar frameworks are tooling designed to aid in Behavior Driven Development. They're not just a prettier way to write tests, though they do help with that. There is plenty of information on BDD here: http://behaviour-driven.org/ And wikipedia: http://en.wikipedia.org/wiki/Behavior_Driven_Development There are too many benefits to list here, so I'd recommend browsing that site a little. A: Test::Unit is good for small applications. But there are a lot of benefits to use testing frameworks like Shoulda or RSpec, e. g. contexts!! I don't see Shoulda and RSpec in an either-or-relation. I use Shoulda as a substitute for RSpec when it comes to single-assertion testing. I really like the Shoulda one-liners, but writing matchers is much easier in RSpec. So my advise is to use the different testing tools where they fit best. A: You may use testing framework like Cucumber which is even more faster than RSpec..
{ "language": "en", "url": "https://stackoverflow.com/questions/109976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: How can I get a hardware-based screen capture? In the past, some of my projects have required me to create a movie version of a fullscreen Flash application. The easiest way to do this has been to get a screen capture. However, capturing anything over 1024x768 has resulted in choppy video, which is unacceptable. I understand that there are hardware based solutions for capturing fullscreen video, but I have not been able to find out what these are. My output needs to be scalable up to 1920x1080 and result in an uncompressed AVI file with no choppy-ness. A: Various professional products support full HD capture: http://www.decklink.com/products/hd/ http://www.aja.com/ There are others. Capturing the full, uncompressed digital or analog stream is a pretty heavy requirement. -Adam A: If the Flash application is non-interactive, there are many tools that can get non-realtime capture (but completely smooth and perfect) to either an AVI file or a series of PNGs. If it is interactive and you absolutely need realtime capture, FRAPS might actually be able to do the job, at least on Vista, where its not usually that difficult to manipulate FRAPS into recording various non-DirectShow applications by using Aero as a graphics layer. A: If you load the movie into the Flash ActiveX control you can invoke the IViewObject::Draw method (or the OleDraw helper function) on the control to paint it into a DC of your choosing and loop through each frame in the animation. Extracting the audio will be more difficult, but if you've made the animations in-house that shouldn't be too much trouble. A: With a bit of luck your graphic adapter already has a analog video output. You could hook up a dvd recorder and just digitze the video signal on a stand alone hardware box. That won't give you 1920x1080 though. If you really need to get captures higher than dvd resolution you need professional (and incredible expensive) video capture equipment. edit: Btw - if you want to capture 1920x1080 in true color at 30 frames per second uncompressed you have to somehow store around 237 megabytes per second. Just to give you an idea how much data you have to deal with... A: Phillips dvdr3575h and other set-top boxes may be the simplest. However, I don't believe they support the resolution you are looking for. A: If you don't need to click around in the movie Flash CS3 supports frame by frame export of Flash movies (including scripted stuff). Open up your animation in Flash, if you don't have a .fla available making a simple wrapper that loads your swf should work too. Then go File -> Export -> Export movie, and choose Quicktime. Set the various fiddly bits to your liking, and then Flash will step through your animation as fast as it can, saving you both the risk of dropped frames and having to wait for a 1 fps capture. A: http://rgb.com/ I've looked at their product before - very high end/expensive but perfect video and it's a hardware solution so it's not processor intensive on the machine you are trying to do the demo on.
{ "language": "en", "url": "https://stackoverflow.com/questions/109993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you protect your software from illegal distribution? I am curious about how do you protect your software against cracking, hacking etc. Do you employ some kind of serial number check? Hardware keys? Do you use any third-party solutions? How do you go about solving licensing issues? (e.g. managing floating licenses) EDIT: I'm not talking any open source, but strictly commercial software distribution... A: Digital "Rights" Management is the single biggest software snake-oil product in the industry. To borrow a page from classic cryptography, the typical scenario is that Alice wants to get a message to Bob without Charlie being able to read it. DRM doesn't work because in its application, Bob and Charlie are the same person! You would be better off asking the inverse question, which is "How do I get people to buy my software instead of stealing it?" And that is a very broad question. But it generally starts by doing research. You figure out who buys the type of software you wish to sell, and then produce software that appeals to those people. The additional prong to this is to limit updates/add-ons to legit copies only. This can be something as simple as an order code received during the purchase transaction. Check out Stardock software, makers of WindowBlinds and games such as Sins of a Solar Empire, the latter has no DRM and turned a sizable profit off a $2M budget. A: There are many, many, many protections available. The key is: * *Assessing your target audience, and what they're willing to put up with *Understanding your audience's desire to play with no pay *Assessing the amount someone is willing to put forth to break your protection *Applying just enough protection to prevent most people from avoiding payment, while not annoying those that use your software. Nothing is unbreakable, so it's more important to gauge these things and pick a good protection than to simply slap on the best (worst) protection you are able to afford. * *Simple registration codes (verified online once). *Simple registration with revokable keys, verified online frequently. *Encrypted key holds portion of program algorithm (can't just skip over the check - it has to be run for the program to work) *Hardware key (public/private key cryptography) *Hardware key (includes portion of program algorithm that runs on the key) *Web service runs critical code (hackers never get to see it) And variations of the above. A: There are several methods, such as using the processor ID to generate an "activation key." The bottom line is that if someone wants it bad enough -- they'll reverse engineer any protection you have. The most failsafe methods are to use online verification at runtime or a hardware hasp. Good luck! A: Given a little time your software will always be cracked. You can search for cracked versions of any well known piece of software in order to confirm this. But it is still well worth adding some form of protection to your software. Remember that dishonest people will never pay for your software and always find/use a cracked version. Very honest people will always stick to the rules even without a licensing scheme just because that is the kind of person they are. But the majority of people are between these two extremes. Adding some simple protection scheme is a good way of making that bulk of people in the middle act in an honest way. It is a way to nudge them into remembering that the software is not free and they should be paying for the appropriate number of licenses. Many people do actually respond to this. Businesses are especially good at sticking to the rules because the manager is not spending his/her own money. Consumers are less likely to stick to the rules because it is their own money. But recent experience with releases such as Spore from Electronic Arts shows that you can go to far in licensing. If you make even legit people feel like criminals because they are constantly being validated then they start to rebel. So add some simple licensing to remind people if they are being dishonest but anything more than that is unlikely to boost sales. A: Online-only games like World of Warcraft (WoW) have it made, everyone has to connect to the server every time and thus accounts can be constantly verified. No other method works for beans. A: Generally there are two systems that often get confused - * *Licensing or activation tracking, legal legitimate usage *Security preventing illegal usage For licensing use a commercial package, FlexLM many companies invest huge sums of money into licensing think they also get security, this is a common mistake key generators for these commercial packages are prolifically abundant. I would only recommend licensing if your selling to corporations who will legitimately pay based on usage, otherwise its probably more effort than its worth. Remember that as your products become successful, all and every licensing and security measure will be breached eventually. So decide now if it is really worth the effort. We implemented a clean room clone of FlexLM a number of years ago, we also had to enhance our applications against binary attacks, its long process, you have to revisit it every release. It also really depends on which global markets you sell too, or where your major customer base is as to what you need to do. Check out another of my answers on securing a DLL. A: Whatever route you go, charge a fair price, make it easy to activate, give free minor updates and never deactivate their software. If you treat your users with respect they'll reward you for it. Still, no matter what you do some people are going to end up pirating it. A: Don't. Pirates will pirate. No matter what solution you come up with, it can and will be cracked. On the other hand, your actual, paying customers are the ones who are being inconvenienced by the crap. A: Make it easier to buy than to steal. If you put mounds of copy protection then it just makes the value of owning the real deal pretty low. Use a simple activation key and assure customers that they can always get an activation key or re-download the software if they ever lose theirs. Any copy protection (aside from online-only components like multiplayer games and finance software that connects to your bank, etc.) you can just assume will be defeated. You want downloading your software illegally, at the very least, to be slightly harder than buying it. I have a PC games that I've never opened, because there is so much copy protection junk on it that it's actually easier to download the fake version. A: As has been pointed out, software protection is never guaranteed to be foolproof. What you intend to use depends largely on your target audience. A game, for instance, is not something you are going to be able to protect forever. A server software, on the other hand, is something far less likely to be distributed on the Internet, for a number of reasons (product penetration and liability come to mind; a large corporation does not want to be held liable for bootleg software, and the pirates only bother with things in large-enough demand). In all honesty, for a high-profile game, the best solution is probably to seed the torrent yourself (clandestinely!) and modify it in some way (for instance, so that after two weeks of play it pops up with messages telling you to please consider supporting the developers by purchasing a legitimate copy). If you put protection in place, bear two things in mind. First, a lower price will supplement any copy protection by making people more inclined to pay the purchase price. Secondly, the protection must not get in the way of users - see Spore for a recent example. A: DRM this, DRM that - publishers who force DRM on their projects are doing it because it's profitable. Their economists are concluding this on data which none of us will ever see. The "DRM is evil" trolls are going a little too far. For a low-visibility product, a simple internet activation is going to stop casual copying. Any other copying is likely negligible to your bottom line. A: Illegal distribution is practically impossible to prevent; just ask the RIAA. Digital content can just be copied; analog content can be digitised, and then copied. You should focus your efforts on preventing unauthorised execution. It's never possible to completely prevent the execution of code on someone else's machine, but you can take certain steps to raise the bar sufficiently high that it becomes easier to purchase your software than to pirate it. Take a look at the article Developing for Software Protection and Licensing that explains how best to go about developing your application with licensing in mind. Obligatory disclaimer & plug: the company I co-founded produces the OffByZero Cobalt software licensing solution for .NET. A: The trouble with this idea of just let the pirates use it they wont buy it anyway and will show their friends who might buy it is twofold. * *With software that uses 3rd party services, the pirated copies are using up valuable bandwidth/resource which gives legit users a worse experience, make my sw look more popular then it is and has the 3rd party services asking me to pay more for their services because of the bandwidth being used. *Many casual wouldn't dream of cracking the sw themselves but if there is an easy assessible crack on a site like piratebay they will use it, if there wasn't they might buy it. This concept of not disabling pirated software once discovered also seems crazy, I don't understand why I should let someone continue to use software they shouldn't be using, I guess this is just the view/hope of the pirates. Also, its worth noting that making a program hard to crack is one thing, but you also need to prevent legit copies being shared, otherwise somebody could simply buy one copy and then share it with thousands of others via a torrent site. The fact of having their name/email address embedded in the license isn't going to be enough to disuade everyone from doing this, and it only really takes one for there to be a problem. The only way I can see to prevent this is to either: * *Have server check and lock license on program startup every time, and release license on program exit. If another client starts with same license whilst the first client has license then it is rejected. This way doesn't prevent the license being used by more than one user, but does prevent it being used concurrently by more than one user - which is good enough. It also allows a legitimate user to transfer the license on any of their computers which provides a better experience. *On first client startup client sends license to server and server verifies it, causing some flag to be set within the client software. Further requests from other clients with the same license are rejected. The trouble with this approach is the original client would have problems if they reinstalled the software or wanted to use a different computer. A: Even if you used some kind of biometric fingerprint authentication, someone would find a way to crack it. There's really no practical way around that. Instead of trying to make your software hack-proof, think about how much extra revenue will be brought in by adding additional copy protection vs. the amount of time and money it will take to implement it. At some point, it gets to be cheaper to go with a less rigorous copy protection scheme. It depends on what exactly your software product is, but one possibility is to move the "valuable" part of the program out of the software and keep it under your exclusive control. You would charge a modest fee for the software (mostly to cover print and distribution costs) and would generate your revenue from the external component. For example, an anti-virus program that is sold for cheap (or bundled for free with other products) but sells subscriptions to its virus definitions update service. With that model, a pirated copy that subscribes to your update service wouldn't represent much of a financial loss. With the increasing popularity of applications "in the cloud", this method is becoming easier to implement; host the application on your cloud, and charge users for cloud access. This doesn't stop someone from re-implementing their own cloud to eliminate the need for your service, but the time and effort involved in doing so would most likely outweigh the benefits (if you keep your pricing model reasonable). A: Software protections aren't worth the money -- if your software is in demand it will be defeated, no matter what. That said, hardware protections can work well. An example way it can work well is this: Find a (fairly) simple but necessary component of your software and implement it in Verilog/VHDL. Generate a public-private keypair and make a webservice that takes a challenge string and encrypts it with the private key. Then make a USB dongle that contains your public key and generates random challenge strings. Your software should ask the USB dongle for a challenge string and send it up to the server for encryption. The software then sends it to the dongle. The dongle validates the encrypted challenge string with the public key and goes into an 'enabled' mode. Your software then calls into the dongle any time it needs to do the operation you wrote in HDL. This way anyone wanting to pirate your software has to figure out what the operation is and reimplement it -- much harder than just defeating a pure software protection. Edit: Just realized some of the verification stuff is backwards from what it should be, but I'm pretty sure the idea comes across. A: The Microsoft Software License scheme is crazy expensive for a small business. The server cost is around $12,000 if you want to set it up yourself. I don't recommend it for the feint of heart. We actually just implemented Intellilock in our product. It lets you have all of the decisions for how strict you want your license to be, and it is very cost effective as well. In addition it does obfuscation, compiler prevention, etc. Another good solution I have seen small/med businesses use is SoloServer. It is much more of an ecommerce and license control system. It is very configurable to the point of maybe a little too complex. But it does a very good job from what I have heard. I have also used the Desaware license system for dot net in the past. It is a pretty lightweight system compared to the two above. It is a very good license control system in terms of cryptographically sound. But it is a very low level API in which you have to implement almost everything your app will actually use. A: If your interested in protecting software that you intend to sell to consumers I would recommend any of a variety of license key generating libraries (Google search on license key generation). Usually the user has to give you some sort of seed like their email address or name and they get back the registration code. Several companies will either host and distribute your software or provide a complete installation/purchase application that you can integrate with and do this automatically probably at no additional cost to you. I have sold software to consumers and I find this the right balance of cost/ease of use/protection. A: The simple, and best solution, is just to charge them up front. Set a price that works for you and them. Asking paying customers to prove that they are paying customers after they've already paid just pisses them off. Implementing the code to make your software not run wastes your time and money, and introduces bugs and annoyances for legitimate customers. You'd be better off spending that time making a better product. Lots of games/etc will "protect" the first version, then drop the protections in the first patch due to compatibility problems with real customers. It's not an unreasonable strategy if you insist on a modicum of protection. A: Almost all copy-protection is both ineffective, and a usability nightmare. Some of it, such as putting root-kits on your customers' machines becomes downright unethical A: I suggest simple activation key (even if you know that it can be broken), you really don't want your software to get in your users way, or they'll simply push it away. Make sure that they can re-download the software, I suggest a web page where they can logging and download your software only after they paid (and yes they should be able to download as many times they wish it, directly, without a single question about why on your part). Thrust your paid users above all, there is nothing more irritating that being accused from being a criminal when you are a legit users (DVD's anti-piracy warnings anyone). You can add a service that checks the key against a server when online, and in case of two different IPs are using the same key, popup a suggestion to buy another license. But please don't inactivate it, it might be a happy user showing your software to a friend!!!! A: Make part of your product an online component which requires connection and authentication. Here are some examples: * *Online Games *Virus Protection *Spam Protection *Laptop tracking software This paradigm only goes so far though and can turn some consumers off. A: I agree with a lot of posters that no software-based copy protection scheme will deter against a skilled software pirate. For commercial .NET based software Microsoft Software License Protection (SLP) is a very reasonably priced solution. It supports time-limited and floating licenses. Their pricing starts at $10/month + $5 per activation and the protection components seem to work as advertised. It's a fairly new offering, though, so buyer beware.
{ "language": "en", "url": "https://stackoverflow.com/questions/109997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "94" }
Q: Windows Licensing Question This is slightly off topic of programming but still has to do with my programming project. I'm writing an app that uses a custom proxy server. I would like to write the server in C# since it would be easier to write and maintain, but I am concerned about the licensing cost of Windows Server + CALS vs a Linux server (obviously, no CALS). There could potentially be many client sites with their own server and 200-500 users at each site. The proxy will work similar to a content filter. Take returning web pages, process based on the content, and either return the webpage, or redirect to a page on another webserver. There will not be any use of SQL server, user authentication, etc. Will I need Cals for this? If so, about how much would it cost to setup a Windows Server with proper licensing (per server, in USA)? A: This really is an OT question. In any case, there is nothing easier than contacting your local MS distributor. As stackoverflow is by nature an international site, asking a question like that, where the answer is most likely to vary by location (MS license prices really are highly variable and country-specific) is in my opinion not likely to receive an useful answer. A: I realize this isn't exactly answering your question but if you want to use Linux, maybe you want to look into using Mono. .Net on Linux. A: If users will not be actually connecting to any MS server apps (such as Exchange, SQL Server, etc) and won't be using any OS features directly (i.e. connecting to UNC paths) then all that should be required is the server license for the machine to run the OS. You need Windows Server CALs when clients connect to shares, Exchange CALs for mail clients, and SQL Server CALs for apps that connect to your databases. If the clients of your server won't be connecting to anything but the ports offered by your service, you should be in the clear, and it shouldn't cost any more to build a server for 100 users than 10. A: You may not need any CALs for users depending on how you use the server. Certain functionality requires the purchase of CALs but some doesn't. There's no real good way to answer this question since the requirements are too vague. Does it use domain services? Does it use SQL server? Clustering? There are many variables. If you are looking at what the most you could possibly pay, go to CDW and look at the Open License/Open Business products to get an estimate. A: Like said above, if you are using your own connections and nothing else on the server you wont need the cals. A: I would Google the ROI on Linux vs Windows for a commercial server, I have no option generally on this, but I have seen that long term they level out, in the grand scheme of things the initial cost of the Windows license is actually minimal and insignificant. Choose the best technology to solve the end users problem, document why, provide an evaluation report, include maintenance costs, development costs etc. When you do this the answer will be clear to you and your customer. A: If your users are not connecting to any other windows resources (Active Directory, SQL Server, File Shares, etc) then you shouldn't need CALs but you I believe there is something like an external connector license. There's also a 'web edition' which looks like it's in the range of ~$400. Also it looks like Microsoft will be removing the CAL restrictions on web servers completely in Windows Server 2008 Microsoft should call their licensing division Enigma...
{ "language": "en", "url": "https://stackoverflow.com/questions/110008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not getting event arguments in IHTMLElement event handler I've added a callback to an IHTMLElement instance but when the IDispatch::Invoke is called for the event, there are never any arguments (i.e. the pDispParams->cArgs and pDispParams->cNamedArgs are always 0). For example, I add a callback for an onmouseup event. From what I can tell, a callback for this event is supposed to receive a MouseEvent object. Is that correct? If so, what do I need to do to ensure this happens? This is using the MSHTML for IE 6 sp2 (or better) on Windows XP SP2. A: Events arguments for all DOM events including onmouseup are stored in the parent window's event property (IHTMLWindow2::event) If you don't already have the parent window cached, IHTMLElement has a document property which returns an IHTMLDocument interface. From that you can query for IHTMLDocument2 which has a parentWindow property. The IHTMLWindow2 that is returned has the event property you're looking for. You should be able to query for the event interface from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/110015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Multiple column sort in JTable I know that JTable can sort by a single column. But is it possible to allow for multiple column sort or do I need to write the code myself? A: You should be able to set the TableRowSorter and the Comparator associated with it. Example: TableModel myModel = createMyTableModel(); JTable table = new JTable(myModel); TableRowSorter t = new TableRowSorter(myModel); t.setComparator(column that the comparator works against, Comparator<?> comparator); table.setRowSorter(new TableRowSorter(myModel)); A: Look into JXTable. JXTable is an extension of JTable that supports multi-column sorting, as well as other functions that JTable doesn't provide. It's freely available from JDNC / SwingLabs. A: You can sort by multiple columns by specifying more than one sort key when calling setSortKeys in the RowSorter you're using. A: ETable from the netbeans collection. It is part of org-netbeans-swing-outline.jar A google search aught to turn it up. The ETable is primarily a foundation for Outline (a TreeTable) but it has multi-column ordering built in as well as many other nice features A: "I know that Jtable can sort by a single column. But is it possible to allow for multiple column sort or do i need to write the code myself? " Table sorting and filtering is managed by a sorter object. The easiest way to provide a sorter object is to set autoCreateRowSorter bound property to true; JTable table = new JTable(); table.setAutoCreateRowSorter(true); This action defines a row sorter that is an instance of javax.swing.table.TableRowSorter.
{ "language": "en", "url": "https://stackoverflow.com/questions/110016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Best way to stamp an image with another image to create a watermark in ASP.NET? Anyone know? Want to be able to on the fly stamp an image with another image as a watermark, also to do large batches. Any type of existing library or a technique you know of would be great. A: I have had good luck with ImageMagick. It has an API for .NET too. A: here is my full article: http://forums.asp.net/p/1323176/2634923.aspx use the SDK Command Prompt and navigate the active folder to the folder containing the below source code... then compile the code using vbc.exe watermark.vb /t:exe /out:watermark.exe this will create an exe in the folder.. the exe accepts two parameters: ex. watermark.exe "c:\source folder" "c:\destination folder" this will iterate through the parent folder and all subfolders. all found jpegs will be watermarked with the image you specify in the code and copied to the destination folder. The original image will stay untouched. // watermark.vb -- Imports System Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Drawing.Imaging Imports System.IO Namespace WatermarkManager Class Watermark Shared sourceDirectory As String = "", destinationDirectory As String = "" Overloads Shared Sub Main(ByVal args() As String) 'See if an argument was passed from the command line If args.Length = 2 Then sourceDirectory = args(0) destinationDirectory = args(1) ' make sure sourceFolder is legit If Directory.Exists(sourceDirectory) = False TerminateExe("Invalid source folder. Folder does not exist.") Exit Sub End If ' try and create destination folder Try Directory.CreateDirectory(destinationDirectory) Catch TerminateExe("Error creating destination folder. Invalid path cannot be created.") Exit Sub End Try ' start the magic CreateHierarchy(sourceDirectory,destinationDirectory) ElseIf args.Length = 1 If args(0) = "/?" DisplayHelp() Else TerminateExe("expected: watermark.exe [source path] [destination path]") End If Exit Sub Else TerminateExe("expected: watermark.exe [source path] [destination path]") Exit Sub End If TerminateExe() End Sub Shared Sub CreateHierarchy(ByVal sourceDirectory As String, ByVal destinationDirectory As String) Dim tmpSourceDirectory As String = sourceDirectory ' copy directory hierarchy to destination folder For Each Item As String In Directory.GetDirectories(sourceDirectory) Directory.CreateDirectory(destinationDirectory + Item.SubString(Item.LastIndexOf("\"))) If hasSubDirectories(Item) CreateSubDirectories(Item) End If Next ' reset destinationDirectory destinationDirectory = tmpSourceDirectory ' now that folder structure is set up, let's iterate through files For Each Item As String In Directory.GetDirectories(sourceDirectory) SearchDirectory(Item) Next End Sub Shared Function hasSubDirectories(ByVal path As String) As Boolean Dim subdirs() As String = Directory.GetDirectories(path) If subdirs.Length > 0 Return True End If Return False End Function Shared Sub CheckFiles(ByVal path As String) For Each f As String In Directory.GetFiles(path) If f.SubString(f.Length-3).ToLower = "jpg" WatermarkImage(f) End If Next End Sub Shared Sub WatermarkImage(ByVal f As String) Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(f) Dim graphic As Graphics Dim indexedImage As New Bitmap(img) graphic = Graphics.FromImage(indexedImage) graphic.DrawImage(img, 0, 0, img.Width, img.Height) img = indexedImage graphic.SmoothingMode = SmoothingMode.AntiAlias graphic.InterpolationMode = InterpolationMode.HighQualityBicubic Dim x As Integer, y As Integer Dim source As New Bitmap("c:\watermark.png") Dim logo As New Bitmap(source, CInt(img.Width / 3), CInt(img.Width / 3)) source.Dispose() x = img.Width - logo.Width y = img.Height - logo.Height graphic.DrawImage(logo, New Point(x,y)) logo.Dispose() img.Save(destinationDirectory+f.SubString(f.LastIndexOf("\")), ImageFormat.Jpeg) indexedImage.Dispose() img.Dispose() graphic.Dispose() Console.WriteLine("successfully watermarked " + f.SubString(f.LastIndexOf("\")+1)) Console.WriteLine("saved to: " + vbCrLf + destinationDirectory + vbCrLf) End Sub Shared Sub SearchDirectory(ByVal path As String) destinationDirectory = destinationDirectory + path.SubString(path.LastIndexOf("\")) CheckFiles(path) For Each Item As String In Directory.GetDirectories(path) destinationDirectory += Item.SubString(Item.LastIndexOf("\")) CheckFiles(Item) If hasSubDirectories(Item) destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) SearchDirectory(Item) destinationDirectory += Item.SubString(Item.LastIndexOf("\")) End If destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) Next destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) End Sub Shared Sub CreateSubDirectories(ByVal path As String) destinationDirectory = destinationDirectory + path.SubString(path.LastIndexOf("\")) For Each Item As String In Directory.GetDirectories(path) destinationDirectory += Item.SubString(Item.LastIndexOf("\")) Directory.CreateDirectory(destinationDirectory) Console.WriteLine(vbCrlf + "created: " + vbCrlf + destinationDirectory) If hasSubDirectories(Item) destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) CreateSubDirectories(Item) destinationDirectory += Item.SubString(Item.LastIndexOf("\")) End If destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) Next destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf("\")) End Sub Shared Sub TerminateExe(ByVal Optional msg As String = "") If msg "" Console.WriteLine(vbCrLf + "AN ERROR HAS OCCURRED //" + vbCrLf + msg) End If Console.WriteLine(vbCrLf + "Press [enter] to close...") 'Console.Read() End Sub Shared Sub DisplayHelp() Console.WriteLine("watermark.exe accepts two parameters:" + vbCrLf + " - [source folder]") Console.WriteLine(" - [destination folder]") Console.WriteLine("ex." + vbCrLf + "watermark.exe ""c:\web_projects\dclr source"" ""d:\new_dclr\copy1 dest""") Console.WriteLine(vbCrLf + "Press [enter] to close...") Console.Read() End Sub End Class End Namespace A: This will answer your question: http://www.codeproject.com/KB/GDI-plus/watermark.aspx Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/110018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: VisualStudio using BootCamp/VMWare on OS X Just bought a 2.4GHz Intel Core 2 Duo iMac with 2GB of memory and a 320GB hard drive. I plan on doing some .net development on it using a BootCamp/VMWare combo since VMWare grants access to the bootcamp partition. What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration? A: I use VMWare Fusion 2.0 on my MacBook Pro and I wouldn't have it any other way. I'd strongly recommend getting a min of 4gb RAM is you're going to run Windows + VS 2008 in virtualisation. I have a 2gb RAM for my VM and you do notice a bit of chugging, particularly when you are compiling a large solution, or when running lots of apps at once. I strongly recommend VMWare over Parallels as VMWare supports 2 virtual CPU's (I think it's up to 4 virtual CPU's in v2). I'd recommend around a 30gb disk for your VM and I don't recommend BootCamp unless you want to play games on it. Why? It's a lot easier to have a really large virtual disk which is not using it all where as BootCamp will take the space. Also a complete virtual disk is easier to backup/ snapshot/ restore. A: While this doesn't address your question directly, I wouldn't recommend running VS 2008 and all of the supporting tools on anything less than 2GB of RAM. A: I have a 2.4 GHz Intel Core Duo Macbook Pro with 4 GB of RAM. I do some .NET development using VM Fusion/XP/Visual Studio 2005, and have allocated 1 GB of RAM for the virtual machine. It works fine for me, and I have been happy with its performance and responsiveness. The only real annoyance for me is that by default some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. For example, F10 triggers the expose function. However, as @Crash points out, the mac keyboard shortcuts can be disabled in the vmware preferences. This works like a charm - thanks for the tip! @Soeren Kuklau: Thanks for your suggestion, but I don't think I was clear about my problem. I've already configured the "use standard function keys" option. What I was referring to is that by default, F10 and F11 trigger expose actions. And that's my real annoyance: to use keyboard shortcuts for debugging, you have to change default settings. A: The only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. Enable System Preference → Keyboard & Mouse → Keyboard → Use all F1, F2, etc. keys as standard function keys. A: The only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. I use VmWare Fusion 2.0 on my MBP with Vista x64. There's an option in virtual machine configuration to let you disable mac-specific-keys. Once i disabled it, i can use F10 and F11 in Visual Studio 2008 without any problems and as soon as i switch back to mac os they act as set in System Preferences (in my case, they behave as standard function keys). What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration? I have a MBP 15", with 4GB of RAM. I use VmWare Fusion 2.0 with Vista x64. I configured the virtual drive to use 40GB (i only installed Vista, Visual Studio 2008 Pro (c#+web dev), MSDN and Microsoft Access 2007. I set 2GB of ram to be used by vm and one cpu. I mostly use Vista in windowed-mode and i can switch back to Leopard very smoothly and vs 2008 experience is really great. A: I ran windows Xp on a mac (AMD 2.4 GHz) and i alloted 1.5GB and it was fairly slow, but it was a file based disk. I agree with the above that you need the ram, especially with vista. I dont think 2GB base is anough for mac and vmware with vista. For the partition, give at least 40 Gb for os + software and whatveer else extra you need for data. If you can create an extra physical partitioon for the pagefile, that would help too. A: You might also find the suggestions here helpful - elements of this were covered on Stack Overflow a few weeks ago. Personally I'd say don't bother trying to give the VM more than 2Gb of ram (I've had mixed results giving it more than 1, but your mileage may vary, and my experience is all with VMware Fusion 1). Certainly I'd echo the comments above about not going with Bootcamp, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/110030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is XSLT a functional programming language? Several questions about functional programming languages have got me thinking about whether XSLT is a functional programming language. If not, what features are missing? Has XSLT 2.0 shortened or closed the gap? A: I am sure you guys have found this link by now :-) http://fxsl.sourceforge.net/articles/FuncProg/Functional%20Programming.html . Well functions in XSLT are first class-citizens with some work arounds after all :-) A: That is sort of how it feels when I am programming it. XSLT is entirely based on defining functions and applying them to selected events that come down the input stream. XSLT lets you set a variable. Functional programming does not allow functions to have side effects - and that is a biggie. Still, writing in XSLT, one has the same "feel as working in an FP fashion. You are working with input - you are not changing it - to create output. This is a very, very different programming model from that used when working with the DOM API. DOM does not separate input and output at all. You are handed a data structure - and you mangle it how you see fit - without hesitation, restriction, or remorse. Suffice it to say if you like FP and the principles behind it, you will probably feel comfortable working in it. Just like experience with event driven programming - and XML itself - will make you comfortable with it as well. If your only experience is with top-down, non event driven programs - then XSLT will be very unfamiliar, alien landscape indeed. At least at first. Growing a little experience and then coming back to XSLT when XPath expressions and event-handling are really comfortable to you will pay off handsomely. A: For the most part, what makes XSLT not a 100% functional programming language is it's inability to treat functions as a first-class data type. There may be some others -- but that's the obvious answer. Good luck! A: Saxon-SA has introduced some extension functions which make XSLT functional. You can use saxon:function() to create a function value (actually a {http://net.sf.saxon/java-type}net.sf.saxon.expr.UserFunctionCall value) which you then call with saxon:call(). Saxon-B has similar functionality with the pairing of saxon:expression() and saxon:eval(). The difference is that saxon:expression() takes any XPath expression, and saxon:eval() evaluates it, whereas saxon:function() takes the name of a function which saxon:call() calls. A: XSLT is declarative as opposed to stateful. Although XSLT is based on functional programming ideas, it is not a full functional programming language, it lacks the ability to treat functions as a first class data type. It has elements like lazy evaluation to reduce unneeded evaluation and also the absence of explicit loops. Like a functional language though, I would think that it can be nicely parallelized with automatic safe multi threading across several processors. From Wikipedia on XSLT: As a language, XSLT is influenced by functional languages, and by text-based pattern matching languages like SNOBOL and awk. Its most direct predecessor was DSSSL, a language that performed the same function for SGML that XSLT performs for XML. XSLT can also be considered as a template processor. Here is a great site on using XSLT as a functional language with the help of FXSL. FXSL is a library that implements support for higher-order functions. Because of FXSL I don't think that XSLT has a need to be fully functional itself. Perhaps FXSL will be included as a W3C standard in the future, but I have no evidence of this. A: That is not really an argument, since you can only declare variables, not change their values after declaration. In that sense it is declarative not imperative style, as stated in Mr Novatchev's article. Functional programming languages like Scheme or Erlang enable you to declare variables as well, and in Haskell you can also do that: -- function 'test' takes variable x and adds it on every element of list xs test :: [Int] -> [Int] test xs = map (+ x) xs where x = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/110031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Star-Schema Design Is a Star-Schema design essential to a data warehouse? Or can you do data warehousing with another design pattern? A: Using star schemas for a data warehouse system gets you several benefits and in most cases it is appropriate to use them for the top layer. You may also have an operational data store (ODS) - a normalised structure that holds 'current state' and facilitates operations such as data conformation. However there are reasonable situations where this is not desirable. I've had occasion to build systems with and without ODS layers, and had specific reasons for the choice of architecture in each case. Without going into the subtlties of data warehouse architecture or starting a Kimball vs. Inmon flame war the main benefits of a star schema are: * *Most database management systems have facilities in the query optimiser to do 'Star Transformations' that use Bitmap Index structures or Index Intersection for fast predicate resolution. This means that selection from a star schema can be done without hitting the fact table (which is usually much bigger than the indexes) until the selection is resolved. *Partitioning a star schema is relatively straightforward as only the fact table needs to be partitioned (unless you have some biblically large dimensions). Partition elimination means that the query optimiser can ignore patitions that could not possibly participate in the query results, which saves on I/O. *Slowly changing dimensions are much easier to implement on a star schema than a snowflake. *The schema is easier to understand and tends to involve less joins than a snowflake or E-R schema. Your reporting team will love you for this *Star schemas are much easier to use and (more importantly) make perform well with ad-hoc query tools such as Business Objects or Report Builder. As a developer you have very little control over the SQL generated by these tools so you need to give the query optimiser as much help as possible. Star schemas give the query optimiser relatively little opportunity to get it wrong. Typically your reporting layer would use star schemas unless you have a specific reason not to. If you have multiple source systems you may want to implement an Operational Data Store with a normalised or snowflake schema to accumulate the data. This is easier because an ODS typically does not do history. Historical state is tracked in star schemas where this is much easier to do than with normalised structures. A normalised or snowflaked Operational Data Store reflects 'current' state and does not hold a historical view over and above any that is inherent in the data. ODS load processes are concerned with data scrubbing and conforming, which is easier to do with a normalised structure. Once you have clean data in an ODS, dimension and fact loads can track history (changes over time) with generic or relatively simple mechanisms relatively simply; this is much easier to do with a star schema, Many ETL tools (for example) provide built-in facilities for slowly changing dimensions and implementing a generic mechanism is relatively straightforward. Layering the system in this way providies a separation of responsibilities - business and data cleansing logic is dealt with in the ODS and the star schema loads deal with historical state. A: There is an ongoing debate in the datawarehousing litterature about where in the datawarehouse-architecture the Star-Schema design should be applied. In short Kimball advocates very highly for using only the Star-Schema design in the datawarehouse, while Inmon first wants to build an Enterprise Datawarehouse using normalized 3NF design and later use the Star-Schema design in the datamarts. In addition here to you could also say that Snowflake schema design is another approach. A fourth design could be the Data Vault Modeling approach. A: Star schemas are used to enable high speed access to large volumes of data. The high performance is enabled by reducing the amount of joins needed to satsify any query that may be made against the subject area. This is done by allowing data redundancy in dimension tables. You have to remember that the star schema is a pattern for the top layer for the warehouse. All models also involve staging schemas at the bottom of the warehouse stack, and some also include a persistant transformed merged staging area where all source systems are merged into a 3NF modelled schema. The various subject areas sit above this. Alternatives to star schemas at the top level include a variation, which is a snowflake schema. A new method that may bear out some investigation as well is Data Vault Modelling proposed by Dan Linstedt. A: The thing about star schemas is they are a natural model for the kinds of things most people want to do with a data warehouse. For instance it is easy to produce reports with different levels of granularity (month or day or year for example). It is also efficient to insert typical business data into a star schema, again a common and important feature of a data warehouse. You certainly can use any kind of database you want but unless you know your business domain very well it is likely that your reports will not run as efficiently as they could if you had used a star schema. A: Star schemas are a natural fit for the last layer of a data warehouse. How you get there is another question. As far as I know, there are two big camps, those of Bill Inmon and Ralph Kimball. You might want to look at the theories of these two guys if/when you decide to go with a star. Also, some reporting tools really like the star schema setup. If you are locked into a specific reporting tool, that might drive what the reporting mart looks like in your warehouse. A: Star schema is a logical data model for relational databases that fits the regular data warehousing needs; if the relational environment is given, a star or a snowflake schema will be a good design pattern, hard-wired in lots of DW design methodologies. There are however other than relational database engines too, and they can be used for efficient data warehousing. Multidimensional storage engines might be very fast for OLAP tasks (TM1 eg.); we can not apply star schema design in this case. Other examples requiring special logical models include XML databases or column-oriented databases (eg. the experimental C-store)). A: It's possible to do without. However, you will make life hard for yourself -- your organization will want to use standard tools that live on top of DWs, and those tools will expect a star schema -- a lot of effort will be spent fitting a square peg in a round hole. A lot of database-level optimizations assume that you have a star schema; you will spend a lot of time optimizing and restructuring to get the DB to do "the right thing" with your not-quite-star layout. Make sure that the pros outweigh the cons.. (Does it sound like I've been there before?) -D A: There are three problems we need to solve. 1) How to get the data out of the operational source system without putting undue pressure on them by joining tables within and between them, cleaning data as we extract, creating derivations etc. 2) How to merge data from disparate sources - some legacy, some file based, from different departments into an integral, accurate, efficiently stored whole that models the business, and does not reflect the structures of the source systems. Remember, systems change / are replaced relatively quickly, but the basic model of the business changes slowly. 3) How to structure the data to meet specific analytical and reporting requirements for particular people/departments in the business as quickly and accurately as possible. The solution to these three very different problems require different architectural layers to solve them Staging Layer We replicate the structures of the sources, but only changed data from the sources are loaded each night. once the data is taken from the staging layer into the next layer, the data is dropped. Queries are single table queries with a simple data_time filter. Very little effect on the source. Enterprise Layer This is a business oriented 3rd normal form database. Data is extracted (and afterward dropped) from the staging layer into the enterprise layer, where it is cleaned, integrated and normalised. Presentation (Star Schema) Layer Here, we model dimensionally to meet specific requirements. Data is deliberately de-normalise to reduce the number of joins. Hierarchies that may occupy several tables in the Enterprise Layer are collapsed into a single dimension tables, and multiple transactional tables may be merged into single fact tables. You always face these three problems. If you choose to do away with the enterprise layer, you still have to solve the second problem, but you have to do it in the star schema layer, and in my view, this is the wrong place to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/110032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: How do I determine if I should install Drupal 5.x or 6.x? I'm planning to install Drupal. Is there any reason not to install the latest 6.x version as opposed to the 5.x branch? Are there any really good modules that are 5.x only? A: Unless you have a 5.x module that you can't do without, and that you know is being worked on to upgrade to 6.x, just use 6.x. i.e. Only start with 5.x now if you know you have a upgrade path with your site to 6.x (and then 7.x). If the module isn't being actively worked on, it mean you'll be unsupported when 7.x rolls around, so you might as well solve the problem of doing without that module with 6.x now rather than wait till your site is developed and up and running. A: I've found enough modules to happily run my site on Drupal 6.x I think the only 5.x module I miss is one that did very easy Google ad integration, and that may have been updated I just haven't checked recently. I don't get enough traffic to make the ads worth the time in setting them up, so I just use the search part of the ad campaign. Drupal 7.x is under development now, so I would expect that anything that hasn't been moved from 5.x to 6.x is just not being developed anymore, and is probably not really that needed. Ultimately, take a look at what modules you may need. With an account on Drupal's site, you can filter by install type. I found that 6.x is much easier to work with in some regards (managing and upgrading modules) and overall I've had a much easier time maintaining my site under Drupal 6.x than I did under 4.x or 5.x. I also think that 6.x runs much faster. A: My bosses were insistent on making Drupal 6 sites for clients as soon as it was released. This was a headache, because views and CCK were not done, as well as many other modules. Their rational was that we'd have to eventually upgrade to 6, and we wouldn't want to go back and redo these sites. It ended up that we had so many workarounds while using the development versions of modules that it was a pain every time we upgraded modules or core itself. Thankfully, this is no longer the case. Views, CCK, and most other modules are now ready and stable for 6. The only module we use that hasn't been upgraded is eCommerce, and it doesn't look like it will be, since ubercart is pretty much the Drupal standard for commerce functionality. A: We asked ourselves the same question several months ago (just before Drupal 6 was finalized & released) Our office has limited development resources, and we had released a couple of D5 sites, and a D5 sales app. We went with Drupal 6. The decision came after considering the core of what we were interacting with. CCK & Views are the only die-hard critical components for anything besides a default Drupal install, and the level of participation and vitality of the projects was very encouraging. The stuff that really, really matters, has been/is being ported over to D6, and the wow, this would be nice, p2 stuff is hit & miss. If you're doing any module development, D6 is a winner. If you're already very comfortable with D5, then stick with it. I hope this helps. A: The one significant CCK-related module that's not D6 production ready is filefield. This may not be an issue if you're not doing anything substantial with images and media, but might be worth considering if you're going to do any serious DAM. Otherwise, I think we're (finally!) to the point where it's making more sense to go with D6 than D5. Either way, it's definitely worth the time to architect the site according to your specific needs, figure out what modules you'll need and find out if any of them have yet to be updated. A: The asset module is not available for D6 yet, not even in a development branch. I've heard a lot about its benefits as a single way to manage all kinds of media files, but most sites can probably happily do without it. A: If you haven't been running Drupal before you could find that version 6 has the modules you need. Besides, modules gets ported and created every day so your missing modules could very well be on the way. A: For me, the lack of a protx payment module was a deal breaker when choosing which version to use. The best thing to do is get a full list of requirements before you start, and make sure it's all available in 6. A: As a module developer, I feel that Drupal 6's API is more mature then version 5. So even if you decide to choose 6, and then finds a module is missing, it will be easy to develop it to 6. A: Now that I've used Views 2, I ain't ever going back (unless it's to revisit old projects). I think now, all modules and themes that are of any worth have been migrated and now I'm seeing a trend of new (actually good themes) are drupal 6 only as are quite a few of the must have modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/110043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the best way to store app specific configuration in rails? I need to store app specific configuration in rails. But it has to be: * *reachable in any file (model, view, helpers and controllers *environment specified (or not), that means each environment can overwrite the configs specified in environment.rb I've tried to use environment.rb and put something like USE_USER_APP = true that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block. So, anyone? A: The most basic thing to do is to set a class variable from your environment.rb. I've done this for Google Analytics. Essentially I want a different key depending on which environment I'm in so development or staging don't skew the metrics. This is how I did it. In lib/analytics/google_analytics.rb: module Analytics class GoogleAnalytics @@account_id = nil cattr_accessor :account_id end end And then in environment.rb or in environments/production.rb or any of the other environment files: Analytics::GoogleAnalytics.account_id = "xxxxxxxxx" Then anywhere you ned to reference, say the default layout with the Google Analytics JavaScript, it you just call Analytics::GoogleAnalytics.account_id. A: I was helping a friend set up the solution mentioned by Ricardo yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here): require 'ostruct' require 'yaml' require 'erb' #config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml")) config = OpenStruct.new(YAML.load(ERB.new(File.read("#{RAILS_ROOT}/config/config.yml")).result)) env_config = config.send(RAILS_ENV) config.common.update(env_config) unless env_config.nil? ::AppConfig = OpenStruct.new(config.common) This allowed him to embed Ruby code in the config, like in Rhtml: development: path_to_something: <%= RAILS_ROOT %>/config/something.yml A: Look at Configatron: http://github.com/markbates/configatron/tree/master I have yet to use it, but he's actively developing it now, and looks quite nice. A: I found a good way here A: Use environment variables. Heroku uses this. Remember that if you keep configuration in the codebase, anyone with access to the code has access to any secret configuration (aws api keys, gateway api keys, etc). daemontool's envdir is a good tool for setting configuration, I'm pretty sure that's what Heroku uses to give application their environment variables. A: I have used Rails Settings Cached. It is very simple to use, keeps your configuration values cached and allows you to change them dynamically.
{ "language": "en", "url": "https://stackoverflow.com/questions/110078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: LinearGradientBrush Artifact Workaround? The LinearGradientBrush in .net (or even in GDI+ as a whole?) seems to have a severe bug: Sometimes, it introduces artifacts. (See here or here - essentially, the first line of a linear gradient is drawn in the endcolor, i.e. a gradient from White to Black will start with a Black line and then with the proper White to Black gradient) I wonder if anyone found a working workaround for this? This is a really annoying bug :-( Here is a picture of the Artifacts, note that there are 2 LinearGradientBrushes: alt text http://img142.imageshack.us/img142/7711/gradientartifactmm6.jpg A: I have noticed this as well when using gradient brushes. The only effective workaround I have is to always create the gradient brush rectangle 1 pixel bigger on all edges than the area that is going to be painted with it. That protects you against the issue on all four edges. The downside is that the colors used at the edges are a fraction off those you specify, but this is better than the drawing artifact problem! A: You can use the nice Inflate(int i) method on a rectangle to get the bigger version. A: I would finesse Phil's answer above (this is really a comment but I don't have that privilege). The behaviour I see is contrary to the documentation, which says: The starting line is perpendicular to the orientation line and passes through one of the corners of the rectangle. All points on the starting line are the starting color. Then ending line is perpendicular to the orientation line and passes through one of the corners of the rectangle. All points on the ending line are the ending color. Namely you get a single pixel wrap-around in some cases. As far as I can tell (by experimentation) I only get the problem when the width or height of the rectangle is odd. So to work around the bug I find it is adequate to increase the LinearGradientBrush rectangle by 1 pixel if and only if the dimension (before expansion) is an odd number. In other words, always round the brush rectangle up the the next even number of pixels in both width and height. So to fill a rectangle r I use something like: Rectangle gradientRect = r; if (r.Width % 2 == 1) { gradientRect.Width += 1; } if (r.Height % 2 == 1) { gradientRect.Height += 1; } var lgb = new LinearGradientBrush(gradientRect, startCol, endCol, angle); graphics.FillRectangle(lgb, r); Insane but true. A: At least with WPF you could try to use GradientStops to get 100% correct colors right at the edges, even when overpainting. A: I experienced artifacts too in my C++ code. What solved the problem is setting a non-default SmoothingMode for the Graphics object. Please note that all non-default smoothing modes use coordinate system, which is bound to the center of a pixel. Thus, you have to correctly convert your rectangle from GDI to GDI+ coordinates: Gdiplus::RectF brushRect; graphics.SetSmoothingMode( Gdiplus::SmoothingModeHighQuality ); brushRect.X = rect.left - (Gdiplus::REAL)0.5; brushRect.Y = rect.top - (Gdiplus::REAL)0.5; brushRect.Width = (Gdiplus::REAL)( rect.right - rect.left ); brushRect.Height = (Gdiplus::REAL)( rect.bottom - rect.top ); It seems like LinearGradientBrush works correctly only in high-quality modes.
{ "language": "en", "url": "https://stackoverflow.com/questions/110081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Which loop has better performance? Why? String s = ""; for(i=0;i<....){ s = some Assignment; } or for(i=0;i<..){ String s = some Assignment; } I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself. EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through. Also, the question isn't because I'm worried about memory management. Just want to know which is better. A: If you want to speed up for loops, I prefer declaring a max variable next to the counter so that no repeated lookups for the condidtion are needed: instead of for (int i = 0; i < array.length; i++) { Object next = array[i]; } I prefer for (int i = 0, max = array.lenth; i < max; i++) { Object next = array[i]; } Any other things that should be considered have already been mentioned, so just my two cents (see ericksons post) Greetz, GHad A: To add on a bit to @Esteban Araya's answer, they will both require the creation of a new string each time through the loop (as the return value of the some Assignment expression). Those strings need to be garbage collected either way. A: I know this is an old question, but I thought I'd add a bit that is slightly related. I've noticed while browsing the Java source code that some methods, like String.contentEquals (duplicated below) makes redundant local variables that are merely copies of class variables. I believe that there was a comment somewhere, that implied that accessing local variables is faster than accessing class variables. In this case "v1" and "v2" are seemingly unnecessary and could be eliminated to simplify the code, but were added to improve performance. public boolean contentEquals(StringBuffer sb) { synchronized(sb) { if (count != sb.length()) return false; char v1[] = value; char v2[] = sb.getValue(); int i = offset; int j = 0; int n = count; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } } return true; } A: In theory, it's a waste of resources to declare the string inside the loop. In practice, however, both of the snippets you presented will compile down to the same code (declaration outside the loop). So, if your compiler does any amount of optimization, there's no difference. A: In general I would choose the second one, because the scope of the 's' variable is limited to the loop. Benefits: * *This is better for the programmer because you don't have to worry about 's' being used again somewhere later in the function *This is better for the compiler because the scope of the variable is smaller, and so it can potentially do more analysis and optimisation *This is better for future readers because they won't wonder why the 's' variable is declared outside the loop if it's never used later A: Limited Scope is Best Use your second option: for ( ... ) { String s = ...; } Scope Doesn't Affect Performance If you disassemble code the compiled from each (with the JDK's javap tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that Brian R. Bondy's "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases. Avoid Premature Initialization The only difference between the two cases is that, in the first example, the variable s is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to s, and a good JIT compiler will probably elide it at runtime. You could fix this simply by using an empty declaration (i.e., String s;), but this is considered bad practice and has another side-effect discussed below. Often a bogus value like null is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value. Conserve Stack Slots As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope: void x(String[] strings, Integer[] integers) { String s; for (int i = 0; i < strings.length; ++i) { s = strings[0]; ... } Integer n; for (int i = 0; i < integers.length; ++i) { n = integers[i]; ... } } The variables s and n could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller. What Really Matters However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application. The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have. A: It seems to me that we need more specification of the problem. The s = some Assignment; is not specified as to what kind of assignment this is. If the assignment is s = "" + i + ""; then a new sting needs to be allocated. but if it is s = some Constant; s will merely point to the constants memory location, and thus the first version would be more memory efficient. Seems i little silly to worry about to much optimization of a for loop for an interpreted lang IMHO. A: When I'm using multiple threads (50+) then i found this to be a very effective way of handling ghost thread issues with not being able to close a process correctly ....if I'm wrong, please let me know why I'm wrong: Process one; BufferedInputStream two; try{ one = Runtime.getRuntime().exec(command); two = new BufferedInputStream(one.getInputStream()); } }catch(e){ e.printstacktrace } finally{ //null to ensure they are erased one = null; two = null; //nudge the gc System.gc(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/110083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Is there set division in SQL? I'm fully aware that set division can be accomplished through a series of other operations, so my question is: Is there a command for set division in SQL? A: http://vadimtropashko.files.wordpress.com/2007/02/ch3.pdf From Page 32: Relational Division is not a fundamental operator. It can be expressed in terms of projection, Cartesian product, and set difference. So, no. :) A: Here is a nice explanation using relational algebra syntax. Given tables sailors, boats and reserves (examples from Ramakrishnan & Gehrke's "Database Management Systems") you can compute sailors who have reserved all boats with the following query: SELECT name FROM sailors WHERE Sid NOT IN ( -- A sailor is disqualified if by attaching a boat, -- we obtain a tuple <sailor, boat> that is not in reserves SELECT s.Sid FROM sailors s, boats b WHERE (s.Sid, b.Bid) NOT IN ( SELECT Sid, Bid FROM reserves ) ); -- Alternatively: SELECT name FROM sailors s WHERE NOT EXISTS ( -- Not reserved boats (SELECT bid FROM boats) EXCEPT (SELECT r.bid FROM reserves r WHERE r.sid = s.sid) ); A: Related question: Database Design for Tagging And relevant part of answer is this article So in short, no, there is no set division in SQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/110088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Logic and its application to Collections.Generic and inheritance Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie. object me = new Person(); Therefore, following this through to its logical conclusion, a group of People would also be a group of objects: List<Person> people = new List<Person>(); people.Add(me); people.Add(you); List<object> things = people; // Ooops. Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator). The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour? For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely. A: OK, everyone who has used generics in .net must have run into this at one point or another. Yes, intuitively it should work. No, in the current version of the C# compiler it doesn't. Eric Lippert has a really good explanation of this issue (it's in eleven parts or something and will bend you mind in places, but it's well worth the read). See here. edit: dug out another relevant link, this one discusses how java handles this. See here A: you can use linq to cast it: IEnumerable<Person> oldList = someIenumarable; IEnumerable<object> newList = oldlist.Cast<object>() A: At first glance, this does not make intuitive sense. But it does. Look at this code: List<Person> people = new List<Person>(); List<object> things = people; // this is not allowed // ... Mouse gerald = new Mouse(); things.add(gerald); Now we suddenly have a List of Person objects... with a Mouse inside it! This explains why the assignment of an object of type A<T> to a variable of type A<S> is not allowed, even if S is a supertype of T. A: The linq workaround is a good one. Another workaround, since you are using type object, is to pass the list as IEnumerable (not the generic version). Edit: C# 4 (currently beta) supports a covariant type parameter in IEnumerable. While you won't be able to assign directly to a List<object>, you can pass your list to a method expecting an IEnumerable<object>. A: While what your trying to does indeed flow logically, its actually a feature that many languages don't natively support. This is whats called co/contra variance, which has to do with when and how objects can be implicitly cast from one thing to nother by a compiler. Thankfully, C# 4.0 will bring covariance and contravariance to the C# arena, and such implicit casts like this should be possible. For a detailed explanation of this, the following Channel9 video should be helpful: http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/ A: With linq extension methods you can do IEnumerable<object> things = people.Cast<object>(); List<object> things = people.Cast<object>().ToList(); Otherwise since you are strongly typing the list the implicit conversion isn't allowed.
{ "language": "en", "url": "https://stackoverflow.com/questions/110121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you allow the usage of an while preventing XSS? I'm using ASP.NET Web Forms for blog style comments. Edit 1: This looks way more complicated then I first thought. How do you filter the src? I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that? A: If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like: Look at this! [http://a.b.c/m.jpg] Which would get converted to Look at this! <img src="http://a.b.c/m.jpg" /> You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe Look at this! [javascript:alert('pwned!')] A: Use an XML parser to validate your input, and drop or encode all elements, and attributes, that you do not want to allow. In this case, delete or encode all tags except the <img> tag, and all attributes from that except src, alt and title. A: If you end up going with a non-HTML format (which makes things easier b/c you can literally escape all HTML), use a standard syntax like markdown. The markdown image syntax is ![alt text](/path/to/image.jpg) There are others also, like Textile. Its syntax for images is !imageurl! A: @chakrit suggested using a custom syntax, e.g. bracketed URLs - This might very well be the best solution. You DEFINITELY dont want to start messing with parsing etc. Just make sure you properly encode the entire comment (according to the context - see my answer on this here Will HTML Encoding prevent all kinds of XSS attacks?) (btw I just discovered a good example of custom syntax right there... ;-) ) As also mentioned, restrict the file extension to jpg/gif/etc - even though this can be bypassed, and also restrict the protocol (e.g. http://). Another issue to be considered besides XSS - is CSRF (http://www.owasp.org/index.php/Cross-Site_Request_Forgery). If you're not familiar with this security issue, it basically allows the attacker to force my browser to submit a valid authenticated request to your application, for instance to transfer money or to change my password. If this is hosted on your site, he can anonymously attack any vulnerable application - including yours. (Note that even if other applications are vulnerable, its not your fault they get attacked, but you still dont want to be the exploit host or the source of the attack...). As far as your own site goes, it's that much easier for the attacker to change the users password on your site, for instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/110123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tips for getting started with SQL? I've never had much need for programming with databases. Since their use is so widespread it seems like a good thing for me to learn. SQL seems like the place to start, possibly SQLite and maybe the Python bindings. What would you recommend for someone new to this? Libraries, tools and project ideas are all welcome. A: Structure Query Language (SQL) is the language used to talk to database management systems (DBMS). While it's a good thing to learn, it's probably best to do it with a project in mind that you'd like to do. It's funny you say you've never had a need, because I'm the opposite, almost every program I've ever written has used a database of some sort. The vast majority (mostly web-based) revolve around using a database. * *Learn about relations and database architecture. This means how to structure your tables, make foreign keys and relations. For example, you might have a movies database. In it, you store information about the Movies, Studios that released the movies, and the Actors in the movies. Each of these becomes a table. Each Movie is released by one Studio. Since you don't want to store duplicate the studio information (address, etc) in each Movie entry, you store a relation to it, so each Movie item contains a reference to a Studio item. This is called a one-to-many relationship (one studio has many movies). Likewise, you don't want to store Actor information for each Movie. But one Actor can be in many Movies, so this is stored as a many-to-many relationship. *Learn SQL itself. SQLCourse is a good place to get started, but there are many other books and resources. SQL is a standard, but each RDBMS has its own vendor-specific ways of doing certain things and other limitations (for example, some systems don't support sub-queries, there are several different syntaxes for limiting the number of rows returned, etc). It's important to learn the syntax for the one you're using (eg, don't learn Oracle syntax and then try and use it in MySQL) but they are similar enough that the concepts are the same. *Tools depend on the DBMS you use. MySQL is a pretty popular database, lots of tools are available, and lots of books. SQLite and Postgresql are also quite popular, and also free/open-source. A: If you can, you really want to find someone who knows how to use it, and pick their brains. That's because there are a lot of important principles (eg 3rd normal form) which will are a lot easier to learn through discussion rather than from books. If you want to teach yourself, you should learn the syntax for doing basic selects, joins, updates, deletes, and group by queries. You should also learn the "Swiss army knife" of selects, the CASE statement. Too many people don't. Many of the tutorials recommended in this thread will do that. Then you need to try to solve SQL problems. I'm sure that Joe Celko's SQL Puzzles and Answers is a good source of them, though it may be a little advanced. This will let you actually write SQL. But you still need to learn how to organize a database. Which for most purposes means that you really need to learn what 3rd normal form looks like. You don't have to be able to give a formal definition of it, just recognize it when you see it, and know how to adjust something to be in that format. Lots of references will explain it, but you won't know if you're reading them correctly. This is where it really, really helps to have access to someone who can look at a table layout and tell you, "That's right" vs "That's wrong, here's what needs to be changed." Failing all else, you could post a question here with a proposed layout. But a back and forth discussion with a live person would still be preferable IMO. A: Try Wikipedia, http://www.w3schools.com/sql/default.asp and http://www.sql-tutorial.net/ Also check YouTube for SQL Videos. A: You are correct, SQLite is a great place to start because it is free, lightweight, and available on many platforms. This is only a start though. SQLite is very liberal on SQL syntax and lacks an intneral programming language like DBMS systems have. Still, if you want to start and learn with minimal overhead, SQLite is the way to go. A: SQLite is nice and they have really nice documentation, however you should be aware that it is not a full featured SQL database like MySQL, Postgres or the commercial variants. SQLite's API relies on callbacks which is a fine model, but not all database APIs work that way. If you are familiar with Perl, then DBI is another nice way to explore SQL. /Allan A: "A Gentle Introduction to SQL" - You can even practice "live queries" right on this tutorial website. http://sqlzoo.net/ A: I always recommend The Practical SQL Handbook for a good starting point for beginners - especially those who have seen SQL but never understood how to build up a query them selves or how they work. All Celko's books are great. Hernandez's Mere Mortals book is good. Ken Henderson's books are also excellent. A: Reading up a bit on relational algebra is a good way to understand the underlying concepts of relational databases. A: Jeo Clecko's SQL for smarties is excellent. A: I recommend the exercises at this site: sql-ex.ru You can even get a certificate if you do the right. A: Start with Ideone and try queries on line just with a web browser. A: If you program using the .NET framework, then learning LINQ might be a good place to start. The LINQ "engine" will handle the back end communication with the database (or objects, or entities, or XML, etc.) for you. If you want to dig deeper, you can explore the SQL generated by the LINQ that you write. A: If you already know a thing or two about web applications, then that would be a good place to start. Nearly every serious webapp uses an SQL database as its backend. A: The folks at Head First have come out with a book. Going by how good their other books are, I'd recommend this one. Haven't read it yet though. (LINK) A: You may want to consider starting with MySQL as it is widely documented and very easy to get started with. You can download the Community Edition and then add the GUI Tools and you'll both GUI and command line interfaces. A: Read a book to start learning about SQL. I read Beginning SQL Queries from Apress not long ago, and found it clear and logically written for a beginner (I reviewed it for a colleague). A: I learnt 90% of what I know about SQL from here. In 1997. I think it still stands up. A: Hey although not complete it's great to get hands on with SQLite as mentioned above, Google 'Learn SQL the hard way' and there is an online book which you can work through which uses SQLite. Google is great for downloading pdf's for free 'Cough Cough' but try http://www.sqlfiddle.com/ It's an online platform which is free! No log in required just go to their page, create your database in whichever language you want (That's the best bit I choose T-SQL as I'm learning that), and then you can query it as much as you like. I'm learning with a pdf file which has opensource SQL files you can download to follow along, and SQLFiddle has been great to learn vendor specific SQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/110124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to retrieve all keys (or values) from a std::map and put them into a vector? This is one of the possible ways I come out: struct RetrieveKey { template <typename T> typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; } }; map<int, int> m; vector<int> keys; // Retrieve all keys transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey()); // Dump all keys copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n")); Of course, we can also retrieve all values from the map by defining another functor RetrieveValues. Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.) A: I think the BOOST_FOREACH presented above is nice and clean, however, there is another option using BOOST as well. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> std::map<int, int> m; std::vector<int> keys; using namespace boost::lambda; transform( m.begin(), m.end(), back_inserter(keys), bind( &std::map<int,int>::value_type::first, _1 ) ); copy( keys.begin(), keys.end(), std::ostream_iterator<int>(std::cout, "\n") ); Personally, I don't think this approach is as clean as the BOOST_FOREACH approach in this case, but boost::lambda can be really clean in other cases. A: Bit of a c++11 take: std::map<uint32_t, uint32_t> items; std::vector<uint32_t> itemKeys; for (auto & kvp : items) { itemKeys.emplace_back(kvp.first); std::cout << kvp.first << std::endl; } A: Here's a nice function template using C++11 magic, working for both std::map, std::unordered_map: template<template <typename...> class MAP, class KEY, class VALUE> std::vector<KEY> keys(const MAP<KEY, VALUE>& map) { std::vector<KEY> result; result.reserve(map.size()); for(const auto& it : map){ result.emplace_back(it.first); } return result; } Check it out here: http://ideone.com/lYBzpL A: Also, if you have Boost, use transform_iterator to avoid making a temporary copy of the keys. A: There is a boost range adaptor for this purpose: #include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm/copy.hpp> vector<int> keys; boost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys)); There is a similar map_values range adaptor for extracting the values. A: C++0x has given us a further, excellent solution: std::vector<int> keys; std::transform( m_Inputs.begin(), m_Inputs.end(), std::back_inserter(keys), [](const std::map<int,int>::value_type &pair){return pair.first;}); A: You can use the versatile boost::transform_iterator. The transform_iterator allows you to transform the iterated values, for example in our case when you want to deal only with the keys, not the values. See http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example A: With the structured binding (“destructuring”) declaration syntax of C++17, you can do this, which is easier to understand. // To get the keys std::map<int, double> map; std::vector<int> keys; keys.reserve(map.size()); for(const auto& [key, value] : map) { keys.push_back(key); } // To get the values std::map<int, double> map; std::vector<double> values; values.reserve(map.size()); for(const auto& [key, value] : map) { values.push_back(value); } A: Yet Another Way using C++20 The ranges library has a keys view, which retrieves the first element in a pair/tuple-like type: #include <ranges> auto kv = std::views::keys(m); std::vector<int> keys{ kv.begin(), kv.end() }; Two related views worth mentioning: * *values - to get the values in a map (2nd element in a pair/tuple-like type) *elements - to get the nth elements in a tuple-like type A: The best non-sgi, non-boost STL solution is to extend map::iterator like so: template<class map_type> class key_iterator : public map_type::iterator { public: typedef typename map_type::iterator map_iterator; typedef typename map_iterator::value_type::first_type key_type; key_iterator(const map_iterator& other) : map_type::iterator(other) {} ; key_type& operator *() { return map_type::iterator::operator*().first; } }; // helpers to create iterators easier: template<class map_type> key_iterator<map_type> key_begin(map_type& m) { return key_iterator<map_type>(m.begin()); } template<class map_type> key_iterator<map_type> key_end(map_type& m) { return key_iterator<map_type>(m.end()); } and then use them like so: map<string,int> test; test["one"] = 1; test["two"] = 2; vector<string> keys; // // method one // key_iterator<map<string,int> > kb(test.begin()); // key_iterator<map<string,int> > ke(test.end()); // keys.insert(keys.begin(), kb, ke); // // method two // keys.insert(keys.begin(), // key_iterator<map<string,int> >(test.begin()), // key_iterator<map<string,int> >(test.end())); // method three (with helpers) keys.insert(keys.begin(), key_begin(test), key_end(test)); string one = keys[0]; A: I found the following three lines of code as the easiest way: // save keys in vector vector<string> keys; for (auto & it : m) { keys.push_back(it.first); } It is a shorten version of the first way of this answer. A: Using ranges in C++20 you can use std::ranges::copy like this #include <ranges> std::map<int,int> mapints; std::vector<int> vints; std::ranges::copy(mapints | std::views::keys, std::back_inserter(vints)); if you want values instead of keys std::ranges::copy(mapints | std::views::values, std::back_inserter(vints)); and if you don't like the pipe syntax std::ranges::copy(std::views::values(mapints), std::back_inserter(vints)); A: Based on @rusty-parks solution, but in c++17: std::map<int, int> items; std::vector<int> itemKeys; for (const auto& [key, _] : items) { itemKeys.push_back(key); } A: While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult. I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this: std::map<int, int> m; std::vector<int> key, value; for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); std::cout << "Key: " << it->first << std::endl(); std::cout << "Value: " << it->second << std::endl(); } Or even simpler, if you are using Boost: map<int,int> m; pair<int,int> me; // what a map<int, int> is made of vector<int> v; BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n"; } Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing. A: @DanDan's answer, using C++11 is: using namespace std; vector<int> keys; transform(begin(map_in), end(map_in), back_inserter(keys), [](decltype(map_in)::value_type const& pair) { return pair.first; }); and using C++14 (as noted by @ivan.ukr) we can replace decltype(map_in)::value_type with auto. A: //c++0x too std::map<int,int> mapints; std::vector<int> vints; for(auto const& imap: mapints) vints.push_back(imap.first); A: Your solution is fine but you can use an iterator to do it: std::map<int, int> m; m.insert(std::pair<int, int>(3, 4)); m.insert(std::pair<int, int>(5, 6)); for(std::map<int, int>::const_iterator it = m.begin(); it != m.end(); it++) { int key = it->first; int value = it->second; //Do something } A: The SGI STL has an extension called select1st. Too bad it's not in standard STL! A: The following functor retrieves the key set of a map: #include <vector> #include <iterator> #include <algorithm> template <class _Map> std::vector<typename _Map::key_type> keyset(const _Map& map) { std::vector<typename _Map::key_type> result; result.reserve(map.size()); std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) { return kvpair.first; }); return result; } Bonus: The following functors retrieve the value set of a map: #include <vector> #include <iterator> #include <algorithm> #include <functional> template <class _Map> std::vector<typename _Map::mapped_type> valueset(const _Map& map) { std::vector<typename _Map::mapped_type> result; result.reserve(map.size()); std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) { return kvpair.second; }); return result; } template <class _Map> std::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map) { std::vector<std::reference_wrapper<typename _Map::mapped_type>> result; result.reserve(map.size()); std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) { return std::ref(kvpair.second); }); return result; } Usage: int main() { std::map<int, double> map{ {1, 9.0}, {2, 9.9}, {3, 9.99}, {4, 9.999}, }; auto ks = keyset(map); auto vs = valueset(map); for (auto& k : ks) std::cout << k << '\n'; std::cout << "------------------\n"; for (auto& v : vs) std::cout << v << '\n'; for (auto& v : vs) v += 100.0; std::cout << "------------------\n"; for (auto& v : vs) std::cout << v << '\n'; std::cout << "------------------\n"; for (auto& [k, v] : map) std::cout << v << '\n'; return 0; } Expected output: 1 2 3 4 ------------------ 9 9.9 9.99 9.999 ------------------ 109 109.9 109.99 109.999 ------------------ 109 109.9 109.99 109.999 A: With atomic map example #include <iostream> #include <map> #include <vector> #include <atomic> using namespace std; typedef std::atomic<std::uint32_t> atomic_uint32_t; typedef std::map<int, atomic_uint32_t> atomic_map_t; int main() { atomic_map_t m; m[4] = 456; m[2] = 45678; vector<int> v; for(map<int,atomic_uint32_t>::iterator it = m.begin(); it != m.end(); ++it) { v.push_back(it->second); cout << it->first << " "<<it->second<<"\n"; } return 0; } A: You can use get_map_keys() from fplus library: #include<fplus/maps.hpp> // ... int main() { map<string, int32_t> myMap{{"a", 1}, {"b", 2}}; vector<string> keys = fplus::get_map_keys(myMap); // ... return 0; } A: With Eric Niebler's range-v3 library, you can take a range and write it out directly to a container using ranges::to (hopefully soon in std, maybe C++26?): [Demo] #include <fmt/ranges.h> #include <map> #include <range/v3/all.hpp> int main() { std::map<int, int> m{ {1, 100}, {2, 200}, {3, 300} }; auto keys{ m | ranges::views::keys | ranges::to<std::vector<int>>() }; fmt::print("{}", keys); } // Outputs: [1, 2, 3] A: (I'm always wondering why std::map does not include a member function for us to do so.) Because it can't do it any better than you can do it. If a method's implementation will be no superior to a free function's implementation then in general you should not write a method; you should write a free function. It's also not immediately clear why it's useful anyway. A: Slightly similar to one of examples here, simplified from std::map usage perspective. template<class KEY, class VALUE> std::vector<KEY> getKeys(const std::map<KEY, VALUE>& map) { std::vector<KEY> keys(map.size()); for (const auto& it : map) keys.push_back(it.first); return keys; } Use like this: auto keys = getKeys(yourMap);
{ "language": "en", "url": "https://stackoverflow.com/questions/110157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "328" }
Q: How do I save a model with this dynamically generated field? I have a rails model that looks something like this: class Recipe < ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end The idea is that when I create the ingredient from the webpage, I pass in the ingredients_string and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the ingredient_string is defined in the set_ingredients method? A: Using these two together are probably causing your issues. Both are trying to define an ingredients_string method that do different things attr_accessor :ingredients_string def ingredients_string ingredients.join("\n") end Get rid of the attr_accessor, the before_save, set_ingredients method and define your own ingredients_string= method, something like this: def ingredients_string=(ingredients) ingredients.each { |x| x.destroy } ingredients_string ||= false if ingredients_string ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end Note I just borrowed your implementation of set_ingredients. There's probably a more elegant way to break up that string and create/delete Ingredient model associations as needed, but it's late and I can't think of it right now. :) A: The previous answer is very good but it could do with a few changes. def ingredients_string=(text) ingredients.each { |x| x.destroy } unless text.blank? text.split("\n").each do |x| ingredient = Ingredient.find_or_create_by_ingredient_string(:ingredient_string => x) self.ingredients A: I basically just modified Otto's answer: class Recipe < ActiveRecord::Base has_many :ingredients attr_accessible :title, :directions, :ingredients, :ingredients_string def ingredients_string=(ingredient_string) ingredient_string ||= false if ingredient_string self.ingredients.each { |x| x.destroy } unless ingredient_string.blank? ingredient_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string => x) self.ingredients << ingredient end end end end def ingredients_string ingredients.join("\n") end end
{ "language": "en", "url": "https://stackoverflow.com/questions/110163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access the current Subversion build number? How can you automatically import the latest build/revision number in subversion? The goal would be to have that number visible on your webpage footer like SO does. A: If you have tortoise SVN you can use SubWCRev.exe Create a file called: RevisionInfo.tmpl SvnRevision = $WCREV$; Then execute this command: SubWCRev.exe . RevisionInfo.tmpl RevisionInfo.txt It will create a file ReivisonInfo.txt with your revision number as follows: SvnRevision = 5000; But instead of using the .txt you could use whatever source file you want, and have access to the reivsion number within your source code. A: You don't say what programming language/framework you're using. Here's how to do it in Python using PySVN import pysvn repo = REPOSITORY_LOCATION rev = pysvn.Revision( pysvn.opt_revision_kind.head ) client = pysvn.Client() info = client.info2(repo,revision=rev,recurse=False) revno = info[0][1].rev.number # revision number as an integer A: Using c# and SharpSvn (from http://sharpsvn.net) the code would be: //using SharpSvn; long revision = -1; using(SvnClient client = new SvnClient()) { client.Info(path, delegate(object sender, SvnInfoEventArgs e) { revision = e.Revision; }); } A: Have your build process call the svnversion command, and embed its output into generated {source|binaries}. This will not only give the current revision (as many other examples here do), but its output string will also tell whether a build is being done in a mixed tree or a tree which doesn't exactly match the revision number in question (ie. a tree with local changes). With a standard tree: $ svnversion 3846 With a modified tree: $ echo 'foo' >> project-ext.dtd $ svnversion 3846M With a mixed-revision, modified tree: $ (cd doc; svn up >/dev/null 2>/dev/null) $ svnversion 3846:4182M A: In my latest project I solved this problem by using several tools, SVN, NAnt, and a custom NAnt task. * *Use NAnt to execute svn info --xml ./svnInfo.xml *Use NAnt to pull the revision number from the xml file with <xmlpeek> *Use a custom NAnt task to update the AssemblyVersion attribute in the AssemblyInfo.cs file with the latest with the version number (e.g., major.minor.maintenance, revision) before compiling the project. The version related sections of my build script look like this: <!-- Retrieve the current revision number for the working directory --> <exec program="svn" commandline='info --xml' output="./svnInfo.xml" failonerror="false"/> <xmlpeek file="./svnInfo.xml" xpath="info/entry/@revision" property="build.version.revision" if="${file::exists('./svnInfo.xml')}"/> <!-- Custom NAnt task to replace strings matching a pattern with a specific value --> <replace file="${filename}" pattern="AssemblyVersion(?:Attribute)?\(\s*?\&quot;(?&lt;version&gt;(?&lt;major&gt;[0-9]+)\.(?&lt;minor&gt;[0-9]+)\.(?&lt;build&gt;[0-9]+)\.(?&lt;revision&gt;[0-9]+))\&quot;\s*?\)" value="AssemblyVersion(${build.version})" outfile="${filename}"/> The credit for the regular expression goes to: http://code.mattgriffith.net/UpdateVersion/. However, I found that UpdateVersion did not meet my needs as the pin feature was broken in the build I had. Hence the custom NAnt task. If anyone is interested in the code, for the custom NAnt replace task let me know. Since this was for a work related project I will need to check with management to see if we can release it under a friendly (free) license. A: Here is a hint, how you might use Netbeans' capabilities to create custom ant tasks which would generate scm-version.txt: Open your build.xml file, and add following code right after <import file="nbproject/build-impl.xml"/> <!-- STORE SUBVERSION BUILD STRING --> <target name="-pre-compile"> <exec executable="svnversion" output="${src.dir}/YOUR/PACKAGE/NAME/scm-version.txt"/> </target> Now, Netbeans strores the Subversion version string to scm-version.txt everytime you make clean/build. You can read the file during runtime by doing: getClass().getResourceAsStream("scm-version.txt"); // ... Don't forget to mark the file scm-version.txt as svn:ignore. A: In Rails I use this snippet in my environment.rb which gives me a constant I can use throughout the application (like in the footer of an application layout). SVN_VERSION = IO.popen("svn info").readlines[4].strip.split[1] A: The svnversion command is the correct way to do this. It outputs the revision number your entire working copy is at, or a range of revisions if your working copy is mixed (e.g. some directories are up to date and some aren't). It will also indicate if the working copy has local modifications. For example, in a rather unclean working directory: $ svnversion 662:738M The $Revision$ keyword doesn't do what you want: it only changes when the containing file does. The Subversion book gives more detail. The "svn info" command also doesn't do what you want, as it only tells you the state of your current directory, ignoring the state of any subdirectories. In the same working tree as the previous example, I had some subdirectories which were newer than the directory I was in, but "svn info" doesn't notice: $ svn info ... snip ... Revision: 662 It's easy to incorporate svnversion into your build process, so that each build gets the revision number in some runtime-accessible form. For a Java project, for example, I had our makefile dump the svnversion output into a .properties file. A: svn info <Repository-URL> or svn info --xml <Repository-URL> Then look at the result. For xml, parse /info/entry/@revision for the revision of the repository (151 in this example) or /info/entry/commit/@revision for the revision of the last commit against this path (133, useful when working with tags): <?xml version="1.0"?> <info> <entry kind="dir" path="cmdtools" revision="151"> <url>http://myserver/svn/stumde/cmdtools</url> <repository> <root>http://myserver/svn/stumde</root> <uuid>a148ce7d-da11-c240-b47f-6810ff02934c</uuid> </repository> <commit revision="133"> <author>mstum</author> <date>2008-07-12T17:09:08.315246Z</date> </commit> </entry> </info> I wrote a tool (cmdnetsvnrev, source code included) for myself which replaces the Revision in my AssemblyInfo.cs files. It's limited to that purpose though, but generally svn info and then processing is the way to go. A: Add svn:keywords to the SVN properties of the source file: svn:keywords Revision Then in the source file include: private const string REVISION = "$Revision$"; The revision will be updated with the revision number at the next commit to (e.g.) "$Revision: 4455$". You can parse this string to extract just the revision number. A: Well, you can run 'svn info' to determine the current revision number, and you could probably extract that pretty easily with a regex, like "Revision: ([0-9]+)". A: If you are running under GNU/Linux, cd to the working copy's directory and run: svn -u status | grep Status\ against\ revision: | awk '{print $4}' From my experience, svn info does not give reliable numbers after renaming directories. A: You want the Subversion info subcommand, as follows: $ svn info . Path: . URL: http://trac-hacks.org/svn/tracdeveloperplugin/trunk Repository Root: http://trac-hacks.org/svn Repository UUID: 7322e99d-02ea-0310-aa39-e9a107903beb Revision: 4190 Node Kind: directory Schedule: normal Last Changed Author: coderanger Last Changed Rev: 3397 Last Changed Date: 2008-03-19 00:49:02 -0400 (Wed, 19 Mar 2008) In this case, there are two revision numbers: 4190 and 3397. 4190 is the last revision number for the repository, and 3397 is the revision number of the last change to the subtree that this workspace was checked out from. You can specify a path to a workspace, or a URL to a repository. A C# fragment to extract this under Windows would look something like this: Process process = new Process(); process.StartInfo.FileName = @"svn.exe"; process.StartInfo.Arguments = String.Format(@"info {0}", path); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); // Parse the svn info output for something like "Last Changed Rev: 1234" using (StreamReader output = process.StandardOutput) { Regex LCR = new Regex(@"Last Changed Rev: (\d+)"); string line; while ((line = output.ReadLine()) != null) { Match match = LCR.Match(line); if (match.Success) { revision = match.Groups[1].Value; } } } (In my case, we use the Subversion revision as part of the version number for assemblies.) A: I use the MSBuild Community Tasks project which has a tool to retrieve the SVN revision number and add it to your AssemblyInfo.vb. You can then use reflection to retrieve this string to display it in your UI. Here's a full blog post with instructions. A: if you're using svnant, you can use wcVersion, which duplicates svnveresion and returns digestible values. see: http://subclipse.tigris.org/svnant/svn.html#wcVersion A: I created an SVN version plug-in for the Build Version Increment project on CodePlex. This SVN plug-in will pull the latest change revision number from your working copy and allow you to use that in your version number, which should accomplish exactly what you're trying to do. Build Version Increment is pretty flexible and will allow you to set up how the versioning is done in a number of ways. BVI only works with Visual Studio, but since you're using Asp.Net, that won't be a problem. It doesn't require writing any code or editing xml, so yay!
{ "language": "en", "url": "https://stackoverflow.com/questions/110175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Feedback on using Google App Engine? Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other than a toy problem? I see some good example apps out there, so I would assume this is good enough for the real deal, but wanted to get some feedback. Any other success/failure notes would be great. A: I used GAE to build http://www.muspy.com It's a bit more than a toy project but not overly complex either. I still depend on a few issues to be addressed by Google, but overall developing the website was an enjoyable experience. If you don't want to deal with hosting issues, server administration, etc, I can definitely recommend it. Especially if you already know Python and Django. A: I think App Engine is pretty cool for small projects at this point. There's a lot to be said for never having to worry about hosting. The API also pushes you in the direction of building scalable apps, which is good practice. * *app-engine-patch is a good layer between Django and App Engine, enabling the use of the auth app and more. *Google have promised an SLA and pricing model by the end of 2008. *Requests must complete in 10 seconds, sub-requests to web services required to complete in 5 seconds. This forces you to design a fast, lightweight application, off-loading serious processing to other platforms (e.g. a hosted service or an EC2 instance). *More languages are coming soon! Google won't say which though :-). My money's on Java next. A: I have tried app engine for my small quake watch application http://quakewatch.appspot.com/ My purpose was to see the capabilities of app engine, so here are the main points: * *it doesn't come by default with Django, it has its own web framework which is pythonic has URL dispatcher like Django and it uses Django templates So if you have Django exp. you will find it easy to use * *But you can use any pure python framework and Django can be easily added see http://code.google.com/appengine/articles/django.html google-app-engine-django (http://code.google.com/p/google-app-engine-django/) project is excellent and works almost like working on a Django project *You can not execute any long running process on server, what you do is reply to request and which should be quick otherwise appengine will kill it So if your app needs lots of backend processing appengine is not the best way otherwise you will have to do processing on a server of your own *My quakewatch app has a subscription feature, it means I had to email latest quakes as they happend, but I can not run a background process in app engine to monitor new quakes solution here is to use a third part service like pingablity.com which can connect to one of your page and which executes the subscription emailer but here also you will have to take care that you don't spend much time here or break task into several pieces *It provides Django like modeling capabilities but backend is totally different but for a new project it should not matter. But overall I think it is excellent for creating apps which do not need lot of background processing. Edit: Now task queues can be used for running batch processing or scheduled tasks Edit: after working/creating a real application on GAE for a year, now my opnion is that unless you are making a application which needs to scale to million and million of users, don't use GAE. Maintaining and doing trivial tasks in GAE is a headache due to distributed nature, to avoid deadline exceeded errors, count entities or do complex queries requires complex code, so small complex application should stick to LAMP. Edit: Models should be specially designed considering all the transactions you wish to have in future, because entities only in same entity group can be used in a transaction and it makes the process of updating two different groups a nightmare e.g. transfer money from user1 to user2 in transaction is impossible unless they are in same entity group, but making them same entity group may not be best for frequent update purposes.... read this http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine A: This question has been fully answered. Which is good. But one thing perhaps is worth mentioning. The google app engine has a plugin for the eclipse ide which is a joy to work with. If you already do your development with eclipse you are going to be so happy about that. To deploy on the google app engine's web site all I need to do is click one little button - with the airplane logo - super. A: Take a look the the sql game, it is very stable and actually pushed traffic limits at one point so that it was getting throttled by Google. I have seen nothing but good news about App Engine, other than hosting you app on servers someone else controls completely. A: I used GAE to build a simple application which accepts some parameters, formats and send email. It was extremely simple and fast. I also made some performance benchmarks on the GAE datastore and memcache services (http://dbaspects.blogspot.com/2010/01/memcache-vs-datastore-on-google-app.html ). It is not that fast. My opinion is that GAE is serious platform which enforce certain methodology. I think it will evolve to the truly scalable platform, where bad practices simply not allowed. A: I used GAE for my flash gaming site, Bearded Games. GAE is a great platform. I used Django templates which are so much easier than the old days of PHP. It comes with a great admin panel, and gives you really good logs. The datastore is different than a database like MySQL, but it's much easier to work with. Building the site was easy and straightforward and they have lots of helpful advice on the site. A: I am using GAE to host several high-traffic applications. Like on the order of 50-100 req/sec. It is great, I can't recommend it enough. My previous experience with web development was with Ruby (Rails/Merb). Learning Python was easy. I didn't mess with Django or Pylons or any other framework, just started from the GAE examples and built what I needed out of the basic webapp libraries that are provided. If you're used to the flexibility of SQL the datastore can take some getting used to. Nothing too traumatic! The biggest adjustment is moving away from JOINs. You have to shed the idea that normalizing is crucial. Ben A: I used GAE and Django to build a Facebook application. I used http://code.google.com/p/app-engine-patch as my starting point as it has Django 1.1 support. I didn't try to use any of the manage.py commands because I assumed they wouldn't work, but I didn't even look into it. The application had three models and also used pyfacebook, but that was the extent of the complexity. I'm in the process of building a much more complicated application which I'm starting to blog about on http://brianyamabe.com. A: One of the compelling reasons I have come across for using Google App Engine is its integration with Google Apps for your domain. Essentially it allows you to create custom, managed web applications that are restricted to the (controlled) logins of your domain. Most of my experience with this code was building a simple time/task tracking application. The template engine was simple and yet made a multi-page application very approachable. The login/user awareness api is similarly useful. I was able to make a public page/private page paradigm without too much issue. (a user would log in to see the private pages. An anonymous user was only shown the public page.) I was just getting into the datastore portion of the project when I got pulled away for "real work". I was able to accomplish a lot (it still is not done yet) in a very little amount of time. Since I had never used Python before, this was particularly pleasant (both because it was a new language for me, and also because the development was still fast despite the new language). I ran into very little that led me to believe that I wouldn't be able to accomplish my task. Instead I have a fairly positive impression of the functionality and features. That is my experience with it. Perhaps it doesn't represent more than an unfinished toy project, but it does represent an informed trial of the platform, and I hope that helps. A: The "App Engine running Django" idea is a bit misleading. App Engine replaces the entire Django model layer so be prepared to spend some time getting acclimated with App Engine's datastore which requires a different way of modeling and thinking about data.
{ "language": "en", "url": "https://stackoverflow.com/questions/110186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "127" }
Q: Want to download a Git repository, what do I need (windows machine)? I want to download this open source application, and they are using Git. What do I need to download the code base? Update How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it. A: Download Git on Msys. Then: git clone git://project.url.here A: I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository. And you get a lot of beneficial side-effects! (:-) A: Install mysysgit. (Same as Greg Hewgill's answer.) Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.) After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok. This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :) A: To change working directory in GitMSYS's Git Bash you can just use cd cd /path/do/directory Note that: * *Directory separators use the forward-slash (/) instead of backslash. *Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff". *Spaces can be escaped with a backslash (\) *Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories. Also, you can right click in Windows Explorer on a directory and "Git Bash here".
{ "language": "en", "url": "https://stackoverflow.com/questions/110205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: Is "int?" somehow a reference type? What is the behind-the-scenes difference between int? and int data types? Is int? somehow a reference type? A: In addition to "int?" being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?" and "int". This also means that any boxing operation will implicitly box the actual value (i.e., it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object). I ran into many of these issues when trying to create Nullable when you don't know T at compile time (you only know it at runtime). http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html A: ? wraps the value type (T) in a Nullable<T> struct: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx A: For one of the better "behind the scenes" discussions about Nullable types you should look at CLR Via C# by Jeffrey Richter. The whole of Chapter 18 is devoted to discussing in detail Nullable types. This book is also excellent for many other areas of the .NET CLR internals. A: I learned that you must explicitly cast a nullable value type to a none-nullable value type, as the following example shows: int? n = null; //int m1 = n; // Doesn't compile int n2 = (int)n; // Compiles, but throws an exception if n is null MS Document
{ "language": "en", "url": "https://stackoverflow.com/questions/110229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: CakePHP multi-model view I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go: I have a three table structure for registering users: Users, Addresses and Contacts. I have to build a view with info of all three tables like: Full Name: [ ] (from Users) Shipping Address: [ ] (from Address) Mobile Phone: [ ] (from Contact) e-Mail Address: [ ] (from Contact) What is the best way to deal with this situation. Specially for saving. Creating a new Model to represent this, that will have a save() method itself (Maybe a sql view in the database) Create a Controller to deal with this View that binds or unbinds info I wonder still how I will handle both contacts as they will be 2 different INSERT's Any hint or resources I can dig of I will be glad. A: CakePHP allows you to easily maintains link between your models using relationship, see http://book.cakephp.org/view/78/Associations-Linking-Models-Together for the complete detail. Then retreiving the right User, you'll also get "for free", its address and contact informations. A: If your using the latest 1.2 code, check out Model::saveAll in the api eg. Your view might look something like this: echo $form->create('User', array('action' => 'add'); echo $form->input('User.name'); echo $form->input('Address.line_1'); echo $form->input('Contact.tel'); echo $form->end('Save'); Then in your Users controller add method you'd have something like: ... if($this->User->saveAll($this->data)) { $this->Session->setFlash('Save Successful'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash('Please review the form for errors'); } ... In your User model you will need something like: var $hasOne = array('Address', 'Contact'); Hope that helps! http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1 A: 3 models : User, Address, Contact User hasOne Address, Contact Address belongsTo User Contact belongsTo User in your model you define this like this : class User extends AppModel { var $name = 'User'; var $hasOne = array('Address','Contact'); .. To make this view, you need user_id field ind addresses, and contacts tables To use this in a view, you simply call a find on the User model with a recursive of one (and btw, the users controller only uses User model). $this->User->recursive = 1; $this->set('user', $this->User->find('first', array('conditions'=>array('id'=>666))); This will result in this array for your view : array( 'Use' => array( 'id' => 666, 'name' => 'Alexander' ), 'Address' => array( 'id' => 123, 'zip' => 555 ), 'Contact' => array( 'id' => 432, 'phone' => '555-1515' ));
{ "language": "en", "url": "https://stackoverflow.com/questions/110232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Building and deploying dll on windows: SxS, manifests and all that jazz Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (http://www.ddj.com/windows/184406482). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ? Basically, where can I find any kind of specification instead of MS jargon ? Thank you to everyone who answered, this was really helpful, A: We use a simple include file in all our applications & DLL's, vcmanifest.h, then set all projects to embedded the manifest file. vcmanifest.h /*----------------------------------------------------------------------------*/ #if _MSC_VER >= 1400 /*----------------------------------------------------------------------------*/ #pragma message ( "Setting up manifest..." ) /*----------------------------------------------------------------------------*/ #ifndef _CRT_ASSEMBLY_VERSION #include <crtassem.h> #endif /*----------------------------------------------------------------------------*/ #ifdef WIN64 #pragma message ( "processorArchitecture=amd64" ) #define MF_PROCESSORARCHITECTURE "amd64" #else #pragma message ( "processorArchitecture=x86" ) #define MF_PROCESSORARCHITECTURE "x86" #endif /*----------------------------------------------------------------------------*/ #pragma message ( "Microsoft.Windows.Common-Controls=6.0.0.0") #pragma comment ( linker,"/manifestdependency:\"type='win32' " \ "name='Microsoft.Windows.Common-Controls' " \ "version='6.0.0.0' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='6595b64144ccf1df'\"" ) /*----------------------------------------------------------------------------*/ #ifdef _DEBUG #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT' " \ "version='" _CRT_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #else #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT' " \ "version='" _CRT_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #endif /*----------------------------------------------------------------------------*/ #ifdef _MFC_ASSEMBLY_VERSION #ifdef _DEBUG #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \ "version='" _MFC_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #else #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION ) #pragma comment(linker,"/manifestdependency:\"type='win32' " \ "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \ "version='" _MFC_ASSEMBLY_VERSION "' " \ "processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \ "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"") #endif #endif /* _MFC_ASSEMBLY_VERSION */ /*----------------------------------------------------------------------------*/ #endif /* _MSC_VER */ /*----------------------------------------------------------------------------*/ A: The simplest thing to do: Assuming a default install of VS2005, you will have a path like: C:\Program Files\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT Go, grab the files in this redist folder, and place the .manifest AND the msvcr80.dll (At least) in your applications .exe folder. These files, present in the root of your installation, should enable your exe and all dlls linked against them, to work flawlessly without resorting to merge modules, MSIs or indeed any kind of just-in-time detection that the runtime is not installed. A: Well, I've encountered some of these issues, so perhaps some of my comments will be helpful. * *The manifest is an xml file. While VS can and will make one for you when you compile, the other solution is to produce a resource file (.rc) and compile it into a compiled resource file (.res) using the resource compiler (rc.exe) included with VS. You'll want to run the VS commandline from the tools menu, which will cause rc to be in the path, as well as setting various environmental variables correctly. Then compile your resource. The resulting .res file can be used by other compilers. *Make sure your manifest xml file's size is divisible by 4. Add whitespace in the middle of it to achieve this if needed. Try to avoid having any characters before the openning xml tag or after the closing xml tag. I've sometimes had issues with this. If you do step 2 incorrectly, expect to get side by side configuration errors. You can check if that is your mistake by openning the exe in a resource editor (e.g. devenv.exe) and examining the manifest resource. You can also see an example of a correct manifest by just opening a built file, though note that dlls and exes have tiny differences in what id the resource should be given. You'll probably want to test on Vista to make sure this is working properly. A: Here is the blog entry explaining the rational behind the SxS crt decision for VC++. It includes explaining how bad it is to statically link the crt, and why you shouldn't do that. Here is the documentation on how to statically link the crt. A: They are redistributable and you have redistributable packages inside msvs directory. Build with runtime of your choice, add corresponding package to your installer and don't bother - it will work. The difference is - they are installed in a different place now (but that is also where your app is going to look for libraries). Otherwise, MSDN or basically any not-too-old book on windows c++ programming. A: Thanks for the answer. For deployment per se, I can see 3 options, then: * *Using .msi merge directive. *Using the redistributable VS package and run it before my own installer *Copying the redistributable files along my own application. But in this case, how do I refer to it in a filesystem hierarchy (say bar/foo1/foo1.dll and bar/foo2/foo2.dll refer to msvcr90.dll in bar/) ? I mean besides the obvious and ugly "copy the dll in every directory where you have dll which depends on it). A: You can't use the VC++8 SP1/9 CRT as a merge module on Vista and windows Server 2008 if you have services you want to start or programs that you want to run before the "InstallFinalize" action in the MSI. This is because the dlls are installed in WinSXS in the "InstallFinalize" action. But the MSI "ServiceStart" action comes before this. So use either a bootstrapper "http://www.davidguyer.us/bmg/publish.htm" Or look into using the installer chainging in the installer 4.5. But this means you need a bootstrapper to install 4.5 so it seems a bit pointless.. A: If you intend to deploy the Microsoft DLLs/.manifest files and are using Java JNI then you will need to put them in the bin directory of your JDK/JRE. If you are running the app in JBoss, then you will need to put them in the JBoss/bin directory. You can put your JNI DLL where appropriate for your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/110249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which Python memory profiler is recommended? I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is Python Memory Validator (Windows only). And open source ones are PySizer and Heapy. I haven't tried anyone, so I wanted to know which one is the best considering: * *Gives most details. *I have to do least or no changes to my code. A: I recommend Dowser. It is very easy to setup, and you need zero changes to your code. You can view counts of objects of each type through time, view list of live objects, view references to live objects, all from the simple web interface. # memdebug.py import cherrypy import dowser def start(port): cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': port }) cherrypy.server.quickstart() cherrypy.engine.start(blocking=False) You import memdebug, and call memdebug.start. That's all. I haven't tried PySizer or Heapy. I would appreciate others' reviews. UPDATE The above code is for CherryPy 2.X, CherryPy 3.X the server.quickstart method has been removed and engine.start does not take the blocking flag. So if you are using CherryPy 3.X # memdebug.py import cherrypy import dowser def start(port): cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': port }) cherrypy.engine.start() A: Consider the objgraph library (see this blog post for an example use case). A: Try also the pytracemalloc project which provides the memory usage per Python line number. EDIT (2014/04): It now has a Qt GUI to analyze snapshots. A: My module memory_profiler is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects. After decorating your function with @profile and running your code with the -m memory_profiler flag it will print a line-by-line report like this: Line # Mem usage Increment Line Contents ============================================== 3 @profile 4 5.97 MB 0.00 MB def my_func(): 5 13.61 MB 7.64 MB a = [1] * (10 ** 6) 6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7) 7 13.61 MB -152.59 MB del b 8 13.61 MB 0.00 MB return a A: guppy3 is quite simple to use. At some point in your code, you have to write the following: from guppy import hpy h = hpy() print(h.heap()) This gives you some output like this: Partition of a set of 132527 objects. Total size = 8301532 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 35144 27 2140412 26 2140412 26 str 1 38397 29 1309020 16 3449432 42 tuple 2 530 0 739856 9 4189288 50 dict (no owner) You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse. There is a graphical browser as well, written in Tk. For Python 2.x, use Heapy. A: Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks. Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects. A: I'm developing a memory profiler for Python called memprof: http://jmdana.github.io/memprof/ It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using: from memprof import memprof And decorate your method using: @memprof This is an example on how the plots look like: The project is hosted in GitHub: https://github.com/jmdana/memprof A: I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser
{ "language": "en", "url": "https://stackoverflow.com/questions/110259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "750" }
Q: how do i add project references to swcs in FlashDevelop I am trying to add a project reference or swc to papervision in FlashDevelop but intellisense isn't picking it up. I've done it before but i forgot how. Thanks. A: In the menus: Project -> Properties -> Compiler Options -> SWC Libraries (and then add the path or file to the list) A: Add your swc to the lib folder of your project. Then right-click it and mark "Add To Library".
{ "language": "en", "url": "https://stackoverflow.com/questions/110263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is using Dexter's character sprite okay, or do I have to . Inspiration -- Southpark game (very popular if you see download count on download.com ,,, did he ask for permission ??) I am making a 2d game based on dexter's lab theme. I've got the sprite of dexter from GSA. basically I'm not an artist, so I have to depend on already available sprites, backgrounds, sfx on websites like GameSpriteArchive etc. But is it okay/legal to use the dexter sprite I have got ? I wish to release it publicly too, so shall I have to make lot of changes to do that? Is it possible to get a permission to use the sprite?? My hopes are very less in getting permission. Besides all that my basic plan is - * *Dexter's sprite from google search *Enemy sprites from various GBA/SNES/etc games *tiles/objects from these retro games *Background art and style from blogs and portfolios of artists behind dexter, powerpuff girls, and samurai jack A: I am not a lawyer. This is not legal advice. If you made the sprite yourself, you'd be fine. If you got a release to use it from the creator, you'd be fine. If it was released into the public domain, you'd be fine. Anything else, you'd have a definate problem with. There's also the possible problem you'd have even if you create the sprite yourself -- the likeness of the character is likely copyrighted. However, that's not as cut-and-dried of an issue. Unfortunately, this is one of the things you'd need to ask a real lawyer to get a firm answer on. If it's for your own use and that of some close friends, you might be able to get away with hoping you don't get noticed (like most people who speed). If you're planning to include this in something you distribute to the public (even more so if you sell it), you're likely to run into problems. A: probably not legal, since Dexter's lab is published by Hanna-Barbera and was created by Genndy Tartakovsky. They would have to grant you a license - but it can't hurt to ask! A: You probably won't have to get permission if they don't notice -- it's the old "legal unless you get caught" thing. However, I strongly reccomend that you DO get permission from the creators or not use it at all on purely ethical grounds. After all, you wouldn't want somebody appropriating your work, right?
{ "language": "en", "url": "https://stackoverflow.com/questions/110271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VMware ESX vs. VMware Workstation I'm using VMware Workstation 6.0 for simulation of tight clusters of "blades" in a "chassis". Both the host and target OSs are Linux. Each "chassis" uses a vmnet switch as a virtual backplane, to which the virtual blades connect. Other vmnet switches are used to mediate point-to-point connections between mutiple virtual ethernet adapters on each blade VM. The chassis, and thus the VMs, are brought up and shutdown rather frequently. My scripts (python) make heavy use of the VIX api, and also manipulate the .vmx config file. What do I gain and/or lose going from VMware Workstation to ESX? Do my scripts that use the VIX api still work? Do my rather complicated virtual network topologies, with lots of vmnet switches defined as "custom", still work the same way? Is the syntax and semantics of the .vmx config file the same between Workstation and ESX?Thanks in advance for your help. A: The first thing you'll gain by switching will be a substantially more powerful platform that's running directly on the bare-metal of your server. From my experience, moving up the VMware application stack has never been problematic (Server to Workstation to ESX). However, I would verify this by exporting all of your VMs from the workstation install to an ESX install to make sure you're not seeing any 'weird' issues related to running the high-end tool from VMware. From my [limited] experience, scripts also carry-over cleanly: each offering moving up their product line doesn't break lower-level tools, but do add substantial improvements. A: You get scalability and performance. ESX scales much better and run much faster than any of VMware desktop products like Workstation or Player. A: You should not lose anything. ESXi performs all the functions that Workstation does, plus a lot more. I use ESXi at home and Workstation on my laptop. You will gain more fine-grained control over the virtual networks, over storage, snapshots, cloning, quiescing guest OSes, and many more advanced options in ESXi configuration. A: One thing to note is the considerable expense of the ESX line compared to Workstation. If you're working for a successful company, though, the cost can easily be justified as ESX is (imho) da bomb. Also, FYI, the old free VMware Server options definitely had a whole different interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/110274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you find media resources for game-dev? I've been wondering, as a lone game developer, or to say a part of team which has only got programmers and people who like to play games... How do I manage the void created by lack of artists (sprites/tiles/animations) in such a situation??? What do you do in that case? and suppose I am a student, with no money to hire artists, is there a place where I can get these resources legally & free ? A: Recently I needed some free-as-in-speech sound samples, and found freesounds.org where all sound samples are under a CC license. Not quite sure where I would go for images/textures though. A: Have you tried to attract a game playing artist to join your effort? Lot's of people play games (even artists). The idea of collaborating on a game may be enough incentive, particulary if they get credit in the game, and samples for a portfolio. A: For images there is also several sites like freespace pointed out for instance http://commons.wikimedia.org/ another great resource for getting artwork/images for your projects is to reach out to art schools or other locations that you know artists frequent and permit them to sign or get credit for any creation you use. A: For a hobbyist, the simplest answer is that you shouldn't worry about your game's art. You can get by fine with only programmer's art. After you've created a working gameplay prototype, only then should you look for artists. For an independent developer, you would need cash to hire artists. There's no getting around this. Just think of it this way: you get what you pay for. Fun trivia: the most popular programmer's art is Kirby. The developers were using a pink fluffy sprite as placeholder's art until the the creator, Masahiro Sakurai, decided that the art fits the game and should stay.
{ "language": "en", "url": "https://stackoverflow.com/questions/110279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How is style inherited How can I make a style have all of the properties of the style defined in .a .b .c except for background-color (or some other property)? This does not seem to work. .a .b .c { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .a .b .c .d { background-color: green; } A: .a, .b, .c, .d { background-color: green; } .a, .b, .c { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } Is this what you meant? Order of definitions is very meaningful, because latter will apply. A: .a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .a {background-color: red;} .b {background-color: blue;} .c {background-color: green;} A: You would add the .d class selector as a selector for your first rule, then add a rule to redefine the background color for .d: .a .b .c, .d { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .d { background-color: green; } That is the answer to the question that you've asked, but I have a feeling that this is not what you are looking for. Maybe you should post an example of your markup and tell us what styles you would like to see applied so we can help you better. A: It seems you've got things mixed up there. If you want to apply the properties in the first set of brackets to ".d" as well it will need to be specified in the selector list. You also need to separate the selectors with commas so they become a list, not an inheritance. Example: <html> <head> <style type="text/css"> .a, .b, .c, .d { background-color: #0000FF; color: #FF0000; border: 1px solid #00FF00; font-weight: bold; } .d { background-color: white; } </style> </head> <body style="background-color: grey;"> <p class="a">Lorem ipsum dolor sit amet.</p> <p class="b">Lorem ipsum dolor sit amet.</p> <p class="c">Lorem ipsum dolor sit amet.</p> <p class="d">Lorem ipsum dolor sit amet.</p> </body> </html> A: I think you're thinking about this a little backwards, so let's try to sort out the language your are using. .a .b .c{ background-color: #0000FF; color: #ffffff; } Looking at the above CSS, the ".a .b .c" part is the selector, and the part between the braces is the style. That selector says 'find me all of the elements with a class with "c" who are inside of elements that have a class of "b" who are inside of elements with a class "a", and apply these styles to them' -- it's a rule the says which elements on the page will get the look you want. More than one selector can match the same element on the page, and there are rules for what order they are applied to the element (http://www.w3.org/TR/CSS2/cascade.html). The simple rule is that more "Specific" selectors override less "specific" selectors. "div.blueBanner p a:hover.highlight" is much more "specific" than ".blueBanner". If two rules have the same specificity, then the one that comes later in the CSS file overrides. html sample: <div class="a"> <div class="b"> <div class="c">foo</div> <div class="c d">bar</div> </div> </div> So, you have a selector ".a .b .c" (as you listed above) and two elements (foo and bar) on the page match that selector, so they all get the background color and all the other styles you defined. Now, you also want the second element to have a green background color. It has another class assigned to it "d", so you can just define another selector which matches only that second element ".a .b .d" and set's it's background-color. The "bar" element still gets all the other styles from the ".a .b .c" selector (font, color, etc), but the background color from ".a .b .d".
{ "language": "en", "url": "https://stackoverflow.com/questions/110281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Internet Explorer ol numbers appear at bottom of li instead of top as expected I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox? You can view the live page here. I know, I'm working on positioning the sidebar. Ignore that for now. Markup is as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="css/global.css" /> <link rel="stylesheet" type="text/css" href="css/whats_included.css" /> <script type="text/javascript" src="script/compliant_target_blank.js"></script> <!--[if lte IE 5]> <script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script> <![endif]--> <!--[if gt IE 5]> <link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" /> <![endif]--> <title> The Daily Plan-It, LLC - Home of the Tax MiniMiser </title> </head> <body> <?php include("includes/nav_bar.php") ?> <div id="content"> <img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" /> <div id="bordered_wrapper"> <h1>Here's What You Get With The Tax MiniMiser!</h1> <h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2> <ol> <li class="main_item"> Business Income &amp; Expense Record <div class="preview_image"> <a href="previews/large/bier/front.html" rel="external"> <img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes with all the income &amp; expense columns you need to transform your planner or binder into a daily tax journal!</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the &quot;20 Column Heading Guidelines&quot;, <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Vehicle Mileage &amp; Expense Record <div class="preview_image"> <a href="previews/large/vme/front.html" rel="external"> <img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li> <li>Store daily receipts in the convenient pocket envelopes.</li> </ul> </div> <p>To get a free copy of the &quot;Instructions for Vehicle Mileage &amp; Expense Record&quot;, <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p> </li> <li class="main_item"> Annual Business Summary of Income and Expense <div class="preview_image"> <a href="previews/large/cover/inside.html" rel="external"> <img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/> Click to Preview! </a> </div> <div class="details"> <ul> <li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li> </ul> </div> </li> </ol> <p class="end">To see previews of the small (6&quot; x 8&frac12;&quot;) Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p> </div> </div> <?php include("includes/footer.php") ?> </body> </html> And the CSS: #content { background-color: white; } #bordered_wrapper { margin-left: 26px; background: top left no-repeat url(../images/borders/yellow-box-top.gif); } #bordered_wrapper h1, #bordered_wrapper h2 { margin-left: 20px; } #bordered_wrapper h1 { padding-top: 15px; margin-bottom: 0; } #bordered_wrapper h2 { margin-top: 0; font-size: 1.3em; } ol { font-size: 1.1em; } ul { list-style-type: disc; } li.main_item { width: 700px; clear: right; } li p { clear: both; margin-bottom: 20px; } .preview_image { width: 200px; float: right; text-align: center; margin-bottom: 10px; } .preview_image a { text-decoration: none; } .preview_image img { border-style: none; } .end { clear: right; padding-bottom: 25px; padding-left: 20px; background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif); } A: Congratulations, you are the victim of IE's hasLayout property. Short version: You've got it easy this time. Changes these rules: ... ol { font-size: 1.1em; } ... li.main_item { width: 700px; clear: right; } ... To this: ... ol { font-size: 1.1em; width: 700px; } ... li.main_item { clear: right; } ... And it's all good. Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called "hasLayout" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use conditional comments to fix it just for IE. Here are some CSS rules that add "hasLayout" to an element that doesn't already have it: * *position: absolute *float: left|right *display: inline-block *height: any value other than 'auto' *zoom: any value other than 'normal' (MS proprietary) *writing-mode: tb-rl (MS proprietary) As of IE7, overflow became a trigger for hasLayout. * *overflow: hidden|scroll|auto Longest version: read the following articles. * *Here's all the neat things Microsoft would like you do by triggering "hasLayout". *Here's the clean-language version of what web designers thought about hasLayout when they found out what was going on. Some of the same content, but includes CSS hacks and stuff. A: I just tested your example html in firefox 3/webkit nightly/internet explorer 7 and all of them rendered exactly the same with the number at the top where it should be. The problem is probably in your CSS, can you show us the actual page that is broken? A: Same here, tested with IE6 on WinXP Pro SP3, it shows correctly. You should provide a snippet reproducing the problem, or a live Web page. Perhaps the environment counts, or the existing CSS, etc. A: Actually, I ran into this bug as well. With my page it only happened after changing the numbering using javascript. The only somewhat real solution available is using: vertical-align: top; I honestly have no idea why IE7 is doing, however there is an easy way to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/110305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to make sure my git repo code is safe? If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure? With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups. Note that I don't consider it a good option to "make the developers push branches to a server" -- that's tedious and the developers will end up not doing it. Is there a common way around this problem? Some clarification: With a natively-central-server VCS then everything has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately. If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server". So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe? A: I think it's a fallacy that using a distributed VCS necessarily means that you must use it in a completely distributed fashion. It's completely valid to set up a common git repository and tell everybody that repository is the official one. For normal development workflow, developers would pull changes from the common repository and update their own repositories. Only in the case of two developers actively collaborating on a specific feature might they need to pull changes directly from each other. With more than a few developers working on a project, it would be seriously tedious to have to remember to pull changes from everybody else. What would you do if you didn't have a central repository? At work we have a backup solution that backs up everybody's working directories daily, and writes the whole lot to a DVD weekly. So, although we have a central repository, each individual one is backed up too. A: I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.). At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop. Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push. With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up. What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time. The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs. On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace. For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) git mybackup. git push origin +refs/heads/*:refs/jbloggs/* This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up. This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master. To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference. I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch. In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial. A: It's not uncommon to use a "central" server as an authority in DVCS, which also provides you the place to do your backups. A: I find this question to be a little bit bizarre. Assuming you're using a non-distributed version control system, such as CVS, you will have a repository on the central server and work in progress on developers' servers. How do you back up the repository? How do you back up developers' work in progress? The answer to those questions is exactly what you have to do to handle your question. Using distributed version control, repositories on developers' servers are just work in progress. Do you want to back it up? Then back it up! It's as simple as that. We have an automated backup system that grabs any directories off our our machines which we specify, so I add any repositories and working copies on my machine to that last, including both git and CVS repositories. By the way, if you are using distributed version control in a company releasing a product, then you will have a central repository. It's the one you release from. It might not be on a special server; it might be on some developer's hard drive. But the repository you release from is the central repository. (I suppose if you haven't released, yet, you might not have one, yet.) I kind of feel that all projects have one or more central repositories. (And really if they have more than one, it's two projects and one is a fork.) This goes for open source as well. Even if you didn't have a central repository, the solution is the same: back up work on developer's machines. You should have been doing that anyway. The fact that the work in progress is in distributed repositories instead of CVS working copies or straight nonversioned directories is immaterial. A: You could have developer home directories mount remote devices over the local network. Then you only have to worry about making the network storage safe. Or maybe you could use something like DropBox to copy your local repo elsewhere seamlessly. A: All developers on your team can have their own branches on the server as well (can be per ticket or just per dev, etc). This way they don't break the build in master branch but they still get to push their work in progress to the server that gets backed up. My own git_remote_branch tool may come in handy for that kind of workflow (Note that it requires Ruby). It helps manipulating remote branches. As a side note, talking about repo safety, on your server you can set up a post-commit hook that does a simple git clone or git push to another machine... You get an up to date backup after each commit! A: We use rsync to backup the individual developers .git directories to a directory on the server. This is setup using wrapper scripts around git clone, and the post-commit etc. hooks. Because it is done in the post-* hooks, developers don't need to remember to do it manually. And because we use rsync with a timeout, if the server goes down or the user is working remotely, they can still work.
{ "language": "en", "url": "https://stackoverflow.com/questions/110313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: LINQ to entities - Building where clauses to test collections within a many to many relationship So, I am using the Linq entity framework. I have 2 entities: Content and Tag. They are in a many-to-many relationship with one another. Content can have many Tags and Tag can have many Contents. So I am trying to write a query to select all contents where any tags names are equal to blah The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for Contains (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1 Edit 1 I ended up finding my own answer. A: Summing it up... contentQuery.Where( content => content.Tags.Any(tag => tags.Any(t => t.Name == tag.Name)) ); So is that what you're expecting? I'm a little confused. A: This is what the question itself asks for: contentQuery.Where( content => content.Tags.Any(tag => tag.Name == "blah") ); I'm not sure what the thought process was to get to the questioner's code, really, and I'm not entirely sure exactly what its really doing. The one thing I'm really sure of is that .AsQueryable() call is completely unnecessary -- either .Tags is already an IQueryable, or the .AsQueryable() is just going to fake it for you -- adding extra calls in where there doesn't need to be any. A: The error is related to the 'tags' variable. LINQ to Entities does not support a parameter that is a collection of values. Simply calling tags.AsQueryable() -- as suggested in an ealier answer -- will not work either because the default in-memory LINQ query provider is not compatible with LINQ to Entities (or other relational providers). As a workaround, you can manually build up the filter using the expression API (see this forum post) and apply it as follows: var filter = BuildContainsExpression<Element, string>(e => e.Name, tags.Select(t => t.Name)); var query = source.Where(e => e.NestedValues.Any(filter)); A: After reading about the PredicateBuilder, reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on Combining Predicates and Canonical Function Mapping.. oh and I picked up a bit from Calling functions in LINQ queries (some of these classes were taken from these pages). I FINALLY have a solution!!! Though there is a piece that is a bit hacked... Let's get the hacked piece over with :( I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from: return sequence.ToReadOnlyCollection<Expression>(); To: return sequence.AsReadOnly(); I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on... I added a ParameterRebinder class: public class ParameterRebinder : ExpressionVisitor { private readonly Dictionary<ParameterExpression, ParameterExpression> map; public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) { this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); } public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) { return new ParameterRebinder(map).Visit(exp); } internal override Expression VisitParameter(ParameterExpression p) { ParameterExpression replacement; if (map.TryGetValue(p, out replacement)) { p = replacement; } return base.VisitParameter(p); } } Then I added a ExpressionExtensions class: public static class ExpressionExtensions { public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.And); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.Or); } } And the last class I added was PredicateBuilder: public static class PredicateBuilder { public static Expression<Func<T, bool>> True<T>() { return f => true; } public static Expression<Func<T, bool>> False<T>() { return f => false; } } This is my result... I was able to execute this code and get back the resulting "content" entities that have matching "tag" entities from the tags that I was searching for! public static IList<Content> GetAllContentByTags(IList<Tag> tags) { IQueryable<Content> contentQuery = ... Expression<Func<Content, bool>> predicate = PredicateBuilder.False<Content>(); foreach (Tag individualTag in tags) { Tag tagParameter = individualTag; predicate = predicate.Or(p => p.Tags.Any(tag => tag.Name.Equals(tagParameter.Name))); } IQueryable<Content> resultExpressions = contentQuery.Where(predicate); return resultExpressions.ToList(); } Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info. A: tags.Select(testTag => testTag.Name) Where does the tags variable gets initialized from? What is it? A: NOTE: please edit the question itself, rather than replying with an answer -- this is not a discussion thread, and they can re-order themselves at any time If you're searching for all Contents that are marked with any one of a set of tags: IEnumerable<Tag> otherTags; ... var query = from content in contentQuery where content.Tags.Intersection(otherTags).Any() select content; It looks like you might be using LINQ To SQL, in which case it might be better if you write a stored procedure to do this one: using LINQ to do this will probably not run on SQL Server -- it's very likely it will try to pull down everything from contentQuery and fetch all the .Tags collections. I'd have to actually set up a server to check that, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/110314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Get millions of records from fixed-width flat file to SQL 2000 Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped. A: Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through. an important note: by default triggers do not fire on bulk inserts (BCP & SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like: BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS ) A: Yeah, if you are using DTS, you should just import into a staging table that uses varchar instead of dates and then massage the data into the proper tables afterwords. A: The problem with What Matt said is that you should not use a cursor to manipulate the data afterwards especially if you have millions of records. CUrsoprs are extremely inefficient and should be avoided. Use batch processing instead. But by all means use his idea of a staging table. I wouldn' ever consider importing directly into a production table as too many things can happen over time to change the data in the input file and cause problems. A: You're saying there's a column full of dates in the file, and you want that data to go into a column of type "datetime" in a table in a SQL database? And it'll blow up if one of the values from the file isn't a valid date? I just wanted to make sure I understand this right. You could create another, temporary, table in the SQL database, of the same structure as the table you want the data from the file to end up in, but with every column of type varchar(255) or something. Sucking the data out of the file and into that table shouldn't fail whether any of the dates is valid or not. Then, in SQL, you could massage the data however you want. You could use a cursor to select all of the records from the temporary table and loop through them. For each record, you could use the T-SQL ISDATE function to conditionally insert the values from the current record into one table or another. I'm saying, get the data into the database and then run script like this: // **this is untested, there could be syntax errors** // if we have tables like this: CREATE TABLE tempoary (id VARCHAR(255), theDate VARCHAR(255), somethingElse VARCHAR(255)) CREATE TABLE theGood (id INT, theDate DATETIME, somethingElse VARCHAR(255)) CREATE TABLE theBad (id INT, theDate VARCHAR(255)) // then after getting the data into [tempoary], do this: DECLARE tempCursor CURSOR FOR SELECT id, theDate, somethingElse FROM temporary OPEN tempCursor DECLARE @id VARCHAR(255) DECLARE @theDate VARCHAR(255) DECLARE @somethingElse VARCHAR(255) FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse While (@@FETCH_STATUS <> -1) BEGIN IF ISDATE(@theDate) BEGIN INSERT INTO theGood (id, theDate, somethingElse) VALUES (CONVERT(INT, @id), CONVERT(DATETIME, theDate), somethingElse) END ELSE BEGIN INSERT INTO theBad (id, theDate) VALUES (CONVERT(INT, @id), theDate) END FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse END CLOSE tempCursor DEALLOCATE tempCursor
{ "language": "en", "url": "https://stackoverflow.com/questions/110325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How much business logic should Value objects contain? One mentor I respect suggests that a simple bean is a waste of time - that value objects 'MUST' contain some business logic to be useful. Another says such code is difficult to maintain and that all business logic must be externalized. I realize this question is subjective. Asking anyway - want to know answers from more perspectives. A: You should better call them Transfer Objects or Data transfer objects (DTO). Earlier this same j2ee pattern was called 'Value object' but they changed the name because it was confused with this http://dddcommunity.org/discussion/messageboardarchive/ValueObjects.html To answer your question, I would only put minimal logic to my DTOs, logic that is required for display reasons. Even better, if we are talking about a database based web application, I would go beyond the core j2ee patterns and use Hibernate or the Java Persistence API to create a domain model that supports lazy loading of relations and use this in the view. See the Open session in view. In this way, you don't have to program a set of DTOs and you have all the business logic available to use in your views/controllers etc. A: It depends. oops, did I just blurt out a cliche? The basic question to ask for designing an object is: will the logic governing the object's data be different or the same when used/consumed by other objects? If different areas of usage call for different logic, externalise it. If it is the same no matter where the object travels to, place it together with the class. A: My personal preference is to put all business logic in the domain model itself, that is in the "true" domain objects. So when Data Transfer Objects are created they are mostly just a (immutable) state representation of domain objects and hence contain no business logic. They can contain methods for cloning and comparing though, but the meat of the business logic code stays in the domain objects. A: The idea of putting data and business logic together is to promote encapsulation, and to expose as little internal state as possible to other objects. That way, clients can rely on an interface rather than on an implementation. See the "Tell, Don't Ask" principle and the Law of Demeter. Encapsulation makes it easier to understand the states data can be in, easier to read code, easier to decouple classes and generally easier to unit test. Externalising business logic (generally into "Service" or "Manager" classes) makes questions like "where is this data used?" and "What states can it be in?" a lot more difficult to answer. It's also a procedural way of thinking, wrapped up in an object. This can lead to an anemic domain model. Externalising behaviour isn't always bad. For example, a service layer might orchestrate domain objects, but without taking over their state-manipulating responsibilities. Or, when you are mostly doing reads/writes to a DB that map nicely to input forms, maybe you don't need a domain model - or the painful object/relational mapping overhead it entails - at all. Transfer Objects often serve to decouple architectural layers from each other (or from an external system) by providing the minimum state information the calling layer needs, without exposing any business logic. This can be useful, for example when preparing information for the view: just give the view the information it needs, and nothing else, so that it can concentrate on how to display the information, rather than what information to display. For example, the TO might be an aggregation of several sources of data. One advantage is that your views and your domain objects are decoupled. Using your domain objects in JSPs can make your domain harder to refactor and promotes the indiscriminate use of getters and setters (hence breaking encapsulation). However, there's also an overhead associated with having a lot of Transfer Objects and often a lot of duplication, too. Some projects I've been on end up with TO's that basically mirror other domain objects (which I consider an anti-pattern). A: What Korros said. Value Object := A small simple object, like money or a date range, whose equality isn't based on identity. DTO := An object that carries data between processes in order to reduce the number of method calls. These are the defintions proposed by Martin Fowler and I'd like to popularize them. A: I agree with Panagiotis: the open session in view pattern is much better than using DTOs. Put otherwise, I've found that an application is much much simpler if you traffic in your domain objects(or some composite thereof) from your view layer all the way down. That said, it's hard to pull off, because you will need to make your HttpSession coincident with your persistence layer's unit of work. Then you will need to ensure that all database modifications (i.e. create, updates and deletes) are intentional. In other words, you do not want it be the case that the view layer has a domain object, a field gets modified and the modification gets persisted without the application code intentionally saving the change. Another problem that is important to deal with is to ensure that your transactional semantics are satisfactory. Usually fetching and modifying one domain object will take place in one transactional context and it's not difficult to make your ORM layer require a new transaction. What is challenging is is a nested transaction, where you want to include a second transactional context within the first one opened. If you don't mind investigating how a non-Java API handles these problems, it's worth looking at Rails' Active Record, which allows Ruby server pages to work directly with the domain model and traverse its associations.
{ "language": "en", "url": "https://stackoverflow.com/questions/110328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: filtering NSArray into a new NSArray in Objective-C I have an NSArray and I'd like to create a new NSArray with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a BOOL. I can create an NSMutableArray, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it. Is there a better way? A: Based on an answer by Clay Bridges, here is an example of filtering using blocks (change yourArray to your array variable name and testFunc to the name of your testing function): yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [self testFunc:obj]; }]]; A: If you are OS X 10.6/iOS 4.0 or later, you're probably better off with blocks than NSPredicate. See -[NSArray indexesOfObjectsPassingTest:] or write your own category to add a handy -select: or -filter: method (example). Want somebody else to write that category, test it, etc.? Check out BlocksKit (array docs). And there are many more examples to be found by, say, searching for e.g. "nsarray block category select". A: NSPredicate is nextstep's way of constructing condition to filter a collection (NSArray, NSSet, NSDictionary). For example consider two arrays arr and filteredarr: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"]; filteredarr = [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]]; the filteredarr will surely have the items that contains the character c alone. to make it easy to remember those who little sql background it is *--select * from tbl where column1 like '%a%'--* 1)select * from tbl --> collection 2)column1 like '%a%' --> NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"]; 3)select * from tbl where column1 like '%a%' --> [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]]; I hope this helps A: Assuming that your objects are all of a similar type you could add a method as a category of their base class that calls the function you're using for your criteria. Then create an NSPredicate object that refers to that method. In some category define your method that uses your function @implementation BaseClass (SomeCategory) - (BOOL)myMethod { return someComparisonFunction(self, whatever); } @end Then wherever you'll be filtering: - (NSArray *)myFilteredObjects { NSPredicate *pred = [NSPredicate predicateWithFormat:@"myMethod = TRUE"]; return [myArray filteredArrayUsingPredicate:pred]; } Of course, if your function only compares against properties reachable from within your class it may just be easier to convert the function's conditions to a predicate string. A: NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example. NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil]; NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"]; NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate]; // beginWithB contains { @"Bill", @"Ben" }. NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"]; [array filteredArrayUsingPredicate:sPredicate]; // array now contains { @"Chris", @"Melissa" } A: There are loads of ways to do this, but by far the neatest is surely using [NSPredicate predicateWithBlock:]: NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) { return [object shouldIKeepYou]; // Return YES for each object you want in filteredArray. }]]; I think that's about as concise as it gets. Swift: For those working with NSArrays in Swift, you may prefer this even more concise version: let filteredArray = array.filter { $0.shouldIKeepYou() } filter is just a method on Array (NSArray is implicitly bridged to Swift’s Array). It takes one argument: a closure that takes one object in the array and returns a Bool. In your closure, just return true for any objects you want in the filtered array. A: Checkout this library https://github.com/BadChoice/Collection It comes with lots of easy array functions to never write a loop again So you can just do: NSArray* youngHeroes = [self.heroes filter:^BOOL(Hero *object) { return object.age.intValue < 20; }]; or NSArray* oldHeroes = [self.heroes reject:^BOOL(Hero *object) { return object.age.intValue < 20; }]; A: The Best and easy Way is to create this method And Pass Array And Value: - (NSArray *) filter:(NSArray *)array where:(NSString *)key is:(id)value{ NSMutableArray *temArr=[[NSMutableArray alloc] init]; for(NSDictionary *dic in self) if([dic[key] isEqual:value]) [temArr addObject:dic]; return temArr; } A: Another category method you could use: - (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block { NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) { return block(obj); }]; return [self objectsAtIndexes:filteredIndexes]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/110332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "127" }
Q: Closing a minimized/iconized process from C# Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window. The other requirement that I have is that the application be closed not killed. I need it to write it's memory buffers to disk - and killing it causes data loss. Here's what I tried so far: foreach (Process proc in Process.GetProcesses()) { if (proc.ProcessName.ToLower().StartsWith("myapp")) { if (proc.MainWindowHandle.ToInt32() != 0) { proc.CloseMainWindow(); proc.Close(); //proc.Kill(); <--- not good! } } } I've added the if clause, after discovering that MainWindowHandle == 0 when the window was minimized. Removing the if doesn't help. Neither the CloseMainWindow() nor the Close() work. The Kill() does, but as mentioned above - it's not what I need. Any idea would be accepted, including the use of arcane Win32 API functions :) A: This should work: [DllImport("user32.dll", CharSet=CharSet.Auto)] private static extern IntPtr FindWindow(string className, string windowName); [DllImport("user32.dll", CharSet=CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); private const int WM_CLOSE = 0x10; private const int WM_QUIT = 0x12; public void SearchAndDestroy(string windowName) { IntPtr hWnd = FindWindow(null, windowName); if (hWnd == IntPtr.Zero) throw new Exception("Couldn't find window!"); SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } Since some windows don't respond to WM_CLOSE, WM_QUIT might have to be sent instead. These declarations should work on both 32bit and 64bit. A: If it's on the taskbar, it'll have a window. Or did you mean that it's in the taskbar notification area (aka the SysTray)? In which case, it'll still have a window. Win32 applications don't really have a "main window", except by convention (the main window is the one that calls PostQuitMessage in response to WM_DESTROY, causing the message loop to exit). With the program running, run Spy++. To find all of the windows owned by a process, you should select Spy -> Processes from the main menu. This will display a tree of processes. From there, you can drill down to threads, and then to windows. This will tell you which windows the process has. Note down the window class and caption. With these, you can use FindWindow (or EnumWindows) to find the window handle in future. With the window handle, you can send a WM_CLOSE or WM_SYSCOMMAND/SC_CLOSE (equivalent to clicking on the 'X' on the window caption) message. This ought to cause the program to shut down nicely. Note that I'm talking from a Win32 point-of-view here. You might need to use P/Invoke or other tricks to get this to work from a .NET program. A: Here are some answers and clarifications: rpetrich: Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0. Roger: Yes, I did mean the taskbar notification area - thanks for the clarification. I NEED to call PostQuitMessage. I just don't know how, given a processs only, and not a Window. Craig: I'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'. Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it. Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down. Hope that clarifies my situation, and again, thanks everyone who's trying to help! A: Question to clarify why you're attempting this: If the only user interface on the process is the system tray icon, why would you want to kill that and but leave the process running? How would the user access the process? And if the machine is "unattended", why concern yourself with the tray icon?
{ "language": "en", "url": "https://stackoverflow.com/questions/110336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: TCP handshake with SOCK_RAW socket Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option. The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client. So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK_RAW, and not SOCK_STREAM)? I would be very grateful. MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH! The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this: iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP A: I realise that this is an old thread, but here's a tutorial that goes beyond the normal SYN flooders: http://www.enderunix.org/docs/en/rawipspoof/ Hope it might be of help to someone. A: I can't help you out on any tutorials. But I can give you some advice on the tools that you could use to assist in debugging. First off, as bmdhacks has suggested, get yourself a copy of wireshark (or tcpdump - but wireshark is easier to use). Capture a good handshake. Make sure that you save this. Capture one of your handshakes that fails. Wireshark has quite good packet parsing and error checking, so if there's a straightforward error it will probably tell you. Next, get yourself a copy of tcpreplay. This should also include a tool called "tcprewrite". tcprewrite will allow you to split your previously saved capture files into two - one for each side of the handshake. You can then use tcpreplay to play back one side of the handshake so you have a consistent set of packets to play with. Then you use wireshark (again) to check your responses. A: You want to implement part of a TCP stack in userspace... this is ok, some other apps do this. One problem you will come across is that the kernel will be sending out (generally negative, unhelpful) replies to incoming packets. This is going to screw up any communication you attempt to initiate. One way to avoid this is to use an IP address and interface that the kernel does not have its own IP stack using- which is fine but you will need to deal with link-layer stuff (specifically, arp) yourself. That would require a socket lower than IPPROTO_IP, SOCK_RAW - you need a packet socket (I think). It may also be possible to block the kernel's responses using an iptables rule- but I rather suspect that the rules will apply to your own packets as well somehow, unless you can manage to get them treated differently (perhaps applying a netfilter "mark" to your own packets?) Read the man pages socket(7) ip(7) packet(7) Which explain about various options and ioctls which apply to types of sockets. Of course you'll need a tool like Wireshark to inspect what's going on. You will need several machines to test this, I recommend using vmware (or similar) to reduce the amount of hardware required. Sorry I can't recommend a specific tutorial. Good luck. A: I don't have a tutorial, but I recently used Wireshark to good effect to debug some raw sockets programming I was doing. If you capture the packets you're sending, wireshark will do a good job of showing you if they're malformed or not. It's useful for comparing to a normal connection too. A: There are structures for IP and TCP headers declared in netinet/ip.h & netinet/tcp.h respectively. You may want to look at the other headers in this directory for extra macros & stuff that may be of use. You send a packet with the SYN flag set and a random sequence number (x). You should receive a SYN+ACK from the other side. This packet will have an acknowledgement number (y) that indicates the next sequence number the other side is expecting to receive as well as another sequence number (z). You send back an ACK packet that has sequence number x+1 and ack number z+1 to complete the connection. You also need to make sure you calculate appropriate TCP/IP checksums & fill out the remainder of the header for the packets you send. Also, don't forget about things like host & network byte order. TCP is defined in RFC 793, available here: http://www.faqs.org/rfcs/rfc793.html A: Depending on what you're trying to do it may be easier to get existing software to handle the TCP handshaking for you. One open source IP stack is lwIP (http://savannah.nongnu.org/projects/lwip/) which provides a full tcp/ip stack. It is very possible to get it running in user mode using either SOCK_RAW or pcap. A: if you are using raw sockets, if you send using different source mac address to the actual one, linux will ignore the response packet and not send an rst.
{ "language": "en", "url": "https://stackoverflow.com/questions/110341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Algorithm to calculate the number of divisors of a given number What would be the most optimal algorithm (performance-wise) to calculate the number of divisors of a given number? It'll be great if you could provide pseudocode or a link to some example. EDIT: All the answers have been very helpful, thank you. I'm implementing the Sieve of Atkin and then I'm going to use something similar to what Jonathan Leffler indicated. The link posted by Justin Bozonier has further information on what I wanted. A: Dmitriy is right that you'll want the Sieve of Atkin to generate the prime list but I don't believe that takes care of the whole issue. Now that you have a list of primes you'll need to see how many of those primes act as a divisor (and how often). Here's some python for the algo Look here and search for "Subject: math - need divisors algorithm". Just count the number of items in the list instead of returning them however. Here's a Dr. Math that explains what exactly it is you need to do mathematically. Essentially it boils down to if your number n is: n = a^x * b^y * c^z (where a, b, and c are n's prime divisors and x, y, and z are the number of times that divisor is repeated) then the total count for all of the divisors is: (x + 1) * (y + 1) * (z + 1). Edit: BTW, to find a,b,c,etc you'll want to do what amounts to a greedy algo if I'm understanding this correctly. Start with your largest prime divisor and multiply it by itself until a further multiplication would exceed the number n. Then move to the next lowest factor and times the previous prime ^ number of times it was multiplied by the current prime and keep multiplying by the prime until the next will exceed n... etc. Keep track of the number of times you multiply the divisors together and apply those numbers into the formula above. Not 100% sure about my algo description but if that isn't it it's something similar . A: JUST one line I have thought very carefuly about your question and I have tried to write a highly efficient and performant piece of code To print all divisors of a given number on screen we need just one line of code! (use option -std=c99 while compiling via gcc) for(int i=1,n=9;((!(n%i)) && printf("%d is a divisor of %d\n",i,n)) || i<=(n/2);i++);//n is your number for finding numbers of divisors you can use the following very very fast function(work correctly for all integer number except 1 and 2) int number_of_divisors(int n) { int counter,i; for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++); return counter; } or if you treat given number as a divisor(work correctly for all integer number except 1 and 2) int number_of_divisors(int n) { int counter,i; for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++); return ++counter; } NOTE:two above functions works correctly for all positive integer number except number 1 and 2 so it is functional for all numbers that are greater than 2 but if you Need to cover 1 and 2 , you can use one of the following functions( a little slower) int number_of_divisors(int n) { int counter,i; for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++); if (n==2 || n==1) { return counter; } return ++counter; } OR int number_of_divisors(int n) { int counter,i; for(counter=0,i=1;(!(i==n) && !(n%i) && (counter++)) || i<=(n/2);i++); return ++counter; } small is beautiful :) A: The sieve of Atkin is an optimized version of the sieve of Eratosthenes which gives all prime numbers up to a given integer. You should be able to google this for more detail. Once you have that list, it's a simple matter to divide your number by each prime to see if it's an exact divisor (i.e., remainder is zero). The basic steps calculating the divisors for a number (n) are [this is pseudocode converted from real code so I hope I haven't introduced errors]: for z in 1..n: prime[z] = false prime[2] = true; prime[3] = true; for x in 1..sqrt(n): xx = x * x for y in 1..sqrt(n): yy = y * y z = 4*xx+yy if (z <= n) and ((z mod 12 == 1) or (z mod 12 == 5)): prime[z] = not prime[z] z = z-xx if (z <= n) and (z mod 12 == 7): prime[z] = not prime[z] z = z-yy-yy if (z <= n) and (x > y) and (z mod 12 == 11): prime[z] = not prime[z] for z in 5..sqrt(n): if prime[z]: zz = z*z x = zz while x <= limit: prime[x] = false x = x + zz for z in 2,3,5..n: if prime[z]: if n modulo z == 0 then print z A: You might try this one. It's a bit hackish, but it's reasonably fast. def factors(n): for x in xrange(2,n): if n%x == 0: return (x,) + factors(n/x) return (n,1) A: Once you have the prime factorization, there is a way to find the number of divisors. Add one to each of the exponents on each individual factor and then multiply the exponents together. For example: 36 Prime Factorization: 2^2*3^2 Divisors: 1, 2, 3, 4, 6, 9, 12, 18, 36 Number of Divisors: 9 Add one to each exponent 2^3*3^3 Multiply exponents: 3*3 = 9 A: There are a lot more techniques to factoring than the sieve of Atkin. For example suppose we want to factor 5893. Well its sqrt is 76.76... Now we'll try to write 5893 as a product of squares. Well (77*77 - 5893) = 36 which is 6 squared, so 5893 = 77*77 - 6*6 = (77 + 6)(77-6) = 83*71. If that hadn't worked we'd have looked at whether 78*78 - 5893 was a perfect square. And so on. With this technique you can quickly test for factors near the square root of n much faster than by testing individual primes. If you combine this technique for ruling out large primes with a sieve, you will have a much better factoring method than with the sieve alone. And this is just one of a large number of techniques that have been developed. This is a fairly simple one. It would take you a long time to learn, say, enough number theory to understand the factoring techniques based on elliptic curves. (I know they exist. I don't understand them.) Therefore unless you are dealing with small integers, I wouldn't try to solve that problem myself. Instead I'd try to find a way to use something like the PARI library that already has a highly efficient solution implemented. With that I can factor a random 40 digit number like 124321342332143213122323434312213424231341 in about .05 seconds. (Its factorization, in case you wondered, is 29*439*1321*157907*284749*33843676813*4857795469949. I am quite confident that it didn't figure this out using the sieve of Atkin...) A: Before you commit to a solution consider that the Sieve approach might not be a good answer in the typical case. A while back there was a prime question and I did a time test--for 32-bit integers at least determining if it was prime was slower than brute force. There are two factors going on: 1) While a human takes a while to do a division they are very quick on the computer--similar to the cost of looking up the answer. 2) If you do not have a prime table you can make a loop that runs entirely in the L1 cache. This makes it faster. A: This is an efficient solution: #include <iostream> int main() { int num = 20; int numberOfDivisors = 1; for (int i = 2; i <= num; i++) { int exponent = 0; while (num % i == 0) { exponent++; num /= i; } numberOfDivisors *= (exponent+1); } std::cout << numberOfDivisors << std::endl; return 0; } A: @Yasky Your divisors function has a bug in that it does not work correctly for perfect squares. Try: int divisors(int x) { int limit = x; int numberOfDivisors = 0; if (x == 1) return 1; for (int i = 1; i < limit; ++i) { if (x % i == 0) { limit = x / i; if (limit != i) { numberOfDivisors++; } numberOfDivisors++; } } return numberOfDivisors; } A: I disagree that the sieve of Atkin is the way to go, because it could easily take longer to check every number in [1,n] for primality than it would to reduce the number by divisions. Here's some code that, although slightly hackier, is generally much faster: import operator # A slightly efficient superset of primes. def PrimesPlus(): yield 2 yield 3 i = 5 while True: yield i if i % 6 == 1: i += 2 i += 2 # Returns a dict d with n = product p ^ d[p] def GetPrimeDecomp(n): d = {} primes = PrimesPlus() for p in primes: while n % p == 0: n /= p d[p] = d.setdefault(p, 0) + 1 if n == 1: return d def NumberOfDivisors(n): d = GetPrimeDecomp(n) powers_plus = map(lambda x: x+1, d.values()) return reduce(operator.mul, powers_plus, 1) ps That's working python code to solve this problem. A: Divisors do something spectacular: they divide completely. If you want to check the number of divisors for a number, n, it clearly is redundant to span the whole spectrum, 1...n. I have not done any in-depth research for this but I solved Project Euler's problem 12 on Triangular Numbers. My solution for the greater then 500 divisors test ran for 309504 microseconds (~0.3s). I wrote this divisor function for the solution. int divisors (int x) { int limit = x; int numberOfDivisors = 1; for (int i(0); i < limit; ++i) { if (x % i == 0) { limit = x / i; numberOfDivisors++; } } return numberOfDivisors * 2; } To every algorithm, there is a weak point. I thought this was weak against prime numbers. But since triangular numbers are not print, it served its purpose flawlessly. From my profiling, I think it did pretty well. Happy Holidays. A: You want the Sieve of Atkin, described here: http://en.wikipedia.org/wiki/Sieve_of_Atkin A: Number theory textbooks call the divisor-counting function tau. The first interesting fact is that it's multiplicative, ie. τ(ab) = τ(a)τ(b) , when a and b have no common factor. (Proof: each pair of divisors of a and b gives a distinct divisor of ab). Now note that for p a prime, τ(p**k) = k+1 (the powers of p). Thus you can easily compute τ(n) from its factorisation. However factorising large numbers can be slow (the security of RSA crytopraphy depends on the product of two large primes being hard to factorise). That suggests this optimised algorithm * *Test if the number is prime (fast) *If so, return 2 *Otherwise, factorise the number (slow if multiple large prime factors) *Compute τ(n) from the factorisation A: This is the most basic way of computing the number divissors: class PrintDivisors { public static void main(String args[]) { System.out.println("Enter the number"); // Create Scanner object for taking input Scanner s=new Scanner(System.in); // Read an int int n=s.nextInt(); // Loop from 1 to 'n' for(int i=1;i<=n;i++) { // If remainder is 0 when 'n' is divided by 'i', if(n%i==0) { System.out.print(i+", "); } } // Print [not necessary] System.out.print("are divisors of "+n); } } A: Here is a straight forward O(sqrt(n)) algorithm. I used this to solve project euler def divisors(n): count = 2 # accounts for 'n' and '1' i = 2 while i ** 2 < n: if n % i == 0: count += 2 i += 1 if i ** 2 == n: count += 1 return count A: This interesting question is much harder than it looks, and it has not been answered. The question can be factored into 2 very different questions. 1 given N, find the list L of N's prime factors 2 given L, calculate number of unique combinations All answers I see so far refer to #1 and fail to mention it is not tractable for enormous numbers. For moderately sized N, even 64-bit numbers, it is easy; for enormous N, the factoring problem can take "forever". Public key encryption depends on this. Question #2 needs more discussion. If L contains only unique numbers, it is a simple calculation using the combination formula for choosing k objects from n items. Actually, you need to sum the results from applying the formula while varying k from 1 to sizeof(L). However, L will usually contain multiple occurrences of multiple primes. For example, L = {2,2,2,3,3,5} is the factorization of N = 360. Now this problem is quite difficult! Restating #2, given collection C containing k items, such that item a has a' duplicates, and item b has b' duplicates, etc. how many unique combinations of 1 to k-1 items are there? For example, {2}, {2,2}, {2,2,2}, {2,3}, {2,2,3,3} must each occur once and only once if L = {2,2,2,3,3,5}. Each such unique sub-collection is a unique divisor of N by multiplying the items in the sub-collection. A: An answer to your question depends greatly on the size of the integer. Methods for small numbers, e.g. less then 100 bit, and for numbers ~1000 bit (such as used in cryptography) are completely different. * *general overview: http://en.wikipedia.org/wiki/Divisor_function *values for small n and some useful references: A000005: d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. *real-world example: factorization of integers A: the prime number method is very clear here . P[] is a list of prime number less than or equal the sq = sqrt(n) ; for (int i = 0 ; i < size && P[i]<=sq ; i++){ nd = 1; while(n%P[i]==0){ n/=P[i]; nd++; } count*=nd; if (n==1)break; } if (n!=1)count*=2;//the confusing line :D :P . i will lift the understanding for the reader . i now look forward to a method more optimized . A: The following is a C program to find the number of divisors of a given number. The complexity of the above algorithm is O(sqrt(n)). This algorithm will work correctly for the number which are perfect square as well as the numbers which are not perfect square. Note that the upperlimit of the loop is set to the square-root of number to have the algorithm most efficient. Note that storing the upperlimit in a separate variable also saves the time, you should not call the sqrt function in the condition section of the for loop, this also saves your computational time. #include<stdio.h> #include<math.h> int main() { int i,n,limit,numberOfDivisors=1; printf("Enter the number : "); scanf("%d",&n); limit=(int)sqrt((double)n); for(i=2;i<=limit;i++) if(n%i==0) { if(i!=n/i) numberOfDivisors+=2; else numberOfDivisors++; } printf("%d\n",numberOfDivisors); return 0; } Instead of the above for loop you can also use the following loop which is even more efficient as this removes the need to find the square-root of the number. for(i=2;i*i<=n;i++) { ... } A: Here is a function that I wrote. it's worst time complexity is O(sqrt(n)),best time on the other hand is O(log(n)). It gives you all the prime divisors along with the number of its occurence. public static List<Integer> divisors(n) { ArrayList<Integer> aList = new ArrayList(); int top_count = (int) Math.round(Math.sqrt(n)); int new_n = n; for (int i = 2; i <= top_count; i++) { if (new_n == (new_n / i) * i) { aList.add(i); new_n = new_n / i; top_count = (int) Math.round(Math.sqrt(new_n)); i = 1; } } aList.add(new_n); return aList; } A: @Kendall I tested your code and made some improvements, now it is even faster. I also tested with @هومن جاویدپور code, this is also faster than his code. long long int FindDivisors(long long int n) { long long int count = 0; long long int i, m = (long long int)sqrt(n); for(i = 1;i <= m;i++) { if(n % i == 0) count += 2; } if(n / m == m && n % m == 0) count--; return count; } A: Isn't this just a question of factoring the number - determining all the factors of the number? You can then decide whether you need all combinations of one or more factors. So, one possible algorithm would be: factor(N) divisor = first_prime list_of_factors = { 1 } while (N > 1) while (N % divisor == 0) add divisor to list_of_factors N /= divisor divisor = next_prime return list_of_factors It is then up to you to combine the factors to determine the rest of the answer. A: I think this is what you are looking for.I does exactly what you asked for. Copy and Paste it in Notepad.Save as *.bat.Run.Enter Number.Multiply the process by 2 and thats the number of divisors.I made that on purpose so the it determine the divisors faster: Pls note that a CMD varriable cant support values over 999999999 @echo off modecon:cols=100 lines=100 :start title Enter the Number to Determine cls echo Determine a number as a product of 2 numbers echo. echo Ex1 : C = A * B echo Ex2 : 8 = 4 * 2 echo. echo Max Number length is 9 echo. echo If there is only 1 proces done it echo means the number is a prime number echo. echo Prime numbers take time to determine echo Number not prime are determined fast echo. set /p number=Enter Number : if %number% GTR 999999999 goto start echo. set proces=0 set mindet=0 set procent=0 set B=%Number% :Determining set /a mindet=%mindet%+1 if %mindet% GTR %B% goto Results set /a solution=%number% %%% %mindet% if %solution% NEQ 0 goto Determining if %solution% EQU 0 set /a proces=%proces%+1 set /a B=%number% / %mindet% set /a procent=%mindet%*100/%B% if %procent% EQU 100 set procent=%procent:~0,3% if %procent% LSS 100 set procent=%procent:~0,2% if %procent% LSS 10 set procent=%procent:~0,1% title Progress : %procent% %%% if %solution% EQU 0 echo %proces%. %mindet% * %B% = %number% goto Determining :Results title %proces% Results Found echo. @pause goto start A: i guess this one will be handy as well as precise script.pyton >>>factors=[ x for x in range (1,n+1) if n%x==0] print len(factors) A: Try something along these lines: int divisors(int myNum) { int limit = myNum; int divisorCount = 0; if (x == 1) return 1; for (int i = 1; i < limit; ++i) { if (myNum % i == 0) { limit = myNum / i; if (limit != i) divisorCount++; divisorCount++; } } return divisorCount; } A: I don't know the MOST efficient method, but I'd do the following: * *Create a table of primes to find all primes less than or equal to the square root of the number (Personally, I'd use the Sieve of Atkin) *Count all primes less than or equal to the square root of the number and multiply that by two. If the square root of the number is an integer, then subtract one from the count variable. Should work \o/ If you need, I can code something up tomorrow in C to demonstrate.
{ "language": "en", "url": "https://stackoverflow.com/questions/110344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "182" }
Q: Can an element's CSS class be set via JavaScript? I want to do this: e.className = t; Where t is the name of a style I have defined in a stylesheet. A: Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the DOM Level 2 Style interface. e.g., button.style.fontFamily = "Verdana, Arial, sans-serif"; where button is (presumably) a button object. :-) A: Not only that works, but it's even a best practice. You definitively want to separate the data format (xHTML) from the design (CSS) and the behaviour (javascript). So it's far better to just add and remove classes in JS according to event while the esthetic concerns are delegated to css styles. E.G : Coloring an error message in red. CSS .error { color: red; } JS var error=document.getElementById('error'); error.className='error'; N.B : * *This snippet is just an example. In real life you would use js just for that. *document.getElementById is not always interoperable. Better to use a JS framework to handle that. I personally use JQuery. A: If e is a reference to a DOM element and you have a class like this: .t {color:green;} then you want reference the class name as a string: e.className = 't'; A: Here is the example that add and remove the class using jQuery. // js $("p:first").addClass("t"); $("p:first").removeClass("t"); // css .t { backgound: red } A: document.getElementById('id').className = 't'
{ "language": "en", "url": "https://stackoverflow.com/questions/110354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I find the current OS in Python? As the title says, how can I find the current operating system in python? A: import os print(os.name) This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method. A: If you want user readable data but still detailed, you can use platform.platform() >>> import platform >>> platform.platform() 'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne' platform also has some other useful methods: >>> platform.system() 'Windows' >>> platform.release() 'XP' >>> platform.version() '5.1.2600' Here's a few different possible calls you can make to identify where you are, linux_distribution and dist seem to have gone from recent python versions, so they have a wrapper function here. import platform import sys def linux_distribution(): try: return platform.linux_distribution() except: return "N/A" def dist(): try: return platform.dist() except: return "N/A" print("""Python version: %s dist: %s linux_distribution: %s system: %s machine: %s platform: %s uname: %s version: %s mac_ver: %s """ % ( sys.version.split('\n'), str(dist()), linux_distribution(), platform.system(), platform.machine(), platform.platform(), platform.uname(), platform.version(), platform.mac_ver(), )) The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version e.g. Solaris on sparc gave: Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]'] dist: ('', '', '') linux_distribution: ('', '', '') system: SunOS machine: sun4u platform: SunOS-5.9-sun4u-sparc-32bit-ELF uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc') version: Generic_122300-60 mac_ver: ('', ('', '', ''), '') or MacOS on M1 Python version: ['2.7.16 (default, Dec 21 2020, 23:00:36) ', '[GCC Apple LLVM 12.0.0 (clang-1200.0.30.4) [+internal-os, ptrauth-isa=sign+stri'] dist: ('', '', '') linux_distribution: ('', '', '') system: Darwin machine: arm64 platform: Darwin-20.3.0-arm64-arm-64bit uname: ('Darwin', 'Nautilus.local', '20.3.0', 'Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', 'arm64', 'arm') version: Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101 mac_ver: ('10.16', ('', '', ''), 'arm64') A: I usually use sys.platform to get the platform. sys.platform will distinguish between linux, other unixes, and OS X, while os.name is "posix" for all of them. For much more detailed information, use the platform module. This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution. A: https://docs.python.org/library/os.html To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is. A: Something along the lines: import os if os.name == "posix": print(os.system("uname -a")) # insert other possible OSes here # ... else: print("unknown OS")
{ "language": "en", "url": "https://stackoverflow.com/questions/110362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "328" }
Q: Change the width of form elements created with ModelForm in Django How can I change the width of a textarea form element if I used ModelForm to create it? Here is my product class: class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product And the template code... {% for f in form %} {{ f.name }}:{{ f }} {% endfor %} f is the actual form element... A: Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be: def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['cols'] = 20 The Field objects have no 'attrs' attributes, but their widgets do. A: In the event that you're using an add-on like Grappelli that makes heavy use of styles, you may find that any overridden row and col attributes get ignored because of CSS selectors acting on your widget. This could happen when using zuber's excellent Second or Third approach above. In this case, simply use the First Approach blended with either the Second or Third Approach by setting a 'style' attribute instead of the 'rows' and 'cols' attributes. Here's an example modifying init in the Third Approach above: def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['short_desc'].widget.attrs['style'] = 'width:400px; height:40px;' self.fields['long_desc'].widget.attrs['style'] = 'width:800px; height:80px;' A: The easiest way for your use case is to use CSS. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for long_desc field in your ProductForm (when your form does not have a custom prefix): #id_long_desc { width: 300px; height: 200px; } Second approach is to pass the attrs keyword to your widget constructor. class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20})) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product It's described in Django documentation. Third approach is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor. class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product # Edit by bryan def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor self.fields['long_desc'].widget.attrs['cols'] = 10 self.fields['long_desc'].widget.attrs['rows'] = 20 This approach has the following advantages: * *You can define widget attributes for fields that are generated automatically from your model without redefining whole fields. *It doesn't depend on the prefix of your form. A: Set row and your css class in your admin model view: 'explicacion': AutosizedTextarea(attrs={'rows': 5, 'class': 'input-xxlarge', 'style': 'width: 99% !important; resize: vertical !important;'}), A: this works for me: step 1: after displaying the form.as_p step 2: go to inspect the page where the form is displayed step 3: copy the id of that particular input field step 4: write the Internal CSS for that id
{ "language": "en", "url": "https://stackoverflow.com/questions/110378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: Setting result for IAuthorizationFilter I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable? Doesn't work: [AttributeUsage(AttributeTargets.Method)] public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = View("User/Login"); } } } A: You should look at the implementation of IAuthorizationFilter that comes with the MVC framework, AuthorizeAttribute. If you are using forms authentication, there's no need for you to set the result to User/Login. You can raise a 401 HTTP status response and ASP.NET Will redirect to the login page for you. The one issue with setting the result to user/login is that the user's address bar is not updated, so they will be on the login page, but the URL won't match. For some people, this is not an issue. But some people want their site's URL to correspond to what the user sees in their browser. A: You can instantiate the appropriate ActionResult directly, then set it on the context. For example: public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = new ViewResult { ViewName = "Whatever" }; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/110384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Limiting a group of checkboxes to a certain amount of checks I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below. I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue. * *Is there a better way to do this? *Is it a good idea to unhook are rehook the event handlers like I did. Here's the code. private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue<CheckBox>(list); } } } Edit: Chakrit answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user. A: Just in case you haven't thought of it this way around. For a usability point of view, presumably you have some text saying something like "click no more than 4 check boxes". In which case, why not simply keep a count of the number of checked boxes, and prevent any changes to the 5th box (until of course there are only 3 check boxes). A: One thing to ask yourself is: do you really want to implement this type of behavior with checkboxes? Checkboxes already have a well-understood behavior from a user point of view, and having a seemingly random box become unchecked when a new one is checked will likely be very confusing or maybe even frustrating for the average user. Maybe consider something like a listbox with add/remove buttons, where the design of the list gives the user a visual cue that there is a max of (say) four items. As a reference, I'm thinking something along the lines of the toolbar customizing dialog in IE. Perhaps not the answer you were looking for, but something to consider. A: I think you are looking for a LinkedList. Use AddLast instead of Enqueue and RemoveFirst instead of Dequeue and for removing something in the middle, just use a normal Remove. A: What I've done before is have a multicolumn selection menu like this:            <----> choices:selected choice-1-empty box- choice-2-empty box- choice-3-empty box- choice-4-empty box-                   Then people could highlight a "choice-1" and hit the right button. Suddenly the second column would be populated by the items in the first. Then you can disable the arrow after 3 choices have been added, and pop up a message saying, "You may only select three choices." This makes far more sense compared to other options. It would be far easier for the user. A: Is it a good idea to unhook are rehook the event handlers like I did. That depends. Is it Windows Forms? Windows Forms run on top of the WinAPI which mean that event handler is really just a function called by the message dispatch loop in the main thread. As such the functions do not need to be re-entrant and it is "safe". But, you must do your error handling and catch any exceptions like failed allocations within your event handler or your application will terminate. A: If you ask a user to pick form a list of options and limit the number of choices it is likely that the first choice is there primary choice. e.g. Pick two, you will never have any of what you don't choose: * *Money *Power *Sex *Excitement *Gadgets *Army of Coders. Was your first choice you primary choice? If you want to use check boxes, simply disable all the unchecked ones when the the second one is checked.
{ "language": "en", "url": "https://stackoverflow.com/questions/110385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TinyXML: Save document to char * or string I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk. It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this? Edit: The printing & streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content. Edit: Printing is cool. A: Here's some sample code I am using, adapted from the TiXMLPrinter documentation: TiXmlDocument doc; // populate document here ... TiXmlPrinter printer; printer.SetIndent( " " ); doc.Accept( &printer ); std::string xmltext = printer.CStr(); A: A simple and elegant solution in TinyXml for printing a TiXmlDocument to a std::string. I have made this little example // Create a TiXmlDocument TiXmlDocument *pDoc =new TiXmlDocument("my_doc_name"); // Add some content to the document, you might fill in something else ;-) TiXmlComment* comment = new TiXmlComment("hello world" ); pDoc->LinkEndChild( comment ); // Declare a printer TiXmlPrinter printer; // attach it to the document you want to convert in to a std::string pDoc->Accept(&printer); // Create a std::string and copy your document data in to the string std::string str = printer.CStr(); A: I'm not familiar with TinyXML, but from the documentation it seems that by using operator << to a C++ stream (so you can use C++ string streams) or a TiXMLPrinter class you can get an STL string without using a file. See TinyXML documentation (look for the "Printing" section) A: Don't quite get what you are saying; your question is not clear. I'm guessing you are wanting to load a file into memory so that you can pass it to the document parse function. In that case, the following code should work. #include <stdio.h> The following code reads a file into memory and stores it in a buffer FILE* fd = fopen("filename.xml", "rb"); // Read-only mode int fsize = fseek(fd, 0, SEEK_END); // Get file size rewind(fd); char* buffer = (char*)calloc(fsize + 1, sizeof(char)); fread(buffer, fsize, 1, fd); fclose(fd); The file is now in the variable "buffer" and can be passed to whatever function required you to provide a char* buffer of the file to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/110393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to serve files from IIS 6 on Windows Server 2003? I have files with extensions like ".dae" , ".gtc" , etc. When I try to hit these files over http, the server returns a 404, but they are in the directories. However I can serve readily known file extensions; if i just rename them to say, xml, they are accessible. Any suggestions for what the problem may be? A: If you request a file with an extension that is not a defined MIME type on your IIS 6.0 Web server, you receive a "HTTP Error 404 - File or directory not found" error message. To define a MIME type for a specific extension (.dae in your case), follow these steps: * *Open the IIS Microsoft Management Console (MMC), right-click the local computer name, and then click Properties. *Click MIME Types. *Click New. *In the Extension box, type the file name extension that you want (in your case .dae). *In the MIME Type box, type application/octet-stream. *Apply the new settings. Note: you must restart the World Wide Web Publishing Service or wait for the worker process to recycle for the changes to take effect. A: You need to define additional MIME types on IIS 6 for the extensions that you mentioned. Here is the MS article on how to add additional MIME types to IIS6: http://support.microsoft.com/kb/326965
{ "language": "en", "url": "https://stackoverflow.com/questions/110426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How many unit tests should I write per function/method? Do you write one test per function/method, with multiple checks in the test, or a test for each check? A: I have a test per capability the function is offering. Each test may have several assertions, however. The name of the testcase indicates the capability being tested. Generally, for one function, I have several "sunny day" tests and one or a few "rainy day" scenario, depending of its complexity. A: BDD (Behavior Driven Development) Though I'm still learning, it's basically TDD organized/focused around how your software will actually be used... NOT how it will be developed/built. Wikipedia General Info BTW as far as whether to do multiple asserts per test method I would recommend trying it both ways. Sometimes you'll see where one strategy left you in a bind and it'll start making sense why you normally just use one assert per method. A: One test per check and super descriptive names, per instance: @Test public void userCannotVoteDownWhenScoreIsLessThanOneHundred() { ... } Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!". A: I think that the rule of single assertion is a little too strict. In my unit tests, I try to follow the rule of single group of assertions -- you can use more than one assertion in one test method, as long as you do the checks one after another (you don't change the state of tested class between the assertions). So, in Python, I believe a test like this is correct: def testGetCountReturnsCountAndEnd(self): count, endReached = self.handler.getCount() self.assertEqual(count, 0) self.assertTrue(endReached) but this one should be split into two test methods: def testGetCountReturnsOneAfterPut(self): self.assertEqual(self.handler.getCount(), 0) self.handler.put('foo') self.assertEqual(self.handler.getCount(), 1) Of course, in case of long and frequently used groups of assertions, I like to create custom assertion methods -- these are especially useful for comparing complex objects. A: A test case for each check. It's more granular. It makes it much easier to see what specific test case failed. A: I write at least one test per method, and somtimes more if the method requires some different setUp to test the good cases and the bad cases. But you should NEVER test more than one method in one unit test. It reduce the amount of work and error in fixing your test in case your API changes. A: I would suggest a test case for every check. The more you keep atomic, the better your results are! Keeping multiple checks in a single tests will help you generate report for how much functionality needs to be corrected. Keeping atomic test case will show you the overall quality ! A: In general one testcase per check. When tests are grouped around a particular function it makes refactoring (eg removing or splitting) that function more difficult because the tests also need a lot of changes. It is much better to write the tests for each type of behaviour that you want from the class. Sometimes when testing a particular behaviour it makes sense to have multiple checks per test case. However, as the tests become more complicated it makes them harder to change when something in the class changes. A: In Java/Eclipse/JUnit I use two source directories (src and test) with the same tree. If I have a src/com/mycompany/whatever/TestMePlease with methods worth testing (e.g. deleteAll(List<?> stuff) throws MyException) I create a test/com/mycompany/whatever/TestMePleaseTest with methods to test differente use case/scenarios: @Test public void deleteAllWithNullInput() { ... } @Test(expect="MyException.class") // not sure about actual syntax here :-P public void deleteAllWithEmptyInput() { ... } @Test public void deleteAllWithSingleLineInput() { ... } @Test public void deleteAllWithMultipleLinesInput() { ... } Having different checks is simpler to handle for me. Nonetheless, since every test should be consistent, if I want my initial data set to stay unaltered I sometimes have, for example, to create stuff and delete it in the same check to insure every other test find the data set pristine: @Test public void insertAndDelete() { assertTrue(/*stuff does not exist yet*/); createStuff(); assertTrue(/*stuff does exist now*/); deleteStuff(); assertTrue(/*stuff does not exist anymore*/); } Don't know if there are smarter ways to do that, to tell you the truth... A: I like to have a test per check in a method and have a meaningfull name for the test-method. For instance: testAddUser_shouldThrowIllegalArgumentExceptionWhenUserIsNull A: A testcase per check. If you name the method appropriately, it can provide valuable hint towards the problem when one of these tests cause a regression failure. A: I try to separate out Database tests and Business Logic Tests (using BDD as others here recommend), running the Database ones first ensures your Database is in a good state before asking your application to play with it. There's a good podcast show with Andy Leonard on what it involves and how to do it, and if you'd like a bit more information, I've written a blog post on the subject (shameless plug ;o)
{ "language": "en", "url": "https://stackoverflow.com/questions/110430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Advice on mixing legacy ASP site with .NET 2.0 We've just been tasked with updating an e-commerce application to use PayPal's PayFlow product. The site was originally written in classic ASP except for the credit card processing portion which was a COM component. Our plan is to replace the COM component with a .NET 2.0 component. I'm looking for tips, gotcha, etc. before we embark. A: I think Dan Bartels' blog post about Replacing Old Classic ASP COM Componenets With .NET Assemblies is the right starting point for you. Implementing the details described in the blog post, you should be able to instantiate your objects in classic asp and execute code like this: Dim myObject Set myObject = Server.CreateObject("MyWebDLL.MyClass") Response.Write myObject.MyMethod("test")
{ "language": "en", "url": "https://stackoverflow.com/questions/110431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Are there any Common Lisp implementations for .Net? Are there any Common Lisp implementations for .Net? A: L Sharp .NET A: Full common lisp for .NET http://code.google.com/p/uabcl/ A: I haven't looked at it recently, but at least in the past there were some problems with fully implementing common lisp on the CLR, and I'd be a little surprised if this has changed. The issues come up with things like the handling of floats where .net/clr has a way to do it that is a) subtly incorrect b) disagrees with the ANSI standard for common lisp but c) doesn't allow any way around this. There are other similar problems. This stuff is fiddly and perhaps not too important, but means you are unlikely to see an ANSI CL on the CLR. There are bigger issues, for example common lisp has a more powerful object system, so you can't map it 1:1 to object in the runtime (no MI, for one). This is ok, but leaves you with an inside/outside sort of approach which is what a common runtime tries to avoid... Whether or not you'll see a common lisp-ish variant running on it is a different story, but I don't know of any at the moment (not that I've looked hard) A: #Script Lisp I'm developing #Script Lisp, an enhanced version of Nukata Lisp with a number of new features that reuses #Script existing scripting capabilities to provide seamless integration with both the rest of #Script (see Language Blocks an Expressions) and .NET including Scripting of .NET Types, support for all .NET numeric types and access to its comprehensive library of over 1000+ Script Methods - optimally designed for accessing .NET functionality from a dynamic language. To improve compatibility with existing Common Lisp source code it also implements most of the Simplified Common Lisp Reference as well as all missing functions required to implement C# LINQ 101 Examples in Lisp: #Script Lisp LINQ Exmples and to improve readability and familiarity it also adopts a number of Clojure syntax for defining a data list and map literals, anonymous functions, syntax in Java Interop for .NET Interop, keyword syntax for indexing collections and accessing index accessors and Clojure's popular shorter aliases for fn, def, defn - improving source-code compatibility with Clojure. YouTube Demos Because it's a first-class #Script language, it benefits from its wide ecosystem of supported use-cases, a few of which you can preview in the YouTube videos below: * *#Script LISP Repl with web lisp *Lisp TCP REPL with #Script Lisp *#Script Live watched Lisp Shell Scripts *Script Unity 3D Game Objects from an in-game #Script Lisp REPL Install #Script Lisp can be installed instantly from the x cross-platform dotnet tool that can be installed with: $ dotnet tool install -g x Where you'll be able to bring up an instant Lisp REPL with: $ x lisp and be able to run and watch Lisp scripts where you can view changes in real-time. The same functionality is available in the Windows app dotnet tool: $ dotnet tool install -g app Which in addition will let you use #Script Lisp to develop Gist Desktop Apps and Sharp Apps (.NET Core Windows Desktop Apps). A: As of 2019 there is now Bike: https://github.com/Lovesan/bike It implements a cross-platform Common Lisp interface to the .Net Core platform, using lisp compatibility layers. * *First of all, it is RDNZL reborn *This time, on .Net Core, without a line of C++ code, and fully cross-platform (saw that on https://github.com/CodyReichert/awesome-cl#net-core) A: If it's OK to go the other way around, you can access .Net from your favourite Lisp through Edi Weitz' RDNZL. A: No, but you might want to consider IronScheme running on the DLR. From the website: IronScheme will aim to be a R6RS conforming Scheme implementation based on the Microsoft DLR. IronScheme will be a complete rewrite of IronLisp incorporating lessons learnt while developing IronLisp. A: Reconsidering this question from 2008 in 2010, you now might want to consider Clojure on the CLR. It's not Common Lisp, but it will be fairly easy to learn if you are coming from that direction. Interoperating with the CLR is dead-easy, it takes on more users every day and addresses several other important topics like concurrency. Might be worth investing some time in it. More CLR specific Clojure info here. A: You could try this (Disclaimer, I haven't tested it myself). Also read this. that's where the link came from.
{ "language": "en", "url": "https://stackoverflow.com/questions/110433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Cleaning up Legacy Code "header spaghetti" Any recommended practices for cleaning up "header spaghetti" which is causing extremely slow compilation times (Linux/Unix)? Is there any equvalent to "#pragma once" with GCC? (found conflicting messages regarding this) Thanks. A: Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards. It was discussed in "Large Scale C++ Software Design". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor parsing required to ignore the header from the 2nd time on (i.e. it still has to parse and look for the start and end of the include guard. With external include guards you place the #ifdef's around the #include line itself. So it looks like this: #ifndef MY_HEADER #include "myheader.h" #endif and of course within the H file you have the classic include guard #ifndef MY_HEADER #define MY_HEADER // content of header #endif This way the myheader.h file isn't even opened / parsed by the preprocessor, and it can save you a lot of time in large projects, especially when header files sit on shared remote locations, as they sometimes do. again, it's all in that book. hth A: If you want to do a complete cleanup and have the time to do it then the best solution is to delete all the #includes in all the files (except for obvious ones e.g. abc.h in abc.cpp) and then compile the project. Add the necessary forward declaration or header to fix the first error and then repeat until you comple cleanly. This doesn't fix underlying problems that can result in include issues, but it does ensure that the only includes are the required ones. A: I've read that GCC considers #pragma once deprecated, although even #pragma once can only do so much to speed things up. To try to untangle the #include spaghetti, you can look into doxygen. It should be able to generate graphs of included headers, which may give you an edge on simplifying things. I can't recall the details offhand, but the graph features may require you to install GraphViz and tell doxygen the path where it can find GraphViz's dotty.exe. Another approach you might consider if compile time is your primary concern is setting up Precompiled Headers. A: Richard was somewhat right (Why his solution was noted down?). Anyway, all C/C++ headers should use internal include guards. This said, either: 1 - Your legacy code is not really maintained anymore, and you should use pre-compiled headers (which are a hack, but hey... Your need is to speed up your compilation, not refactor unmaintained code) 2 - Your legacy code is still living. Then, you either use the precompiled headers and/or the guards/external guards for a temporary solution, but in the end, you'll need to remove all your includes, one .C or .CPP at a time, and compile each .C or .CPP file one at a time, correcting their includes with forward-declarations or includes when necessary (or even breaking a large include into smaller ones to be sure each .C or .CPP file will get only the headers it needs). Anyway, testing and removing obsolete includes is part of maintenance of a project, so... My own experience with precompiled headers was not exactly a good one, because half the time, the compiler could not find a symbol I had defined, and so I tried a full "clean/rebuild", to be sure it was not the precompiled header that was obsolete. So my guess is to use it for external libraries you won't even touch (like the STL, C API headers, Boost, whatever). Still, my own experience was with Visual C++ 6, so I guess (hope?) they got it right, now. Now, one last thing: Headers should always be self-sufficient. That means that if the inclusion of headers depends on order of inclusion, then you have a problem. For example, if you can write: #include "AAA.hpp" #include "BBB.hpp" But not: #include "BBB.hpp" #include "AAA.hpp" because BBB depends on AAA, then all you have is a dependency you never acknowledged in the code. Not acknowledging it with a define will only make your compilation a nightmare. BBB should include AAA, too (even if it could be somewhat slower: in the end, forward-declarations will anyway clean useless includes, so you should have a faster compile timer). A: I read the other day about a neat trick to reduce header dependencies: Write a script that will * *find all #include statements *remove one statement at a time and recompiles *if compilation fails, add the include statement back in At the end, you'll hopefully end up with the minimum of required includes in your code. You could write a similar script that re-arranges includes to find out if they are self-sufficient, or require other headers to be included before them (include the header first, see if compilation fails, report it). That should go some way to cleaning up your code. Some more notes: * *Modern compilers (gcc among them) recognize header guards, and optimize in the same way as pragma once would, only opening the file once. *pragma once can be problematic when the same file has different names in the filesystem (i.e. with soft-links) *gcc supports #pragma once, but calls it "obsolete" *pragma once isn't supported by all compilers, and not part of the C standard *not only compilers can be problematic. Tools like Incredibuild also have issues with #pragma once A: Use one or more of those for speeding up the build time * *Use Precompiled Headers *Use a caching mechanism (scons for example) *Use a distributed build system ( distcc, Incredibuild($) ) A: In headers: include headers only if you can't use forward declaration, but always #include any file that you need (include dependencies are evil!). A: As mentioned in the other answer, you should definitely use forward declarations whenever possible. To my knowledge, GCC doesn't have anything equivalent to #pragma once, which is why I stick to the old fashion style of include guards. A: Thanks for the replies, but the question is regarding existing code which includes strict "include order" etc. The question is whether there are any tools/scripts to clarify what is actually going on. Header guards arent the solution as they dont prevent the compiler from reading the whole file again and again and ... A: PC-Lint will go a long way to cleaning up spaghetti headers. Also it will solve other problems for you too like uninitialised variables going unseen, etc. A: As onebyone.livejournal.com commented in a response to your question, some compilers support include guard optimization, which the page I linked defines as follows: The include guard optimisation is when a compiler recognises the internal include guard idiom described above and takes steps to avoid opening the file multiple times. The compiler can look at an include file, strip out comments and white space and work out if the whole of the file is within the include guards. If it is, it stores the filename and include guard condition in a map. The next time the compiler is asked to include the file, it can check the include guard condition and make the decision whether to skip the file or #include it without needing to open the file. Then again, you already answered that external include guards are not the answer to your question. For disentangling header files that must be included in a specific order, I would suggest the following: * *Each .c or .cpp file should #include the corresponding .h file first, and the rest of its #include directives should be sorted alphabetically. You will usually get build errors when this breaks unstated dependencies between header files. *If you have a header file that defines global typedefs for basic types or global #define directives that are used for most of the code, each .h file should #include that file first, and the rest of its #include directives should be sorted alphabetically. *When these changes cause compile errors, you will usually have to add an explicit dependency from one header file to another, in the form of an #include. *When these changes do not cause compile errors, they might cause behavioral changes. Hopefully you have some sort of test suite that you can use to verify the functionality of your application. It also sounds like part of the problem might be that incremental builds are much slower than they ought to be. This situation can be improved with forward declarations or a distributed build system, as others have pointed out.
{ "language": "en", "url": "https://stackoverflow.com/questions/110436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to add WCF templates to Visual Studio Express? I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There are templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere? A: If you are a student you could get the full Visual Studio 2008 from DreamSpark for free. A: Mike, Visual Web Developer 2008 Express will help you in working with WCF Projects. I have the following... Microsoft Visual Studio 2008 Version 9.0.30729.1 SP Microsoft .NET Framework Version 3.5 SP1 Hope this helps. Sanjeev A: If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default): C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress The VC# templates live in: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ProjectTemplates\1033 into: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress\ProjectTemplates\CSharp\Windows\1033 The templates won't appear straight away in the template browser. For VWD you need to run: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplates For VC# you run: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress.exe /installvstemplates A: As a be aware follow-up, I also had to run C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /ResetSettings After copying the templates and running the C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplats The IDE was crashing when it tried to enumerate the C# project templates tree. After running the ResetSettings, the tree iterated and the new templates were present.
{ "language": "en", "url": "https://stackoverflow.com/questions/110451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What percentage of my time will be spent in user input verfication during web development? I'm new to developing things on the web. So far, I'm spending a lot of time (50% or so) to try and prevent bad people from putting things like sql injection into my input forms and validating it server side. Is this normal? A: @Jeremy - some PHP specifics When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string. Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors. Imagine the following SQL: $result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']); You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector: 1 OR 1=1 There's no risky chars in their to encode, so it will pass straight through the escaping filter. Leaving us: SELECT fields FROM table WHERE id = 1 OR 1=1 Which is a lovely SQL injection vector. Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that 1 OR 1=1 is not a valid literal. As for htmlspecialchars(). That's a minefield of its own. There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. Firstly, if you are inside an HTML tag, you are in real trouble. Look at echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />'; We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be javascript:alert(document.cookie) Now resultant HTML looks like <img src= "javascript:alert(document.cookie)" /> The attack gets straight through. It gets worse. Why? because htmlspecialchars only encodes double quotes and not single. So if we had echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />"; Our evil attacker can now inject whole new parameters pic.png' onclick='location.href=xxx' onmouseover='... gives us <img src='pic.png' onclick='location.href=xxx' onmouseover='...' /> In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the XSS cheat sheet for examples on how diverse vectors can be Even if you use htmlspecialchars($string) outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors. The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows. $str = mb_convert_encoding($str, ‘UTF-8′, ‘UTF-8′); $str = htmlentities($str, ENT_QUOTES, ‘UTF-8′); Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off. A: To prevent sql injection attacks just do your queries with prepared statements (the exact way will depend on your platform). Once you do that, you'll never have to bother with this particular aspect again. You just need to use this everywhere. As for general input validation, it's always good to rely on a common base to test for required fields, numbers, etc. ASP.Net's validators are very easy to use for example. One rule of thumb you should follow is not to trust client-side (javascript) to do this for you, since it's easy to go around it. Always do it server-side first. A special case to keep under your radar is when you allow rich content to be introduced that may contain html/javascript. This can allow a malicious user to inject javascript in your data that will trigger code you don't control when you render it. Do not try to roll your own validation code. Search the web for free, tested, mantained code that will do it for you. Jeff had a few pointers in that regard in one of the podcasts. Once you automate your input validation code, the time spent doing it should be directly related to the complexity of your business rules. So as a general rule: keep them simple. A: No. It is not normal. Maybe you need to: * *Use the rights components to avoid SQL Injection (PreparedStatements in Java) *Create a component that "filters" messages coming from user (a servlet Filter in Java). Any modern language has support for both things. Kind Regards A: I'm glad you're taking care to protect yourself. Too many don't. However as others have said, a better choice of architecture will make your problems go away. Using prepared statements (most languages should have support for that) will make SQL injection attacks go away. Plus with many databases they will result in significantly better performance. Handling cross-site scripting attacks is more tricky. But the basic strategy has to be to decide how you will escape user input, decide where you will escape it, and always do it in the same place. Don't fall into the trap of thinking that more is better! Consistently doing it in one way in one place will suffice, and will avoid your having to figure out which of the multiple levels of escaping are causing a specific bug. Or course learning how to create and maintain a sane architecture takes experience. And moreover, it takes reflecting on your bad experiences. So pay attention to your current pain points (it looks like you are), and think about what you could have done differently to avoid them. If you have a mentor, talk with your mentor. That won't always help you so much with this project, but it will with the next. A: I see your problem. It looks like you have the protection logic sprinkled all over the codebase. And each time you write potentially dangerous code you have to be careful to include all protections. And each time a new threat is out, you have to go through all these statements and verify that they're secure. You can't do real security this way. You should have some wrappers, that would make producing insecure code hard, if not impossible. For example, prepared statements. But you may want to use an ORM, like Ruby on Rails' ActiveRecord, or some equivalent in your framework. For output and XSS protection, make sure that output is HTML-escaped by default. Then if you really need to output generated HTML to user, you'll do this explicitly, and it will be easier to verify. For CSRF protection try to also find a generic solution. Generally it should do its duty automatically, without the need for you to explicitly create a verification token, and manually verify it, discard it, or deny the request. A: Just a note on prepared statements. First of all, you should try to use stored procedures if you can... they are probably a better solution in most cases. Secondly, they both protect you from SQL injection only as long as you don't use dynamic SQL, that is, SQL that writes more SQL and then executes it. In this case they will be ineffective -- and so will be stored procedures. Regarding the percentage of time you spend: validation is very important and it does take some thought, if not some time. But the percentage depends on how large your application is, no? In a very small application, say, only a newsletter registration, it's quite possible that validation takes a huge percentage of your time. In larger applications, i.e. where you have a lot of non-presentation code, it is not normal. A: You're facing a problem that only can be solved by generalizing. Try to identify common types of input-validation you need * *numeric / string values / regex validation *range / length *escaping special characters *check for common keywords you don't expect in a particular context ('script', 'select', 'drop'...) against a blacklist and call them systematically before processing the data. All database access must be done with prepared statements and not concatenating a query string. All output must be escaped, since you d'ont want to store everything escaped in your database. A good out of band/social approach is: identify your users the best you can. The higher the chance to get identified, the lesser they will fool with the system. Get their mobile phone number to send a code, check their credit-card etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/110458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Anyone know of any (free / open source) VI integration for Visual Studio? vi is for cool kids. A: * *ViEmu - Not Free but great Vim emulation. *Visual_Studio.vim - Allows you to manage visual studio from Vim. *Using GVim as the Visual Studio Editor http://vim.wikia.com/wiki/Integrate_gvim_with_Visual_Studio and SO has same details available in Anyone know of any (free / open source) VI integration for Visual Studio? A: After @joe's answer, Jared Parsons created the great VsVim. It's been featured on Visual Studio Gallery. It's a ready extension package. I downloaded it, ran the file and it worked out of the box. It's free, too. A: ViEmu is not free but does what you want at a cost of $99. You may also want to read this http://vim.wikia.com/wiki/Integrate_gvim_with_Visual_Studio A: Starting with Visual Studio 2010 you can use VsVim. It's a free extension available on the extension gallery. Source code is hosted on github * *http://github.com/jaredpar/VsVim *http://visualstudiogallery.msdn.microsoft.com/en-us/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329 A: * *ViEmu - Not Free but great Vim emulation. *Visual_Studio.vim - Allows you to manage visual studio from Vim. *Using GVim as the Visual Studio Editor A: Have you tried the gvim OLE package? I have used it with previous versions of Visual Studio and it worked okay. http://www.vim.org/download.php#pc -- gvim##ole.zip A GUI version with OLE support. This offers a few extra features, such as integration with Visual Developer Studio. But it uses quite a bit more memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/110477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: What is the best way to collect/report unexpected errors in .NET Window Applications? I am looking for a better solution than what we currently have to deal with unexpected production errors, without reinventing the wheel. A larger number of our products are WinForm and WPF applications that are installed at remote sites. Inevitably unexpected errors occur, from NullReferenceExceptions to 'General network errors'. Thus ranging from programmer errors to environment problems. Currently all these unhandled exceptions are logged using log4net and then emailed back to us for analysis. However we found that sometimes these error 'reports' contain too little information to identify the problem. In these reports we need information such as: * *Application name *Application Version *Workstation *Maybe a screen shot *Exception details *Operating system *Available RAM *Running processes *And so on... I don't really want to re-invent the wheel by developing this from scratch. Components that are required: * *Error collection (details as mentioned above) *Error 'sender' (Queuing required if DB or Internet is unavailable) *Error database *Analysis and reporting of these errors. E.g. 10 most frequent errors or timeouts occur between 4:00PM and 5:00PM. How do the errors compare between version x and y? Note: We looked at SmartAssembly as a possible solution but although close it didn't quite met our needs and I was hoping to hear what other developers do and if some alternatives exist. Edit: Thanks for the answers so far. Maybe I wasn't clear in my original question, the problem is not how to catch all unhanded exceptions but rather how to deal with them and to create a reporting engine (analysis) around them. A: I'd suggest Jeff Atwood's article on User Friendly Exception Handling, which does most of what you ask already (Application Info, Screenshot, Exception Details, OS, Logging to text files and Emailing), and contains the source code so you add the extra stuff you need. A: You can attach to the unhandled exception event and log it/hit a webservice/etc. [STAThread] static void Main() { Application.ThreadException += new ThreadExceptionEventHandler(OnUnhandledException); Application.Run(new FormStartUp()); } static void OnUnhandledException(object sender, ThreadExceptionEventArgs t) { // Log } I also found this code snippet using AppDomain instead of ThreadException: static class EntryPoint { [MTAThread] static void Main() { // Add Global Exception Handler AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException); Application.Run(new Form1()); } // In CF case only, ALL unhandled exceptions come here private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; if (ex != null) { // Can't imagine e.IsTerminating ever being false // or e.ExceptionObject not being an Exception SomeClass.SomeStaticHandlingMethod(ex, e.IsTerminating); } } } Here is some documentation on it: AppDomain Unhandled Exception Outside of just handling it yourself, there isn't really a generic way to do this that is reusable, it really needs to be integrated with the interface of the application properly, but you could setup a webservice that takes application name, exception, and all that good stuff and have a centralized point for all your apps. A: You may want to study the error reporting feature built into JetBrain's Omea Reader. It has a catch-all error-handling component that pops a dialog when an unexpected error occurs. The user can input more details before submitting the problem to JetBrain's public error-collection web service. They made Omea open source to allow the community to upgrade the .NET 1.1 code base to v2 or 3. http://www.jetbrains.net/confluence/display/OMEA/this+link
{ "language": "en", "url": "https://stackoverflow.com/questions/110488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is there an easy way to request a URL in python and NOT follow redirects? Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. A: The redirections keyword in the httplib2 request method is a red herring. Rather than return the first request it will raise a RedirectLimit exception if it receives a redirection status code. To return the inital response you need to set follow_redirects to False on the Http object: import httplib2 h = httplib2.Http() h.follow_redirects = False (response, body) = h.request("http://example.com") A: i suppose this would help from httplib2 import Http def get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects conn = Http() return conn.request(uri,redirections=num_redirections) A: I second olt's pointer to Dive into Python. Here's an implementation using urllib2 redirect handlers, more work than it should be? Maybe, shrug. import sys import urllib2 class RedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers) result.status = code raise Exception("Permanent Redirect: %s" % 301) def http_error_302(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_302( self, req, fp, code, msg, headers) result.status = code raise Exception("Temporary Redirect: %s" % 302) def main(script_name, url): opener = urllib2.build_opener(RedirectHandler) urllib2.install_opener(opener) print urllib2.urlopen(url).read() if __name__ == "__main__": main(*sys.argv) A: The shortest way however is class NoRedirect(urllib2.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, hdrs, newurl): pass noredir_opener = urllib2.build_opener(NoRedirect()) A: Dive Into Python has a good chapter on handling redirects with urllib2. Another solution is httplib. >>> import httplib >>> conn = httplib.HTTPConnection("www.bogosoft.com") >>> conn.request("GET", "") >>> r1 = conn.getresponse() >>> print r1.status, r1.reason 301 Moved Permanently >>> print r1.getheader('Location') http://www.bogosoft.com/new/location A: Here is the Requests way: import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code, r.headers['Location']) A: This is a urllib2 handler that will not follow redirects: class NoRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): infourl = urllib.addinfourl(fp, headers, req.get_full_url()) infourl.status = code infourl.code = code return infourl http_error_300 = http_error_302 http_error_301 = http_error_302 http_error_303 = http_error_302 http_error_307 = http_error_302 opener = urllib2.build_opener(NoRedirectHandler()) urllib2.install_opener(opener)
{ "language": "en", "url": "https://stackoverflow.com/questions/110498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "141" }
Q: Mod_rails and mongrel running on the same server? I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server. I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app. As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level. What configuration gotchas should I look out for with this type of setup? A: I would probably just move all the apps to mod_rails, as the performance seems comparable to Mongrel and there's less administration overhead. With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing: <Directory "/var/www/app/current/public"> Options FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> Aside from that, if you know how to configure Apache, mod_rails is very painless. A: Ended up moving everything to mod_rails. Works like a champ!
{ "language": "en", "url": "https://stackoverflow.com/questions/110512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What are jQuery's limitations? Joel always said to be careful when using 3rd party libraries. From my initial impressions, jQuery is great. What should I beware of when using it? What are the limitations? What headaches will I run into later on as I use it more? A: I've used it extensively and I have to admit, I'm yet to run into any serious brick walls! I have come up against a couple of bugs which I had to find a quick fix for myself, and then do extra testing with the next jQuery release to ensure that the bug had been dealt with properly, but that's something which applies to any 3rd party library rather than just jQuery. I think it's a fantastic library I must say, and whilst the advice concerning 3rd party libraries has merit, with the amount of Javascript usage having rocketed in this Web 2.0 world, and with so many little discrepancies between browsers, having a well-maintained library can really speed up development as it saves you the overhead of having to do all the legwork yourself. I guess if I was to issue one warning, it would be to make sure you don't go overboard with it - whilst it really accelerates Javascript development by abstracting away loads of logic you don't need to worry about, there's always the risk you'll start writing an inefficient application because you don't realise exactly what demands you're placing on the browser. I would therefore advise you do plenty of profiling with the likes of Firebug to check what's going on under the hood. A: @ mjc $("a tip") .you() .can() .chain() .stuff() .like() .this(); And/or define a variable, for which to use the jQuery functions on: var $tip = $("a tip"); $tip.choo(); $tip.choo(); $tip.train(); A: One thing I've run into with jQuery is that you end up chaining a lot of items together, and it tends to quickly get unreadable if you are not careful. an example I can think of that illustrates this is on John David Anderson's blog: There’s a guy who wrote a logging function so you can figure out whereYou(are).whenYoureCoding().inThe(middleOf).a(jQuery).trainWreck(). I can see the power of chaining things together, but my guess is you’ve probably gone too far if you’re needing to log things to the console mid-swing. There’s probably little to no chance you’re going to be able to read it a week from now, too. A: jQuery is great - it can do whatever javascript can do, but quicker, and in less code. Its only limitations are the ones inherent in javascript as a client-side scripting language. Like any tool, it's possible to missuse, but unless your scripting needs are profoundly basic there's almost no reason NOT to use it. A: I came across the following in my blog reading. It's not really limitations in jQuery but common mistakes made when using ASP.NET developers using jQuery: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/ A: @ BrilliantWinter jQuery is not at all bloated. It's one of the smallest libraries out there. All it's functions are extends of the jQuery object, which means you can detach whatever functionality you don't use, and make the footprint of the library even smaller than it's default size (15kb, Minified and Gzipped). jQuery - and every other library for that matter - provides an API which is the same across all A-grade browsers. This abstraction leaves your code cleaner and less error-prone. Finally, jQuery is used by major "players". Companies like Google, Dell, Digg and NBC use the library. This is not only a big seal-of-approval, but also an assurance that the developers of jQuery are very careful when revising the library, making sure nothing breaks and no bugs are introduced. A: @BrilliantWater - Most people don't use jQuery to "learn", they use it because it's quicker and easier to use and causes less headaches than creating all the methods yourself. And the whole "bloated" argument is totally moot; jQuery is one of the smallest libraries out there and with more and more people getting broadband it's becoming less and less of an issue. Plus, since jQuery is hosted by GoogleCode it's likely that it'll already be in the users cache since so many websites use it! jQuery is awesome! I keep saying to myself that I need to learn another library but I really don't. jQuery has everything I need. I know it's not suited to all projects but it certainly has a place in most! A: I've found jQuery to be indispensable when writing just about any useful bit of javascript. That said, one site I was working on wanted to do animations. I suggested NOT using flash, but performing the relatively "simple" animations that jQuery packages so well with jQuery. We used fades and slides and the like. In the end, it was too much for the browsers to handle (specifically IE, but FF showed signs of stress), and we had to scale almost all of it back. jQuery is tons of fun to code with, and experiment with. It has a fantastic developer community that fields questions very quickly. Just be careful not to get too carried away! :) A: The only downside to jQuery is its too simple and easy to use. You get a very low bar of newbies using it and doing some very strange and close to retarded things. Other than that, jQuery is beautiful and well crafted by a genius and his minions of smart programmers ensuring cross browser quality that reduces tons of work for the developer. Can't go wrong. If you don't like jQuery, you are a little bit off and probably don't bathe often enough. UPDATE This was a very old answer of mine. jQuery is really no longer necessary if you use querySelector and MDN reference as browsers have converged to be the same for the most part, unless of course you are still living in IE8 death land requirements. jQuery also lives globally which is bad if you are building modern JavaScript. jQuery is not really useful at this point aside from having some old school plugins not using modular syntax libraries. Start to look toward modularizing JavaScript as that was the trend after jQuery. Pay attention to es6/es2015. Start using React/React Native OR Angular 2 for making apps as that's on par since it caught up to some degree. Sorry, John Resig. At this point, people are like "John who?" even though he's still a genius in my book. I hope he gets off his laurels though and makes something even better. Funny how things change. A: You can always consider different frameworks if jQuery doesn't suit. Here's an example of mootools. MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API. A: I'm a big fan of jQuery (as evidenced by my having written both a plug-in and a Dashboard widget for it). One thing to be aware of is which browsers jQuery supports. The docs site appears to be having issues at the moment. That's another thing to be aware of... ;-) A: I've been using it for about 6 months now and except for some of the slower developers on my team not embracing it (probably because of the intimidating appearance of some of the longer chains) I haven't run into a single problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/110533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Prevent .NET from "lifting" local variables I have the following code: string prefix = "OLD:"; Func<string, string> prependAction = (x => prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console. Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to: Func<string, string> prependAction = (x => "OLD:" + x); The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method: string prefix = "NEW:"; var prepender = new Prepender {Prefix = prefix}; Func<string, string> prependAction = prepender.Prepend; prefix = "OLD:"; Console.WriteLine(prependAction("brownie")); With helper class: [Serializable] public class Prepender { public string Prefix { get; set; } public string Prepend(string str) { return Prefix + str; } } This seems like a lot of extra work to get the compiler to be "dumb". A: I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization". There is an explanation of it here. A: Just make another closure... Say, something like: var prepend = "OLD:"; Func<string, Func<string, string>> makePrepender = x => y => (x + y); Func<string, string> oldPrepend = makePrepender(prepend); prepend = "NEW:"; Console.WriteLine(oldPrepend("Brownie")); Havn't tested it yet as I don't have access to VS at the moment, but normally, this is how I solve such problem. A: Lambdas automatically 'suck' in local variables, I'm afraid that's simply how they work by definition. A: This is a pretty common problem i.e. variables being modified by a closure unintentionally - a far simpler solution is just to go: string prefix = "OLD:"; var actionPrefix = prefix; Func<string, string> prependAction = (x => actionPrefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); If you're using resharper it will actually identify the places in your code where you're at risk of causing unexpected side effects such as this - so if the file is "all green" your code should be OK. I think in some ways it would have been nice if we had some syntactic sugar to handle this situation so we could have written it as a one-liner i.e. Func<string, string> prependAction = (x => ~prefix + x); Where some prefix operator would cause the variable's value to be evaluated prior to constructing the anonymous delegate/function. A: There are already several answers here explaining how you can avoid the lambda "lifting" your variable. Unfortunately that does not solve your underlying problem. Being unable to serialize the lambda has nothing to do with the lambda having "lifted" your variable. If the lambda expression needs an instance of a non-serialize class to compute, it makes perfect sense that it cannot be serialized. Depending on what you actually are trying to do (I can't quite decide from your post), a solution would be to move the non-serializable part of the lambda outside. For example, instead of: NonSerializable nonSerializable = new NonSerializable(); Func<string, string> prependAction = (x => nonSerializable.ToString() + x); use: NonSerializable nonSerializable = new NonSerializable(); string prefix = nonSerializable.ToString(); Func<string, string> prependAction = (x => prefix + x); A: I get the problem now: the lambda refers to the containing class which might not be serializable. Then do something like this: public void static Func<string, string> MakePrependAction(String prefix){ return (x => prefix + x); } (Note the static keyword.) Then the lambda needs not reference the containing class. A: What about this string prefix = "OLD:"; string _prefix=prefix; Func<string, string> prependAction = (x => _prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); A: How about: string prefix = "OLD:"; string prefixCopy = prefix; Func<string, string> prependAction = (x => prefixCopy + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); ? A: Well, if we're gonna talk about "problems" here, lambdas come from the functional programming world, and in a purely functional programming langauge, there are no assignments and so your problem would never arise because prefix's value could never change. I understand C# thinks it's cool to import ideas from functional programs (because FP is cool!) but it's very hard to make it pretty, because C# is and will always be an imperative programming language.
{ "language": "en", "url": "https://stackoverflow.com/questions/110536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Anyone familiar with a good "sticky windows" library for Winforms? I want to recreate the stickiness and snapping of windows, like it is implemented in Winamp. The basic premise is, when you drag a window and it comes close to another one, it will snap to it and will stick. When you move it the two will move together. I need it for a MDI application. A: You could read this article and try to adopt it for your program: Sticky Windows - How to make your (top-level) forms to stick one to the other or to the screen The class presented in the article inherits from System.Windows.Forms.NativeWindow, thus no inheritance is required in order to make your class "Stick-able". A: I have created a magnet forms component that also supports joint move of "glued" forms. I hope it helps. Disclaimer: I don't know how well will it works with MDI projects. A: Check out this one: http://www.codeproject.com/KB/cs/eugsnapformextender.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/110554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you recommend a good FLEX online resource or book? Are there any favorite online references or good introductory and intermediate/advanced books on this topic that you could recommend to me? I'm a java developer, so I'm looking for something which would be familiar as possible as to me. A: Essential ActionScript 3.0, by Colin Moock Programming Flex 3: The Comprehensive Guide to Creating Rich Internet Applications with Adobe Flex, by Chafic Kazoun, Joey Lott Also check the books section on Flex.org There are some good video tutorials on lynda.com * *http://www.flex.org *http://www.adobe.com/devnet/flex A: Here are some links that helped me out a lot: http://onflex.org/ http://www.flexdevelopers.com/ http://livedocs.adobe.com/flex/3/langref/ http://blog.flexexamples.com/ http://www.ifbin.com/ (added line breaks) A: A great online resource is the Flex Coders mailing list and it's searchable archive. archive: http://www.mail-archive.com/flexcoders@yahoogroups.com/info.html firefox search plugin: http://flexed.wordpress.com/2006/11/20/flex-coders-search-plugin-for-ie7-and-firefox-2/ A: http://oreilly.com/catalog/9780596529857/ I won't give it a glowing review, but it's definitely good for the beginner as a reference. A: I really got a great intro from Flexible Rails: http://www.flexiblerails.com/ A: i wouldn't call them a great reference but if your a video learner, and want some sold tutorials, check out lynda.com (note: i can only recommend their adobe videos) A: The Total Training Flex 3 video tutorials are a great way to get started if you're new to Flex. They cover a good variety of useful subjects, with a nice learning curve. http://www.totaltraining.com/ A: I got great mileage out of the Adobe Flex 3 Developer's Guide, most famous for being huge and freely available on PDF. A little known fact: You can order it in print. I blogged about it at http://williampower.vox.com/library/post/learning-flex-for-book-learners-what-should-i-read.html The book set seems to only be available through Adobe's online store. A: It's been a long time since I read a how-to programming book cover to cover, but that's what I did in fact recently do with Learning Flex 3: Getting up to Speed with Rich Internet Applications by Alaric Cole (O'Reilly). The text is written for beginners, yet it covers some advanced topics along the way in side boxes (e.g., the Flex layout engine). I particularly liked that the examples came naturally, rather than in that contrived and mechanical format of "in chapter 2 we will build an address book, which we will turn into an exciting e-commerce venue in chapter 3, and which by chapter 4 will become a full-fledged event management application." Also, the graphics are nice and colorful, but still not overwhelmingly flashy. No, the writing style and the book design aren't as important as the content itself, but I figure for a beginner book my primary goal is to make the odds as likely as possible that I'll stick with it to the end, and that's what I found with this title. A: The "official" flex manual is online.
{ "language": "en", "url": "https://stackoverflow.com/questions/110558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to pass a generic property as a parameter to a function? I need to write a function that receives a property as a parameter and execute its getter. If I needed to pass a function/delegate I would have used: delegate RET FunctionDelegate<T, RET>(T t); void func<T, RET>(FunctionDelegate function, T param, ...) { ... return function.Invoke(param); } Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code? A: You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method. The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code: For example to get the value of property Foo of object obj you can write: value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null); to set it: obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value}); So you can pass obj.GetType().GetProperty("Foo").GetAccessors()[0] to your method and execute it's Invoke method. an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example: delegate RET FunctionDelegate<T, RET>(T t); void func<T, RET>(FunctionDelegate<T,RET> function, T param, ...) { ... return function(param); } for a property named Foo of type int that is part of a class SomeClass: SomeClass obj = new SomeClass(); func<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj); A: Properties are simply syntactic sugar for methods. I don't think you can modify a property such that it becomes some entity "whose getter you can call". You can however create a method GetPropertyValue() and pass that around as if it were a delegate. A: @Dror Helper, I'm afraid you can't do it that way. Compiler generates get_PropertyName and set_PropertyName methods but they are not accessible without using Reflection. IMO best you can do is create function that takes System.Reflection.ProperyInfo and System.Object params and returns propInfo.GetValue(obj, null); A: You can also write something like: static void Method<T, U>(this T obj, Expression<Func<T, U>> property) { var memberExpression = property.Body as MemberExpression; //getter U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null); //setter obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null); } and example of invocation: DbComputerSet cs = new DbComputerSet(); cs.Method<DbComputerSet, string>(set => set.Code); A: Re: aku's answer: Then you have to obtain that property info first. It seems "use reflection" is the standard answer to the harder C# questions, but reflection yields not-so-pretty hard-to-maintain code. Dror, why not just create a delegate that reads the property for you? It's a simple one-liner and is probably the quickest and prettiest solution to your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/110562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Does anybody know of a tabbed FTP client? Am I the only person who has the need to view multiple directories at once (usually on the same remote server, but sometimes other ones too)? Disconnecting and reconnecting is driving me crazy. Preferably a free tool, but I'm getting to the stage where I'll try anything! Can you have multiple FireFTP tabs in Firefox? Alternatively, I've thought of using WinTabber - I used it about 12 months ago for multiple PuTTY sessions, but it just felt a little clunky. Cheers. A: Directory Opus A: FireFTP in Firefox does the job nicely. I've been using it about 2 hours and it's fast on the way to consigning FileZilla to the bin! A: CrossFTP: Clients available for Windows, Mac OSX and Linux. Download is here. A: I use TotalCommander as my default Windows file manager. It handles FTP as well and it is tabbed. It also handles tar files and a lot of other stuff that I really like. It's brilliant imo. A: FileZilla is my favourite FTP client.
{ "language": "en", "url": "https://stackoverflow.com/questions/110574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection? Earlier today a question was asked regarding input validation strategies in web apps. The top answer, at time of writing, suggests in PHP just using htmlspecialchars and mysql_real_escape_string. My question is: Is this always enough? Is there more we should know? Where do these functions break down? A: I would definitely agree with the above posts, but I have one small thing to add in reply to Cheekysoft's answer, specifically: When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string. Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors. Imagine the following SQL: $result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']); You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector: 1 OR 1=1 There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us: SELECT fields FROM table WHERE id = 1 OR 1=1 I coded up a quick little function that I put in my database class that will strip out anything that isnt a number. It uses preg_replace, so there is prob a bit more optimized function, but it works in a pinch... function Numbers($input) { $input = preg_replace("/[^0-9]/","", $input); if($input == '') $input = 0; return $input; } So instead of using $result = "SELECT fields FROM table WHERE id = ".mysqlrealescapestring("1 OR 1=1"); I would use $result = "SELECT fields FROM table WHERE id = ".Numbers("1 OR 1=1"); and it would safely run the query SELECT fields FROM table WHERE id = 111 Sure, that just stopped it from displaying the correct row, but I dont think that is a big issue for whoever is trying to inject sql into your site ;) A: When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string. Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors. Imagine the following SQL: $result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']); You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector: 1 OR 1=1 There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us: SELECT fields FROM table WHERE id= 1 OR 1=1 Which is a lovely SQL injection vector and would allow the attacker to return all the rows. Or 1 or is_admin=1 order by id limit 1 which produces SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1 Which allows the attacker to return the first administrator's details in this completely fictional example. Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that 1 OR 1=1 is not a valid literal. As for htmlspecialchars(). That's a minefield of its own. There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what. Firstly, if you are inside an HTML tag, you are in real trouble. Look at echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />'; We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be javascript:alert(document.cookie) Now resultant HTML looks like <img src= "javascript:alert(document.cookie)" /> The attack gets straight through. It gets worse. Why? because htmlspecialchars (when called this way) only encodes double quotes and not single. So if we had echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />"; Our evil attacker can now inject whole new parameters pic.png' onclick='location.href=xxx' onmouseover='... gives us <img src='pic.png' onclick='location.href=xxx' onmouseover='...' /> In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the XSS cheat sheet for examples on how diverse vectors can be Even if you use htmlspecialchars($string) outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors. The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows. $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8'); $str = htmlentities($str, ENT_QUOTES, 'UTF-8'); Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off. For a more in-depth study to the multibyte problems, see https://stackoverflow.com/a/12118602/1820 A: An important piece of this puzzle is contexts. Someone sending "1 OR 1=1" as the ID is not a problem if you quote every argument in your query: SELECT fields FROM table WHERE id='".mysql_real_escape_string($_GET['id'])."'" Which results in: SELECT fields FROM table WHERE id='1 OR 1=1' which is ineffectual. Since you're escaping the string, the input cannot break out of the string context. I've tested this as far as version 5.0.45 of MySQL, and using a string context for an integer column does not cause any problems. A: $result = "SELECT fields FROM table WHERE id = ".(INT) $_GET['id']; Works well, even better on 64 bit systems. Beware of your systems limitations on addressing large numbers though, but for database ids this works great 99% of the time. You should be using a single function/method for cleaning your values as well. Even if this function is just a wrapper for mysql_real_escape_string(). Why? Because one day when an exploit to your preferred method of cleaning data is found you only have to update it one place, rather than a system-wide find and replace. A: In addition to Cheekysoft's excellent answer: * *Yes, they will keep you safe, but only if they're used absolutely correctly. Use them incorrectly and you will still be vulnerable, and may have other problems (for example data corruption) *Please use parameterised queries instead (as stated above). You can use them through e.g. PDO or via a wrapper like PEAR DB *Make sure that magic_quotes_gpc and magic_quotes_runtime are off at all times, and never get accidentally turned on, not even briefly. These are an early and deeply misguided attempt by PHP's developers to prevent security problems (which destroys data) There isn't really a silver bullet for preventing HTML injection (e.g. cross site scripting), but you may be able to achieve it more easily if you're using a library or templating system for outputting HTML. Read the documentation for that for how to escape things appropriately. In HTML, things need to be escaped differently depending on context. This is especially true of strings being placed into Javascript. A: why, oh WHY, would you not include quotes around user input in your sql statement? seems quite silly not to! including quotes in your sql statement would render "1 or 1=1" a fruitless attempt, no? so now, you'll say, "what if the user includes a quote (or double quotes) in the input?" well, easy fix for that: just remove user input'd quotes. eg: input =~ s/'//g;. now, it seems to me anyway, that user input would be secured...
{ "language": "en", "url": "https://stackoverflow.com/questions/110575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "116" }
Q: How to allow different content types in different folders of the same document library in WSS 3.0? I have a document library with about 50 available content types. This document library is divided into several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong? private void CreateFolder(SPFolder parent, string name) { SPFolder z = parent.SubFolders.Add(name); List col = new List(); foreach (SPContentType type in myDocumentLibrary.ContentTypes) { if (ContentTypeMatchesName(name, type)) { col.Add(type); } } z.UniqueContentTypeOrder = col; z.Update(); } A: Have you looked at this article by Ton Stegeman? A: I think Magnus' answer will be exactly what you need but why are you storing to many content types and document types in one library? Wouldn't it make more sense to have more than one document library? this would make it much more easily managed.
{ "language": "en", "url": "https://stackoverflow.com/questions/110584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL - How do you compare a CLOB in a DB2 trigger, I need to compare the value of a CLOB field. Something like: IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD but "!=" does not work for comparing CLOBs. What is the way to compare it? Edited to add: My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code. I'm looking for some detailed information on how this can be done A: In Oracle 10g you can use DBMS_LOB.compare() API. Example: select * from table t where dbms_lob.compare(t.clob1, t.clob2) != 0 Full API: DBMS_LOB.COMPARE ( lob_1 IN BLOB, lob_2 IN BLOB, amount IN INTEGER := 4294967295, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; DBMS_LOB.COMPARE ( lob_1 IN CLOB CHARACTER SET ANY_CS, lob_2 IN CLOB CHARACTER SET lob_1%CHARSET, amount IN INTEGER := 4294967295, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; DBMS_LOB.COMPARE ( lob_1 IN BFILE, lob_2 IN BFILE, amount IN INTEGER, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; A: Calculate the md5 (or other) hash of the clobs and then compare these. Initial calculation will be slow but comparison is fast and easy. This could be a good method if the bulk of your data doesn't change very often. One way to calculate md5 is through a java statement in your trigger. Save these in the same table (if possible) or build a simple auxiliary table. A: Iglekott's idea is a good one, with a caveat: Be careful with compare-by-hash if your data is likely to get attacked. It is not currently computationally feasible to generate a hash collision for a specific MD5 value, but it is possible to generate two different inputs that will produce the same MD5 (therefore not triggering your code). It is also possible to generate two different strings with the same prefix that hash to the same value. If that kind of attack can lead to the integrity of your system being compromised, and that's a concern, you want to explore other options. The easiest would be simply switching the hash functions, SHA-2 does not have currently known vulnerabilities. If this isn't a concern -- hell, go with CRC. You aren't going for cryptographic security here. Just don't go with a cryptographically weak function if this stuff is getting installed on a smartbomb, 'mkay? :-) A: If the CLOBs are 32K or less, you can cast them as VARCHAR, which allows comparison, LIKE, and various SQL string functions. Otherwise, you may want to consider adding a column to contain the hash of the CLOB and change the application(s) to keep that hash up to date whenever the CLOB is updated. A: The md5 idea is probably the best, but another alternative is to create a special trigger that only fires when your CLOB field is updated. According to the syntax diagram, you would define the trigger as: CREATE TRIGGER trig_name AFTER UPDATE OF CLOB_FIELD //trigger body goes here This is assuming that your application (or whoever is updating the table) is smart enough to update the CLOB field ONLY WHEN there has been a change made to the clob field, and not every time your table is updated. A: I believe it's not possible to use these kind of operators on CLOB fields, because of the way they're stored. A: Just declare the trigger to fire if that particular column is updated. create trigger T_TRIG on T before update of CLOB_COL ... A: Generating a hash value and comparing them is the best way IMHO. Here is the untested code: ... declare leftClobHash integer; declare rightClobHash integer; set leftClobHash = ( SELECT DBMS_UTILITY.GET_HASH_VALUE(OLD_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE FROM SYSIBM.SYSDUMMY1); set rightClobHash = ( SELECT DBMS_UTILITY.GET_HASH_VALUE(UPDATED_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE FROM SYSIBM.SYSDUMMY1); IF leftClobHash != rightClobHash ... Note that you need EXECUTE privilege on the DBMS_UTILITY module. You can find more information about the provided SQL PL code in the following links. * *Declaring variables: http://www.sqlpl-guide.com/DECLARE *Setting values for variables: http://www.sqlpl-guide.com/SET *Generating Hash: http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055167.html *More on DBMS_UTILITY module: http://pic.dhe.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.sql.rtn.doc%2Fdoc%2Fr0055155.html A: Does DB2 use != for not equals? The ANSI SQL Standard uses <> for not equals.
{ "language": "en", "url": "https://stackoverflow.com/questions/110587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: User Defined Fields with NHibernate I need to add a user defined fields feature to an asp.net c# application that uses NHibernate. The user must be able to add and remove fields from several objects in the system "on the fly", preferably without any system downtime. One important constraint is that the database schema can't be changed by the user - that is, I can add whatever fields/tables I need to support this feature but when the user adds or removes a field he can't change the database schema. EDIT: I also have to sort and filter by the values of the user defined fields. I know how to do it in c#/SQL with a key/value table, but I don't know how to do it with NHibrenate (including filtering and sorting by the user defined fields) A: It sounds like you just want to add a name/value properties table. Have one table defining the name (e.g. ID, FIELDNAME, DESCRIPTION) and another defining the value (e.g. ID, NAME_FK, OBJECT_FK, VALUE). Have the user adding new rows to the NAME table to add a new property and adding values by adding rows to the VALUE table, foreign-keyed to the NAME table and whatever object you want to attach it to. Your view can then query the VALUE table keyed against the OBJECT_FK and use the NAME_FK to reference the property name. Edit: NHibernate won't see the new values as actual properties, but if you map them as collections you should be able to query & filter using ICriteria: IList<MyProp> props = session .CreateCriteria(typeof(MyProp)) .Add(Expression.Eq("ObjectName", "Widget")) .Add(Expression.Eq("Name", "Size")) .List<MyProp>();
{ "language": "en", "url": "https://stackoverflow.com/questions/110591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to unit test a DAO that is extending SqlMapClientDaoSupport Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it. A: DAO and unit tests do not get along well ! That does not make sense to mock anything in a component that does not hold any business logic and is focused on database access. You should try instead to write an integration test. Take a look at the spring reference documentation, chapter 8.3 : http://static.springframework.org/spring/docs/2.5.x/reference/testing.html A: This exact reason is why I don't extend from SqlMapClientDaoSupport. Instead, I inject a dependency to the SqlMapClientTemplate (typed as the interface SqlMapClientOperations). Here's a Spring 2.5 example: @Component public class MyDaoImpl implements MyDao { @Autowired public SqlMapClientOperations template; public void myDaoMethod(BigInteger id) { int rowcount = template.update("ibatisOperationName", id); } } A: As @Banengusk suggested - this can be achieved with Mockito. However, it is important to establish that your DAO will be using a Spring SqlMapClientTemplate that wraps your mock SqlMapClient. Infact, SqlMapClientTemplate delegates invocations to the SqlMapSession in the IBatis layer. Therefore some additional mock setup is required: mockSqlMapSession = mock(SqlMapSession.class); mockDataSource = mock(DataSource.class); mockSqlMapClient = mock(SqlMapClient.class); when(mockSqlMapClient.openSession()).thenReturn(mockSqlMapSession); when(mockSqlMapClient.getDataSource()).thenReturn(mockDataSource); dao = new MyDao(); dao.setSqlMapClient(mockSqlMapClient); We can then verify behaviour like so: Entity entity = new EntityImpl(4, "someField"); dao.save(entity); ArgumentCaptor<Map> params = ArgumentCaptor.forClass(Map.class); verify(mockSqlMapSession).insert(eq("insertEntity"), params.capture()); assertEquals(3, params.getValue().size()); assertEquals(Integer.valueOf(4), params.getValue().get("id")); assertEquals("someField", params.getValue().get("name")); assertNull(params.getValue().get("message")); A: Try Mockito. It lets mock classes, not only interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/110592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do you change the http header information sent in IIS 6 Currently IIS sends an expires http header of yesterday minus 1 hour on ASP.NET pages. How do I change this to 60 seconds in the further instead? A: You can also add a content-expires page directive to your ASP.NET page (for different expire schedules): @Outputcache Or you can set the header inside your code (perhaps a base page class): Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); A good article on caching can be found on MSDN: http://support.microsoft.com/?scid=kb%3Ben-us%3B323290&x=11&y=6 A: Go to IIS administration -> -> Properties -> HTTP Headers tab -> click Enable Content Expiration, and set it to whatever you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/110632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there any OS X equivalents to `hcitool`? I'd like to write some quick scripts to play with bluetooth devices (scan etc…), for the Mac. Under linux I'd probably use hcitool, or the python bluez library. What tools are there for the Mac? A: hcitool is a command that comes with BlueZ, which is specific to the Linux kernel. Unfortunately, I don't have Mac OSX, so I can't test this, but as far as I know, Darwin shares a lot with BSD, so they both use Netgraph framework for bluetooth drivers. There's some information on how to use Bluetooth in FreeBSD, I think they might be helpful, at least as a starting point. The hcitool equivalent in FreeBSD is hccontrol.
{ "language": "en", "url": "https://stackoverflow.com/questions/110661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: GCC optimization flags for Intel Atom I'm developing a performance critical application for Intel Atom processor. What are the best gcc optimization flags for this CPU? A: Well, the Gentoo wiki states for the prescott: http://en.gentoo-wiki.com/wiki/Safe_Cflags/Intel#Atom_N270 CHOST="i686-pc-linux-gnu" CFLAGS="-march=prescott -O2 -pipe -fomit-frame-pointer" CXXFLAGS="${CFLAGS}" A: From Intel, Getting Started with MID When using GCC to compile, there are a few recommended flags to use: * *-O2 or -O1: O2 flag optimizes for speed, while the -O1 flag optimizes for size *-msse3 *-march=core2 *-mfpmath=sse A: There is a cool framework called Acovea (Analysis of Compiler Options via Evolutionary Algorithm), by Scott Rober Ladd, one of the GCC hackers. It's a genetic/evolutionary algorithm framework that tries to optimize GCC optimization flags for a specific piece of code via natural selection. It works something like this: you write a little piece of benchmark code (it really has to be little, because it will be re-compiled and executed several thousand times) that represents the performance characteristics of the larger program you want to optimize. Then Acovea randomly constructs some dozens of different GCC commandlines and compiles and runs your benchmark with each of them. The best of these commandlines are then allowed to "mate" and "breed" new "children" which (hopefully) inherit the best "genes" from their "parents". This process is repeated for a couple dozen "generations", until a stable set of commandline flags emerges. A: GCC 4.5 will contain the -march=atom and -mtune=atom options. Source: http://gcc.gnu.org/gcc-4.5/changes.html A: Just like for Pentium 4: -march=prescott -O2 -pipe -fomit-frame-pointer A: I've a script that auto selects the appropriate flags for your CPU and compiler combination. I've just updated it to support Intel Atom: http://www.pixelbeat.org/scripts/gcccpuopt Update: I previously specified -march=prescott for Atom, but looking more into it shows that Atom is merom ISA compliant, therefore -march=core2 is more appropriate. Note however that Atoms are in-order cores, the last of those being the original pentium. Therefore it's probably better to -mtune=pentium as well. Unfortunately I don't have an Atom to test. I would really appreciate if anyone could benchmark the diff between: -march=core2 -mfpmath=sse -O3 -march=core2 -mtune=pentium -mfpmath=sse -O3 Update: Here are a couple of nice articles on low level optimization for Atom: * *http://virtualdub.org/blog/pivot/entry.php?id=286 *http://virtualdub.org/blog/pivot/entry.php?id=287 A: I don't know if GCC has any Atom-specific optimization flags yet, but the Atom core is supposed to be very similar to the original Pentium, with the very significant addition of the MMX/SSE/SSE2/SSE3/SSSE3 instruction sets. Of course, these only make a significant difference if your code is floating-point or DSP-heavy. Perhaps you could try: gcc -O2 -march=pentium -mmmx -msse -msse2 -msse3 -mssse3 -mfpmath=sse A: here's some cross-pollenation of blogs... what i was really hoping for was a firefox-compiled-for-atom benchmark... Address : http :// ivoras.sharanet.org/blog/tree/2009-02-11.optimizing-for-atom.html "As it turns out, gcc appears to do a very decent job with -mtune=native, and mtune=generic is more than acceptable. The biggest gains (in this math-heavy benchmark) come from using SSE for math, but even they are destroyed by tuning for pentium4. "The difference between the fastest and the slowest optimization is 21%. The impact of using march instead of mtune is negligible (not enough difference to tell if it helps or not). "(I've included k6 just for reference - I know Atom doesn't have 3dnow) "Late update: Tuning for k8 (with SSE and O3) yields a slightly higher best score of 182." A: i686 is closest. Don't go for core2. GCC 4.1 -O3 -march=i686 GCC 4.3 -O3 -march=native GCC 4.1 -O4 -ffast-math GCC 4.3 -O4 -ffast-math http://macles.blogspot.com/2008/09/intel-cc-compiler-gcc-and-intel-atom.html
{ "language": "en", "url": "https://stackoverflow.com/questions/110674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: USRP2: Number of A/D Converters Why are there two A/D converters on the USRP2 board if you can only use one RX daughtercard? A: Most of the daughterboards do quadrature downconversion and produce analog I & Q. For those daughterboards we use 1 A/D for I and another one for Q.
{ "language": "en", "url": "https://stackoverflow.com/questions/110680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What coding techniques do you use for optimising C programs? Some years ago I was on a panel that was interviewing candidates for a relatively senior embedded C programmer position. One of the standard questions that I asked was about optimisation techniques. I was quite surprised that some of the candidates didn't have answers. So, in the interests of putting together a list for posterity - what techniques and constructs do you normally use when optimising C programs? Answers to optimisation for speed and size both accepted. A: For low-level optimization: * *START_TIMER/STOP_TIMER macros from ffmpeg (clock-level accuracy for measurement of any code). *Oprofile, of course, for profiling. *Enormous amounts of hand-coded assembly (just do a wc -l on x264's /common/x86 directory, and then remember most of the code is templated). *Careful coding in general; shorter code is usually better. *Smart low-level algorithms, like the 64-bit bitstream writer I wrote that uses only a single if and no else. *Explicit write-combining. *Taking into account important weird aspects of processors, like Intel's cacheline split issue. *Finding cases where one can losslessly or near-losslessly make an early termination, where the early-termination check costs much less than the speed one gains from it. *Actually inlined assembly for tasks which are far more suited to the x86 SIMD unit, such as median calculations (requires compile-time check for MMX support). A: * *First and foremost, use a better/faster algorithm. There is no point optimizing code that is slow by design. *When optimizing for speed, trade memory for speed: lookup tables of precomputed values, binary trees, write faster custom implementation of system calls... *When trading speed for memory: use in-memory compression A: First things first - don't optimise too early. It's not uncommon to spend time carefully optimising a chunk of code only to find that it wasn't the bottleneck that you thought it was going to be. Or, to put it another way "Before you make it fast, make it work" Investigate whether there's any option for optimising the algorithm before optimising the code. It'll be easier to find an improvement in performance by optimising a poor algorithm than it is to optimise the code, only then to throw it away when you change the algorithm anyway. And work out why you need to optimise in the first place. What are you trying to achieve? If you're trying, say, to improve the response time to some event work out if there is an opportunity to change the order of execution to minimise the time critical areas. For example when trying to improve the response to some external interrupt can you do any preparation in the dead time between events? Once you've decided that you need to optimise the code, which bit do you optimise? Use a profiler. Focus your attention (first) on the areas that are used most often. So what can you do about those areas? * *minimise condition checking. Checking conditions (eg. terminating conditions for loops) is time that isn't being spent on actual processing. Condition checking can be minimised with techniques like loop-unrolling. *In some circumstances condition checking can also be eliminated by using function pointers. For example if you are implementing a state machine you may find that implementing the handlers for individual states as small functions (with a uniform prototype) and storing the "next state" by storing the function pointer of the next handler is more efficient than using a large switch statement with the handler code implemented in the individual case statements. YMMV. *minimise function calls. Function calls usually carry a burden of context saving (eg. writing local variables contained in registers to the stack, saving the stack pointer), so if you don't have to make a call this is time saved. One option (if you're optimising for speed and not space) is to make use of inline functions. *If function calls are unavoidable minimise the data that is being passed to the functions. For example passing pointers is likely to be more efficient than passing structures. *When optimising for speed choose datatypes that are the native size for your platform. For example on a 32bit processor it is likely to be more efficient to manipulate 32bit values than 8 or 16 bit values. (side note - it is worth checking that the compiler is doing what you think it is. I've had situations where I've discovered that my compiler insisted on doing 16 bit arithmetic on 8 bit values with all of the to and from conversions to go with them) *Find data that can be precalculated, and either calculate during initialisation or (better yet) at compile time. For example when implementing a CRC you can either calculate your CRC values on the fly (using the polynomial directly) which is great for size (but dreadful for performance), or you can generate a table of all of the interim values - which is a much faster implementation, to the detriment of the size. *Localise your data. If you're manipulating a blob of data often your processor may be able to speed things up by storing it all in cache. And your compiler may be able to use shorter instructions that are suited to more localised data (eg. instructions that use 8 bit offsets instead of 32 bit) *In the same vein, localise your functions. For the same reasons. *Work out the assumptions that you can make about the operations that you're performing and find ways of exploiting them. For example, on an 8 bit platform if the only operation that at you're doing on a 32 bit value is an increment you may find that you can do better than the compiler by inlining (or creating a macro) specifically for this purpose, rather than using a normal arithmetic operation. *Avoid expensive instructions - division is a prime example. *The "register" keyword can be your friend (although hopefully your compiler has a pretty good idea about your register usage). If you're going to use "register" it's likely that you'll have to declare the local variables that you want "register"ed first. *Be consistent with your data types. If you are doing arithmetic on a mixture of data types (eg. shorts and ints, doubles and floats) then the compiler is adding implicit type conversions for each mismatch. This is wasted cpu cycles that may not be necessary. Most of the options listed above can be used as part of normal practice without any ill effects. However if you're really trying to eke out the best performance: - Investigate where you can (safely) disable error checking. It's not recommended, but it will save you some space and cycles. - Hand craft portions of your code in assembler. This of course means that your code is no longer portable but where that's not an issue you may find savings here. Be aware though that there is potentially time lost moving data into and out of the registers that you have at your disposal (ie. to satisfy the register usage of your compiler). Also be aware that your compiler should be doing a pretty good job on its own. (of course there are exceptions) A: Avoid using the heap. Use obstacks or pool-allocator for identical sized objects. Put small things with short lifetime onto the stack. alloca still exists. A: Pre-mature optimization is the root of all evil! ;) A: As my applications usually don't need much CPU time by design, I focus on the size my binaries on disk and in memory. What I do mostly is looking out for statically sized arrays and replacing them with dynamically allocated memory where it's worth the additional effort of free'ing the memory later. To cut down the size of the binary, I look for big arrays that are initialized at compile time and put the initializiation to runtime. char buf[1024] = { 0, }; /* becomes: */ char buf[1024]; memset(buf, 0, sizeof(buf)); This will remove the 1024 zero-bytes from the binaries .DATA section and will instead create the buffer on the stack at runtime and the fill it with zeros. EDIT: Oh yeah, and I like to cache things. It's not C specific but depending on what you're caching, it can give you a huge boost in performance. PS: Please let us know when your list is finished, I'm very curious. ;) A: If possible, compare with 0, not with arbitrary numbers, especially in loops, because comparison with 0 is often implemented with separate, faster assembler commands. For example, if possible, write for (i=n; i!=0; --i) { ... } instead of for (i=0; i!=n; ++i) { ... } A: Another thing that was not mentioned: * *Know your requirements: don't optimize for situations that will unlikely or never happen, concentrate on the most bang for the buck A: basics/general: * *Do not optimize when you have no problem. *Know your platform/CPU... *...know it thoroughly *know your ABI *Let the compiler do the optimization, just help it with the job. some things that have actually helped: Opt for size/memory: * *Use bitfields for storing bools *re-use big global arrays by overlaying with a union (be careful) Opt for speed (be careful): * *use precomputed tables where possible *place critical functions/data in fast memory *Use dedicated registers for often used globals *count to-zero, zero flag is free A: Difficult to summarize ... * *Data structures: * *Splitting of a data structure depending on case of usage is extremely important. It is common to see a structure that holds data that is accessed based on a flow control. This situation can lower significantly the cache usage. *To take into account cache line size and prefetch rules. *To reorder the members of the structure to obtain a sequential access to them from your code *Algorithms: * *Take time to think about your problem and to find the correct algorithm. *Know the limitations of the algorithm you choose (a radix-sort/quick-sort for 10 elements to be sorted might not be the best choice). *Low level: * *As for the latest processors it is not recommended to unroll a loop that has a small body. The processor provides its own detection mechanism for this and will short-circuit whole section of its pipeline. *Trust the HW prefetcher. Of course if your data structures are well designed ;) *Care about your L2 cache line misses. *Try to reduce as much as possible the local working set of your application as the processors are leaning to smaller caches per cores (C2D enjoyed a 3MB per core max where iCore7 will provide a max of 256KB per core + 8MB shared to all cores for a quad core die.). The most important of all: Measure early, Measure often and never ever makes assumptions, base your thinking and optimizations on data retrieved by a profiler (please use PTU). Another hint, performance is key to the success of an application and should be considered at design time and you should have clear performance targets. This is far from being exhaustive but should provide an interesting base. A: These days, the most important things in optimzation are: * *respecting the cache - try to access memory in simple patterns, and don't unroll loops just for fun. Use arrays instead of data structures with lots of pointer chasing and it'll probably be faster for small amounts of data. And don't make anything too big. *avoiding latency - try to avoid divisions and stuff that's slow if other calculations depend on them immediately. Memory accesses that depend on other memory accesses (ie, a[b[c]]) are bad. *avoiding unpredictabilty - a lot of if/elses with unpredictable conditions, or conditions that introduce more latency, will really mess you up. There's a lot of branchless math tricks that are useful here, but they increase latency and are only useful if you really need them. Otherwise, just write simple code and don't have crazy loop conditions. Don't bother with optimizations that involve copy-and-pasting your code (like loop unrolling), or reordering loops by hand. The compiler usually does a better job than you at doing this, but most of them aren't smart enough to undo it. A: As everybody else has said: profile, profile profile. As for actual techniques, one that I don't think has been mentioned yet: Hot & Cold Data Separation: Staying within the CPU's cache is incredibly important. One way of helping to do this is by splitting your data structures into frequently accessed ("hot") and rarely accessed ("cold") sections. An example: Suppose you have a structure for a customer that looks something like this: struct Customer { int ID; int AccountNumber; char Name[128]; char Address[256]; }; Customer customers[1000]; Now, lets assume that you want to access the ID and AccountNumber a lot, but not so much the name and address. What you'd do is to split it into two: struct CustomerAccount { int ID; int AccountNumber; CustomerData *pData; }; struct CustomerData { char Name[128]; char Address[256]; }; CustomerAccount customers[1000]; In this way, when you're looping through your "customers" array, each entry is only 12 bytes and so you can fit many more entries in the cache. This can be a huge win if you can apply it to situations like the inner loop of a rendering engine. A: My favorite technique is to use a good profiler. Without a good profile telling you where the bottleneck lies, no tricks and techniques are going to help you. A: Collecting profiles of code execution get you 50% of the way there. The other 50% deals with analyzing these reports. Further, if you use GCC or VisualC++, you can use "profile guided optimization" where the compiler will take info from previous executions and reschedule instructions to make the CPU happier. A: Inline functions! Inspired by the profiling fans here I profiled an application of mine and found a small function that does some bitshifting on MP3 frames. It makes about 90% of all function calls in my applcation, so I made it inline and voila - the program now uses half of the CPU time it did before. A: On most of embedded system i worked there was no profiling tools, so it's nice to say use profiler but not very practical. First rule in speed optimization is - find your critical path. Usually you will find that this path is not so long and not so complex. It's hard to say in generic way how to optimize this it's depend on what are you doing and what is in your power to do. For example you want usually avoid memcpy on critical path, so ever you need to use DMA or optimize, but what if you hw does not have DMA ? check if memcpy implementation is a best one if not rewrite it. Do not use dynamic allocation at all in embedded but if you do for some reason don't do it in critical path. Organize your thread priorities correctly, what is correctly is real question and it's clearly system specific. We use very simple tools to analyze the bottle-necks, simple macro that store the time-stamp and index. Few (2-3) runs in 90% of cases will find where you spend your time. And the last one is code review a very important one. In most case we avoid performance problem during code review very effective way :) A: * *Measure performance. *Use realistic and non-trivial benchmarks. Remember that "everything is fast for small N". *Use a profiler to find hotspots. *Reduce number of dynamic memory allocations, disk accesses, database accesses, network accesses, and user/kernel transitions, because these often tend to be hotspots. *Measure performance. In addition, you should measure performance. A: Sometimes you have to decide whether it is more space or more speed that you are after, which will lead to almost opposite optimizations. For example, to get the most out of you space, you pack structures e.g. #pragma pack(1) and use bit fields in structures. For more speed you pack to align with the processors preference and avoid bitfields. Another trick is picking the right re-sizing algorithms for growing arrays via realloc, or better still writing your own heap manager based on your particular application. Don't assume the one that comes with the compiler is the best possible solution for every application. A: If someone doesn't have an answer to that question, it could be they don't know much. It could also be that they know a lot. I know a lot (IMHO :-), and if I were asked that question, I would be asking you back: Why do you think that's important? The problem is, any a-priori notions about performance, if they are not informed by a specific situation, are guesses by definition. I think it is important to know coding techniques for performance, but I think it is even more important to know not to use them, until diagnosis reveals that there is a problem and what it is. Now I'm going to contradict myself and say, if you do that, you learn how to recognize the design approaches that lead to trouble so you can avoid them, and to a novice, that sounds like premature optimization. To give you a concrete example, this is a C application that was optimized. A: most common techniques I encountered are: * *loop unrolling *loop optimization for better cache prefetch (i.e. do N operations in M cycles instead of NxM singular operations) *data aligning *inline functions *hand-crafted asm snippets As for general recommendations, most of them are already sounded: * *choose better algos *use profiler *don't optimize if it doesn't give 20-30% performance boost A: Great lists. I will just add one tip I didn't saw in the above lists that in some case can yield huge optimisation for minimal cost. * *bypass linker if you have some application divided in two files, say main.c and lib.c, in many cases you can just add a \#include "lib.c" in your main.c That will completely bypass linker and allow for much more efficient optimisation for compiler. The same effect can be achieved optimizing dependencies between files, but the cost of changes is usually higher. A: Sometimes Google is the best algorithm optimization tool. When I have a complex problem, a bit of searching reveals some guys with PhD's have found a mapping between this and a well-known problem and have already done most of the work. A: I would recommend optimizing using more efficient algorithms and not do it as an afterthought but code it that way from the start. Let the compiler work out the details on the small things as it knows more about the target processor than you do. For one, I rarely use loops to look things up, I add items to a hashtable and then use the hashtable to lookup the results. For example you have a string to lookup and then 50 possible values. So instead of doing 50 strcmps, you add all 50 strings to a hashtable and give each a unique number ( you only have to do this once ). Then you lookup the target string in the hashtable and have one large switch with all 50 cases ( or have functions pointers ). When looking up things with common sets of input ( like css rules ), I use fast code to keep track of the only possible solitions and then iterate thought those to find a match. Once I have a match I save the results into a hashtable ( as a cache ) and then use the cache results if I get that same input set later. My main tools for faster code are: hashtable - for quick lookups and for caching results qsort - it's the only sort I use bsp - for looking up things based on area ( map rendering etc )
{ "language": "en", "url": "https://stackoverflow.com/questions/110684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Bandwith USRP2 What is the maximum bandwith I can handle with an USRP2? A: USRP2 A/D samples at 100MS/s I & Q is decimated to 25MS/s complex. We use 16-bit I & Q. That works out to ~800Mbit/s on the gigabit ethernet, which the USRP2 can sustain, no problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/110692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which Continuous Integration library to use? I've worked with Cruise Control as the CI framework in my last project. Any recommendations on some other tools? (Not that i found CruiseControl lacking, just wanted to know if someone did some comparisons) A: JetBrain's TeamCity is pretty cool. A: We use Bamboo. For a rather extensive feature matrix of the various major CI servers, have a look at: http://confluence.public.thoughtworks.org/display/CC/CI+Feature+Matrix A: Since I've switched from Ant to Maven as my build system, Continuum is the obvious choice. It's very clean and offers all the features that I need. A: I second Peter's recommendation for Hudson. Continuum and Hudson are both very easy to set-up and use (compared to CruiseControl), but Hudson offers a lot more functionality. If you're interested, I've previously written about why I would choose Hudson. TeamCity, with its pre-tested commit functionality, is also a good choice if you can live with the limitations of a free Professional Licence (maximum of 20 users and 20 build configurations). A: We use LuntBuild which works perfectly with maven. In addition, Lunbuild offers a good deal of granularity for access control. I haven't used too many CI tools, but that was the main reason my company switched to Luntbuild from Cruise Control. We wanted to give clients access to the build server so they could pull daily builds, etc, but we couldn't have them accessing other clients' builds. A: We use TFS 2008 which works for us because we're pretty much an all MS environment... however, I've also used FinalBuilder, which has more features than just about anything else I've seen and would be especially useful in environments where you were using a mix of technologies (multiple SCM's for example). A: We have had great success with Hudson. It is easy to install and configure, has a great range of plugins and a good web user interface. The checkstyle and cobertura code coverage plugins are two that we use. A: TFS 2008 is pretty good. It has continuous integration built in to TFS build. A: TFS 2008 is pretty good As are CruiseControl and Nant Have a look at CI factory, which requires minimal configuration
{ "language": "en", "url": "https://stackoverflow.com/questions/110712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What are some good microcontroller development boards to learn the .Net micro framework? Excluding the Micro Framework Emulator ;) A: A well known one is Tahoe. Others are * *http://www.sjjmicro.com/EDK.html *http://www.ghielectronics.com/details.php?id=107&sid=108 A: I recommend http://www.netduino.com It is Pin Compatible with the Arduino so all kinds of hardware shields are available see http://www.sparkfun.com. The price is also very reasonable at $35 to $60 (The Plus model supports Ethernet and SD card with no change in Arduino Compatibility. Note: the Netduino/Netduino Plus operate at 3.3V but are 5V tolerant and have 8mA of current available on each pin instead of the 20 mA on Arduino. A: Domino and Panda with it's many Arduino compatible shields are highly affordable and well supported.
{ "language": "en", "url": "https://stackoverflow.com/questions/110736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular expression to convert mark down to HTML How would you write a regular expression to convert mark down into HTML? For example, you would type in the following: This would be *italicized* text and this would be **bold** text This would then need to be converted to: This would be <em>italicized</em> text and this would be <strong>bold</strong> text Very similar to the mark down edit control used by stackoverflow. Clarification For what it is worth, I am using C#. Also, these are the only real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so. A: The best way is to find a version of the Markdown library ported to whatever language you are using (you did not specify in your question). Now that you have clarified that you only want STRONG and EM to be processed, and that you are using C#, I recommend you take a look at Markdown.NET to see how those tags are implemented. As you can see, it is in fact two expressions. Here is the code: private string DoItalicsAndBold (string text) { // <strong> must go first: text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", new MatchEvaluator (BoldEvaluator), RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); // Then <em>: text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1", new MatchEvaluator (ItalicsEvaluator), RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); return text; } private string ItalicsEvaluator (Match match) { return string.Format ("<em>{0}</em>", match.Groups[2].Value); } private string BoldEvaluator (Match match) { return string.Format ("<strong>{0}</strong>", match.Groups[2].Value); } A: A single regex won't do. Every text markup will have it's own html translator. Better look into how the existing converters are implemented to get an idea on how it works. http://en.wikipedia.org/wiki/Markdown#See_also A: I don't know about C# specifically, but in perl it would be: \\\*\\\*(.*?)\\\*\\\*/ \< bold\>$1\<\/bold\>/g \\\*(.\*?)\\\*/ \< em\>$1\<\/em\>/g A: I came across the following post that recommends to not do this. In my case though I am looking to keep it simple, but thought I would post this per jop's recommendation in case someone else wanted to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/110749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Report generation I am writing a web app using TurboGears, and in that app the users must be able to generate different reports. The data the reports need is stored in a database (MySQL). The reports must be returned either as a easily printable html document, or a pdf file. I have previously used jasper and iReport for creating the documents, but if I can avoid having to fire up Java to create the report I would be happy. Ideally I would like to specify reports in a easily readable markup language and then just feed the template data with some kind of library that produces the report. I gladly accept any kind of hints on how I should go about generating these reports! A: Pod is my favorite solution to your problem. A: You can build some fancy PDFs from Python with the ReportLab toolkit. A: A partial answer: the easily readable format you are looking for might be DocBook. From there it is very easy to go to PDF, html, RTF, etc. etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/110760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to convert from Decimal to T? I've built a wrapper over NumbericUpDown control. The wrapper is generic and can support int? and double? I would like to write a method that will do the following. public partial class NullableNumericUpDown<T> : UserControl where T : struct { private NumbericUpDown numericUpDown; private T? Getvalue() { T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question return value; }} of course there is no cast between decimal and double? or int? so I need to use a certain way of converting. I would like to avoid switch or if expressions. What would you do? To clarify my question I've provided more code... A: It's not clear how you gonna use it. If you want double create GetDouble() method, for integers - GetInteger() EDIT: Ok, now I think I understand your use case Try this: using System; using System.ComponentModel; static Nullable<T> ConvertFromString<T>(string value) where T:struct { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null && !string.IsNullOrEmpty(value)) { try { return (T)converter.ConvertFrom(value); } catch (Exception e) // Unfortunately Converter throws general Exception { return null; } } return null; } ... double? @double = ConvertFromString<double>("1.23"); Console.WriteLine(@double); // prints 1.23 int? @int = ConvertFromString<int>("100"); Console.WriteLine(@int); // prints 100 long? @long = ConvertFromString<int>("1.1"); Console.WriteLine(@long.HasValue); // prints False A: Since this method will always return the result of numericUpDown.Value you have no cause for the value to be converted to anything other than Decimal. Are you trying to solve a problem you don't have? A: public class FromDecimal<T> where T : struct, IConvertible { public T GetFromDecimal(decimal Source) { T myValue = default(T); myValue = (T) Convert.ChangeType(Source, myValue.GetTypeCode()); return myValue; } } public class FromDecimalTestClass { public void TestMethod() { decimal a = 1.1m; var Inter = new FromDecimal<int>(); int x = Inter.GetFromDecimal(a); int? y = Inter.GetFromDecimal(a); Console.WriteLine("{0} {1}", x, y); var Doubler = new FromDecimal<double>(); double dx = Doubler.GetFromDecimal(a); double? dy = Doubler.GetFromDecimal(a); Console.WriteLine("{0} {1}", dx, dy); } } private T? Getvalue() { T? value = null; if (this.HasValue) value = new FromDecimal<T>().GetFromDecimal(NumericUpDown); return value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/110763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to reduce the bandwith with very high sample frequency on USRP I am using USRP with DBSRX daughter board. I need a very high sample frequency. Currently, the USRP can give me maximum sample frequency of 64M/8 in I and Q, and the data type is short, which takes 2 bytes. So can I decrease the length of the output data? for example save the data as char which takes 1 bytes, and increase the sample frequency to 64M/4. Can I do this? and how? A: $ usrp_rx_cfile.py --help See the -8 option which gets you 8-bit I & Q and allows a minimum decimation factor of 4. A: You can do this in different ways, one is the was user19899 explained. The more 'difficult' way is to modify the FPGA code of the USRP and add a loss-less compression before the UHD interface. On the driver side, you must add an extra layer to your code to to the opposite. I did that for another platform where we saved close to 40% bandwidth using this solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/110766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Re-ordering entries in a model using drag-and-drop Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin? It would be best if i didn't have to add any extra fields to the model, but if i really have to i can. A: For working code to do this, check out snippet 1053 at djangosnippets.org. A: Note on the "It would be best if i didn't have to add any extra fields to the model, but if i really have to i can." Sorry, but order of information in a database is determined by the information itself: you always have to add a column for ordering. There's really no choice about that. Further, to retrieve things in this order, you'll need to specifically add .order_by(x) to your queries or add ordering to your model. class InOrder( models.Model ): position = models.IntegerField() data = models.TextField() class Meta: ordering = [ 'position' ] Without the additional field ordering cannot happen. It's one of the rules of relational databases. A: There's a nice package for ordering admin objects these days https://github.com/iambrandontaylor/django-admin-sortable Also, django-suit has builtin support for this A: You may try this snippet https://gist.github.com/barseghyanartur/1ebf927512b18dc2e5be (originally based on this snippet http://djangosnippets.org/snippets/2160/). Integration is very simple. Your model (in models.py): class MyModel(models.Model): name = models.CharField(max_length=255) order = models.IntegerField() # Other fields... class Meta: ordering = ('order',) You admin (admin.py): class MyModelAdmin(admin.ModelAdmin): fields = ('name', 'order',) # Add other fields here list_display = ('name', 'order',) list_editable = ('order',) class Media: js = ( '//code.jquery.com/jquery-1.4.2.js', '//code.jquery.com/ui/1.8.6/jquery-ui.js', 'path/to/sortable_list.js', ) Change the JS (of the snippet) accordingly if your attributes responsible for holding the name and ordering are named differently in your model. A: In model class you would probably have to add "order" field, to maintain specific order (eg. item with order = 10 is the last one and order = 1 is the first one). Then you can add a JS code in admin change_list template (see this) to maintain drag&drop feature. Finally change ordering in Meta of model to something like ['order']. A: The order can only be determined if you add a field in your model.Let's add a position field in your model. In your models.py class MainModel(models.Model): name = models.CharField(max_length=255) position = models.PositiveSmallIntegerField(null=True) class Meta: ordering = ('position',) In your apps admin.py class IdeaCardTagInline(nested_admin.NestedStackedInline): model = MainModel extra = 0 min_num = 1 sortable_field_name = "position" ordering = ('position',) in Meta will order the MainModel according to the value in the position field. sortable_field_name = "position" will help in autofill of the value in position when an user drag and drop the multiple models. To see the same order in your api, use order_by(x) in views_model.py. Just a model example: Model.objects.filter().order_by('position').
{ "language": "en", "url": "https://stackoverflow.com/questions/110774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to do Channel measurements in Gnuradio? What is the best way to measure the channel for use in space-time coding schemes using an RFX2400 board? As far as I know you can only get the I and Q streams out of the USRP, and I'm not sure how you would get a set of channel coefficients. I am planning on using the conjugate of the measured channel to 'reverse' the damage done by transmission. A: If you trying to measure the impulse response of the channel, then one technique would be to transmit a known pseudo-random bit sequence (an m-sequence) using BPSK modulation at the carrier frequency of interest. The chip rate of the sequence determines the measurement system bandwidth, while the sequence length determines the 'dynamic range' of the measurement. At the receiver set the LO to the same carrier frequency as that at the transmitter. Here you need to cross-correlate the equivalent low-pass received signal with the known m-sequence to give the (complex) impulse response of the channel. Any 'peaks' that exceed your definition of a threshold noise level would be your channel coefficients in the time domain. This is actually implemented in gr-sounder. The channel sounder transmitter is sending the PRNG modulated BPSK at 32 Mchips/sec. You need to do the correlation at this speed; it's not possible to send that much data over the USB to the host. A channel sounder in software would work for chip rates less than 4 Mchip/sec. But that limits the resolution of your impulse response to about 250 ns per bin, or 75 meters per bin in the spatial domain. Unfortunately, the cross-correlation done on the very limited space FPGA has no frequency offset compensation, so the resulting impulse response vectors "roll" in the time domain. -- answer (c) by Johnathan Corgan
{ "language": "en", "url": "https://stackoverflow.com/questions/110781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I install ExtUtils::PkgConfig in Perl on Windows? I've tried cpan and cpanp shell and I keep getting: ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't seem to be in your PATH. Is it correctly installed? What is the pkg-config utility and how do I install it? Updates: * *OS: Windows *This module is a prerequisite for the File::Extractor module A: look here: http://gtk2-perl.sourceforge.net/win32/howto_build_gtk2perl_win32.html I found this page by googling for ExtUtils::PkgConfig and "PPM" (Actvestates Perl Package Manager). A: pkg-config is used for when you are compiling applcations and libraries. It's really used for inserting the right command line arguments. It comes installed on most new releases of linux, but is pretty common if it's not there initially so it shouldn't be too hard to find. Here's how to install it on ubuntu: sudo apt-get install pkg-config Here's the wikipedia page: http://en.wikipedia.org/wiki/Pkg-config A: http://pkgconfig.freedesktop.org/wiki/ pkg-config is a helper tool used when compiling applications and libraries. Depending on your OS, you might be able to get a binary distribution (try apt-get on Ubuntu, for example), otherwise you can get the source from their web site. A: I found the Windows binaries for the pkg-config utility here: http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ (Link was found here: http://www.go-evolution.org/Building_Evolution_on_Windows) Update: straight download link from gtk.org : pkg-config-0.23-2.zip Thanks for the pointers! A: A better source for Windows binaries for pkg-config is the gtk site
{ "language": "en", "url": "https://stackoverflow.com/questions/110801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dirty fields in django In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not. A: I extended Trey Hunner's solution to support m2m relationships. Hopefully this will help others looking for a similar solution. from django.db.models.signals import post_save DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s._reset_state' % self.__class__.__name__) self._reset_state() def _as_dict(self): fields = dict([ (f.attname, getattr(self, f.attname)) for f in self._meta.local_fields ]) m2m_fields = dict([ (f.attname, set([ obj.id for obj in getattr(self, f.attname).all() ])) for f in self._meta.local_many_to_many ]) return fields, m2m_fields def _reset_state(self, *args, **kwargs): self._original_state, self._original_m2m_state = self._as_dict() def get_dirty_fields(self): new_state, new_m2m_state = self._as_dict() changed_fields = dict([ (key, value) for key, value in self._original_state.iteritems() if value != new_state[key] ]) changed_m2m_fields = dict([ (key, value) for key, value in self._original_m2m_state.iteritems() if sorted(value) != sorted(new_m2m_state[key]) ]) return changed_fields, changed_m2m_fields One may also wish to merge the two field lists. For that, replace the last line return changed_fields, changed_m2m_fields with changed_fields.update(changed_m2m_fields) return changed_fields A: Continuing on Muhuk's suggestion & adding Django's signals and a unique dispatch_uid you could reset the state on save without overriding save(): from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) self._reset_state() def _reset_state(self, *args, **kwargs): self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) Which would clean the original state once saved without having to override save(). The code works but not sure what the performance penalty is of connecting signals at __init__ A: I extended muhuk and smn's solutions to include difference checking on the primary keys for foreign key and one-to-one fields: from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(self._reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) self._reset_state() def _reset_state(self, *args, **kwargs): self._original_state = self._as_dict() def _as_dict(self): return dict([(f.attname, getattr(self, f.attname)) for f in self._meta.local_fields]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) The only difference is in _as_dict I changed the last line from return dict([ (f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel ]) to return dict([ (f.attname, getattr(self, f.attname)) for f in self._meta.local_fields ]) This mixin, like the ones above, can be used like so: class MyModel(DirtyFieldsMixin, models.Model): .... A: I've found Armin's idea very useful. Here is my variation; class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) Edit: I've tested this BTW. Sorry about the long lines. The difference is (aside from the names) it only caches local non-relation fields. In other words it doesn't cache a parent model's fields if present. And there's one more thing; you need to reset _original_state dict after saving. But I didn't want to overwrite save() method since most of the times we discard model instances after saving. def save(self, *args, **kwargs): super(Klass, self).save(*args, **kwargs) self._original_state = self._as_dict() A: If you're using your own transactions (not the default admin application), you can save the before and after versions of your object. You can save the before version in the session, or you can put it in "hidden" fields in the form. Hidden fields is a security nightmare. Therefore, use the session to retain history of what's happening with this user. Additionally, of course, you do have to fetch the previous object so you can make changes to it. So you have several ways to monitor the differences. def updateSomething( request, object_id ): object= Model.objects.get( id=object_id ) if request.method == "GET": request.session['before']= object form= SomethingForm( instance=object ) else request.method == "POST" form= SomethingForm( request.POST ) if form.is_valid(): # You have before in the session # You have the old object # You have after in the form.cleaned_data # Log the changes # Apply the changes to the object object.save() A: You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of all changes to your objects stored in the DB, try this AuditTrail solution. UPDATE: The AuditTrail code I linked to above is the closest I've seen to a full solution that would work for your case, though it has some limitations (doesn't work at all for ManyToMany fields). It will store all previous versions of your objects in the DB, so the admin could roll back to any previous version. You'd have to work with it a bit if you want the change to not take effect until approved. You could also build a custom solution based on something like @Armin Ronacher's DiffingMixin. You'd store the diff dictionary (maybe pickled?) in a table for the admin to review later and apply if desired (you'd need to write the code to take the diff dictionary and apply it to an instance). A: Django is currently sending all columns to the database, even if you just changed one. To change this, some changes in the database system would be necessary. This could be easily implemented on the existing code by adding a set of dirty fields to the model and adding column names to it, each time you __set__ a column value. If you need that feature, I would suggest you look at the Django ORM, implement it and put a patch into the Django trac. It should be very easy to add that and it would help other users too. When you do that, add a hook that is called each time a column is set. If you don't want to hack on Django itself, you could copy the dict on object creation and diff it. Maybe with a mixin like this: class DiffingMixin(object): def __init__(self, *args, **kwargs): super(DiffingMixin, self).__init__(*args, **kwargs) self._original_state = dict(self.__dict__) def get_changed_columns(self): missing = object() result = {} for key, value in self._original_state.iteritems(): if key != self.__dict__.get(key, missing): result[key] = value return result class MyModel(DiffingMixin, models.Model): pass This code is untested but should work. When you call model.get_changed_columns() you get a dict of all changed values. This of course won't work for mutable objects in columns because the original state is a flat copy of the dict. A: Adding a second answer because a lot has changed since the time this questions was originally posted. There are a number of apps in the Django world that solve this problem now. You can find a full list of model auditing and history apps on the Django Packages site. I wrote a blog post comparing a few of these apps. This post is now 4 years old and it's a little dated. The different approaches for solving this problem seem to be the same though. The approaches: * *Store all historical changes in a serialized format (JSON?) in a single table *Store all historical changes in a table mirroring the original for each model *Store all historical changes in the same table as the original model (I don't recommend this) The django-reversion package still seems to be the most popular solution to this problem. It takes the first approach: serialize changes instead of mirroring tables. I revived django-simple-history a few years back. It takes the second approach: mirror each table. So I would recommend using an app to solve this problem. There's a couple of popular ones that work pretty well at this point. Oh and if you're just looking for dirty field checking and not storing all historical changes, check out FieldTracker from django-model-utils. A: An updated solution with m2m support (using updated dirtyfields and new _meta API and some bug fixes), based on @Trey and @Tony's above. This has passed some basic light testing for me. from dirtyfields import DirtyFieldsMixin class M2MDirtyFieldsMixin(DirtyFieldsMixin): def __init__(self, *args, **kwargs): super(M2MDirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect( reset_state, sender=self.__class__, dispatch_uid='{name}-DirtyFieldsMixin-sweeper'.format( name=self.__class__.__name__)) reset_state(sender=self.__class__, instance=self) def _as_dict_m2m(self): if self.pk: m2m_fields = dict([ (f.attname, set([ obj.id for obj in getattr(self, f.attname).all() ])) for f,model in self._meta.get_m2m_with_model() ]) return m2m_fields return {} def get_dirty_fields(self, check_relationship=False): changed_fields = super(M2MDirtyFieldsMixin, self).get_dirty_fields(check_relationship) new_m2m_state = self._as_dict_m2m() changed_m2m_fields = dict([ (key, value) for key, value in self._original_m2m_state.iteritems() if sorted(value) != sorted(new_m2m_state[key]) ]) changed_fields.update(changed_m2m_fields) return changed_fields def reset_state(sender, instance, **kwargs): # original state should hold all possible dirty fields to avoid # getting a `KeyError` when checking if a field is dirty or not instance._original_state = instance._as_dict(check_relationship=True) instance._original_m2m_state = instance._as_dict_m2m() A: for everyone's information, muhuk's solution fails under python2.6 as it raises an exception stating 'object.__ init __()' accepts no argument... edit: ho! apparently it might've been me misusing the the mixin... I didnt pay attention and declared it as the last parent and because of that the call to init ended up in the object parent rather than the next parent as it noramlly would with diamond diagram inheritance! so please disregard my comment :)
{ "language": "en", "url": "https://stackoverflow.com/questions/110803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Integrating gyro and accelerometer readings Possible Duplicate: Combine Gyroscope and Accelerometer Data I have read a number of papers on Kalman filters, but there seem to be few good publically accessible worked examples of getting from mathematical paper to actual working code. I have a system containing a three-axis accelerometer and a single gyro measuring rotation around one of the accelerometer axes. The system is designed to be held by a human, and much of the time the gyro will be measuring rotation about the gravity vector or close to it. (People working in the same industry will likely recognise what I am talking about from that ;)) I realise this is underconstrained. The gyros appear to have a near-constant bias that is slightly different for each instance of the system. How would I go about coding a filter to use the accelerometer readings to calibrate the gyro at times when the system is tilted so the gyro axis is not collinear with gravity, and is being rotated about the gyro axis? It seems like there should be enough information to do that, but being told that there isn't and why would be an answer too :) A: You seem to have two (or three) separate problems here. 1. You don't really understand Kalman filters and/or the mathematics behind them. That is going to make it very difficult to correctly implement and use one. 2. You don't seem to understand the basic physics involved in the problem. (Basic physics means underlying physics, not simple physics, because it isn't simple.) I'd suggest that you try to use a much simpler integrator, such as a Runga-Kutta 4, for which you can find many books with examples of both the implementation and the use. It should be sufficient for this problem. (If the customer specified Kalman, inquire why.) As for why the problem is under constrained, it seems to me that it is having no way to insure that the device is held vertically and no way to measure the actual orientation. Forget the gyro for the moment and assume the device can not be rotated about a vertical axis. You have three accelerometers, presumably to estimate position in 3D. So if you see an acceleration in the X direction, you increase the estimate of where you are in the X direction. Similarly, if you see an acceleration in the Z direction (which I will assume is "up"), you increase the estimate of where you are in the Z direction. Now rotate the device slightly, say 30 degrees about the Y axis. Now when the device thinks you are accelerating along the X direction, the device is actually accelerating a bit less than indicated in X and it is also accelerating in the Z direction. So your position estimate is now incorrect. Rotations are much harder to integrate (the equations are more "stiff", requiring a smaller time step to maintain precision). But they will suffer similar problems of computing wrong answers if the device is tipped (because the device can not tell that it is tipped). It will think that the rotation about the vertical axis is larger or smaller than it actually is, because part of the rotation is actually about a different axis (just as part of the acceleration part was along a different axis). Perhaps you need to hire a consultant (no, I'm not seeking a job) to assist you in formulating the mathematics. A: Given your interest in the kalman filter, perhaps you intend to augment GPS data with inertial measurements. About your question: "How would I go about coding a filter to use the accelerometer readings to calibrate the gyro at times when the system is tilted so the gyro axis is not collinear with gravity, and is being rotated about the gyro axis? It seems like there should be enough information to do that" This sounds like a gyrocompasing alignment. Assuming you are doing a factory calibration, and have the unit on a bench, you will be able to independently measure the alignment. Then run the leveling code you will write and back out the gyro bias error from the difference between the measure and gyrocompased alignments. If you want to update gyro drift on-the fly, then you will need the kalman filter. As far as implementation goes I recommend Chapter 7, GPS and Inertial Integration of Global Position System Theory and Applications vol 2 has excellent background on the topic. It has the theory and math, but no source code. A: I found good articles about the use of accelerometers and gyroscopes in navigation on this blog. The part on Kalman filtering is a bit hazy, but there seems to be code samples. You will also find general resources on Kalman filtering at http://academic.csuohio.edu/simond/publications.html. The article referred in (8) is a good, not too scary, introduction to the mathematics behind Kalman filters. A: nBot, a two wheel balancing robot Quite a bit of info and links about how this author chose to solve the balance problem for his two wheeled robot. A: A gentleman in Denmark has just posted a worked example of the derivation of a Kalman filter for solving almost exactly this problem. A: If you happen to be developing for the Propeller uController, than the Parallax Object Exchange has some code. Great question ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/110804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Best graphic library for .NET/Mono I am looking for a high-performance graphic library for .NET and Mono. I have taken a look at Tao framework and, while it is very complete, it's quite lacking in terms of usability. It should be cross-platform compatible. What other alternatives worked for you? A: There is a more modern OpenGL wrapper for .NET/Mono called OpenTK. A: OpenGL would be my choice, .NET bindings exist from many open source wrappers, with OpenGL you're set for cross platform. A: I agree with mhutch - OpenTK is a very good .NET/Mono wrapper for OpenGL. For one, it has its own vector/matrix math library that, among other things, contains some of the more useful GLUT functions (I used to miss) like CreatePerspectiveFieldOfView and LookAt. I've found this library especially useful now that the matrix stack is no longer "kosher". Finally, it comes with a nice sample project so you can study how to use the wrapper without extensive documentation study.
{ "language": "en", "url": "https://stackoverflow.com/questions/110814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Firefox status bar is 3/4" above the bottom border Somehow my FireFox 2 got corrupted, and the status bar is about 3/4" above the bottom window border. Anyone have an idea on how to get it back to being flush with the bottom window border? A: Not sure it is programming-related... but: firefox -safe-mode Reset toolbar and control More at Firefox support
{ "language": "en", "url": "https://stackoverflow.com/questions/110822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Saving information in "sub" model in CakePHP I've got a simple CakePHP site (1.2). I've got a page where you can edit and save a Person. So I have a Person model and controller. Each Person has none or more comments, in the comment table. So I have a Comment model, and I have a hasMany association on my Person model to the Comment model. View is working great. My question is, on the view Person page, I have an add comment button. How should this work? Should I expect the Person controller to include a save for the comment record, or create a comment controller and save it outside of it's association for a person? I'm experienced with PHP, but brand new to Cake. Any ideas? I think I'm just missing something obvious, but I'm not sure what to do. I feel like if this was PHP I would reference the Person_id in my add comment form, and thus use a separate controller, but I feel like having a controller for a simple Model is useless, since Comments are only edited in the context of a Person record. Ideas? A: I'm not a CakePHP expert, but I still think it would make sense to have your own controller. From what I remember from doing one of those CakePHP blog tutorials is, that you need to link the comments and the post in the comment model. This is some of the code I have from it: class Comment extends AppModel { var $name = ‘Comment’; var $belongsTo = array(‘Person’); } And then you need a controller (comments_controller.php): class CommentsController extends AppController { var $name = ‘Comments’; var $scaffold; } Some SQL: CREATE TABLE comments ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, author VARCHAR(50), comment TEXT, person_id INT, created DATETIME DEFAULT NULL, modified DATETIME DEFAULT NULL ); The $scaffold creates a CRUD application for you, so when you go to /comments in your browser you can create, read, update and delete comments. So, as you see, there is not much involved here. All you need is your database tables and a little logic to provide person_id. To save a comment (in your Person/view): <h2>Add comment</h2> <?php echo $form->create(‘Comment’, array(‘action’=>‘add/’.$person[‘Person’][‘id’]); echo $form->input(‘author’); echo $form->input(‘content’); echo $form->submit(‘Add comment’); echo $form->end(); ?> And in your CommentsController: function add($id = NULL) { if (!empty($this->data)) { $this->data['Comment']['person_id'] = $id; $this->data['Comment']['id'] = ''; if ($this->Comment->save($this->data)) { $this->Session->setFlash('Commented added'); $this->redirect($this->referer()); } } } So you basically overwrite the standard add action, which Cake adds by itself. Hope that makes sense now. Also, you might need a route so it picks up /comments/add/ID. I don't know about this part. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/110825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamically importing a C++ class from a DLL What is the correct way to import a C++ class from a DLL? We're using Visual C++. There's the dllexport/exports.def+LoadLibrary+GetProcAddress trifecta, but it doesn't work on C++ classes, only C functions. Is this due to C++ name-mangling? How do I make this work? A: Found the solution at http://www.codeproject.com/KB/DLL/XDllPt4.aspx Thanks for your efforts guys & girls A: I normally declare an interface base class, use this declaration in my application, then use LoadLibrary, GetProcAddress to get the factory function. The factor always returns pointer of the interface type. Here is a practical example, exporting an MFC document/view from a DLL, dynamically loaded A: dllexport/dllimport works, place it before your class name in the header file and you're good to go. Typically you want to use dllexport in the dll, and dllimport in the exe (but you can just use dllexport everywhere and it works, doing it 'right' makes it tinily faster to load). Obviously that is for link-time compilation. You can use /delayload linker directive to make it 'dynamic', but that's probably not what you want from the subject line. If you truly want a LoadLibrary style loading, you're going to have to wrap your C++ functions with "extern C" wrappers. The problem is because of name mangling, you could type in the fully-mangled name and it'd work. The workarounds are generally to provide a C function that returns a pointer to the correct class - COM works this way, as it exports 4 C functions from a dll that are used to get the interface methods inside the object in the dll. A: Check out this question. Basically, there are two ways. You can mark the class using _dllexport and then link with the import library, and the DLL will be loaded automatically. Or if you want to load the DLL dynamically yourself, you can use the factory function idea that @titanae suggested A: You need to add the following: extern "C" { ... } to avoid function mangling. you might consider writing two simple C functions: SomeClass* CreateObjectInstace() { return new SomeClass(); } void ReleaseObject(SomeClass* someClass) { delete someClass; } By only using those functions you can afterward add/change functionality of your object creation/deletion. This is sometimes called a Factory.
{ "language": "en", "url": "https://stackoverflow.com/questions/110833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Never do anything until you ready to use it, in software too? [Toyota principle] I was listening to a podcast. Where they talked about principles Toyota was using: Never do anything until you are ready to use it. I think this tells us to look in other places, to learn what other practices have been known for years. A: It may apply to software construction, but I am not sure it does apply If we consider the five elements in a "toyota-way of decision making", based on the principle that "how you arrive at the decision is just as important as the quality of the decision": [mode humour ON] * *Finding out what is really going on, including genchi gembutsu. Except that sometime, one does finally understand what is going on when the client explain to us at the end of the project;) *Understanding underlying causes that explain surface appearances—asking “Why?” five times. Sure but the client is not available enough during the project ;) *Broadly considering alternative solutions and developing a detailed rationale for the preferred solution. Too late, the programmers are already coding like madmen :) *Building consensus within the team, including Toyota employees and outside partners. Oops that programmer is already re-writing the authentification system even though the old one was working fine *Using very efficient communication vehicles to do one through four, preferably one side of one sheet of paper. Did you hear "death by powerpoint" ? This is not always our strong suit ;) [mode humour OFF] Seriously, as stated by the previous answers, the Agile philosophy does address some of the core tenants of this Toyota principle. And it may be a little richer that just "You Ain't Gonna Need It", as described in the book "The Toyota way" A: Sort of, yes. This is a core part of the agile philosophy. Basically, favour flexibility and speed of response over big design up front and unwieldy specifications. One of the best ways of doing that is to only build enough to meet your current requirements, because you never know when they're going to change. A: It is old news a little. It's often called "You ain't gonna need it" ( "You Arent' Going to Need It" in non-idomatic English), and abbreviated YAGNI. Problems associated with implementing a feature when you don't need it: * *the implementation takes time away from developing features that are needed *the feature is hard to document and test, since if you don't need it, who knows what it's supposed to do exactly? *maintaining the feature will take additional time *the feature adds extra code, complicating the codebase *the feature may have a snowball effect, whereby it suggests other features that you may then want to add, even though they're not needed A: It is a good agile practice to think just like that. There is also something called Test-Driven-Development, that helps you get software without bugs (almost), but also have that side effect that NOTHING is implemented that you don't use. A example is you're own collection class. If you only are needing a Add method, and a ToArray method, then why use the time to implement the Remove and Count methods? So yep. Follow that principle :)
{ "language": "en", "url": "https://stackoverflow.com/questions/110855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In need for a site that explains how to use PHPUnit I am searching for a tutorial (optimally with Zend Framework) on how to use PHPUnit. I have found a couple on google but have not quiet understood it yet. A: For information about PHPUnit, be sure to read the documentation. It does not look too bad IMO. There is a blog entry about Automatic testing of MVC applications created with Zend Framework which looks quite good, too. :) A: There is also an "Introduction to the Art of Unit Testing" posted on the Zend Developer Zone, which covers PHPUnit with Zend specifically. A: What your are looking for is the Pocket Guide. It explaines how to work with PHPUnit from A to Z in several languages. You can read it online or offline, for free, and it's regularly updated. A: Simpletest, which is very similar to PHPUnit, but a lot simpler, has a good introductory tutorial. Even if you plan to use PHPUnit, this should teach you the basics of unit testing. A: If you're looking for a simple introduction to using PHPUnit and Zend_Test with the Zend Framework, I wrote a simple tutorial that covers the basics of setting up PHPUnit and writing a few simple tests both with PHPUnit and Zend_Test. A: A great tutorial (git-based, exercise based), on physically going through the motions of testing by Sebastian Marek: https://github.com/proofek/phpnw12-tutorial Found it very helpful for very baseline beginners. The slides: http://www.slideshare.net/proofek/test-your-code-like-a-pro-phpunit-in-practice
{ "language": "en", "url": "https://stackoverflow.com/questions/110858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Debugging Designer processing in VS 2008 I have a public property set in my form of type ListE<T> where: public class ListE<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection. Arithmetic operation resulted in an overflow. Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas? EDIT: Yes, I can use the property successfully, well even manually, ie. in the OnLoad handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :( A: I can't understand what's motivating you to attempt to reinvent the List<T> wheel in that way, but to answer your question: I would add a line "System.Diagnostics.Debugger.Break()" to the constructor of your class. Then try to use it in the designer, and you'll get a popup asking you if you want to attach a debugger. Attach a second instance of Visual Studio as a debugger, and you'll be able to set some breakpoints in your code and start debugging. A: One place to start would be that it may be doing math with your ListE`1::Count property. If that has some subtle flaw (i.e. it is more complicated than return this.innerList.Count) it could be causing the designer to arithmetic overflow on some operation. Normally arithmetic overflows do not occur unless specifically asked for using the checked { // ... } syntax. A: You don't have to add the Debugger.Break(); call to your code to debug it. You can just open a different instance of VS and attach to the one that you using it in and you should be able to debug it with no issues (just make sure that you have the symbols loaded).
{ "language": "en", "url": "https://stackoverflow.com/questions/110867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Never produce to an unknown pathway, in software too? [Toyota principle] In Toyota manufacturing lines they always know what path a part have traveled. Just so they can be sure they can fix it of something goes wrong. Is this applicable in software too? All error messages should tell me exactly what path they traveled. Some do, the error messages with stack trace. Is this a correct interpretation? Could it be used some where else? Ok, here is the podcast. I think it is interesting http://itc.conversationsnetwork.org/shows/detail3798.html A: A good idea where practicable. Unfortunately, it is usually prohibitively difficult to keep track of the entire history of the state of the machine. You just can't tag each data structure with where you got it from, and the entire state of that object. You might be able to store just the external events and in that way reproduce where everything came from. Some examples: I did work on a project where it was practicable and it helped immensely. When we were getting close to shipping, and running out of bugs to fix, we would have our game play in "zero players mode", where the computer would repeatedly play itself all night long with all variations of characters and locales. If it asserted, it would display the random key that started the match. When we came to work in the morning we'd write the key down from our screen (there usually was one) and start it again using that key. Then we'd just watch it until the assert came up, and track it down. The important thing is that we could recreate all the original inputs that led to the error, and rerun it as many times as we wanted, even after recompiles (within limits... the number of fetches from the random number generator could not be changed, although we had a separate RNG for non-game stuff like visual fx). This only worked because each match started after a warm reboot and took only a very small amount of data as input. I have heard that Bungie used a similar method to try to discover bad geometry in their Halo levels. They would set the dev kits running overnight in a special mode where the indestructable protagonist would move and jump randomly. In the morning they'd look and see if he got stuck in the geometry at some location where he couldn't get out. There may have been grenades involved, too. On another project we actually logged all user interaction with a timestamp so we could replay it. That works great if you can, but most people have interactions with a changing DB whose entire state might not be stored so easily. A: It's less vital with software. If something goes wrong in software, you can usually reproduce the fault and analyse it in captivity. Even if it only happens 1 time in 1000, you can often switch on all the logging and run it 1000 times (a simple soak test). That's much more expensive and time-consuming on a manufacturing line, to the point of being impossible. Having as much information available as possible the first time it goes wrong is no bad thing, but it's not as important to me as it is to Toyota. A: This is a good approach. But be aware that you shouldn't over-do logging. Otherwise you couldn't find the interesting informations in all the noise, and it reduces the overall performance (e.g. anonymous object creation, depending on the language). A: Producing error messages with a full stack trace is usually bad security practice. On the other hand, and more in line with Toyota's intent, every developed module should be traced back to the original programmer(s) - and they should be held accountable for shoddy work, bug fixes, security vulnerabilities, etc. Not for disciplinary purposes, but both maintenance, and education if necessary. And maybe for bonuses, in the contrary situation... ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/110868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Always do it with the same method every time, is this usable in Software projects? I was out running.. listening to a podcast about Toyota.. anyway. This principle I think does not come to use in the software projects. (maybe project management). The art is still to young. We don't know what we are doing, at the moment. But eventually, we will. Or, do some one see how to use this core principle? Ok, here is the podcast. I think it is interesting http://itc.conversationsnetwork.org/shows/detail3798.html A: I would suggest a small modification, if the method has been proven to work properly (performance/maintenance/security/etc.), THEN use that every time. The trick is the "proven to work", and also the "properly". So basically, unless there is a problem with the current method, don't change it for the sake of change. (Note that a method that works provably better, in actuality highlights that the other method has a problem, notably does not work as well). Particularly in our field it is especially applicable, because of the productivity/scalability gains you get when most code is built the same way. E.g. maintenance, developer training, etc. In other, more familiar words from the famed philosopher: If it ain't broke, don't fix it. A: Well, I think it absolutely depends. If the method you have already used has good execution time, is (mostly) free of bugs, and works just how you want, then there is no need to write a new way of doing this task. Especially if you are programming for money, or for a company. However, if you are wanting to learn some new features of a programming language, or simply a different way of doing things, completely for you personal interest, why not? In a company like Toyota, saving time and money is of utmost importance. However, your personal time has whatever importance you assign to it. If learning a new method of doing something is good for your bottom line then do it. If your bottom line is to learn as much as possible, then this is probably the right thing to do. If, on the other hand, your bottom line is to get as many projects done as fast as possible then it is not. However, trying a different method could still be useful, even if your bottom line is to save time and money; because, by doing something you've already done with a different methodology may introduce ideas to you that could potentially save you time (and time is money) in the long run. So I'd pretty much say, if redoing something in a completely different way is what you want to do, then just do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/110876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Does Microsoft Robotics Developer Studio work on CE 6? I have a DSS service I created (For Microsoft Robotics Studio). I then followed the documentation to make it a compact framework service and created a deployment package. I then deploy it to a CE 6 device... Does a MSRS service work on CE 6? The documentation talks about CE 5. What should I see if I run it? I expect to see something simillar to running DSSHost on Windows... but I only see a blank screen so I do not know if the service is running. The documentation states that it does take time the first time (+/- 30 seconds on a EBOX-2300) . I left it for a while but there is still a blank screen! Should I see something? I also tried to access the service using web browser but no luck. Also, how do I set up the security settings to allow distributed nodes? I haven't yet isolated the problem completely but I have a work-around!!! I initially tried creating my service using MSRS 2008 (CTP) + Visual Studio 2008 without any sucess!!! I now did exactly the same using MSRS 1.5 Refresh + Visual Studio 2005 and it is working 100% I will try and isolate if it is the VS 2008 vs VS 2005 or the MSRS 1.5 vs MSRS 2008 PS. I also tried it on CE 5 and CE 6 and both works!!! A: Applications can also run directly on PC-based robots running Windows® Vista, Window® XP, Windows® XP Embedded, Windows® Embedded CE 6.0 and Windows Mobile® 6, enabling fully autonomous operation. Taken from this document
{ "language": "en", "url": "https://stackoverflow.com/questions/110881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP parse configuration ini files Is there a way to read a module's configuration ini file? For example I installed php-eaccelerator (http://eaccelerator.net) and it put a eaccelerator.ini file in /etc/php.d. My PHP installation wont read this .ini file because the --with-config-file-scan-dir option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings? A: This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a <?php phpinfo(); ?> and check where it's located. For example, try this: [eAccelerator] extension="eaccelerator.so" eaccelerator.shm_size="32" eaccelerator.cache_dir="/tmp" eaccelerator.enable="1" eaccelerator.optimizer="1" eaccelerator.check_mtime="1" eaccelerator.debug="0" eaccelerator.filter="" eaccelerator.shm_max="0" eaccelerator.shm_ttl="0" eaccelerator.shm_prune_period="0" eaccelerator.shm_only="0" eaccelerator.compress="1" eaccelerator.compress_level="9" Another thing you could do is set all the settings on run-time using ini_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure. A: The standard way in this instance is to copy the relevant .ini lines to the bottom of the php.ini file. There is no 'include "file.ini"' functionality in the php.ini file itself. You can't do it at run time either, since the extension has already been initialised by then. A: If using Apache, and mod-php, you can configure/override some php settings locally with a .htaccess file. Your webserver has to "AlloweOverride" appropriately in the main config file to allow you to override these settings locally. In my experience, many hosting companies will let you set php settings via htaccess. (thanks commenter for pointing out this only works with mod-php)
{ "language": "en", "url": "https://stackoverflow.com/questions/110887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL transaction with thousands of Inserts - how many "round trips" does it take? I've got C# code that accesses MySQL through ODBC. It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way? A: There is no limit on the number of rows per se; The limit is on the number of bytes transferred to the server. You could build the bulk insert up to the number of bytes specified in 'max allowed packet'. If I wanted to use the least amount of inserts I would try that. A: MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time: INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015); I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself. A: It does one round trip per query you submit (regardless of whether it's in a transaction or not). It is possible, in MySQL, to use "extended insert" syntax which allows you to insert several (or indeed, many) rows in a single statement. This is generally considered a Good Thing. A: A round trip to the DB server is not the same as a round trip to the database on disk. Before you decide that the round trips are a bottleneck, do some actual measurements. There are ways to insert multiple rows with a single insert, depending on your DBMS. Before you invest the coding effort, figure out whether it's likely to do you any good. A: It's hard to say without seeing your code, but I'm assuming you are executing the statements one at a time. So, you will get one round trip per insert statement. In MSSql you can execute multiple inserts in a single statement: cmd.ExecuteNonQuery "insert table values (1) insert table values (2)" So you can create a big string and execute it (I think it will have a limit), I assume this will work for MySQL. Also in MSSQL you have a batch inserter (lookup "SqlBulkCopy"), in MySQL perhaps try loading the data from a temp file. A: It depends on where you invoke the SQL statement. I tried it once with MySQL JDBC driver and got an error saying the limit is 1MB but it is configurable. I didn't bother to try to configure it and just split the SQL statements into smaller pieces. A: The limit of data that will be send depends on your server so the maximal length of multiple insert statements is automagically adjusted to fit. The bottleneck is a packet length and a buffer length. See the net_buffer_length and max_allowed_packet variable descriptions for more info: https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_net_buffer_length https://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_max_allowed_packet In some cases you can adjust these (e.g. when dumping data) to not generate inserts that are too long yet preserve multiple inserts. Be aware that if you have some blobs in your tables or any other long values that might exceede values of the mentioned variables you may get errors or incomplete data. A: When using MySQL 4.x a few years ago, we ran into a hard limit on query size that was not configurable. This probably won't help you much as: * *I don't remember what the hard limit was. *You're probably not using MySQL 4.x. *We weren't using transactions. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/110894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }