instruction
stringlengths
34
36.1k
A social network has API, but also it has some limitations like the amount of requests that can be done in one second (let's say API will give an error, if it accepts more than 3 requests per second) I want to write a web application that allows me to send messages via API. However, I want to automatically do requests ...
It's mostly all in the title. How do you report the runtime of a C++ program that has intensive calculations at compile-time? If I have a program that, when I use the bash time command on it, appears to run in .5 seconds, but the COMPILE TIME CALCULATIONS take over 10 minutes, can I honestly say my program runs in .5 s...
I stumbled on following problem, and I'm curious if it could be done better. A while ago I wrote a factory class that looked something like this: public class Foo { private IDbContext _dbContext; public Foo(IDbContext dbContext) { _dbContext = dbContext; } ...
The way I see used most frequently int main() { int i; for (i=0; i<10; i++) { printf("hello\n"); } return 0; } The way I’m used to int main() { for (int i=0; i<10; i++) { printf("hello\n"); } return 0; } Questions Is the first way not cumbersome?...
We have a few apps that communicate with each other. I work on the core backend project X. X needs to make requests to a cloud native project Y in order to process some information. Now, locally I don't run Y because it can't run locally since it depends on a lot of cloud provider specific stuff and I also don't have a...
I have a REST API and a SPA application, with Auth0 server issuing access tokens and enabling end users to login with their social identity provider. The API expects to receive a JWT access token with the user's external identity in the sub claim with each request. After the user registers for the first time (and provi...
Assume the following class structure: class Base; class A : public Base; class B : public Base; class WrapperBase; class AWrapper : public WrapperBase; class BWrapper : public WrapperBase; I would like to create some function like below std::unique_ptr<WrapperBase> create(const Base* v); That creates the appropr...
I often have to write a function which may return an output of two kinds: "short" and "long". As an example, consider the subset sum problem: the input is a set of integers S and an integer C, and the output is the largest sum of a subset of S that is at most C. The short output is just the largest sum (an integer); th...
Let's say there is a user table and has field called coins to represent the coins available for that user in the system. At this stage a certain user has 50 coins in his account. Same user do the following requests almost instantly, but in the following order. Buy something for 20 coins Insert a promo code that double...
I have the following classes: public class MyCaller{ @Inject private MyService service; private void callerMethod(int arg1, String arg2){ service.serviceMethod(arg1, arg2); } } @Transactional public class MyService{ @MyAutorizationInterceptor(ADMINS_ONLY) public void serviceMethod(@My...
We know that RGB is additive color model and CMYK is subtractive color model. RGB starts with darkness (black) and we gradually add light; an CMY(K) image requires to be illuminated by white light. When a printer performs printing operation, how do CMYK and RGB work together to print on white paper? And why does CMYK ...
I'm making an UML class diagram representing classes used for authentication. There are 3 classes: X509AuthenticationFilter ProviderManager X509AuthenticationProvider The X509AuthenticationFilter HAS a ProviderManager. The ProviderManager HAS a List<AuthenticationProvider> And in this list that the manager has there'...
Context for this question I'm currently working with small data storage media (e.g. RFID tags) that contain some fixed number of bytes that can be manipulated. The drivers that allow reading bytes from or writing bytes to the storage medium already exist, so now I'm trying to create a wrapper around the driver that wil...
I'm currently working on a project which uses azure function apps, we also create a data access layers for each function app which are built as nuget packages and are then published to a private nuget feed. For the function apps, we have three separate environments, QA, Staging, and Production. I want to create separa...
I have multiple VMs set up that have the same repo and with slight differences. I use these VMs to prototype or run different experiments. Sometimes I sync or merge between them and from different branches. I want to avoid polluting the repository's commit history as a way to rsync between them. Rsync is too dangerous ...
First an foremost I would like to apologise if this is a trivial question, however it has been costing me a few workdays worth of freetime and I am appearantly too incompetent to figure this out myself. I am currently tasked with developing an Android BLE-Client that scans and processes specifically Eddystone-based Blu...
I've been curious about why Python seems to be so popular amongst data scientists. Firstly I needed to check there was some truth to this assertion so I wrote a query on the StackExchange data explorer: https://data.stackexchange.com/stackoverflow/query/1555958/other-tags-on-python-posts This shows common data processi...
Why are use-cases counted separately from the other views in the 4+1 architecture? How are use-cases different from others views?
Although the splitting of web application/ web sites to front-end (client) and back-end (server) is popular, this binary division is frequently pretty far from actual complexity of architecture: The database could be in separate server Except client, "server" (already ambiguous term) and dababase, there are could be s...
In my MVP app, my model (a service) returns a collection of ISession pointers. Each pointer points to an object of a derived type HttpSession or HttpsSession. The model (the service) knows nothing about any GUI, Views, Presenters, etc. In my Presenter, I need to create and show a View, which should be different dependi...
When designing a REST API for update request. Usually PUT is used. Question: should the resource URL include the id usually? For instance, there is a book resource: http://localhost:8080/library/book When updating a given book with Id, say 123, we could send a PUT request with JSON as the HTTP request body as the updat...
I've just started learning about Inheritance vs Composition and it's kind of tricky for me to get my head around it for some reason. I have these classes: Person class Person { public string Name { get; set; } public int Age { get; set; } public Person(string name) { Name = name; } pub...
I have a question about DDD. I wonder if I should add validation in a web api controller and duplicate it in a command handler? Is it good approach to validate a DTO and a command even if the validation is the same? For example, here I used data annotation validation attributes for a controller: public class EmailsCont...
I have a utility function called connectToMongoDB() which connects to MongoDB. Basically, it creates a client for MongoDB and returns that. I'm making a library and I'm thinking of unit testing the utility functions. The way my unit test would work is by calling the function, then doing CRUD operations on it and seeing...
I'm working with a legacy codebase that has a lot of functions with a nullcheck on the same object. Example: std::vector<SessionNode*> * SessionManager::SessionMap; Session * getSession(int SessionId) { //Try to find the Session //And get the lock int index1 = getIndex1FromSessionId(); int index2 = getIndex2Fr...
On a platform with ECC memory, you can assure the compiled binary is 100% legit with EDAC daemon. (single-bit error will be corrected automatically, and multi-bit error will be logged so you can just re-run the compilation). But on a platform without ECC memory, you cannot guarantee that the output binary is legit. It ...
I have a very big form - let's call it <MyForm> - consisting of the following: text fields and dropdowns custom selector made of selectable cards table input (for this example 50 rows with each row having inputable text field) cancel button and submit button which will submit all the data inputted above to the API Fo...
I am exploring two ways of passing certain flags representing user behaviour to the backend. When should I pass flags via headers and update routing based on header, and when is it more appropriate to pass them in the body of the request and let backend handle it? For instance, I want certain additional information bas...
We have an application producing 5k-10k datapoints per second. Each datapoint has more than one metric, alongside its time of creation. We are looking for an efficient, scalable way to store this huge volume, such that aggregations can be queried by business logic shortly after storage, and such that they can be aggreg...
I have to draw a component diagram that depicts the architecture of my system with its subsystem decomposition and its dependencies. My system has a 3 tier architecture: The top layer just acts as a system boundary: it gets the HTTP parameter, calls a method and returns a simple response. For this reason, my presentat...
I'm getting ready to release a feature to production tomorrow & feel I have misdesigned said feature. I'll try to explain my scenario clearly. I'm looking for alternative design suggestions to this. My real concern is my title - the "final" class takes two parameters of the same interface type, but they MUST be in the ...
My aggregate root is "Post" and sub aggregate is "Comment". In my database I have a table called "ForbiddenWords" with one column "Name" (it contains words for example: "sex", "porn"). If someone wants to add a comment, he can't use forbidden words. I need to create a class "ForbiddenWords" to validate a comment. Is th...
I have an event that is raised when my job objects change state (e.g. initializing, running, complete, etc). The event is to be invoked from my set method in the State property, but before I make it that far, I'm trying to determine what makes more sense from a consumer standpoint. The event declaration is: public even...
I'm drawing some sequence diagrams to give a graphical depiction of the use cases written during the requirements elicitation phase for my project. This is a simple one: Vote Post Use Case Precondition: the user must be logged and the post the user wants to vote exists Postcondition: the post is voted by the user S...
Assume a low-level API is provided without source code (e.g. DirectX). The API provides a virtualization of hardware resources (GPU, CPU, audio card, etc.), which enables the user to call hardware-specific drivers through the OS. As a software developer, we do not care about the implementation details at the hardware l...
We currently have a monolith public api which serves most of our api endpoints. This has introduced a bottleneck as the owning team needs to make changes to publicise anything new and other teams don't have control over their own endpoints. To remove this we're looking to introduce an azure app gateway which will break...
I'm developing an application that has no client-server connection by design, all of the work is done locally (no internet connection needed), so I'm wondering if I can call it a client? (I'm asking for documentation purposes)
The behavior of my systems is as follows user places an order for a product 1a. order management creates a placeholder record for the order 1b. forwards the order to an external vendor. external vendor fills the order and also says ships it for delivery 2a. then returns my system back a list of filled orders only end ...
I have the following scenario: My .NET Core API has two Endpoints CreateProduct and UpdateProduct. The only difference between the two will be that UpdateProduct will need to know the ID of the Product to update Is it bad style to create a common CreateOrUpdateModel with a nullable property for the ID that will be se...
I have a system that publishes events to a message broker, lets call that system A. I also have system B and system C that subscribes to the "events"/messages. My payload/message looks like the following: { "eventType":"EntityCreated", "entityId": 123, "properties": { "somedata1": "somevalue1", ...
I've come onto a new a project and the permissions are done with an allow and a deny option for every permission. Until now i've only ever seen/build allow only permissions. What is the advantage of this? It seems to introduce extra complexity for developer as well as enduser. The only situation i could think of that a...
In my design i have a lot of objects which have a single Run() method, which when called performs what the object should do. Is that a valid interface design? It seems as though most objects I normally use have more than 1 method.
My application has big integration with the database. Classes that use the database are very crucial for the system, so I write small unit tests for classes that I call Repository. The reason behind the unit-testing database operations are for example verification of caching or correct order of query execution (to avoi...
I am currently building an application that uses the Spotify API to work with a user's playlists. My frontend is a Flutter app, which is connected to the backend, that is built with Node.js. Currently my backend handles the logic of implementing the [Authorization Code flow1 by using the spotify-web-api-node package. I...
I'm a mechanical engineering student currently building a rubik's cube solver. I'd like to code a VSCode program (meant to interface with an arduino mega) that uses the basic CFOP method (solves cross -> corners -> second layer edges -> OLL -> PLL). The simplest way of going about it would be to pretty much hardcode in...
I am currently in the design phase of a binary protocol which is intended to be agnostic of the transport layer, meaning it should work on top of for example websockets as well as serial device to device communication. In short each participant maintains and send and a receive buffer of size X. Received messages are pu...
I am working on a portable SaaS web application that has these requirements: The application can run as a cloud service hosted by my organization. Clients can run the application in their own on-premises networks. There must be business logic for customer account registration, authorization, licensing, subscriptions, ...
List<T>.Enumerator “snapshots” list version upon creation by _version = list._version;. This allows enumerator to halt enumeration when List<T> changed during it. This behavior likely originates from need to move what is hidden under foreach statement into forefront while in obedience to contract (for each). foreach(va...
The use case output port is called by the Interactor returning the response model, and the output port could be called many times with different responses. Question: Could the output port has multiple methods and the response model divided into multiple response models one for each method? I mean to do this interface...
How much (if any) unit tests should be written when you start a new templated project? In particular, let's take as an example a typical .net framework template for asp.net mvc or other similare ones that give a bunch of boilerplate. Typically, much of this is pre-configured configuration, and you delete much of the "...
I have a very large C++ application running on a *nix environment, which is occasionally setting a particular date attribute on a structure, way off what it should be. I know which structure and which attribute is going wrong, but what I need to do is to capture the stack trace where the value is being set incorrectly....
Currently, I'm reading "Code Complete" by Steve McConnell, 24.3 chapter "Specific Refactorings". I've become kind of confused with 4th paragraph, that looks like: Move an expression inline Replace an intermediate variable that was assigned the result of an expression with the expression itself. Does that inline expre...
I have a class called SomethingProvider that contains: private static string convertMapA(string convertA) { switch (convertA?.ToUpper()) { case "NONE": case "TEST": case "MEHTEST": return "None"; case "MEH": return "meh"...
For a middleware solution I expose an API, which processes data and sends the necessary information to different parties. In the current design we create a new client, which acts sort of like an HttpClient per request (because it holds internal state which we keep track of). Previously the clients were tightly coupled ...
I have app which uses IOC container. I have services registered in container, and I can consume either data factory, or particular data object. Which approach is preffereable? Consuming factory object: DiContainer.Register(ConfigurationFactory); class Service { Configuration _configuration; Service(OperationC...
I'm drawing the class diagram that depicts the domain model of a system. This diagram is for requirements analysis purposes so it is completely implementation-agnostic. I want to communicate the allowed values for some attributes in some objects. This is an example: So basically it should act like an Enum. Is the diag...
Trying to clarify my knowledge on databases and indexes. I'd like to know how exactly it works. So I have a few questions: When indexing a table over column or set of columns, a new table is created that holds "indexes". What exactly is stored in that table? A pointer to the row related to the index & some integer val...
I've discovered my biggest issue with practicing interview questions and writing software more generally is keeping track of indices in python, maybe partly because my first two languages were the 1-indexed Fortran and R. When I'm iterating through an array, especially with more complicated nested for loops, I very fr...
I'm developing an application (Java) in a modular architecture. I have two approaches in mind and I'm not sure which one will be "better code" in case of maintenance and conventions. I have two main modules that I want to wire them up: CORE - backend stuff UI - frontend stuff I can think of two approaches: APPROACH ...
I've recently been learning go and the versioning system seems rather odd to me. Most languages / dependency management systems that I'm familiar with (like rust and cargo) have an explicit way to specify a package or module version built into whatever configuration file they use (Cargo.toml). I understand that go does...
I'm trying to design a workflow engine using a DDD approach. Context (B1) Assign items to a workflow Invariant: depending on their types, items can only start the workflow on specific steps. (B2) Attach/detach items to other items Invariant: all items (container and elements) must be on the same step. (B3) Trans...
I refer to this fantastic answer to an earlier question I had. My question is, say you have an endpoint GET /tasks and that endpoint accepts query params to get certain groupings of data like: GET /tasks?createdDate=01-01-2022&completedDate=30-01-2022 GET /tasks?isOpen=true&priority=high etc. As a consumer of this AP...
We have a suite of integration tests that take about 2 hours to complete. Currently our flow is that each feature branch runs the integration tests, and only if the branch is updated from master and the tests completed, it can be merged to master. So naturally, it happens quite a lot that you start the tests when your ...
I need to start testing a Web API, for now I'm going to start with unit tests and I can't figure out the right way to do it. Here is what I have in mind doing: The API consists on a list of endpoints that authenticated users can access. My intention is, for each endpoint, write a unit test that checks: Status code is ...
I have a requirement where we need to collect N different events and store them for analysis. I am having trouble coming up with a general architecture for this. FINAL REQUIREMENTS The end goal of the system is to store the raw events as they appear in the Kafka Queue for downstream processing. Let's say I have three d...
Hope this is the right StackExchange community to ask this question. I am building a (Python) project that will have a list if URLs to hit. They have to be hit serially, and part of response of one API will be input to the next one. I say "part of" because which part of the response is to be fed to the next input will ...
I am designing a system for a company which provides multiple services to users, all of which generate a document. The documents all have a validity period. Some of the services can be grouped, and their documents have the same length of validity. None of the services have the same parameters, except for the general on...
I'm learning to make games with OOP and there's something I don't understand. What I can see is that the more I add methods to a class, the less it becomes reusable and flexible. For example, if we have a Player class which we can make jump: class Player { Vec2 position; Vec2 velocity; update() { velocity *=...
I am currently using tracy to profile a program I am writing. Tracy as a tool seems quite awesome, but it has one issue. You need to markup your code when profiling. This has the negative consequence of obfuscating readability by introducing code that is unrelated to the functionality of the functions being profiled. O...
Problem summary: In an application with wrapper methods over SQLAlchemy add() and query() methods, can integration tests that use the add() method wrapper use the query() method wrapper to validate that database table attributes and relationships are properly saved? Detailed problem description: We have a python applic...
So I've a class that is some kind of wrapper of a state machine for a multipart upload and it's database writes/reads. Everytime something is uploaded via REST basically the following happens MyMultipartUpload mpu = multipartUploadFactory.create(...); mpu.load(request.mpuID); //sets mutex lock if (mpu.state != MpuState...
I'm mostly interested in C and C++, but I think this question can also apply to other languages. My question is, if an unamed object or value is generated from the evaluation of an expression or function, can it be cached if that same expression or function is later called, and the compiler recognizes that the result i...
Might be a silly question or something I might have just messed up in my head but here we go... I saw a code example of someone using getPos() in their own class to retrieve the current position of an object instead of for example using myObj.x and myObj.y. That made me think about the use of public variables or genera...
I'm coding an enum strategy pattern where one of the strategies makes use of an ScheduledExecutor: class ControllerImpl { //... boolean applyStrat(StratParam param) { getStrat().apply(param); } //... private enum Strats { NOOP (NoopStrategyImpl.class), REAL (RealtimeStrategyI...
I recently attended a C++ talk on SOLID principles and the presenter provided std::string as an example that violates SRP. I wasn't quite able to comprehend why that was the case. From what I understand, std::string isn't a paragon for STL data structures, unlike std::vector etc., since it duplicates some free function...
I have a simple lambda that is basically x => "Error: "+x+".". I was just wondering if this was worth a test. It's really just a one-liner, so there's not much that can go wrong. Should I write a test?
Imagine a system for loan applications where loans can be in one of three states: PENDING, APPROVED, REJECTED. Over time, people create code, UIs, internal reports, etc. that assume there are only 3 states. It's unlikely a single person knows all of the places where this assumption is made. An idea I had is to create c...
For the project I'm working on I was thinking to create a Java Module for each layer of my system: servlet-presentation defines the implementation of the presentation layer. It is composed by Java Servlets that call the layer below and by JSPs that represent the view (Also JS, CSS...) business represents the service c...
I'm trying to group the components of my system by funtionality. This is the analysis class diagram of my system model. A service class that involves a Post entity might necessarily interact sometimes with Section, User, or also (to a lesser degree) PostVote. This also applies with the repository classes of each entit...
I'm studying DDD and trying to plan how we'll migrate from our monolith to a microservice architecture. At the moment I'm trying to work through two possibilities The first is where the shopper is an aggregate with its own microservice. There's CRUD operations against these users and their data is replicated to other m...
I am in this situation where I have to review pull requests (PRs) from one of my colleagues, who has a very broad knowledge and years of experience, she is well respected and we all know that the quality of her results are very good. However, from time to time, her PRs are just to complex for what we want to achieve, i...
I am a front end developer with 2 years experience, I am new to agile and I am having difficulty doing estimates to for user stories since I don't have any design for it? I am not sure how can I give estimate without even seeing a wire-frame and just by user story definition? We are following scrum as I have been told....
I wondered what is the "correct" or "intended" interpretation of MVVM? I worked mainly with WPF but I guess it is still relevant to all platforms embracing MVVM architectural pattern. 1. ViewModel as application Model is representation of data+logic for retrieving the data ViewModel is all the application logic and i...
I have an API that will be exposed on the internet publicly, the primary use of this API will be initially by a ReactJs front end but in the future we'd be looking to open this up to other clients that exist externally and require access to be able to call our API endpoints. The ReactJs frontend will support a logged i...
My team is working on building a bunch of automated tests for our project. Each automated test targets a "customization" our client ordered to modify an existing website. The current flow is: checkout development git pull checkout -b unique-customization-test-branch magic code stuffs git commit && git push create pull...
I am currently reading Clean Code by Robert C. Martin and in Chapter 8: Boundaries one can find this paragraph: We wanted to tell the transmitter something like this: Key the transmitter on the provided frequency and emit an analog representation of the data coming from this stream We had no Idea how that would be...
Given an app that manages appointment bookings, I'm separately storing purchases, bookings made, or cancellations (some of them non-refundable) and am required to show the sum of these, based on different conditions, in the form of one number. Right now the application will fetch the entire dataset and recalculate this...
I have read in an article DIP in the Wild that "When Robert Martin first discussed the DIP, he equated it a first-class combination of the Open Closed Principle and the Liskov Substitution Principle". As all of them are in scope of SOLID Principles, doesn't that mean that we have some redundancy within SOLID if one of ...
We want our developers to be able to diagnose production issues in staging. For the sake of this, we are planning to make an exact replica of production into staging. We are thinking however, if we scrub the non-encrypted data, that it could no longer represent issues that may be present in production. What is the best...
Refer to the highest upvoted answer here for why you should make an IPizza interface with a IPizza.Prepare() method. This is highly upvoted, But I think the answer is flawed. Sure a pizza can be prepared, but so can literally anything. Interfaces are only a guarantee of behaviors, not a guarantee of type, proven here: ...
We are trying to redesign our microservice architecture-based application to support multiple tenants. We have a simple queue service that will be utilized by other services to queue any asynchronous jobs. On the other side individual microservices will poll the queue service to fetch/pick any asynchronous jobs that th...
I have a class where I want to chain certain operations. The class look something like this class MyClass<T> { create<X>(fn: (_: T) => X): MyClass<X> { ... doCreate(fn); return this as unknown as MyClass<X>; } update<O>(x: (_: T) => O): MyClass<O> { ... doUpdate(x); r...
I am trying something out in Springboot and stuck with a weird issue where I want to send some data from my frontend (react app) to backend (SpringBoot) and make that request non replay able by users (users should not be able to capture the request and make the request again and again). Problem: I am writing some sampl...
Take this constructed example: def fetch_person(person_id, country_code=None): if is_fully_qualified(person_id): return person_source_1.fetch_person(person_id) else: return person_source_2.fetch_person(person_id, country_code) If the function caller supplies the right kind of person_id the coun...
I have three entities inside one bounded context: Company Department Agent A few business requirements: A company has a list of departments, and a list of available phone numbers. A department has one phone number, and this phone number must be part of the company's list of available phone numbers. An agent can assi...
I have a class like this. (My actual class is different. I am using this to explain the problem). This class instance is shared between 2 threads. However those 2 threads (thread1 and thread2), call the methods addToList1 and addToList2 respectively. We can safely assume that thread1 does not call addToList2 vice vers...
I've been building a library (NuGet package as I'm in the C# world here) & I want to add logging so the consumer of the library can optionally provide some logger to the library. However, there are many logging libraries out there with different interfaces, so I'm not sure the best way to go about it. I'm leaning towar...
I think I am struggling to model a relationship between 2 entities. I am trying to do so in a way that promotes DDD and captures business semantics. The following is my business context: I am developing a memberships microservice. It is a service that is used to create organizations to which you can then invite members...
Is using templates for specifying capacities of containers a good use or misue of the templates? Eg. template <unsigned int Length> class String { public: String(); String(String& other); String& operator=(String& rhs); ~String(); void Append(String& other); private: unsigned int length = Leng...
I am trying to convince others that the following first code snippet is bad practice and the second snippet is best practice. Bad practice: // There is only one implementation of Adapter public function setAdapter(Adapter $adapter) { $this->adapter = $adapter; } public function persist(Entity $entity): void { i...