instruction
stringlengths
34
36.1k
There is a single network-shared folder of files that is to be processed by threads running on several servers. Once a thread starts processing a certain file, I don't want any other thread to process it. What are some techniques to ensure that only one thread processes a certain file? Keep in mind that the threads ...
It is well known that Singletons are anti-patters for several reasons: tight coupling singletons are pathological liars no testability inheritance is not available you cannot program to interfaces, you program to implementations But there is the code: class ISingleton { protected: ISingleton() {} public: vir...
I have a project in visual studio that contain more than 10 header and source files. I start to realize I did not assign return error codes for each header correctly (i.e I found out that there are multiple error codes with the same value in different headers with different names, some error values even match state va...
I am very new to elastic search and i need to know it is even useful to store data? because i was curious to try my hands on how elastic search works and i used postman>run elastic search then added some data in postman and then could able to do POST operation on the data so i need to know without any database also ho...
In Clean Code, it is written that "the ideal number of arguments for a function is zero". The reasons why are explained and make sense. What I'm after is techniques to refactor methods with 4 or more arguments to solve this issue. One way is to extract the arguments into a new class, but that would surely lead to an ex...
I've created an application that can create and update documents. A document is a relational database (it's a SQLite database). I'm planning to update the structure of the database (add fields, add relations, add tables) The database stores the database_version in itself. I plan to embed update SQL scripts into the sof...
I'm trying to get a Java programming project set up in a way that it can be built completely offline just from the files in version control, on any machine, with no prerequisites to install. (Sole exception: the JDK) I don't know much of Maven, but I'm learning Gradle currently. For the build I'm using Gradle with the ...
I apologize in advance if the question is not directly involved in programming but I could not find a forum of programmers who deal with general questions. I am developing a cross-organization application. For a person that has no programming knowledge at all, the final product looks fairly simple - a desktop applicati...
I can't understand how the following structure elements are being initialized. MSG m = {4, 1, 0};. MSG has two elements: one is of type int and other one is an array of type short that's already been initialized. Which elements of m are assigned the values 4, 1 and 0? Here is the listing of the code taken from the bo...
I'm currently writing a web application for our small company which was originally just planned to organize appointments more efficiently by displaying our customer structure and automatically plan tours which originally just meant that our staff needs access to it. However, since we then have our structure built we co...
If I am loading a model with Model::find($id) and the id is not found it returns null. This is fine except if I try to chain things. Model::find($id)->loadAttributes(); Load attributes is going to fail because it's not a method of null. The simple solution break it into two lines and check if it's null before calling l...
I have n number of one-dimensional arrays similar to: [0,0,0,0,0,1,1,1,0,0,1,1,...] 0's and 1's indicating occupation. And k number of smaller arrays similar to: [2,2,2], [2,2], [2], [2,2,2,2] with varying sizes. What I want to do is to see where and how I can fit the smaller (second) arrays to bigger arrays followi...
I've got my answer to this in the comment of the one I checked. Which Algorithm Approach Should I Take to Generate Lambda Expressions in Java? but I don't exactly know where to look in terms of generating lambda expressions with Parsing in Reverse. I'm not exactly allowed to use programs like ANTLR. The tutorials and ...
I have some information about a user I need to store and access in an ASP.NET MVC 5 application. Here are some of the things that I will need to store/access: Theme choice If they want to show panel bar navigation If they want to show menu bar navigation If they want to hide unauthorized links etc. I am trying to fig...
I am writing a program that controls some hardware via a serial port. The program will run various function based on user input. I need a way to queue these tasks and execute them synchronously on the same thread. I also need to be able to cancel them and track their status. So I was thinking I could use tasks and cha...
I've done a lot of research on this, but I'm still quite confused. I'm currently working on an Arduino-compatible software project. The project is open source, so I want others to make use of it as well, but I don't want them to create derivative works with closed-source licenses. I would like them to acknowledge any c...
Which of these is the ideal way to check if a value exists without caring exactly what its value is? if let _ = flags[.showField] { showField() } if flags[.showField] != nil { showField() } In the first case, it seems more Swift-y to use if let _ = and futureproofs it (I can imagine a future where Apple says you must...
I don't have much experience in caching among web applications, but I am trying to educate myself in the field and try out various techniques and approaches in ASP.NET MVC. The majority of tutorials and articles I see online are mentioning output cache ([OutputCache(VaryByParam="...")]), various donut caching methods e...
Today I had an interesting discussion with a colleague. I am a defensive programmer. I believe that the rule "a class must ensure that its objects have a valid state when interacted with from outside the class" must always be adhered to. The reason for this rule is that the class does not know who its users are and tha...
What is the historic reasoning behind having both prefix increment(++i) and postfix increment( i++) in the C language? (this question and this other stack overflow question aren't as complete as the answers here.) Two obvious ones always come up: One is often clearer than the other: For instance: i=0; while (i++ ...
I have been looking for a term to deal with a seemingly common pattern where a string consists of numbers separated by a . to n levels deep. A prime example is Semantic Versioning numbers which are comprised of three numbers wherein 1.0.0 > 0.1.0. A project I am working on uses this pattern for identifiers for an n-lev...
Basically: I am creating an enterprise web application. I would like to do extensive logging of both client and server activity, with all logs ultimately stored on the server. I have found many articles describing one specific strategy or tool for this, but nothing comparing the options. I know there is no single be...
I am self-learning Michael L. Scott's Programming Language Pragmatics. The following quote explains how deep binding and shallow binding are different in the presence of static scoping: program binding_example(input, output); procedure A(I : integer; procedure P); procedure B; begin writeln(I); e...
I am posting this here instead of on Stack Overflow because this is more conceptual. I am primarily thinking of this a Linux context, but this can be extended to other operating systems. When I didn't know what I know now about operating systems, I figured that iOS applications signature checked by other programs. I wa...
From https://en.wikipedia.org/wiki/Name_binding name binding is the association of entities (data and/or code) with identifiers.[1] An identifier bound to an object is said to reference that object. Binding is intimately connected with scoping, as scope determines which names bind to which objects – at which locations...
I'm working on a software using VB.Net which retrieves string packets through a TCP socket. The problem is it receives hundreds of packets per second. For each incoming packet the software should connect to the database (right now it's Access DB) and do one of the following: Query one row of the database and use some ...
As per the classical SDLC phases of planning, defining, designing, building, testing, deployment and maintenance what could be quite unique in the scenario of modern or contemporary apps. By modern apps i mean all modern apps that are being used on mobiles/smartphones and tablets and also those that are used in drones,...
My string is of type"abacsdsdvvsg" or"a a a a a a a" And I use String[] stringArray = s.split(""); or String[] stringArray = s.split(" "); I'm wondering what would be the complexity(in O(string length)) for above splitting? PS: I know how to calculate O(...) if code is given. Here I don't know the algorithm of split fu...
I'm really struggling to come up with a design pattern for an Alerter I'm building. Here's a contrived example of what I'm trying to do: A person wants to get an alert by weather type (rain, snow, sun, etc.). A person also has a choice of alert method (email, sms, slack channel, hipchat room, etc.) I need to: have a cl...
Situation We are currently developing a large web application (Web API 2) - several entities and thus require several endpoints for each. But suddenly, they changed to "one endpoint fits all" approach, something like: /api/data?entity=entity_name Then the usual controller for GET, POST, PUT, DELETE. We have something ...
I read some articles about developers who takes rabbitmq and produce from PHP messages to write to mysql. they do this to make the page speedup and not wait for mysql to return an answer. So in my case, since I want to write to mysql every page request in my site, and yet PHP does not have thread pooling, this I assum...
I'm just starting out using programming using the MVC design pattern, and I would like to know if I understood it correctly and where I should put certain things. So I understood that I should put all my files in one out of three folders, (or just separate the code): Model - Database models. Controllers - logic that de...
I have 500.000 files with the combined size of 350GB. So an average file has 0.7MB size. Each file has metadata: 1 to 100 keywords and optionally a short description. I need to filter the files and find the keywords of the search expression in the keywords of the files and in the descriptions. Note that some of the fil...
I have an array of elements, each with a start time and an end time. These form a timeline, some of which overlap, and others that do not (and have a gap between groups of overlapping elements). I written some code that removes the gaps between the non-overlapping elements (red lines as per the image below) however it ...
I am developing a REST API for a user management service (being used by other micro services). My model contains the types User and Server among others. Server to User relation is many-to-one (each user has a non-null foreign key to the server table).The Server type has a field named address. I have to implement a REST...
The terms debugging and antibugging seem to be widely used for referring to tools, measures and design patterns to get rid of bugs. After reading Peter Norvig's Paradigms of Artificial Intelligence Programming: Case Studies in Common LISP I was not sure about the difference between those terms: It is a good idea to in...
I have the following JavaScript code: function tokensOnSameLine(node1, node2) { return node1.line == node2.line; } What would the preferred name for this function be? I've considered the following: isTokensOnSameLine - sounds awkward but it matches the is convention for predicates. areTokensOnSameLine - sounds ...
In Java there are primitive types for byte, short, int and long and the same thing for float and double. Why is it necessary to have a person set how many bytes should be used for a primitive value? Couldn't the size just be determined dynamically depending on how big the number passed in was? There are 2 reasons I can...
May be it seems an open question (or non-constructive according to stackoverflow standards) .... but I am asking if there's something rigid according to Software process standards addressing this topic ? If there are one or more "Hard to find bugs" that need complex scenarios, extensive testing, very big or special dat...
I'm trying to read up on implementation details of Swift, and one thing I can't nail down are its "witness tables". It looks like they're a separate vtable pointer used for structs. But why would you need that? Structs are copied by value, so you already know at compile-time what type they are. So wouldn't you just har...
I came across the term identity mapping in some papers about neural networks but am not sure what it is supposed to mean in that context. I'm guessing it means to map a sort of input to an output? I came across this term in the papers Deep Residual Learning for Image Recognition (2015) and Identity Mappings in Deep Res...
Does this question still apply: Why are native ES6 promises slower and more memory-intensive than bluebird?? In regards to the latest versions of Node.js and EC7?
I'm going to write a simple password manager, which is going to store my accounts encrypted. Here is description of the classes , LoginManager - This class will be responsible for authenticating the user, since the data on the harddrive will be encrypted, it will succeed only if the data is succesfully decrypted, the f...
Lets say I want to setup a roles table that has a polymorphic relationship to resource. I understand that that I could directly setup a foreign key - by adding for example a roles.forum_id column. But why is (AFAIK) creating a compound foreign key where one column holds the key and another the table to reference not p...
I am working on a Java / Spring web application. The application issues licenses on demand. Each license has an expiry date. Licenses can be renewed by the admin. I want to send an email notification or perform some operation 90, 45, 30, x, y, z no. of days before the license expiry. The email notification to be sent e...
I have a global position keeper of screen items so items don't need store their own positions. class Screen_Position_Keeper: # functions to add stuff def get_px_row( self, item ): try: return self.item_to_row[ item ] except KeyError: raise KeyError( 'You never registere...
I'm reading the Design patterns book by the Gang of 4. Does a singleton use encapsulation? To me it would seem like yes, but i'm not 100% sure. Maybe I don't have a good understanding of encapsulation.
I have a file editor. It reads from a file, creates an object with the read data and can then write that data into a same (or another) file. Every time user opens a file a new tab is created and a private instance of the object is assigned to it, containing it in the tab. The object itself is complex and is composited...
I have a weird question for community. One well respected by management developer is strongly against putting data files for JUnit tests in the Maven project directory so that they are committed to the version control system (VCS). His reasons might be formulated as: Project managers do not have convenient access to V...
Again and again I find myself in situations where I want to do this: class Outer { private static final Runnable Inner = new Runnable() { private static final String CONSTANT1 = "foo"; private static final int CONSTANT2 = CONSTANT1.length(); //'static' gives error private static final ...
Is the #include order guaranteed by the standard to be the order of the -I options in the invocation: example: having the folders and files: A/foo.h B/foo.h can it be guaranteed that #include <foo.h> when cpp is invoqued with ... -I A -I B ... will choose A/foo.h ?
We're multiple users working on multiple apps using one same database. The database schema is used in production, preproduction and development environments. Right now, we're keeping it updated using migrations across all environments, but this leaves us with hundreds of migration files and it's incredibly messy. Is th...
I have a class which will have a huge number of properties (30 to 50). A huge numnber of these properties will be read only on the client. Is it a good practice to have one class with lots of properties or have smaller classes and use them as properties in parent class? Note that objects of this class will be sent to c...
We want to serve different applications on the same domain, based on path. For example mydomain.com Serves a WordPress website and mydomain.com/app serves a google app engine application. My natural choice was to point to mydomain.com at a cluster of NGINX machines, which are configured to proxy based on path. My quest...
I just came across this question telling how to store ListView Data(basically ListView.Items) into a text file but it got me thinking that, is it the best way to do it? In terms of efficiency, basically running available operations of the data efficiently, because storing large ListView Data might take time to access w...
I am highly confuse while calculating time complexity of Merge Sort Algorithm. Specifically on the Dividing Step. In the dividing step we have to calculate the mid point of "n" i.e. "q = n/2". How it will take constant time. If we assume that divide is an elementary operation and take very less time, then also we s...
Introduction Many of the mainline vector graphics rendering engines have an algorithmic flaw in them. They render each shape separately, and antialias by calculating pixel coverage and then compose them on top of each other. Yes it is simple but the correct solutions are even simpler. This leads to a conflation problem...
According to this article on Appropriate Uses For SQLite it says that, while SQLite is limited to 140 terabytes, a client/server RDBMS may work better: An SQLite database is limited in size to 140 terabytes (247 bytes, 128 tibibytes). And even if it could handle larger databases, SQLite stores the entire database in a...
I am currently implementing my own programming language. Until now I have written: An Error class for errors (to be thrown) encountered while processing the input source code; Some SyntaxError functions (each one with a different tag, passed with a template, like SyntaxError<malformed_number>() or SyntaxError<unexpect...
I'm implementing a state-pattern design in Java to calculate the current position of an object following a trapezoidal trajectory. The pattern consists of a Context, State and states classes. Currently, the variables (accel, max_vel and target) are passed as parameters to each state object upon instantiation - in effec...
I have created a standalone application with WPF and I need to use some of its functions via web. In few words, I would like that an user can access a web page and have the chance to insert some data and invoke some of the functions present in desktop application, which is running on a remote machine. My idea is to cr...
I'm writing a compiler that compiles to C, one thing I'm attempting to do is implement a construct like Rust's match: // { some function let mut foo = 32; match foo { 3 => return "hey", 4 | 5 | 6 => return "foo", 9 ... 12 => return "blah", _ => return "bar", } // } How would...
Under static scoping, by its definition, how can we determine the scope of a variable inside a recursive function? For example, in a pseudo-language, int i=1; function myfun(){ if (i > 4){ printf("%d\n", i); } else { ++i; myfun(); } } myfun(); i changes in each call to myfun According to static s...
In previous applications I've worked on, I've had a single factory class which built my object structure, and all dependencies were passed to each class through its constructor parameters. I'm now considering using a DIC framework such as Pimple, in which case it seems like you have a global dependency container which ...
I've been having some trouble coming up with a design that would alleviate most, if not all, the issues I've been running into, and I'm wondering if it is my base design. Our company accepts orders. We accept different types of orders based on the product line they belong to, but all orders share some functionality and...
I currently work inside a system that any new tools get created as an ASP.NET custom server-side control, rather than a Forms or MVC page. One of my most recent projects is to convert a Forms page into a control (basically moving from an old site to the current one), and as far as I can see, this requires very few cha...
In C, the assignment command also returns the value assigned, so it is also an expression. Similarly, initialization, which happens when defining a variable, also assigns a value to the newly created variable. In programming languages, does a command for initialization ever return a value, so it can be used as an expre...
So I have an unsorted data set with x and y float coordinates as keys. The data is in a txt file. It looks like this: x,y,data; x2,y2,data2; etc I need to retrieve all data in a specific rectangular area multiple times with different areas each time. What would be the fastest algorithm to do this. (I'm working in C#) M...
Is it possible to use static or dependent types to prove a function is idempotent? I've searched Google and various places on StackOverflow/StackExchange for the answer with no luck. The closest I've found was this conversation about Idris: https://groups.google.com/forum/#!topic/idris-lang/yp7vrspChRg Unfortunately, t...
Added Just found two related questions https://math.stackexchange.com/q/1759680/1281 https://stackoverflow.com/a/2582804/156458 In programming languages, from Michael Scott's Programming Language Pragmatics In general, a value in a programming language is said to have first-class status if it can be passed as a para...
I have an app with the following structure (simplified a bit here)... var RecorderApp = function(canvas) { this.state = undefined; this.states = { record: recordState, save: saveState }; this.init = function() { this.audEng = new AudioEngine(); this.waveDisp = new WaveformDisplay(canvas); this.mouse =...
I'm reading this article, Low Level Programming of the Raspberry Pi in C, which explains how to access the raspberry pi on a low level. It states that the virtual gpio address is 0x7E200000. Therefore a macro is defined like this #define BCM2708_PERI_BASE 0x20000000 #define GPIO_BASE (BCM2708_PERI_...
I'm working on simple 8086 simulator. But I'm not sure how to implement lock prefix. I know this prefix used in semaphore implementations. 1) For now I have only 8086 core and no other cores like FPU. Manual says lock prefix used in multiprocessor environment. So how treat lock prefix with 8086 alone. 2) How to treat ...
I'm working in a corporation that has two products. One is a desktop application the other is a web-application. I'm in on the part as backend-engineer on the web-application. I design the web-interfaces. We use SOAP as the interface technology. Now as the product develops there are lots of changes in the current not r...
Our build process changes the version number of all AssemlyInfo.cs files, so that the version number can be managed completely by the build server. Right now, we commit the changed AssemblyInfo.cs files after successful build. During evaluation of TeamCity, I couldn't find a way to do that without using svn via command...
For some reasons, I need a child-first ClassLoader. Such ClassLoader doesn't exist in the JDK, so I'm writing it. Since this is a key component of my use case, I'd like it to be heavily tested. To ensure it's not changed without breaking the behavior, I want to be extremely thorough and test all that's testable automat...
I am currently building an application that consists of multiple small rest services that communicate between them. For example, a request to service A might make requests to services B and C in the background. The question is, how can I mock the services B and C in order to test A (that includes checking if the reques...
I'm working on medium sized ASP.NET MVC 4 web app, that is about 2.5 years old. Around 25-30k lines of code. The project has never followed any of the good .NET design practices. It is a very tightly coupled solution. There are not interfaces at all. Do you think it is worth to upgrade the legacy/spaghetti code to foll...
I'm writing a Java client library for a simple API service and I was wondering how much should I be strict for invalid values. For example for an endpoint a parameter should not exceed a certain value. Should the client check this parameter and abort the request, execute it anyway or log it as a warning? If the API doe...
I work in a small programming team supporting a larger organisation. This year our manager has decided we are going to use Oracle Apex technologies to handle the vast majority of our company data. This would be ok, except we only have one Apex server. Our manager has decreed that everything happens in that one instance...
I am trying to decide the type of relationship (or association) there is between the following two classes: Class Stable { private const int MaxStableRooms; private Horses[] Horses; public Stable(int MaxStableRooms) { Horses = new Horse[MaxStableRooms]; for (int i = 0; i < horsecount; i++) Horses[i] = new Horse();...
First let me explain what is my understanding of the terms statically typed language and type safety: Statically typed language: a language that does not allow you to change the type of a variable at run-time. Type safety: type safety means that you are not allowed to mix incompatible data types. For example, you canno...
I believe, in Python defaultdict inherited from dict violates Liskov Substitution Principle. defaultdict doesn't raise KeyError while x in d is still False, for instance. Is that so? If it is, why developer decided to make such a sacrifice?
In the context of MVC sometimes I find myself creating a Factory and injecting the factory with Repository. While it is certainly possible to use Repository as layer inside the Factory, I wonder if it is an anti-pattern to do so. i.e. is it advisable to keep Factory Repository-free? Example For example, my QuoteFactor...
tl;dr-ers: How does a lexer normally deal with none-inline statements. statements that do not end with a specified statement delimiter. Such as control flow statements? I believe that I have a fairly good grasp on lexical analysis, and can move on in my quest for understanding lexers/parsers. I do however, understand ...
Lets say I have a function that takes an argument, does some action based on the value of that argument and returns false if there is no action for that value. (pseudo-code): bool executeSomeAction(someValue) { switch (someValue) { case shouldDoAction1: action1(); break; case shouldDoActi...
Should I use an easy readable code like this if (var.isServicePGM() || var.isStandardPGM()) { //Much code if (var.isServicePGM()) { //Some code } else if (var.isStandardPGM()) { //Some code } } or should i use an faster code like this if (var.isServicePGM() || var.isStandar...
Often I see the implementation of the builder pattern (in Java) to be like this: public class Foo { private Foo(FooBuilder builder) { // get alle the parameters from the builder and apply them to this instance } public static class FooBuilder { // ... public Foo build() { ...
You could setup special mouse events using Javascript that fires when the pointer is enter or hovering over a specific HTML element (i.e: object.addEventListener("mouseover", theScript); ). But how does it work? Is it like a classic collison detection? When the mouse pointer X and Y coordinates is inside the boundaries...
Rust needs external linkers (e.g. GCC) to generate final output. Why doesn't it provide a bundled one? Are there any languages that does the similar?
I'm testing on my laptop a C++ TCP proxy listening on a fixed port given to command line; the proxy works with the usual bind and listen and loops on incoming connections with accept, forking for each accepted connection. GET and CONNECT requests are managed. Now I'm planning to deliver the packets not as they come, bu...
I am developing a complex web application, which is working fine on Chrome and IE, but recently has developed huge performance issues on Firefox which lead us to block it's usage completely to avoid a poor UX while the problem isn't solved. Below is a screenshot of the Firefox profiler: The file is available here for ...
I'm considering different designs for a generic role library gem. The first is based off the Rolify gem but with a has_many through: relationship instead of HABTM. HABTM tables are "headless" in ActiveRecord and cannot be queried directly which is a huge con. class User < ApplicationRecord has_many :user_roles has...
For nested if constructs, some languages provide constructs similar to if Bexp1 then C1 elseif Bexp2 then C2 ... elseif Bexpn then Cn else Cn+1 endif All I have seen provide elseif. I wonder why not further provide thenif? Is there a need for thenif? Thanks.
I am trying to create a new variable with class Lamb (called hold) using a variable (main), which also has class Lamb. Lamb has two parameters (x and y). I create a variable called main with class Lamb where main.x is a list. I then create hold using main.x and main.y (see code snip 2 below). When I try to change h...
Suppose I have a conceptual Ledger that is populated with Line Items. Assume that Line Items themselves are stored in some type of persistent storage. The ledger is shown to the user who can add/remove Line Items, or update variables inside a particular Line Item, such as price/quantity/description. To handle this,...
Recently, I have been coding in Cordova a lot for the company I work for. For those of you who don't know, Cordova is a cross platform development tool for mobile applications which is web based. Essentially you can use your HTML/JS/CSS to make Android and iOS applications. However, I come from a heavy OOP background a...
Collections class in Java consists only from static methods, as stated in the specs This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, ...
What is the best method to parse events in daily batches from external source (csv file) that produces entries in a separate table if any of a multiple of conditions are met. Conditions can vary through time and need to maintain certain level of flexibility. They are simple conditions though, either a field is equal, s...
Recently, I've been getting familiar with COCOMO II model to calculate the effort (person-months) and duration (calendar time in months) required to develop a mobile application. To calculate the effort, the following formula should be used according to COCOMO II Model Definition Manual. PM = A * Size^E * (Product of ...