Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Currently my code is organized in the following tree structure: ``` src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py ``` Where the `module*.py` files contains the source code and the `test_module*.py` contains the `TestCase`s for the relevant module. With the following comands I can run the tests contained in a single file, for example: ``` $ cd src $ nosetests test_filesystem.py .................. ---------------------------------------------------------------------- Ran 18 tests in 0.390s OK ``` How can I run all tests? I tried with `nosetests -m 'test_.*'` but it doesn't work. ``` $cd src $ nosetests -m 'test_.*' ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK ``` Thanks
If they all begin with `test` then just `nosetest` should work. Nose automatically searches for any files beginning with 'test'.
Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc). When you're using nosetests, make sure that all directories with tests are real packages: ``` src/ module1.py module2.py subpackage1/ __init__.py moduleA.py moduleB.py tests/ __init__.py test_module1.py test_module2.py subpackage1/ __init__.py test_moduleA.py test_moduleB.py ``` This way, you can just run `nosetests` in the toplevel directory and all tests will be found. You need to make sure that `src/` is on the `PYTHONPATH`, however, otherwise all the tests will fail due to missing imports.
How to organize python test in a way that I can run all tests in a single command?
[ "", "python", "unit-testing", "python-nose", "" ]
What's the easiest way to truncate a C++ `float` variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?
First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable. But here are a couple of solutions to the problem that will probably meet your need: Probably the better method but less efficient: ``` char sz[64]; double lf = 0.600000002; sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000 double lf2 = atof(sz); //lf == 0.600000002; //lf2 == 0.6000 printf("%.4lf", lf2); //print 0.6000 ``` The more efficient way, but probably less precise: ``` double lf = 0.600000002; int iSigned = lf > 0? 1: -1; unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate lf = (((double)uiTemp)/pow(10,4) * iSigned); ```
A good reference for *why* this happens can be found in [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) by David Goldberg.
Truncate a decimal value in C++
[ "", "c++", "decimal", "truncate", "" ]
I've got a number of WebService methods that all include some very boilerplate code of wrapping the actual work in a try/catch/finally and performing the same tasks in the catch/finally. So as a way to encapsulate all of the shared catch/finally stuff I wrote a simple generic. This works and really eliminates a bunch of repetitive code but feels klunky, and the syntax is very obtuse. Every time I come back to this my brain gets twisted trying to figure it out (a clear sign it is not a good design). I'm looking for feedback on whether this is a crazy thing to do, and if there is a better way to approach it. Here is my template: ``` public delegate T2 RestfulServiceRequest<T1, T2>(T1 req); static class RestfulService { public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req) { if (req == null) throw new BadRequestException(new ArgumentNullException("Invalid or missing request object")); try { return serviceCall(req); } catch (RestfulException e) { // log it and rethrow Logger.Write(e); throw; } catch (Exception e) { Logger.Error(e); // wrap in a consistent exception for propagation back to caller throw new InternalServerException(e); } finally { Logger.Debug("Complete"); } } } ``` } And here is a usage of it: ``` public class Initialization : IInitialization { // MyMethod thas uses the template public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req) { return RestfulService.ExceptionHandler<ApplianceInitReq, ApplianceInitResp>(delegate(ApplianceInitReq x) { // do some work return new ApplianceInitResp(); }, req); } } ``` }
I would change ``` public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req) ``` to ``` public static T2 Invoke<T1, T2>( this T1 req, RestfulServiceRequest<T1, T2> serviceCall) ``` This will change the call to ``` public class Initialization :IInitialization { public ApplianceInitResp CreateApplianceServer( ApplianceInitReq req ) { return req.Invoke( r => { // do some work return new ApplianceInitResp(); }); } } ```
One thing that will make it cleaner is to define interfaces that your request/response objects implement. Then you can get rid of the generics in favor of the interfaces. Note, too, the name change which I think is more descriptive of what you are really trying to do. ``` public interface IServiceResponse { ... } public class ApplianceInitResp : IServiceResponse { ... } public interface IServiceRequest { ... } public class ApplianceInitReq : IServiceRequest { ... } public delegate IServiceResponse RestfulServiceRequest( IServiceRequest req ); static class RestfulService { public static IServiceResponse Invoke( RestfulServiceRequest serviceCall, IServiceRequest req) { if (req == null) throw new BadRequestException( ...inner-exception... ); try { return serviceCall(req); } catch (RestfulException e) { Logger.Write(e); throw; } catch (Exception e) { Logger.Error(e); throw new InternalServerException(e); } finally { Logger.Debug("Complete"); } } } public class Initialization : IInitialization { // MyMethod thas uses the template public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req) { return RestfulService.Invoke( delegate(ApplianceInitReq x) { // do some work return new ApplianceInitResp(); }, req ); } } ```
Using Generics to encapsulate common method work
[ "", "c#", "generics", "" ]
I'm using JQuery and Prototype in this web application that I'm developing. I'm looking for a way to use Lightbox v2.04 by Lokesh Dhakar to play flash movies. If its not possible using the Lightbox v2.04 then what other ways can I accomplish the shadowing overlayed flash video pop-up with jquery and/or Prototype? The reason I'm set on v2.04 is because I'm using it already as an image gallery. I'm using flv type flash files if that helps.
I've used [LightWindow](http://www.stickmanlabs.com/lightwindow/) to display arbitrary HTML before, but my experience shows flash and LightWindow don't mix that well. We had a FLV player in the background (not in the LightWindow), and LightWindow caused flicker in some browsers.
Another alternative is using JQuery's [Thickbox plugin](http://jquery.com/demo/thickbox/).
playing flash movies in lightbox
[ "", "javascript", "jquery", "flash", "prototype", "lightbox", "" ]
A simple stupid "`UPDATE table SET something=another WHERE (always true)`" in accident will easily destroy everything in the database. It could be a human mistake, an SQL injection/overflow/truncation attack, or a bug in the code who build the WHERE causes. Are popular databases provide a feature that protect tables by limit maximum number of row could be updated in one SQL statement? I mean some kind of defensive setting that apply to pre-table access right on database: no-way to bypass, less code to program, no human mistake(unless grant yourself too much access right).
You can add a trigger that checks how many rows are being updated (count the Inserted magic trigger table), and RAISEERROR if that's too many rows.
I don't know of anything. I'm not sure that this would solve anything. How can the database distinguish between a SQL injection attack and a nightly batch update that happens to exceed your limit? One assumption is the auto commit is set to true. If the SQL injection attack isn't committed, you always have the opportunity to roll it back, assuming that you're looking at logs and such. I think the real answer is better layering of apps, validation, binding, etc. You can't do SQL injection if those measures are in place.
Is it possible to prevent batch update at the sql database level?
[ "", "sql", "sql-server", "database", "security", "" ]
I have to choose a platform for our product. I have to decide between The Qt Framework and Adobe's AIR. I am well versed with Qt as I have worked for the last two years. I looked up at the Adobe's site but all the info about flex, flash, ability to coding in HTML/ActionScript is overwhelming and confusing. I cannot understand the following about the Adobe ecosystem. I have the following questions on Adobe AIR: 1. What language do I use for coding my application? (not just defining the looks of UI) Like in Qt I use C++. Is it Actionscript? 2. Can we say AIR is only for making UI's for apps. 3. Where is the doc for the utility classes along with AIR? e.g. <http://qt-project.org/doc/> for Qt 4. Qt ships with a huge set of premade widgets that one can use. Does Adobe ship with any such widget set and if so where can i see it as in url? 5. I understand flex SDK is open source. Can I make commerical apps and ship them ? Does flex SDK ship everything (compiler, utility classes/widgets) 6. How much does AIR cost in terms of licensing? 7. Is there something in AIR that is equivalent to QGraphicsView of QT?
If you needs to access a lot of native libraries, you'll need to stay within your QT environment. Keep in mind that AIR is single-threaded and is run on the Flash Player (something that was originally designed for frame-based animations.) However, depending on the style of application you're building, AIR might suit you just fine. Beware that AIR can get confusing because there's a few different developer paths to creating AIR applications: 1) using html/javascript and the AIR SDK, 2) using Flash/Actionscript and 3) using Flex SDK and/or Flex builder. The last one is the most capable as far as coming from traditional desktop development background. Small apps that are Web 2.0 for hooking into web services are good candidates for AIR applications. Things like the IM client Digsby would be great. My favorite AIR app that I've seen thus far is Basamiq Mockups. Other useful apps are TweetDeck. These are good examples of the types of things that are well-suited to solve with AIR. You should visit the Adobe Showcase and look at some applications: <http://www.adobe.com/products/air/showcase/> Also, if you're looking to just get out of the C++ game, I believe QT has some java bindings now...also I remember some python bindings, but never look at those myself. As far as QGraphicsView, people have done similar things in Flex. I tried Googling right now but couldn't find them initially, but people have taken things like A large image, and then only displayed a current region in the window. Also, in the next version of Flex, they're acutaly building an official ViewPort component: <http://opensource.adobe.com/wiki/display/flexsdk/Gumbo+Viewport>
Go spend some time with this AIR application and then ask yourself if Adobe Flex and AIR are worth investing your time in mastering (be prepared to ask yourself why something comparable doesn't exist for the likes of C++/QT): [Tour de Flex](http://flex.org/tour) > Tour de Flex is a desktop application > for exploring Flex capabilities and > resources, including the core Flex > components, Adobe AIR and data > integration, as well as a variety of > third-party components, effects, > skins, and more. Some of your questions: * Flex can be coded in MXML and ActionScript3. AIR additionally supports HTML/DOM/JavaScript programming as webkit HTML render engine is built into the AIR runtime. * MXML is an XML declarative DSL that gets compiled into ActionScript3 imperative code. It is quite good, though, for declaratively coding the graphical forms of the UI (i.e., the views of the MVC pattern). * ActionScript3 has a heratige that is founded on JavaScript, but it has been embelished to the point it more resembles Java or C#. It has package namespace, classes and interfaces with inheritance, class member access protection keywords, constructors, static members, and some very nice additions over Java: properties, events, data-binding, and closures. Flex style programming is also a single-threaded model that relies on asynchronous I/O interactions. This is a simpler model to program than multi-threaded Java Swing or C# .NET Winform apps, yet permits achieving the same net results of program behavior. I elaborate on that here: [Flex Async I/O vs Java and C# Explicit Threading](http://humbleblogger.blogspot.com/2008/05/flex-async-io-vs-java-and-c-explicit.html)
C++/Qt vs Adobe AIR
[ "", "c++", "apache-flex", "qt", "air", "" ]
I've seen [Veloedit](http://veloedit.sourceforge.net/), which seems to have good syntax highlighting but doesn't allow tab characters in the file being edited (wtf?) and also has no understanding of HTML. With a little bit of googling I've found [Veloecipse](http://propsorter.sourceforge.net/), which claims to build upon Veloedit and also add HTML support - but doesn't seem to be compatible with Eclipse 3.4. Are there any other Velocity template editor plugins for Eclipse that anyone is using? The ideal solution would have the following features: * Syntax hightlighting of VTL * HTML syntax highlighting as well * Auto-complete of VTL syntax * Allows tabs! **Update**: see my answer below
Here's an update: I've been using Veloeclipse and it works well, not sure what led to my original comment about not working with Eclipse 3.4 but I am definitely using it with 3.4 now. Veloeclipse works better than Veloedit and Velocity Web Editor, in my opinion.
I have installed Veloeclipse since Veloedit raised exceptions when opening the editor and it works fine with eclipse 3.5.2. In order to install it, I had to *de*select "Group items by category" in the "Install new software..." dialog.
Velocity editor plugin for Eclipse?
[ "", "java", "eclipse", "velocity", "" ]
I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.
``` /^[a-z0-9]+$/i ^ Start of string [a-z0-9] a or b or c or ... z or 0 or 1 or ... 9 + one or more times (change to * to allow empty string) $ end of string /i case-insensitive ``` **Update (supporting universal characters)** if you need to this regexp supports universal character you can find [list of unicode characters here.](https://en.wikipedia.org/wiki/List_of_Unicode_characters) for example: `/^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/` this will support persian.
If you wanted to return a replaced result, then this would work: ``` var a = 'Test123*** TEST'; var b = a.replace(/[^a-z0-9]/gi, ''); console.log(b); ``` This would return: ``` Test123TEST ``` Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets". **WARNING**: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar". **UPDATE**: To support unicode alphanumeric, then the REGEXP could be changed to: `/[^\p{L}\p{N}]/giu`.
RegEx for Javascript to allow only alphanumeric
[ "", "javascript", "regex", "" ]
This is in reference to the [question](https://stackoverflow.com/questions/282944/jquery-one-slider-controls-another) previously asked The problem here is, each `slider` controls the other. It results in feedback. How do I possibly stop it? ``` $(function() { $("#slider").slider({ slide: moveSlider2 }); $("#slider1").slider({ slide: moveSlider1 }); function moveSlider2( e, ui ) { $('#slider1').slider( 'moveTo', Math.round(ui.value) ); } function moveSlider1( e, ui ) { $('#slider').slider( 'moveTo', Math.round(ui.value) ); } }); ```
This is sort of a hack, but works: ``` $(function () { var slider = $("#slider"); var slider1 = $("#slider1"); var sliderHandle = $("#slider").find('.ui-slider-handle'); var slider1Handle = $("#slider1").find('.ui-slider-handle'); slider.slider({ slide: moveSlider1 }); slider1.slider({ slide: moveSlider }); function moveSlider( e, ui ) { sliderHandle.css('left', slider1Handle.css('left')); } function moveSlider1( e, ui ) { slider1Handle.css('left', sliderHandle.css('left')); } }); ``` Basically, you avoid the feedback by manipulating the css directly, not firing the slide event.
You could store a var CurrentSlider = 'slider'; on mousedown on either of the sliders, you set the CurrentSlider value to that slider, and in your moveSlider(...) method you check whether this is the CurrentSlider, if not, you don't propagate the sliding (avoiding the feedback)
jQuery-ui slider - How to stop two sliders from controlling each other
[ "", "javascript", "jquery", "jquery-ui", "slider", "jquery-ui-slider", "" ]
I am sending the echo to mail function via PHP from variable that includes HTML code. The strange thing is, that this ``` <����}im� ``` shows up AFTER the string.. but I do not manipulate with it anymore. The charset of mail function (the attachment) is same as charset of HTML code.
Encoding problem, maybe it tries to display binary code? You should use htmlentities if ou want to display HTML > // Outputs: A 'quote' is > > <b>bold</b> echo > > htmlentities($str);
You could consider using the [htmlMimeMail](http://www.phpguru.org/static/mime.mail.html) class for handling the email. So you can avoid the nasty email internals.
How do I get these strange characters when I try to "echo" the html string?
[ "", "php", "html", "echo", "character", "" ]
I have a problem that I would like have solved via a SQL query. This is going to be used as a PoC (proof of concept). The problem: Product offerings are made up of one or many product instances, a product instance can belong to many product offerings. This can be realised like this in a table: ``` PO | PI ----- A | 10 A | 11 A | 12 B | 10 B | 11 C | 13 ``` Now I would like to get back the product offer from a set of product instances. E.g. if we send in 10,11,13 the expected result back is B & C, and if we send in only 10 then the result should be NULL since no product offering is made up of only 10. Sending in 10,11,12 would result in A (not A & B since 12 is not a valid product offer in it self). Prerequisites: The combination of product instances sent in can only result in one specific combination of product offerings, so there is only one solution to each query.
Okay, I think I have it. This meets the constraints you provided. There might be a way to simplify this further, but it ate my brain a little: ``` select distinct PO from POPI x where PO not in ( select PO from POPI where PI not in (10,11,12) ) and PI not in ( select PI from POPI where PO != x.PO and PO not in ( select PO from POPI where PI not in (10,11,12) ) ); ``` This yields only results who fill the given set which are disjoint with all other results, which I **think** is what you were asking for. For the test examples given: * Providing 10,11,12 yields A * Providing 10,11,13 yields B,C
**Edit:** Whilst I think mine works fine, Adam's answer is without a doubt more elegant and more efficient - I'll just leave mine here for posterity! Apologies since I know this has been tagged as an Oracle issue since I started playing. This is some SQL2008 code which I think works for all the stated cases.... ``` declare @test table ( [PI] int ) insert @test values (10), (11), (13) declare @testCount int select @testCount = COUNT(*) from @test ;with PO_WITH_COUNTS as ( select PO_FULL.PO, COUNT(PO_FULL.[PI]) PI_Count from ProductOffering PO_FULL left join ( select PO_QUALIFYING.PO, PO_QUALIFYING.[PI] from ProductOffering PO_QUALIFYING where PO_QUALIFYING.[PI] in (select [PI] from @test) ) AS QUALIFYING on QUALIFYING.PO = PO_FULL.PO and QUALIFYING.[PI] = PO_FULL.[PI] group by PO_FULL.PO having COUNT(PO_FULL.[PI]) = COUNT(QUALIFYING.[PI]) ) select PO_OUTER.PO from PO_WITH_COUNTS PO_OUTER cross join PO_WITH_COUNTS PO_INNER where PO_OUTER.PI_Count = @testCount or PO_OUTER.PO <> PO_INNER.PO group by PO_OUTER.PO, PO_OUTER.PI_Count having PO_OUTER.PI_Count = @testCount or PO_OUTER.PI_Count + SUM(PO_INNER.PI_Count) = @testCount ``` Not sure if Oracle has CTEs but could just state the inner query as two derived tables. The cross join in the outer query lets us find combinations of offerings that have all the valid items. I know that this will only work based on the statement in the question that the data is such that there is only 1 valid combination for each requested set, Without that it's even more complicated as counts are not enough to remove combinations that have duplicate products in them.
Recursive sql problem
[ "", "sql", "" ]
Let's say we have ``` public interface ITimestampProvider { DateTime GetTimestamp(); } ``` and a class which consumes it ``` public class Timestamped { private ITimestampProvider _timestampProvider public Timestamped(ITimestampProvider timestampProvider) { // arg null check _timestampProvider = timestampProvider; } public DateTime Timestamp { get; private set; } public void Stamp() { this.Timestamp = _timestampProvider.GetTimestamp(); } } ``` and a default implementation of: ``` public sealed class SystemTimestampProvider : ITimestampProvider { public DateTime GetTimestamp() { return DateTime.Now; } } ``` Is it helpful or harfmful to introduce this constructor? ``` public Timestamped() : this(new SystemTimestampProvider()) {} ``` This is a general question, i.e. timestamping is not the interesting part.
I think it depends on the scenario, and is basically a function of who the consumer the code is (library vs. application) and whether you're using an IoC container or not. * If you're using an IoC container, and this is not part of a public API, then let the container do the heavy lifting, and just have the single constructor. Adding the no-args constructor just makes things confusing, since you'll never use it. * If this is part of a public API, then keep both. If you're using IoC, just make sure your IoC finds the "greediest" constructor (the one with the most arguments). Folks not using IoC, but using your API will appreciate not having to construct an entire dependency graph in order to use your object. * If you're not using an IoC container, but just want to to unit test with a mock, keep the no-args constructor, and make the greedy constructor internal. Add InternalsVisibleTo for your unit test assembly so that it can use the greedy constructor. If you're just unit testing, then you don't need the extra public API surface.
i wouldn't provide that constructor. Doing so makes it far too easy to call new TimeStamped and get an instance with new SystemTimestampProvider() when your IoC may be configured to use OtherTimestampProvider(). End of the day you'll end up with one hell of a time trying to debug why you're getting the wrong timestamp. If you only provide the first constructor you can do a simple find usages of SystemTimestampProvider to find out who is (wrongly) using that provider instead of the IoC configured Provider.
Constructor injection and default overloads
[ "", "c#", ".net", "dependency-injection", "" ]
Button class: ``` class SubmitButton extends JButton implements ActionListener { public SubmitButton(String title){ super(title); .... ``` Where I declare it: ``` SubmitButton submit = new SubmitButton("Submit"); submit.setBounds(530+150, 200, 100, 25); ``` **How does super(title) set the String title to the title of the button? How does it do the same as the method .setText() for regular JButtons?** In other words, how did calling super() do the same thing as .setText() how does super() know to change title? is .setText() the only method in JButton Class that takes in string as parameter?
* SubmitButton extends JButton * JButton has a constructor which might look like this (simplified): ``` public JButton(String title) { setText(title); } ``` * SubmitBUtton has a constructor: ``` public SubmitButton(String title) { super(title); } ``` The SubmitButton constructor is calling the superclass (JButton) constructor, which is in turn calling setText. Now internally, JButton might work differently, but the effect is the same. **The overall point is that super(...) calls the superclass constructor.**
JButton is a central Java Swing class that supports multiple constructors. One of these constructors allows you to set the text for the button label. Adding super(title) didn't actually make a call - the constructor of the parent would have been called anyway, but it helped select which constructor is invoked. The setText() operation allows you to change text after button is created but (usually) before it is displayed.
super() function in JAVA
[ "", "java", "super", "" ]
If I have a form-backing object that has a complicated object tree -- say a Person that has a Contact Info object that has an Address object that has a bunch of Strings -- it seems that the object needs to be fully populated with component objects before I can bind to it. So if I'm creating a new Person, I need to make sure it has all the component objects populated off the bat, and if I'm retrieving a Person from the database, I need to make sure that any objects that aren't populated from the database get populated with empty objects. First question, of course -- am I correct in my assumptions above? It does seem that if I try to bind to person.contactInfo.homeAddress.street and there is no ContactInfo, I get a null pointer exception. Second, what's the best way to initialize my object. I can think of a couple of approaches. One is to initialize all member objects at declaration: ``` public class Person { String name; ContactInfo contactInfo = new ContactInfo(); //getters, setters, etc. } public class ContactInfo { String phone; Address homeAddress = new Address(); } ``` and so forth. Another approach is to have a PersonFactory that initializes everything (or to have a factory method Person.getInstance that initializes everything). In the case of retrieving a Person from the database, the first approach will solve the issue (i.e. if this particular person doesn't have an address in the database, the object will still have an Address), but this will mean creating each object twice. Not sure how to handle this otherwise, except to make the DAO explicitly populate everything even if nothing has been retrieved from the database. Or to give the factory a method to go through the object and "fill in" anything that's missing. Suggestions?
Call it overkill if you like, but what we actually ended up doing was to create a generic factory that will take any object and use reflection to (recursively) find all the null properties and instantiate an object of the correct type. I did this using Apache Commons BeanUtils. This way you can take an object that you may have gotten from various sources (a DAO, deserialization from XML, whatever), pass it through this factory, and use it as a form-backing object without worrying that something you need for binding may be null. Admittedly, this means instantiating properties that we may not need for a given form, but in our case that doesn't typically apply.
I would generally make sure objects are fully initialized - it makes using the object that much simplier and avoids you scattering null checks throughout your code. In the case you give here I'd probably put the initialization in the getter so the child object is only instantiated when it's actually going to be used, ie: when the getter is called and then only if it's null. In terms of loading from the database with one-to-one relationships I'd normally do the join and load the lot. The performance impact is typically minimal but you should be aware that there may be one. When it comes to one-to-many relationships I normally go for lazy loading. Hibernate will take of this for you, but if you're rolling your own then you just need a custom implementation of List that calls the appropriate DAO when any of the methods relating to its contents are called. The one exception to this behavior with one-to-many relationships is when you've got a list of parent objects that you intend to iterate over and for each parent you want to iterate over its children. Obviously the performance would suck because you'd be making a n + 1 calls to the DB when you could actually do it with 2 calls.
Best Practice for Spring MVC form-backing object tree initialization
[ "", "java", "spring", "spring-mvc", "" ]
From what I gather, Google Chrome can run browser plugins written using [NPAPI](http://en.wikipedia.org/wiki/NPAPI). I've written one that does its job just fine in Firefox, but makes Chrome crash and burn as soon as you embed it on a page. I don't even have to call any of my methods, embedding is enough to cause a crash. How do I debug this? I tried attaching the debugger to chrome but the stack traces I get are deep down in Chrome itself and like I said, none of "my" actual code is being run, but supposedly just the NPAPI init code. I'd appreciate some pointers.
As it turns out, part of the initialization code from the old NPAPI plugin example I was using caused the crash. I'm sorry to say I solved this quite a while back and can't seem to locate the specific modifications I made to fix it in the version control history. Anyway, my problem is fixed and was caused by me being stupid and blindly trusting the example code.
The Chromium dev docs describe some tricks for attaching Visual Studio to Chrome processes: [Chromium Developer Documentation > Debugging Chromium](http://dev.chromium.org/developers/how-tos/debugging). Some problems you might be facing with an NPAPI plugin in Chrome: * Your plugin will be running in a separate process from the Chrome UI. (You probably know this already :) * If multiple instances of your plugin are loaded (in the same HTML page or in different Chrome tabs), your plugin instances *will* be running in the same process together. If you have global variables, your plugin instances might be stomping on each other. * Chrome uses DEP (Data Execution Protection), but Firefox does not. If you are using ATL or other JITted code tricks, DEP can crash your plugin.
Firefox plugin crashes in Chrome
[ "", "c++", "google-chrome", "npapi", "" ]
In the unmanaged development world, you could observe the DWORD return value of a method by typing '@eax' into the watch window of the debugger. Does anyone know of an equivalent shortcut in managed code? Related point: I have learned that VS2008 SP1 supports **$exception** as a magic word in the watch window. Are there any other shortcuts that you know of?
The watch window tricks like @eax are called [Psuedovariables]. They are actually [documented.](http://msdn.microsoft.com/en-us/library/ms164891(VS.80).aspx) I wrote a [blog post](http://blogs.msdn.com/stevejs/archive/2005/10/18/482300.aspx#comments) about this and some other VS debugging items a few years ago. Format specifiers are typically highly useful. For your specific question there is no psuedo variable for eax in managed code. There is however a register window which will actually have EAX and the other registers in it. It is questionable that this will be useful in many situations as I don't believe there is any way to cast the address to a managed type. You can however look at the layout in the memory window
I'm not sure if this is quite what you mean, but there are some other keywords that you can have printed out for tracepoints: ``` $ADDRESS address of current instruction $CALLER name of the previous function on the call stack $CALLSTACK entire call stack $FUNCTION name of the current function $PID process ID for current process $PNAME name of the current process $TID thread ID for current thread $TNAME name of the current thread ```
Do you know a managed equivalent to '@eax'?
[ "", "c#", "visual-studio-2008", "debugging", "" ]
I want to write a program in C/C++ that will dynamically read a web page and extract information from it. As an example imagine if you wanted to write an application to follow and log an ebay auction. Is there an easy way to grab the web page? A library which provides this functionality? And is there an easy way to parse the page to get the specific data?
Have a look at the [cURL library](http://curl.haxx.se/libcurl/c/example.html): ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); } return 0; } ``` BTW, if C++ is not strictly required. I encourage you to try C# or Java. It is much easier and there is a built-in way.
Windows code: ``` #include <winsock2.h> #include <windows.h> #include <iostream> #pragma comment(lib,"ws2_32.lib") using namespace std; int main (){ WSADATA wsaData; if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { cout << "WSAStartup failed.\n"; system("pause"); return 1; } SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); struct hostent *host; host = gethostbyname("www.google.com"); SOCKADDR_IN SockAddr; SockAddr.sin_port=htons(80); SockAddr.sin_family=AF_INET; SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr); cout << "Connecting...\n"; if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){ cout << "Could not connect"; system("pause"); return 1; } cout << "Connected.\n"; send(Socket,"GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"),0); char buffer[10000]; int nDataLength; while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){ int i = 0; while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') { cout << buffer[i]; i += 1; } } closesocket(Socket); WSACleanup(); system("pause"); return 0; } ```
Programmatically reading a web page
[ "", "c++", "c", "http", "" ]
I am tasked with developing a web application and am thinking of using the Struts framework as it seems to be a standard and is easy to implement. However, before making a decision I need to know the security features available in Struts. Are there effective ways to handle the [OWASP Top 10](http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project) using Struts? And if so, how would I accomplish it?
Struts is there to offer you an MVC framework, and it has limited security features, e.g. you can map roles to actions. I will recommend you to look into something more full-fledged like the [Spring Security](http://static.springframework.org/spring-security/site/) (formerly Acegi).
The best way to handle the OWASP Top ten in struts is to look at the OWASP Enterprise Security API...
What security features are available in Struts?
[ "", "java", "security", "struts", "owasp", "" ]
is there any support in Mac OS X for signing data using smartcards? I have looked through the system headers and found only vauge references to smart card support (in SecKeychain.h), which didn't really take me anywhere. If there's no built-in support, which are my options (ie. what free/non-free libraries exist that can help me)?
I'm answering my own question here, for reference. The [OpenSC](http://www.opensc-project.org/) libraries provides everything you need to deal with smartcards, and it is cross-platform (Windows, Linux and Mac), and its license is good for commercial projects.
The [Apple-CDSA mailing list](http://lists.apple.com/mailman/listinfo/apple-cdsa "Apple-CDSA mailing list") is probably the best place to ask this; CDSA stands for Common Data Security Architecture, which includes all of the security/keychain/signing infrastructure on Mac OS X, including any support for smart-card security. Plenty of people who use and work on CDSA will be there. It will probably also be worth checking the archives; someone may have already done what you're trying to do.
Signing data with smartcards on Mac in C++
[ "", "c++", "macos", "cryptography", "smartcard", "" ]
Here's some code I saw once. Can you see what's wrong with it? [updated] ``` public class ResourceManager1 { private final String mutex = ""; Object resource = null; public Object getResource() { synchronized (mutex) { if (resource == null) { resource = new Object(); } } return resource; } } public class ResourceManager2 { private final String mutex = ""; Object resource = null; public Object getResource() { synchronized (mutex) { if (resource == null) { resource = new Object(); } } return resource; } } ```
Never synchronize on strings, particularly string literals which are interned. You've basically just got a single lock. In general, never synchronize on any reference that might be visible outside your class (including "this") *unless* the purpose of the external visibility is precisely for locking purposes. I usually use a `private final` variable created solely for the purpose of locking.
You are using the same String as a mutex for both classes and hence only one of the synchronized blocks can be used at a time, which does not seem to be the intention of the code.
Java synchronisation poll
[ "", "java", "synchronization", "" ]
everybody; I have this problem in asp.net, I have a page where I insert and modify data, before saving I make a validation if it passes I save the data but if not I raise an exception and show it, the function goes like this; ``` protected void btnSave_Click(object sender, EventArgs e) { try { ... if(ValidData()) //Save ... else throw new Exception("Invalid data"); } catch(Exception ex) { // Javascript alert JSLiteral.Text = Utilities.JSAlert(ex.Message); } } ``` The problem is that after I raise the exception and fix the data in the page I click again the save button and it saves but before it shows me again the exception message and its annoying. Even when the data is saved I click again and it shows the message from the exception again. Do you know the answer for this issue?
If JSLiteral is a server side control and it's using view state. Then you'd need to clear the state of the control, when the save is succesful. You could disable the viewstate for the control like JSLiteral.EnableViewState =false;
Are you resetting the value of JSLiteral to empty after you save?
Annoying exception in asp.net
[ "", "c#", "asp.net", "" ]
With wxWidgets I use the following code: ``` HWND main_window = ... ... wxWindow *w = new wxWindow(); wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window); ``` How do I do the same thing in Qt? The `HWND` is the handle of the window I want as the parent window for the new QtWidget.
Use the create method of QWidget. ``` HWND main_window = ... ... QWidget *w = new QWidget(); w->create((WinId)main_window); ```
Have you tried the [`QWinWidget`](http://doc.qt.digia.com/solutions/qtwinmigrate/qwinwidget.html) class from the [Qt/MFC Migration Framework](http://doc.qt.digia.com/solutions/qtwinmigrate/)?
How to create a QWidget with a HWND as parent?
[ "", "c++", "windows", "qt", "wxwidgets", "" ]
I need a 'good' way to initialize the pseudo-random number generator in C++. I've found [an article](http://www.cplusplus.com/reference/clibrary/cstdlib/srand.html) that states: > In order to generate random-like > numbers, srand is usually initialized > to some distinctive value, like those > related with the execution time. For > example, the value returned by the > function time (declared in header > ctime) is different each second, which > is distinctive enough for most > randoming needs. Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts. I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from `/dev/urandom`. Thanks! **EDIT** Yes, I am actually starting my application multiple times a second and I've run into collisions.
The best answer is to use [`<random>`](http://en.cppreference.com/w/cpp/header/random). If you are using a pre C++11 version, you can look at the Boost random number stuff. But if we are talking about `rand()` and `srand()` The best simplest way is just to use `time()`: ``` int main() { srand(time(nullptr)); ... } ``` Be sure to do this at the beginning of your program, and not every time you call `rand()`! --- Side Note: ***NOTE***: There is a discussion in the comments below about this being insecure (which is true, but ultimately not relevant (read on)). So an alternative is to seed from the random device `/dev/random` (or some other secure real(er) random number generator). ***BUT***: Don't let this lull you into a false sense of security. This is `rand()` we are using. Even if you seed it with a brilliantly generated seed it is still predictable (if you have any value you can predict the full sequence of next values). This is only useful for generating `"pseudo"` random values. If you want "secure" you should probably be using `<random>` (Though I would do some more reading on a security informed site). See the answer below as a starting point: <https://stackoverflow.com/a/29190957/14065> for a better answer. Secondary note: Using the random device actually solves the issues with starting multiple copies per second better than my original suggestion below (just not the security issue). --- Back to the original story: Every time you start up, time() will return a unique value (unless you start the application multiple times a second). In 32 bit systems, it will only repeat every 60 years or so. I know you don't think time is unique enough but I find that hard to believe. But I have been known to be wrong. If you are starting a lot of copies of your application simultaneously you could use a timer with a finer resolution. But then you run the risk of a shorter time period before the value repeats. OK, so if you really think you are starting multiple applications a second. Then use a finer grain on the timer. ``` int main() { struct timeval time; gettimeofday(&time,NULL); // microsecond has 1 000 000 // Assuming you did not need quite that accuracy // Also do not assume the system clock has that accuracy. srand((time.tv_sec * 1000) + (time.tv_usec / 1000)); // The trouble here is that the seed will repeat every // 24 days or so. // If you use 100 (rather than 1000) the seed repeats every 248 days. // Do not make the MISTAKE of using just the tv_usec // This will mean your seed repeats every second. } ```
This is what I've used for small command line programs that can be run frequently (multiple times a second): ``` unsigned long seed = mix(clock(), time(NULL), getpid()); ``` Where mix is: ``` // Robert Jenkins' 96 bit Mix Function unsigned long mix(unsigned long a, unsigned long b, unsigned long c) { a=a-b; a=a-c; a=a^(c >> 13); b=b-c; b=b-a; b=b^(a << 8); c=c-a; c=c-b; c=c^(b >> 13); a=a-b; a=a-c; a=a^(c >> 12); b=b-c; b=b-a; b=b^(a << 16); c=c-a; c=c-b; c=c^(b >> 5); a=a-b; a=a-c; a=a^(c >> 3); b=b-c; b=b-a; b=b^(a << 10); c=c-a; c=c-b; c=c^(b >> 15); return c; } ```
Recommended way to initialize srand?
[ "", "c++", "random", "srand", "" ]
Say I wanted to have a project, and one-to-many with to-do items, and wanted to re-order the to-do items arbitrarily? In the past, I've added a numbered order field, and when someone wants to change the order, had to update all the items with their new order numbers. This is probably the worst approach, since it's not atomic & required several updates. I notice Django has a multi-valued CommaSeparatedIntegerField which could contain the order by storing the ordered keys to the items in the to-do items table right in one field of the project table. I've pondered a dewey decimal system where if I wanted to take item 3 and put it between 1 and 2 I would change it's order number to 1.5. Something tells me there's an easier option that I'm missing though... How would you give order to a one-to-many relationship?
I hate this problem ... and I run into it all the time. For my most recent Django site we had a Newsletter which contained N Articles and, of course, order was important. I assigned the default order as ascending Article.id, but this failed if Articles were entered in something other than "correct" order. On the Newsletter change\_form.html page I added a little bit of jQuery magic using the Interface plugin (<http://interface.eyecon.ro/>). I show the titles of the associated Articles and the user can drag them around as they like. There is an onChange handler that recomputes the Article.id's in article\_order field. Enjoy, Peter For app=content, model=Newsletter, the following is in templates/admin/content/newslettter/change\_form.html ``` {% extends 'admin/change_form.html' %} {% block form_top %}{% endblock %} {% block extrahead %}{{ block.super }} <script type="text/javascript" src="/media/js/jquery.js"></script> <script type="text/javascript" src="/media/js/interface.js"></script> <script> $(document).ready( function () { $('ol.articles').Sortable( { accept : 'sortableitem', helperclass : 'sorthelper', activeclass : 'sortableactive', hoverclass : 'sortablehover', opacity: 0.8, fx: 200, axis: 'vertically', opacity: 0.4, revert: true, trim: 'art_', onchange: function(list){ var arts = list[0].o[list[0].id]; var vals = new Array(); var a; for (a in arts) { vals[a] = arts[a].replace(/article./, ''); } $('#id_article_order').attr('value', vals.join(',')); } }); } ); </script> {% endblock %} {% block after_related_objects %} {% if original.articles %} <style> .sortableitem { cursor:move; width: 300px; list-style-type: none; } </style> <h4>Associated Articles</h4> <ol class="articles" id="article_list"> {% for art in original.articles %} <li id="article.{{art.id}}" class="sortableitem">{{art.title}}</li> {% endfor %} </ol> {% endif %} {% endblock %} ```
"added a numbered order field" - good. "update all the items with their new order numbers" - avoidable. Use numbers with gaps. * Floating point. That way, someone can insert "1.1" between 1 and 2. I find that this works nicely, as most people can understand how the sequencing works. And you don't have to worry too much about how much space to leave -- there's lots and lots of space between each number. * On the initial load, number the articles by the 100 or 1000 or something with space between each one. In this case, you have to guess how many digits to leave for reordering. * A comma-separated position. Initially, they're all (1,0), (2,0), (3,0), etc. But when you want to rearrange things, you might have to introduce (2,1) and (2,2) that go after (2,0) but before (3.0). This looks kind of complicated, but some people like this kind of complexity. It's essentially the same as floating-point, except the single number is replace by a (whole-number, implicit-fraction) tuple. And this extends to handle hierarchies.
in SQL, or Django ORM, what's the conventional way to have an ordered one-to-many?
[ "", "sql", "django", "" ]
Is there a particular scenario where a `WriteOnly` property makes more sense then a method? The method approach feels much more natural to me. What is the right approach? **Using Properties**: ``` Public WriteOnly Property MyProperty As String Set(ByVal value as String) m_myField = value End Set End Property ``` ``` public string MyProperty { set{ m_myField = value;} } ``` **Using Methods**: ``` Public Sub SetMyProperty(ByVal value as String) m_myField = value End Sub ``` ``` public void SetMyProperty(string value) { m_myField = value; } ``` **EDIT** Just to clarify I am referring to "WriteOnly" properties.
I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them. As an example, setting a list of values in a drop-down on a view and accessing the selected item: ``` public interface IWidgetSelector { void SetAvailableWidgets(string[] widgets); string SelectedWidget { get; set; } } ``` Makes more sense than: ``` public interface IWidgetSelector { string[] AvailableWidgets { set; } string SelectedWidget { get; set; } } ```
For what it's worth, the Microsoft Framework Design Guidelines (as embodied in their FxCop tool) discourage Write-Only Properties and flag their presence as an API design issue, due to the unintuitiveness of that approach.
WriteOnly Property or Method?
[ "", "c#", ".net", "vb.net", "coding-style", "" ]
When selecting a block of text (possibly spanning across many DOM nodes), is it possible to extract the selected text and nodes using Javascript? Imagine this HTML code: ``` <h1>Hello World</h1><p>Hi <b>there!</b></p> ``` If the user initiated a mouseDown event starting at "World..." and then a mouseUp even right after "there!", I'm hoping it would return: ``` Text : { selectedText: "WorldHi there!" }, Nodes: [ { node: "h1", offset: 6, length: 5 }, { node: "p", offset: 0, length: 16 }, { node: "p > b", offset: 0, length: 6 } ] ``` I've tried putting the HTML into a textarea but that will only get me the selectedText. I haven't tried the `<canvas>` element but that may be another option. If not JavaScript, is there a way this is possible using a Firefox extension?
You are in for a bumpy ride, but this is quite possible. The main problem is that IE and W3C expose completely different interfaces to selections so if you want cross browser functionality then you basically have to write the whole thing twice. Also, some basic functionality is missing from both interfaces. Mozilla developer connection has the story on [W3C selections](https://developer.mozilla.org/en/DOM/window.getSelection). Microsoft have their system [documented on MSDN](http://msdn.microsoft.com/en-us/library/ms535869(VS.85).aspx). I recommend starting at PPK's [introduction to ranges](http://www.quirksmode.org/dom/range_intro.html). Here are some basic functions that I believe work: ``` // selection objects will differ between browsers function getSelection () { return ( msie ) ? document.selection : ( window.getSelection || document.getSelection )(); } // range objects will differ between browsers function getRange () { return ( msie ) ? getSelection().createRange() : getSelection().getRangeAt( 0 ) } // abstract getting a parent container from a range function parentContainer ( range ) { return ( msie ) ? range.parentElement() : range.commonAncestorContainer; } ```
My [Rangy](http://code.google.com/p/rangy) library will get your part of the way there by unifying the different APIs in IE < 9 and all other major browsers, and by providing a `getNodes()` function on its Range objects: ``` function getSelectedNodes() { var selectedNodes = []; var sel = rangy.getSelection(); for (var i = 0; i < sel.rangeCount; ++i) { selectedNodes = selectedNodes.concat( sel.getRangeAt(i).getNodes() ); } return selectedNodes; } ``` Getting the selected text is pretty easy in all browsers. In Rangy it's just ``` var selectedText = rangy.getSelection().toString(); ``` Without Rangy: ``` function getSelectedText() { var sel, text = ""; if (window.getSelection) { text = "" + window.getSelection(); } else if ( (sel = document.selection) && sel.type == "Text") { text = sel.createRange().text; } return text; } ``` As for the character offsets, you can do something like this for any node `node` in the selection. Note this does not necessarily represent the visible text in the document because it takes no account of collapsed spaces, text hidden via CSS, text positioned outside the normal document flow via CSS, line breaks implied by `<br>` and block elements, plus other subtleties. ``` var sel = rangy.getSelection(); var selRange = sel.getRangeAt(0); var rangePrecedingNode = rangy.createRange(); rangePrecedingNode.setStart(selRange.startContainer, selRange.startOffset); rangePrecedingNode.setEndBefore(node); var startIndex = rangePrecedingNode.toString().length; rangePrecedingNode.setEndAfter(node); var endIndex = rangePrecedingNode.toString().length; alert(startIndex + ", " + endIndex); ```
Get selected text and selected nodes on a page?
[ "", "javascript", "firefox", "xhtml", "firefox-addon", "selection", "" ]
I have a website where all requests are redirected silently (via `.htaccess`) to `index.php` and then PHP is used to show the correct page (by parsing the `REQUEST_URI`). I was wondering if it's possible to submit POST data to a fake address too? I've currently got my form like so... ``` <form action="/send-mail" method="post"> ``` And my `.htaccess` rule is... ``` # redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,L] ``` My `index.php` checks `isset($_GET['send-mail'])` which works fine. This however seems to drop off all the POST data that should be sent to it. Is there a way to keep the post data? I don't want to use GET because it can't send as much information, though it might not be an issue with a simple inquiry form. Here is my `.htaccess` for redirecting to `index.php` ``` # serve files and dirs if they exist please, otherwise send to index RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php ```
Try this: ``` # redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,P] ``` "P" acts like "L" in that it stops processing rules but it also tells the module that the request should be passed off to the proxy module intact (meaning POST data is preserved).
You should be able to simply redirect to `index.php`, and then in that script, access `$_SERVER['REQUEST_URI']` to see the original request, with "send-mail" intact. By the way, "can't send as much information" is not the reason to use POST. The reason to use POST is that the request will modify data on your site, instead of simply retrieving data. Suppose you put a hyperlink on your page with a GET request like "`/delete_user?id=1234`," and then some search engine innocently follows the link as it's indexing your site. That's why GET requests are not good for requests that modify data.
Is it possible to redirect post data?
[ "", "php", "apache", ".htaccess", "" ]
I have a TreeView control showing multiple TreeNodes in an organised heirarchy. I want to stop the user selecting the highest level Nodes (this was achieved by using the BeforeSelect Event). I also want to stop the TreeView from highlighting the top level nodes if the user selects them i.e. stop the TreeView from changing the background color of the node and 'selecting' it. The TreeView that I am using is the WinForms version of the control. Below is the source code I am currently attempting to use: ``` private void tree_BeforeSelect ( object sender, TreeViewCancelEventArgs e ) { if ( e.Node.Level == 0 ) { e.Cancel = true; } } ``` This does de-select the Node but only after a noticible flash (~200ms) which is undesirable.
In addition to your existing code if you add a handler to the MouseDown event on the TreeView with the code and select the node out using it's location, you can then set the nodes colours. ``` private void treeView1_MouseDown(object sender, MouseEventArgs e) { TreeNode tn = treeView1.GetNodeAt(e.Location); tn.BackColor = System.Drawing.Color.White; tn.ForeColor = System.Drawing.Color.Black; } ``` There is still a slight problem in that the select outline still shows on MouseDown but it atleast stops the blue background and gets you a little further. HTH OneSHOT
This code prevents drawing the selection before it is canceled: ``` private void treeView1_MouseDown(object sender, MouseEventArgs e) { treeView1.BeginUpdate(); } private void treeView1_MouseUp(object sender, MouseEventArgs e) { treeView1.EndUpdate(); } ```
C# Stop a Treeview selecting one or more TreeNodes
[ "", "c#", "winforms", "treeview", "treenode", "" ]
I have a basic HTML form that gets inserted into a server side *div* tag based on how many records exist in the database. This HTML form comes out just fine, and everything looks good. But on my action page I cannot seem to access the input elements from the code behind. I have tried using the *Request* scope, but I have come up empty on that approach. Any other suggestions? All of the below suggestions are great, and normally that is what I would do. But these forms are being built on the fly after the page is being compiled, so `runat='server'` did not do anything for me. It just passed that along to the HTML page.
If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via JavaScript post). This usually means that your form definition will look like this (I'm going off of memory - make sure you check the HTML elements are correct): ``` <form method="POST" action="page.aspx"> <input id="customerName" name="customerName" type="Text" /> <input id="customerPhone" name="customerPhone" type="Text" /> <input value="Save" type="Submit" /> </form> ``` You should be able to access the customerName and customerPhone data like this: ``` string n = String.Format("{0}", Request.Form["customerName"]); ``` If you have `method="GET"` in the form (not recommended - it messes up your URL space), you will have to access the form data like this: ``` string n = String.Format("{0}", Request.QueryString["customerName"]); ``` This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback' (i.e., somebody clicked the 'Save' button, or this was done programmatically via JavaScript). Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e., `runat="server"`). With server controls, the id and name are different.
What I'm guessing is that you need to set those input elements to **runat="server"**. So you won't be able to access the control ``` <input type="text" name="email" id="myTextBox" /> ``` But you'll be able to work with ``` <input type="text" name="email" id="myTextBox" runat="server" /> ``` And read from it by using ``` string myStringFromTheInput = myTextBox.Value; ```
How to access HTML form input from ASP.NET code behind
[ "", "c#", "asp.net", "html", "forms", "" ]
In the past, I have used XSD.exe to create c# classes from an xsd. Today, I added an XSD to VS.NET 2008 SP1 and it automatically generated a dataset from my xsd, slick but I don't want a dataset. Is there a way to have vs.net automatically execute xsd.exe each time I modify my xsd.
I believe your best bet would be to run xsd.exe as a pre-build event, and setting the build action for your XSD to "None".
Select the \*.xsd file, open Properties Window (F4 key) and delete "Custom Tool" and "Custom Tool Namespace". This will remove the "DataSet" issue. The "c# class from an xsd" issue can be solved by another custom tool. Look at [XsdCondeGenTool](http://weblogs.asp.net/cazzu/archive/2004/05/14/XsdCodeGenTool.aspx) - there is sample, how to do it.
Have vs.net automatically execute xsd.exe everytime time xsd is modified
[ "", "c#", "xsd", "xsd.exe", "" ]
After reading some threads on misuses of exceptions (basically saying you don't want to unwind the stack if a functions preconditions are incorrect - possibly signalling that all your memory is corrupt or something equally dangerous) I'm thinking about using assert() more often. Previously I have only used assert() as a debug tool and I think this is how a lot of C++ programmers use it. I'm concerned about part of my error handling being turned off by a NDEBUG #define introduced to the runtime builds at some point in the future. Is there a way round this and have others had a problem with this (i.e. should I be worrying about it)? Thanks, Pat Edit: The point of the threads I was reading was that if your application is truely buggered then unwinding stack could damage the system, for instance if a destructor wrote something to a file and the file handle was corrupted. I'm not suggesting using assert for normal error handling. The current use case I have is pretty weak but see what you think: ``` //check later code won't crash the system if( buf.length() % 2 ) return false; // do other stuff that shouldn't affect bufs length //copy 2 bytes into buf at a time, if length is odd then don't know //what will happen so use assert to make sure it can't damage anything assert( !(buf.length() % 2) ); for( i = 0; i != buf.length(); i += 2 ) memcpy( buf + i, data, 2 ); ``` edit2: the discussion is here: <http://groups.google.com/group/comp.lang.c++.moderated/browse_frm/thread/80083ac31a1188da>
You could build your own assert instead of using the stock C assert.h. Your assert won't be disabled. Look at how assert() is implemented in /usr/include/assert.h (or wherever). It's simply some preprocessor magic eventually calling an "assert fail" function. In our embedded environments, we replace assert() all the time.
I like to define my own assertion macros. I make two -- ASSERT tests always (even for optimized builds) and DASSERT only has an effect for debug builds. You probably want to default to ASSERT, but if something is expensive to test, or assertions inside inner loops of performance-sensitive areas can be changed to DASSERT. Also, remember, that assertions should only be used for totally nonsensical conditions that indicate a logical error in your program and from which you can't recover. It's a test of your programming correctness. Assertions should NEVER be used in place of error handling, exceptions, or robustness, and you should never assert anything related to malformed or incorrect user input -- such things should be handled gracefully. An assertion is just a controlled crash where you have the opportunity to output some extra debugging info. Here are my macros: ``` /// ASSERT(condition) checks if the condition is met, and if not, calls /// ABORT with an error message indicating the module and line where /// the error occurred. #ifndef ASSERT #define ASSERT(x) \ if (!(x)) { \ char buf[2048]; \ snprintf (buf, 2048, "Assertion failed in \"%s\", line %d\n" \ "\tProbable bug in software.\n", \ __FILE__, __LINE__); \ ABORT (buf); \ } \ else // This 'else' exists to catch the user's following semicolon #endif /// DASSERT(condition) is just like ASSERT, except that it only is /// functional in DEBUG mode, but does nothing when in a non-DEBUG /// (optimized, shipping) build. #ifdef DEBUG # define DASSERT(x) ASSERT(x) #else # define DASSERT(x) /* DASSERT does nothing when not debugging */ #endif ```
assert and NDEBUG
[ "", "c++", "error-handling", "" ]
I've been tasked with rewriting the Javascript engine currently powering my customer's internal website. While reviewing the code I've come across this function *flvFPW1* which I do not recognize, nor can I decipher the code(my Javascript knowledge is modest at best). A Google search gives me a few hits, but most if not all page hits are from the Javascript used on that particular page. In other words, I cannot find a description for this function, even though it is obviously used by others. Can someone here enlighten me? Thanks / Fredrik
My own research agrees that it's a dreamweaver extension: I found [code for version 1.44](http://forums.devshed.com/javascript-development-115/apply-onclick-to-all-links-in-template-265457.html) (scroll down some on this page) rather than 1.3: ``` function flvFPW1(){//v1.44 var v1=arguments,v2=v1[2].split(","),v3=(v1.length>3)?v1[3]:false,v4=(v1.length>4)?parseInt(v1[4]):0, v5=(v1.length>5)?parseInt(v1[5]):0,v6,v7=0,v8,v9,v10,v11,v12,v13,v14,v15,v16;v11= new Array("width,left,"+v4,"height,top,"+v5);for (i=0;i<v11.length;i++){v12=v11[i].split(",");l_iTarget=parseInt(v12[2]); if (l_iTarget>1||v1[2].indexOf("%")>-1){v13=eval("screen."+v12[0]); for (v6=0;v6<v2.length;v6++){v10=v2[v6].split("="); if (v10[0]==v12[0]){v14=parseInt(v10[1]);if (v10[1].indexOf("%")>-1){v14=(v14/100)*v13;v2[v6]=v12[0]+"="+v14;}} if (v10[0]==v12[1]){v16=parseInt(v10[1]);v15=v6;}} if (l_iTarget==2){v7=(v13-v14)/2;v15=v2.length;} else if (l_iTarget==3){v7=v13-v14-v16;}v2[v15]=v12[1]+"="+v7;}}v8=v2.join(",");v9=window.open(v1[0],v1[1],v8); if (v3){v9.focus();}document.MM_returnValue=false;return v9;} ``` Which was, of course, passed through a compressor to save bandwidth making it very hard to read. I spent a little bit of time un-obfuscating it before I realized that I could get better results by adding "dreamweaver" to my search string. Doing that I was able to find some more interesting documentation: <http://www.flevooware.nl/dreamweaver/extdetails.asp?extID=8> (short description) <http://satsuki.altervista.org/basibloggers/source40.txt> (full script code, in italian) In short: it's basically just a wrapper for `window.open`. Here's the progress I made translating the code: ``` function flvFPW1() {//v1.44 var v1=arguments; // pass v1[0] and v1[1] directly to window.open var arg3=v1[2].split(","); var focusNewWindow=(v1.length>3)?v1[3]:false; var newWindowWidth=(v1.length>4)?parseInt(v1[4]):0; var newWindowHeight=(v1.length>5)?parseInt(v1[5]):0; var adjustedWindowPosition=0,result,keyValuePair,AxisProperty; var windowSize,sizeValue,arg3Index,anchorValue; var hwArray= new Array("width,left,"+newWindowWidth,"height,top,"+newWindowHeight); for (i=0;i<hwArray.length;i++) // x-axis, then y-axis { AxisProperty=hwArray[i].split(","); // {"width", "left", 0} or {"height", "top", 0} l_iTarget=parseInt(AxisProperty[2]); // l_iTarget defined where? if (l_iTarget>1||v1[2].indexOf("%")>-1) { screenSize=eval("screen."+AxisProperty[0]); // x or y size of the window for (var i=0;i<arg3.length;i++) { keyValuePair=arg3[i].split("="); if (keyValuePair[0]==AxisProperty[0]) // if the key is (width|height) { sizeValue=parseInt(keyValuePair[1]); if (keyValuePair[1].indexOf("%")>-1) { sizeValue=(sizeValue/100)* screenSize; arg3[i]=AxisProperty[0]+"="+sizeValue; } } if (keyValuePair[0]==AxisProperty[1]) // if the key is (left|top) { anchorValue=parseInt(keyValuePair[1]); arg3Index=i; } } if (l_iTarget==2) { adjustedWindowPosition=(screenSize-sizeValue)/2; // will center the window on this axix arg3Index=arg3.length; } else if (l_iTarget==3) { adjustedWindowPosition= screenSize-sizeValue-anchorValue; } arg3[arg3Index]=AxisProperty[1]+"="+adjustedWindowPosition; // (left|top) = value } } var newArg3=arg3.join(","); result=window.open(v1[0],v1[1],newArg3); if (focusNewWindow) { result.focus(); } document.MM_returnValue=false; return result; } ```
on your site, type in this in the location bar: ``` javascript:alert(flvFPW1); ``` it will report the function code
flvFPW1() - What does it do?
[ "", "javascript", "" ]
Should I instantiate my worker variables inside or outside my for loop E.g. a) ``` bool b = default(bool); for (int i = 0; i < MyCollection.Length; i++) { b = false; foreach(object myObject in myObjectCollection) { if (object.Property == MyCollection[i].Property) { b = true; break; } } if (b) { DoSomethingWith(MyCollection[i]); } } ``` b) ``` for (int i = 0; i < MyCollection.Length; i++) { bool b = default(bool); foreach(object myObject in myObjectCollection) { if (object.Property == MyCollection[i].Property) { b = true; break; } } if (b) { DoSomethingWith(MyCollection[i]); } } ``` EDIT: Seems universally agreed that there will be no difference where the IL is concerned. But for readability and clarity of scope... inside is better
Previous answer deleted as I'd misread the code. (Using "default(bool)" anywhere is a bit odd, btw.) However, unless the variable is captured by a delegate etc, I'd expect them to *either* compile to IL which is effectively the same (in terms of both behaviour and performance). As ever, write the most *readable* code first. Micro-optimising things like this is asking for trouble. I agree with the others who have suggested that you restrict the scope of variables as much as you can - so if you need it after the loop, you haven't got any choice anyway; otherwise declare it inside. Okay, here's a test program: ``` using System; class Test { static void Main() {} static void DeclareInside() { for (int i=0; i < 10; i++) { bool x = false; for (int j=5; j < 20; j++) { if (i == j) { x = true; break; } if (x) { Console.WriteLine("Yes"); } } } } static void DeclareOutside() { bool x; for (int i=0; i < 10; i++) { x = false; for (int j=5; j < 20; j++) { if (i == j) { x = true; break; } if (x) { Console.WriteLine("Yes"); } } } } } ``` Generated IL (just `csc Test.cs`): ``` .method private hidebysig static void DeclareOutside() cil managed { // Code size 79 (0x4f) .maxstack 2 .locals init (bool V_0, int32 V_1, int32 V_2, bool V_3) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: stloc.1 IL_0003: br.s IL_0045 IL_0005: nop IL_0006: ldc.i4.0 IL_0007: stloc.0 IL_0008: ldc.i4.5 IL_0009: stloc.2 IL_000a: br.s IL_0037 IL_000c: nop IL_000d: ldloc.1 IL_000e: ldloc.2 IL_000f: ceq IL_0011: ldc.i4.0 IL_0012: ceq IL_0014: stloc.3 IL_0015: ldloc.3 IL_0016: brtrue.s IL_001d IL_0018: nop IL_0019: ldc.i4.1 IL_001a: stloc.0 IL_001b: br.s IL_0040 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ceq IL_0021: stloc.3 IL_0022: ldloc.3 IL_0023: brtrue.s IL_0032 IL_0025: nop IL_0026: ldstr "Yes" IL_002b: call void [mscorlib]System.Console::WriteLine(string) IL_0030: nop IL_0031: nop IL_0032: nop IL_0033: ldloc.2 IL_0034: ldc.i4.1 IL_0035: add IL_0036: stloc.2 IL_0037: ldloc.2 IL_0038: ldc.i4.s 20 IL_003a: clt IL_003c: stloc.3 IL_003d: ldloc.3 IL_003e: brtrue.s IL_000c IL_0040: nop IL_0041: ldloc.1 IL_0042: ldc.i4.1 IL_0043: add IL_0044: stloc.1 IL_0045: ldloc.1 IL_0046: ldc.i4.s 10 IL_0048: clt IL_004a: stloc.3 IL_004b: ldloc.3 IL_004c: brtrue.s IL_0005 IL_004e: ret } // end of method Test::DeclareOutside .method private hidebysig static void DeclareInside() cil managed { // Code size 79 (0x4f) .maxstack 2 .locals init (int32 V_0, bool V_1, int32 V_2, bool V_3) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: stloc.0 IL_0003: br.s IL_0045 IL_0005: nop IL_0006: ldc.i4.0 IL_0007: stloc.1 IL_0008: ldc.i4.5 IL_0009: stloc.2 IL_000a: br.s IL_0037 IL_000c: nop IL_000d: ldloc.0 IL_000e: ldloc.2 IL_000f: ceq IL_0011: ldc.i4.0 IL_0012: ceq IL_0014: stloc.3 IL_0015: ldloc.3 IL_0016: brtrue.s IL_001d IL_0018: nop IL_0019: ldc.i4.1 IL_001a: stloc.1 IL_001b: br.s IL_0040 IL_001d: ldloc.1 IL_001e: ldc.i4.0 IL_001f: ceq IL_0021: stloc.3 IL_0022: ldloc.3 IL_0023: brtrue.s IL_0032 IL_0025: nop IL_0026: ldstr "Yes" IL_002b: call void [mscorlib]System.Console::WriteLine(string) IL_0030: nop IL_0031: nop IL_0032: nop IL_0033: ldloc.2 IL_0034: ldc.i4.1 IL_0035: add IL_0036: stloc.2 IL_0037: ldloc.2 IL_0038: ldc.i4.s 20 IL_003a: clt IL_003c: stloc.3 IL_003d: ldloc.3 IL_003e: brtrue.s IL_000c IL_0040: nop IL_0041: ldloc.0 IL_0042: ldc.i4.1 IL_0043: add IL_0044: stloc.0 IL_0045: ldloc.0 IL_0046: ldc.i4.s 10 IL_0048: clt IL_004a: stloc.3 IL_004b: ldloc.3 IL_004c: brtrue.s IL_0005 IL_004e: ret } // end of method Test::DeclareInside ``` The only differences are where the variables are located within the stack.
inside looks cleaner but agree with Jon, the IL will be the same.
Whats The Most Efficient Way To Instantiate Worker Variables
[ "", "c#", "variables", "for-loop", "" ]
When I try this code: ``` a, b, c = (1, 2, 3) def test(): print(a) print(b) print(c) c += 1 test() ``` I get an error from the `print(c)` line that says: ``` UnboundLocalError: local variable 'c' referenced before assignment ``` in newer versions of Python, or ``` UnboundLocalError: 'c' not assigned ``` in some older versions. If I comment out `c += 1`, both `print`s are successful. I don't understand: why does printing `a` and `b` work, if `c` does not? How did `c += 1` cause `print(c)` to fail, even when it comes later in the code? It seems like the assignment `c += 1` creates a **local** variable `c`, which takes precedence over the global `c`. But how can a variable "steal" scope before it exists? Why is `c` apparently local here? --- See also [Using global variables in a function](https://stackoverflow.com/questions/423379/) for questions that are simply about how to reassign a global variable from within a function, and [Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?](https://stackoverflow.com/questions/8447947) for reassigning from an enclosing function (closure). See [Why isn't the 'global' keyword needed to access a global variable?](https://stackoverflow.com/questions/4693120) for cases where OP *expected* an error but *didn't* get one, from simply accessing a global without the `global` keyword. See [How can a name be "unbound" in Python? What code can cause an `UnboundLocalError`?](https://stackoverflow.com/questions/22101836/) for cases where OP *expected* the variable to be local, but has a logical error that prevents assignment in every case.
Python treats variables in functions differently depending on whether you assign values to them from inside or outside the function. If a variable is assigned within a function, it is treated by default as a local variable. Therefore, when you uncomment the line, you are trying to reference the local variable `c` before any value has been assigned to it. If you want the variable `c` to refer to the global `c = 3` assigned before the function, put ``` global c ``` as the first line of the function. As for python 3, there is now ``` nonlocal c ``` that you can use to refer to the nearest enclosing function scope that has a `c` variable.
Python is a little weird in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the `print(a)` and `print(b)` statements, there's nothing by that name in the dictionary, so Python looks up the list and finds them in the global dictionary. Now we get to `c+=1`, which is, of course, equivalent to `c=c+1`. When Python scans that line, it says "aha, there's a variable named c, I'll put it into my local scope dictionary." Then when it goes looking for a value for c for the c on the right hand side of the assignment, it finds its *local variable named c*, which has no value yet, and so throws the error. The statement `global c` mentioned above simply tells the parser that it uses the `c` from the global scope and so doesn't need a new one. The reason it says there's an issue on the line it does is because it is effectively looking for the names before it tries to generate code, and so in some sense doesn't think it's really doing that line yet. I'd argue that is a usability bug, but it's generally a good practice to just learn not to take a compiler's messages *too* seriously. If it's any comfort, I spent probably a day digging and experimenting with this same issue before I found something Guido had written about the dictionaries that Explained Everything. ### Update, see comments: It doesn't scan the code twice, but it does scan the code in two phases, lexing and parsing. Consider how the parse of this line of code works. The lexer reads the source text and breaks it into lexemes, the "smallest components" of the grammar. So when it hits the line ``` c+=1 ``` it breaks it up into something like ``` SYMBOL(c) OPERATOR(+=) DIGIT(1) ``` The parser eventually wants to make this into a parse tree and execute it, but since it's an assignment, before it does, it looks for the name c in the local dictionary, doesn't see it, and inserts it in the dictionary, marking it as uninitialized. In a fully compiled language, it would just go into the symbol table and wait for the parse, but since it WON'T have the luxury of a second pass, the lexer does a little extra work to make life easier later on. Only, then it sees the OPERATOR, sees that the rules say "if you have an operator += the left hand side must have been initialized" and says "whoops!" The point here is that it *hasn't really started the parse of the line yet*. This is all happening sort of preparatory to the actual parse, so the line counter hasn't advanced to the next line. Thus when it signals the error, it still thinks its on the previous line. As I say, you could argue it's a usability bug, but its actually a fairly common thing. Some compilers are more honest about it and say "error on or around line XXX", but this one doesn't.
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
[ "", "python", "scope", "global-variables", "local-variables", "shadowing", "" ]
I'm creating HTML with a loop that has a column for Action. That column is a Hyperlink that when the user clicks calls a JavaScript function and passes the parameters... example: ``` <a href="#" OnClick="DoAction(1,'Jose');" > Click </a> <a href="#" OnClick="DoAction(2,'Juan');" > Click </a> <a href="#" OnClick="DoAction(3,'Pedro');" > Click </a> ... <a href="#" OnClick="DoAction(n,'xxx');" > Click </a> ``` I want that function to call an Ajax jQuery function with the correct parameters. Any help?
Using POST ``` function DoAction( id, name ) { $.ajax({ type: "POST", url: "someurl.php", data: "id=" + id + "&name=" + name, success: function(msg){ alert( "Data Saved: " + msg ); } }); } ``` Using GET ``` function DoAction( id, name ) { $.ajax({ type: "GET", url: "someurl.php", data: "id=" + id + "&name=" + name, success: function(msg){ alert( "Data Saved: " + msg ); } }); } ``` EDIT: A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead. ``` <a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a> <a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a> <a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a> ... <a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a> <script type="text/javascript"> $(function() { $('.ajax-link').click( function() { $.get( $(this).attr('href'), function(msg) { alert( "Data Saved: " + msg ); }); return false; // don't follow the link! }); }); </script> ```
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false like this: ``` function DoAction(id, name) { // your code return false; } ```
Passing parameters to a JQuery function
[ "", "javascript", "jquery", "html", "function", "parameters", "" ]
I am having some issues with using the OrderBy extension method on a LINQ query when it is operating on an enum type. I have created a regular DataContext using visual studio by simply dragging and dropping everything onto the designer. I have then created seperate entity models, which are simply POCO's, and I have used a repository pattern to fetch the data from my database and map them into my own entity models (or rather, I have a repository pattern, that builds up and IQueryable that'll do all this). Everything works just fine, except when I try to apply an OrderBy (outside of the repository) on a property that I have mapped from short/smallint to an enum. Here are the relevant code bits: ``` public class Campaign { public long Id { get; set; } public string Name { get; set; } .... public CampaignStatus Status { get; set; } ... } public enum CampaignStatus : short { Active, Inactive, Todo, Hidden } public class SqlCampaignRepository : ICampaignRepository { ... public IQueryable<Campaign> Campaigns() { DataContext db = new DataContext(); return from c in db.Campaigns select new Campaign { Id = c.Id, Name = c.Name, ... Status = (CampaignStatus)c.Status, ... }; } } ``` And then elsewhere ``` SqlCampaignRepository rep = new SqlCampaignRepository(); var query = rep.Campaigns().OrderBy(c => c.Status); ``` This triggers the following exception: System.ArgumentException was unhandled by user code Message="The argument 'value' was the wrong type. Expected 'IQMedia.Models.CampaignType'. Actual 'System.Int16'." Source="System.Data.Linq" StackTrace: ved System.Data.Linq.SqlClient.SqlOrderExpression.set\_Expression(SqlExpression value) ved System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitSelect(SqlSelect select) ved System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) ved System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitIncludeScope(SqlIncludeScope scope) ... (sorry about the danish in there, ved = by/at). I have tried typecasting the Status to short in the orderBy expression, but that doesn't help it, same if i cast it to the actual enum type as well. Any help fixing this is greatly appreciated!
Can you specify the type `CampaignStatus` directly in your `DataContext` trough the designer? This way the value is automatically mapped to the `enum`.
What is the relationship between the `Campaign` class and `Campaigns`? If `Campaigns` returns the set of `Campaign` object, note you can't normally `select new` a mapped entity. I wonder if it would work any better if you did the OrderBy before the Select? One final trick might be to create a fake composable `[Function]`, using trivial TSQL. For example, `ABS` might be enough. i.e. something like (on the context): ``` [Function(Name="ABS", IsComposable=true)] public int Abs(int value) { // to prove not used by our C# code... throw new NotImplementedException(); } ``` Then try: ``` .OrderBy(x => ctx.Abs(x.Status)) ``` I haven't tested the above, but can give it a go later... it works for some other similar cases, though. Worth a shot...
Linq To SQL OrderBy, issue when using enums
[ "", "c#", "linq-to-sql", "enums", "" ]
I noticed for a while now the following syntax in some of our code: ``` if( NULL == var){ //... } ``` or ``` if( 0 == var){ //... } ``` and similar things. Can someone please explain why did the person who wrote this choose this notation instead of the common `var == 0` way)? Is it a matter of style, or does it somehow affect performance?
It's a mechanism to avoid mistakes like this: ``` if ( var = NULL ) { // ... } ``` If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes: ``` if ( NULL = var ) { // not legal, won't compile // ... } ``` Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing. **Edit:** As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, `gcc -Wall` will give you the following: ``` warning: suggest parentheses around assignment used as truth value ``` You should always enable warnings on your compiler, it is the cheapest way to find errors. Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.
If you mistakenly put ``` if ( var = NULL ) ``` instead of ``` if ( var == NULL ) ``` then there will only be a compiler warning. If you reverse the order: ``` if ( NULL == var ) ``` then there will be a compiler error if you put ``` if ( NULL = var ) ``` Personally, I hate to read code written that way, and I only made that mistake once in my first year of coding. =)
Why put the constant before the variable in a comparison?
[ "", "c++", "c", "syntax", "comparison", "" ]
I'm doing a addin system where the main app loads assemblies Addin1.dll and Addin2.dll on runtime in new AppDomain's. However, in case that Addin1.dll is signed (strong name) with my key and Addin2.dll is not, I want to be able to only load Addin1.dll and reject Addin2.dll. I'm suspecting that it needs to be done by setting some parameters in AppDomainSetup?
Look into the [Assembly.Load](http://msdn.microsoft.com/en-us/library/ms145229.aspx "Assembly.Load Method (AssemblyName, Evidence)") method that takes an Evidence parameter. You can find an example of how to create an evidence from your public key [here](http://msdn.microsoft.com/en-us/library/system.security.policy.evidence.aspx "Evidence Class").
You can implment a DomainManager and base your load/block decision's on whatever you like. I answered a somewhat related question [here.](https://stackoverflow.com/questions/439173/message-pumps-and-appdomains/924653#924653)
How to load only signed assembly to a new AppDomain?
[ "", "c#", "assemblies", "appdomain", "strongname", "signed", "" ]
I am trying to use regular expressions to find a UK postcode within a string. I have got the regular expression working inside RegexBuddy, see below: ``` \b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b ``` I have a bunch of addresses and want to grab the postcode from them, example below: > 123 Some Road Name > Town, City > County > PA23 6NH How would I go about this in Python? I am aware of the `re` module for Python but I am struggling to get it working. Cheers Eef
repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is.. ``` import re s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\ "County\nPA2 6NH\n123 Some Road Name\nTown, City\nCounty\nPA2Q 6NH" #custom print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s) #regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s) ``` the result is ``` ['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] ['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] ``` both the regex's give the same result.
Try ``` import re re.findall("[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}", x) ``` You don't need the \b.
Python, Regular Expression Postcode search
[ "", "python", "regex", "postal-code", "" ]
I’m working on an in-house app that tracks a bunch of tasks. I wanted to have a simple task monitor that would list the task name and the task’s status. I need this to look just a little nice, I’m no designer so whatever I do is going to suck, but a basic text display won’t work for the project requirements. What I am essentially attempting to do is show something similar to the Firefox download window, the I-Tunes download window, and well I could name more but they all look basically the same. In each of these apps, each of the ‘progress panels’ is selectable. So to implement this I thought it would be simple to just use a list of JPanels each with a JProgressBar and a JLabel, each of which can just accept focus to determine if it and others are selected. I thought this was going to be an easy task, but if I use a JList it just displays text. I then just figured I would show all the task panels in a larger panel, but I cannot get the inner panels to recognize focus. Is there a pattern for this? Is there a rolled standard solution that I just have not found? Or is there a better method for doing this? I don’t want to re-invent the wheel, but I thought this was just going to be simple.
It sounds like what you may be looking for is an [`JList`](http://java.sun.com/javase/6/docs/api/javax/swing/JList.html). You can add your items to the `JList`'s by first adding your "task" to the `JList` object's [`ListModel`](http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html) (see the [Create a Model](http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#creating) section from The Java Tutorials), and then you'll want to assigned a custom [`ListCellRenderer`](http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html) which will accept your "task" and render on the `JList` as a `JPanel` in the list itself. The key here is to make your custom `ListCellRenderer` be able to display your "task" in the `JList` the way you want to have it show on the `JList`. Take a look into the [Writing a Custom Cell Renderer](http://java.sun.com/docs/books/tutorial/uiswing/components/list.html#renderer) section from the [How to Use Lists](http://java.sun.com/docs/books/tutorial/uiswing/components/list.html) page of The Java Tutorials. It will describe how to make your custom `ListCellRenderer` so you can represent your "task" as anything you want. To keep it short, you will implement the [`ListCellRenderer`](http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html) interface by implementing the [`getListCellRendererComponent`](http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html#getListCellRendererComponent(javax.swing.JList,%20java.lang.Object,%20int,%20boolean,%20boolean)) which will return a [`Component`](http://java.sun.com/javase/6/docs/api/java/awt/Component.html) which is the representation of your task in the `JList`. You'll probably want to either construct or instantiate your `JPanel` in this method and return it as the `Component`.
The standard way of doing this kind of things is to use JTable (or JList) as a container. You don't have to use default renderes fot table cells, but you can specify your own renderer for specific cells. Take a look at [CellRenderer](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableCellRenderer.html)
In Java Swing how can you manage a list of panels allowing multiple panels to be selected?
[ "", "java", "swing", "jpanel", "jlist", "" ]
I have a table where I store customer sales (on periodicals, like newspaper) data. The product is stored by issue. Example ``` custid prodid issue qty datesold 1 123 2 12 01052008 2 234 1 5 01022008 1 123 1 5 01012008 2 444 2 3 02052008 ``` How can I retrieve (whats a faster way) the get last issue for all products, for a specific customer? Can I have samples for both SQL Server 2000 and 2005? Please note, the table is over 500k rows. Thanks
Assuming that "latest" is determined by date (rather than by issue number), this method is usually pretty fast, assuming decent indexes: ``` SELECT T1.prodid, T1.issue FROM Sales T1 LEFT OUTER JOIN dbo.Sales T2 ON T2.custid = T1.custid AND T2.prodid = T1.prodid AND T2.datesold > T1.datesold WHERE T1.custid = @custid AND T2.custid IS NULL ``` Handling 500k rows is something that a laptop can probably handle without trouble, let alone a real server, so I'd stay clear of denormalizing your database for "performance". Don't add extra maintenance, inaccuracy, and most of all headaches by tracking a "last sold" somewhere else. EDIT: I forgot to mention... this doesn't specifically handle cases where two issues have the same exact datesold. You might need to tweak it based on your business rules for that situation.
Generic SQL; SQL Server's syntax shouldn't be much different: ``` SELECT prodid, max(issue) FROM sales WHERE custid = ? GROUP BY prodid; ```
SQL Query Advice - Most recent item
[ "", "sql", "sql-server", "" ]
Looking for advice (perhaps best practice). We have a MS Word document (Office 2007) that we are extracting text from a cell. We can use the following: ``` string text = wordTable.cell(tablerow.index, 1).Range.Text; ``` The text is extracted; however we seem to get extra characters trailing, for example `\r\a`. Now we could add the following: ``` .... wordTable.cell(tablerow.index, 1).Range.Text.Replace("\r\a,""); ``` But this seems a little too lazy, and pretty much a waste of time that would most likely lead to problems down the road. We could also have a method that receives the string to clean: ``` private string cleanTextWordCellBreak(string wordTextToClean) { // Clean the text here return cleanstring; } ``` then we could use it: ``` cleanTextWordCellBreak(wordTable.cell(tablerow.index, 1).Range.Text; ); ``` This seems closer to a better way of handling the issue. What would you do?
I would break it out into a separate method but use the replace implementation since it's the simplest solution. You could always change the implementation later if you run into problem (like the text contains more than one `\r\a` and needs to be preserved) So: ``` private string stripCellText(string text) { return text.Replace("\r\a", ""); } string text = stripCellText(wordTable.cell(tablerow.index, 1).Range.Text); ```
I would definitely opt for breaking it out into a separate method personally. it helps with code readability and makes it a lot easier to change if needed in the future.
Advice for extracting word text and handling cellbreak characters
[ "", "c#", "string", "ms-word", "vsto", "" ]
I am creating a Windows service. When an exception occurrs, I handle it appropriately and create a log. I am using the [decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern), as there are many different ways people will be looking at these logs. I have an email logger, a file logger, and a windows event logger, all which inherit from LoggingDecorator, which implements ILogger. So, no logger knows about any other logger. My question is: How should I handle logging exceptions? If writing to a file fails, or sending an email fails, what should I do? I want to log the initial log content with the other loggers, but what do I do with the logging exception? Doesn't it also depend on the order of the loggers in the constructor? Right now, I'm just wrapping try/catch blocks with empty catch(Exception) statements, which just feels dirty and makes FxCop yell at me. However, is this one of those ["it depends"](https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception) moments? ``` [Flags] public enum LoggingCategories { None = 0, ServiceEvents = 1, ProcessingInformation = 2, ProcessingErrors = 4, UnexpectedErrors = 8 } public interface ILogger { void LogMessage(LoggingCategories category, string message); } public abstract class LoggerDecorator : ILogger { private ILogger _decoratedLogger; private LoggingCategories _categories; protected LoggerDecorator(ILogger logger, LoggingCategories categories) { this._decoratedLogger = logger; this._categories = categories; } protected bool ShouldLogCategory(LoggingCategories category) { return ((this._categories & category) == category); } public virtual void LogMessage(LoggingCategories category, string message) { _decoratedLogger.LogMessage(category, message); } } public class ControlLogger : ILogger { public ControlLogger() { } public void LogMessage(LoggingCategories category, string message) { Console.WriteLine(LoggingHelper.ConstructLog(category, message)); } } ``` (questionable code in WindowsEventLogger) ``` try { this._eventLog.WriteEntry(log, type); } catch (Exception) { //Even if this logging fails, we do not want to halt any further logging/processing. } ``` (code in service constructor) ``` ILogger controlLogger = new ControlLogger(); ILogger windowsEventLogger = new WindowsEventLogger(controlLogger, windowsEventLogCategories, windowsEventLogSource); ILogger emailLogger = new EmailLogger(windowsEventLogger, emailCategories, emailSubject, emailAddresses); ILogger fileLogger = new FileLogger(emailLogger, fileCategories, logDirectory, logFileNamePrefix, logFileExtension); this._logger = fileLogger; ```
Its not an answer, but curious why did you choose to not utilize the existing System.Diagnostics.Trace methods. You could implement some type of categorization of log types on top it it perhaps?
Why don't put it in the actual Windows Event log if logger fails?
c# windows-services - How do I handle logging exceptions?
[ "", "c#", "exception", "logging", "windows-services", "decorator", "" ]
Is there a way to update more than one Database having same schema using single ObjectDataSource in C#??? i.e Just by providing more than one connection string is it some how possible to update more than one Database? I need to update/insert same record in multiple Database with same schema using ObjectDataSource in C#.
Yes you can do it, since with an ObjectDataSource YOU ae the one writing the code that does the insert. Inside your "Update" and "Delete" methods you can simply perform two database actions, one for each database that you are working with. You can abstract this out to an operation that could be passed a connection to ensure that you don't have duplicate code sitting everywhere. **NOTE** You CANNOT do this thought via a single connection, you must do two fully separate database actions. **Example** Per the comment there was a request for more detail. Basically inside each of your methods, simply do two db calls, a crude AND NOT properly formed example to show the concept is below, for a "delete" method. ``` public void DeleteMyObject(int objectId) { SqlConnection connectionOne = new SqlConnection("MyFirstDbConnection"); SqlConnection connedtionTwo = new SqlConnection("MySecondDbCOnnection"); SqlCommand myCommand = new SqlCommand(connectionOne); myCommand.CommandText = "DELETE FROM myTable where myid = " + objectId.ToString(); connectionOne.Open(); myCommand.ExecuteNonQuery(); connectionOne.Close(); myCommand.Connection = connectionTwo; connectionTwo.Open(); myCommand.ExecuteNonQuery(); connectionTwo.Close(); } ``` Obviously the usage of a stored procedure, as well as proper using statements or try/catch is needed, but this gets the idea across.
Considering "**Mitchel Sellers**" Suggestion with some changes:- For **ObjectDataSource** create **OnInserting,OnUpdating,OnDeleting** Events in which handle Insert/Update/Delete on all the Databases except the one attached to he ObjectDataSource. e.g If **DataConnectionString1**,**DataConnectionString2** and **DataConnectionString3** are present and **DataConnectionString1** is attached to **ObjectDataSource1** then consider the ObjectDataSource1\_ObjectUpdating Event code given below.... protected void ObjectDataSource1\_ObjectUpdating(object sender, ObjectDataSourceMethodEventArgs e) { ``` string name = (string)e.InputParameters["name"]; int id = (int)e.InputParameters["id"]; if (string.IsNullOrEmpty(name)) e.Cancel = true; else { // Here insert in all Databases currently present // Except DB with StorageIndex = 1 as will b updated by ObjectDataSource1 for (int index = 2; index <= 3; index++) { string DataConnectionString = ConfigurationManager.AppSettings["DataConnectionString " + index]); SqlConnection con = new SqlConnection(DataConnectionString); string query = "UPDATE student SET [name] = @name WHERE (([id] = @id))"; int cnt = Utils.executeQuery(query, con, new object[] { "@name", "@id" }, new object[] { name, id }); } } } ``` This is what I did!!! Hope it Helps others too....
Update more than one database using same ObjectDataSource using C#
[ "", "c#", ".net", "ado.net", "" ]
I know python functions are virtual by default. Let's say I have this: ``` class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" ``` I don't want them to be able to do this: ``` class Aoo(Foo): def roo(): print "I don't want you to be able to do this" ``` Is there a way to prevent users from overloading roo()?
You can use a metaclass: ``` class NonOverridable(type): def __new__(self, name, bases, dct): if bases and "roo" in dct: raise SyntaxError, "Overriding roo is not allowed" return type.__new__(self, name, bases, dct) class foo: __metaclass__=NonOverridable ... ``` The metatype's **new** is called whenever a subclass is created; this will cause an error in the case you present. It will accept a definition of roo only if there are no base classes. You can make the approach more fancy by using annotations to declare which methods are final; you then need to inspect all bases and compute all final methods, to see whether any of them is overridden. This still doesn't prevent somebody monkey-patching a method into a class after it is defined; you can try to catch these by using a custom dictionary as the classes' dictionary (which might not work in all Python versions, as classes might require the class dictionary to be of the exact dict type).
Python 3.8 (released Oct/2019) adds `final` qualifier to typing. A `final` qualifier was added to the typing module---in the form of a `final` decorator and a Final type annotation---to serve three related purposes: * Declaring that a method should not be overridden * Declaring that a class should not be subclassed * Declaring that a variable or attribute should not be reassigned ``` from typing import final class Base: @final def foo(self) -> None: ... class Derived(Base): def foo(self) -> None: # Error: Cannot override final attribute "foo" # (previously declared in base class "Base") ... ``` It is in line with what your were asking and is supported by core Python now. Have a look at [PEP-591](https://www.python.org/dev/peps/pep-0591/) for more details.
Making functions non override-able
[ "", "python", "" ]
My company currently evaluates the development of a Java FAT client. It should support a dynamic GUI and has as much logic as possible on the server side. Hence the idea came up to send the screen as XML to the FAT client, show it to the user and send the entered data similar to "html form" back in a structure like: ``` <fields> <field type="checkbox" name="active" checked="false" x="10" y="10" /> <field type="textbox" name="username" value="dummy" x="10" y="30" /> <field type="selection" name="group" selectedIndex="1" x="10" y="50"> <data index="0">user</data> <data index="1">admin</data> </field> <field type="button" name="ok" x="10" y="70" /> <field type="button" name="cancel" x="10" y="90" /> </field> ``` *Background* The sponsor is looking for an data entry and review application which they can adapt to their needs by simply changing the configuration. Hence we have to provide a possibility for their administrators to design so called "screens" (aka forms) and provide a client/server system enabling them to distribute those to their end users. Incoming data (i.e. data entered by an user) will be then forwarded to an already existing workflow engine which is handling the business logic. **Question** Has anybody out there developed something similar? Which libraries would you suggest? Any pro & cons? Many thanks! *Update* Many thanks for your input, [Thinlet](http://www.thinlet.com) looks very promising as well as [JavaFX](http://en.wikipedia.org/wiki/JavaFX) - I will look into both.
When I last looked for such a thing, two options were [Thinlet](http://www.thinlet.com/index.html) and [Apache Jelly](http://commons.apache.org/jelly/libs/swing/index.html). The plus points were that you could separate the wiring and construction of your application from the behaviour. I'm not sure of the viability of either of them to do this, but I guess there *could* be some functionality for translating into another toolkit, much as [Lazlo](http://www.openlaszlo.org/showcase) can translate into AJAX and Flash. Before I found these, I had written a similar toolkit (when [Echo](http://echo.nextapp.com/) was the cutting edge, and Java 1.3 was bleeding edge), based upon the JHTMLEditor. It worked, but listeners were running in the same VM as the renderer. Which brings up the point that @Draemon makes, in a client/server context, I would have to ask if this is a fruitful way to solve the larger problem. I am guessing that you want to offload a lot of CPU cycles onto the client? Perhaps if you add a bit more, we can make more suggestions? This does point to an approach where your application is deployed on the desktop as a `localhost` webserver, and you serve pages to a local browser. If you can wait, I would, and wait for [JavaFX](http://en.wikipedia.org/wiki/JavaFX), as this will make building applets a good deal more declarative, and will also cut down on the initial download of the rendering library.
"It should support a dynamic GUI and has as much logic as possible on the server side." What you're describing is a web app. The client is already written (the browser) and the XML (ish) format is (X)HTML. It would be possible to recreate this process using your own XML format and your own client, but I don't see why this is necessary or desirable.
Java GUI described in XML
[ "", "java", "xml", "user-interface", "" ]
suppose I declare a dynamic array like ``` int *dynArray = new int [1]; ``` which is initialized with an unknown amount of int values at some point. How would I iterate till the end of my array of unknown size? Also, if it read a blank space would its corresponding position in the array end up junked? # Copying Input From users post below: Thing is: a) I'm not allowed to use STL (means: no ) b) I want to decompose a string into its characters and store them. So far I wanted to use a function like this: ``` string breakLine (string line){ int lineSize = line.size(); const char *aux; aux=line.data(); int index=0; while (index<=lineSize){ mySynonyms[index]=aux[index]; index++; } ``` I thought that the array aux would end up junked if there was a large blank space between the two numbers to be stored (apparently not). And I was wondering if there was a way to iterate till an undefined end in this type of array. Thanks for you answers.
No portable way of doing this. Either pass the size together with the array, or, better, use a standard container such as `std::vector`
You don't: wrap the array into a structure that remembers its length: `std::vector`. ``` std::vector v(1); std::for_each( v.begin(), v.end(), ... ); ```
C++ How can I iterate till the end of a dynamic array?
[ "", "c++", "arrays", "" ]
Consider this example table (assuming SQL Server 2005): ``` create table product_bill_of_materials ( parent_product_id int not null, child_product_id int not null, quantity int not null ) ``` I'm considering a composite primary key containing the two product\_id columns (I'll definitely want a unique constraint) as opposed to a separate unique ID column. Question is, from a performance point of view, should that primary key be clustered? Should I also create an index on each ID column so that lookups for the foreign keys are faster? I believe this table is going to get hit much more on reads than writes.
As has already been said by several others, it depends on how you will access the table. Keep in mind though, that any RDBMS out there should be able to use the clustered index for searching by a single column as long as that column appears first. For example, if your clustered index is on (parent\_id, child\_id) you don't need another separate index on (parent\_id). Your best bet may be a clustered index on (parent\_id, child\_id), which also happens to be the primary key, with a separate non-clustered index on (child\_id). Ultimately, indexing should be addressed after you've got an idea of how the database will be accessed. Come up with some standard performance stress tests if you can and then analyze the behavior using a profiling tool (SQL Profiler for SQL Server) and performance tune from there. If you don't have the expertise or knowledge to do that ahead of time, then try for a (hopefully limited) release of the application, collect the performance metrics, and see where you need to improve performance and figure out what indexes will help. If you do things right, you should be able to capture the "typical" profile of how the database is accessed and you can then rerun that over and over again on a test server as you try various indexing approaches. In your case I would probably just put a clustered PK on (parent\_id, child\_id) to start with and then add the non-clustered index only if I saw a performance problem that would be helped by it.
"What you query on most often" is not necessarily the best reason to choose an index for clustering. What matters most is what you query on to obtain multiple rows. Clustering is the strategy appropriate for making it efficient to obtain multiple rows in the fewest number of disk reads. The best example is sales history for a customer. Say you have two indexes on the Sales table, one on Customer (and maybe date, but the point applies either way). If you query the table most often on CustomerID, then you'll want all the customer's Sales records together to give you one or two disk reads for all the records. The primary key, OTOH, might be a surrogate key, or SalesId, - but a unique value in any case. If this were clustered, it would be of no benefit compared to a normal unique index. EDIT: Let's take this particular table for discussion - it will reveal yet more subtleties. The "natural" primary key is in all likelihood parentid + childid. But in what sequence? Parentid + childid is no more unique than childid + parentid. For clustering purposes, which ordering is more appropriate? One would assume it must be parentid + childid, since we will want to ask: "For a given item, what are its constituents"? But is not that unlikely to want to go the other way, and ask "For a given constuent, of what items is it a component?". Add in the consideration of "covering indexes", which contain, within the index, all the information needed to satisfy the query. If that's true, then you never need to read the rest of the record; so clustering is of no benefit; just reading the index is sufficient. (BTW, that means two indexes on the same pair of fields, in opposite order; which may be the proper thing to do in cases like this. Or at least a composite index on one, and a single-field index on the other.) But that still doesn't dictate which should be clustered; which would finally probably be determined by which queries will, in fact, need to grab the record for the Quantity field. Even for such a clear example, in principle it's best to leave decidintg about other indexes until you can test them with realistic data (obviously before production); but asking here for speculation is pointless. Testing always will give you the proper answer. Forget worrying about slowing down inserts until you have a problem (which in most cases will never happen), and can test to make sure giving up useful indexes for a measurable benefit. Things still aren't certain, though, because junction tables like this one are also frequently involved in lots of other types of queries. So I'd just pick one and test as needed as the application gels, and data volume for testing becomes available. BTW, I'd expect it to end up with a PK on parentid + childid; a non-unique index on childid; and the first clustered. If you prefer a surrogate PK, then you'll still want a unique index on parentid + childid, clustered. Clustering the surrogate key is very unlikely to be optimal.
Should a Composite Primary Key be clustered in SQL Server?
[ "", "sql", "database", "database-design", "primary-key", "" ]
I've been working with Vector2's and XNA, and I've come to find that calling the Normalize() member function on a Zero Vector normalizes it to a vector of {NaN, NaN}. This is all well and good, but in my case I'd prefer it instead just leave them as Zero Vectors. Adding this code to my project enabled a cute extension method: ``` using ExtensionMethods; namespace ExtensionMethods { public static class MyExtensions { public static Vector2 NormalizeOrZero(this Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); return v2; } } } ``` Unfortunately, this method *returns* the normalized vector, rather than simply normalizing the vector which I use to invoke this extension method. I'd like to to instead behave as *vector2Instance*.Normalize() does. Aside from making this void, how do I adjust this so that the 'v2' is modified? (Essentially, I need access to the 'this' object, or I need 'v2' to be passed by reference.) Edit: And yes, I have tried this: ``` public static void NormalizeOrZero(this Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); } ``` Doesn't work, v2 is just a variable in the scope of NormalizeOrZero.
This doesn't work because Vector 2 [is actually a struct](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx). This means it gets passed by value and you can't modify the caller's copy. I think the best you can do is the workaround specified by lomaxxx. This illustrates why you should generally avoid using structures. See [this question](https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class) for more information. Vector2 violates the guideline that structs should be immutable, but it probably made sense to do so in the context of XNA.
Well, if you're really just *dying* to do this, you could do something like this: ``` public static void NormalizeOrZero(this Vector2 ignore, ref Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); } ``` You would call it this way: ``` v2.NormalizeOrZero(ref v2); ``` It's mighty ugly, but it'll work, for what it's worth. But at that point you may as well call a static method in the first place.
How do I access 'this' from within a C# extension method?
[ "", "c#", "pass-by-reference", "this", "" ]
I have a `JTable` with a custom `TableModel` called `DataTableModel`. I initialized the table with a set of column names and no data as follows: ``` books = new JTable(new DataTableModel(new Vector<Vector<String>>(), title2)); JScrollPane scroll1 = new JScrollPane(books); scroll1.setEnabled(true); scroll1.setVisible(true); JSplitPane jsp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scroll1, scroll2); JSplitPane jsp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inventory, jsp1); myPanel.add(jsp2, BorderLayout.CENTER); ``` I later want to update books with a set of data, and use the following: ``` DataTableModel d = (DataTableModel)books.getModel(); d.setValues(bookList); books.setModel(d); ``` where bookList is a `Vector<Vector<String>>` that definitely has data. However, although all this code is being executed, it is not displaying on the screen. The code for the `setValues()` method is: ``` public void setValues(Vector<Vector<String>> v) { values = v; fireTableDataChanged(); } ``` Am I missing something here? The class and methods for my DataTableModel are (these methods are all implemented to return correct results): ``` public class DataTableModel extends AbstractTableModel { public DataTableModel(Vector<Vector<String>> v, Vector<String> c) {} public int getColumnCount() { if (values != null && values.size() > 0) return values.elementAt(0).size(); else return 0; } public int getRowCount() { if (values != null && values.size() > 0) return values.size(); else return 0; } public Object getValueAt(int arg0, int arg1) {} public void setValues(Vector<Vector<String>> v) {} public Vector<Vector<String>> getValues() {} public void setColumnNames(Vector<String> columns) {} public String getColumnName(int col) {} } ```
Have you implemented the other methods for `TableModel`? If so, how does your implementation look? Maybe you should post your table model code to let us inspect it? BTW: My main error when implementing `TableModel` was to override `getRowCount()` and `getColumnCount()` to `return 0`. This will tell the table that there is no data to display... EDIT: So you seem to be using something like an `AbstractTableModel` or a `DefaultTableModel`, right? Have you overridden some of the methods? EDIT 2: You should call `fireTableStructureChanged` instead of `fireTabeDataChanged()`, because initially your table model is returning `0` for `getColumnCount()`. EDIT 3: To further optimize your model you should consider returning a fixed value for `getColumnCount()` if you have data that has the same number of columns every time. Then you can call the `fireTabeDataChanged()` which just loads the new data instead of completely building up the table and data (`fireTableStructureChanged()`) every time.
This is weird problem. You said that `DataTableModel` implements `TableModel`. So. If you does not use abstract class the problem should be in the way how you are handling the events. Are listeners really registered and then notified? If you can, please send link to source of `DataTableModel`. But before, verify that you are correctly handling listeners registered into this model.
JTable updates not appearing
[ "", "java", "user-interface", "swing", "jtable", "" ]
An interface is a 100% abstract class, so we can use an interface for efficient programming. Is there any situation where an abstract class is better than an interface?
Abstract classes are used when you do intend to create a concrete class, but want to make sure that there is some **common state** in all the subclasses or a possible **common implementation** for some operations. Interfaces cannot contain either.
Yes, there is a place for both abstract classes and interfaces. Let's go with a concrete example. We'll look into how to make a `CheckingAccount` and `SavingsAccount` from an abstract `AbstractBankAccount` and see how we can use an interface differentiate the two types of accounts. To start off, here's an abstract class `AbstractBankAccount`: ``` abstract class AbstractBankAccount { int balance; public abstract void deposit(int amount); public abstract void withdraw(int amount); } ``` We have the account balance as `balance` and two methods `deposit` and `withdraw` that must be implemented by the subclasses. As we can see, an **abstract class declares the structure** of how bank accounts should be defined. As @Uri mentions in his response, there is a *state* to this abstract class, which is the `balance` field. This would not be possible with an interface. Now, let's subclass `AbstractBankAccount` to make a `CheckingAccount` ``` class CheckingAccount extends AbstractBankAccount { public void deposit(int amount) { balance += amount; } public void withdraw(int amount) { balance -= amount; } } ``` In this subclass `CheckingAccount`, we implemented the two abstract classes -- nothing too interesting here. Now, how could we implement `SavingsAccount`? It is different from a `CheckingAccount` in that it will gain interest. The interest could be increased by using the `deposit` method, but then again, it's not as if the customer is depositing the interest him/herself. Therefore, it might be more clearer if we had another means of adding money into an account, specifically for interest, say, an `accrueInterest` method. We could directly implement the method in `SavingsAccount`, but we may have more bank account types that can accrue interest in the future, so we may want to make an `InterestBearing` interface that has the `accrueInterest` method: ``` interface InterestBearing { public void accrueInterest(int amount); } ``` So, we now can make an `SavingsAccount` class that can gain interest by implementing the `InterestBearing` interface: ``` class SavingsAccount extends AbstractBankAccount implements InterestBearing { public void deposit(int amount) { balance += amount; } public void withdraw(int amount) { balance -= amount; } public void accrueInterest(int amount) { balance += amount; } } ``` Now, if we want to make another type of account, say a `PremiumSavingsAccount`, we can make a subclass of the `AbstractBankAccount` and implement the `InterestBearing` interface to make another interest-bearing account. The `InterestBearing` interface can be seen as **adding a common feature** to different classes. It would have not have made sense to have a feature to deal with interest in a checking account when it doesn't accrue any interest. So, there are indeed places for both abstract classes and interfaces to coexist and work together in one situation.
Need for Abstract Class as well as Interface?
[ "", "java", "interface", "abstract-class", "" ]
Greetings, I have data stored on mysql with delimiter "," in 1 table. I have rows and column stored on database too. Now i have to output the data using rows and column number stored on database to draw the table. Rows and column number are user input, so it may varies. Let say, there is number 3 on column and 3 on rows. I need to do it like display like, ``` |___d1__|___d2__|___d3__| |___d4__|___d5__|___d6__| |___d7__|___d8__|___d9__| ``` Where d1-d9 would be the data stored on mysql database with delimiter "," in one table. Thanks for helping me.
You can turn the comma separated values from your data column into an array using the explode() function: ``` <?php $result = mysql_query('SELECT rows, columns, data from table_name where id=1'); $record = mysql_fetch_assoc($result); $rows = $record['rows']; $columns = $record['columns']; $data = explode(',' , $record['data']); if (sizeof($data) != $rows * $columns) die('invalid data'); ?> ``` To display the table, you need two nested for-loops: ``` <table> <?php for ($row = 0; $row < $rows; $row++) : ?> <tr> <?php for ($column = 0; $column < $columns; $column++) : ?> <td> <?php echo $data[$row * $columns + $column]; ?> </td> <?php endfor ?> </tr> <?php endfor ?> </table> ```
This won't help you solve this very problem, but a word of good advice: never EVER write comma seperated values into a database field. You can't sensibly query information stored like this, and your application code will be cluttered with ugly conversions. Instead, use a seperate table with a reference to the main table and one row per value.
PHP MYSQL - Explode help
[ "", "php", "mysql", "explode", "" ]
Is there a way in Python, to have more than one constructor or more than one method with the *same name*, who differ in the *number of arguments* they accept or the *type(s) of one or more argument(s)*? If not, what would be the best way to handle such situations? For an example I made up a color class. *This class should only work as a basic example to discuss this*, there is lot's of unnecessary and/or redundant stuff in there. It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with \* args and \* \* kwargs, but using class methods is the only general way I came up with. What would be a "**best practice**" like solution for this? The constructor aside, if I would like to implement an \_ \_ **add** \_ \_ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)? **EDIT** * I added an *alternative* constructor (initializer, \_ \_ **init** \_ \_) that basicly does all the stuff I wanted. * But I stick with the first one and the factory methods. Seems clearer. * I also added an \_ \_ **add** \_ \_, which does all the things mentioned above but I'm not sure if it's *good style*. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho. * I have taken a look at \_ \_ **new** \_ \_, thanks for the links. * My first quick try with it fails: I filter the rgb values from the \* args and \* \* kwargs (is it a class, a list, etc.) then call the superclass's \_ \_ new \_ \_ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self).\_ \_ new \_ \_ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to \_ \_ init \_ \_ (working as intended), so it bails. * I could get rid of the \_ \_ init \_ \_ completly and set the values in the \_ \_ new \_ \_ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess. Source: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- class Color (object): # It's strict on what to accept, but I kinda like it that way. def __init__(self, r=0, g=0, b=0): self.r = r self.g = g self.b = b # Maybe this would be a better __init__? # The first may be more clear but this could handle way more cases... # I like the first more though. What do you think? # #def __init__(self, obj): # self.r, self.g, self.b = list(obj)[:3] # This methods allows to use lists longer than 3 items (eg. rgba), where # 'Color(*alist)' would bail @classmethod def from_List(cls, alist): r, g, b = alist[:3] return cls(r, g, b) # So we could use dicts with more keys than rgb keys, where # 'Color(**adict)' would bail @classmethod def from_Dict(cls, adict): return cls(adict['r'], adict['g'], adict['b']) # This should theoreticaly work with every object that's iterable. # Maybe that's more intuitive duck typing than to rely on an object # to have an as_List() methode or similar. @classmethod def from_Object(cls, obj): return cls.from_List(list(obj)) def __str__(self): return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b) def _set_rgb(self, r, g, b): self.r = r self.g = g self.b = b def _get_rgb(self): return (self.r, self.g, self.b) rgb = property(_get_rgb, _set_rgb) def as_List(self): return [self.r, self.g, self.b] def __iter__(self): return (c for c in (self.r, self.g, self.b)) # We could add a single value (to all colorvalues) or a list of three # (or more) values (from any object supporting the iterator protocoll) # one for each colorvalue def __add__(self, obj): r, g, b = self.r, self.g, self.b try: ra, ga, ba = list(obj)[:3] except TypeError: ra = ga = ba = obj r += ra g += ga b += ba return Color(*Color.check_rgb(r, g, b)) @staticmethod def check_rgb(*vals): ret = [] for c in vals: c = int(c) c = min(c, 255) c = max(c, 0) ret.append(c) return ret class ColorAlpha(Color): def __init__(self, r=0, g=0, b=0, alpha=255): Color.__init__(self, r, g, b) self.alpha = alpha def __str__(self): return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha) # ... if __name__ == '__main__': l = (220, 0, 70) la = (57, 58, 61, 255) d = {'r': 220, 'g': 0, 'b':70} da = {'r': 57, 'g': 58, 'b':61, 'a':255} c = Color(); print c # <Color(0, 0, 0)> ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)> print '---' c = Color(220, 0, 70); print c # <Color(220, 0, 70)> c = Color(*l); print c # <Color(220, 0, 70)> #c = Color(*la); print c # -> Fail c = Color(**d); print c # <Color(220, 0, 70)> #c = Color(**da); print c # -> Fail print '---' c = Color.from_Object(c); print c # <Color(220, 0, 70)> c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)> c = Color.from_List(l); print c # <Color(220, 0, 70)> c = Color.from_List(la); print c # <Color(57, 58, 61, 255)> c = Color.from_Dict(d); print c # <Color(220, 0, 70)> c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)> print '---' print 'Check =', Color.check_rgb('1', 0x29a, -23, 40) # Check = [1, 255, 0, 40] print '%s + %s = %s' % (c, 10, c + 10) # <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)> print '%s + %s = %s' % (c, ca, c + ca) # <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)> ```
In general, use factory methods, marked up as `@classmethod`s. They'll also work correctly on subclasses. From a design perspective, they are more explicit, especially when given a good name. In this case, mixing everything together is probably more convenient, but it also makes the contract for your constructor more difficult.
You can have the factory methods, it is fine. But why not just call it as it is? ``` Color(r, g, b) Color(*[r, g, b]) Color(**{'r': r, 'g': g, 'b': b}) ``` This is the python way. As for the from object constructor, I would prefer something like: ``` Color(*Color2.as_list()) ``` *Explicit is better than implicit* - Python Zen
How to handle constructors or methods with a different set (or type) of arguments in Python?
[ "", "python", "" ]
I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this: ``` int i = true; ``` Is it "always" guaranteed that variable i will have value 1 or is it again depends on the compiler I am using ? Further for some Win32 APIs which accept BOOL as the parameter what happens if I pass bool variable?
bool is a fundamental datatype in C++. Converting `true` to an integer type will yield 1, and converting `false` will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like ``` enum bool { false, true }; ``` So did the Windows API. Starting with C99, we have `_Bool` as a basic data type. Including `stdbool.h` will typedef `#define` that to `bool` and provide the constants `true` and `false`. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.
Yes, bool is a built-in type. WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.
Is 'bool' a basic datatype in C++?
[ "", "c++", "" ]
I've been watching Douglas Crockford's talks at YUI Theater, and I have a question about JavaScript inheritance... Douglas gives this example to show that "Hoozit" inherits from "Gizmo": ``` function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; ``` Why does he write `Hoozit.prototype = new Gizmo()` instead of `Hoozit.prototype = Gizmo.prototype`? Is there any difference between these two?
The reason is that using `Hoozit.prototype = Gizmo.prototype` would mean that modifying Hoozit's prototype object would also modify objects of type Gizmo, which is not expected behavior. `Hoozit.prototype = new Gizmo()` inherits from Gizmo, and then leaves Gizmo alone.
The other answers address this, but if you DO want to inherit the prototype, you can use some parasitic magic: ``` Object.prototype.inherit = function(p) { NewObj = function(){}; NewObj.prototype = p; return new NewObj(); }; // Paraphrasing of Nicholas Zakas's Prototype Inheritance helper function inheritPrototype(subType, superType) { var prototype = Object.inherit(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; }; ``` Now you can replace the: ``` Hoozit.prototype = new Gizmo(); ``` with ``` inheritPrototype(Hoozit, Gizmo); ``` It might not be worth the trouble unless you have a real big Gizmo constructor (the only win in my suggestion is that you don't have to call Gizmo's constructor to hook up the prototype). I have examples of many of these types of patterns in *[TDD JavaScript Examples](http://github.com/roblevintennis/Testing-and-Debugging-JavaScript)*.
Prototypal inheritance in JavaScript
[ "", "javascript", "inheritance", "prototypal-inheritance", "" ]
In C#, it is possible to retrieve assembly related information like product name, version etc using reflection: ``` string productName = Assembly.GetCallingAssembly().GetName().Name; string versionString = Assembly.GetCallingAssembly().GetName().Version.ToString(); ``` How do I do the equivalent if the executing assembly is written in unmanaged C++ (say)? Is it even possible? Assume that I have a .NET dll which is being invoked in unmanaged code via a COM interface. **edit:** To make things absolutely clear, this is my scenario: * I have an executable written in unmanaged C++ * I have a dll written in C#/.NET * The dll is invoked by the executable via a COM interface * Within the .NET dll I want to be able to retrieve information like the product name and version of the calling executable. Possible?
Walking the stack is not necessary to find out what process you are in. You simply make a single Win32 API call: ``` HMODULE hEXE = GetModuleHandle(NULL); ``` According to the [documentation for this call](http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx): > If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file). You can turn this module handle into a filename with [GetModuleFileName()](http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx), another standard Win32 API. File name in hand, you can then call [GetFileVersionInfo()](http://msdn.microsoft.com/en-us/library/ms647003(VS.85).aspx) to retrieve the VS\_VERSIONINFO structure for that file. The information you want is in there. Now since you are in .NET you could use P/Invoke signatures for [GetModuleHandle()](http://www.pinvoke.net/default.aspx/kernel32/GetModuleHandle.html?diff=y), [GetModuleFileName()](http://www.pinvoke.net/default.aspx/kernel32/GetModuleFileName.html). For GetFileVersionInfo() you can use [System.Diagnostics.FileVersionInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo_members.aspx). But actually the easiest way to do it is probably to stick with the System.Diagnostics namespace, everything you need is there. Call [System.Diagnostics.Process.GetCurrentProcess()](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx) to return a Process object for the process you are running in. Then you can retrieve a ProcessModule from the [MainModule](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainmodule.aspx) property. ProcessModule has a property called [FileVersionInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.fileversioninfo.aspx). The information you want is there.
you could use the following code in VB.Net to retrieve extended document properties: ``` Sub Main() Dim arrHeaders(41) Dim shell As New Shell32.Shell Dim objFolder As Shell32.Folder objFolder = shell.NameSpace("C:\tmp\") For i = 0 To 40 arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i) Next For Each strFileName In objfolder.Items For i = 0 To 40 Console.WriteLine(i & vbTab & arrHeaders(i) & ": " & objFolder.GetDetailsOf(strFileName, i)) Next Next End Sub ``` Add a COM reference to Microsoft Shell Controls and Automation to your project to compile. The output of the above program will be a list of the meta data assigned to all files in C:\tmp such as ``` 0 Name: dpvoice.dll 1 Size: 208 KB 2 Type: Application Extension 3 Date Modified: 14.04.2008 04:41 4 Date Created: 14.04.2008 04:41 5 Date Accessed: 01.12.2008 09:56 6 Attributes: A 7 Status: Online 8 Owner: Administrators 9 Author: 10 Title: 11 Subject: 12 Category: 13 Pages: 14 Comments: 15 Copyright: 16 Artist: 17 Album Title: 18 Year: 19 Track Number: 20 Genre: 21 Duration: 22 Bit Rate: 23 Protected: 24 Camera Model: 25 Date Picture Taken: 26 Dimensions: 27 : 28 : 29 Episode Name: 30 Program Description: 31 : 32 Audio sample size: 33 Audio sample rate: 34 Channels: 35 Company: Microsoft Corporation 36 Description: Microsoft DirectPlay Voice 37 File Version: 5.3.2600.5512 38 Product Name: Microsoftr Windowsr Operating System 39 Product Version: 5.03.2600.5512 40 Keywords: ```
Retrieving product information from an unmanaged executing application in C#/.NET
[ "", "c#", ".net", "com", "unmanaged", "" ]
**Description |** A Java program to read a text file and print each of the unique words in alphabetical order together with the number of times the word occurs in the text. The program should declare a variable of type `Map<String, Integer>` to store the words and corresponding frequency of occurrence. Which concrete type, though? `TreeMap<String, Number>` or `HashMap<String, Number>` ? The input should be converted to lower case. A word does not contain any of these characters: `\t\t\n]f.,!?:;\"()'` **Example output |** ``` Word Frequency a 1 and 5 appearances 1 as 1 . . . ``` **Remark |** I know, I've seen elegant solutions to this in Perl with roughly two lines of code. However, I want to see it in Java. Edit: Oh yeah, it be helpful to show an implementation using one of these structures (in Java).
[`TreeMap`](http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html) seems a no-brainer to me - simply because of the "in alphabetical order" requirement. `HashMap` has no ordering when you iterate through it; `TreeMap` iterates in the natural key order. EDIT: I think Konrad's comment may have been suggesting "use `HashMap`, then sort." This is good because although we'll have N iterations initially, we'll have K <= N keys by the end due to duplicates. We might as well save the expensive bit (sorting) until the end when we've got fewer keys than take the small-but-non-constant hit of keeping it sorted as we go. Having said that, I'm sticking to my answer for the moment: because it's the *simplest* way of achieving the goal. We don't really know that the OP is particularly worried about performance, but the question implies that he's concerned about the elegance and brevity. Using a `TreeMap` makes this incredibly brief, which appeals to me. I suspect that if performance is really an issue, there may be a better way of attacking it than either `TreeMap` or `HashMap` :)
TreeMap beats HashMap because TreeMap is already sorted for you. However, you might want to consider using a more appropriate data structure, a bag. See [Commons Collections](http://commons.apache.org/collections) - and the [TreeBag](http://commons.apache.org/collections/api-3.2/org/apache/commons/collections/bag/TreeBag.html) class: This has a nice optimised internal structure and API: ``` bag.add("big") bag.add("small") bag.add("big") int count = bag.getCount("big") ``` EDIT: The question of HashMap vs TreeMap performance was answered by Jon - HashMap and sort may be quicker (try it!), but TreeBag is easier. The same is true for bags. There is a HashBag as well as a TreeBag. Based on the implementation (uses a mutable integer) a bag should outperform the equivalent plain map of Integer. The only way to know for sure is to test, as with any performance question.
Which data structure would you use: TreeMap or HashMap? (Java)
[ "", "java", "data-structures", "dictionary", "hashmap", "treemap", "" ]
I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli\_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J The way i pull emails is this code. ``` pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) ``` I have tried probably all combinations of encode / decode within python and php.
You can use the python email library (python 2.5+) to avoid these problems: ``` import email import poplib import random from cStringIO import StringIO from email.generator import Generator pop = poplib.POP3(server) mail_count = len(pop.list()[1]) for message_num in xrange(mail_count): message = "\r\n".join(pop.retr(message_num)[1]) message = email.message_from_string(message) out_file = StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(message_text) email_file.close() ``` This code will get all the messages from your server and turn them into Python message objects then flatten them out into strings again for writing to the file. By using the email package from the Python standard library MIME encoding and decoding issues should be handled for you. DISCLAIMER: I have not tested that code, but it should work just fine.
There is a better way to do this, but this is what i ended up with. Thanks for your help guys. ``` import poplib, quopri import random, md5 import sys, rfc822, StringIO import email from email.Generator import Generator user = "email@example.com" password = "password" server = "mail.example.com" # connects try: pop = poplib.POP3(server) except: print "Error connecting to server" sys.exit(-1) # user auth try: print pop.user(user) print pop.pass_(password) except: print "Authentication error" sys.exit(-2) # gets the mail list mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() message = "\r\n".join(pop.retr(mno)[1]) message = email.message_from_string(message) # uses the email flatten out_file = StringIO.StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() # fixes mime encoding issues (for display within html) clean_text = quopri.decodestring(message_text) msg = email.message_from_string(clean_text) # finds the last body (when in mime multipart, html is the last one) for part in msg.walk(): if part.get_content_type(): body = part.get_payload(decode=True) filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(msg["From"] + "\n") email_file.write(msg["Return-Path"] + "\n") email_file.write(msg["Subject"] + "\n") email_file.write(msg["Date"] + "\n") email_file.write(body) email_file.close() pop.quit() sys.exit() ```
Trouble with encoding in emails
[ "", "python", "email", "encoding", "" ]
Do you localize your javascript to the page, or have a master "application.js" or similar? If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages? EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering. And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do. All shared JS code lives in the `SITE/javascripts` directory, but it's loaded in 'tiers' For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The `script` tags go at the top of the page. There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags) For less-shared stuff (say my library that's only needed in a few places) then I put a `script` tag in those HTML pages individually. The script tags go at the top of the page. For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the `script` tag will go below the button. For inline JS that doesn't have a target (eg: `onload` events) it goes at the bottom of the page. --- So, how does something get into a localised library, or a site-wide library?. * The first time you need it, write it inline * The next time you need it, pull the inline code up to a localised library * If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library * If it's needed from more than one region, pull it up to a site-wide library. A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view. However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations. I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Where do you put your javascript?
[ "", "javascript", "" ]
Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, *now*. Too late. Okay. Take a deep breath. Here are the rules. Take *two* thirty sided dice (yes, [they do exist](http://paizo.com/store/byCompany/k/koplow/dice/d30)) and roll them simultaneously. * Add the two numbers * If both dice show <= 5 or >= 26, throw again and *add* the result to what you have * If one is <= 5 and the other >= 26, throw again and *subtract* the result from what you have * Repeat until either is > 5 and < 26! If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%. Now the question: Is it possible to write a program to *calculate* the *exact* value f(x), i.e. the probability to roll a certain value? Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :) For the geeks around, the code in Python: ``` import random import sys def OW60 (): """Do an open throw with a "60" sided dice""" val = 0 sign = 1 while 1: r1 = random.randint (1, 30) r2 = random.randint (1, 30) #print r1,r2 val = val + sign * (r1 + r2) islow = 0 ishigh = 0 if r1 <= 5: islow += 1 elif r1 >= 26: ishigh += 1 if r2 <= 5: islow += 1 elif r2 >= 26: ishigh += 1 if islow == 2 or ishigh == 2: sign = 1 elif islow == 1 and ishigh == 1: sign = -1 else: break #print sign #print val return val result = [0] * 2000 N = 100000 for i in range(N): r = OW60() x = r+1000 if x < 0: print "Too low:",r if i % 1000 == 0: sys.stderr.write('%d\n' % i) result[x] += 1 i = 0 while result[i] == 0: i += 1 j = len(result) - 1 while result[j] == 0: j -= 1 pSum = 0 # Lower Probability: The probability to throw this or less # Higher Probability: The probability to throw this or higher print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;" while i <= j: pSum += result[i] print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N)) i += 1 ```
I had to first rewrite your code before I could understand it: ``` def OW60(sign=1): r1 = random.randint (1, 30) r2 = random.randint (1, 30) val = sign * (r1 + r2) islow = (r1<=5) + (r2<=5) ishigh = (r1>=26) + (r2>=26) if islow == 2 or ishigh == 2: return val + OW60(1) elif islow == 1 and ishigh == 1: return val + OW60(-1) else: return val ``` Maybe you might find this less readable; I don't know. (Do check if it is equivalent to what you had in mind.) Also, regarding the way you use "result" in your code -- do you know of Python's [dict](http://www.diveintopython.org/getting_to_know_python/dictionaries.html)s? Anyway, matters of programming style aside: Suppose F(x) is the [CDF](http://en.wikipedia.org/wiki/Cumulative_distribution_function) of OW60(1), i.e. ``` F(x) = the probability that OW60(1) returns a value ≤ x. ``` Similarly let ``` G(x) = the probability that OW60(-1) returns a value ≤ x. ``` Then you can calculate F(x) from the definition, by summing over all (30×30) possible values of the result of the first throw. For instance, if the first throw is (2,3) then you'll roll again, so this term contributes (1/30)(1/30)(5+F(x-5)) to the expression for F(x). So you'll get some obscenely long expression like ``` F(x) = (1/900)(2+F(x-2) + 3+F(x-3) + ... + 59+F(x-59) + 60+F(x-60)) ``` which is a sum over 900 terms, one for each pair (a,b) in [30]×[30]. The pairs (a,b) with both ≤ 5 or both ≥26 have a term a+b+F(x-a-b), the pairs with one ≤5 and one ≥26 have a term a+b+G(x-a-b), and the rest have a term like (a+b), because you don't throw again. Similarly you have ``` G(x) = (1/900)(-2+F(x-2) + (-3)+F(x-3) + ... + (-59)+F(x-59) + (-60)+F(x-60)) ``` Of course, you can collect coefficients; the only F terms that occur are from F(x-60) to F(x-52) and from F(x-10) to F(x-2) (for a,b≥26 or both≤5), and the only G terms that occur are from G(x-35) to G(x-27) (for one of a,b≥26 and the other ≤5), so there are fewer terms than 30 terms. In any case, defining the vector V(x) as ``` V(x) = [F(x-60) G(x-60) ... F(x-2) G(x-2) F(x-1) G(x-1) F(x) G(x)] ``` (say), you have (from those expressions for F and G) a relation of the form ``` V(x) = A*V(x-1) + B ``` for an appropriate matrix A and an appropriate vector B (which you can calculate), so starting from initial values of the form V(x) = [0 0] for x sufficiently small, you can find F(x) and G(x) for x in the range you want to arbitrarily close precision. (And your f(x), the probability of throwing x, is just F(x)-F(x-1), so that comes out as well.) There might be a better way. All said and done, though, why are you doing this? Whatever kind of distribution you want, there are nice and simple probability distributions, with the appropriate parameters, that have good properties (e.g. small variance, one-sided errors, whatever). There is no reason to make up your own ad-hoc procedure to generate random numbers.
I've done some basic statistics on a sample of 20 million throws. Here are the results: ``` Median: 17 (+18, -?) # This result is meaningless Arithmetic Mean: 31.0 (±0.1) Standard Deviation: 21 (+1, -2) Root Mean Square: 35.4 (±0.7) Mode: 36 (seemingly accurate) ``` The errors were determined experimentally. The arithmetic mean and the mode are really accurate, and changing the parameters even quite aggressively doesn't seem to influence them much. I suppose the behaviour of the median has already been explained. Note: don't take these number for a proper mathematical description of the function. Use them to quickly get a picture of what the distribution looks like. For anything else, they aren't accurate enough (even though they might be precise. Perhaps this is helpful to someone. Edit 2: ![graph](https://chart.apis.google.com/chart?cht=lc&chs=400x200&chd=e:UshVbmkydgXwlLifjQljW.cvgkackylLRPd5ZriGhVbmgkdgfCi3eRfCgk4VSyYhhufbbmYhcvhVg9ZrljkZa0ZrljhVY6gMfzkZkyXYacfClLfbackBifd5kZi3fCiGcvgMi3acnel8g9gMmtZrdgbmbNd5l8fCcvbNkBmUdIbNgMZrb-kymUbmdIhuxDiGbNeRYJwqgkjobmeqiGaDY6cvpxjobNlLhVgMonkZcXg92aVFl8iGljeRjoljhVdIiGn2bNfzd5-1kZhVWOhVnenFgMbmaceRfzgMifeqbNfbfCjon2dIjo2yi3gMdIjQZSjQa0y9hukBi3jog9ZrfbeRmUkycvgMdIZrnFbNjQhVjo04bmbNZracYhfbi3aceqhuYhZSlLcXd5n21pljkBa0kZmtifaceqifUUiG6oeRgMkycXeqQ3fCmtaDlLjogMgMjQkygkkyfbcveqiGZSkZeRfbbNaceReRd5l8gkpYfCiGlLkyfzgMfCmUififdgifb-mUac2ymtifd5kBfzjQnFcvfbfCYhjQac2yacifeqjocvb-bmjQifdghVd5g9ifkZeqd5hVdgjQnFn2fCZScXcXifd5-dhVnFbmbNacgMgk8KbmmUWncvlLd5bNcXRojonF.mkZbNmUdgfCnFkBljoPhVjQoPdId5fzifachufCgkhVpAcXgkmUd5nFiGdgi3gMV2kyl8n2jofCfzoPdIeqPVa0kZhVoncvhVaDlLbmXwaDiGYhkyZrVFljSZhuaDi3acnecvb-gknFbmjQeRkBonjQeqfbb-mUjob-jQdgmtzueqmUifoPFwcX2aeRjoiGfCXYa0b-iGpAaDiGNCoPi3kZl8ZrQ3jQiGW.ZrbmY6dIiGeRjQkyY6bmfzoPpxgMd5l8fzhufzlLg9lLa0i3YhkBiGXweqjQcXjogMa0WOg9oPl8eRhujQfbZSjocvifhVRPmtd5hVgMn2jQhuifd5gkYJnen2kZcXY6fCdgcvmtjobNfChufCnekZdIgkg9ackydggMeq7AYhiGfbjoeqeRachuT7cvVFbmeqeRkyUshusEd5joiGRPgMlLeqdgfChujoifg9g9YJiGdgkBmtdIhuYhO8RoiffzfCiGfbjQi3Yhkylja0gMjobmfCdIdghVljdIjQwqhVoPl8jQljg9kZdIdgfCd5yMnFeRZraDYhgkmtWOjQn2l8fznecva0mthuAAkyg9ZrZSYJonkyNafCeqfCx0fzkymtkycXgkl8b-jQcXhVW.eRdgkZcvfbnegkjoeqkZiGkykBhVfbkBcXfCSymUg9neeRnehVeqd5g9hukBififn2kZl8n2d5l8huYhfzifd5bNXYW.oni3b-jQifacn2eqjQifmUdIfCNalLeqvhkZpAjQkBXweRi3T7kBZr5GifjoneYJifWnackZbmeqeqiGaDeRyli30fbmeqcvn2ifackyfCifkya0kBfCeqcXY6oPhujogMiGlLg9YhneYhg9iGiGiGgkgkoPjQn2eqlLa0VdoPbNXYfChufCjobNeRhui3g9a0gkbmifSAifaceqhueRifZSb-mUmtfCZrb-lLYJbmjQfCdgjooncXhufC-1fbb-eRdgfbdgoPdgeRdIl8lLgMdgfbljkyljbmlLhuifeRfzg904L4fzfzgMbNkyYJZrcvkygMiGeRkBn2hVd5cXd5gMfbZrbNfzn2eRgMlLZrlLn2g9ljg9hVifnFd5nFonhunecXdgneSARPifl8iGfbYhkZkBfzneacnFyMYhjoa0fCjoaDgkd5iGkBeqmtnehub-eRnekZ2BaDkBlLd5eRgMkBljcvZrlj1Qy9ZSkZhubmhuifd5bNkykBcvpAa0onifnFdgfCjonFifbNMpjoaDhVkZfbQGmUfzjobmljfzeqgMiGmtjofCi3joRoeqdIpAb-a0d5dgi3cXfzeRljb-cXjofbmUmt&chxt=y,x&chxr=0,-54,112|1,0,991) Based on just 991 values. I could've crammed more values into it, but they would've distorted the result. This sample happens to be fairly typical. Edit 1: here are the above values for just one sixty-sided die, for comparison: ``` Median: 30.5 Arithmetic Mean: 30.5 Standard Deviation: 7.68114574787 Root Mean Square: 35.0737318611 ``` Note that these values are calculated, not experimental.
Calculate exact result of complex throw of two D30
[ "", "python", "math", "statistics", "puzzle", "" ]
I have a third-party library in my SVN repository and I'd like to associate source/javadoc with it locally in Eclipse. I.e., there should be some local setting (for example, an entry in the `local.properties` file) that associates the source/javadoc with the JAR file, but which doesn't introduce local dependencies into the repository via `.classpath`. Ideally I'd have ``` lib_src_dir = /my/path/to/lib/src ``` in `local.properties` and then ``` <classpathentry kind="lib" path="lib.jar" sourcepath="${lib_src_dir}"> ``` in `.classpath`. Can this be done? [EDIT] @VonC's answer is helpful... Is there a way to load Path Variables from a text file (e.g., `local.properties`) instead of going through Window -> Preferences -> General -> Workspace -> Linked Resources?
I believe this would be better achieved through: * the creation of a linked folder combined with * the declaration of a linked resource The linked resource defines a path variable which would be equals to `/my/path/to/lib/src` ![Eclipse Linked Resources](https://i.stack.imgur.com/YPlVi.jpg) The linked folder would refers to your linked resource ![Linked Resources](https://i.stack.imgur.com/cwywG.gif) (you can use a variable and not a fixed path, with the "Variable" button) The variable is actually always local (to one's workspace), and will be modified through the `Linked Resources` preference screen. The linked folder can also be... a linked *file*, thus allowing the reference of an archive through a relative path (relative to the variable). Then this linked file (here a linked archive) can be associated to your `classpathentry` in the "`source`" attribute. --- The problem with Linked Resources is they are local to the workspace, in the preferences. You can **export the preferences in a `[myPrefs.epf]` file**, and then trim the exported file in order to leave only the lines containing **`pathvariable`**: ``` /instance/org.eclipse.core.resources/pathvariable.MY_DIRECTORY=/my/path/to/lib/src ``` Anyone can then import this special preference file, which will only affect the "`Linked Resources`" part. **That solution is not very satisfying, since the `.epf` preference file can not be loaded automatically in the project**. When I setup a project with a linked resources defining a path, I always leave a big `README.txt` at the root of my project, in order to incite the user of said project to define that same linked resources with his/her own fixed local path. [Several bugs](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=advanced&short_desc_type=allwordssubstr&short_desc=relative+path+linked&long_desc_type=allwordssubstr&long_desc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=allwords&keywords=&resolution=FIXED&resolution=INVALID&resolution=WONTFIX&resolution=LATER&resolution=REMIND&resolution=DUPLICATE&resolution=WORKSFORME&resolution=MOVED&emailtype1=substring&email1=&emailtype2=substring&email2=&bugidtype=include&bug_id=&votes=&chfieldfrom=&chfieldto=Now&chfieldvalue=&cmdtype=doit&order=Reuse+same+sort+as+last+time&field0-0-0=noop&type0-0-0=noop&value0-0-0=) are in progress to enhance this situation or around the [Linked Resources topic](https://bugs.eclipse.org/bugs/buglist.cgi?quicksearch=LinkedResources). Especially: * [Exporting a project with linked resources](https://bugs.eclipse.org/bugs/show_bug.cgi?id=67329) * [Relative paths without variables](https://bugs.eclipse.org/bugs/show_bug.cgi?id=86607) * [Have linked resources relative to workspace paths](https://bugs.eclipse.org/bugs/show_bug.cgi?id=33957) * [Would like to use path relative to workspace root](https://bugs.eclipse.org/bugs/show_bug.cgi?id=29023) --- [DevByStarlight](https://stackoverflow.com/users/735533/devbystarlight) mentions in [the comments](https://stackoverflow.com/questions/300328/eclipse-attach-source-javadoc-to-a-library-via-a-local-property/300346?noredirect=1#comment22430417_300346) the project (not very active since Oct. 2011) [workspacemechanic](https://code.google.com/a/eclipselabs.org/p/workspacemechanic/). > The Workspace Mechanic automates maintenance of your Eclipse environment by tweaking preferences, adding extension locations, and so on. You can use it to: > > * Create a consistent environment among groups as large as the entire company, your local team, or even among your own many workspaces > * Save time setting up new workspaces > * Create tasks that ensure your favorite new preferences are applied to all your current and future workspaces. (This is one of our favorite features!) > > The key to the Workspace Mechanic's behavior is the **`Task`**. > A task describes a simple test and an action that, when run, changes the environment so the test will subsequently pass. > **`Tasks`** can come in many forms: preference files, Java classes, Groovy scripts and Eclipse extensions. You can easily define your own Tasks. It comes with a collection of scripts: * [workspace-mechanic](https://github.com/oschrenk/workspace-mechanic) * [workspacemechanic-settings](https://github.com/signed/workspacemechanic-settings)
I just figured out a simple answer to this (in Indigo) after working on it in the background and free moments for a couple of days. The easiest way I've found is to expand your project in the Project Explorer, go into your Referenced Libraries, right-click the appropriate referenced JAR and click Properties. In there you have the options to designate a JavaDocs location. Enter the location of the folder that contains index.html and packages-list, files that are part of the Javadocs. Piece of cake! The only problem I see so far is that I bet you need to do this in every projects that references that library.
Eclipse: Attach source/javadoc to a library via a local property
[ "", "java", "eclipse", "jar", "javadoc", "" ]
So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following **working** code: ``` class Test { private int privateInt; [...] public boolean equals(Object obj) { [...] Test t = (Test) obj; if ( t.privateInt == privateInt ) { [...] } } ``` t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public. So what is happening here? How is this called? **Where would somebody use this?** Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it? Generally, where can I find information about this? Thank you.
It's accessible from different instances of the same class. According to [this page](http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html) (bolding mine): > At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. **The private modifier specifies that the member can only be accessed in its own class.** For clarity I'll rewrite this line: ``` if ( t.privateInt == this.privateInt ) ``` We can agree that "this.privateInt" should be allowed: you are accessing it from within the instance of class Test that the message "equals" has been sent to. It's less clear that "t.privateInt" should be visible, because t is a separate instance of class Test and we are not executing inside its equals method. However java allows this since both objects (t and this) are of the same class Test and can see each others private members.
Mike's quite correct; you are confusing objects (instances of a class) with the class itself. The members are private to the *class*, not any particular *instance* of the class. I recall being just as surprised about this when I was new to Java.
Java Private Field Visibility
[ "", "java", "language-features", "visibility", "" ]
I made an html file called test.html then I navigated to it as "<http://site.com/test.html?test1=a>" but the textbox stayed blank. Why is this? Super simple code ``` <html> <head> <title>Test</title> </head> <body > <input type=text name="test1"> </body> </html> ```
The file should be a PHP file, so test.php. Then maybe something like this: ``` <html> <head> <title>Test</title> </head> <body> <input type="text" name="test1" value="<?php echo htmlspecialchars($_GET['test1'], ENT_QUOTES); ?>"> </body> </html> ``` The reason it stays blank in your example is because there is no PHP code to put the value into the field. It isn't automatic. Also, on most servers (but not always), a file with an .html extension will not be parsed by PHP. Also, passing it to the [htmlspecialchars](https://www.php.net/htmlspecialchars) function will help prevent [cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).
HTML is just another file extension to a webserver, it's not going to do any kind of processing unless you've done something to make that so. Would you expect to open <http://site.com/foo.txt?contents=helloworld> and see "helloworld" in the browser? I suggest you google up some tutorials (w3schools is usually good for this sort of thing) on PHP, then on "query strings" and how server side scripting works. You should be up and running with basic site scripting pretty fast.
Pass variable into an input
[ "", "php", "html", "" ]
I came across a problem in my current application that required fiddling with the query string in a base `Page` class (which all my pages inherit from) to solve the problem. Since some of my pages use the query string I was wondering if there is any class that provides clean and simple query string manipulation. Example of code: ``` // What happens if I want to future manipulate the query string elsewhere // (e.g. maybe rewrite when the request comes back in) // Or maybe the URL already has a query string (and the ? is invalid) Response.Redirect(Request.Path + "?ProductID=" + productId); ```
Use `HttpUtility.ParseQueryString`, as someone suggested (and then deleted). This will work, because the return value from that method is actually an `HttpValueCollection`, which inherits `NameValueCollection` (and is internal, you can't reference it directly). You can then set the names/values in the collection normally (including add/remove), and call `ToString` -- which will produce the finished querystring, because `HttpValueCollection` overrides `ToString` to reproduce an actual query string.
I was hoping to find a solution built into the framework but didn't. (those methods that are in the framework require to much work to make it simple and clean) After trying several alternatives I currently use the following extension method: (post a better solution or comment if you have one) ``` public static class UriExtensions { public static Uri AddQuery(this Uri uri, string name, string value) { string newUrl = uri.OriginalString; if (newUrl.EndsWith("&") || newUrl.EndsWith("?")) newUrl = string.Format("{0}{1}={2}", newUrl, name, value); else if (newUrl.Contains("?")) newUrl = string.Format("{0}&{1}={2}", newUrl, name, value); else newUrl = string.Format("{0}?{1}={2}", newUrl, name, value); return new Uri(newUrl); } } ``` This extension method makes for very clean redirection and uri manipulation: ``` Response.Redirect(Request.Url.AddQuery("ProductID", productId).ToString()); // Will generate a URL of www.google.com/search?q=asp.net var url = new Uri("www.google.com/search").AddQuery("q", "asp.net") ``` and will work for the following Url's: ``` "http://www.google.com/somepage" "http://www.google.com/somepage?" "http://www.google.com/somepage?OldQuery=Data" "http://www.google.com/somepage?OldQuery=Data&" ```
A clean way of generating QueryString parameters for web requests
[ "", "c#", ".net", "asp.net", "url", "" ]
How can you access and display the row index of a gridview item as the command argument in a buttonfield column button? ``` <gridview> <Columns> <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument=" ? ? ? " /> ..... ```
Here is a very simple way: ``` <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument='<%# Container.DataItemIndex %>' /> ```
[MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx) says that: > The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled. So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g. ``` protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e ) { int rowIndex = Convert.ToInt32( e.CommandArgument ); ... } ```
ASP.NET GridView RowIndex As CommandArgument
[ "", "c#", "asp.net", "gridview", "" ]
Background: I'm currently debugging an application written over a custom-built GUI framework in C++. I've managed to pin down most bugs, but the bugs I'm having the most trouble with tend to have a common theme. All of them seem to be to do with the screen refreshing, redrawing or updating to match provided data. This is a pain to debug, because I can't break on every refresh, and most of this stuff is time-sensitive, so breakpoints occasionally "fix" the bug. **Q: Does anyone have any tips for debugging Windows-based GUIs, especially regarding the refreshing of individual components?**
I agree with dual monitors or even remote debugging to reduce interfering with the messages. I also highly recommend Spy utilities. These let you see what messages are being sent in the system. One such program is Winspector. <http://www.windows-spy.com/>
This may not help, but I've found using dual monitors useful in this scenario. I have the debugger on one screen and the application on another. I can then step thru the code and see the application refreshing or doing whatever it is on the other screen. There is still issues with focus doing this way, but at least I can see when it repaints.
Debugging GUI Applications in C++
[ "", "c++", "debugging", "user-interface", "" ]
I have the following string: ``` <SEM>electric</SEM> cu <SEM>hello</SEM> rent <SEM>is<I>love</I>, <PARTITION />mind ``` I want to find the last "SEM" start tag before the "PARTITION" tag. not the SEM end tag but the start tag. The result should be: ``` <SEM>is <Im>love</Im>, <PARTITION /> ``` I have tried this regular expression: ``` <SEM>[^<]*<PARTITION[ ]/> ``` but it only works if the final "SEM" and "PARTITION" tags do not have any other tag between them. Any ideas?
And here's your goofy Regex!!! ``` (?=[\s\S]*?\<PARTITION)(?![\s\S]+?\<SEM\>)\<SEM\> ``` What that says is "While ahead somewhere is a PARTITION tag... but while ahead is NOT another SEM tag... match a SEM tag." Enjoy! Here's that regex broken down: ``` (?=[\s\S]*?\<PARTITION) means "While ahead somewhere is a PARTITION tag" (?![\s\S]+?\<SEM\>) means "While ahead somewhere is not a SEM tag" \<SEM\> means "Match a SEM tag" ```
Use [String.IndexOf](http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx) to find PARTITION and [String.LastIndexOf](http://msdn.microsoft.com/en-us/library/system.string.lastindexof.aspx) to find SEM? ``` int partitionIndex = text.IndexOf("<PARTITION"); int emIndex = text.LastIndexOf("<SEM>", partitionIndex); ```
Finding the last occurrence of a word
[ "", "c#", ".net", "regex", "" ]
Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?
I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter. <http://www.emacswiki.org/emacs/PythonMode#toc10> ``` (setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" "~/.emacs.d/pymacs/" "~/.emacs.d/ropemacs-0.6" ) load-path)) (setq py-shell-name "ipython") (defadvice py-execute-buffer (around python-keep-focus activate) "return focus to python code buffer" (save-excursion ad-do-it)) (setenv "PYMACS_PYTHON" "python2.5") (require 'pymacs) (pymacs-load "ropemacs" "rope-") (provide 'python-programming) ```
never used it myself, but I do follow the ipython mailing list, and there was a [thread](http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/thread.html) a couple months back. maybe this will help <http://lists.ipython.scipy.org/pipermail/ipython-user/2008-September/005791.html> It's also a very responsive mailing list if you run into trouble.
Emacs 23 and iPython
[ "", "python", "emacs", "ipython", "emacs23", "" ]
I have a page which has a rectangular area with text and icons in it and the whole thing is clickable. The anchor tag is set to display: block. One of the icons has an onclick handler. If a person clicks on an icon, I just want the icon's onclick handler to run and not to actually activate the containing anchor tag. Firefox behaves like I want, IE doesn't. So I tried to trap the event in the onclick handler: ``` function my_onclick_handler(evt){ if (!evt) evt = window.event; // ... handle the click if (evt.stopPropagation) evt.stopPropagation(); evt.cancelBubble = true; } ``` That didn't work so then I thought maybe it's actually the onmouseup or onmousedown events that trigger the anchor tag so I added a clickSwallow method to onmouseup and onmousedown methods: ``` function clickSwallow(evt){ if (!evt) evt = window.event; if (evt.stopPropagation) evt.stopPropagation(); evt.cancelBubble = true; } ``` That didn't work either. Any ideas how to keep the enclosing anchor from reacting to the click in this case?
I would just use a `<span>`, but I think returning `false` from the event handler should also do the trick.
[This post](http://www.openjs.com/articles/prevent_default_action/) has a few items yours doesn't (like e.returnValue and e.preventDefault) but from the text it appears those are FF specific functions. Might be worth a shot though.
Why can't I trap a mouse click in IE?
[ "", "javascript", "internet-explorer", "" ]
The *VS2008 SP1* documentation talks about **`std::tr1::mem_fun`**. So why, when I try and use **`std::tr1::mem_fun`**, why do I get this compile error?: ``` 'mem_fun' : is not a member of 'std::tr1' ``` At the same time, I can use **`std::tr1::function`** without problems. Here is the sample code I am trying to compile, which is supposed to call `TakesInt` on an instance of `Test`, via a `function<void (int)>`: ``` #include "stdafx.h" #include <iostream> #include <functional> #include <memory> struct Test { void TakesInt(int i) { std::cout << i; } }; void _tmain() { Test* t = new Test(); //error C2039: 'mem_fun' : is not a member of 'std::tr1' std::tr1::function<void (int)> f = std::tr1::bind(std::tr1::mem_fun(&Test::TakesInt), t); f(2); } ``` I'm trying to use the tr1 version of **`mem_fun`**, because when using **`std::mem_fun`** my code doesn't compile either! I can't tell from the compiler error whether the problem is with my code or whether it would be fixed by using tr1's **`mem_fun`**. That's C++ compiler errors for you (or maybe it's just me!). --- ## Update: Right. The answer is to spell it correctly as mem\_fn! However when I fix that, the code still doesn't compile. Here's the compiler error: ``` error C2562: 'std::tr1::_Callable_obj<_Ty,_Indirect>::_ApplyX' : 'void' function returning a value ```
Change it to this: ``` std::tr1::function<void (int)> f = std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1); f(2); ``` The binder requires the int argument. So you have to give it a placeholder which stands for the integer argument that the generated function object needs. Btw: I'm not sure whether you already know this or not. But you don't need that mem\_fn for this. Just change it to ``` std::tr1::function<void (int)> f = std::tr1::bind(&Test::TakesInt, t, std::tr1::placeholders::_1); f(2); ```
I am no expert on either TR1 or VS2008, but a quick googling suggests that the function you're looking for is std::tr1::mem\_fn instead. (At least, that's what Boost calls it in their [TR1 implementation](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_tr1/subject_list.html#boost_tr1.subject_list.mem_fn), and that's how it's detailed on [Wikipedia](http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1#mem_fn).) I'm not sure why you're getting a compile error with the old version of mem\_fun though. If you post the compiler's message about that, it might help us figure it out.
How do I use std::tr1::mem_fun in Visual Studio 2008 SP1?
[ "", "c++", "std", "tr1", "mem-fun", "" ]
I have a digital certificate that identifies a user. I need to use it to Digitally sign pdf files. Does anyone have an example that does not uses a third party component? I need to get this done but it would be nice to fully understand how things are done. C# Examples please :)
The open source [iTextSharp](http://itextsharp.sourceforge.net/) library will allow you to do this. Here's a [post](http://www.codeproject.com/Articles/14488/E-signing-PDF-documents-with-iTextSharp) explaining how to digitally sign a pdf file. If you don't want to use a third party library then you can implement it yourself but it could be a tough task -> you can start by reading the [pdf specification](http://www.adobe.com/devnet/acrobat/pdfs/PDF32000_2008.pdf) (8.6MB)
Proper PDF signing is a *very* sophisticated task. There exist a number of files that don't conform to the PDF specification (broken xrefs etc) and your code must handle all of them. Then various Acrobat versions treat certain things in signed fields differently. So if you need to do the task (rather than study how it works) you should rely on third-party solution, such as our [PDFBlackbox](http://www.eldos.com/sbbdev/net-pdf.php) components.
Digitally sign PDF files
[ "", "c#", "pdf", "digital-signature", "" ]
I have an enum ``` public enum FileExtentions { mp3, mpeg } ``` And I have a FileInfo of which I want to check if the extension is in the previous enum. I was hoping I could do a ``` FileExtensions.Any(e=>e.ToString().Equals(file.Extension)); ``` But that would have been too awesome. Any ideas?
What's the reason behind `Any` … `Equals`? Did you overlook `Contains`? ``` bool result = Enum.GetNames(typeof(FileExtensions)).Contains("mp3"); ```
While pressing submit I thought of the answer myself: ``` Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension)) ```
Check if an enum has a field that equals a string
[ "", "c#", "enums", "" ]
Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.). I also want to be able to define a transparent color (not alpha channel) for this image. **The GdiPlus solution seems to be limited to images of width divisible by 4**. Anything else fails during the call to Save(). Does anyone know the reason for this limitation and how/whether I can work around it? **Update: Bounty** I'm starting a bounty (I really want this to work). I implemented the GDI+ solution, but as I said, it's limited to images with quad width. The bounty will go to anyone who can solve this width issue (without changing the image dimensions), or can offer an alternative non-GDI+ solution that works.
I read and write PNGs using [libpng](http://www.libpng.org/pub/png/libpng.html) and it seems to deal with everthing I throw at it (I've used it in unit-tests with things like 257x255 images and they cause no trouble). I believe the [API](http://www.libpng.org/pub/png/libpng-1.2.5-manual.html) is flexible enough to not be tied to file I/O (or at least you can override its default behaviour e.g see `png_set_write_fn` in section on [customization](http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-5)) In practice I always use it via the much cleaner [boost::gil](http://www.boost.org/doc/libs/1_38_0/libs/gil/doc/index.html) [PNG IO extension](http://stlab.adobe.com/gil/html/group___p_n_g___i_o.html), but unfortunately that takes `char*` filenames and if you dig into it the `png_writer` and `file_mgr` classes in its implementation it seem pretty tied to `FILE*` (although if you were on Linux a version using fmemopen and in-memory buffers could probably be cooked up quite easily).
[LodePNG](https://lodev.org/lodepng/) ([GitHub](https://github.com/lvandeve/lodepng)) is a lib-less PNG encoder/decoder.
Convert bitmap to PNG in-memory in C++ (win32)
[ "", "c++", "winapi", "png", "" ]
What is the best way to limit the amount of text that a user can enter into a 'textarea' field on a web page? The application in question is ASP .NET, but a platform agnostic answer is preferred. I understand that some amount of javascript is likely needed to get this done as I do not wish to actually perform the 'post' with that amount of data if possible as ASP .NET does have an upper limit to the size of the request that it will service (though I don't know what that is exactly). So maybe the real question is, what's the best way to do this in javascript that will meet the following criteria: -Must work equally well for both users simply typing data and copy/paste'ing data in from another source. -Must be as '508 compliance' friendly as possible.
use a RegularExpressionValidator Control in ASP.Net to validate number of character along with with usual validation
``` function limit(element, max_chars) { if(element.value.length > max_chars) element.value = element.value.substr(0, max_chars); } ``` As javascript, and... ``` <textarea onkeyup="javascript:limit(this, 80)"></textarea> ``` As XHTML. Replace 80 with your desired limit. This is how I do it anyway. Note that this will prevent the user from typing past the limit in the textbox, however the user could still bypass this using javascript of their own. To make sure, you must also check with your server side language.
What is the best way to limit the amount of text that can be entered into a 'textarea'?
[ "", "asp.net", "javascript", "html", "" ]
I have an ATL control that I want to be Unicode-aware. I added a message handler for WM\_UNICHAR: ``` MESSAGE_HANDLER( WM_UNICHAR, OnUniChar ) ``` But, for some reason, the OnUniChar handler is never called. According to the documentation, the handler should first be called with "UNICODE\_NOCHAR", on which the handler should return TRUE if you want to receive UTF-32 characters. But, as I said, the handler is never called. Is there anything special that needs to be done to activate this?
What are you doing that you think should generate a WM\_UNICHAR message? If your code (or the ATL code) ultimately calls CreateWindowW, then your window is already Unicode aware, and WM\_CHAR messages will be UTF-16 format. The documentation is far from clear on when, exactly, a WM\_UNICHAR message gets generated, but from what I can gather in very limited poking around on Google Groups and on the Internet it looks like it gets sent by 3rd party apps and not by Windows itself, unless the Window is an ANSI window (CreateWindowA and all that). Have you tried manually sending a WM\_UNICHAR message to your window to see what happens? If you get the message then there's nothing wrong with your message dispatch code and there's just nothing happening that would cause WM\_UNICHAR. You can also check with Spy++ and see whether you're getting that message, though I suspect it's just not being sent.
My experience today is that Spy++ does not give correct results for WM\_CHAR in a Unicode proc. I am getting ASCII translations or '?' showing in the Messages list, even if I view Raw (not Decoded) arguments. The debugger shows wParam to be the Unicode code point though.
Why is my WM_UNICHAR handler never called?
[ "", "c++", "com", "unicode", "atl", "" ]
I want to get a list of all Django auth user with a specific permission group, something like this: ``` user_dict = { 'queryset': User.objects.filter(permisson='blogger') } ``` I cannot find out how to do this. How are the permissions groups saved in the user model?
If you want to get list of users by permission, look at this variant: ``` from django.contrib.auth.models import User, Permission from django.db.models import Q perm = Permission.objects.get(codename='blogger') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() ```
This would be the easiest ``` from django.contrib.auth import models group = models.Group.objects.get(name='blogger') users = group.user_set.all() ```
How to get a list of all users with a specific permission group in Django
[ "", "python", "django", "dictionary", "permissions", "" ]
``` <?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; echo preg_replace($patterns, $replacements, $string); ?> ``` Ok guys, Now I have the above code. It just works well. Now for example I'd like to also replace "lazy" and "dog" with "slow" What I have to do now is would look like this, right? ``` <?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $patterns[3] = '/lazy/'; $patterns[4] = '/dog/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; $replacements[3] = 'slow'; $replacements[4] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?> ``` Ok. So my question is, is there any way I can do like this ``` $patterns[0] = '/quick/', '/lazy/', '/dog/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements[0] = 'slow'; $replacements[1] = 'black'; $replacements[2] = 'bear'; ``` Thanks
You can use pipes for ["Alternation"](http://perldoc.perl.org/perlre.html#Regular-Expressions): ``` $patterns[0] = '/quick|lazy|dog/'; ```
why not use str\_replace ? ``` $output = str_replace(array('quick', 'brown', 'fox'), array('lazy', 'white', 'rabbit'), $input) ```
multi words PHP arrays replacement
[ "", "php", "arrays", "" ]
I have data bound `DataGridView` in a desktop app with columns that have their `ToolTipText` property set, yet no tool tip is displayed when I hover over grid view (cells or cell headers). The `ShowCellToolTips` property of the grid view is `true`, and I have verified using break points that it is not changed programmatically before I mouse over. I have tried creating a `CellToolTipTextNeeded` event handler to see what the tool tip text was, but the event handler is never called. Is there anything I have missed? Thanks, Rob **Edit:** We're using framework 2.0.
We ended up using a ToolTip widget and the `CellMouseEnter`, `CellMouseLeave` events to show it appropriately. Not optimal, but it works around the odd behaviour we were experiencing.
It appears from your question that you set the tooltip text of the columns. Columns tooltip text only appears when floating over the headers. To show tooltip text on the cells you have to hookup the `CellToolTipTextNeeded` event and set the value of `e.ToolTipText` in the event args
DataGridView ToolTipText not showing
[ "", "c#", "visual-studio", "visual-studio-2008", "datagridview", "desktop-application", "" ]
How can I change `CSS` from `javascript`. I'm using `jQuery-ui Dialog` and I want to change the style of a `DIV` from javascript. Thanks
Check out [the jQuery documentation](http://docs.jquery.com/CSS/css). If you want anything it will be there. Anyhow, if you want to add styles to elements, you need to use the `css` function, which has a few variants. ``` $(selector).css(properties); // option 1 $(selector).css(name, value); // option 2 ``` So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do ``` $("div#mydiv").css({'background-color' : 'red'}); // option 1 $("div#mydiv").css('background-color','red'); // option 2 ``` The first way is easier if you're setting multiple things at once. If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value. ``` var color = $("div#mydiv").css('background-color'); ``` Would make the var `color` be `red` if you already set it above, for example. You can also add and remove classes, doing something like ``` $(selector).addClass(class_name); $(selector).removeClass(class_name); ```
*This answer works even without jQuery.* So you have something like this: ``` <style type="text/css"> .foo { color: Red; } .bar { color: Blue; } </style> <div class="foo" id="redtext"> some red text here </div> ``` If you wish to change just some attributes, you can always find the element using ``` var div = document.getElementById('redtext'); ``` function and then change the attached color style by ``` div.style.color = 'Green'; ``` Making your red text appear in green instead. If you want to change the class defined for the div to another style class, you can do: ``` div.className = 'bar'; ``` making the div now use class bar, which makes your previously green text blue.
How to change css properties of html elements using javascript or jquery
[ "", "javascript", "jquery", "css", "jquery-ui", "jquery-ui-dialog", "" ]
In my C# winforms app, I have a datagrid. When the datagrid reloads, I want to set the scrollbar back to where the user had it set. How can I do this? EDIT: I'm using the old winforms DataGrid control, not the newer DataGridView
You don't actually interact directly with the scrollbar, rather you set the `FirstDisplayedScrollingRowIndex`. So before it reloads, capture that index, once it's reloaded, reset it to that index. **EDIT:** Good point in the comment. If you're using a `DataGridView` then this will work. If you're using the old `DataGrid` then the easiest way to do that is to inherit from it. See here: [Linkage](http://www.thescarms.com/dotnet/ScrollDataGrid.aspx) The DataGrid has a protected GridVScrolled method that can be used to scroll the grid to a specific row. To use it, derive a new grid from the DataGrid and add a ScrollToRow method. **C# code** ``` public void ScrollToRow(int theRow) { // // Expose the protected GridVScrolled method allowing you // to programmatically scroll the grid to a particular row. // if (DataSource != null) { GridVScrolled(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)); } } ```
Yep, definitely [FirstDisplayedScrollingRowIndex](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.firstdisplayedscrollingrowindex.aspx). You'll need to capture this value after some user interaction, and then after the grid reloads you'll want to set it back to the old value. For instance, if the reload is triggered by the click of a button, then in the button click handler, you might want to have as your first line a command that places this value into a variable: ``` // Get current user scroll position int scrollPosition = myGridView.FirstDisplayedScrollingRowIndex; // Do some work ... // Rebind the grid and reset scrolling myGridView.DataBind; myGridView.FirstDisplayedScrollingRowIndex = scrollPosition; ```
How can I set the position of my datagrid scrollbar in my winforms app?
[ "", "c#", "winforms", "datagrid", "" ]
I want to exceute a simple command which works from the shell but doesn't work from Java. This is the command I want to execute, which works fine: ``` soffice -headless "-accept=socket,host=localhost,port=8100;urp;" ``` This is the code I am excecuting from Java trying to run this command: ``` String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""}; Process process = Runtime.getRuntime().exec(commands) int code = process.waitFor(); if(code == 0) System.out.println("Commands executed successfully"); ``` When I run this program I get "Commands executed successfully". However the process is not running when the program finishes. Is it possible that the JVM kills the program after it has run? Why doesn't this work?
I would like to say how I solved this. I created a sh script that basically run the command of soffice for me. Then from Java I just run the script, and it works fine, like this: ``` public void startSOfficeService() throws InterruptedException, IOException { //First we need to check if the soffice process is running String commands = "pgrep soffice"; Process process = Runtime.getRuntime().exec(commands); //Need to wait for this command to execute int code = process.waitFor(); //If we get anything back from readLine, then we know the process is running BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); if (in.readLine() == null) { //Nothing back, then we should execute the process process = Runtime.getRuntime().exec("/etc/init.d/soffice.sh"); code = process.waitFor(); log.debug("soffice script started"); } else { log.debug("soffice script is already running"); } in.close(); } ``` I also kill the soffice process by calling this method: ``` public void killSOfficeProcess() throws IOException { if (System.getProperty("os.name").matches(("(?i).*Linux.*"))) { Runtime.getRuntime().exec("pkill soffice"); } } ``` Note that this only works in Linux.
I'm not sure if I'm not mistaken, but as far as I see you're generating the commands but never passing them to the "execute" method... you're executing "". Try using Runtime.getRuntime().exec(commands) =)
Problem with starting OpenOffice service (soffice) from Java (command working in commandline, but not from Java)
[ "", "java", "command", "openoffice.org", "runtime.exec", "soffice", "" ]
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is: ``` "$C/test/testing" ``` What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names. Is there a specific command I'm missing, or do I have to take `os.environ.keys()` and manually replace the strings?
Use [os.path.expandvars](http://docs.python.org/library/os.path.html#os.path.expandvars) to expand the environment variables in the string, for example: ``` >>> os.path.expandvars('$C/test/testing') '/stackoverflow/test/testing' ```
In Python 3 you can do: ``` '{VAR}'.format(**os.environ)) ``` for example ``` >>> 'hello from {PWD}'.format(**os.environ)) hello from /Users/william ```
How to evaluate environment variables into a string in Python?
[ "", "python", "filesystems", "environment-variables", "" ]
I am trying to write operator overload for custom class and don't know how to handle null comparison. ``` Class Customer { int id; public static bool operator ==(Customer a, Customer b) { //When both a and b are null don't know how to compare as can't use == in here as //it will fall into loop } } ``` Problem is when a and b both are null result is true but not sure how to check it without using ==.
``` if (Object.ReferenceEquals(a,b)) return true; ``` ReferenceEquals() checks if they are pointing to the exact same object (or if they are both null) (As a general rule, it's good to start an Equals() method with a call to ReferenceEquals, particularly if the rest of the method is complicated. It will make things like `a==a` quickly return true, instead of having to check every element.)
I'm not 100% sure I understand the problem, but you should be able to do: ``` if (((object)a == null) && ((object)b == null)) { return true; } ``` Without any problems.
operator overload problem
[ "", "c#", ".net", "" ]
Extension method is a really helpful feature that you can add a lot of functions you want in any class. But I am wondering if there is any disadvantage that might bring troubles to me. Any comments or suggestions?
* The way that extension methods are imported (i.e. a whole namespace at a time) isn't granular. You can't import one extension from a namespace without getting all the rest. * It's not immediately obvious from the source code where the method is defined. This is also an *advantage* - it means you can make your code look consistent with the rest of the methods on the type, even if you can't put it in the same place for whatever reason. In other words, the code is simpler to understand at a high level, but more complicated in terms of *exactly* what's being executed. I'd argue this is true of LINQ in general, too. * You can only have extension methods, not properties, indexers, operators, constructors etc. * If you're extending a 3rd party class and in a later version they introduce a new method with the same signature, you won't easily know that the meaning of your calling code has changed. If the new method is very *similar* to your extension, but with subtly different boundary conditions (or whatever) then this could lead to some very tricky bugs. It's relatively unlikely to happen though.
Couple of things: * It's not always clear as to where the extension method comes from unless you are inside VS.NET * Extension methods can't be resolved via reflection or C# 4.0's dynamic lookup
Disadvantages of extension methods?
[ "", "c#", "extension-methods", "" ]
How can I remove duplicate values from a multi-dimensional array in PHP? Example array: ``` Array ( [0] => Array ( [0] => abc [1] => def ) [1] => Array ( [0] => ghi [1] => jkl ) [2] => Array ( [0] => mno [1] => pql ) [3] => Array ( [0] => abc [1] => def ) [4] => Array ( [0] => ghi [1] => jkl ) [5] => Array ( [0] => mno [1] => pql ) ) ```
Here is another way. No intermediate variables are saved. We used this to de-duplicate results from a variety of overlapping queries. ``` $input = array_map("unserialize", array_unique(array_map("serialize", $input))); ```
Since 5.2.9 you can use [`array_unique()`](https://secure.php.net/manual/en/function.array-unique.php) if you use the `SORT_REGULAR` flag like so: ``` array_unique($array, SORT_REGULAR); ``` This makes the function compare elements for equality as if `$a == $b` were being used, which is perfect for your case. **Output** ``` Array ( [0] => Array ( [0] => abc [1] => def ) [1] => Array ( [0] => ghi [1] => jkl ) [2] => Array ( [0] => mno [1] => pql ) ) ``` Keep in mind, though, that [the documentation](https://secure.php.net/manual/en/function.array-unique.php#refsect1-function.array-unique-notes) states: > `array_unique()` is not intended to work on multi dimensional arrays.
How to remove duplicate values from a multi-dimensional array in PHP
[ "", "php", "arrays", "duplicate-data", "" ]
So, I've had a fair amount of experience programming database driven web apps using php and coldfusion (not together, at different times) and I'm starting to look into the asp.net world (I have a project coming up at work that is all asp.net/c#.) My question is: there seems to be *a lot* of stuff to get mired in and if I'm just making web-based applications (mostly CRUD-type stuff - no mind-bending logic) what are the topics I should be focusing on? I just don't want to go down the rabbit trail of something to find out later that it's not really used too much by the development community. In reading some books (ASP.net 3.5 step by step and ASP.net 3.5 unleashed) I'm finding some area's where a topic will be explained but at the end of the chapter it'll say "this stuff is cool but not for use in multi-tiered applications..." The topics I've looked at so far (that seem to differ greatly from the applications I'm used to building) are: * Master pages * DataBinding * Linq to SQL * ASP.NET MVC * Templates and databinding expressions * asp.net controls
Good question! I'm assuming that you can pick up the C# syntax as you go so I'll focus on the big picture. To get started with a WebForms application, you *must* understand the page lifecycle and the application lifecycle. This is your first priority. The model used by ASP.NET is based on Windows form-based programming and this has implications for how you think about the entire software production process. Now, I'm assuming that you will be building a WebForms application because WebForms technology (in ASP.NET) is more mature, has better third-party support and has far more documentation. If you are inclined to MVC, then just keep in mind that a good design will be one or the other - MVC isn't a part of WebForms, it is an alternative to it. Next, you have some decisions. Will you be using standard data access (e.g. SQLClient) tools, rolling your own data access layer (or using DAL), or using linq to SQL? I say "decisions" because everyone on the team will have to be together on this one. I heartily recommend building a DAL as you can optimize it for your needs. Linq is nice as well but there are some [ominous clouds on the horizon](http://vistadb.net/blog/news/microsoft-killing-linq-to-sql/). Coordinate, decide and stay with it. While not mandatory, you should seriously consider building your Business Logic in a separate Class Library (DLL). Visual Studio / ASP.NET make it trivially easy to create your own Class Library and to fold it into your solution. Learn how to do this and you'll be a better developer for years. People usually argue for this on the basis that it will insulate your UI from your data access. While true, that isn't really the advantage - the advantage comes down the road when you are ready to learn and do Unit testing. Just start out with the assumption that you'll split UI from logic and you'll thank me down the road. At this point, you can (A) build web pages and (B) show dynamic, database-based content in them. Make sure that you master the GridView and the ObjectDataSource objects used to fill them. Note: the ObjectDataSource is what shuttles data from your Business Class Library to your UI. If you don't use a Business Layer, then you'll use SQLDataSource or LinqDataSource objects to access your data directly from the UI. Don't be settling on your architecture yet! You now need to decide whether you want to use Microsoft's WebParts, Login and Navigation components. These lock you in to a specific approach to site navigation, UI, etc. but can save you loads of time if appropriate. Once you know if you'll be using these and you have had a chance to get used to them, then I would recommend getting familiar with Master Pages. I use them extensively and they are great for standardizing the overall look and feel of the site. Finally, every professional ASP.NET developer must derive their own Page class (e.g. "MyPageClass") so that they can encapsulate common actions at the Page level. For example, I've built a session management object so that I can access all of my commonly-used session variables in a type-safe manner. The derived page class is responsible for providing the sessionObj instance so that *every* page can access it without any additional work. Now you are ready to begin building an enterprise class web app!
Design an application. What you *need* to know should bubble up to the top fairly quickly.
I'm new to .NET - what should I concentrate on and what should I ignore?
[ "", "c#", ".net", "data-binding", "master-pages", "" ]
``` class Ball: a = [] def __init__(self): pass def add(self,thing): self.a.append(thing) def size(self): print len(self.a) for i in range(3): foo = Ball() foo.add(1) foo.add(2) foo.size() ``` I would expect a return of : ``` 2 2 2 ``` But I get : ``` 2 4 6 ``` Why is this? I've found that by doing a=[] in the **init**, I can route around this behavior, but I'm less than clear why.
*doh* I just figured out why. In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the **init** block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances. Whoa. One question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable?
What you probably want to do is: ``` class Ball: def __init__(self): self.a = [] ``` If you use just `a = []`, it creates a local variable in the `__init__` function, which disappears when the function returns. Assigning to `self.a` makes it an instance variable which is what you're after. For a semi-related gotcha, see how you can [change the value of default parameters for future callers](https://stackoverflow.com/questions/146329/what-is-the-worst-gotcha-youve-experienced#147877).
Why do new instances of a class share members with other instances?
[ "", "python", "scope", "mutable", "" ]
I am having a frame-based webpage with 3 frames. A topliner, a navigation on the left side and a content frame on the bottom right side. Now, I want to show up a popup-menu when the user right-clicks on the content-frame. Because a div-container can not go out of the frame, my idea was, placing the whole frame-page into a new iframe. In that page I could have a second iframe which is my popup-menu. So now, I am having this layout: ``` <html> (start-page) <iframe (real content) <frameset top-frame navigation-frame content-frame > > <iframe> (my popup-menu, positioned absolutelly and hidden by default) </html> ``` In my content-frame I am having a "onmouseover"-event assigned to the body-tag. This event should open the popup-iframe at the current mouse-position. And exactly here is my problem: How to get the mouse-coordinates relativelly to the top-website (start-page in my draft)? Currently I am having this mouseDown-function (works in IE only, right now - but getting it working in FF & Co shouldn't be the problem...) ``` function mouseDown(e) { if (window.event.button === 2 || window.event.which === 3) { top.popupFrame.style.left = event.screenX + "px"; top.popupFrame.style.top = event.screenY + "px"; top.popupFrame.style.display = ""; return false; } } ``` As you can see, the "event.screenX" and "screenY" - variables are not that variables I can use, because they are not relative to the mainpage. Any ideas?
If you are only planning to support IE - you can try using a new modal window by calling window.showModalDialog. You can position the new window anywhere on the screen. There are many drawbacks to using a new window in general and a modal one at that... By the way - FF 3 and up also [supports window.showModalDialog](https://developer.mozilla.org/en/DOM/window.showModalDialog)
You say it's an enterprise application - do you have to support all major browser, or is IE enough? I'm asking this because IE has a function that works exactly like you need: ``` window.createPopup(...) ``` <http://msdn.microsoft.com/en-us/library/ms536392(VS.85).aspx> The pop-up will be visible even outside the browser window! :-) To show it, use the .show(...) method which accepts position and size arguments (refer to MSDN for details). The nice thing is, you can also pass a reference to a page element relative to which the position is relative to, so you can easily position the popup relative to a certain page element, certain frame, certain browser window or even relatively to the desktop.
Frame position in JavaScript
[ "", "javascript", "popup", "frame", "mouse-position", "" ]
The comment to [this answer](https://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int#200099) got me wondering. I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension. Am I wrong about that? Is it possible to write a valid C program that is not valid C++ code? EDIT: This is really similar to, but not an exact duplicate of [this question](https://stackoverflow.com/questions/145096/is-c-actually-a-superset-of-c#145098).
In general, yes C code is considered C++ code. But C is not a proper subset in a strict sense. There are a couple of exceptions. Here are some valid things in C that are not valid in C++: ``` int *new;//<-- new is not a keyword in C char *p = malloc(1024); //void * to char* without cast ``` There are more examples too, but you get the idea. I previously wrote a more extensive answer in a similar question [here](https://stackoverflow.com/questions/145096/is-c-actually-a-superset-of-c#145098).
Also note that C99 adds several features which aren't permitted in C++ (or are only supported using vendor extensions), such as builtin `_Complex` and `_Imaginary` data types, variable-length arrays (arrays sized at runtime rather than compile time), flexible array members (arrays declared as the last member of a struct that may contain an unspecified number of elements), and more. For the exhaustive list of incompatibilities between C and C++, including changes with C99, see <http://david.tribble.com/text/cdiffs.htm>.
Is C code still considered C++?
[ "", "c++", "c", "" ]
I develop tools in Autodesk Maya. Many of the tools I build have simple windowed GUIs for the animators and modellers to use. These GUIs often contain what you'd normally expect to see in any basic window; labels, lists, menus, buttons, textfields, etc. However, there are limitations to the complexity of the UIs you can build with the available tools, specifically in the types of available widgets. I'm interested in using some of the more advanced wxPython widgets such as the ListView (grid), Tree, etc. This would involve using a complete wxFrame (window) to display the whole UI, which would essentially mean that window would no longer be tied to Maya. Not a deal breaker, but it means when Maya is minimized, the window won't follow suit. I've tried something like this before with tkinter as a test, but found that it needed a MainLoop to run in its own thread. This is logical, but in my case, it conflicts with Maya's own thread, essentially making Maya hang until the window is closed. This is due to the fact that Maya runs all scripts, be they MEL or Python, in a single thread that the main Maya GUI shares. This is to prevent one script from, say, deleting an object while another script is trying to do work on the same object. wxPython has this same "mainloop" methodolgy. I'm wondering if there's any way around it so that it can work within Maya?
I'm not sure if this is germane, but some googling turns up that PyQt is pretty popular inside of Maya. You could try the technique [here](http://www.highend3d.com/boards/lofiversion/index.php/t236041.html) or [here](http://www.highend3d.com/boards/index.php?showtopic=242116) (explained [here](http://groups.google.com/group/xsi_list/msg/dd500eb2420f3417?) with source code) of creating a new threadloop via Maya and executing inside of that. It seems Maya has a module included that sets up a new thread object, with a QApplication inside it: ``` def initializePumpThread(): global pumpedThread global app if pumpedThread == None: app = QtGui.QApplication(sys.argv) pumpedThread = threading.Thread(target = pumpQt, args = ()) pumpedThread.start() ``` and then sets up a function to process the Qt events: ``` def pumpQt(): global app def processor(): app.processEvents() while 1: time.sleep(0.01) utils.executeDeferred( processor ) ``` You can probably do something similar with wxPython as well. (utils.executeDeferred is a Maya function.) Be sure to check out how to create a [non-blocking GUI](http://wiki.wxpython.org/Non-Blocking%20Gui) on the wxPython wiki. Instead of processEvents(), you'll want to set up an event loop and check for "Pending" events inside the (hopefully renamed?) pumpQt function above. (The wxPython source has a [Python implementation](http://cvs.wxwidgets.org/viewcvs.cgi/wxWidgets/wxPython/samples/mainloop/mainloop.py) of MainLoop.) Likely this should be done through the app.Yield() function, but I'm not sure. ``` def pumpWx(): global app def processor(): app.Yield(True) while 1: time.sleep(0.01) utils.executeDeferred( processor ) def initializePumpThread(): global pumpedThread global app if pumpedThread == None: app = wx.App(False) pumpedThread = threading.Thread(target = pumpWx, args = ()) pumpedThread.start() ``` The wxPython docs [indicate SafeYield()](http://www.wxpython.org/docs/api/wx-module.html#SafeYield) is preferred. Again, this seems like it could be a first step, but I'm not sure it will work and not just crash horribly. (There's some discussion about what you want to do on the [wxPython mailing list](http://www.nabble.com/app.MainLoop-vs.-Pending-Dispatch-td17921845.html) but it's from a few minor versions of wx ago.) There is also some indication in various forums that this technique causes problems with keyboard input. You might also try doing: ``` def processor(): while app.Pending(): app.Dispatch() ``` to deal with the current list of events. Good luck!
I don't know if there is a way around a mainloop for the gui, since it is needed to handle all event chains and redraw queues. But there are several means of inter-process communication, like pipes or semaphores. Maybe it is an option to split your Maya extension into the actual plugin, being tight into maya, and a separate application for the gui. These two could use such means to communicate and exchange model information between plugin and gui. I'm not sure, however, if I can really recommend this approach because it very much complicates the application. You could have a look at IPython, an interactive Python shell, whose dev team has put some effort into integrating it with wxPython. They have some way of interrupting the event loop and hooking into it to do their own stuff.
Using external GUI libraries to make user interfaces in Autodesk Maya
[ "", "python", "scripting", "wxpython", "wxwidgets", "maya", "" ]
Is there a widely accepted class for dealing with URLs in PHP? Things like: getting/changing parts of an existing URL (e.g. path, scheme, etc), resolving relative paths from a base URL. Kind of like a two-way [parse\_url()](http://php.net/parse_url), encapsulated with a bunch of handy functions. Does something like this exist?
You've got the [Net\_URL2](http://pear.php.net/package/Net_URL2/docs) package over at PEAR, which appears to have replaced the [original Net\_URL](http://pear.php.net/package/Net_URL/docs). I have no first hand experience with it, but I'll almost always take a PEAR package over "random library found on website".
This **[URL.php class](http://www.phpclasses.org/browse/file/3008.html)** may be a good start (not sure it is 'widely' accepted though). > URL class intended for http and https schemes > > This class allows you store absolute or relative URLs and access it's various parts (scheme, host, port, part, query, fragment). > > It will also accept and attempt to resolve a relative URL against an absolute URL already stored. > > Note: this URL class is based on the HTTP scheme. > > Example: ``` $url =& new URL('http://www.domain.com/path/file.php?query=blah'); echo $url->get_scheme(),"\n"; // http echo $url->get_host(),"\n"; // www.domain.com echo $url->get_path(),"\n"; // /path/file.php echo $url->get_query(),"\n"; // query=blah // Setting a relative URL against our existing URL $url->set_relative('../great.php'); echo $url->as_string(); // http://www.domain.com/great.php ```
Is there a good pre-existing class for dealing with URLs in PHP?
[ "", "php", "url", "" ]
I have the following table ``` custid ordid qty datesold 1 A2 12 2008-01-05 2 A5 5 2008-01-02 1 A1 5 2008-01-01 2 A7 3 2007-02-05 ``` What't the best way of getting the previous order for every customer? Thanks
If by "previous" you mean "the one before the latest": ``` SELECT TOP 1 ordid FROM orders WHERE custid = @custid and datesold < (SELECT MAX(datesold) FROM orders i where i.custid = orders.custid) ORDER BY datesold DESC ``` Of course `datesold` has to be a DATETIME with distinct enough values for this to work. A date alone will not be enough. If you have a record created date for example, this would be a good substitution for `datesold`.
A common solution for this kind of problem is to choose the Max(datesold) and get the latest that way. This is ok if the custid/datesold combination is unique, but if there were two orders on the same day, it can cause duplicates. If you have SQL 2005 or higher, you can use the Row\_Number function to rank each customers orders and select the first one for each: ``` SELECT custid, ordid, qty, datesold FROM ( SELECT *, Row_Number() OVER (PARTITION BY custid ORDER BY datesold desc) as 'Rank' FROM tbl ) WHERE Rank = 1 ``` To make sure it always picks the same item, even if they have the same datesold, add some more items (such as RowID, recieptNumber) into the ORDER BY clause of the Row\_number. If you don't have SQL 2005, by adding identity column can do similar things: ``` SELECT custid, ordid, qty, datesold FROM tbl WHERE id = (SELECT TOP 1 id FROM tbl a WHERE custid = a.custID ORDER BY dateSold) ``` The downside of this is that there will be a table lookup at least for every customer if not every row. If you are lucky you want to get the latest order processed, you could: ``` SELECT custid, ordid, qty, datesold FROM tbl INNER JOIN ( SELECT a.id FROM tbl a GROUP BY tbl.custId ) s ON tbl.id = s.id ```
SQL Query Advice - Get Previous Customer Order
[ "", "sql", "sql-server", "" ]
I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this. Let me elaborate with a hypothetical situation: I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'. Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one. How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks. edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under `if __name__ == '__main__':`, which from what I've read does not play with relative imports: * <http://mail.python.org/pipermail/python-list/2006-October/408945.html> * <http://www.velocityreviews.com/forums/t502905-relative-import-broken.html> The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities? edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.
Maybe I'm not understanding correctly, but it seems that git would *be* the solution here, since git's branches don't need separate paths. Create a branch for each working version of your eggs module. Then when you checkout that branch, the entire module is changed to a state matching the version of your sub-module. You could then merge what you need back and forth between the branches. And as S.Lott pointed out, may a little refactoring couldn't hurt either ;)
[Relative imports](http://www.python.org/doc/2.5.2/tut/node8.html#SECTION008420000000000000000) ([PEP 328](http://www.python.org/dev/peps/pep-0328/)) might help: ``` eggs/ __init__.py foo.py bar.py # foo.py from __future__ import absolute_import from . import bar ``` See [How do you organize Python modules?](https://stackoverflow.com/questions/171785/how-do-you-organize-python-modules) for other options. EDIT: Yet another option is to use S.Lott's and Jim's suggestions i.e, restructure your package to factor out a `eggs.foo` part used by `eggs.bar.a` and use `git` to work on experimental branches (see [Git Community Book](http://book.git-scm.com/)). Here's an example: ``` $ git status # On branch master nothing to commit (working directory clean) ``` [just to make sure that all is good] ``` $ git checkout -b experimental Switched to a new branch "experimental" ``` [work on experimental stuff] ``` $ git commit -a ``` [commit to experimental branch] ``` $ git checkout master Switched to branch "master" ``` [work on master branch] ``` $ git commit -a ``` To merge changes into master branch: ``` $ git merge experimental ``` See chapter [Basic Branching and Merging](http://book.git-scm.com/3_basic_branching_and_merging.html) from the above book.
How do I work with multiple git branches of a python module?
[ "", "python", "git", "module", "" ]
I was thinking along the lines of using `typeid()` but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)
You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help. I am assuming you have a situation like this: ``` class Base; class A : public Base {...}; class B : public Base {...}; void foo(Base *p) { if(/* p is A */) /* do X */ else /* do Y */ } ``` If this is what you have, then try to do something like this: ``` class Base { virtual void bar() = 0; }; class A : public Base { void bar() {/* do X */} }; class B : public Base { void bar() {/* do Y */} }; void foo(Base *p) { p->bar(); } ``` **Edit:** Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). [Uncle Bob](http://www.objectmentor.com/omTeam/martin_r.html) calls this an "[anathema to Object Oriented Design](http://www.objectmentor.com/resources/articles/lsp.pdf)".
``` class Base { public: virtual ~Base() {} }; class D1: public Base {}; class D2: public Base {}; int main(int argc,char* argv[]); { D1 d1; D2 d2; Base* x = (argc > 2)?&d1:&d2; if (dynamic_cast<D2*>(x) == nullptr) { std::cout << "NOT A D2" << std::endl; } if (dynamic_cast<D1*>(x) == nullptr) { std::cout << "NOT A D1" << std::endl; } } ```
How do I check if an object's type is a particular subclass in C++?
[ "", "c++", "class", "subclass", "identification", "" ]
I am asking about the common techniques which are used in c# to support multilingual interface in windows forms
Everything I said here: [Internationalizing Desktop App within a couple years... What should we do now?](https://stackoverflow.com/questions/270829/internationalizing-desktop-app-within-a-couple-years-what-should-we-do-now) applies to this question.
I would also recommend to check out this tool: [Multilizer](http://www.multilizer.com/). I have been using it in my CBuilder/Delphi projects.
Develop multilingual windows application C#
[ "", "c#", "winforms", "internationalization", "multilingual", "" ]
This is a really basic question but... I have some code like this ``` var arr = Array('blah.jpg','ha.jpg'); for (var i=0; i<array.length; i++) { $('div#blah' + i).click(function() { $('img').attr('src', arr[i]); }); } ``` This should bind the div with `id="blah0"` to change all images to `'blah.jpg'` when clicked. Similarly, clicking the div with `id ="blah1"` should change all images to `'ha.jpg'`. However, the anonymous function won't work because it will use the value of 'i' at the time of execution, i.e. 2. This means that clicking either div will try and set all images to arr[2] - a non-existent element (interestingly not throwing a JS error on my machine but that's another story...). How can I get the anonymous function to be created using the value of 'i' at declaration time? As a simpler example: ``` for (var i=0; i<10; i++) { $('div#blah'+i).click(function() { alert(i)); }); } ``` This should display '0' when I click 'blah0', '1' when I click 'blah1' etc. However, by default it will display '10' no matter which 'blah' i click.
Declare a new variable inside a function that creates a new click handler that gets the current value of i as a parameter: ``` function makeClickHandler(arr, local_i) { return function() { $('img').attr('src', arr[local_i]); }; } var arr = Array('blah.jpg','ha.jpg'); for (var i=0; i<array.length; i++) { $('div#blah' + i).click(makeClickHandler(arr, i)); } ``` Each instance of the function gets its own copy of local\_i, that doesn't change each time.
In this particular case you should be using a closure: ``` for (var i=0; i<10; i++) { (function(j){ $('div#blah'+j).click(function() { alert(j)); }); })(i); } ``` `(function(){ /* code */ })()` denotes a self executing function, which implies that it will use and evaluate the value of i immediately in the loop as opposed to at click time.
How do I use the value of a variable at declaration time in a JavaScript anonymous function?
[ "", "javascript", "jquery", "closures", "" ]
EDIT: I'm told that making you guys read means I get less attention. My apologies. Here's a simpler version: Bill got $100 dollars worth of items from a store. He wants to return enough of the items to get exactly $30 dollars back. The store has a Point of Return system that will help him do this. Here is the data after he scans his items: ``` item ¦ price ¦ socks 4.00 cheap tv 22.00 book on tape 9.00 book on paper 7.00 party hats 3.00 picture frame 10.00 hammer 5.00 juicer 16.00 mysql guide 24.00 total items ¦ total price ¦ 9 100.00 Option 1 =============== item ¦ price ¦ cheap tv 22.00 party hats 3.00 hammer 5.00 =============== Option 2 =============== item ¦ price ¦ socks 4.00 picture frame 10.00 juicer 16.00 =============== Option 3 =============== item ¦ price ¦ book on tape 9.00 hammer 5.00 juicer 16.00 ``` I probably missed a few options, since I made all of this up. So, the big question is: Is there a way (with GROUP BY, probably) to have one query that would return ever possible combination of items? Thanks! a
If the number of items are small enough you can brute force this with SQL. This might be a quick to write solution, but you probably want to do something smarter. Sounds like the "[knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem)" which is NP complete. If the number of items is large, you will need to delve into dynamic programming algorithms. You have to ask yourself how important this is to your application. If the number of items is relatively small, you may be able to brute-force this. A brute-force SQL statement (which is what you asked for) that finds combinations of 1,2 or 3 items that match is as follows. If this is not satisfactory, then maybe SQL is not the right tool for this job. ``` SELECT i1.id AS id1, NULL AS id2, NULL AS id3, i1.amount FROM items i1 UNION ALL SELECT i1.id AS id1, i2.id AS id2, i3.id AS id3, i1.amount + i2.amount AS total FROM items i1, items i2 WHERE i1.amount + i2.amount = 30 AND i1.id <> i2.id AND i1.id <> i3.id UNION ALL SELECT i1.id AS id1, i2.id AS id2, i3.id AS id3, i1.amount + i2.amount + i3.amount AS total FROM items i1, items i2, items i3 WHERE i1.amount + i2.amount + i3.amount = 30 AND i1.id <> i2.id AND i1.id <> i3.id AND i2.id <> i3.id ``` In Oracle, you would use the CUBE function to turn this into a generic version, not sure about a MySQL equivalent.
You're asking for all subsets which sum up to exactly $30. This sounds a lot like the [subset sum problem](http://en.wikipedia.org/wiki/Subset_sum_problem), and [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem), so I strongly doubt you can do this with a simple query. You'd probably have to turn to T-SQL, but even that would probably look ugly. I think programming is the way to go here.
MySQL finding subtotals
[ "", "sql", "mysql", "group-by", "aggregate", "subtotal", "" ]
Hopefully a nice simple one. I've got a php3 website that I want to run on php 5.2 To start with I'd just like to have every reference to the current "index.php3" \_within\_each\_file\_ (recursively) changed to "index.php" and then move on to worrying about globals etc. K. Go! :) Update: Thanks a lot! I realise that my question missed the fact that the references are in each file of a website and I wanted to do it recursively in all files/folders.
``` find -type f -exec perl -pi -e 's/\bindex\.php3\b/index.php/g' {} \; ```
How about: ``` for file in *.php3 do sed 's/\.php3/.php/g' $file > ${file%3} done ``` The for/do/done loop deals with each .php3 file in turn, editing the file and replacing each string `.php3` with `.php`, and copying the file from something.php3 to something.php. *Added for amended question:* ``` for file in $(find . -type f -name '*.php3' -print) do sed 's/\.php3/.php/g' $file > ${file%3} done ``` The '`-print`' can usually be omitted these days, but historically, a lot of machine time was wasted by people who forgot to add it because there was originally (pre-POSIX) no default action. This fragment is about the simplest modification of the original code to do the extended task, but isn't necessarily the best way to do it any more - it pre-generates the entire list of files before processing any. You could instead use: ``` find . -type f -name '*.php3' -print | while read file do sed 's/\.php3/.php/g' $file > ${file%3} done ``` However, both the amended versions can run into problems if file names or path names can contain blanks or newlines or other such characters. To avoid such issues, you have to work harder - using Perl or (GNU find + xargs) or some other techniques. If you're sane, you avoid such problems. If you've inherited a less than entirely sane setup, then you may have to delve deeper into the arcana of Unix file name handling.
How do I replace 'php3' with 'php' inside every file in a directory
[ "", "php", "regex", "string", "bash", "replace", "" ]
I'm working on a little web crawler that will run in the system tray and crawl a web site every hour on the hour. What is the best way to get .NET to raise an event every hour or some other interval to perform some task. For example I want to run an event every 20 minutes based on the time. The event would be raised at: ``` 00:20 00:40 01:00 01:20 01:40 ``` and so on. The best way I can think of to do this is by creating a loop on a thread, that constantly checks if the time is divisible by a given interval and raises a callback event if the time is reached. I feel like there has got to be a better way. I'd use a `Timer` but I'd prefer something that follows a "schedule" that runs on the hour or something along those lines. Without setting up my application in the windows task scheduler is this possible? **UPDATE:** I'm adding my algorithm for calculating the time interval for a timer. This method takes a "`minute`" parameter, which is what time the timer should trigger a tick. For example, if the "`minute`" parameter is 20, then the timer will tick at the intervals in the timetable above. ``` int CalculateTimerInterval(int minute) { if (minute <= 0) minute = 60; DateTime now = DateTime.Now; DateTime future = now.AddMinutes((minute - (now.Minute % minute))).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1); TimeSpan interval = future - now; return (int)interval.TotalMilliseconds; } ``` This code is used as follows: ``` static System.Windows.Forms.Timer t; const int CHECK_INTERVAL = 20; static void Main() { t = new System.Windows.Forms.Timer(); t.Interval = CalculateTimerInterval(CHECK_INTERVAL); t.Tick += new EventHandler(t_Tick); t.Start(); } static void t_Tick(object sender, EventArgs e) { t.Interval = CalculateTimerInterval(CHECK_INTERVAL); } ```
[System.Timers.Timer](http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx). If you want to run at specific times of the day, you will need to figure out how long it is until the next time and set that as your interval. This is just the basic idea. Depending on how precise you need to be you can do more. ``` int minutes = DateTime.Now.Minute; int adjust = 10 - (minutes % 10); timer.Interval = adjust * 60 * 1000; ```
You may find help from Quartz.net <http://quartznet.sourceforge.net/>
How can I raise an event every hour (or specific time interval each hour) in .NET?
[ "", "c#", ".net", "scheduled-tasks", "" ]
I understand that [Firefox](http://www.mozilla.com/en-US/) addins can be created in Javascript and Chrome. How do they run advanced graphics applications such as [CoolIris](http://www.cooliris.com/) ? [![alt text](https://i.stack.imgur.com/CqFWU.png)](https://i.stack.imgur.com/CqFWU.png) (source: [cooliris.com](http://www.cooliris.com/static/images/product/slider1.png))
Cooliris uses native compiled code utilizing graphics acceleration on the platforms it supports. You can get a full screen GUI if you use Flash, but the user is informed about it (try watching a YouTube vid in fullscreen) and also the user can't do everything they can otherwise, like type using the keyboard.
*"Firefox addins can be created in Javascript*", It could be true *"All Firefox Add ins are created using javascript"* might not be not true Javascript is not the only way you can create Firefox addin, Just like Google toolbar may not have been created using javascript.Cooloris uses something more than javascript. Coolliris probably [scraps](http://en.wikipedia.org/wiki/Web_scraping) Content using javascript or so, and uses a custom plug in (or something like Adobe Flash ) to run advanced graphics. I could be wrong though.
How do firefox extensions make use of the whole screen in 3D (eg. CoolIris)?
[ "", "javascript", "firefox", "add-in", "google-chrome", "cooliris", "" ]