instruction
stringlengths
34
36.1k
While most of the top IT companies will ask you (during the interview) to solve a problem applying some data structure, is it good if you define your own class for that data structure? Like if I know this problem is going to b solved by applying a LinkedList, should I make my own implementation of a LinkedList class or...
How can I manage my code to exactly wait for a certain amount of time (say 10s), if all * time functions on the system are not reliable and return immediately ? Sleep(10000); // Do not sleep for 10s and execute directly the next function MyFunction(); The solution should if possible, consume the fewer possible CPU cyc...
As the title states, what is the difference between -> and . I thought they were the same thing?
Question: Talking about software development, how to provide good approaches to achieve a repository of reusable components inside a project? Context: Working on a team of 10 coworkers may be very interesting but could be also unorganized. Duplicated services, components, in other words, shareable code. Documenting and...
I'm designing a RESTful API and wondering what's the best format for validation error messages. For example, my account creation endpoint accepts a JSON object: user: { first_name: string, last_name: string, address: { street: string, city: string, zip_code: string } } My responses will be in the f...
Apparently this algorithm is well known. The algorithm will build the square root answer bit by bit starting from the left-most bit to the last. Let's say we will support squaring up to a 8 bit unsigned integer for simplicity. let res be result let x be 8 bit unsigned integer let n be the nth bit in the result where th...
I've been toying with a project idea for a while now but can't quite settle on one important detail. The plan is to write a client that can author and upload WebMs to a server for global viewing (should the user wish), however, I only want to allow WebMs made with the official application for the sake of consistency. ...
I'm building a web API that is going to be consumed by several internal systems. Naturally the different systems have different requirements. The consumers may create change requests to the API, when they need new features. Everything is within my organization. How do I know when a change request is too specific and wh...
This is a re-post from my question in StackOverflow, so here goes: For the past few weeks now I've been studying Concurrency(Multithreading) in Java. I find it difficult and rather different than anything I've encountered in the Java language so far(or in programming in general). Often I have to reread and reread over ...
According to DDD and the clean architecture, entities should encapsulate data and related logic. So, how do you design a class to represent a particular real world entity? Two alternatives among lots of possible strategies: Firstly, define properties of entity (ask which information should be stored.). Then create req...
This is an embarrassingly basic question, but until recently I have avoided properly understanding IO in Haskell and now I need to. I am writing (with someone else) a program that takes as part of its input a library of background data. So as part of main I'll have a couple of lines such as lib <- library.txt let libra...
I have a test class with about 25 tests that are testing the different aspect of it. I wonder Should I break it down into smaller classes? If so, then what is the best naming/packaging convention? Lets say my class name is abcService and I want to break it down into x, y and z aspect of it. Name test classes as xTe...
I've been learning functional programming in javascript of late, and there's one thing that's been confusing me. I can't quite understand if it's ever okay to redefine variables. Something like: a = a + 1 immediately throws up red flags. a is mutating, so that's a no go. And certainly declaring a variable like so: var ...
I am currently working in an aleady developed C++ project. The existing files are the following: -main.cpp -HydroModel.cpp -ODESys.cpp -HydroModel.hpp -ODESys.hpp -ODESysSol.hpp In the file HydroModel.hpp there are some constants defined in the namespace config, for example namespace config { const unsigned ...
I am testing a REST api. Let's say it returns a JSON structure. What is the best approach to testing the server? Each test step can only succeed if all previous were successful. Structure A: test everything at once - Test method 1: - make server request - assert http response code was 200 - assert returned ...
I am working on a piece of server software that is licensed under the AGPL. I would like to require that all clients to it be released under a free license (GPL preferable, but I'm open to other licenses). Is there a way to do this? Is there a standard way to do this?
I have a save game editor. It uses a library that can read the file and return it in a form of an object. Within that object is an ItemSave object. Also, to be able to interpret the data in the ItemSave object, I need more info (from an xml) which I get by a method in my own code that returns the ItemData object. They ...
I am designing my own little OOP program to simulate Vampires, Wolves, Humans and Trucks and am trying to implement my own limited understanding of Interfaces. (I am still abstracting here and have no code implementation yet, so it's rather a question of OOP design...I think!) Am I right in looking for 'common behaviou...
I'm new to Java, I've been mostly a scripter. I recently started working at an all Java shop and have been investigating the architecture. I've encountered more than one project with a directory structure like this: | src/ ---| api/ ---| app/ ---| dal/ ---| sal/ ---| metrics/ ---| worker/ API, app, metrics are pretty ...
What do you call a tree where each node has an arbitrary number of children (i.e. not necessarily 2)? I'm trying to research some algorithms online, and Google keeps returning results for binary trees when I specify just "tree". I'm looking for a word I can add to my search terms to specify arbitrary branch counts.
The questions are: Do generators break the functional programming paradigm? Why or why not? If yes, can generators be used in functional programming and how? Consider the following: function * downCounter(maxValue) { yield maxValue; yield * downCounter(maxValue > 0 ? maxValue - 1 : 0); } let counter = downCounte...
Is it reasonable to use Makefile targets as scripts? So for example, instead of having a script script_A, script_B, etc, and running them as standard executables with ./script_A, we have a makefile that has targets script_A, script_B, and run them by invoker make script_A. There are no dependencies between the scripts....
For a real-time forum app I'm working on currently. It takes about 1-5 seconds for the sockets on my node.js server to connect and deliver the first payload, which is some database results from mongo. I want to do something while this is happening, since otherwise I get some angular {{ vars }} action going on, which is...
From https://en.wikipedia.org/wiki/Recursively_enumerable_language a formal language is called recursively enumerable (also recognizable, partially decidable, semidecidable, Turing-acceptable or Turing-recognizable) if it is a recursively enumerable subset in the set of all possible words over the alphabet of th...
The Principle of Least Astonishment is a design guideline that you should make your behavior match what people would expect. Don't redefine equality, behave consistently, choose sane defaults, etc. At my company we have several code bases which were written at different times by different people in different styles ...
Consider the following code snippet: class Foo { Baz baz; // ... void bar() { int p = this.baz.doSomething(); if (p == this.x) { throw new FooException('Invalid values', FooException::INVALID_VALUES); } this.x = p * this.y; } // ... } Baz::doSomething() can throw exceptions of the Ba...
In a recent internship, I worked on a project involving traffic detection using radar. The company developed their own unique hardware and ran Windows Compact Embedded on an ARM processor. I thought this was a bit odd (I mean Linux is always better, right? :P) Turns out the root of the concern for the company was, beca...
I'm developing some Javascript front-end code using JQuery with some back-end JSON webservices. IDE is Netbeans, and debugging using that and Chrome. Coming from a C++ background I'm used to small source files, each encapsulating one (or a small handful) of classes. With JS, the lack of simple 'include files' means tha...
In my intership I used the D3.js framework to visualize data, now at the end of the internship I'm going to write a documentation about the project as a whole. Only few people in my team have been involved in the project. None of them were involved in the JavaScript writing. As far as I know not many know how to write ...
There are some programming languages, like the many dialects of Lisp, that allow for macro-metaprogramming: rewriting and altering sections of code before the code is run. It is relatively trivial to write a simple interpreter for Lisp (mostly because there is only very little special syntax). However, I cannot underst...
So I've been programming for a few years mostly as an amateur/student, and I'm aware of the fact that using exceptions is generally frowned upon when used as a lack of consideration for input and just a catch-all (e.g., lazy programming). But I have a specific question regarding a programming interview question: Given ...
I'm working on a special project where I need to create a new application with a similar but restricted functionality of an original application (basically a type of free application with limited functionality). Now, the problem comes with the maintenance of the code. I'm using Visual Studio 2013 for the development an...
I have worked in company A for less than 1 year and I was given the task to do a security code review for a small project I was involved in the late 3 months. Until now I have been mainly been reading about common security culprits like SQL injection, XSS, etc. and trying to find these in the codebase. During the revie...
I've started working on an existing project (an sdk) at work, and the code base uses listeners like there's no tomorrow. Pretty much every second method takes some sort of listener argument and I have yet to find an occurrence where the listener is not the calling class or an anonymous class declared when the method is...
In my application - I have to expose services using JAX-RS(for mobile platform) and consume the same set of services in a JSF based web app. Now, I have @Entity beans for persistence layer, @ManagedBean beans from presentation layer and another set of beans for mapping JAX-RS related request objects. Lets take login op...
Recently I've been learning about the different ways languages handle concurrency under the hood, and would like to know a bit more about the shortcomings of M:N threading. Please forgive me if I get some facts wrong in the following paragraphs. I understand event loops (at least the style of event loop used in a langu...
In our business logic we occasionally have methods defined something like this: User.ResetCourse(Course courseToReset) The problem is that both User and Course are Entity Framework proxy objects. This means that when we hit navigation properties on either User or Course it can cause a huge hit to the database because ...
I am using an application, which I know, is c# with WPF. I want to grab data from some of its windows. In detail, i want to grab a grid with all content and the header. If I do copy+paste, i just get all content, but no headers. Is there any way to connect to the process and get a handle to the control and access the c...
This is more of a nomenclature (technical writing) rather than a purely technical question. I am trying to write a refactoring proposal (and get it assigned to myself) centered around expanding dependency injection in our application. While we do use Spring for autowiring beans, there are still instances that instantia...
I have try{ var progress = raw_progress[module_id][modulette_id][tab_id][track_id]; if(progress.started){ count += 3; } if(progress.complete){ count += 3; } return count + 'of_6'; }catch(e){ return '0_of_6'; } ... and the raw_progress object might not have a match on any of ...
Suppose I have Project and Task entities for a to-do list. If Tasks are required to be in a Project, the Task routes would probably look like this: GET /projects/{projectId}/tasks returns all tasks for the specified project POST /projects/{projectId}/tasks creates a new task in the specified project But it's not ...
Why do some Java methods throw exceptions that are subclasses of another exception that they also throw? One example is org.apache.commons.httpclient.HttpClient.executeMethod(HttpMethod method). It throws the HttpException, which is a subclass of the IOException, which it also throws. Syntactically, it would have been ...
This question may apply to other languages but it is explicitly about JavaScript. I've been trying to write a lazy evaluation implementation to filter through an array of elements. The filter process can be made up of 2 functions, F and G, that each check an element against some logic and return a Boolean that is used ...
I have basic viewmodel on server-side, let it be on C# language and ASP.NET Core server-side, for example: public class BookViewModel { public string Id { get; set; } public string Name { get; set; } //other properties removed for brevity } Then, I send it to client page. On client-side, I have rich ...
When I call Stream.sort(..) is there a new array of elements created and the stream iterates over the newly created sorted array? In other words, how Java 8 Stream does sort under the hood?
A web application I'm working on has a tool that queries a database and returns up to several thousand rows. When considering pagination, at what point does it make more sense to get the entire result set at once, and store it in memory, as opposed to making asynchronous calls each time a user changes pages on the tabl...
Trying to understand how experienced programmers tackle programming when they are stuck with a really hairy issues. The situation that I face a few times is like I am stuck with code for quite a few hours, trying to nail down some issue that I don't understand. The approach that I have tried to get out of the situatio...
I'm tasked with implementing a spec for a simple simulated shopping system. The spec however uses strange abreviations everywhere (it has a 2 page long table of nonsense abreviations). For example the contains lines like this: Each potential VG has a AL of VGI's. When replacing the abreviations using the abreviations...
I'm trying to refactor some code, so it uses dependency injection. Take this (non-sense) example class: class Foo { protected $min; protected $max; public $bar; public function __construct($min, $max) { $this->min = $min; $this->max = $max; $this->bar = new Bar($this->calc()); } public functi...
In Java and C#, you can create an object with properties that can be set at initialisation by either defining a constructor with parameters, defining each property after constructing the object, or using the builder/fluid interface pattern. However, C# 3 introduced object and collection initialisers, which meant the bu...
What is the recommendation regarding re-using DTO's as a child in another DTO? I'm using ASP.NET Web API (C#) and consuming the results with Angular 1.x (not sure if that really matters). I have the following DTOs class SiteDto { public int SiteId {get;set;} public string Name {get; set;} public DateTime CreatedDate...
I have come across a programming question in which I have to determine : Does there exists at least one pair in a given unsorted array such that |i - j| <= K and |A[i] - A[j]| <= x ? For example: A = {5,4,8,3} and x = 3 and k = 2. Answer: Yes - any one of (5,4), (5,8), (4,3) I have tried it many times but couldn'...
I've been reading about C++ memory models and think I have a grasp of the basic concepts of happens-before, synchronizes-with and inter-thread happens-before. However, applying them in some examples has been difficult. In particular I have been thinking about the following sequence of operations when they are repeated:...
I'm running a Java application that creates 50 threads as part of a threadpool; each thread running in an object that reads 1000 unique rows at a time from a MySQL table. So each object has it's own SqlManager class I created which can open an Sql connection. wait_timeout is 28800, which would be 8 hours (am surprise...
The web App has four distinct user areas. The frontend for people off the street The user area for logged in users A teacher zone An Admin c-panel I am using CodeIgniter with the HMVC extension. Here is my current list of module folders. Each database table has a corresponding module. Each module has a MVC triad exc...
What is the convention about describing the direction of the stack, i.e., about what the words up, down, top, and bottom mean? I noticed that with stack data structure API, top usually to refer to the most recently added item. I never saw high level language or library documentation refer to the newly added item in the...
I have R objects, where R >= 3. I have a N-sized array, where N > R. I would like to determine in which indexes of the array I must put the R objects so the distance between any two neighbors will be equal, or the most similar possible. Eg: for N = 4, R = 3 {1, 2, 3, 4} {o, o, , o} or {1, 2, 3, 4} {o, , o, o} for N...
Our scrum team consists of the usual scrum roles. We do not have a UI/UX designer and the developers work the UI/UX with the product owner. Here lies a problem. Everytime we are about to create the backlog and we do not define the exact UI/UX design before the beginning of the sprint we end up spending too much time du...
I have a small circle (on a sphere) with given center and radius and I want to mark grid points which are within the small circle. The grid itself is discretised in evenly spaced longitude and latitude degrees in a geographical map. My simple algorithm that I implemented to solve this goes from the center of the small ...
I have an asm/C code which implements some image filters. The objective of this project is experimentation with different implementations, benchmarking, plotting and reporting data to write a paper with relevant insights. So for example one work-flow I need would be: Start at a base code implementation (Step 0) Compil...
For example, if I have a method public void method(Pair<String, Object> pair){ ... } Should I create the method public void method(String str, Object obj){ this.method(new Pair<>(str, obj); } if it is not to maintain an existing API? What are the considerations?
Good day, I am new to java and new to this forum but I request a bit of help. I am learning java on my own and I am currently learning binary trees. I have come an algorithm that is giving me a little issue. It is a binary tree code that basically inserts five nodes into a tree structure and then traverses the tree. My...
I have a Node.js application that reads and writes images from a server. The images are stored in a directory on an Ubuntu operating system. Express static routes serve images from that folder when accessed by mywebsite.com/images/xyz.jpg. Currently, anyone who can log into the server can see what's inside the image fo...
The difference between a command and an event in bus communication seems a little vague to me. I know that commands should be executed once only, while an event can be handled multiple times, but still I'm not sure when to use a command or an event. Let's look at an example: When a new user registers to a web applicat...
The codebase I work with has a certain pattern prevalent in all public methods, which goes like this: public void UpdateUser(User userArg) { Framework.NullCheck(userArg); var user = userDb.Get(userArg.Id); Framework.NullCheck(user); user = userArg; userDb.Update(user); } The NullCheck method is...
So as my the title says, SonarQube is complaining whenever you use list.size() == 0 or list.size > 0 However I started changing to isEmpty() and !is.Empty() and noticed the code becomes way less readable and had to change it back, therefore I don't think it's better to use the isEmpty() method as you have to read t...
What makes SDLC a "lifecycle" in the first place? Let's say that a software vendor signed up a contract with a customer who does not require their software to maintained or supported by the vendor. In that scenario, would the lifecycle repeat itself? In other words: is maintenance, feedback, or support an integral pha...
I'm writing the core logic of Pokemon Gen I in Java (8), and I am struggling to figure out the best way to implement the turn-based aspect of the game. Right now I have a Battle class which has two Players each with a PokemonTeam. The idea is that one Player takes a Turn (a Battle has many Turns), and some action happe...
Given a modern 64-bit architecture with 6-bytes used for each page pointer, 1 MB pages, and 16 GB installed memory: a) How would I calculate how much memory can be addressed by the paging solution? b) How would I calculate how large must each page table be? I'm not looking for the answer. I would just appreciate a clea...
I am working on a WCF Service that returns the Status for a Device. A Device has multiple Status for different Companies. I need to develop a WCF Service that allows a Company to retrieve the Status for their Company (and only theirs). What is the best way, to differentiate between this companies in WCF. As far as i c...
I have a desktop application with each window decopuled into presentation layer (containing the Form/Controls etc.) and application layer (Controller/Presenter - naming is irrelevant to the question). Presentation layer is passive, it only displays the data provided by application layer and comunicates with it using ev...
On a POST (or PUT) webservice, I know can use three different type of parameters, I can send my parameters in the path of the URL /objects/{path_param}, after a question mark in the URL /objects?{param_name}={Param_value} or in the body of the request. For GET webservices, I use path to identify a ressource, and query ...
Wikipedia gives a few examples of statements that we all know: Return statement: return value; Assignment statement: var value = expression; Call statement: expression;, e.g. action(); If statement short: if (expression) expression; If statement long: if (expression) { n statements } Is there a general term that incl...
I'm trying to design a hierarchy classes that extends the integers C types. What I'm trying to achieve is basically the following: I have a basic class called Integer this class is an abstract class, the only thing I wish it would provide is basically the basic operations between integers, namely +,-,*,/,&,^,|,~,etc if...
I have recently implemented quickselect, an algorithm for computing the k-th smallest element of an array, which, roughly speaking, works by repeatedly partitioning the array around a pivot and suitably shrinking the array. The implementation rearranges the input array, which it recevies by reference, to avoid wasting ...
I plan to release my very first app on Google Play Store but I am still a bit confused on the concept of releasing software. I tried to read a few articles online about the life cycle of software development but it left me with more questions. My Question is: Can I and should I release my app if it has a lot of unfinis...
I usually understand code by fiddling around, or by inserting printfs here and there, but this time around, that isn't possible, since the end product is an OS, so any suggestions on how to tackle this problem?
I'm about to implement my first State Machine and I'm left with one question, which is the acceptable coding form on who should change the state of the object/entity? Should the StateMachine change the state? Should the object itself change its own state? Should a sevice (e.g. IncidentTicketService) change the state of...
In C++ a variable is allocated in the 'Call Stack' ('Stack') or the 'Heap.' Frequently when referring to allocating a variable to the 'Stack', people use the phrase "Push to the Stack." My issue with this is that the variables allocated to the Stack can be randomly accessed in any order. Therefore, the variables are no...
I have a conceptual problem here. When i query my database, i often do so with joins. So a result set row might look like +------------+--------------+------------+-------+----------+----------+---------+ | CustomerId | CustomerName | MaterialId | Sales | Quantity | Salesman | Manager | +------------+--------------+---...
I recently I started learning Rust and Scala and what struck me was the lack of inheritance model that I'm used to in C++ and Java. Although I can model simple things with structs and traits in Rust, I want to see a more idiomatic way to model different kinds of problem domains using traits and composition. For exampl...
When is it advisable to write a class that can do multiple things? A bit of background: my boss prefers to write things that can be used over and over again. While I tend to agree with this sort of concept (OOP and all), there have been some instances where trying to do such a thing causes, what seems like, extraneous...
SOAP has a standard way of propagating errors, a SOAPFault field in the envelope. This standard also implies a number of things, such as its structure. RESTful, being an application style, implies much less on how errors should be propagated. There's no concept of an envelope and more and more I believe that the servic...
I'm trying to store more than 512 combinations of a game somewhere locally on my hard drive as a single file permanently unlike the temorary nature of arrays. If I store it in a text file like I normally do, I wouldint be able to access the n'th combination easily. Is there any database kind of thing where i can store ...
Getting useful feedback early in the development cycle gets you to a high-quality feature faster. And the most useful feedback can be in the form of users actually using something in the wild, instead of in a contrived setting. If you see users use a feature during their actual use of the product, their experience is "...
I have a couple of questions about the practicality of developing a WPF application that loads data into memory from a text file and then manipulates the resulting object(s) instead of transactions with a database such as SQLite. Multiple views would have bindings on the resulting object(s) in memory. Persisting the up...
I've done a number of LOB ASP.NET MVC projects (MVC5) and would like to re-structure how I handle some things for a new project. Specifically, I have a component that I want to re-use throughout multiple places in the application. Current Method Let's say I have an app that handles patient case management. Part of th...
What is complexity related to number of operations/interactions between objects within a system? as that number increases the programmer capability of understanding and maintaining the system degrade.
Is there a distinction between a function definition (not a declaration) and a function? For me a function definition, is what gets defined by the programmer in the source code while the function it self is what we get after compilation. Is that a valid distinction?
Now I'm working in a mobile apps company, and Objective-c ,c++ (for iOS) and Java (for android) are my most frequently used language. Is it a good habit to just use common language features among them? (for example: never use multiple inheritance which can be used in c++ only) I know there is already a famous thread si...
I have a small issue with namespace and class naming. Here is a practical example: ResourceLayer.cs - Public component that holds the manager and the map provider, implements an interface ResourceMapProvider.cs - Provides a bitmap representation of the resources ResourceManager.cs - Is a repository of resour...
I'm trying to pass a parameter to create a thumbnail in AWS Elastic transcoder, which shouldn't be that difficult except I know nothing about regular expressions. My log is giving me the following error: Member must satisfy regular expression pattern: (^$)|(^.*\\{count\\}.*$)\n I just need to specify something calle...
We have three layers in our application. Service layer to provide an external API. BO layer for our business logic, and a DAO layer for our database connection. Let's say every time we update a File, we also want to change something in the Folder, for example 'last modified date'. This needs to be done in a transacti...
I'm doing a little bit of cleanup and I'm trying to gather all the spread SQL queries done to an object into a single place. I have a class whose responsibility is to present a CRUD interface to the developer, and to encapsulate the results coming from selection queries into objects, that at the same time can be update...
On websites like Facebook and Twitter, you've got a function to log off on all devices. How does it work? Does it work with IP addresses or something? What happens when you login on a device and use that function? P.S.: Facebook and Twitter are just examples in this question. It was just easier to explain what I mean.
In situations when we need to write something like this: if ($doStuff) { $obj->doStuff(); } is it acceptable to write something like this? $doStuff && $obj->doStuff(); If not, why?
In his book Patterns in C, Adam Petersen describes using a pointer to a struct, which is declared in a header file, to create a first-class abstract data-type: /* Customer.h */ /* A pointer to an incomplete type (hides the implementation details). */ typedef struct Customer* CustomerPtr; /* Create a Customer and return...
I've moved this from Stack Overflow and this was the suggested place to ask. This has been marked as a possible duplicate of a question about the merits of composition over inheritance. I'm not asking that question, I'm looking for strategies to manage development given the code we have. The context of the question is...
I've seen an API list methods with both of the following signatures: methodA(...) : ReturnType methodB(...) : typeof ReturnType I understand the first but not the second. My question comes from reading through the API for Angular2 where I encounter both of the above. For example, class TestBed lists two method...
Logging is something that is necessary but is (relatively) rarely used. As such it can be made much more compact in terms of storage. For example the data most commonly logged like ip, date, time and other data that can be represented as an integer is being stored as text. If logging was stored as binary data, a lot of...