instruction
stringlengths
34
36.1k
I am currently trying to refactor a piece of C# code that is somewhat procedurally written. I want to make the design clean, object oriented and using classes with single responsibilities. The code contains a class "Solution", which represents a Visual Studio solution and only contains data. This class is used by other...
Why does Twilio offer: Trunking REST API docs - Provision, configure, and modify SIP Trunks and phone numbers with the REST API. What are the top usages for this API? I appreciate that the process can be automated, but to what end? Is it really so time consuming to click the buttons? I'm having a fundamental diffi...
I am transcribing thousands of lines of computational code from MATLAB to C++. I don't fully understand the math myself, but I can run it with MATLAB, assume it's correct, and compare the results to my C++ code. The issue is that the precision I get is very inconsistent. Sometimes MATLAB gives me four significant digit...
Today, an interesting discussion with a colleague. We're going to create a wrapper for WCF's channels, that will handle the Close(), Abort() and Dispose() correctly. This wrapper is to be used instead. A coworker argued that this was like creating a domain specific language. He opposed the idea, saying it would impose ...
Assume an application with a layered architecture, i.e. presentation, business/domain/logic, data access: it makes sense to plug access to external APIs in at the data layer if what they do resembles data operations. For instance, a DLL that simply performs CRUD operations against a particular data repository would g...
In the accepted answer to "Encrypting stored data for multiple unique users to access information", @lserni describes a mapping table for users. But among the operations for the table, they didn't mention adding a user, nor "forgot my password" reset requests, which are required for my (growing/changing) environment. H...
Say I have a company directory application, so Companies have Employees. It's pretty clear to me why you would have the following GET endpoints: api/companies # Get all company records api/companies/{id} # Get company with specified id api/companies/{id}/employees # Get all employees for the co...
In OOP there is a common pattern of using listeners and events. Recently I've come upon a task where two opposite listeners were setup to accomplish needed logic: private ValueChanger createValueChanger(UIComponentFactory f) { // ValueChanger is some kind of user facing UI component ValueChanger comp = f.create...
In my web application users can submit their advertises and buy package for advertise (packages are used for priority of showing advertises) Database schema is like this: **Package: id, title, priority(integer) **PackageDuration: id, package_id(fk), duration, title **Advertise: id, title, content, ... **Order: price, u...
This is a small C++ application (and the table is not huge either) so if possible I would like to avoid include anything other than STL (and boost). So to the problem: I have a table of predefined matching of input and output conditions. This table contains 4 input variables (states), and their combination leads to 1 o...
So I've developed a website for a client, however he used to use this url with a re-direct to 'another' site of his. I had the re-direct cancelled, but whoever visited their old website before, still has it in their cache that it redirects to the old site. This can be solved by a browser cache clean-up, but I was wonde...
I'm looking for information on searching (filtering) high-dimensional data. I'm not interested in nearest-neighbour search or clustering, but rather filtering/sorting by subset of dimensions - like in relational algebra. Unfortunately my google-fu points me mostly towards spatial indexes or already mentioned nearest-ne...
Let's say I have an object A, which is too big(having too many methods and variables). So, I break it down to smaller objects. After that, I have Object A, B, and C. Obviously, Object A is from Class A, Object B is from Class B and so on. Unfortunately, I got dependencies: A depends on B, and B depends on C. Ultimately...
I've decided to lean SDL and make a Snake game. I have gotten to coding the spawning of a fruit, which the snake eats to get longer. Every time the snake eats the fruit, the fruit needs to change to a random position on the screen. I can either simply change its coordinates to new random ones, or I can trash the old fr...
I created a Python package and licensed it under GPLv3. When I created an account on PyPI, I had to agree to the following: The PSF is free to use or disseminate any content that I upload on an unrestricted basis for any purpose. In particular, the PSF and all other users of the web site are granted an irrevocable...
This question on StackOverflow presents a minimal Win32 program written in C which launches some processes (Notepad and Calc) using CreateProcess. The OP's issue is that the windows of these programs appear in the background, behind the Explorer window from where the sample program is launched. Though the question is ...
Even though I have a decent bit of professional experience with object oriented programming in Java and a basic familiarity with C, I've run into a bit of a mental block with C++ that I was hoping other developers could help me shine a light on. In Java, almost every time I define a class I naturally create a new .java...
As an example, I have database select query that returns n columns and I didn't know how many rows return (lets call x number of rows return). Sample code (c++ and SQLite): while (sqlite3_step(res) == SQLITE_ROW) { printf("\nCOLUMN1 :%s", sqlite3_column_text(res, 0)); printf("\nCOLUMN2 :%s", sqlite3...
This is ALMOST a direct duplicate of (What is the netiquette for forking other people's open source projects?) except that I could not find my answer there, and I cannot comment (because I don't have enough reputation yet). Here's my scenario: I have a public fork of a public GitHub project (https://github.com/fengyuan...
I am writing a program for monitoring communications between a server and multiple clients on a network. In particular Websocket protocol based communications. I construct monitoring objects for every client that connects to the server and route the information and trigger events for logging purposes. I am looking for ...
I am working on a complex widget with a "preferences" object tree with 50-100 objects and 3-5 properties in each object. Each property is watched by Angular and controls how some aspects of the data are displayed. The user can directly change each preference via inputs in the widget and I want to save the preference tr...
Is it wrong to add fields to exceptions? I have a problem that happens and I'm thinking of adding considerable information to an exception, but it sounds weird: an exception with getters. What you think about this?
Say you have a smartphone with two browsers, DefaultBrowser and OtherBrowser. You visit the webshop by opening Otherbrowser, and proceed through the cart steps At the end, you go from OtherBrowser to PaymentApp to pay. After you've paid, PaymentApp closes and opens the confirmation URL in the DefaultBrowser. And th...
Java arrays only allow subscripts to range between 0 and N-1 for an array of size N. The class below aims to remove that constraint by allowing the class user to specify the valid subscripts for a one dimensional array of integers. public class BoundedIntArray { private int[] array; // further state required ...
So, there are many times where I have to do things with my REST API that seem outside the boundaries of REST. In this particular instance I need to have an endpoint that checks whether a member is eligible for free training or not. I could possibly add this information onto the Read endpoint but that means that its go...
I've been looking at the Dolphin 5.0 release trailer. They made a big deal about "zfreeze" fixes, and proceeded to show a few comparisons between the old and new versions. They keep mentioning how it was previously thought to be impossible to implement zfreeze in the emulator. My question is, what is zfreeze, why's it...
I was reading this post on what it takes to become an elite developer: http://www.aaronstannard.com/what-do-you-need-to-become-an-elite-developer/ It says: "Write code for patterns, not specific instances". What does that mean? Always write your program using a predefined design pattern rather than your custom solution...
Consider a web page where a user changes his password after clicking on an emailed password reset link. The page will be implemented against an API using ajax, rather than as an ordinary form submission. That is, this question is about designing an API endpoint for changing a password. Requirements Any time a password...
Is there a single word that can describe JavaScript functions, variables, and objects? I was thinking "entities", but that word is usually used to describe the mapping between objects and a database. And I'm trying to be more descriptive than calling them just "things". Also, "concepts" or "ideas" seem a bit too abs...
How is the C language portable to any instruction set (I mean for new architectures)? Do we have to write a new C compiler for each new architecture?
I am searching for a universal algorithm that shifts pitch and time while keeping the sample rate. (I am trying to program a sound generator (sine, triangle...) as an exercise) I just want to squeeze the samples of the sound together so it appears to be shorter and pitched higher. It's easy if you want to speed it up w...
I am about to release my first ever app, I have used a library that is licensed under Apache 2.0, my question is do I need to communicate with the library owner before I release it or in case I decide to monetize my app am I by any means obligated to sharing my revenue with the library developer? lastly do I need to ma...
In object oriented, we have requirements, use cases, and UML which can form a nice conceptual framework. The goal there, is to define objects, their responsibilities, behaviors and communications between them. What would be the equivalent in functional programming world of objects / responsibilities, behaviors and com...
I have the following scenario: client asks to develop an application for his company. It will be a simple frontend, rest api and Oracle database. It needs to be installed on 15 devices which will work in a local network and use some rest api to save/read data from database. Now the question is: can I deploy this app to...
The 0-1 knapsack is a well-known algorithm that solves the problem of finding the maximum profit P of putting some of n object( each of weight w and profit p) in a bag of capacity W. How can I use the same algorithm to find the maximum profit of putting sum of the n elements in more than one bag? I'm trying to solve th...
I have modeled a problem as a graph that consists of many trees. Some of the nodes in the graph may belong to more than one tree. I am trying to describe a subset of paths in the graph with as few nodes as possible in order to store them efficiently. All paths start from a root and end at a leaf node. Below are a few e...
Let's say I have such code (and its meaning is like in C#): class Foo<T> { public T my_field; } and later in code I have: var foo = new Foo<int>(); foo.my_field = 5; My problem starts with the Foo<int>. What I currently do is I take type Foo<T> and mapping T -> int and clone the surface of that type. Surface beca...
I am trying to create a program for managing employees. I cannot, however, figure out how to design the Employee class. My goal is to be able to create and manipulate employee data on the database using an Employee object. The basic implementation I thought of, was this simple one: class Employee { // Employee data...
In the merge_sort part, there are multiple calls to the same function within the recursive. How are the other two executed when the definition holds that till a condition is false, the recursion does not stop? T tempArray[right - left + 1]; int pos = 0; int left_pos; int right_pos = mid + 1; ...
When modeling bigger domain entities you will probably have some kind of relation between these entities. These relations will usually result in entities referencing different entities. If i am not mistaken, there are two ways of modeling these relations: Aggregation ( A uses B ) Composition ( A owns B ) When modelin...
My Controller code: ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ObjectReader objectReader = objectMapper.reader(User.class); ..... .... response.setData(userControllerDao.updateUserDao(user, id)); My Dao code: public List<User> updat...
While I'm trying to design classes based on DDD principles, I'm quite confused for this particular "pattern". For example, ScholarshipProgram contains many Cycle. They seem to be aggregate to me. But Student only apply to a Cycle not the ScholarshipProgram. Should I design it to be like this: This seems to break ag...
I am reading the classic book on C - The C Programming Language Book by Brian Kernighan and Dennis Ritchie. The preface of the book says All examples have been tested directly from the text, which is in machine-readable form. What does this mean?
I have a video coming from a stationary camera. Both the resolution and the FPS are quite high. The data I get is in Bayer format and uses 10 bit per pixel. As there's no 10 bit data type on my platform, the original data is stored in memory using 16-bit words. I want to implement some kind of lossless compression of t...
Please forgive me if this question belongs on different StackExchange site. A much more experienced colleague (like, 8 times more experienced than me) has vigorously defended an idea that you should check multiple hash types (md5, sha1 etc.) as well as size to be absolutely sure that given file is not a duplicate of an...
I was recently hired, and I found two exact applications with a single extra service in the duplicated version, and of course each application points to separate databases. However, the original version had some vulnerabilities that I need to duplicate again on the copied version. Thus, the raised question is: should w...
Can one define a section of an HTML webpage to download (typically using HTTP), instead of the whole file, and utilize this in a program to save bandwidth? For example, in C# (but I guess the language is not important).
I am currently designing a programming language and I'm at the stage of making all the design choices that will guide the developement. My language has a slightly different syntax and concept to many other languages out here, and I wonder if it's more important that the language blindly follows its concept, or if it's ...
I'm doing some cleanup operations that could throw an exception, and I want to implement the logic of a finally block, but only if no exceptions are thrown: The initial implementation is this: acquireResource(); try { // stuff } catch (Exception e) { cleanupFromException(e); throw e; } finally { cleanup...
At the moment my specification files are along the lines of: Scenario Outline: Do stuff Given I am on the "<website>" And I have entered "red" into the search field When I do something Then something happens Examples: | Description | website | | Domain1 | www.domain1.com | | Domain2 |...
I have a data structure, a large dictionary, that is mutated by several functions. Each function does a database call, some calculations and then changes the value of a key in the data structure. Each function never changes more than 2 keys in the dictionary with the vast majority of functions changing only one. I've e...
I have a website that was originally created as a one page application that is now morphing into a full (multi-page) site. I am trying to refactor the various design elements for reuse on the other pages. Not all pages have the same elements. What would be the best way to do this: put the code for each element in a ...
I got this problem in an interview and want to confirm multi threading adds no value here. Case: You are writing an agent to buy stocks. The agent is initialized with a set of stocks to buy when they hit a certain price. A separate (out of scope) service monitors the market and invokes a callback on your agent when ...
Programming books usually preach to only test a single method in a unit test. This is supposed to keep the tests independent of each other and reduce the amount of work needed to rewrite the tests if a particular part of the system changes. But what about calls to set up the object under test? @Test public void testMet...
I've come across the following State Design Pattern which seems extremely logical and simple to implement: class CeilingFanPullChain { private State m_current_state; public CeilingFanPullChain() { m_current_state = new Off(); } public void set_state(State s) { m_current_state = ...
I'm developing a Xamarin.Forms app with a .Net Web API backend. I definitely don't want to do long polls on my app to the server, but I need the app to remain updated with the server information. I thought push notifications were the solution (I even started developing that way), until I saw several examples using it o...
def quicksort(N): if len(N) < 2: return N else: less = quicksort([number for number in N[1:] if number < N[0]]) more = quicksort([number for number in N[1:] if number >= N[0]]) return sum([less, [N[0]], more], []) print(quicksort([1, 9, 6, 10, 8, 7, 2, 4, 3, 5])) It seems to work,...
I am writing an application in Angular JS (1.5), and I need to be able to track a model for changes (updates/deletes/additions). For example, I have an ng-model that holds an array of user pets. This array has 5 pets, but the user (from the front end) can delete pets from that model or add more pets. I want to be able ...
No opinions, please. Is there any technical reason to typedef void? My current company and my last both have typedef void XYZ_void; where XYZ is the project name. I can understand a typedef for XYZ_INT, but void? Is someone afraid that the size of void might be different on another architecture?!
I have a method that updates employees data in the database. The Employee class is immutable, so "updating" the object means actually to instantiate a new object. I want the Update method to return a new instance of Employee with the updated data, but since now I can say the responsibility of the method is to update th...
Is it correct to say that threads were invented to enable programmers to expose process internals to the OS scheduler?
On the topic of Git; are there other types of version control systems? other than Local VCS, Centralized VCS and Distributed VCS stated in here?
I found an interesting quote in SICP that I think is highly relevant in object oriented design: We see that, in general, a type may have more than one subtype. Triangles and quadrilaterals, for instance, are both subtypes of polygons. In addition, a type may have more than one supertype. For example, an isoscele...
First off all: sorry for the title, but I didn't now how to better formulate the meaning of my following question in a single phrase. While I was writing the following Swift code: if errorData.isMemberOfClass(UIAlertController) { self.presentViewController(errorData, animated: true, completion: nil) } else { /*...
I've been tasked with overhauling a fairly large web-system that requires much user input. In an attempt to instruct the users when making input, the original creators has made extensive use of feedback structures like help texts and tool-tips. The problem for me is that all the text material used for user feedback is ...
Sometimes we meet a situation where we should iterate (or map) over a collection, applying the same procedure (function) for all elements except the first one. The simplest example is finding the max element of collection, but is not a good one: the operation here is idempotent. More realistic example is table dumping ...
I am trying to formulate a definition of a monad without needing mathematical terms or Haskell to understand. Can a monad be thought of as a function that accepts a value and wraps it such that it meets specific interface and behavioral constraints that have been found to be useful when working in a functional style? T...
When using tools such as TFS or JIRA to plan an application made of 10+ microservices, I am concerned should I consider microservice as an epic or as an new project? In TFS when splitting microservices as different projects, the benefit is a separated git repository, but on the other hand it is difficult to plan a sing...
I want to make a small command-line-run program that looks for a word or phrase in a target .txt. or .docx file, prints out a corresponding blurb about that phrase, and then replaces it with a different word/phrase. There are about 200 of these tuples. What is the best way to structure this? I'm thinking of putting th...
Most higher level (or scripting) languages out there have data structures that can hold different types of data (like numbers, strings and even functions) in the same structure, and you can also add elements without caring about their size, which you don't have to specify. They are sometimes called lists. In contrast, ...
I have a set of about 300 unit tests that have been through a difficult few months. The poor tests were subject to being upgraded from a V110 compiler (Visual Studio 2008) alongside Visual Studio 2012 to a V120 (Visual Studio 2013) compiler alongside an upgrade to Visual Studio 2015. These tests were passing in VS2012....
We have a web application that is accessed via kiosk workstations. We are looking for a way to track usage of each individual kiosk. Using the IP address was our first thought, but we quickly realized this wouldn't work since these particular machines are behind networks with dynamically allocated IP addresses. To acco...
I don't know very well Python. I'm trying to understand more precisely what exact features of dynamic languages (à la Python, Lua, Scheme, Perl, Ruby, ....) are forcing their implementations to be slow. As a case in point, Lua 5.3 metatable machinery would intuitively make Lua quite slow, but in practice Lua is rumored...
I have a requirement to (re)design an existing REST API which is written in Django REST. One of the main requirements is allowing third parties, approved by us, extending of our API. The API is a gateway to couple systems like central ldap, application databases, mail configuration etc. and provides couple means of aut...
So, I have a bunch of calls that are all being generated with a UUID1 throughout the day. At the end of the call the call is processed and some metrics around that call are generated and stored in Rethinkdb/Cassandra. Each call will generate something that looks like this [{ "company": "foo company", "campaign":...
I'm creating a .NET MVC solution that will have two web projects, one for API and for Web. Some models, such as customer, will be the same between the two projects. Is it best to have them kept in a common web library and referenced from the two web projects, or keep them unique to each project?
In a library with many code, some of them being the API which user would use to interact with the library, what should I call the rest of the code which is not part of the API directly? In other words, what's the opposite of API called? Internal code? Private code? Seems really simple but can't find the correct termin...
I am programmer with 1 year experience, recently I realized I seldom start a project correctly (most of my side project), normally the project cycle goes like Start with a few use-cases Start coding Realize a few things I did not handle well, and does not fit well in current codebase. Rewrite most part of code and th...
I am working with an effectively third-party library. This library has a base class that's used as the interface (C++ style), ComponentBase. ComponentBase has a number of methods and setters that are implemented by its derived classes. In particular, right now I am interested in one specific item there: the Value prope...
Let's say, I have created a business logic layer service (or a handler in Command/Query pattern) with a method DoSomething which processes a bunch of entities and stores them in database. Later on, another developer sees - "oh, this DoSomething method does almost everything I need, I can call it from my DoThisSomething...
For example, I have an UI with a button "Get Items" and a text field "Order". Then my button will retrieve all items from the order written in the text field. How should my controller know the order? Should it be public void GetItems(string order){ } or public void GetItems(){ string order = View.Order } or may...
After trying to write small programs with out reading much of the concepts in Java, the following syntax bugs me a little: Car volvo = new Car("Sweden"); class Car { String country; // constructor which has no return value and is to construct an object (fill with data) while creating it with the arguments supplied...
Apllication structure: Business layer public interface IOrderDataService { void Save(Order order); } public interface IOrderLineDataService { void Save(OrderLine orderLine); } public class OrderManager { private IOrderDataService _OrderDataService; private IOrderLineDataService _OrderLineDataService...
I was told to avoid "new" statements in classes or functions but rather create the objects from classes in the root of the program (maybe with the use of a DI-container) and then inject the objects into the classes. Anyway, I think there are many (the majority of) cases where this "rule" can not be true. Let's see this...
I referred this page for understanding about constructors in Java: http://www.javatpoint.com/constructor So, I pretty much got it as in my own words: constructor has no return value and is used to construct an object (fill with data) while creating it with the arguments supplied What is the purpose of using construct...
A Google Search on this topic just returns results explaining how to hack Google Analytics site search for POST-based search engine measurement. So, I thought I would turn to you fine men and women for help. I know the main differences between GET and POST involve security and caching (POST requests are secure and are ...
Let's consider an example wherein I have to model the following: Class to schedule exams for a Student, lets call it StudentExamScheduler Class to schedule exam for a Class. Let's call it ClassExamScheduler and currently it depends on the logic provided by StudentExamScheduler. So since both the classes schedule exam...
What is the term to describe all the instructions that executed as a result of a particular instruction? main(){ if(a) call_a(); else call_b(); } func call_a(){ //do_something //sleep... call_b(); } I would like to describe all the statements that are executed as a result of calling call_a() until it...
I recently encountered a class which provides pretty much every single-character as a constant; everything from COMMA to BRACKET_OPEN. Wondering whether this was necessary; I read an "article" which suggests that it may be helpful to pull single-character literals into constants. So, I'm skeptical. The main appeal of u...
Is the following an acceptable way of doing program licensing? A license file containing following informations: Magic identifier (to verifiy that it is a license file for the program) License id Customer id License create date License expire date (to check if it is expired) Last use date (to verify that the system t...
Our lecture provides us students a quiz to revise the material learnt of the last study session. The answer to the following questions was stated as "Yes": "The receiver of a message does not have to be known, when the message was sent." This really confused me, cause thus far I expected a sequence diagram to visuali...
Why doesn't System.String include a constructor capable of taking a IEnumerable<char>? The expected behavior would be: var foo = "hello"; var bar = new string(foo.Select(x => x)); Actual behavior: Cannot convert from 'System.Collections.Generic.IEnumerable<char>' to 'char*' If there is no obvious reason, I think it c...
I have a list of numbers (let's call it L) and I need to split this list into three groups (A, B, and C) such that the sum of the numbers in each group (sum(A), sum(B), sum(C)) is as close as possible to the sum(L) / 3. I'm sure it is an old problem, but I couldn't find a solution. The closest I got is to sort L, then ...
If I want to allocate a struct in C, #include<stdio.h> typedef struct container { int i; } Container; int main() { Container *ptr_to_container; ptr_to_container = (Container *) malloc(sizeof(Container)); ptr_to_container->i = 10; printf("Container value: %d\n", ptr_to_container->i); free(p...
I was solving a seating problem whose solution seems trivial but I am not able to get it. The problem states in short that we have to seat n (even) students in n/2 rows where students are labelled from 1 to n and no two adjacent students should have consecutive labels like "1 2" or "5 4". Also every student is either i...
I'm learning about paradigms of functional languages. So I've read that while Subtype polymorphism is typical for OO languages, Parametric polymorphism is typical for functional languages. But I wonder if there is Subtype polymorphism in functional languages. The functional language I know best is Haskell, and I know t...
I'm thinking about a way of finding similar parts in Strings. I have a set of strings of varying length i.e: The quick brown fox jumps fox force five the bunny is much quicker than the fox is First, i thought of just tokenizing the strings and count the tokens but in the case of "quick" here I also need to match "qui...
In an open source framework deprecated APIs were removed during the beta phase on the road to a new major version. Now users request to restore some deprecated APIs because it breaks compatibility. For me, beta stands for "Use at your own risk". Isn't it expected that due to a major version bump the API may change? I...
Given that Explicit is better than implicit. But also Simple is better than complex. I was wondering how accepted it is to transform code like this: import argparse def func(a, b): return a + b parser = argparse.ArgumentParser() parser.add_argument('a') parser.add_argument('b') parser.add_argument('c') args...
I am wondering why every git workflow merge develop into the production branch. Is there any reason why we cannot just leave the old production branches and create new ones from develop (in case we have only those two "special" branches). What is in there what need to be merged. Anyway every hotfix should be put into d...