instruction
stringlengths
34
36.1k
I'm building a RESTful API that supports queuing long-running tasks for eventual handling. The typical workflow for this API would be: User fills in form Client posts data to API API returns 202 Accepted Client redirects user to a unique URL for that request (/results/{request_id}) ~eventually~ Client visits URL again...
I was taught this expression and pattern way back in the day. Sure, the name comes from old pumps that needed to be filled with water before they could pump water, but who cares? We're talking about code here. Some really good examples and an explanation of what the pattern accomplishes would be welcome. How is this ...
I'm digging on how to structure projects and so I stumble into Onion Architecture. As to how I understand it, its more on a domain-centered-focus architecture instead of a database-driven type. I'm looking for some github projects to study and learn more about the architecture, so I found this one https://github.com/ch...
Why is it that in nearly all modern programming languages (Go, Rust, Kotlin, Swift, Scala, Nim, even Python last version) types always come after the variable name in the variable declaration, and not before? Why x: int = 42 and not int x = 42? Is the latter not more readable than the former? Is it just a trend or are...
I am wondering if it is both possible and how one would write an opensource version of the Windows API. What I mean by this is, say you #include <Windows.h> in your C++ application. Then you make a call to ::CreateProcess(...). Now if you know what that function is supposed to do, what the function signature is and you...
I want to log responses using Spring's RestTemplate. At first I thought I should do it using a ClientHttpRequestInterceptor, but since every set of requests should be logged to a different file, I figured out I should create a new RestTemplate with a new ClientHttpRequestInterceptor for every set of requests (though al...
My program models a sport tournament which has one or many events or categories. The class Event has members like players or courts as a List, as well as some dictionaries using the class Map. So far accessing publicly those members can be done through their respective getters, but I realized this is a bad practice bec...
I'd like my (currently) closed-source iOS app to use some GPLv2 licensed code. The code I want to use is simply a converter from one file format to another — nothing too complex or proprietary. Given the restrictions imposed by the GPL, I understand that I cannot integrate the GPL-licensed code directly into my app. Ho...
I see where most readings online derive that the Big-Oh notation of a Binary Search is O(log(n)), but doesn't this assume a balanced tree? What if the tree is completely unbalanced (i.e. similar to a linked list). In this case the height of the tree is not log(n) it is n. So considering that Big-Oh takes into account...
I am using MS Sql Server and my system contains power usage data in one table as timestamp and values for KW(two columns). This data is collected at 1 hour interval. At the end of the month I need to calculate on peak and off peak usage. The definition of on peak and off peak will depend on the contract with the utilit...
So, we have started trying to work to Agile/scrum in our business to run the software dev team and it's not (in my eyes as a humble dev) working very well. Its getting to the point now where the team (devs/scrum master) are getting very pissed off due to it turning into more of a time and motion exercise than a 'get qu...
I am reading company's coding guidelines, and I encountered the MISRA 8-0-1 rule, which states: An init-declarator-list or a member-declarator-list shall consist of a single init-declarator or member-declarator respectively. No example. So, what is this rule about? Can anyone provide some example of this (bad and g...
My client wishes to launch a specific version of the Rails platform I am developing that will be restricted to a particular group of users (some sort of test-of-concept). I will have another server instance at a different url (regional.mydomain.com), in parallel to the main instance of the server (www.mydomain.com) Now...
For example, suppose you have a console game program, which has all kinds of input/output methods to and from the console. Would it be smart to keep them all in a single inputOutput class or break them down to more specific classes like startMenuIO, inGameIO, playerIO, gameBoardIO, etc. such that each class has about 1...
Background I have never had a formal class in OOP/OOD although I understand how the protected members work. Being accessible by any instance/derived class, they are thereby less private (more accessible) than private. Now, what I am confused on... is how to access the protected members within the class for C#. I have s...
I am still trying to get some experience with DI. Let me illustrate my situation and you can give me advice on whether I am using DI and Abstract Factory correctly. I need to create IModels at runtime. So I am going to use DI to inject an IModelFactory into my objects. But the concrete implementation of my IModels depe...
Members must frequently be destroyed in the correct order. As member creation is in forward order and destruction is in reverse order this will usually work fine. However, when assignment operators and non-copyable objects are involved, things can start to break down, due to the forward order of move-assignment in the ...
I'm a python programmer trying to get to grips with Java's inflexibility; I'm trying to parse a date from a string into a Calendar object private Calendar parsedDate ( String dateString ) throws Exception { Calendar calendar = Calendar.getInstance(); DateFormat format; Date date; try { format = new SimpleDa...
Is there a general term for the code that sets the parameters of statements require some kind of initialization or bounds? Examples: C: for (x=0; x<y; ++i) switch (controlling_variable) SystemVerilog: foreach (array[i]) case (someVar) Python: while foo(): for x in y: All of these examples have some statement follow...
I have data that indicates which topics each student has got right/wrong in an assessment.: | Student | Topic 1 | Topic 2 | Topic 3 | Topic 4 | Topic 5 | ... (perhaps 30 topics) | 1 | T | T | T | T | F | | 2 | F | T | F | T | T | | 3 | T ...
I'm not entirely sure how to phrase my question, so I'm going to give an example. Say you work on payment processing software. You implemented Service Oriented architecture and you have 3 main phases of an event Intake, where you get a new payment Verification, where you verify. Payment, where you settle up the accoun...
have a query in my mind that how the time estimation is made in sprint meeting for agile work flow? Lets say for example: In a team there are 4 developers and the first sprint is designed for about 10 issues/tickets (in terms of JIRA). Each developer give rough estimate to every ticket and the whole sprint time is calc...
If I write the expression, if not (expr1 or expr2) then value I get the following warning from FSharpLint, In F# code, use 'e1 || e2' instead of 'e1 or e2'. Why is using || preferred over using or? I want to write idiomatic code, but this appears to me to degrade readability. I really like the readability of the not f...
I have plenty of setters in my classes, as well as many methods to add an item or a set of items to lists or maps. Should I check for nulls for each one of them, or should I allow NullPointerException to happen? This is dangerous for maps though, since I could end up with null values and I wouldn't want that. So basica...
I want to make a program, which will put some sentence in shared memory so another program will receive this massage. I made that, but I do not understand the 4th and 5th parameters of CreateFileMapping(). In my program I write 256 (5th parameter), but when I changed this to 1, the program still worked. I thought it s...
Let's say we have a list of players in our Event class. And we have a dictionary with the score of each player. We can add a score to a player using the addScore method: public class Event { private List<Player> players; private Map<Player, Integer> score; public void addScore(Player p, int playerScore) { ...
In C, a non const object implicitly converts, without warning, to its const counterpart, so you can write a function, and call it as: void foo( const char *p ); char bar[] = "bar"; foo( bar ); However, if the function is to be called via a pointer, it seems you can not be const correct without getting a warning: void ...
I am always a huge fan of standards and think I finally decided on one of the many C++ naming standards. However, it almost seems moot because working with a couple of libraries where the standard use is to inherit the classes, the naming is now off when overriding. Now, I am not forced to actually inherit these class...
We currently have a sensitive discussion going in the company that touches on a couple of old primary opinion based discussions. Nevertheless, I would like to discuss the case in this forum to establish some sensible code guidelines. Let's assume we have the following two classes of non-modifiable legacy classes: publ...
So i found out this following code used to check the strong level of password. I was kind of confused about the part: score = len([x for x in password_strength.values() if x]) I know that it was used to count value appeared in 'password' but the syntax is strange to me. And i'm wondering if this is the simplest way. #!...
I have datetime type column in sql tablename id createdand i get date from input date type html tag I want to compare in sql query where close condition. How to compare both field. var startDate = $('#startDate').val(); '.... where created >='+ startDate;
I have PDF generation feature in my app. I am using iTextPDF for generating reports, so it works well. The problem is not exactly in pdf generation but in approach. Currently PDF generation code looks horrible, hard-coded and not flexible, so there is a lot of duplication and everything is highly coupled. Are there any...
I've got a real-world problem that I'm trying to represent and automate. I've simplified and abstracted it down to the following: There are n places of work (P1, P2, ..., Pn). Each place, Pn has a key, Kn. There are m Workers, (W1, W2, ..., Wm). In order to work at Pn, a worker must hold Kn. Each key can either be hel...
I work with large HashMap's and ArrayLists. When not needing them to be in memory any longer, I use myArray.clear(); to free up the memory. When my colleague saw that line, he changed it to myArray = new ArrayList<>();. He agreed when I asked if he was doing it to let the garbage collector take care of it. Althoug...
I'm working on a personal project that I'm planning on licensing under GNU Affero GPL. However, I found some code that's licensed under MIT that really want to utilize, but I'm not sure what I should do about licensing. The rest of the code will be mine under GNU Affero, it's just a source file and a header file that I...
I'm doing a php MVC project using code igniter. I have two models, a and b. Each class contains four functions (insert, delete, update and view) and their implementations are almost the same with each other. A friend suggested to put generic versions of the four functions inside a utility class and the two models can a...
I have a website that pulls from a database to display images/names/misc info. The pages are used on both iOS Devices (iPhones, iPads, iPods so far) and on PCs using internet explorer and Safari/Chrome on the iOS devices. The websites use jQuery/jQueryMobile...A lot of ListView content. I have noticed a huge difference...
ES2015 introduced the let and const keywords, which essentially have the same semantics apart from reassignment. (const can be seen as a final variable in languages like Java.) I see the point of switching from var to let, but many online articles recommend using const whenever possible (in some form of manual SSA). Ho...
Let's say we have a class with many methods that do something different but can be grouped together as one "kind of functionality". For example, adding a configuration o setting rules up. Let's go with the rules example. Say we have a class that models a board game, and we have add different rules so when the game is p...
Let's say I have a set of Tasks that they have dependencies. These tasks are not in order, but the execution of tasks should be in the proper order. Each task has two properties: Before and After. Before contains list of tasks that are dependending to the result of this task -- so it should be run before them; After co...
I often find myself struggling to decide which of these two ways to use when I require to use common data across some methods in my classes. What would be a better choice? In this option, I can create an instance variable to avoid the need of having to declare additional variables, and also to avoid defining method par...
I'm new to Haskell, so this is more a high-level conceptual question. I've read this: https://wiki.haskell.org/Real_World_Applications/Event_Driven_Applications and it has this: run :: Domain -> [Event] -> IO () run dm [] = do events <- uiUpdate dm run dm events run _ (EventExit:_) = return () run dm (e:es) = ...
To sync on the terms I will first give my perspective on what a callback function in the simplest possible terms: A callback function is a function that is executed as a response to a certain event that can happen at arbitrary time. The event that can happen at arbitrary time. implies that some external source is pr...
In my experience, technical design is made more challenging when it is divorced from implementation, particularly by assigning the roles to different people, because its easy for the designer to overlook a myriad of implementation details/gotchas. In theory, I like the idea though. So my question is, should we be stri...
Background I am fairly new to unit testing, and have been recently using the Visual Studio Test Manager to create my Unit Tests. The way that I have currently been doing things is as follows: Create some libraries. Add the libraries to one big solution, along with the application. Create a folder called Tests that I p...
^ e.g. is it allowed to link directly from a use case to an activity diagram - or- from a class diagram to a use case by connecting them with an association note -or - form a component diagram to a object diagram? also, if it's allowed, and I firmly believe it is since I saw such diagrams, where does it say so in the ...
I have a set of 2-D data (x,y) and it produces a set of curves, and sometimes the set of curves do not overlap, and there is a distinct separation between the groups of curves, how would I identify and get this separation? Here is some sample data and its plot 0.0000 -0.4270 0.1000 -0.4239 0.2000 -0.4141 0.3...
I'm creating an API and data model for a multi-user document-creation application and I'm having trouble with a particular part of the data model/API design. Below is my current line of thinking: There are two similar actions that can happen while a user is writing a document: A user can manually save a document. This...
Is there a difference between public class B implements C public class A extends B implements C and public class B implements C public class A extends B Is it just redundant implementation? Or there are advantage to do that? Edit Asking this question, because I saw it in java.util package e.g. public class HashM...
I'm looking for an algorithm to help me out with a combination of combinations problem. I have generated two lists of combinations of letters: (26 choose 6) & (26 choose 5) My goal is to be able to generate all sets of the alphabet in four groupings of 5 and one grouping of 6. For example: { [abcdef], [ghijk], [lmnop]...
My application has users and ads. A user has a unique email. An ad belongs to a user (so, the ads table has a user_id FK, that is simple). Every ad can also have multiple emails and phone numbers associated with it as a way to contact it's owner. Finally, the user should remember all his ever used_emails and used_phone...
Errors can come from many different sources - third-party services, libraries, environment, etc. When an error prevents a user from performing their desired action, these diverse errors should be communicated to the user, so they their action failed and can take steps to solve the issue. Are there any common strategies...
In C#, I sometimes use: const string FirstName = "FirstName"; const string SSN = "SSN"; ... var ssn = GetValue(key: SSN); // e.g. GetValue fetches value from some key/value store to avoid hard-coding key strings throughout my code. I'm thinking of taking advantage of C# 6.0 nameof to avoid the repetition in the co...
Let's say I have a builder class (which by the way is not techinically a builder, but it's not a factory either) to generate different rules for a game: public class RuleBuilder { private Game game; public RuleBuilder(Game g) { game = g; } public Rule scoreRule() { return new ScoreRule...
I am new in the object oriented world. I am interested on learn the foundations of object oriented programming independently of any language. But for the moment I am doing the implementation on VB.NET. The question is: Can an object contain a property that is another object? or only the properties can be of primitive t...
I have detailed specification of what should my program take as input, and give as output. How to convert this specification into classes/methods/properties? I used such algorithm: Take specification, plus data flow model based on it Extract nouns from them (most frequently used or important from your point of view) U...
I have a program written in Python that I would like to make available to the public under a three-clause BSD license. My program has an import blah statement, where blah is a Python module that is licensed under LGPL version 3. Now, I don't even plan to include blah in my distribution... I plan to make users download ...
I have a class Party that has a constructor that takes a Collection<Foo>. I plan to have two subclasses NpcParty and PlayerParty. All Party instances have an upper limit on the size of the input collection (6). However, an NpcParty has a lower bound of 1, while a PlayerParty has a lower bound of 0 (or rather, there is ...
Dependency injection is often recommended in MVC projects because it's easy to implement with the pattern and adds a host of potential benefits. Indeed, it actually comes bundled with the default MVC project in Visual Studio. If you read around MVC, however, you will also see a lot of people recommending the use of sk...
I'm trying to understand how to implement service discovery pattern in my architechture. I understand that each instance of one service must register itself in the service registry when starts and then refresh the registration each, for instance, 30 seconds. Say I have a purchases service that needs to read some data ...
I have a problem dealing with word ladders. The problem is: given two words and a dictionary file, find the shortest word ladder between the two words. So if given the words cat and pot: cat -> cot -> pot That is just an easy example. You get the idea. The problem is the time constraint, The problem calls for using a...
On one hand class complex { double real; double imaginary; } it is composition on the other hand class complex : double { double imaginary; } it is inheritance Which one is correct? Why arrows go opposite direction, denoting the same thing? Who invented all this?
I have a class, something like this one (C#): public class MyFavoriteClass { public string Name { get; set; } public string Description { get; set; } (...) public ReferencedClass1 ReferencedClass1 {get; protected set;} public ReferencedClass2 ReferencedClass2 {get; protected set;} public Refere...
I'm designing the data model for a project where users can create documents, save revisions of that document that can be reverted to, and publish documents. The basic data model I have right now is something like this: Documents --------- id: integer PK currentRevisionId: integer FK references DocumentRevisions(id) pub...
We're looking for a good source control and project management solution at my workplace and I've suggested creating a GitHub organization and private repositories. I love GitHub for many reasons, but this isn't about GitHub (in fact my colleagues are going to present points in favor of competing platforms) - it's about...
I have written a class which represents a SQLite Trigger. public SQLiteTrigger(string Name, string On, TriggerStartType StartType, TriggerEventType EventType) : this(...) public SQLiteTrigger(string Name, st...
In order to estimate the fastest function in various cases in a non fully deterministic context, I'm running an experiment calling one or the other at random and recording the duration of the operation on the production server. I get this kind of table: (numbers grow larger the more I wait) A problem in interpreting t...
I sort of understand unobtrusive javascript. Even in my CSS now I hardly ever use classes or id's because I like clean, easy to read, uncluttered html files. For example, why use this: <body id="anchor" ontouchstart=""> <nav id="nav"> <div id="design" class="option"> <p class="vCenter">design</p> </div>...
What are the valid use case for internationalizing logs? Especially, are there any uses that make sense for a web application. I'm working on converting the logging API used by a web application from log4j to slf4j, and noticed that the interface used to abstract over the log4j implementation supports internationalizat...
Consider the following situation: You have a program which creates numerous 'jobs' that need to be processed and places them into a queue. You have other worker programs which grab the next 'job' in line so they can process that job. Each job has a category. There could be any number of categories. Two jobs that have ...
I maintain an open source application that is licensed under the MIT license, with myself as the sole copyright holder. A friend has ported my application to another language, and has also licensed it under MIT, with himself as the sole copyright holder. Is this considered a derivative work, if none of my code is prese...
In C++ I frequently see these two signatures used seemingly interchangeably: void fill_array(Array<Type>* array_to_fill); Array<Type>* filled_array(); I imagine there is a subtle difference, but I don't know what it is. Could someone explain when I might prefer one form over the other?
So I am writing a Finger paint app. I have multiple color which user can select. I save the path and paint information inside an array. ArrayList<PaintPath> arrayPaintPath = new ArrayList<PaintPath>(); Paint path is class PaintPath{ Paint aPaint; Path aPath; PaintPath(Paint paint, Path path){ a...
I am developing a server-client application where the client will run on Windows and the server probably on Linux. Maybe I'll later port the client over to Mac and Linux, but not yet. All home-computers these days run on little-endian. I googled a while, but I couldn't really find a list of devices which run on big-end...
I'm writing a quite simple application that deals with hotel rooms reservation. I've got a problem at one stage. I'm processing a queue of orders. For every order one of the receptionists should choose a room (one or none at all) for the client according to his strategy. That's why I decided to go with Java Optional. T...
Let's say I have a source file of 800 lines, and I want to "copy/paste" one function from a github project that has a MIT license, and I also have my own (which may be a MIT license, or a stronger one). 1.- Am I allowed to do the following: /* My copyright notice (MIt or smt) */ Line 1 ..code Line.300 ..code Line.500 ...
NOTE: This question is about finding a proper name for an exception where the condition for throwing the exception has not actually happened (eg. preventing a StackOverflow by throwing a StackOverflowException before an overflow can occur) I have a FooList class that has bounds on the number of elements it can contain....
Are there other ways of indexing?, Which are the more used? Does sql have an standard for indexes, it uses hash tables?
This is a follow-up of this question. I decided to implement what the accepted answer suggests, however, I realized I also needed individual public methods for each member the entity to be validated has, so it is not only validated as a whole, but also its members as separate units: This is what was suggested: public i...
A client has recently expressed a wish to assign their market segmentation labels to their customers, so that they can sort by market segmentation in their dashboards ("show me all the VIP customers that fulfill a certain criteria", etc). Good idea. I'd like to offer this to all my clients. The only trouble is that "th...
I am in a need to prove the performance of a single page application. I would compare it with an application that uses server side to fill the HTML content. How would one do that? Obviously the Ajax JSON requests are faster than making a full request with all the html and other stuff everytime. But maybe just comparing...
Suppose you want to combine some arrays of objects that have similar properties: var people = [{name: 'Jack', age: 10}, {name: 'Jill', age: 12}] var items = [{owner: 'Jack', name: 'pail'}, {owner: 'Jill', name: 'water'}] var output = process(people, items) // [{name: 'Jack', age: 10, items: ['pail']}, // {name: 'Ja...
I have below in my stored proc if then SELECT TABLE1.COLUMN1,TABLE1.COLUMN2,TABLE1.COLUMN3,TABLE1.COLUMN4 FROM TABLE1,TABLE2 where criteria1 (covers functionality 1) UNION SELECT TABLE1.COLUMN1,TABLE1.COLUMN2,TABLE1.COLUMN3,TABLE1.COLUMN4 FROM TABLE1,TABLE3 where criteria2 (covers functionality 2) UNI...
I am currently learning JavaFX and I came across a very strange API for laying out GUI components. It is perhaps best explained by it's javadoc: To use the GridPane, an application needs to set the layout constraints on the children and add those children to the gridpane instance. Constraints are set on the childr...
I'm building a multiplayer trivia game where the server is written in NodeJS and hosted on Heroku. I ran into a problem when the server should notify the users that time's up for answering a question because Heroku reboots servers every once in awhile and can reboot my server in the middle of a game. Is there an elegan...
Let's say I'd like to perform the following command: house.getFloor(0).getWall(WEST).getDoor().getDoorknob(); To avoid a NullPointerException, I'd have to do the following if: if (house != null && house.getFloor(0) && house.getFloor(0).getWall(WEST) != null && house.getFloor(0).getWall(WEST).getDoor() != null) ... ...
Considering that using a relational DB or other hierarchical or such databases is not an option, looking for the alternative approach using a simple (but very fast, efficient, distributed KV-store). The value (referred by key) is an encrypted BLOB, whose contents are 2 related entities / objects, with a 1:N 'refers-to'...
I'm new to this whole thing, so please tell me if I'm doing this wrong of if there's a better spot for my question. I'm making a game with basic systems for projectiles, npcs and items. This game will have multiple variants of each of these types. For the purposes of this example, there will be a Bullet projectile, a R...
Some background information I'm part of an in-house software dev team. It consists of 5 developers (with experiences ranging from 2 to 5 years, I'm one of them) 3 implementation staff (they do the software deployment and training) and 1 project manager. We develop plenty of small to medium-sized projects, and their t...
I've seen some programmers doing the following : File file = new File("folder\\subfolder\\subsubfolder"); And I find it totally wrong because of compatibility issues with a different OS than Windows. So is there one single reason why using double backslashes is preferable than forward slashs or File.separator ?
I have a few layers in my WebApplication: Presentation, Service, DAO, Domain. Services call DAO objects which reads data from a Database/File whatever. I have a Controller that needs to fetch data from different Services and set them as part of the Response. Should I put the logic to call different Services in the Cont...
I am looking at a large scale low latency way to calculate the geometric distance between vectors. Let's say I have a vector A. It has size 128 and of type 32 bit float. I want to get it's geometric distance from about 10milion other vectors of the same type. So basically how far is A from all the other vectors. The re...
I've developed a Restful API in PHP, now the API makes different resources available like: Article, User, Service, Trace etc.... I'm going to implement each resource in a portable DLL, so I can use the API method in each platform as Xamarin, XBox, Windows etc... I want to ask how I should setup the structure of each DL...
There is a microservices system that is currently using Zookeeper. Let's assume there is just one type of service A that exhibits a simple read of some value t. However, the one of existing A instances has scheduled task that updates t from time to time and its notify other through message bus that value has been chang...
I have someone homework to make and in the instructions it says that we need to implement a function in O(1). Now, does it mean that I can make my function in O(5) or O(2) or whatever?
Using C# and Visual Studio, I've developed a class that zips and archives a folder into desired location, creating directories and manipulating files on a machine. The intended use is as an part of an embedded piece of software that will collect logging information for another piece of software after its completion. T...
Say we have a user interface with Forms, Buttons and such. Each item has some properties (such as Visible, Enabled, etc.). Who should check on these properties and decide whenever to render the item or not? Parent item: for I := 0 to Count - 1 do if Child[I].Visible then Child[I].Paint Or each item itself: if not Self...
I code a new shell in C, that could be done in several ways: Flex/bison, finite state machine, abstract syntax tree or just a tokenizer in C. Now I've written a for-loop that changes the condition of the increment and I wonder if that is the same as a FSM? First I did it as a finite state machine but that code was ver...
Summary: component used to work and now doesn't, the regression happened 1+ years ago and we're not sure when, now I'm considering replacing the broken and poorly architected component with a mature library Background: I am working on a web application which interacts with a 3rd party API to import and export data. Thi...
I have a class with around 1300 lines and it has many CRUD-like methods that need parameters to be checked, for some of them it's more than just a few rules. For clarity purposes, I am going to use generic names for my class and methods. I finished implementing all the preconditions check recently, and although I have ...