MCPD: Webdeveloper 4 Visual Studio 2010 Training Stuff

I think about doing the 4 exams required to become a MCPD Webdeveloper 4 Visual Studio 2010. The examns can be found here: http://www.microsoft.com/learning/en/us/certification/mcpd.aspx#tab2 I found only one book at amazon, having a rather bad rating. Can somebody recommend any training material for those examns?


How should I introduce a new programmer to a complex project?

We have a pretty complex project with 100 or so classes, multiple custom elements, etc. We have a new senior programmer who will work on this project. How should we approach the task of introducing the senior programmer to the project? How can we make sure the programmer does not break some other feature while fixing the current one? I have seen too many similar situation.s Sometimes, new bugs are not noticed immediately -- but pop up months later. Shall I direct the programmer by first giving them smaller tasks and waiting for them to finish them? Or there is a better solution? I am asking this because I don't want to become micromanager but I also don't want to have nasty bugs created because of my bad approach to the new programmer.


A programmer as project manager or non-programmer?

We are a team of programmers and are employing a new person who will be a project manager only. Our project are only programming ones and we are not sure how to decide who will be the best for project manager. Shall we find a senior programmer from our programming field? Or we must find a regular guy (economics or management studies) who never coded in his life? **EDIT** A project manager will_   * Create tasks for developers   * Monitor that our ticket workflow is respected   * Warn developers is they cross estimated work time    * Manage weekly finance timesheets   * Help client and reply to his questions   * Set meetings between client and developers (internet meetings) And similar things. Now, when I wrote this I see that there are no IT tasks in here. But what about simple questions the clients ask and which an educated It person will be able to reply? we obviously cannot bother programmers for this all the time. this is the main reason whay we are in doubt.


C# books for the experienced programmer

> **Possible Duplicate:**   >  Is there a canonical source for learning C# and .NET internals? So I've been programming in C# for 3 years now (been programming in various languages for 3 years before that as well) and most of the stuff I learned I pieced together on the internet. The thing is, I want to understand C# more formally and in depth and so would like to get some books on the subjects. Any books you'd recommend? Also, I've heard good things about "C# 4.0 in a Nutshell", "Pro C# 2010 and the .NET 4 Platform" and "CLR via C#". What do you think of these? (The people at stackoverflow told me to take it here. Please, Please tell me I'm in the right place this time)


What does it mean when data is scalar?

I don't know what scalar means exactly, but I'm trying to see if I'm thinking about it correctly. Does scalar relate to arbitrariness where the type of data could be any type, or a system is not able to know what the data is in advance.


Where should I put bindings for dependency injection?

I'm new to dependency injection and though I've really liked it so far, I'm not sure where bindings should go. I'm using Guice in Java, so some of what I say might be specific to just Guice. As I see it, there's two options: **Accompanying the class(s) its needed for.** Then, just write `install(OtherClassModule.class)` in whatever other modules want to be able to use said class. As I see it, the advantage of this is that classes that want to use it (or manage classes that want to use it) don't need to know any of the implementation detail. The issue I see is that what if two classes want to use two different versions of the same class? There's a lot of customization possible because of DI and this seems to restrict it a lot. **Implemented in the module of the class(s) its needed for.** It's the flip of what I said above. Now you have customization, but not encapsulation. Is there a third option? Am I misunderstanding something obvious? What's the best practice?


Why std::allocators are not that popular?

With the latest trends about C and C++ applications, and with latest I mean the latest years, I was expecting to see `std::allocator`s to be used way more frequently than what it really is. Modern applications are usually multithreaded or with form of concurrency in them, and they manage a significant amount of memory, especially in some fields like games and multimedia applications; so the usual high cost of the allocation/deallocations rises and impacts the performances even more than in old applications. But for what I can see this kind of memory management through `std::allocator`s is not popular, I can't even count 1 library that I know of, that is using any rationale about a standardize way of managing memory. There is a real reason why `std::allocator` is not popular ? Technical reasons ?


What can I do in order to inform users of potential errors in my software in order to minimize liability?

I'm an independent software developer that's spent the last few months creating software for viewing and searching map data. The software has some navigation functionality as well (mapping, directions,etc). The eventual goal is to sell it in mobile app markets. I use OpenStreetMap as my data source. I'm concerned about liability for erroneous map data / routing instructions, etc that might result when someone uses the application. There are a lot of stories on the internet where someone gets into an accident or gets stuck or gets lost because of their GPS unit/Google Maps/mapping app... I myself have come across incorrect map data as well in a GPS unit I have in my car. While I try to make my own software as bug free as possible, no software is truly bug free. And moving beyond what I can control, OpenStreetMap data (and street map data in general) is prone to errors as well. What steps can I take to clearly inform the user that results from the software aren't always perfect, and to minimize my liability?


Greater than or identical to?

While browsing my code in a weakly-typed language I was seeing that I've trained myself to use identity (`===`) where logical. Then I came across a greater (or less) than or equal to (`>=`), and it made me wonder... why is there no "greater than or identical to"? I suppose it would be `>==`. For example...               5 == 5    // true     5 === 5   // true     5.5 >= 5  // true     5.5 >== 5 // false     6 >= 5    // true     6 >== 5   // true      Basically, I would throw a false if it was of a different type. For example, if I want to check if $x is greater than $y, but I want them both to be integers (or floats, but no mixing), then wouldn't it make sense to have a single call that can do all that, rather than having to check separately to see if they were the same type? A quick google indicated that this may not exist in any language; why not? Is it just not as useful as I might think it is? :)


Should data models know where / how they're stored?

I have some classes that represent, for the most part, data that's deserialized from XML. They also have some behavior in them, because I don't want to suffer from an anemic domain model. These domain objects don't have any XML specific code in them, but they do have properties that correspond exactly to the tags and attributes in the XML. Many of these classes' behaviors rely on resources loaded from disk, like images. For that, some properties / xml attributes are relative file paths to these resources. Now my problems begin. The absolute path to be constructed for these resources is based on a separate dependency - the root of the "project". Here's what I'm struggling with:   1. Should my domain objects store the full absolute path to their resources? Or just the relative paths? If they held the absolute path, then the classes that load them - my XML readers - will have to take a dependency on the project root in order to build the full path for them. If not, I'll have to make yet another layer of classes to handle that. I already have 3 layers, I don't know if I can handle any more!   2. Should my domain objects store _their own paths_ for where they are on disk? It makes sense for them to know where their dependencies are in relation to them, but to know their own location just feels wrong to me intuitively. This is sort of unrelated to the other part of the question, but I think if I go the wrong way on this it could bite me later.


Examples of operator overloading, which make sense

While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:   1. Make sense (ex. adding class named sheep and cow)   2. Is not an example of concatenation of two strings Examples from Base Class Library are welcome.


Optional dependencies in npm?

I have a similar question to this, but not quite the same. I would like for the user of my app to install it with whatever dependencies are needed for the way he would want to use it. So, for example, if they want to persist to MongoDB, then only Mongo-related libraries will be installed, but if they want to persist to Redis, then only Redis-related libraries will be installed. I don't want to make them download and install libraries they won't be using. I know I can do that for development purposes with `devDependencies`, but this goes farther than that. As the answer in the question above says, this is more closely related to Python's `setuptools` `extras_require` and Clojure's `leiningen` profiles. Anything like that in npm? I really feel like `devDependencies` should be a `dev` profile of a more versatile way of specifying dependencies.


Validation and authorization in layered architecture

I know you are thinking (or maybe yelling), "not another question asking where validation belongs in a layered architecture?!?" Well, yes, but hopefully this will be a little bit of a different take on the subject. I am a firm believer that validation takes many forms, is context-based and varies at each level of the architecture. That is the basis for the post - helping to identify what type of validation should be performed in each layer. In addition, a question that often comes up is where authorization checks belong. The example scenario comes from an application for a catering business. Periodically during the day, a driver may turn in to the office any excess cash they've accumulated while taking the truck from site to site. The application allows a user to record the 'cash drop' by collecting the driver's ID, and the amount. Here's some skeleton code to illustrate the layers involved:               public class CashDropApi  // This is in the Service Facade Layer     {         [WebInvoke(Method = "POST")]         public void AddCashDrop(NewCashDropContract contract)         {             // 1             Service.AddCashDrop(contract.Amount, contract.DriverId);         }     }          public class CashDropService  // This is the Application Service in the Domain Layer     {         public void AddCashDrop(Decimal amount, Int32 driverId)         {             // 2             CommandBus.Send(new AddCashDropCommand(amount, driverId));         }     }          internal class AddCashDropCommand  // This is a command object in Domain Layer     {         public AddCashDropCommand(Decimal amount, Int32 driverId)         {             // 3             Amount = amount;             DriverId = driverId;         }              public Decimal Amount { get; private set; }         public Int32 DriverId { get; private set; }     }          internal class AddCashDropCommandHandler : IHandle<AddCashDropCommand>     {         internal ICashDropFactory Factory { get; set; }       // Set by IoC container         internal ICashDropRepository CashDrops { get; set; }  // Set by IoC container         internal IEmployeeRepository Employees { get; set; }  // Set by IoC container              public void Handle(AddCashDropCommand command)         {             // 4             var driver = Employees.GetById(command.DriverId);             // 5             var authorizedBy = CurrentUser as Employee;             // 6             var cashDrop = Factory.CreateCashDrop(command.Amount, driver, authorizedBy);             // 7             CashDrops.Add(cashDrop);         }     }          public class CashDropFactory     {         public CashDrop CreateCashDrop(Decimal amount, Employee driver, Employee authorizedBy)         {             // 8             return new CashDrop(amount, driver, authorizedBy, DateTime.Now);         }     }          public class CashDrop  // The domain object (entity)     {         public CashDrop(Decimal amount, Employee driver, Employee authorizedBy, DateTime at)         {             // 9             ...         }     }          public class CashDropRepository // The implementation is in the Data Access Layer     {         public void Add(CashDrop item)         {             // 10             ...         }     }      I've indicated 10 locations where I've seen validation checks placed in code. My question is what checks you would, if any, be performing at each given the following business rules (along with standard checks for length, range, format, type, etc):   1. The amount of the cash drop must be greater than zero.   2. The cash drop must have a valid Driver.   3. The current user must be authorized to add cash drops (current user is not the driver). Please share your thoughts, how you have or would approach this scenario and the reasons for your choices.


How is the publish-subscribe pattern different from gotos?

My understanding is that Goto statements are generally frowned up. But the publish-subscribe pattern seems to be conceptually similar in that when a piece of code publishes a message, it performs a one-way transfer of control. The programmer may have no idea what parts of the program are subscribing to this message. I have see something similar in a lot of JavaScript programs in which events are used to conveniently "hop" across modules. Am I missing something about the publish-subscribe or event-driven patterns?


Should I wait until Mango's release?

I was deciding whether to start a Windows Phone application, but it seems like it might be better to wait until Mango is released. Is Mango a new platform, or is it an upgrade to Windows Phone 7 (i.e. Windows Phone 8)? Is it expected to arrive in the near future? That is, should a project starting today worry about it?


Best practise is not to poll...but isn't polling happening internally anyway when a thread calls wait()?

Say we have some thread that wants to check when another thread is finished its task. I have read that we should call a wait() type function that will make this thread wait until it receives a notification that the other thread is finished. And that this is good because it means we aren't performing expensive polling. But isn't polling happening internally at a lower level anyway? I.e. if we make the thread wait() isn't the kernal performing polling anyway to check when the other thread is finished so that it can then notify the first thread? I presume I a missing out on something here, can someone enlighten me?


Design: Object method vs separate class's method which takes Object as parameter?

For example, is it better to do:               Pdf pdf = new Pdf();     pdf.Print();      or:               Pdf pdf = new Pdf();     PdfPrinter printer = new PdfPrinter();     printer.Print(pdf);      Another example:               Country m = new Country("Mexico");     double ratio = m.GetDebtToGDPRatio();      or:               Country m = new Country("Mexico");     Country us = new Country("US");     DebtStatistics ds = new DebtStatistics();     double usRatio = ds.GetDebtToGDPRatio(us);     double mRatio = ds.GetDebtToGDPRatio(m);          My concern in the last example is there are potentially endless statistics (but let's say even just 10) you might want to know about a country; do they all belong on the country object? e.g.               Country m = new Country("Mexico");     double ratio = m.GetGDPToMedianIncomeRatio();      These are simple ratios but lets assume the statistics are complicated enough to warrant a method. Where is that line between operations that are intrinsic to an object vs operations that can be performed on an object but are not part of it?


The deference between Computer science and Computer information system?

I'm Asking you that question because you are an experts in programming , and maybe you could help me . Unfortunately in my country you can't get a job if you don't have a university certification, even if you are a great programmer , so this year i went to college and majored in Computer Science , But I'm so Confused between CS and CIS , and in what major should I spent my money on it ,, There is more than 25 subjects are mutual between us but there is some subjects are special for Computer science , also another subjects for Computer information system too , **Computer science specialization** :   1. Discrete Mathematics   2. Linear algebra And Numerical Analyses    3. Computation theory    4. Compiler Design    5. Wireless Networks security    6. Artificial Intelligence    7. Computer Organization & Architecture    8. Expert Systems  =========================================== **Computer information system specialization :** 1.Information retrieval systems   1. Management for network    2. Wireless network    3. Data base management systems    4. Information security    5. Data warehousing    6. Data mining    7. Intelligent systems


Does C++ compiler remove/optimize useless parentheses?

Will the code               int a = ((1 + 2) + 3); // Easy to read      run slower than               int a = 1 + 2 + 3; // (Barely) Not quite so easy to read      or are modern compilers clever enough to remove/optimize "useless" parentheses. It might seems like a very tiny optimization concern, but choosing C++ over C#/Java/... is all about optimizations (IMHO).


Best practices for managing and maintaining large Rails app?

What are best practices for managing and maintaining large Rails app?


JavaScript strict mode compatibility

While reading about strict mode on MDN I really was surprised to read the following near the end of the page, quote: > Browsers don't reliably implement strict mode yet, so don't blindly depend > on it. Strict mode changes semantics. Relying on those changes will cause > mistakes and errors in browsers which don't implement strict mode. Exercise > caution in using strict mode, and back up reliance on strict mode with > feature tests that check whether relevant parts of strict mode are > implemented. Finally, make sure to test your code in browsers that do and > don't support strict mode. If you test only in browsers that don't support > strict mode, you're very likely to have problems in browsers that do, and > vice versa. As far as I understand it, strict mode is a redused set of "nonstict" mode, thus I can't imagine situation where strict code can't run correctly in a nonstrict browser. So, the question is this statement really makes sense? Is the any situation where strict to "nonstrict" switch will make code invalid?


C# Design Issue

I am building a small application and I am trying to understand the best way to approach the design. I am looking for some guidance/advice how best to approach the following issue. What I have is that I receive a set of data, real time. I then analyze the data for patterns. The patterns are classes that derive from an abstract class which implements an interface. The number of patterns will change over time as patterns are added/removed. In addition, depending on the access level of the user, the data is analyzed with different pattern options. For example, if I have five patterns, A, B, C, D and E, level 100 access may only analyze the data with pattern A whereas access level 300 will analyze with patterns B, D and E, and access level 500 will analyze with all the patterns. The access levels are linked to the user, and a user can have different access levels on different data streams. My thought is to create a hash table or dictionary for the patterns and a db for the users and their various access levels. Is this the best way to go or is there a better approach that will work in real time?


How do I account for changed or forgotten tasks in an estimate?

To handle task-level estimates and time reporting, I have been using (roughly) the technique that Steve McConnell describes in Chapter 10 of _Software Estimation_. Specifically, when the time comes for me to create task-level estimates (right before coding begins on a project), I determine the tasks at a fairly granular level so that, whenever possible, I have no tasks with a single-point, 50%-confidence estimate greater than four hours. That way, the task estimation process helps with constructing the software while helping me not to forget tasks during estimation. I come up with a range of hours possible for each task also, and using the statistical calculations that McConnell describes along with my historical accuracy data, I can generate estimates at other confidence levels when desired. I feel like this method has been working fairly well for me. We are required to put tasks and their estimates into TFS for tracking, so I use the estimates at the percentage of confidence I am told to use. I am unsure, however, what to do when I do forget a task, or I end up needing to do work that does not neatly fall within one of the tasks I estimated. Of course, trying to avoid this situation is best, but how do I account for forgotten/changed tasks? I want to have the best historical data I can to help me with future estimates, but right now, I basically am just calculating whether I made the 50%-confidence estimate and whether I made it inside the ranged estimate. I'll be happy to clarify what I'm asking if needed -- let me know what is unclear.


Is it acceptable to deploy web app to production directly from SVN

**Question** Is there a legitimate reason **NOT** to use SVN for production deploys, or is this merely a case of personal preference and there is no real case against SVN? **Background** My workplace has a culture of tagging release in SVN and then deploying those releases directly to the various web servers using `svn co` or `svn switch` including directly to production. I personally have a problem with this as I believe that without using a build and deploy script or some form or automated deploy you lose integration environment settings as they're undocumented. However more than that I have a gut feeling that there may be a hidden danger to doing that which has been overlooked, something which has yet to rear its ugly head. I've brought up my concerns with the operations staff who are responsible for deploying code to our various environments (staging, pre-prod, production) etc. Their arguments were pretty much that it's worked pretty well so far, no reason to change. **Edit:** _What I mean about build and deploy:_ For example, if a developer requires a web.config setting added for a particular environment. Web.config is generally not kept in svn and so these files are updated manually without any form of automated build script. So if they're lost or OPS forget to add a field to the web.config for a release then you have issues. A build script that say uses XMLPoke to automatically generate a web.config appropriate for a particular environment is ideal in that you have a versionable script which documents all changes necessary for each of your environments. _Current Build and Deploy Method_ For the project in question a developer builds a release manually, other projects have the build step automated either with NANT, or MSBuild which is OK. Database migrations for most projects are via DB scripts, or migration scripts (Migrator.NET), or CMS Packages. CI is usually done by Team City on a per checkin basis, we have a code review process that all tickets are done in branches and then peer reviewed for validation and correctness/quality prior to checking into trunk (works well). However actual code deploy is pretty much always via SVN, either via a checkout of a tagged release or more generally an SVN Switch. This is something that sticks odd with me that we're using our repository as part of the deploy process. Configuration doesn't generally change very often, the only things that will be in config files are environment specific information. Everything else is in the db. Don't get me wrong this works, it works well. However I want to try and push for an automated build and deploy. I've used this with Rails and Capistrano, and for personal projects using Cygwin, Nant and SSH. More importantly I would need very specific valid arguments to get my colleagues to change to using an Automated build and deploy. Or are there NO real valid arguments against using SVN specifically to deploy to production?


Why the decline in search traffic for popular programming languages?

Is there any solid evidence behind the reasons for decline in search volume for popular programming languages? Could this possibly be due to improvements in finding necessary information (no need to search 10 times to find something) and quality of information? ![enter image description here](http://i.stack.imgur.com/Wfc7T.jpg)


What kind of webservice can be called with just a browser url?

Can a webservice be written in such a way that it can be called via just a browser url? For eg. if the webservice is called GetStockQuote, then it should be callable by the following url on the browser               http://myserver.com/WebServices/GetStockQuote?sym=MSFT      Likewise, if there are more params, they can be passed via the URL. Unlike this one - http://www.webservicex.net/stockquote.asmx \- where it doesn't look like the param can be passed via a URL. It seems to require either a program or a human to type in the param & click on invoke. Or does it always require a client program? Is there a way from the wsdl to figure out whether it can be called from a browser or not. How can I program a webservice which fulfils the above criteria?


Is it okay to define a [] method in ruby's NilClass?

Ruby by default does not include the method `[]` for `NilClass` For example, to check if `foo["bar"]` exists when `foo` may be nil, I have to do:               foo = something_that_may_or_may_not_return_nil     if foo && foo["bar"]       # do something with foo["bar"] here     end      If I define this method:               class NilClass       def [](arg)         nil       end     end      Something like that would make this possible, even if `foo` is nil:               if foo["bar"]       # do something with foo["bar"]     end      Or even:               if foo["bar"]["baz"]       # do something with foo["bar"]["baz"] here     end      **Question:** Is this a good idea or is there some reason ruby doesn't include this functionality by default?


Pros and cons of hosted scripts

I have seen some developers use hosted scripts to link their libraries. `cdn.jquerytools.org` is one example. I have also seen people complain that a hosted script link has been hijacked. How safe is using hosted scripts in reality? Are the scripts automatically updated? For example, if jQuery 5 goes to 6 do I automatically get version 6 or do I need to update my link? I also see that Google has a large set of these scripts setup for hosting. What are the pros and cons?


Avoiding duplicate bug reports

I use Linux and other open source software in my home. As I'm not a professional coder, I usually report bugs to developers as my skills are not enough to solve problems on my own. What kind of things you want me to check before I send a bug report? I mean, once I thought I found a bug in Gedit and I couldn't find similar bug in Bugzilla. But after I sent the report, some developer said that the bug is already in Bugzilla as the bug was in GTK+, not in Gedit. Sometimes it might be hard for an amateur to guess whether some previously known bug would solve the issue I found.


What do you consider to be a high-level language and for what reason?

Traditionally, C was called a high-level language, but these days it is often referred to as a low-level language (it is high-level compared to Assembly, but it is **very** low-level compared to, for instance, Python, these days). Generally, everyone calls languages of the sort of Python and Java high-level languages nowadays. How would you judge whether a programming language _really_ is a high-level language (or a low-level one)? Must you give direct instructions to the CPU while programming in a language to call it low-level (e.g. Assembly), or is C, which provides some abstraction from the hardware, a low-level language too? Has the meaning of "high-level" and "low-level" changed over the years?


Why do some programmers categorize C, Python, C++ differently? - regarding level

I am taking an introductory course on python and the instructor says that python is a high level language and C and C++ are low level languages. It's just damn confusing. I thought that C, C++, Python, Java, etc were all high level languages. I was reading questions at stackoverflow on C, C++, etc and they all seem to refer to those languages as high level. it seems to me that some programmers use those terms interchangably. Please clarify this for me.


Model Driven Design with Bean Validation

If I have a rich domain library that gets included into a Java web application, but I want to achieve a level of dependency isolation with that domain library such that it is possible to build and test it totally independently(of larger libraries like Spring), how can I realistically use JSR-303 bean validation? The domain library itself can use the hibernate validation annotations, like @NotNull on fields and getters just fine, and this is still independent and testable. However, if I want to use newer features, such as method parameter validation, which requires AOP, how do I maintain minimal dependencies while maintaining testability (via JUnit)? Is this a simple matter of configuring the unit test to exercise the domain objects through an AOP proxy? The design philosophy of JSR-303 seems, on the face of it, to be at odds with rich domain design, favouring more of a dumb-bean, business layer service design.


Tomcat 7 vs. ehCache Standalone Server (Glassfish) Configuration with RESTful Web Services

My requirements consist of using ehCache to send and store data via RESTful web service calls. The data can be stored in-memory or via the filesystem... Never used ehCache before so I am having some issues deciding on which bundle to use. Have downloaded the following bundles: ehcache-2.6.2 ehcache-standalone-server-1.0.0 (1) What is the difference between the two? It seems the ehcache-2.6.2 contains src and binaries, which essentially enables one to bundle it with their webapps (by putting the compiled jar or binaries inside the webapp's WEB-INF/lib folder). But it doesn't seem that it has support for Restful web services. Whereas, ehcache-standalone-server-1.0.0 (comes with an embedded Glassfish server and has support for REST & SOAP) can be used to run as a standalone server. If I my answers to my own question are correct, then that means, I should just use the standalone server? (2) My requirements are to setup ehCache (with REST support) on Tomcat 7. So, how could I setup ehCache on Tomcat 7 as a separate app with REST & SOAP support? Thank you for taking the time to read this...


Should I make a seperate unit test for a method, if it only modifies the parent state?

Should classes, that modify the state of the parent class, but not itself, be unit tested separately? And by separately, I mean putting the test in the corresponding unit test class, that tests that specific class. I'm developing a library based on chained methods, that return a new instance of a new type in most cases, where a chained method is called. The returned instances only modify the root parent state, but not itself. Overly simplified example, to get the point across:                   public class BoxedRabbits         {             private readonly Box _box;             public BoxedRabbits(Box box)             {                 _box = box;             }                  public void SetCount(int count)             {                 _box.Items += count;             }         }              public class Box         {             public int Items { get; set; }             public BoxedRabbits AddRabbits()             {                 return new BoxedRabbits(this);             }         }          var box = new Box();     box.AddRabbits().SetCount(14);      Say, if I write a unit test under the `Box` class unit tests:               box.AddRabbits().SetCount(14)      I could effectively say, that I've already tested the `BoxedRabbits` class as well. Is this the wrong way of approaching this, even though it's far simpler to first write a test for the above call, then to first write a unit test for the `BoxedRabbits` separately?


OO design for a Windows application that communicates with an external machine via RS232

I'm after a bit of OO design advice... I'm about to start developing a Windows application that communicates with an external machine via RS232. The machine has an onboard "system controller" consisting of registers (addresses). You can write a value to a register (e.g. to turn a pump on), or read a value from a register (e.g. to see if the pump is running). The app will have a config file detailing each register's settings, e.g. its address, whether it's 16- or 32-bit, a friendly "alias" (so other code can deal with "Pump XYZ" rather than address "50B3D124"), and a few other things. My first thought was to have a `Register` class reflecting these properties, plus `Read()` and `Write()` methods. But this raises the first question - should the `Read()` method have a return value, or should it populate a `Value` property on the class? Similarly, should the `Write()` method include a "valueToWrite" parameter, or should it write whatever value is currently held in the `Value` property? I could take this one step further (possibly even answering the above question) - instead of Read/Write methods, put the functionality into the `Value` property's getter and setter? Using a property for this purpose doesn't feel right though. I then started wondering if a `Register` class was even necessary, as its read/write functionality would be doing little more than calling Read/Write methods on a `SystemController` class, e.g.               long ReadRegister(string registerAlias);     void WriteRegister(string registerAlias, long value);      Why not just let the rest of the application read/write registers via the `SystemController` class? (I suspect I would still need some concept of a `Register` class, even if it's just to represent a register's config settings).


algorithm for project euler problem no 18

Problem number 18 from Project Euler's site is as follows:               By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.          3     7 4     2 4 6     8 5 9 3          That is, 3 + 7 + 4 + 9 = 23.          Find the maximum total from top to bottom of the triangle below:          75     95 64     17 47 82     18 35 87 10     20 04 82 47 65     19 01 23 75 03 34     88 02 77 73 07 63 67     99 65 04 28 06 16 70 92     41 41 26 56 83 40 80 70 33     41 48 72 33 47 32 37 16 94 29     53 71 44 65 25 43 91 52 97 51 14     70 11 33 28 77 73 17 78 39 68 17 57     91 71 52 38 17 14 91 43 58 50 27 29 48     63 66 04 68 89 53 67 30 73 16 69 87 40 31     04 62 98 27 23 09 70 98 73 93 38 53 60 04 23          NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)      The formulation of this problems does not make clear if   * the "Traversor" is greedy, meaning that he always choosed the child with be higher value   * the maximum of every single walkthrough is asked The `NOTE` says, that `it is possible to solve this problem by trying every route`. This means to me, that is is also possible **without**! This leads to my actual question: Assumed that not the greedy one is the max, is there any algorithm that finds the max walkthrough value without trying every route and that doesn't act like the greedy algorithm? I implemented an algorithm in Java, putting the values first in a node structure, then applying the greedy algorithm. The result, however, is cosidered as wrong by Project Euler.               sum = 0;          void findWay(Node node){         sum += node.value;         if(node.nodeLeft != null && node.nodeRight != null){                 if(node.nodeLeft.value > node.nodeRight.value){                     findWay(node.nodeLeft);                 }else{                     findWay(node.nodeRight);                 }             }     }


Usage of __ while declaring any variables or class member in python

Is it good practice to use `__` convention while declaring the member variable? This also imparts private kind of feature of that data member. There have been cases when I found that its good to have hidden members of a class. This is certainly exposes only that feature that will help the the object to behave in more protected manner.


Design principles : classifying different types of class

I'm trying to clarify the design of a C++ application, and would like to define a clear classification among classes to aid clarity. However I'm struggling to find any literature to help me, probably because I don't really know what I'm searching for. To help, here is what I've got so far. Classes can be one of a number of types:   * Value object. Here I mean things like std::string, std::vector. These are concrete classes that are typically instantiated on the stack, can be copied etc.    * Service objects. Clients will interact with these through a pure virtual interface, and these will typically be injected, DI style. A persistence service might be a good example here. There would typically be once instance of a service, either injected or accessed through a ServiceLocator (yeah, I know).   * (Domain object?). Clients interact with these through a pure virtual interface, but these represent abstract domain objects and are constructed using an abstract factory, which itself will be a service. These would typically have identity, but you want to interact with them in an abstract way. So a database connection might be a good example (note that this is different from a persistence service -- the concrete implementation of persistence service may use a database connection, but the database connection would represent one actual connection, and there would be subclasses for Mysql, SqlServer etc). There will be many instances of such objects, they have identity.   * Other things that don't fit into the above, but which I've failed to come up with any clear classification.  Now someone must have documented this kind of taxonomy, but so far I can't find anything. Does anyone have any good references? Thanks.


UnitTests, will cleaning up your act-statement make your test more or less clear?

Lets say that we are testing `FooClass` with the following method:                   public void Foo(string stringParameter, int intParameter, Action<Bar> successCallback, Action<Exception> errorCallback);      If the call to `Foo` succeeds, the `successCallback` will be called with the result of `Foo` in the form of a `Bar` object. If it fails, the `errorCallback` will be called with an `Exception`. So the tests will look something like this:               [TestMethod]     public void Foo_UnderGivenConditions_WeExpectAGivenResult()     {         //Arrange         var fooObject = CreateFooObjectWithGivenConditions( ... );              //Act         fooObject.Foo(String.Empty, 0, (bar) => { ... }, (error) => { ... });              //Assert         Assert.AreEqual(..., ...);     }      Now, there are a lot of tests on this `Foo`-method, all of them containing a call to `Foo`, but not every test will care for all the parameters. Some may provide different string values, but doesn't care about the int param, and some will need to provide an error callback to assert that the right exception is thrown and so on. Now, since all the parameters are mandatory, we have to pass a string value to the `Foo` method, even though the value has no meaning for the test. There will be a lot of `"I don't care"` or `"some text"`. When some one else comes and read the test, they have to consider if the given value actually has a meaning for the test result or not. The same goes for the callbacks. Sometimes we need the callbacks to get to the result value or the exception, but most of the time we do not. So lets implement an extension method, `PerformFoo`, that defaults every parameter:               public static Bar PerformBar(this FooClass fooObject, string stringParameter = "some text", int intParameter = 0, Action<Bar> successCallback = null, Action<Exception> errorCallback = null);     {        Bar result = null;             var ourCallback = (bar) =>            {                result = bar;                if (successCallback != null)                    sucessCallback.invoke();           }             fooObject.Foo(stringParameter, intParameter, ourCallback, errorCallback);             return result;     }      The extension method will call `Foo` with default parameters, and even return the result if the successCallback is called. This lets us change the Act part of the test to something like:               //Act, all we care about is the string parameter:     fooObject.PerformFoo("A string that we care about");          //Act, we need the resulting bar when the int parameter is 10:     var bar = fooObject.PerformFoo(intParameter: 10);          //Act, we still needs to provide a callback to get the exception      fooObject.PerformFoo("SomeInvalidValueCausingAnException", errorCallback: (error) => { exceptionThrown = error; });       So the questions would be:   * Does this make the tests more readable?   * Is it easier to get what the test really tests?   * The fact that we call `PerformFoo`, which doesn't really exist on the class under test make the test less worth as an documentation?   * Would dropping the extension method for a regular method taking the fooObject as the first parameter be less of a 'lie'? (e.g. `PerformFoo(fooObject, intParameter: 10)` ) How far would you go to make your tests clean and clear?


Least Change Problem with Thousands of Denominations

In a hypothetical economy there are currency units that can represent thousands of different values. So, for example there might be coins worth 1c, 3c, 5c, 7c, 7.5c, 80c, 8001.5c etc. Given a list of all of the possible denominations and an arbitrary value how would one return a list of coins representing the smallest number of coins needed to match that value. For bonus points, imagine that you have arbitrary finite quantities of each currency. So you may have only two 3c coins but thirty 18c coins. Sounds like a nightmare compsci class problem but it's something I ran into recently on a personal project of mine. The economy is a barter economy (tf2) in which every type of item has a distinct value relative to other items. I have an Item class where items have a Value attribute and this attribute is a double that represents the value of the item relative to a base item which has a value of 1. I'm trying to come up with a way so that if someone makes an offer of a value of 30 I can then look through a list of around 1200 item objects and find the smallest set of objects which combine in value to match 30. I cannot think of a remotely efficient way to do this, but I figured the problem was interesting enough that someone would like to ponder over it with me. My program is in c# but even a psuedocode brainstorm would be helpful.


MVC Pattern, ViewModels, Location of conversion

I've been working with ASP.Net MVC for around a year now and have created my applications in the following way. > X.Web - MVC Application Contains Controller and Views > > X.Lib - Contains Data Access, Repositories and Services. This allows us to drop the .Lib into any application that requires it. At the moment we are using Entity Framework, the conversion from EntityO to a more specific model is done in the controller. This set-up means if a service method returns an EntityO and then the Controller will do a conversion before the data is passed to a view. I'm interested to know if I should move the conversion to the Service so that the app doesn't have Entity Objects being passed around.


Migrating legacy procedural code to MVC without rewriting

I recently started working on a PHP application that was built many years ago before the advent of objects and namespaces in PHP. The code is procedural, does not separate presentation logic from business logic, lacks a front end point (front controller), and has files everywhere with a seemingly random folder heirarchy. However, it works great for customers and despite the code mess it's actually pretty fast. I'd like to slowly move the codebase into something more maintainable and organized. I put MVC in this title, but truthfully all I really mean is an organized and maintainable. Key objectives of this effort are:   * Not degrade the customer experience in any sort of way while this overhaul takes place (a rewrite is not an option)   * Fully separate views from logic    * At least have a "best practice" or method for implementing new application end points (routes)   * Have a consistent method or layer for persisting data   * Begin encapsulating as much code as possible in objects so that unit testing is feasible at some point in time.


How can a web site be set up using the MVC Pattern? (Without MS ASP.NET MVC)

We used a contractor to create the initial version of our site; they used their own MVC-pattern code-generator to create the (ASP.NET / C#) site and customized from there. That was turned over to us two years ago, and we've been working on it since. That's the environment I'm coming into, with little practical MVC experience. Thus I need to grok MVC in general but it seems that every article/tutorial/book I find is either extremely general in nature or very specific to MS ASP.NET MVC. Can someone here help with examples, a tutorial or walk-through of setting up a basic site using the MVC Pattern _without using Microsoft ASP.NET MVC_ so that I can better understand the concepts and see how they can be applied in real life?


How to incorporate existing open source software from a licensing perspective?

I'm working on software that uses the following libraries:   * Biopython   * SciPy   * NumPy All of the above have licenses similar to `MIT` or `BSD`. Three scenarios:   1. First, if I don't redistribute those dependencies, and only my code, then all I need is my own copyright and license (planing on using the `MIT License`) for my code. Correct?    2. What if I use py2exe or py2app to create a binary executable to distribute so as to make it easy for people to run the application without needing to install python and all the dependencies. Of course this also means that my binary file(s) contains python itself (along with any other packages I might have performed a `pip install xyz`).   3. What if I bundle Biopython, SciPy, and NumPy binaries in my package? In the latter two cases, what do I need to do to comply with copyright laws.


IDEs for dynamic languages - how far can you get?

I find it frustrating how the speed of development that dynamic languages should offer gets significantly compromised by the lack of completions and other assets that IDEs would give you in their static counterparts. It's not just about typing less - it's the productivity boost and plain fun you get by browsing APIs without constantly having to refer to a documentation that is not integrated with the editor. To date all IDE + dynamic language combinations -which to be fair aren't that much- I've tried were:   * buggy   * slow   * clueless/overenthusiastic (as in showing all completions ever possible)   * or simply not as complete as, say, Eclipse + Java. I'm aware that dynamic code analysis is not a trivial task. But one can't help wondering - _is this piece of code really so hard to figure out_? So my question is: **Have any particular IDEs (or less all-in-one setups) achieved a totally outstanding support for a dynamic language, or is this still an 'unsolved' problem?**


Implenting ActiveRecord with inheritance?

I recently converted an old application that was using XML files as the data store to use SQL instead. To avoid a lot of changes I basically created ActiveRecord style classes that inherited from the original business objects. For example               SomeClassRecord :SomeClass     //ID Property     //Save method      I then used this new class in place of the other one, because of polymorphism I didn't need to change any methods that took SomeClass as a parameter. Would this be considered 'Bad'? What would be a better alternative?


Questions about the issue of getting stuck in a problem, and making snail's pace progress

Let me describe my background. I am currently a software developer co-op working at an architecture firm that has a large focus on research and development, mainly in mathematical modeling and physics simulations in better aid architecture design. I am one of the three main software developers. Realistically, we're all people that specialize in different topics, for example, one developer is an architect that's been programming and doing mathematical models since he was in high school (he's like 30 years old), and the other architect also has a Masters in data analytics. We all specialize in different things, making us part of a very multi-disciplinary group of nine people in total. Currently I am working on a project that handles Grasshopper 3D and Rhino 3D programming, making use of the Grasshopper SDK. I really enjoy what I am doing and appreciate the learning opportunity, however, with that said, the nature of Grasshopper programming has been difficult for me. I don't think I am that poor programming-wise, however, since most of my projects involve extending functionality beyond what the default Grasshopper SDK does, there are often times I have to spend a good couple hours or even days to understand a problem and then apply code to it. The very nature of this "functionality beyond what the default Grasshopper SDK provides" means that finding a solution to a problem isn't as simple as Googling, because of the relatively rare resources available, whether it's documentation or help threads online. The nature of getting stuck on an issue and the only remedy to said problem has been slowly chipping away at my confidence, and I evidently see that I am slowing down in shipping out components (that's what Grasshopper 3D "tools" are called). I've already made a good impression in the first couple months of my co-op in being known as efficient, quick, and comprehensive, however, in my three month review, once I began this task of working on Grasshopper programming, my advisors have noticed that my progress has not been as quick, and they mentioned that they are wondering what/where better to put me to work on that will bring out my full potential. I like the idea of working on another project, but I do not wish to do so until I've finished the current one I am on, which day by day I feel like I am making snail's pace progress because of some issues I am stuck with where finding help is a problem in itself. I dislike making a bad impression on my colleagues (and on my school as well, since I am a co-op employee), as I really believe I have the potential to do great. However, this issue of getting stuck on something, making small progresses, then getting stuck again, is simply chipping away my confidence. What are some things I can do? I feel like once I am stuck on a problem, I find myself closing up, unable to voice it, as if asking for help is a sign of incompetency.


What features should a programming language have to say it has good reusability?

What should a programming language have so that it can be said to promote good reusability? Only generics and functions come to my mind when I hear the word reusability. What else make a programming language good for writing easily reusable code?


Is it possible to call a Javascript function from C?

I'd like to find a way to call Javascript functions from C. Are there any language bindings available for this purpose? I'm trying to make a library of Javascript functions accessible from C. (Something like a C -> Javascript foreign function interface would be suitable for this purpose, but I haven't been able to find one so far.)


Switching domains in one's career?

I have been a C++,Qt programmer for the last 3.5 years and have hit a plateau in terms of doing something new. Work has been repetitive and routine. I personally believe it is time to move on but off late I am getting more offers in mobile development like Android,Iphone etc. The latest offer I have is for objective-C based profile. I do not have the slightest idea about objective-C apart from that it is Object oriented C resembling C++ but not exactly a clone. Questions in my mind are   * what are the pros/cons of this careers switch or for any such switch?    * Is it good for one's career to change domains after sometime?   * How difficult it is to get back to one's previous area of proficiency? Thanks


Should we ever delete data in a database?

I am new to databases and trying to understand the basic concepts. I have learned how to delete data in a database. But one of my friends told me that you should never delete data in a database. Rather, when its no longer needed, it's better to simply mark it or flag it as 'not in use'. Is that true? If so, how would a big company like IBM handle their data for a hundred or more years?


Mutable and Immutable version of Collection implementations or both stuffed into one via .makeImmutable()

I am currently working on a collection implementation in JavaScript. I need a mutable and an immutable version of that. So what I thought of first was something like:   * _Collection_   * _MutableCollection_ extends _Collection_   * _ImmutableCollection_ extends _Collection_. My main issue with this is that if I want to implement more specific collections like _List_ or _Set_ , they could still inherit from _Collection_ while their Mutable/Immutable implementations could not inherit from _MutableCollection_ / _ImmutableCollection_. So this made me think whether having all three, _Collection_ , _MutableCollection_ and _ImmutableCollection_ would actually bring any significant benefit. An alternative approach which came to me would be to only have _Collection_ and then have a _Collection.prototype.makeImmutable_ or _freeze_ there. I would then also introduce a _Collection.requireMutableInstance( collectionInstance )_ which can be used in functions explicitly requiring a mutable collection. Here are my main concerns about putting everything into just _Collection_ :   * The prototype definition is getting much bigger compared to defineing a _MutableCollection_ prototype as well which would then hold the code of all the operations for alteration. I guess I could solve this by just defining a second file anyhow which would then just extend the basic _Collection_ definition with those additional operations and the _makeImmutable_ operation.   * Documentation of those function signatures that actually care about mutable vs. immutable and not just require the basic collection would look less pretty. Take:               /**      * @param {MutableCollection} collection     /*     function messAroundWithSomeCollection( collection ) { /* ... */ }      vs.               /**      * @param {Collection} collection A collection not yet made immutable.     /*     function messAroundWithSomeCollection( collection ) { /* ... */ }      What would be the more _natural_ way of doing this in JavaScript? Especially without having interfaces I can check against and considering the flatter chains of inheritance if I would also implement a _Set_ and _Map_ collection, the everything-in-one approach seems more intuitive to me.


Codeigniter + JQuery + Processing.js to replace a Delphi App

So, I've got a mandate to make our aged trillion lined Delphi app web based and it needs to make heavy use of the `<canvas>` element (HTML5 compatibility doesn't seem to be a big issue since we can just make our clients use a compatible browser the way we'd make them use a compatible version of Windows in the win32 environment). The Delphi app in question is almost completely database driven and will still pretty much continue to be developed as the main product. What I am tasked with is pretty much recreating a scaled down version of the program that performs the major functions of the whole program. I couldn't find any frameworks that simulate windows forms using the canvas element, I'm assuming this is probably by design since it is easier just to use HTML, well, be that as it may, I still think it would be cool to have a few of my cool controls on the web (TRichView and TVirtualTree, etc...) So my question is, to anyone who has tried this before, A.) What can we use for an IDE to code this web app (I just use emacs, but no one else in my company does)? B.) Is it a good idea to mix PHP and Processing.JS? It seems like I'm using a lot of AJAX to get anything to happen. 3 calls just for one dialog box to pop up,   1. Loads the HTML for the dialog,    2. Loads the XML to populate the database info on the form   3. Loads the processing.js PJS file which draws the database info to the canvas.  Is three a lot, do people usually combine all their gets into one?


.c FIle Dedicated to Data

Is it completely unheard of to have a `.c` file dedicated to just data? In my case, I'd be using it for global variables that are shared across two other `.c` files. Here's specifically how I'm using it.               // serverth.h          struct serverth_parameters {         struct { // right now, this is the only struct needed             char * root,                  * user,                  * public,                  * site;         } paths;              // I anticipate needing another struct here          };          #ifndef SERVERTH_SOURCE     extern struct serverth_parameters parameters;     #endif      * * *               // serverth.c          #define SERVERTH_SOURCE     #include "serverth.h"          struct serverth_parameters parameters = {         .paths = { // macros are actually used here             "/srv",             "/user",             "/public"             "/site"         }     };      * * * `parameters` is a struct that's used for a websockets server, in two files:   * One for HTTP (uses `parameters.paths.site`)   * Two for proprietary protocols (both use `.paths.user`, one uses `paths.public`) Is this a bad practice? Do people do this? Or, is it more conventional to just keep the data in the source file in which it is most relevant?


What are some easy-to-implement scaffolding systems?

Often when stating a new project I'll require a _"quick 'n' dirty"_ content management solution. Ideally something that can read my database schema and generated HTML forms. Previously I've used; phpMyEdit and phpMyAdmin but they are lacking is key areas. My wish list woulds be:   1. Database independent   2. Foreign key aware   3. Handles views as-well-as tables   4. Generates modern HTML and CSS   5. AJAX interface. What's your swiss army knife when it comes to CMS on a project?


Should I expect my peers to read or practice on a regular basis?

I've been debating asking this question for some time. Based several of the comments I read in this question I decided I had to ask. This feels like I'm stating the obvious, but I believe that regular reading (of books, blogs, StackOverflow, whatever) and/or practice are required just to _stay current_ (let alone excel) in whichever stack you use to pay the bills, not to mention playing with things outside your comfort zone to learn new ways of doing things. Yet, I virtually never see this from many of my peers. Even when I go out of my way to point out useful (and almost always free) learning material, I quite often get a sense of total apathy from those I'm speaking to. I'd even go so far as to say that if someone doesn't try to improve (or at least stay current), they'll atrophy as technology advances and actually become less useful to the company. I don't expect people to spend hours a day studying or practicing. I have two young kids and hours of practice simply aren't feasible. Still, I find **some** time; perhaps on the train, at lunch, in bed for a few minutes, whatever. I'm willing to believe this is arrogance or naivete on my part, but I'd like to hear what the community has to say. **So here's my question:** Should I expect (and encourage) the same from my peers, or just keep my mouth shut and do my own thing?


How to move a car around an environment with hills in C++?

I don't have any code for this since I don't know how I am meant to do this. I have a car and I am able to move it around on a flat plane and I have that working correctly. However, I want it to also be able to move up hills accurately. So that when I drive up a hill the front wheels start going up first and then the back wheels follow like a normal car would. So far all I have managed to be able to do is when one point of the car reaches an incline the whole car moves to that new y value instead of just the section of the car that is supposed to. Does it require some kind of translation and rotation applying to it so that it reacts correctly?


Modelling highly specific business requirements

How can one go about modelling highly specific business requirements, which have no precedent in the system? Take for example the following requirement: ` When a purchase order contains N lines, is over X value in total and is being recorded against project Y, an email needs to be sent to persons A and B with the details ` This requirement supplements other requirements surrounding purchase orders, but comes in at a much later date in response to some ongoing problem elsewhere in the business. Persons A and B are not part of any role or group in the system, and don't hold any specific responsibility; they are simply the two people the business has appointed to receive these emails in this very specific case. Projects are also data driven, so project Y has no special properties to distinguish it from any other project. The only way to identify it is to compare its identifier to a magic number. **How can one go about modelling this kind of case without introducing too much additional complexity?** That I can think of right now, there are a couple of options.   1. **Perform the checks and actions inline with the existing code.** Here we find the correct spot in the code, check the conditions in the requirement and send the emails to hardcoded addresses. Of course this is fraught with issues. At the very least it stops working if one of these people leaves or changes their email address. At worst you have to ensure that any tests and test data are aware that additional actions are taken for a specific set of criteria.   2. **Introduce some form of events system.** Here we introduce an eventing system, so that we might react to some event, and fulfil the requirement outside of the usual path of execution. This sounds like a cleaner solution than option 1, but the work involved is ultimately probably slightly overkill for this one small requirement. That said, having it in place does allow the system to handle these kinds of specific requirements consistently and easily in the future. **Are there any other (good/better) ways of handling highly specific requirements?** I mean other than telling the other parts of the business no!


How to design console application with good seperation of UI from Logic

1. Is it considered an overkill for console application to be design like MVC , MVP or N tier architecture? If not which is more common and if you can link me to simple example of it.    2. I want to implement a tic tac toe game in console application.   I have a solution which hold two projects: `TicTacToeBusinessLogic (Class library project)` and `TicTacToeConsoleApplication (Console application project)` to represent the view logic. In the `TicTacToeConsoleApplication` I've `Program.cs` class which holds the main entry point (`public static void Main`).   Now I face a problem.   I want the game to handle its own game flow so I can: Create new GameManager class (`from BL`) but this causing the view to directly know the `BL` part. So I'm a little confused how to write it in an acceptable way. Should I use delegates? Please show me a simple example.


MySQL setup for remote site failover

I'm designing a custom web-based inventory management and workflow system for a client of mine. One of their remote sites has fairly sketchy internet access, and needs to have no (or very little) interruption of business when their connection to the universe goes down. I'm picturing some sort of local installation of the web app with MySQL replication keeping their local DB up to date. When their connection out of the building fails, they can manually kick over to the local URL, which is configured to hit their local MySQL, and they stay in business. Question is, replicating those changes back up to the real master. I know of such a thing as master-master replication, but will that really hot-sync divergent tables back together when the connection comes back up? It's some help that the remote site's use case is fairly unique, and it's likely (though not guaranteed) to write only to tables related to their wing of the business. I could perhaps limit the "failover mode" local application to only those pieces of the app that are unique to their location, which would be enough to keep them in business. How would you approach this?


Specifying Query in Unit Test

When writing unit tests, should I specify the query that will be performed for interacting with the database? I can see both sides of this. On one hand, I want to make sure that the query that I specify is being performed. But I can be making the test more brittle due to the formatting of the query. **EDIT:** Basically the code would be a mapper object that interacts with the db layer. But I am wondering how specific do I need to be in my interactions with a Db object. **Edit:** As I want to mock any external dependencies to my objects when I am mocking my Database connection. Should I specify the query that is going to be performed. For example:               testGettingUsers() {         $mockDb = $this->getMockBuilder('My_DB_Connection')              ->setMethods(array('query'))              ->getMock();              $mockDb->expects($this->once())              ->method('query')              ->with('SELECT id, name FROM USERS WHERE name = foo')              ->will($this->returnValue($dbReturn));      Here I have specified my query as the parameter that I am going to call my DB connection with. Is that necessary?


What .NET objects should I use to create a cookie based session in MVC?

I'm writing a custom password reset application that uses a validation technique that doesn't fit cleanly with ASP.NET Membership Provider's challenge questions. Namely I need to invoke a workflow and collect information from the end user (backup phone number, email address) after the user logs in using a custom form. The only way I know to create a cookie-based session (without too much "innovation" on my part) is to use WIF.   * What other standard objects can I use with ASP.NET MVC to create an authenticated session that works with non-windows user stores? Ideally I can store "role" or claim information in the session object such as "admin", "departmentXadmin", "normalUser", or "restrictedUser" * * * The workflow would look like this:   1. User logs in with username and password   2. If the username and pw are correct a (stateless) cookie based session is created   3. The user gets redirected to a HTML form that allows them to enter their backup phone number (for SMS dual factor), or validate it if already set.   4. The user can then change their password using the form provided The "forgot password" would look like this   1. User requests OTP code to be sent to the phone   2. User logs in using username and OTP   3. If the OTP is valid and not expired then create a cookie based session and redirect to a form that allows password reset   4. Show password reset form, and process results.


How to backup data and images in this project?

I have MS C# and MS SQL 2008 database project. It can capture employees' records with pictures of more than 1000 records. Presently, I'm able to capture say 150 records on PC1 using my installed C# application, save the records into XML or CSV file format. My friends are able to continue registration or entering (i.e from 151 to 1000) after restoring or uploading the information contained in that XML or CSV using another copy of my C# application installed on their laptops at another location.   1. How can the content be hidden or locked from user viewing its content except for my C# app reading or writing to it (not necessarily in XML or CSV format)?   2. If I still use same XML or CSV, how can the file be compressed to smaller sizes?


What is the clean way to pass my LoginContext down through the layers to the data access layer?

I have inherited an API implemented using ASP.NET WebApi 2. The actions on the controllers are all like this:               public object Get(long id) {         LoginContext loginDetails = GetLoginDetails();         if (loginDetails.IsAuthorised) {             return _dependency.DoSomething(loginDetails, id);         }              return new HttpResponseMessage(HttpStatusCodes.Unauthorised);     }      The `_dependency` will have many methods all with similar signatures, and it will have dependencies of its own, and those will also use the `LoginContext` class until you finally reach the bottom of the call stack at the data access layer, where the `LoginContext` class is actually used. Dependencies are currently all injected into the constructor by the IoC container. So there are a number of issues here that bother me - the repetitive checking in each controller action that the user is authorized, and the need to have a `LoginContext` on every method of every dependency referenced anywhere by the controller. Now in the first case, I have created an action filter that handles the authentication, and writes a custom identity (which contains the `LoginContext` details) back to the `HttpContext`. That then leaves the meat of my question - what is the best way to pass my `LoginContext` down through the layers to the data access layer? **UPDATE:** just to clarify, in response to some of the questions below, authentication itself is not being checked by the data access layer (although the business layer will obviously do things differently based on the caller's authorisation claims); but rather we are passing data gathered during the authentication process to the data access layer, where it is then being used to access particular resources, or for infrastructure concerns such as auditing. The problem still remains though, should every method of my business layer and every method of my data layer, take a LoginContext as one of its parameters, or are there better ways?


Is it okay to mock multiple objects in one class?

For developers with extensive experience using mocks, **is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended?** I am wondering because mocks are stubs anyway, from a testing perspective, it doesn't seem to make a big difference if I consolidate mocks. However, I do wonder if there are negative impacts from a maintenance/clarity POV.


What is the best strategy for quickly implementing small business applications?

I'm not a software developer, but I have previously developed a project- specific Access application for another employer. My current employer would like me to help organize their workflow and data for an upcoming project, and I was considering using Access again. In previous projects the staff used large piles of Excel spreadsheets; now they would like to keep their data more organized as well as automate some processes. I've found that it is difficult to create forms in Access that are pleasant and usable, due to the limited control over forms. Are there better options for quickly developing a business application, such as MS LightSwitch, Delphi, or .NET? The team that will be using the application is small - less than five users.


Is path in Set-Cookie URL encoded?

I'm writing some code that sets cookies and I'm wondering about the exact semantics of the `Set-Cookie` header. Imagine the following HTTP header line:               Set-Cookie: name=value; Path=/%20      For with path does this set the cookie? `/` or `/%20`(unescaped) (`/%20` or `/%2520` escaped)? The reason I'm asking is that I should support non-ASCII paths. Since HTTP header must only be ASCII my plan was to URL escape the path value but the HTTP specification is not as clear as I'd hoped for. **Edit** I know what Path is supposed to do. My question is: Is the value interpreted as percent encoded or not?


App Store: Why did I get paid less than it says in iTunes Connect?

Ok so not really a programming question... but it is very relevant for any non-US Apple Devs. - Basically, iTunesConnect lists my last payment as $248 NZ (I live in NZ, I signed the basic US tax contract that says I do not live in the US). The payment I received in my bank account a while ago was $221. That's about a 10% difference, maybe because of some type of tax? However, I was under the impression that I should not be getting taxed, and that it was up to me to declare and pay the tax in my own country. - So for any other non-US iOS devs - do you also see this 10% difference - if so, where does the 10% go to (NZ, US, or my bank?). If not, what am I doing wrong, and how should I be doing it? Any help is much appreciated! Thanks :)


Versioned Resources to Improve Cacheability

Here's an API concept which could be useful for performance optimisation. It's an example of key-based cache expiry applied to a broader internet-wide context instead of the internal Memcached-style scenario it seems to be mostly used for. I want to make API calls almost as cacheable as static images. Using a news/feed subscriber as an example, which we might poll hourly, the idea is to send a last-updated timestamp along with each topic (it could just as easily be a version number or checksum):               {       username: "Wendy",       topics: [{         name: "tv",         updated: 1357647954355       },       {         name: "movies",         updated: 1357648018817       },       {         name: "music",         updated: 1357648028264       }]     }      To be clear, this resource itself comes directly from the server every time and is not cached on the edge or by the client. It's our subsequent calls for topics that we can aggressively cache, thanks to the timestamp. Assuming we want to sync all topics, we'd have "N" further calls to make in a naieve implementation (`/topics/tv` etc). But because of the timestamp, we can construct a URL like `/topics/tv/1357647954355.json`. The client usually doesn't make a call at all if it's already seen (and cached) the same version of that resource. Furthermore, even if it's new to the client, an edge cache (e.g. a reverse-proxy like Squid, Varnish, or service like Cloudflare) probably _has_ seen it before, because some other user has probably opened the latest version of this topic already. So we still bypass the application server; the server only ever creates topic JSON once after the underlying resource has updated. So instead of N+1 calls to the server, the client probably makes a much smaller number of calls, and those calls will rarely hit the app server anyway. **Now for my question** All this seems feasible and worth doing, but my question is if there's any prior art for this kind of thing and in particular, any HTTP standards to support it. I initially thought of conditional caching (ETags and modified dates), and I think they'd help to optimise this setup further, but I don't believe they are the answer. They are subtly different, because they require calls to be passed through to the application server in order to check something's changed. The idea here is the client saying "I already know the latest version, please send that resource back to me". I don't think there's any HTTP standard for it, which is why I propose a URL scheme like /topics/tv/1357647954355.json instead of some ETag-like header. I believe some CDNs work this way and it's surprising to me if there's no real HTTP standard around it. **Update:** On reflection, an important special case of this is what a web browser does when it fetches a new HTML page. We know it will immediately be requesting CSS+JS, so the same versioning/timestamp trick can be used to ensure those static resources are cache-friendly. That this trick has not been formalised by the spec gives me confidence that unfortunately there is no HTTP standard for it. http://www.particletree.com/notebook/automatically-version- your-css-and-javascript-files/


Fiscal quarter vs calendar quarter

I'm building a Date/Time class with a "configurable quarter" system as follows.   * User specifies which month the quarter starts at (config)   * Set of functions to deal with quarters (next quarter, prev quarter, etc)   * All quarter functions respect the config Now this class is primarily to be used for fiscal quarter calculations. So assuming I have this class with a configurable "quarter" system, would I need another parallel set of functions for calendar quarters too? What are the applications for calendar quarters anyways? By calendar quarters I mean where Q1 is Jan-Mar, and Q4 is Oct-Dec. By fiscal quarters I mean whatever standard your Country uses (in India Q1 starts in April)


Use a template to get alternate behaviour?

Is this a bad practice?               const int sId(int const id);          // true/false it doesn't matter     template<bool i>     const int sId(int const id) {         return this->id = id;     }                       const int MCard::sId(int const id){         MCard card = *this;              this->id = id;              this->onChange.fire(EventArgs<MCard&, MCard&>(*this, card));              return this->id;     }                       myCard.sId(9);          myCard.sId<true>(8);      As you can see, my goal is to be able to have an alternative behaviour for sId.   I know I could use a second parameter to the function and use a if, but this feels more fun (imo) and might prevent branch prediction (I'm no expert in that field). So, is it a valid practice, and/or is there a better approach?


Dynamic Query Generation : suggestion for better approaches

I am currently designing a functionality in my Web Application where the verified user of the application can execute queries which he wishes to from the predefined set of queries with where clause varying as per user's choice. For example,Table ABC contains the following Template query called SecretReport "Select def as FOO, ghi as BAR from MNO where " SecretReport can have parameters XYZ, ILP. Again XYZ can have values as 1,2 and ILP can have 3,4 so if the user chooses ILP=3, he will get the result of the following query on his screen "Select def as FOO, ghi as BAR from MNO where ILP=3" Again the user is allowed permutations of XYZ / ILP My initial thought is that User will be shown a list of Report names and each report will have parameters and corresponding values. But this approach although technically simple does not appear intuitive. I would like to extend this functionality to a more generic level. Such that the user can choose a table and query based on his requirements. Of course we do not want the end user to take complete control of DB. But only tables and fields that are relevant to him. At present we are defining what is relevant in the code. But I want the Admin to take over this functionality such that he can decide what is relevant and expose the same to the user. On user's side it should be intuitive what is available to him and what queries he can form. Please share your thoughts what is the most user friendly way to provide this feature to the end user.


How do you keep focused through long compiles

I find it fairly simple keep focused on a task at hand whilst I am actively engaged on it, however, during a long compile (and our current main project can compile in 5-10 mintues on a bad day) that my focus will drift. I'll start procrastinating, check the web, talk to someone, start thinking about something else, and just generally lose my attention, and realise that the compile had finished a while back and I have lost my train of thought, or worse, a lot of time. This is hurting my productivity, and whilst it has not been mentioned by anyone, I think it's a habit I should stop. I have tried white-noise generators (brilliant whilst I have something to focus on), shutting down my web connection and the like, however, through long compiles what can I do rather than stare at the monitor? What tricks or tips can be used to keep focused without spending large amounts of your day starting at a compile in boredom, just to ensure you don't miss it finishing? Hang on, my build broke 10 minutes ago ... :) Finally, I am fairly sure this question isn't a dup of this, as as I am talking specifically about compile times, rather than waining motivation. Foosball is not an option, rather the problem :) **EDIT** People trying to gloat about their language of choice compiling faster are not really helping, nor being particularly amusing. Thanks anyway.


Experience With Similar Technologies: Convincing HR People?

Let's say that a job posting asks for experience in technology X. You have no experience in X but you do have experience in technology Y, which you're convinced is similar enough that the learning curve to be productive in X would be extremely short. How do you get hiring people, especially HR people without much technical background, to look past your lack of experience in X and take you seriously? Examples:   * You're applying for a Java job and have never used Java except for some very small toy projects. However, you do have substantial experience in C#, which is clearly derivative of Java and promotes the same style of programming (class-based OO, static typing, autoboxing, etc.)   * You're applying for a C job. You've never worked on anything written in straight C, but you have done substantial work in C++ and used the C-like subset (raw pointers, malloc/free memory management, void* pointers, etc.) for some of the low-level parts of the project.   * You're applying for a C++ job and you've done extensive work in D. D is intended to be a reengineering of C++ and includes the key concepts like RAII, templates, the ability to manage memory manually and do low-level work, etc. Furthermore, you're aware of exactly where the differences lie from extensive discussions on language design in the D community. Edit: I guess my more fundamental question that inspired this post is, "Why do most job ads place so much emphasis on specific technologies (which aren't hard to learn on the fly if you grasp the underlying concepts) instead of fundamental language-agnostic skills?" If I were running a language X shop, I'd much rather hire a top notch programmer regardless of specific technologies and assume he'd pick up X pretty fast than hire an expert in X who had mediocre fundamental, language-agnostic programming skills.


Translating between Python-Django and Javascript

I have a conceptual question about 'translating' between objects I have stored in Django (in Postgres) that I want to use on the front-end. So I have a user object in Python that holds basic things: an id, a username, a password. Let's say I want to output all of that information using Javascript on the client side. Can I just give JS a python object and it will make it into a JS object? I know JS is known for being 'fast and loose' with typing but that just seems absurd! I'm not looking for syntax, but just an overview of how this would work. Can I put Python objects in AJAX requests, then translate them client side, or is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?


Looking for an algorithm to connect dots - shortest route

I have written a program to solve a special puzzle, but now I'm kind of stuck at the following problem: I have about 3200 points/nodes/dots. Each of these points is connected to a few other points (usually 2-5, theoretical limit is 1-26). I have exactly one starting point and about 30 exit points (probably all of the exit points are connected to each other). Many of these 3200 points are probably not connected to neither start nor end point in any way, like a separate net, but all points are connected to at least one other point. I need to find the shortest number of hops to go from entry to exit. There is no distance between the points (unlike the road or train routing problem), just the number of hops counts. I need to find all solutions with the shortest number of hops, and not just one solution, but all. And potentially also solutions with one more hop etc. I expect to have a solution with about 30-50 hops to go from start to exit. I already tried: 1) randomly trying possibilities and just starting over when the count was bigger than a previous solution. I got first solution with 3500 hops, then it got down to about 97 after some minutes, but looking at the solutions I saw problems like unnecessary loops and stuff, so I tried to optimize a bit (like not going back where it came from etc.). More optimizations are possible, but this random thing doesn't find all best solutions or takes too long. 2) Recursively run through all ways from start (chess-problem-like) and breaking the try when it reached a previous point. This was looping at about a length of 120 nodes, so it tries chains that are (probably) by far too long. If we calculate 4 possibilities and 120 nodes, we're reaching 1.7E72 possibilities, which is not possible to calculate through. This is called Depth-first search (DFS) as I found out in the meantime. Maybe I should try Breadth-first search by adding some queue? The connections between the points are actually moves you can make in the game and the points are how the game looks like after you made the move. What would be the algorithm to use for this problem? I'm using C#.NET, but the language shouldn't matter.


Should one reject over-scoped projects?

I spoke to my first potential client today and he told me about the requirements of his project - an Android app. He is a well-known designer / photographer in my country and now wants me to "convert the website into an app, custom-tailored". So the requirements, details stripped out, are as follows:   * eCommerce   * Aggregating all his content like videos, blogs, tweets, etc. into the app   * Live streaming any of his studio demos   * Augmented reality. So that people can see what his painting will look like on their wall before they buy it   * Taxi Sharing Now, for a freelance project, it seems too over-scoped. I am not saying that I cannot do it. I can. But let me be realistic:   * There is a steep learning curve when it comes to VR.   * I am not a tester. I have never white-box tested my own apps. I always black-box test.   * Since he is a renowned artist, something short of perfect _might_ harm his public image So, I asked him for 2 weeks' worth of time before I give him the final answer. Now knowing whom to consult for advise, I am posting the question here. Although interesting and personally challenging, I am split-minded about accepting a project like this. I will be **the only developer** for this. **Should one reject a project that seems to be over-scoped for one's own abilities?**


How to model a many to many from a DDD perspective in UML?

I have a two entity objects Site and Customer where there is a many to many relationship. I have read you try not to model this in DDD as it is in the data model and go for a unidirectional flow. If I wanted to show this in UML, would I show it as it is in the data model: `Site * ----->*Customer` but the direction arrow gives the flow? or as following `Site ----->*Customer` But then this would imply that Customer can only go in one site.


How to measure the quality of my use cases?

When I'm coding something I know that there are many ways to see if my code is good or not. First is testing: I can do unit tests or even test the software by myself and see that it works or not. After getting it working, I can analyze the coupling of the code and so on to refactor and make it better. In that sense, I'm confident when coding because I have a way to know if what I did works or not and ways to think it better if it doesn't work. When designing the software though I'm mainly having difficulties to analyze whether the uses cases I write are good or not. I've read lots of theory on use cases, but the practice is being a little hard because I always find myself questioning things like: "should this be included? is this necessary to say here? isn't it missing something?" and all sorts of things like that. So, how can I "test" my use cases? How do I know if they are well written or not? I know in OOAD iterative approach, we don't try to get it right on the first iteration, however it should at least contain the exact information to get me started in coding, and I don't now how to discover if it does contain that information.


C# vector class - Interpolation design decision

Currently I'm working on a vector class in C# and now I'm coming to the point, where I've to figure out, how i want to implement the functions for interpolation between two vectors. At first I came up with implementing the functions directly into the vector class...               public class Vector3D     {         public static Vector3D LinearInterpolate(Vector3D vector1,             Vector3D vector2, double factor) { ... }              public Vector3D LinearInterpolate(Vector3D other, double factor { ... }     }      (I always offer both: a static method with two vectors as parameters and one non-static, with only one vector as parameter) ...but then I got the idea to use extension methods (defined in a seperate class called "Interpolation" for example), since interpolation isn't really a thing only available for vectors. So this could be another solution:               public class Vector3D { ... }          public static class Interpolation     {         public static Vector3D LinearInterpolate(this Vector3D vector,             Vector3D other, double factor) { ... }     }      So here an example how you'd use the different possibilities:               {         var vec1 = new Vector3D(5, 3, 1);         var vec2 = new Vector3D(4, 2, 0);         Vector3D vec3;              vec3 = vec1.LinearInterpolate(vec2, 0.5); //1         vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2              //or with extension-methods              vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)         vec3 = Interpolation.LinearInterpolation(vec1, vec2,         0.5); //4     }      So I really don't know which design is better. Also I don't know if there's an ultimate rule for things like this or if it's just about what someone personally prefers. But I really would like to hear your opinions, what's better (and if possible why ).


Does OpenMp have support for Real Time Multiprocessor Computing?

I am working on a real time multiprocessor scheduling algorithm. I found very few results via google research related to it. A few simulators are available but are not robust enough. OpenMp is an API I have previously used for small parallel application development. But I am not sure if it provides any support for real time parallel computing which involves time related parameters such as task period, deadline etc. Are those features available in OpenMp? If not, are the underpinnings available so I could extend OpenMp instead?


How to inherit from two parent classes

I have many classes with many relationship I draw Uml that relation between them: > ![enter image description here](http://i.stack.imgur.com/tw1H9.jpg) Is this relation true and how to implement this?


How is major software protected?

I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands. Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands). What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?


Will giving new recruits a separate subproject from experienced developers help the newbies ramp up more quickly?

We have 7 developers in a team and need to double our development pace in a short period of time (around one month). I know there is a common sense rule that "if you hire more developers, you only lose in productivity for the first few months". The project is an e-commerce web service and has around 270K lines of code. My idea for now is to divide the project in two more or less independent sub- projects and let the new team work on the smaller of the two sub-projects, while the current team works on the main project. Namely, the new team will work on checkout functionality, which will eventually become an independent web service in order to decrease coupling. This way, the new team works on a projects with only 100K lines of code. My question is: will this approach help newbie developers to adapt easily to the new project? What are other ways to extend the development team rapidly without waiting two months until newbies start producing more software then bugs?


Using a binary from a project that violates GPL

There is an open source project which uses GPLv2. It had numerous releases that complied with GPL in the past where source code was available for given binaries. The newest source code is about 18 months old and is being called a last "official release". Since that OSed "last version" further development has been done by a single main developer. Features have been added and it is clearly visible that the code must have been changed. The main developer only holds part of the copyright for the whole package (it is not 100% his work, the project was started as a fork of another GPLed project). Lets call the ongoing development a TRUNK branch. The problem is that the latest development is done as closed source and **only binaries are being distributed for the TRUNK branch and no source code** was revealed yet. While this most likely is a GPL violation and is a bad thing itself, I dont mind this (even as I should) because I want to use the TRUNK binaries. My question is - **what is the legal status of such TRUNK binaries** that have no source available to them? Are these poised somehow? I want to use the binaries in my project which is open source itself but the binaries would be used in a standalone working unit that only is used for data acquisition so I most likely wont need to modify the unavailable TRUNK source code anyway.


Purpose of the csx folder in Azure projects?

I'm fairly new to Azure but I noticed that Visual Studio auto-creates the following folders (among others)               ...     /<nameOfAzureProject>/bin     /<nameOfAzureProject>/obj     /<nameOfAzureProject>/csx <==     ...      Now the bin and obj folders are fairly standard. But I'm not clear about the purpose of the **csx** folder. Any ideas?