instruction
stringlengths
34
36.1k
i have following code: for ( int i = 1; i < n; i ++) for ( int j = 0; j < n*n; j ++) if (j % i == 0) for (int k = 0; k < j; k++) sum++; How would if (j % i == 0) affect the overall complexity? As k goes up to j, which is n*n, the third loop should also be of complexity n*n= O(n^...
PHP variables are dynamic in type so I can do: $x = 'hello world!'; $x = strlen($x); Sometimes this is trivial and I could save many lines of code, but it reduces clarity. I'm using a text editor, but I guess IDEs (and programmers) could be confused if a variable change type. Less trivial case: if (is_string($da...
In order to increase the parallel-ability of my objects, I try to make them read-only and include only data that naturally belong to the entity. I have class Object { ... }; class Processor { void foo(const Object& o) { ... } } The benefit of this model is I need only one Processor instance for any number of Objec...
In my Android app I have: A SQLiteHelper class that extends SQLIteOpenHelper, and takes care of things like table-creation and upgrades. A SQLiteDatasource class that performs CRUD operations on the SQLiteHelper object. However my SQLiteDatasource class is getting very bloated because it have so many methods. Lots of...
Background: Currently in the process of building out a REST API, using node w/express and it is consumed by a mobile app and eventually a (modern browser based) website. I'm trying to identify the best way to authorize a user's update/action request so they are only allowed to modify their own resources. The actions wi...
I would like to have a caching solution for a variety of function calls. All of the function calls fit the following signature public ResponseType ProcessRequest(RequestType request); About half the time the cache key can be applied very simply, in a generic manner by pulling a key from the serialized string. The ot...
Is it fair to say that it is good practice to default everything to private up front when coding something? And then only upgrade it to protected if a subclass needs it, or public if another class needs it?
Suppose I work at Microsoft. I would probably write the bulk of my code using Visual Studio, which is one of Microsoft's most popular projects. Therefore, dogfooding. Now suppose I work at Netflix, which provides a video streaming service for entertainment value. I'm not going to watch House of Cards on the job (win...
It seems like any Bounded instance should have a sane implementation of Enum. I cannot personally think of a counterexample, although if someone comes up with one that isn't pathological then I will understand why this isn't the case. From doing :i on the two typeclasses it seems like the only exception currently in th...
Should the author of a changeset be required to obtain sign off from all reviewers who have reviewed the code or should code be allowed to check in as long as there is one sign off? I think giving veto power to reviewers does more harm than good as then they use it to blackmail (asking for unnecessary changes) and bloc...
I have the following class and a method named ValidateEverything(), where IsEverythingValid becomes true only when a or b or both of them are true. I was wondering about what would be the best way to break the foreach loop. Also, what would the best approach to update IsEverythingValid variable. Assume that first three...
In a multipurpose website (user system, lots of database operations on different tables, schedule creators, …) should all PHP request be centralized to one app? For example, my current set up is like this: User related requests go to users.php Managing a specific MySQL table goes to ../tables/thatTableName.php Managin...
In this documentation it is mentioned A commit object may have any number of parents. But from my understanding, the only case where a commit will have more than 1 parent is when a merge has happened, and in that case there will only be two parents. So my question is, can a commit have more than 2 parents? If so, wh...
I want to apply the k-means algorithm on an RGB image data-set. I don't know how to proceed. You can mention basic step by step flow to proceed. I do know basics of Image Processing & OpenCV.
Currently I'm working on a big website that will be published on almost 40 domains with different languages. My question is what would be the best way of doing localization/internationalization. I'm interested in programming technique. What have I found so far is : Store literals in Resource files Store literals Data...
I am rearchitecturing and rewriting my monolithic BaaS solution into microservices regarding to scalability and single responsibility rules. Due to the internal dependencies, services are placed on different logical tiers. See figure below; Instead of directly accessing to database or key-value storage, each service i...
How does a program composed of several languages work? How do the languages work together or interact with each other? How do they understand stand each other? How do you know when to use any given language and how do you implement them so they work together? (Not in terms of strengths and weaknesses but in terms of ta...
How do people make libraries cross-platform (UNIX-systems and Android, sometimes even iOS)? What do they use? I'm asking this because I make libraries as a hobby and I'm curious.
I'll will make ERP software for managing data for business activities. The solution must have two big parts: a WPF application for all the clients and an ASP MVC Web API application for all the client. The API application manage all the public data that is equal for all the clients and store it into a SQL server databa...
Given that CDNs are a Good Thing because they can serve resources closer to the client, the client can cache them, and you can reduce load on your own server. In recent browsers, loading resources from third-party servers does not decrease security thanks to Subresource Integrity (SRI). CDNs may be down or blocked in ...
I have a Position class with int x and int y fields. I have a bunch of points and some of them need to know the distance to all other points. Does it make sense to store it in Map<Position, float> distances (this is another field in the Position class)? Other points don't need that information, so their distances field...
Thought experiment. Tom is a software developer. He releases his relatively simple software under GPL. Jerry forks his source code and creates a world savior software with months or years of hard work. The software works and is great, and it can save millions from the Something Evil. Then, before he releases it, someth...
I have a bunch of REST webservices that my client uses. For instance, to create a user, I have POST /users and to modify it POST /users/{id} The problem is, some fields, as marketArea, are allowed to be edited only by employees, that will have an EMPLOYEE role. Other fields, as name and age, are editable by end users...
I posted a question on github to the EF Team. I got a reply saying it would be better to ask this question here so I will copy and paste it here as we as a link so other can see the few replies on GitHub. Question: I was doing some research and someone pointed out that Line 24 of the DBContext Class states DbContext i...
This is what I need to do, in a nutshell: Generate Excel spreadsheet files (programmatically). Store these .xlsx files in a location where they can be accessed by users later. These files need to be "on the Internet/in the cloud", since most legitimate downloaders are not internal users and thus are not on our compan...
For example, imagine a website which stores results about a certain sport or game, which has a typical "season" structure, such that there's both a Player and a Season class. To retrieve a player's average score during a specific season, should this be done with $player->averageScore($season), or should it be done with...
This question has kind of been asked before here Why are structs and classes separate concepts in C#? but I'm interested in a specific aspect of this that wasn't really answered. I'm trying to understand why the language designers for C# and Swift (and possibly others) opted for a language design that promotes implicit...
While watching a youtube video on Value Types in Swift, I was surprised by a simple example (around the 3:00 minute mark) that was given to demonstrate the pitfalls of reference types. Example code: let home = House() let temp = Temperature() temp.fahrenheit = 75 home.thermostat.temperature = temp.copy() temp.fahrenhe...
I have a home project, which is not open-source. To save time I'd like to use that source code for company project. How can I protect myself against the claim that I stole company source code? It is unlikely I will get permission to use my source code beforehand, but there's also no restriction on using open-source sof...
I want a server to be a producer of tasks for the client to process and be sent back. What is the proper HTTP method in RESTful approach to create and return a new resource? This seems silly, but the natural way seems to be GET /task/, or more verbosely GET /new_task/. A task is being created and returned. But this doe...
In file1.js I read: // NOTE: initialize your app event handlers here, see file2.js for a simple event handler example // TODO: configure following to work with both touch and click events (mouse + touch) // see http://msopentech.com/blog/2013/09/16/add-pinch-pointer-events-apache-cordova-phonegap-app/ //...overly sim...
So I've been doing a lot of research into game engines, and Entity Component System (ECS) seems to be the most flexible and extendable design to use. Just to summarize, in ECS the basic idea is that you have Entities which are just containers for Components, and different Components correspond to different functionali...
What is a Relocatable Binary? I tried doing some search on Google, but I am still confused. Also: what is the difference between an Executable and a Relocatable Binary?
I have an application (full-stack) that is used millions of times concurrently. Some vital application properties are managed on the client side (at the time it seemed to be the simplest approach to me), but of course this has security issues, so I have to manage all properties on the server side. I was thinking on ad...
Can we say that MVC is subsystem (or subset, sub-architecture) of client-server architecture?
I am trying to explore and understand RESTful approach to things. I've read that the interface be should not be contractual. That is what I get from HATEOAS. But surely there must exist some contracts between a client and a server in the communication. So a server returns a resource and possible actions defined for it ...
I have a larger directory structure (dir + sub directories) with files. It contains files of certain types. For one particular type (let's say with appendix .foo) I need to figure out if files have been added, changed or deleted. The first approach was to iterate over all files and check the timestamp of the files. It ...
In an application I'm developing we have integrated with a third party api. One of the use cases consists of a user of our system filling out a form and submitting it. This results in us mapping the form to an api request model and posting it to the third party api. This starts an external process, the details of which...
I want to learn how to write testcases for a piece of logic like unit tests. Now I am not concerned about any specific framework or language, just wanted to know how can I get learn to write input-output pairs that cover all of the possible input domain? Hey can you people suggest me some strategies more like andres su...
There has been a discussion recently (with my colleagues) on whether or not checks should be performed on client machines to check for specific software, within a web based platform, mainly because we have some requirements for certain user actions and to help diagnose certain issues we could log whether or not they ac...
Say you finished a sprint, successfully deployed your application to the production environment and started another 2-week-long sprint. But then you find a critical bug in the version you just shipped, so critical that there's no way you can wait until the end of the sprint to deploy the fix. What are the guidelines fo...
Coming over from the Java world, I am having trouble translating a multi-threaded approach to IO to the ES6 Promises concept of aysnc IO. Many of the examples I have seen on promises show a linear flow. promiseFunction .then(functionThatReturnsAnotherPromise) .then(functionThatReturnsYetAnotherPromise) ... ...
Philosophical Question: An issue that occurred to me is that especially when using frameworks like Spring or Hibernate ( which are everywhere in industry), we have annotate everything. This is better obviously then the declarative XML statements... but it also means that we are engaging in declarative programming sinc...
I've been reading a few different guides and tutorials, as I am interested in learning some best practices of programming. I was reading the How to be a Programmer guide, and there is a section about memory management, from which I have taken this piece of text: But even with garbage collection, you can fill up all me...
Is it a good practice to have a setter method of this kind? With primitive types, it's obviously fine, but when you have a setter for a field which holds a reference to mutable object, this might go wrong - the caller could modify the object after passing it to setField method. class Myclass{ private MyOtherClass f...
I've written a fair bit of Win32 desktop apps as hobby projects throughout my career but I've never used resources of the type string table in any of them; usually I either hard-code strings or build them through environment variables to determine paths and drive letters etc. In what situations might I want to use a st...
I will be working on a system which will be ported over from Java to .Net. It is a pretty big system. I don't have any specifics about how the system is designed, no documentation, nothing. You know as much about it as I do at this point. Apparently no one else does either, so I have been tasked to figure it out and th...
I'm trying to understand compilation and interpretation, step by step figuring out a total image. So I came up to a question while reading http://www.cs.man.ac.uk/~pjj/farrell/comp3.html this article It says : The next stage of the compiler is called the Parser. This part of the compiler has an understanding of the l...
I've been reading about MVP, specifically Supervising Controller. One thing I'm having difficulty wrapping my head around is how the View interacts with the Model. It was my understanding that the Presenter should update the Model and that the View reads from the Model. The Presenter can also update the view through a...
I have a front/back applications that needs to be logged in to be used. When I log in (by means of the front-end app sending a request to the back end), what I do is not sending a cookie, but a JSON with a token in it. The latter will be stored by the front end app in a sessionstorage and each time it will interact wit...
Java Pattern provides flags that enables you match regex control characters. Passing Pattern.LITERAL or 16 as second argument will match any Unicode char, but not if you use a word bound with the Unicode regex. Pattern p = Pattern.compile("$", Pattern.LITERAL); //I could also escape \\$ Matcher m = p.matcher("$ $ $ $$"...
Suppose I use a open source framework in my project and I would not contribute (submit changes) to that framework, and the current version is stable, should we keep the framework unchanged when possible? for example, if I found a function in a class of framework does not fulfill my requirements: public class Fruit{ ...
Suppose you write a subclass that extends to a certain class and in that subclass, you use the super() method for your constructor. Would you write "super(parameter: type): return type" in the UML?
Is it possible to have private objects? For example, when you instantiate an object (classType object1 = new classType()), can that be private or protected or is it always public?
In the below program, I'm calling method1() of SampleClass from two threads. So, basically I have created two objects for each thread and called the method1(). I have also seen the scenario of calling static method from two different threads. Now I want to know what will happen If I use only one object for two threads...
I know this topic has been discussed a lot already so I don't want to get into which one is the "best way". I have been using field injection for a couple of years now but recently I discovered that many people prefer constructor injection because the collaborators of a class have to be explicitly set before you can cr...
Can you explain this method call syntax to me? this.mainParticleSystem.Simulate(time, withChildren: false, restart: true); Particularly I don't understand what withChildren: false parameters syntax means. Is it some kind of default value or something?
class A { B bObject; } class B { private List<SomeType> list; public List getList() {return list;} public void foo(int i) { list.get(i).someTypeMethod(); // 2 dots } } class SomeType { public void someTypeMethod() {} } Suppose I want to call get on the list from bObject in class A. ...
I am doing a webapp for the internals in my company, it has been 8 months and now I want to become more professional about it, and to know precisely what I am doing. My workflow is to make little changes, upload it on a side-site that I use for testing/developing process, and see what happens, until a line where "I am ...
I would like to work on a project where I can authenticate or validate a user without the typical user/password combination to authenticate a user in my system. In other words, I would have a API and a frontend web/mobile app, but I need the user to validate in order to use the app. I was thinking of using some valida...
At the new client, we had a discussion regarding access modifiers for classes, methods, members etc. One opinion was to keep things as private as possible, only allowing for protected (internal, public) level when necessary. The opposite opinion was to "let things flow" and apply public access level throughout all (or ...
Most hash table implementations guarantee O(1) average case but O(n) maximum case for lookup (where 'n' is the number of keys in the table). But Cuckoo Hashing is described as O(1) maximum. Apparently it achieves this by using two hash functions, and if it gets a collision with one, it uses the alternative one. If i...
I'm a student of systems engineering, and all my teachers and friends (that actually work in the area) say that it is better to have as much logic as possible implemented in the database (queries, views, triggers, T-SQL, etc.). I think that it's better to have it in the code. Their reasons are: If they need to change ...
I am looking for any info. (I know some C++ with win32 and C#) The Idea: The idea is to help a program with missing files load. In the end I wanted to see if I could have my program launch a simple c++ executable that requires a dll which prints "hello world" to standard output. The quirk would be that the dll is not p...
I am working in some open source project in PHP. My question is, should I make it using some kind of framework, say Laravel, or in plain PHP, in a hope for a large no of programmers using it? Btw, eventually, I do need to setup the routing, filtering, views for my app.
I took this screen shot while watching a BBC documentary. The scene showed a scientist keying into a computer. The language isn't something I've seen before. Does anybody know what it's?
I was reading an 'User End License Agreement' and asked myself whether such paragraphs aren't suspect. As well my I asked myself whether such sentences are normal in those end license agreements or are verbalized in other form. You agree to create, retain and provide to Axosoft and its auditors accurate written record...
Disclaimer: This is my first time: using node, creating a REST API, and trying out MVC server side. (so, just statistically speaking, I'm probably doing something wrong ¯\_(ツ)_/¯) I'm working on creating a video sharing platform for use at my university. It's going to be a single page application with client side rout...
in our app we have a Json file that contains several properties used for menu configuration. One of the keys should tell us if a menu item should be displayed. The thing is that the value for this key, can be an int but written as String "0" or "1", a Boolean written as String "true", "false", or an URL. So depending o...
I've made a data structure that has insert, search, and delete functions that are base on the number of characters in the key. As an example if it's a number based key (base10), then the complexity for the given functions is at worst equal to the number of digits in the key. If was the case how would I express that? I ...
It is rumoured that early C++ implementations have had dot operator for namespace access. There is an opinion that the dot is more convenient that the modern double colon operator. What was the reasoning behind introducing the double colon?
Why does :nth-child() iterate from one instead of zero? As shown in this example. Why does it select the first element and not the second when p :nth-child(1)
I'm trying to find an efficient way to represent a grid in any number of dimensions. I would want to be able to specify a set of coordinates and then get the value stored in the location on the grid. I would also like to simply move any number of squares in any dimension easily. How could I create a data structure like...
Scenario We have a class Vehicle, this class contains some properties to define the object such as a CarBrand, TransmissionType, Color, etc.. A car (vehicle) also has options, these days a lot of options. My idea is to create a separate class called Options and list the needed options that I require as a Boolean value,...
I am dealing with an arbitrarily large numbers, which is beyond the capacity of modern computer(I am talking about larger than 64 bits number here). How I'll represent them in my program while I will do operations on them?
I see in a lot of legacy software and bad tutorials on the Internet that recommend using exit(-1), return -1 or similar to represent "abnormal termination". The problem is, in POSIX at least, -1 has never been and is not a valid status code. man 3 exit illustrates that exit() returns the value of status & 0377 to the p...
I'm improving a WordPress theme with PHP. The theme contains a gallery section which loads data from the Flickr API. Now the client wants to display Flickr galleries as well as "local" galleries without disclosing where a particular gallery is loaded from. On page load the theme does a Flickr API request loading 6 gall...
This implementation of Murmur hash yields different results when called twice in a row: Murmur3 m3 = new Murmur3(); var la = m3.ComputeHash(new byte[] { 1, 2 }); var lb = m3.ComputeHash(new byte[] { 1, 2 }); //la and lb now have different bytes Nowhere in Murmur description on wikipedia it is mentioned, that the hash ...
I was reading through the Hacklang docs on Collections, and came across this curious definition [paraphrased slightly]: interface KeyedIterable<Tk, Tv> ... interface ConstVector<+Tv> implements KeyedIterable<int, Tv> ... Of course, KeyedIterable must be read-only with respect to Tv, and indeed it is since its methods...
Note: I spent some time thinking about this question before choosing which StackExchance site to post it on. I have decided on this domain because of the description: "For professional programmers interested in conceptual questions about software development". I am not looking for an implementation, I am only looking ...
A major application we use has a bug that the vendor is calling (a swear word in our business) "working as designed". As a programmer / system analyst this is a bug - and against all I have been taught about systems / database programming / multi-user applications etc. should act when erroneous data is removed / marked...
I've been wondering why XML has an L in its name. By itself, XML doesn't "do" anything. It's just a data storage format, not a language! Languages "do" things. The way you get XML to "do" stuff, to turn it into a language proper, is to add xmlns attributes to its root element. Only then does it tell its environment wha...
I am converting an old Subversion repository to Git. Here is an example: $ svn info http://alfa.com/bravo/charlie Path: charlie URL: http://alfa.com/bravo/charlie Relative URL: ^/charlie Repository Root: http://alfa.com/bravo Repository UUID: 01234567-89ab-cdef-0123-456789abcdef Does Git have some equivalent to Reposi...
I want to write a kind of "diagnostic function" which is able to detect when a TCP/IP based network is interrupted. I would like to connect two endpoints and detect when an established connection between them two is dropped. The network connection can be wired or wireless. The check should be independent of operating s...
If I have a Pair class like this: class Pair<K, L>{ public final K a; public final L b; public Pair(K obj1, L obj2){this.a = obj1; this.b = obj2;} //... } I want to associate a Float with every pair of objects. They happen to be of the same type, so the Pair object will be Pair<SomeType, SomeType>. It's ...
The Burrows-Wheeler-Transform takes a string with length n, creates a matrix with n rows by shifting this string one position to the left for each row. Then the rows are sorted by the first column in lexicographical order. Then the last column will be submitted. Why taking the last column? On Wikipedia there is an exam...
I have an idea for a client-server software project which involves using information from Wikipedia, but I am not sure about what the conditions for using it in regards of licensing and copyrights would be in my case. My planned architecture: On the server side there is a script which fetches articles from a wikipedia ...
For a specific device there exists a Linux kernel module. This module only initialized the device and provides control mechanisms to user land via ioctls and mmap. To use this the device properly one must use the proprietary library from the hardware vendor. So the source code of the kernel module is available and lic...
Note: There are many questions answers related to the licensing. But I think my requirement is specific, so asking a separate question. We are considering to fork a GPL 2 project and use it for commercial purposes. This project has not been updated in past 2 years, but it's a great solution for our requirement. Ofcours...
The "D" in SOLID stands for dependency inversion. If I have for example, a Blacksmith class that depends on Hammer, I should create my Hammer externally and pass it to Blacksmith, rather than having Blacksmith create her own Hammer. This makes it easy for me to give my Blacksmith a DeluxeMagicHammer instead without h...
In the first cracking the coding interview video Ms. McDowell talks about candidates that begin by writing test cases in whiteboard interviews. How would one go about this? For example, the derivative problem in the video (the candidate is asked to write a function to take derivatives of a list of "Term" structs, whi...
Having Circle extend Ellipse breaks the Liskov Substition Principle, because it modifies a postcondition: namely, you can set X and Y independently to draw an ellipse, but X must always equal Y for circles. But isn't the problem here caused by having Circle be the subtype of an Ellipse? Couldn't we reverse the relation...
I have just noticed that I am coding stuff like this: <input type="text" ng-model="userName" id="userName" name="userName" /> And it occurs to me that I have access to the data though ng-data. I will never use getElementById() or getElementsByName(). Are theid= and name=just cluttering my HTML, or might I ever need th...
I am a beginner in C coding. I'm writing a C code where a variable is required to be used by different functions. I want to ask whether to use a global variable and manipulate it through functions or declare it as local variable and pass from function to function as argument. My understanding is that if I declare it as...
I have a set of numbers S and I want to find the largest subset S' such that for any two elements x,y in S' property(x, y) == True in_relation(x,y) == True. How could I find it? Bruteforcing is an option, ok. But I'd like to find something more efficient.
I work on a large software product which, being over 20 years old, has a number of constructs which have been superseded by language updates. One of these is a home-rolled smart pointer template class which acts similarly to - but is not quite indentical to - std::unique_ptr. The class has its destructor specialised fo...
I don't know much about how Google Chrome or SQLite works, but I know that Chrome makes heavy use of threads (I think a thread per tab). Additionally, I know that SQLite suggests to use a client-server database if parallel access is required. I'm not sure, but I assume Chrome uses SQLite like Firefox does, to save coo...
I am not very good at writing unit tests so I have a dilemma. I have a binary_search_tree and I am writing tests for insert and contains methods: struct BinarySearchTree {}; TEST(BinarySearchTree, Insert) { BinarySearchTree t; t.insert(5); EXPECT_TRUE(t.contains(5)); } TEST(BinarySearchTree, Contains) { ...
I'm building a new application in JSE for which I want to support internationalization. I've never built such an application. I'm looking for the best practices for internationalization. The application will be writing the translated data in files or a database. I've searched for best practices but I didn't find anyth...
I have recently been tasked with a project to create an API that handles a form post using PHP. I have never done something like this before and this will be handling payments so I would like to do it as best I can. Basically the objective of the project as a whole is to incorporate multiple payment API's into one sing...