instruction
stringlengths
34
19.9k
If I use an unsealed trait or abstract class in Scala and then use pattern matching, I wonder, does the compiler not know at compile time for this particular patternmatch what possible implementations of this trait/class are available? So, if it does, could it not give pattern match warnings even though that the trait/...
I am working on a collaborative project, for which I have to submit source code, which will be used/embedded in the main repository for re-compilation. Is there any way, I can encrypt the source code or may apply some other technique so that I can remove the readability of my code completely, but it still compiles well...
I have some code that tightly couples Product specific code and Product-Access code. I am not sure how to untangle it. So for example, for testing Product, I have to mock up Access objects. And maybe there is no way around it, but maybe there is. I have code that goes something like this: class Product { functi...
I wish to release a non-commercial python application under GPL3 in both source and (PyInstaller) executable form. I'm struggling to find a consistent answer to the problem of imported modules. Can I just put the usual GPL headers on my source files, include the GPL in COPYING and leave it at that? Or do I have to coll...
I saw around that development teams usually use source control in one of 2 schemes: Either "Feature Branch", where each feature is developed in a new branch, or "Developer Branch", where each developer in the team has a dedicated branch for his work. I understand the technical differences, but I don't really understand...
In my project, I'm going to create lots of mini games. Those mini games can last 30 seconds to 1 week (the duration of the game is decided when it is created and is fixed). The number of concurrent games can be large (more than 1 game per user and we hope to have many users of course :-)). Nothing really happens during...
I'm learning MVC and the book I'm using favors strongly-typed views. Some of these concepts are new to me and I'm trying to better understand the design philosophy. Strongly typed views typically result in having to create a ViewModel since the domain entities are unlikely to have all the information a particular view ...
These days, it's fairly common for me to be tasked to make a change that actually breaks the prior spec. I know that one of the major ideas behind TDD is to have a suite that verifies all your changes didn't actually break anything, but what do you do when the change you need to do, by it's very nature, actually must b...
When QA discovers an issue during testing should they... Log the bug with the test case and scenario information and move on testing? Try investigating to determine why the bug is happening? I would think it is normally both, but some people are saying it is not QA's job to even try to find root causes. QA is just me...
Suppose I have a class that looks vaguely like this: class Foo(object): _value = None # XXX: see below def __init__(self, value): self._value = value @property def value(self): """The value of this Foo.""" return self._value def __hash__(self): return hash(self.va...
I'm developing a web application which uses MS SQL for various data: including users, user accounts, user licenses, license prices, invoices. I need to log users' real-time usage of the system, and use that for monthly billing: e.g. log whenever a user gets a specific page/URL and bill users at the end of the month bas...
I have forgotten the term for a class that provides pre-canned objects for use as test data. e.g. If I'm testing a payment module and I need credit card objects of different types, I might have a class in my test scope called CreditCard__something__ with static members or factory methods for creating cards of different...
I'm writing a structural detailing (CAD) software for concrete buildings in C#. I have defined like hundreds of static classes each with one public method and if needed some private methods. Each one of these methods in these static classes does part of the job. They are called from one God static class named Building....
When it comes to code coverage, you often hear about the flaws of statement coverage criteria. We're told that statement does not take into account control structures and branches thereof, and is therefore sub-par compared to other criteria such as branch coverage, condition coverage, and even function coverage. But wh...
I m actually studying Unit testing, reading some articles on the internet and trying to understand how it works exactly, but it's not very clear for me actually. What should I test ? I have seen that it's a good thing to create interfaces and make our testable classes implement this interface (permitting to implement i...
I understand that "data sanitization" mainly deals with cleaning user-entered data to prevent harmful effects (e.g. SQL injection), but what about other forms of cleaning data? E.g., trimming whitespace from text or removing leading zeros from numbers. Do these also fall under "data sanitization"? If not, what is this ...
Which is preferable for both solid technique and secure coding? Example #1: function_one() blah; function_two() blah; print blah; exit; ... Example #2: function_one() blah; function_two() blah; return blah; return blah; print blah; Obviously this is a simpl...
I'm building a service in .NET that process "things" in the background and I'd like to trace the execution of these things per item, not per application. Most logging frameworks (I'm familiar with System.Diagnostics.TraceSource and NLog) work in a way that you generate messages for everything and decide in a configura...
I'm writing a CAD program. Let's say I have in input class, this class reads various data from a text file and creates lots of lists/dictionaries and .... These data need to be accessed by other methods in other classes to be modified. Now here is how I have done it so far: I have one static class: Building.cs When I c...
I used to program in Java. As a result of that I got well-versed with Object Oriented Paradigm. In my opinion it is a great approach to programming because it's easy to unit test, use design patterns, and so on. I am now programming in JavaScript. Should I approach JavaScript with an Object Oriented mindset, too? It se...
In concurrent code, what is the difference between, and the pros and cons of each: Locking on data Locking on functions My understanding is that locking on data is better, and I think I'm doing it, but apparently I am not. Could anyone provide some clarification?
The simplest way to explain this is with an example. You're given then number 19 and you have a set of numbers to choose from: 1, 2, 3, 4, 6 When choosing values from the list (which can be duplicates), the smallest number of values that adds up to 19 is 4: 6, 6, 6, 1 6, 6, 4, 3 Now the list of numbers I want to select...
I need a "lock" that can be either shared or held exclusively, that will provide the following behavior for the following sequence of events: Process A: Requests and is granted a shared lock Process B: Requests an exclusive lock, and is blocked by A's ownership of the lock Process C: Requests a shared lock, and is blo...
I want to start by saying I understand Change Management's job especially when there are government contracts and security policies that must be followed. They are invaluable to prevent the mayhem that would ensue if devs were in control of prod. That being said... I'm working on a project that monitors MSMQ instances ...
I noticed that nearly every time I see programmers using static classes in object oriented languages such as C#, they are doing it wrong. The major problems are obviously the global state and the difficulty to swap implementations at runtime or with mocks/stubs during tests. By curiosity, I've looked at a few of my pro...
I have two callbacks for WM_MOVE and WM_MOVING. Oddly enough, WM_MOVE is being called while dragging the window. I expected WM_MOVE to be called only when I'm done dragging the window. MSDN says that WM_MOVE is sent after a window is moved, and WM_MOVING is when the window is moving. The docs don't show any changes for...
We have to create a web application that will be used as an application form for multiple insurance products (15 in total). This application form will be similar to a form wizard, it will span across multiple pages, depending on what product between 4 and 10. The grand total of all different elements (inputs, select bo...
These types of if-elseif-else blocks appear all over the place, and in no small number (so the less the better). Every time I have to think and decide: Do I want the simpler or the more thorough of the two... and I don't want to think about it anymore. For example, if I am expecting only one of three integers (0, 1, 2...
I was seeing this post on StackOverflow and saw a new way (at least for me) to define a two dimensional array of 5x5, it works well, but I feel I don't understand what is going on in the background. The code is. double (*matrix)[5] = malloc(5 * sizeof *matrix); How can this define a two dimensional array of 5x5?, befo...
If I know what a field will be initialized to, should I initialize it in the field, constructor, or receive it as a parameter? I am asking about best practices. All three options effectively provide the same result. I am not considering what is happening behind the scenes, because I think it would be insignificant. ...
I noticed that many (large) PHP applications use Composer for managing the dependencies. I'm currently trying to figure out if I should switch to Composer (at the moment I'm simply keeping my dependencies in a folder called vendor/ - without being able to automatically update them). I prefer this way because: I don't ...
I have a database table which stores Incident details. Each Incident can have an image saved for it. There are some Incidents which will not have an image for it. I have an API which pulls the image for a given Incident. I have an issue with handling the API in case an Incident doesn't have the image. What is the best ...
A large part of the vert.x architecture is around the message bus, and message passing between verticals. The main idea I guess being that I can create multiple modules (possibly in multiple languages) that communicate via JSON messages that are sent over a message bus (hazelcast). I can imagine that building a message...
With the below piece of thread related code, I see that author of Thread class is hiding the details about the working of start() method. What a user of Thread class need to know is, class Thread would expect a piece of his own code which will be an instance of Runnable's anonymous concrete sub-class that gets passed. ...
I'm attempting to make an online game with a mini-economy in it. The challenge is that the only person selling anything will be the website itself, and hence the supply and demand curve doesn't apply (as it costs the website nothing to produce the items being sold). Products sold will have several factors that contri...
Sorry guys, I should have clarified the fact that the modified method is abstract in Father. Then if the method signature changes, all its implementations in SonX shall also change(at least the signature, though the implementation may stay still). Now the question should be asked like following: Say I have the abstract...
It make sense to see close() as non-core functionality of stream objects. This is the reason this method is placed in interface Closeable. One evidence is that class ByteArrayInputStream does not require the close() operation. public abstract class InputStream implements Closeable {} public abstract class OutputStream...
Douglas Crockford has recently been giving a talk called The Better Parts. The gist of the talk is that JavaScript developers should actually avoid a superset of the The Bad Parts, which now includes new, Object.create, any from of delegation or inheritence, including ES6 classes, and this. Specifically, Crockford reco...
I want to write a simple traffic simulation with one road intersection. First I thought of a cellular automata in the model but it should not be limited by an underlying discrete grid system so the streets could be more independent to location or levels. Currently I can think of three approaches and I would like to get...
It is easy to find the origin of the term OOP coined by Alan Kay when he created Smalltalk, but I can't find if when creating the language he also created the 3 tenets of OOP (Encapsulation, Inheritance, Polymorphism). Especially since he is much more focused on the message passing aspect of the language. So where did ...
Why does Git's stash commit need two parents? In the Hacker's Guide to Git, I see this mental model for stashes: The guide tells me that stash@{0} needs both A and B as parents. Why? Why doesn't the stash just point to B, getting rid of the need for C? I think I am missing something in my Git comprehension.
In something as simple as int sq(int x) { int y = x*x; return y; } versus int sq(int x) { return (x*x); } the former function requires an extra IL step. EDIT: IL code from the first example, using the current C# compiler from VS 2013 Update 4 (.NET Framework 4.5.1), code from the optimized release version: IL_000...
Alright so of course, I know the differences. byte is a primitive and Byte is an object. Byte offers more functions but there is one thing I dont understand. Why would anyone create a variable using Byte? It takes a lot longer. As an example: byte primitive: byte mikeHawk = 5; Byte object: byte blackHawk = Byte.valueO...
I am trying to use template pattern to define a generic algorithm in java. But the method that needs to be overridden, takes an object as input. This object will vary depending on the concrete implementation. So I decided to use inheritance in input parameter. I am passing parent object in the overridden method of the...
I am trying to create a graphics application where the user can use an arbitrary shape as a "brush", which will be swept along the drawing path. The shape may be transformed along the path (rotated, resized, etc). I read this paper, and it seemed promising: Approximate General Sweep Boundary of a 2D Curved Object My u...
Consider the following program: Many people when they want to use a struct, they create a new variable as: struct structureName variableName While it works when you just define it as: structureName variableName My teacher always uses the first method. My question is how do they differ? Do I ever need to specify stru...
I am given a set of tourist attractions(nodes identified by x, y) and i need to find the shortest path to visit them. The way i thought of it, is i will ignore if there are streets available and consider the streets always go the way a segment uniting the two points does. However, i need to find the shortest path throu...
Below is the code that is written using byte stream non-buffer class FileInputStream and FileOutputStream with the usage of explicit user buffers. public class FileCopyUserBuffer{ public static void main(String[] args){ String inFileStr = "C:\\practice_in.jpg"; String outFileStr = "C:\\practice_out...
I am working on a large C++ project. It consists in a server that exposes a REST API, providing a simple and user-friendly interface for a very broad system comprising many other servers. The codebase is quite large and complex, and evolved through time without a proper design upfront. My task is to implement new featu...
In the below server socket program, byte stream object is used to read data from client, as mentioned - InputStream in = socket.getInputStream(); public class SingleThreadTCPServer{ ServerSocket serverSocket; int serverPort = 3333; public SingleThreadTCPServer(){ try{ serverSocket = n...
I'm reading this article by John Funge about Cognitive Modeling for Computer Games: http://www.qrg.northwestern.edu/resources/aigames.org/1999/fungegame99.pdf And some further detailed reading about it in this URL: http://www.msci.memphis.edu/~classweb/public_html/comp7990/Spring2000/Wally/Presentation5/tsld014.htm ...
Being either static or dynamic should be something completely supported in the language. Static vs dynamic shouldn't be something that you have to turn on and off, switching between basically 2 languages. I'm talking full blown mixed typing madness like this thing: class MyClass { function myMethod(x: int, y: int){ ...
It may be a stupid question but in C#, performance wise, an object's size or complexity does matter when you access one of its members through a reference? Or only that specific member is all that matters? I know it's premature optimization but I'm curious.
Sometimes while programming in different languages (C/C++, C#), this thought comes to my mind: Is each and every language written in the C programming language? Is the C language the mother/father of all languages? Is each concept (OOP, etc.) all implemented in C? Am I in right direction?
Say I produce system X, which contains some components (A, B and C, say) which are specific to X, but ripe for generalisation. Let's say X is licensed with a viral open source license ([AL]?GPL). If I decide to break any of A, B or C out as standalone systems, under their own distribution, can they be relicensed, or do...
Embedding data (such as images) in a executable seems to have a few advantages, like easier distribution of the executable and easier compatibility with different OSes. But, is it a good practice? More specifically, how does the OS deals with a big executable? Would it be using much more RAM than needed?
I was chatting with my product manager last week and he was bemoaning the lack of progress on our product. It's a fair criticism, too. So we got to talking about to describe the writing of requirements. I'm a big fan of BDD and using something like the Gherkin syntax to describe how the system should behave in terms...
Based on: C# Keywords Keywords are predefined, reserved identifiers that have special meanings to the compiler. and Based on: Contextual Keywords A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. For Keyword new we have multiple situation for use it, for e...
I'm wondering the performance of reflection in this situation. I'm iterating a (probably) large excel file (let's say 3000 max) which it's going to be done from time to time, and the implementation that my mate is something like this, iterating each row: while (cells.hasNext()) { XSSFCell ce...
Using Dart in the client part of a web app where I have an application manager that contains a List of application instances and references to services that are used by each application as in the following diagram As you can see the application manager is a singleton, so are the services that it contains which are use...
I was wondering why pointers are not included in modern languages now-a-days. I already did research on this on internet, and found out few theories/reasons: Memory leakage is the biggest concern while using pointers. If not handled properly it may ruin whole project or application. Understanding and using pointers in...
In an app, a user can initiate the generation a six-digit alphanumeric code (actually done via Web API). The code needs to be checked against a remote database to ensure it is unique. Other than for diagnostics or logging, the DB table is only used by the Web API and an Azure web job that cleans out expired codes. In m...
I am in the process of developing a tool for a game called MechWarrior: Online which defines a map of an area of space called the Inner Sphere. Essentially, this map is a set of points (planets) on a Cartesian plane. Each planet can be owned by a different faction, typically represented on the map by a colour. I can co...
Let me apologize first if this topic is too subjective, or not concrete enough. I want to implement a login api for an internal web service at my company using asp web api 2. I know how to implement a owin bearer token system for a single user login scenario for a single website. The issue here is that I want to provi...
Is there a class of hash functions that meets the following specs: Upper and lower bound can be specified Uniqueness is guaranteed as long as the input is between the upper and lower bounds Amount of entropy is controllable, or at least high and evenly distributed An example of a low entropy hash function that prod...
In my working environment, over the past few years I have observed an increasing stress on developer management and self-management over technical education. For example, at work I hear lots of discussions about software development processes, about ways to handle software specifications, e.g. through automatic tests, ...
public void warning(){ System.out.println("Watch out!"); } public void warning(){ System.out.println("Watch out!"); return; } We must use "return" statement with void methods. Bot of these bring same output. What's the difference?
Disclaimer: I am not a lawyer, and I don't expect anyone answering this question to also be, and I will not take the answer as legal advice. Starting from a piece of software (in this case, a game mod) that is licensed as CC-BY-SA, can I create a derivative code (another mod, plus art assets) and publish my software as...
After learning about encapsulation in OOP, I started to use only protected and private properties, share data via accessors and change properties via mutators. Right now, I'm afraid of declaring public properties. Is it good to keep everything private and protected or is there some cases where I need to use public pro...
Such a simple question, but I have not found a reasonable answer to this. I currently program in Python, an interpreted language. I always hear of people using multiple languages in the same program? Then I hear them using scripting languages; Can someone on here please in plain english explain to me the difference bet...
Recently I was assigned a task of creating a calculator with functions addition, subtraction, multiplication, division and power using Object Oriented Programming. I successfully completed this task. However afterwards I reprogrammed the whole program without using Object Oriented technique/method. The thing I noticed ...
I have a little project (a CMS) that was developed using .jsp-files in 2006. I moved in 2011 to JSF and had only one .jsp-file for the frontend. In 2014 I integrated the backend into the frontend using JSON and kicked all .jsp-files. I only use servlets now to build JSON-Answers, AJAX-Answers for XHTML and binary stre...
If we need to store some data in a database, but without the need of advanced SQL features, can we use this scheme (written here in Javascript / node.js) : // the DB will be in RAM ! var myDb = {}; // read DB from disk if file exists try { myDb = JSON.parse(fs.readFileSync(DBFILENAME)); } catch(e) { } // serialize ...
Consider the following "C" code: #include<stdio.h> main() { printf("func:%d",Func_i()); } Func_i() { int i=3; return i; } Func_i() is defined at the end of the source code and no declaration is provide before its use in main(). At the very time when the compiler sees Func_i() in main(), it comes out of t...
I am looking for a good pattern to handle cron-type data in a MongoDB collection (or collections). I have been peeking at the O'Reilly book MongoDB Applied Design Patterns and poking around the MongoDB site's Use Cases site but neither seems to to cover this type of data. Is there a good pattern for storing repeating ...
I have this problem, a team with 4 members working under scrum, with specific skills each one of them: Person A) DBA with reporting skills Person B) DBA with stored procedure skills and a very deep knowledge of the business Person C) Developer Person D) Tester Problem 1 Right now, we're at the end of sprint 6, P...
I have a very common function that I have always unit tested in the same way, but I'm wondering if there is a better solution or if it's even possible a code smell is involved. It seems like a very simple case but I have a function that clears the properties of the object. Working in JavaScript, here is a simple exampl...
I'm sure every new iOS developer has the following problem: The View Controllers get very fast crowded with code for various purposes, easily getting to 500 + lines of code. This is how it looks like for two basic and common screens: 1) The Form Screen: 2) The Table View Controller Screen So far I have read about two...
So, I should really know this stuff already, but I am starting to learn more about the lower levels of software development. I am currently reading Computer Systems: A Programmer's Perspective. by Bryant O'Hallaron. I am on chapter 2 and he is talking about the way data is represented internally. I am having troubl...
I've been looking into building an entity-component-system. Basically, an entity is just an id wrapped around a struct, components are data belonging to that entity(and reference said id), and systems are the code. Entities and components are all stored inside arrays, to allow fast iteration over each. For example, an...
To keep my question short and to the point, consider this: $relation = $mysql->query("SELECT relation($loggeduser, $requesteduser) AS a")->fetch_assoc()['a']; if ($relation != BLOCKED) { return $mysql->query("SELECT stuff FROM sometable WHERE powerlevel>9000 LIMIT 39"); } else { return '{"error":"not enough jqu...
I have noticed that many websites have their own mobile apps. For developers, What is the benefit of creating mobile app for a website? In which cases it is better than viewing it using browser? From users point of view it is not always good. Why should I install separate app for every website I often visit? Mobile ap...
Given a matrix A with 0 and 1 entries. Neighbours of a[i,j] are a[i-1,j], a[i+1,j], a[i,j-1] and a[i,j+1] (if exists any). Tow neigbour entries are an Improper pair if they have not equal values. if number of improper pair of matrix A equals to q, then the penalty of matrix will be equals to b*q (which b is a natural n...
I was reading a really great Bjarne Stroustrup's article where he exposes some C++ myths. I look at code that focus my attention, because I wouldn't know that C++ supports this kind of expressions. I'm talking about lambda expressions, or closures. void do_my_sort(vector<double>& v) { sort(v,[](double x, double y) {...
I have 2 controllers: 1 top level controller,MainController, and a SubController, which MainController has an instance of and controls. The SubController has a Subview which goes inside the MainView as some sub web element. What is a good way to insert the SubView into MainView? I can think of: 1) I can give SubContro...
I was wondering what is the prefered way of accessing data from a server in a client application. The data will be stored on the server in an SQL database and I have previously used the following 2 methods for getting at the data: 1) Client's connect directly to the SQL database 2) Client's connect to a web service whi...
I've come from a C++ background and am going all out C# in my current job and I've just been reading a lot of Q&A about what's the difference between public fields and properties and all the back and forth in variations and incarnations of this basic question (e.g. this SO post and all the related linked questions). Al...
Given the following elements: <div class="container"> <span class="some-class">content</span> ..n span repetitions.. </div> Given the following .on() $('.some-class').on('click', function () { ... }); If you redraw the .container with new span.some-class, will you leak the old events? What I mean is, before the r...
As the title of this question suggests, I am looking forward to develop app(s) on Android platform without using Java at all. It doesn't mean I have some kind of vendetta against this beautiful language or I don't know how to develop apps in Java. But I am considering that my application(s) can be developed by only usi...
I'm having some trouble with a game developed in Java which is kinda slow. I benchmarked it a little bit and found the problem: most of the time, the JVM is in the Object.<init>() since there are a lot of objects which gets created and destroyed every tick. This class which gets created this often is a really small cla...
I'm reading some internal documentation for code developed to the MISRA C guidelines, and I see that in compiler flags section of the documentation there is a note to compile with optimisation off (-O0). I'm new to safety-critical development, so in my mind turning off optimisation is overly-pessimistic and modern comp...
I'd like to know whether a task must be self contained. Our tasks mostly contain a couple of sentences. To understand what you are to do you should: Read the requirements document for several related back log items. Know how system currently works and understand how it differs from what is required. In other words: n...
I am trying to get my head around as to why having a local variable or a for loop inside a function is not considered to be pure functional programming. Given this function: int as_int(char *str) { int acc; /* accumulate the partial result */ for (acc = 0; isdigit(*str); str++) { acc = acc * 10 + (*st...
I have the method which returns java.util.Date inside the hibernate-entity class: package ua.com.winforce.loto_partner.commons.db.entity; @Entity @Table(schema = "pr", name = "publice") public class Pr { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; ...
Very often I have to review pull requests of fellow programmers and I face the problem - what should I do when the code is not as good as I would expect? Should I reject the pull request or accept/merge even though I don't like the code? Of course, I reject when I see errors, but I can't keep rejecting again and again....
I'm building a php system with the Services/DAOs/Domain Models pattern, and now is the time to implement a caching system for the DAOs. Would you use a decorator pattern, or maybe the strategy pattern? What are the ups and downs of each one? added requirement: Like I told in a comment answering to edalorzo I need to be...
We know that checking return values prevent our software from unexpected states. (You can see CWE definition.) But, we are sometimes sure about the return value. For example: bool calculateSquareRootReturnFalseIfInputIsNegative(float input, float& output); float calculateHypotenuse(float a, float b){ float c2 = (a*a)...
This is a really simple question but oddly, I'm finding it difficult to get a definite answer.... What do you do with fields? Is this valid? /** * Keeps track of all usernames in the system. */ private List<String> usernames = new ArrayList<>(); Or is above ingnored by documentation tools, so would it be best t...
I joined a project were we sell services for different providers through web, iOS and android apps. I am working on iOS. I was ask to display a purchase form via a web view and react by what is entered natively. I do so by intercepting the network communication but as you can imagine it is slow, error prone and just ki...
I am just learning Java, and am not a practicing programmer. The book I am following says that when overriding a method, the argument types must be the same, but the return types can be polymorphically compatible. My question is why can't the arguments passed to the overriding method not be a subclass type of the su...