instruction stringlengths 34 36.1k |
|---|
I want a class A, and I want the relation that A can have zero or one X.
So I wrote this class:
public class A {
private X x = null;
public A() {}
public A(X x) { this.x = x; }
public boolean hasX() {
if(x==null)
return false;
return true;
}
public void setX(X x) { ... |
Let's say we have function A and function B which perform consecutive operations on some data, with B never receiving the data before A processes it.
Function A makes exhaustive checks on potential errors on the input data. For A, it's a no-brainer to write proper unit tests. Should there also be tests written for B? ... |
I am having trouble with a coding question that I found practicing for a interview:
A scatter graph of points on a page, draw two horizontal lines (these lines are parallel) across the page such that the perpendicular y distance to a line from all points is minimized. Count the total distance from each point to the lin... |
I am minding my own business at home and my wife comes to me and says
Honey.. Can you print all the Day Light Savings around the world for 2018 in the console? I need to check something.
And I am super happy because that was what I had been waiting for my whole life with my Java experience and come up with:
import j... |
The question: Is it considered better practice to use derived types/subtypes or to use conditions and exception-handling to restrict the acceptable inputs for a subprogram in Ada? I understand that in Ada2012 you can use contracts, but what about for previous versions like Ada95?
The context: I want to make a series of... |
I was revisiting my question How can I prevent header hell?, when I noticed a comment which said
A good technique for ensuring a header is independent is having a rule that the source file always includes its own header first. This will catch cases where you need to move dependency includes out of the implementation f... |
I was wondering what would be the best approach to allocate/deallocate multiple one-dimensional, dynamic arrays in C. This seems easy at first, however, for me it turned out to be problematic. Consider the following example program, which illustrates my problem:
#include <stdio.h>
#include <stdlib.h>
#define N 10
int... |
Basically, I am asking, whether my code should say
#include “../libs/src/my_lib.h”
or
#include “my_lib.h”
with a complier option of
-I ../libs/src/
I feel (reasonably strongly) that the former is preferable, because:
it is independent of build system
it specifies exactly which “my_lib” is meant, in case ... |
As I understand, the point of unit tests is to test units of code in isolation. This means, that:
They should not break by any unrelated code change elsewhere in the codebase.
Only one unit test should break by a bug in the tested unit, as opposed to integration tests (which may break in heaps).
All of this implies, ... |
I am used to treating the issue tracker as a source of truth and an organisational memory. I use it to record what the issue is and what has been done towards resolving it.
I consider this to be essential and basic to good software engineering (including agile development).
I am willing to consider the possibility that... |
We have about 10 applications in one Monolith that need to be refactored into Microservices.
Following an Agile approach, we would like to split work into vertical slices where each slice would be useful to the User. Each slice would include a persistence layer, a service, and a user interface. However, we are not sure... |
The problem I am trying to solve today is DDoS. I am working on a game project which is hosted on a TCP port (7777). The game is known to have a community full of idiots (pardon the language) that do not like competition among communities, so they just like to DDoS servers to... kill the competition instead. Depending ... |
I am trying to write a spellchecker, I have a huge wordlist (at least 500K, because of the nature of the language). The performance would suffer a lot if I got the lavenshtein distance of all of the words in the wordlist to the current word.
So I am trying to distribute the wordlist into buckets based on the characters... |
I would say no, because a MATLAB licence is required to run the software, but this point isn't completely clear to me.
EDIT: This was a terminology question, not a request for legal advice.
|
I have an app that already locally archives user created objects and has for several years. Each archived object can have several nested objects or arrays of objects in it--all of which conform to NSCoding and are archived with NSKeyedArchiver.
Would it be wise to use the NSData objects I already have from local archiv... |
Where do you draw the line for how much logic can go in your read models? For example, we have 2 BCs: Inventory and Sales. We need to generate reports regarding inventory levels on specific dates: perfect for a Read Model.
Simple SELECT from InventoryItem and OrderLine tables based on the ProductSKU. I can then use the... |
Say I have a TypeScript class:
export class TypeCreator {
entities: Set<Whatever>
registerEntities(e: Set<Whatever>): Set<Whatever>{
return this.entities = e;
}
}
if registerEntities() should only be called once, should I throw an error if they call it twice, or just overwrite the value, or is this a code ... |
I'm relatively new to programming and have never written tests. I want to write unit tests for a group project (Angular web app with node background environment written in typescript), which you can find here. I picked out an examples which I want to test and I hope with your answers I can transfer what I learn to othe... |
I have relatively simple controller logic with ugly parts of object creation. Some of the objects are really huge and even though all the controller does is to return the object, it looks messy and hard to read. So I would like to ask how can I make such cases cleaner. Let me show you a few examples:
For instance, pay ... |
Many place that i have read about static method they said please shouldn't use static method for access to database and should use dependency injection for inject other service and use that service to write other logic.But problem it
happen when i inject AService in BService and inject AService in CService many month... |
I'm working on implementing my first clean architecture and CQRS application, I've stumbled across a bit of logic that's leaving me a bit stumped. I'm working on integrating authorization and authentication into my application, but I'm having some trouble trying to figure out how to architect a portion of my applicatio... |
In the C++, there are 6 bitwise operators:
Symbol Operator
& bitwise AND
| bitwise inclusive OR
^ bitwise XOR (eXclusive OR)
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)
In Qt, I have seen |, ~, and & used fairly often in functions:
file->open(QIODevice::Wri... |
So say I have a controller Method
// GET: TimeEntries
[HttpGet("[action]")]
public IEnumerable<TimeEntryDTO> GetLast(int value)
{
return dal.GetLast(value);
}
And a data access layer method of (using AutoMapper to convert TimeEntry to TimeEntryDTO)
public IEnumerable<TimeEntryDTO> GetLa... |
I'm doing this in python, in case that changes anything.
I'm trying to make a lamp/bit go 1-0-1-0 until the user says "okay"
the "okay" should indicate that the user has found the lamp/Bit IRL.
Now i'm struggling to find a way to ask the user a question, (because it stops the program cycle), when I also want the lamp b... |
I am new to C# and have a difficulty with the code structure. My application has:
GUI with button Show my Ethernet IP. When user clicks this button PC's IP address is displayed.
Class ModbusTCPSlaveMachine. Within this class I create TCPListenter and supply it with PC's Ethernet IP address.
In both cases I get local ... |
I was following a tutorial on the normal forms of SQL databases, and I got confused landing on this example : https://www.tutorialspoint.com/sql/third-normal-form.htm.
From
CREATE TABLE CUSTOMERS(
CUST_ID INT NOT NULL,
CUST_NAME VARCHAR (20) NOT NULL,
DOB DATE,
STREET ... |
In a program I'm working on, I need to do a substantial amount of real-time reflection in order to maintain a list of known "attributes" throughout the program structure (for use by a sort of "virtual programming assistant"). I came up with kind of a "cheaty" way of doing this (which I'm frankly kind of proud of), whic... |
What is the best way to Mock a return type if we don't care about the actual state of the object.
For example, I am Mocking a method whose return type is: IEnumerable<Document>
Now, I can add relevant Nuget package and add necessary namespace so the type Document is defined, however I actually don't need to test anythi... |
I have a use case for which I need to build a data processing pipeline
Customer contact leads data coming from different data sources like csv, data base, api has to be first mapped to a universal schema fields. There could be ~100k rows coming each day that need to be processed.
Then some of the fields have to be cl... |
Domain Driven Design states that you should have a domain model, which reflects the ubiquitious language used by the domain experts. When using ORMs and many to many relationships I am use to doing this:
public class Student
{
public Student()
{
this.Courses = new HashSet<Course>();
}
public ... |
In a long running Windows Service I have a custom thread pool manager that has a loop which continuously looks through a couple lists for idle threads.
Given multiple uses of the same predicate, is there any benefit to saving off the lambda as a Func?
How might the recommendation change based on the count of threads th... |
This is purely a design philosophy question in the context of C++.
Is it a okay design philosophy to start a thread from within a constructor? I have a library whose sole responsibility is to asynchronously handle some requests by exposed APIs. For this to work it has to start a thread internally.
I have MyClass which ... |
Our team had recently a big struggle of deciding whether it is a good practice or not for the .NET Core class libraries to register their own implementations by the fact of providing a IServiceCollection extension methods like AddMyServices().
My point was that it is good to do this because:
Top level application does... |
Is it a pattern or antipattern to inject a dependency that is a tree of dependencies?
For example:
public class ClassExample
{
private IContainer _container;
public ClassExample(IContainer container)
{
_container = container;
}
}
public interface IContainer
{
IDependencyA DependencyA { get... |
I have programmed using the architecture below, where "client, order, piece" are just data classes, have no methods, and "managers" are the manipulators of that data, the "ClothingStore" is a wrapper where there is no logic, only calls the methods of the managers and return what they return, so the "ClothingStore" woul... |
Burn down and burn up charts are used in agile projects to visualize the progress of a sprint. The same type of chart could also be applied to entire projects, not only to a single sprint. Thus they could be used in 'traditional' waterfall or v model projects as well, however I could not find evidence for that.
Is ther... |
Uncle Bob says in 'The Clean Coder', chapter 5 'Test Driven Development':
You are not allowed to write any production code unless it is to make a failing unit test pass.
You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
You are not allowed to write... |
Generally, constructors in an interface are considered as being an anti-pattern. Some languages even don't allow that.
Then I don't understand how we're supposed to deal with polymorphic immutable objects in the some particular IOC contexts...
Say we have to instantiate a polymorphic object, its class implementing our ... |
I have a "tracker" class. This class tracks objects from a given input image. But in addition to this, there is another parameter that corresponds to a value used in generating the image. The tracker may want to suggest a new value for this parameter to get better results on the next iteration. It would be suggestin... |
On a typical web app, we commonly have to deal the LOADING/SUCCESS/ERROR problem - which is that:
When I make a backend request I want to display a loading cursor, perhaps disable some buttons.
When the request finishes successfully, I want to display the data.
When the request finishes with an error - I want to di... |
In my C# project, I have a domain class named 'User'. this class will contain user's id, firstname, last name, DoB, home address, phone, etc. And we also have a typical REST web api (i.e. api/users) to read/create/update/delete user. When we create a method (in class UsersController) to return a single user's details, ... |
I need to send a json response. I use the jackson library to convert the class to json. I have a core java class to which I need to add some more fields to create my json response. I came with two ideas.
To extend the core java class.
To have an another class with the core class object as constructor.
Concerns over ... |
What is a good strategy for Q/A Engineers peer reviewing Unit tests as part of the software development life cycle?
I think that there are, indeed, things that I should check regarding the unit test made by the devs (like making sure that critical part are well tested).
So, what should I be looking for in those peers r... |
Suppose we have the following classes:
As you see, it's an implementation of the State Pattern.
Basically, the Order class proxies the pay() and cancel() method calls to it's concrete OrderState instance.
After executing their part of business logic, the PendingOrderState and PaidOrderState call setState on the Order ... |
Assume that a Python package (available via PyPI) is too difficult for novice users to utilize. Specifically, typing python2 path_to_package/start_GUI.py in the command line, which opens a TKinter GUI, is too hard for many users. Instead, users would like to simply double-click on the file start_GUI.py, irrespective of... |
I bought three boxes of tea bags with different flavors (A, B, C).
I wish to mix them in such a way that - there is never two consecutive bags of the same flavor (ABCCAB is avoided) ; - the mixing is the "most" random, i.e. avoid patterns such as ABCABCABC... or ABABAB...BCBCBC...CACACA.
Is there a known algorithm for ... |
I had a conversation with a recruiter recently. As a contract engineer, I've worked several jobs over the years and it's been ages since I saw a formal specification. Confluence pages, yes. Jira items, yes. Agile and Kanban documents, yes. I made the statement that specifications are discredited because, like war ... |
I'm trying my hand at multi-thread C programming and decided to start with a simple ncurses program to move a character across the terminal screen and change direction based on user input (think classic snake game). I decided that I needed to create a separate thread to handle moving the character across the screen, w... |
Here are the requirements: (not the real case, just very simplied version)
There is some sort of promotion which lasts for a week.
The selected users who may benefit from the promotion is fixed at the beginning.
Everyday, each selected user gets some bonus(say some credit points) from the system.
I'm thinking about i... |
I'm developing a database with a price list table for my workplace. I came with two major options, and would like to have your opinion :)
It's rather simple, containing: Id, description and price
On one hand, it's now working with each price on new row and having an extra field start_date, and is the way I've found o... |
I have a system that checks the status of a large number of entities on schedule every minute. For each entity, there would be a JSON file which has fields indicating the statuses for different attributes. The system dumps these JSON files on a network share.
Each run of the schedule that runs every minute generates a ... |
I am new to TDD/unit testing.
I am going to write a complex scheduling algorithm in Java. As this module is a core part of our application and there are number of scenarios in it, I want to write unit-test cases for every case.
To compute this schedule, I need to interact with 25-30 entities and each entity, on averag... |
I wrote a binary calculator & binary teaching program in the Rust programming language. I was taking an iterative approach in that I decided to first get a basic "learn binary" game started. This game displays a hex or decimal number to the console and requires the player to enter the number in binary 1s and 0s as a me... |
I encountered a situation where the dev team suggested that they will push bug fixes to our dev environment rather than to the test environment, and they asked QA to test there first. I am not sure if this is a good practice, I always thought it is better to test in the test environment, but maybe there are circumstanc... |
Let's say I have User resource which has Address sub-resource (let's forget about why this is a resource instead of attribute). To get a user's address, I can do
GET /users/{id}/address
Now I want to have an API which returns all the addresses regardless of their owners. I can do
GET /addresses. This feels a little bit... |
I got the following code snippet:
public Task DistributeAsync(BankAccount account, decimal amount)
{
lock (account)
{
return repository.AddLoanAsync(account, amount).ContinueWith(task =>
{
if (!task.Result)
{
throw new LoanException();
}
... |
I have a problem in formulating LL(K) grammar for this postfix expression problem, given (4 3 / 2 * 4 5 / +) as an input must output 52/12
|
Given is a design of a video game in which a player has several possibilities to adjust his character:
Game designers realized it's senseless to be a fire-elemental and water-elemental at the same time. Is it possible to create such a character with the current design? If yes, is it possible to avoid that without remo... |
I'm coding a game and I have a design issue in which I have a superclass which all items in the game inherit from. The game is grid based, and the items can be placed at different parts of the grid. The grid has a dictionary of grid positions -> BaseItem.
The problem is, the derived items all do very different things. ... |
TL;DR:
My goal is to create some framework with which I could discover/test all possible internal states of my application so that I would approach with confidence for example engineering software for medical devices, airplanes etc...
Let me first explain some context...
I was watching interesting video on example mapp... |
A common algorithm used in N-body gravitational calculations with large numbers of bodies (stars in a galaxy, galaxies in the universe, etc.) is the Barnes-Hut algorithm, which assembles particles into an octree for approximate bulk calculations of gravitational forces between distant areas. The complexity of this alg... |
I am starting a new service that would be an abstraction on top of git repositories. Basically, a user would sign up and Add Project (GitHub/GitLab/BitBucket repository).
The tricky part for me is how do I verify that the person has appropriate permissions on the repository they're adding?
I was thinking of a method to... |
I wrote a Music Player and Library in Java for GNU/Linux and Windows.
My build process is currently in ANT, but I intend to migrate away from that to something more modern after the next release. I've heard good things about gradle, but if there's something more suitable you'd like to recommend, I'm open to that.
The... |
I am wondering if it is possible to create a regular language from a irregular language if we add or remove finite number of words from it?
say L is irregular, can we add or remove finite number of words to create a regular language?
i might be mistaken, but since all regular languages are finite - if we add a finite a... |
Good Pythonic style is much looser than Java's uptight restrictiveness:
In Java, good style means private on methods wherever possible, all fields encapsulated, type declarations, defined interfaces including abstract methods.
All this is now doable in Python, but good style allows and encourages public members, d... |
I am creating an application where users can create forms with many fields of text, numeric, date and select types.
The model will have a forms table referenced by responses table;
It also have the fields table with 'name', 'field_type' - it points to forms too;
The filled data will point to responses and to fields, b... |
This is kinda like a concrete version of the question Coming up with tokens for a lexer.
I'm writing a lexer for a small subset of HTML. I'm wondering what should I do when the input stream ends and I'm in a state where I've successfully recognized a token, but I know that it will be a syntax error.
I emphasise "I know... |
This expands on "Deadlock in Single threaded application" on StackOverflow.
That question was not really conclusive and I think it better belongs here.
By the definition of a deadlock, is it technically possible to produce a deadlock by using just a single thread?
This is the definition of a deadlock according to Wikip... |
Almost every blog post I've encountered around generic auth handling using JWTs in a React/Redux/Saga application does the same thing, which is to store the JWT in local storage, in the action/saga.
For example:
Example A (redux-saga):
function* authorize({ payload: { login, password } }) {
const options = {
bo... |
I need to make an Employee Payroll application and the client specifically stated that the application will run on their computer locally and will not be hosted anywhere in the internet.
I can code in Javascript, C# and in Python. I was thinking of using Electron for my front-end so that I don't have to worry about c... |
I have introduced sprint into our team and after a rocky start, we are starting to get some rhythm. One of the opinions of the dev team is they still want to be able to work on bugs and enhancements requests that are "easy" to do as this makes our customers (internal to our organisation) happy. After all, that's the en... |
I have an array that holds valuable data related to what I stored in a setup / onboarding process:
$imported_headers = [ 'headers_2', 'headers_3' ];
Given the fact that these elements are from the same category but their [each element's] content varies by a lot at times and each of them only holds references that all... |
In our agile-scrum process, for each epic we are creating , we are creating automatically one user story that is related to that epic.
From that user story, we are creating automatically too, 4 subtasks:
one design task
one technical analysis task
one product task
one QA task.
The technical analysis task should ex... |
We have a bug process that is currently being worked.
We have 3 levels of bug:
P1 bug: Bugs that prevents users from working. They must be solved on the spot.
P2 bug: Bugs that are impacting but users can work
P3 bug: Bugs that are not impacting and where users can work.
P1 is mandatory and must be dealt on the spot... |
I'm developing a set of classes designed to communicate with external APIs, and I'm running into trouble with how to properly structure everything for proper loose coupling and unit testing.
Currently, each API we need to talk to has a distinct class, which implements an interface a bit like this:
public interface IApi... |
I am from OO background just started learning FP paradigm. Came across quote by Michael Feathers - "OO makes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts"
What exactly he meant by "moving parts" ? My guess is that by moving parts he meant "state mutation" be... |
This is a question about terminology.
If I say "I'm a developer, and the team I'm a part of does foo" then you'd understand my position.
If I'm a scrum master (who is a scrum master for two teams), I might say "one of the teams that I am a scrum master of", but I was wondering whether there was a way to say that in a l... |
Background information
I have a database that will be used by two different web applications.
Solution A (user driven web application) resides on the public internet and will write / update / delete records to the db. Solution / Service B (not user but process driven) resides behind the FW and will only read the data... |
We are discussing at the company the migration of some on premises services to cloud alternatives. Is it market practice to backup servers on AWS, or repositories on GitLab.com, or files on Google Drive?
Personally I'm pretty confident on these big companies, I'm pretty sure that their backups will outlive mine 10 out ... |
I am using protobuf definitions to define message types.
Structure looks like
message1 {
}
message2 {
bytes msg1 = 1
}
So message2 has a field which is a byte array representation of message1. I am:
Creating a msg1 struct instance
Serializing it
Encrypting byte array obtained in step2
Compute digital signature on... |
I have Customer, Order, and Product Aggregate Roots... When the order is created, it takes in a Customer and a List<Sales.Items>. It looks something like:
public class Order
{
public static Order Create(Customer customer, List<Sales.Item> items)
{
// Creates the order
return newOrder;
}
}
T... |
Broadly speaking how many downstream calls would be acceptable for a synchronous Microservice interaction, from say a gateway API down to a a few supporting services? We are seeing big swings in response time with 4-6 calls - some pass-through proxies. Is this expected?
Obviously the fallacies of distributed computing... |
The common argument for stability in a sorting algorithm typically involves an example where a list is sorted by two criteria. For example:
1,4,5,7,2,6,8,9,15,65,24,27
sort by evenness/oddness and then by value
2,4,6,8,24,1,5,7,9,15,27,65
The claim is that by choosing a stable sorting algorithm, you can sort this list... |
Discussing about a CQRS implementation with my team we don’t agree on a point concerning the Query side.
On the Commad side we have actual command clases; a CommandDispatcher that schedules commands, defines a Unit of Work scope and dispatches commands to handlers; handlers that contain the business logic and do CRUD o... |
I am on a project for which I have to spawn many different processes, all in different executables, and there will be some shared memory segments and some semaphores to synchronize them. I use an "initializer" process to open some POSIX semaphores and allocate some shared memory segments.
I can not decide which is the ... |
I have a basic GameController with a finite state machine to handle game logic.
I'm adding game modes and coming across problems cleanly implementing them. The core functionality of the game stays the same--Physics, input handling, level creation--but I have many places where I need an if/else block because functional... |
I'm building a service where I need to filter activities from different products. The actual data itself lies in another key value store. As the service needs to support filtering on the activities as well was planning to use mysql for the filtering usecase alone. As the activities from different products can be differ... |
One of the scrum tests contains the question about the definition best describing "Done" when multiple development teams perform a work on a same product.
A proper answer states that those development teams must have such a definition of "Done" that can make their combined work potentially releasable.
What is not clea... |
If an ETL tool is being used to move data from an OLTP database into a "business intelligence reporting" database, is there any standard way of automatically testing that the data in the reporting database is accurate and correct?
NOTE: I'm not interested in testing the functionality of the ETL tool itself only that th... |
I'm having trouble keeping my user stories for basic operations from sounding ... basic. For example, suppose I'm building a CRM to keep track of clients:
C: As a user, I want to create a client, so I can ... keep track of my clients?
R: As a user, I want to view my clients and their properties, so I can ... know what... |
Let's say we have this method:
string Add(int a, int b) {
var sum = _calculator.Add(a,b);
var response = _formatter.Format(sum);
return response;
}
Now I want to unit-test this method. Assume of course the code is not actually that trivial, _calculator and _formatter might be external services, there's som... |
I have been repeatedly told that explicit type conversions are an indicator of bad code and they should be avoided.
Now in all honesty I have been annoyed a bit by these claims due to the nature of my work which seems to require a lot of primitive type conversion. So I want to know if there is a better way to structure... |
I've been learning about proxy classes in c++. I really don't see the advantages of using proxy classes, as they're not any better at concealing information than private members are. What advantages and/or disadvantages do proxy classes offer compared to normal private members?
Note: I am using the "proxy" definition f... |
Let's say I have a REST API, that has the ability to provide field mask (i.e. the API can return M out of N attributes where M is a subset of N).
If a statically typed client (example: one that's written in Java) requests data from this API, is there a way to "gracefully" handle nullability issues.
If out of N fields, ... |
Let's say your company sells software that comes with customizable text, and your team's job is to customize it. The client engagement includes a contract in which the client specifies all of the text resources and where your team guarantees a complete test cycle.
Somewhere in the code there is logic that looks like th... |
Basically, I have a remote hosted server somewhere https://nnn.com
And then I have the NNN Desktop Client.
The Desktop Client shows information X.
I change information X from the remote hosted server.
How can I make it so that the displayed information X in Desktop Client is automatically updated?
At first I thought t... |
This question concerns the C# language, but I expect it to cover other languages such as Java or TypeScript.
Microsoft recommends best practices on using asynchronous calls in .NET. Among these recommendations, let's pick two:
change the signature of the async methods so that they return Task or Task<> (in TypeScript,... |
In an effort to save this question, I have re-written it. The original question was regarding how to associate aggregate roots. I have re-factored the code slightly but believe this may couple the code too tightly.
Do I introduce too tight of coupling by passing aggregate roots around? For example:
class Order
{
pu... |
Components involved:
Mobile Client
Microservices
API Gateway
Each microservice is a Flask application exposing a RESTful API. When a request is made by the mobile client, it is sent to the API Gateway.
One of the most important tasks of the system is to perform the furniture selection and furniture placement algorit... |
Some test frameworks, notably DejaGnu and py.test, have an "XFAIL" flag/status for a test which says that this test is expected to fail. If the test succeeds, it's marked as "XPASS" (unexpected pass).
Isn't this just a redundant overcomplication? It seems much easier and comprehensible to just use an assert that would ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.