instruction
stringlengths
71
71.9k
Given a nested list of strings (which may contain other nested lists), print the contents of the list and the corresponding depth. Here is my solution: private static void dumpList(String string, List l) { int n = l.size(); for (int i = 0; i < n; i++) { if(l.get(i) instanceof String){ Syst...
I am still new to Scala and wrote a small snippet to find all the combinations with replacement of a sequence (e.g. cwr(ab, 3) should give aaa, aab, abb, bbb). The slow way would be to generate all permutations, sort them, and throw out duplicates. I'd like to know if this code is idiomatic Scala style, and if I'm mak...
I am looking for best practice help. Slow loops seem to be a recurring problem for me and I'd like to learn a better way. The code itself works as it should, except it is far too slow. The problem is the worksheet needs to calculate after each B & i value is dropped into "N13" so that "U12", "V12", and "W12" update b...
I'm working on a project where a spinlock is more appropriate than a mutex, and after few tries I came up with: type SpinLock uint32 func (sl *SpinLock) Lock() { for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) { runtime.Gosched() //without this it locks up on GOMAXPROCS > 1 } } func (sl *SpinLoc...
I am building a classifieds website here in Portugal, and I'm now in the security phase. So until now, I already made what I think is a good measure against SQL injection: $firstname = chunk_split(mysql_real_escape_string($_POST[firstname]),1,'.'); $lastname = chunk_split(mysql_real_escape_string($_POST[lastname]),1,'....
I'm trying to become more familiar with C (been working through the MIT Practical Programming in C course and K&R) so decided to write a simple command-line linear interpolator. You can feed it a vector (where missing values are represented by 0n) and it should print an interpolated vector. Any comments on style etc ar...
Given the binary Tree and the two nodes say ‘a’ and ‘b’, determine whether the two nodes are cousins of each other or not. Two nodes are cousins of each other if they are at same level and have different parents. Looking for code review, optimizations and best practices. public final class CheckCousins { private ...
I decided to strengthen my "vanilla JavaScript" skills since I've lately been getting more into jQuery and just discovered the potential of node.js. As a result, I decided to make a basic alarm clock in javascript and html. (Plus I needed an alarm clock). Here's the Fiddle // Load an alarm sound var sound = new Aud...
I have around ~2M of files in one folder, which I need to manage. So, I want to separate them in groups by their filetypes. Example: filenames 1.A, 2.A, 3.A, 2.B, 3.B, 4.B, 5.C, 6.C My code: import os all_files = os.listdir(".") filetypes = list(set([i.split(".")[-1] for i in all_files])) for i in filetypes: os.sy...
My requirement is to add two binary numbers, say "1001" and "0101" as binary1 and binary2. Partial Class Default2 Inherits System.Web.UI.Page Dim carry As Boolean = False ' Boolean variable to hold the carry if occured Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Clic...
As an exercise in using C++11 features I decided to make a thread pool class. I would like to have a review on the code with focus on: Standards compliance / Portability issues / Best practices Thread Safety / Exception handling API Performance issues (Yes I know std::mutex is slow on windows, but besides that :) Any ...
The following function works well to print out a help message for the program I have written. It prints a multi-line string message that describes the command line usage with some examples: def usage(): print( """ Usage examples: Test deployment: $ fab [noinput] test deploy Staging deployment: ...
I'm currently developping an MVC framework on which I will be writing my websites. This is done through the usage of a starter kit. In standard MVC, your routes are registered like the following: /// <summary> /// Registers the routes. /// </summary> /// <param name="routes">The <see cref="RouteCollection" /> to w...
Given a string (for example: "a?bc?def?g"), write a program to generate all the possible strings by replacing ? with 0 and 1. Example: Input : a?b?c? Output: a0b0c0, a0b0c1, a0b1c0, a0b1c1, a1b0c0, a1b0c1, a1b1c0, a1b1c1. I have developed a program as shown below but please advise if something more efficiently...
This is my working solution for the following problem: given an array of integers of size n, print all possible combinations of size r. Before I proceed to the solution, I have the following question: combination means that the order does not matter, right? I.e. printing {1, 2} is the same as {2, 1}, so I want to avoid...
The problem asks you to take an integer (debit amount) and a double (credit or initial balance amount) and process the requested debit verifying that 1 it's a multiple of the minimum denomimation amount of $5 and that it's also smaller than the credit/balance. If either is untrue, it is supposed to return the initial ...
I want to apply a different badge color with bootstrap depending on a number. I wrote a filter to accomplish this... angular.module('Demo') .filter('reserveStatus', function() { return function(num) { var klass = ""; num = parseInt(num, 10); if (num > 2 && num < 5) { ...
I use terminal alot, so it was frustrating to me to deal with gedit's inconsistent behavior between having a window open and when one was not. I ended up searching around, and finding a way of getting around this. I've created this bash script, and aliased it to gedit, and I've slowly been expanding it. Basically the s...
Is there a cleaner way to do this? try { $ffprobe = FFProbe::create(); $streams = $ffprobe->streams($infile); $videoStreams = $streams->videos(); $audioStreams = $streams->audios(); if (!$videoStreams) { throw new Exception("Could not find a video strea...
How can I improve the performance of the code below? package utils.session; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * <p> * A very simple LRU cache implementation, used for our server side session * management. * </p> * * @author royguo@abcdefg.com */ public cl...
I have tried like this to check a substring in a mainstring in 8086. Is there any shorter way of doing this? My implementation seems lengthy. DATA SEGMENT STR1 DB 'MADAM' LEN1 DW ($-STR1); storing the length of STR1 STR2 DB 'MADAA' LEN2 DW ($-STR2); stroing the length of STR2 DATA ENDS CODE SEGMENT LEA ...
I don't really have a problem, but my code bothers me, because I know it could be done in a much better way. I have an enum of 4 directions: north west, north east, south east and south west. And I have a method that converts a vector to one of those directions. The method prefers North and East, so values of 0 would r...
I use EHCache to maintain a mostly read-only cache of results from database queries. It works perfectly for over a dozen queries. However, there is one table which needs an odd access method that is causing me grief. I hope someone with a knowledgeable eye could see what I am doing wrong, if anything. Note that these c...
I have an implementation of an Euler method for solving N-many 1st order coupled differential equations, but I feel that I did not write it as efficiently as I could, due to lack of programming experience. Here is the implementation: def eulerMethod(f, init0, h, om, mesh): """ f - array of ODES i...
The netlink service is used, among other things, to notify userspace about hotplug events (e.g. "a device has been connected"). These events come in the form of packets, which follow the following format, explained here: The netlink packet contains a set of null terminated text lines. The first line of the netlink p...
I'm very new to Go, and am trying to get some experience by re-writing some of my Python code in Go. Below is a function that takes an IP address (ipv4) in integer form and returns the string version. From 572779703 to 34.35.236.183 for example. func int2ip(num int) (string) { result := [4]int{} for i, n := ...
I'm trying to get more familiar with the new Java 8 features, so I am rewriting one of my earlier projects. It includes a class that keeps track of the best entry seen so far: import java.util.List; public class Maxinator<T> { private final QualityFunction<T> qualityFunction; private T best; private doubl...
There's a div in my webpage which will load data from an SQL server when the user clicks the button loadresource. Here's the JavaScript for button click: $("#ButtonLR").click(function () { //stopwatch var start = window.performance.now(); $("#getData").empty(); $("#stateB").empty(); // display load...
I am trying to solve the common "print a character after every item in a list, except the last one" problem. I do not want to use list indexes. There are a couple of simple ways to do this in Python, but I am not sure how to apply them to my code. Is there a more readable/couple liner way to do this? def echo(*args): ...
I think it could have been designed with more object orientation. I don't like how one of my methods calls another from within the method, but I wasn't sure how to return the result because it is a loop. Also is it ok to have all methods static, or should I be instantiating the classes? If there is any other improvemen...
I have developed my custom solution for this. It happened that the first solution is using XPath queries and the second, a conceptually similar to the first one, is using CSS queries processed by sizzle.js Here is the sample code for the second solution: using System; using System.Collections.Generic; using System.Refl...
I've been working with Lua for a little bit, and I have finally come up with some code that can be extended to create the core of a game model. I come from an object oriented background, so working with Lua is very different for me. The purpose of this code would be to create the game model for a game with Lua. Ano...
Is this the optimal method to check for collisions in a 2d-based game? I put together a working demo of 2D collisions here (WSAD to move, orange blocks collide). I currently use the following code to check for collisions: function checkmove(x, y) { if(level[Math.floor(x/20)][Math.floor(y/20)] == 1 || level[Math.ceil...
@nhgrif and I were curious about a couple different ways to aggregate a number of records based on a duplicate/common datum. Two different ideas will be shown. Any advice on all code but especially making it perform better is appreciated. Note: @nhgrif did not write most of this, so if it's wrong it's my fault... Make...
I created a procedural implementation of the nested set model in JavaScript. The use case for this small library was that the front-end(presented as an MVC) needs to traverse hierarchical data from back-ends. The library that I created satisfies the following: DSL-like architecture, with clear distinction between a t...
I have col D (in sheet1 called Students), col A (in Sheet2 called Students too) and col B (in sheet2 called Age). In colD there are a lot of similar Students names that are sorted from A to Z. I have this code that finds matched students name and put his age in col D (sheet1): Set rngSearch = Sheets("Sheet1").Range("D...
I want to return a set of items with an attached score to the user so that the user can easily iterate from highest to lowest and get the n-th highest items. Problems The JavaDoc of SortedSet.first() says "Returns the first (lowest) element currently in this set.". However in this case it is actually the highest score...
I have a detail view for my object. There is only one field available for editing. When I click on the Edit button I want to hide text for field and show input with the OK and Cancel button. // create kendo buttons $('#editGrnz').kendoButton({ icon: "k-icon k-i-pencil", }); $('.rt-field-cancel-button').kendoButto...
While learning object oriented design I'm judging my own design critically. This framework should be able to print objects in either XML, or JSON, I've stubbed in a basic implementation to avoid getting into details of XML and JSON parser APIs for now. So I made the Formatter be the base class. But with my current des...
I'm trying to refactor some code for fitting parametric models that are defined symbolically using Theano. My goal is for all models to expose a common interface so that, as far as possible, they can be drop-in replacements for one another. To that end I've tried to encapsulate each model within a separate class. A key...
I have two 2D arrays of doubles a and b. Both have two rows and different numbers of columns. a [[ 1,2,3][4,5,6]] The list b represents a number of bins of numbers and the list is a list of numbers I'm trying to sort into these bins. I need to go through each of the numbers in b to look for its corresponding bin. H...
I've been working on our application (CQRS and DDD) for awhile now. The application architecture is well layered and thought through. However we are having difficulties in decide where to put the below code, in such a way that it makes sense from an architectural point of view. What the code does: It's a generic method...
This is my code for 503 page: header.php if(getOption('maintence_mode')==1) { header("location:503.php"); exit; } 503.php <?php $protocol = "HTTP/1.0"; if ( "HTTP/1.1" == $_SERVER["SERVER_PROTOCOL"] ) $protocol = "HTTP/1.1"; header( "$protocol 503 Service Unavailable", true, 503 ); header( "Retry-After: 3600" ); ?>...
I have a conditional active record query that checks to see if a relationship of type X exists (.count > 0) where attribute x and attribute y match specific input or if they match when attribute x and attribute y are switched. I currently use an || operator with two long active record queries to cover both situations. ...
I'm working on the OSCP, and Information Security certificate based around penetration testing. CLI-based tools seem to be the core of most pen-testing assignments, so I'd like to build a tool aiding in command/switch searching. The goal of the program will to (eventually) load command line arguments by searching in r...
I am working with a mesh of triangles (in 3D, although I doubt it makes a difference). The mesh is given as list of lists, each list containing the indices of the three vertices of a triangle in said mesh. For example: 0 2 6 0 12 15 2 66 10234 I want to find the neighbours of each point, i.e., to have an array where t...
I've implemented a simple vector-like structure. I would appreciate all criticism relevant to code, style, flow, camelCase vs underscore, and so forth. template <class T> class Vector { public: typedef T* Iterator; Vector(); Vector(unsigned int size); Vector(unsigned int size, const T & initial); ...
I have an Eloquent model that has multiple types of joins that is used to filter out different request to grab the data of movies e.g.: Actors, Directors, Writers, etc... The joins are necessary because they use unconventional pivot tables. All the queries and eloquent here works and gives the desired returned data - h...
I am experimenting with the produce and consume concept while trying to incorporate it into my own project. I basically have two Workers in a small example I made: ProduceWorker: Populates a list with random numbers with a delay to emulate a real world adding in the doInBackground() method. Then in the process() that l...
I would like to get feedback on the code. It is working and can be seen here. I welcome any kind of feedback, since I am just starting to use JavaScript. Epecially in the case of performance, there might be better ways to code. $(document).ready(function () { var latlng, altitude, time, distance; var graphData...
I have this class: class adminTemplate { public static function load() { return new self(); } public function sidebarGuide() { return 'content'; // Very long html markup } public function wrapSidebars($content) { ob_start(); echo "<div class='sidebar w...
I have some code in progress that does multi threaded communication via sockets. I am using a poison pill to shut it down. It is a local port number. Is there a better way to shut it down gracefully? import java.io.IOException; import java.io.OutputStream; import java.net.*; import java.util.concurrent.ExecutorService;...
I'd like to get some guidance on whether or not I'm approaching my design the correct way, especially with regards to usage of smart pointers and references. I've started developing a small game engine which among other things consists of Entities, an EntityManager to 'own' the entities, a Quadtree for 2d entity positi...
I have a class in C# that uses a Random object to get a list of numbers randomized from an array of 1-25. Now what I need is improve this method to use RNGCryptoServiceProvider because it is not random enough for the application. I know that RNGCryptoServiceProvider is slower than Random, but I need to change it and I ...
With the SDL library, I'm creating an SDL_Surface* at w and h dimensions. SDL_Color is a struct with 4 unsigned char fields: a, r, g and b for alpha, red, green and blue. c1 is the origin color, c2 the destination color, and c is the color of the pixel at position (i,j). That gradient works fine, but it is very basic ...
VBA's 'Collection' is.... lacking, so, I've been working on a better Collection object that implements many of the features of C#'s Enumerable. This is very much inspired by this question and a follow up to Sorting a Collection and More imitation of Enumerable. I'm concerned that the API is inconsistent. Some methods l...
I'm trying to create a light system, with the midpoint algorithm and Bresenham Line Algorithm. I'm trying to redraw all the time (1 option) or redraw when I need to. When the circles are too big it becomes a bit laggy. Example function Light(x, y, range) { this.CordX = x; this.CordY = y; this.LuminosityRan...
The following code works and it prints out only True as it is supposed to, for all the different cases: class User(object): def __init__(self, key): self.key = key def is_ok(user_dbs, self_db): count = len(user_dbs) if not self_db: return not count return (count != 1 or self_db.key == user_dbs[0].key) ...
I'm trying to do the Reverse Groups Challenge on CodeEval: Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is. My logic is functional, but when I try to submit...
I am trying to convert hex to rgb, and rgb to hex. My current code doesn't seem optimal, and there is an issue with 0's in the hexadecimal. What do you think about the overall quality of this code? Can you think of a more efficient way of converting? $scope.$watch('hex', function() { var rgb = parseInt($scope.hex...
I have a simple Model class that represents a calculator. Header file: @class MMCalculator; @protocol MMCalculatorDelegate <NSObject> @required - (void)mmCalculator:(MMCalculator *)mmCalulatorFinishedCalculatingValues; @end @interface MMCalculator : NSObject @property (nonatomic, weak) id <MMCalculatorDelegate> de...
I was asked to create a script which will increment the letter-spacing of one line of text, until its width matches that of the first line; for use in headline/subheadline text to maintain a block effect as illustrated: The problem is, it's very slow. Is there a faster way of calculating this? $(window).resize(functi...
Here is my Model class's new header file: @interface MMCalculator : NSObject @property (readonly) CGFloat calculatedPay; @property (readonly) CGFloat calculatedSavingsForStuff; @property (readonly) CGFloat calculatedSavingsForProfitFormula; @property (readonly) CGFloat calculatedSavingsForTaxes; - (void)calculateValu...
In the following code, I've just parsed an JSON object called responseObject from an AJAX call, one of whose members is an array of objects called theArray. For each object in that array, I'm creating a row in a table. Each object contains three strings named code, author, date, and module. Each row gets three columns,...
I have a struct lying in a class as below, which I think is not good. Structs should be in a separate file, however, in this case, this struct is only used in a class. What is the best practice for a C# struct? class StudentMangement { private struct Student { public string Name { get; ...
The profile tells me it took ~15s to run, but without telling me more. Tue Aug 19 20:55:38 2014 Profile.prof 3 function calls in 15.623 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 15.623 15.623 15.623 15.623 {singleLoan.genLoan} 1 0....
I was asked to modify existing code to allow multi-level page structure. Each page can have one parent, and one page can have multiple children. I will present following code. My question is is there a more efficient way of doing this? I am hard-coding the number of levels that are reachable. Is there easier way to do...
The following is a fairly naive implementation of a Finagle protocol that uses the scodec library for binary encoding and decoding. I'll assume something like the following SBT setup: scalaVersion := "2.10.4" resolvers += Resolver.sonatypeRepo("snapshots") libraryDependencies ++= Seq( "com.twitter" %% "finagle-core...
I want to check if a record already exists in a database, and return true or false. If it exists, I want to update the update_at datetime field. The method touch_with_version from the paper_trail gem will do it. Which is better? def repeated?(unprocessed) occurrence = Occurrence.find_by(unprocessed: unprocessed)...
Please review my class. It uses iconv() (it's probably not the best solution however I haven't found any better alternative to change unknown characters). <?php /** * Class NiceUrl * * Creates friendly url from given name */ class NiceUrl { /** * Whether convert to lower * * @var bool|null ...
How could I rewrite this? I'd like to see as many ideas as you can come up with so I can pick one I like. I prefer simple and smart solutions. if (txtName.Text == "") { txtName.Focus(); } else if (txtSNo.Text == "") { txtSNo.Focus(); } else if (txtFNo.Text == "") { txtFNo.Focus(); } else if (txtMNo...
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n). I'm loo...
We are using the below code to optimally display our menu items (metro style). We are looping through an array of menu items and automatically shifting them based on size. Our tiles could be a size of 1, 2, 3. The row length is 6 Could you help me optimize the code? private void SortTiles(ref List<MenuItems> t) {...
I am upgrading my C++11 knowledge and repeating some essential algorithm. Here is binary search only in terms of iterators. #include <iostream> #include <vector> #include <iterator> using namespace std; template<typename t_iter> t_iter binarySearch(t_iter begin, t_iter end, typename iterator_traits<t_iter>::value_ty...
I am trying to write a text adventure as my first Python project. For this segment, I wanted a random enemy (part of a class with its own attributes) to appear and then enter a turn based battle with the player until either the enemies health is 0 or the player's health is 0. The player can use one of three moves to at...
I want to print all permutations of a given string in Java. To do this I create one auxiliary array boolean used[] to check if I have used some character or not. private static void permute(String s) { int n = s.length(); boolean[] used = new boolean[n]; char[] in = s.toCharArray(); Stri...
This is a follow-up of my question here: I am currently working on an application for various statistics. One task is to analyse a good amount of sentences for their word counts. The specifications are: sentences are read from SQLiteDatabase (up to 20k with an average of about 15 words) transformation: split by whites...
I have a table with this schema: CREATE TABLE [td].[MyTable] ( [ID] [int] NOT NULL ,[FatherID] [int] NULL ) (Note: I have excluded all the columns not relevant to the discussion) I receive an [ID] as input, and I need to collect the relative record and all of its fathers in one single output. Every record ha...
I generally prefer to work with EF by specifying exactly the data to fetch from the DB with regards to Navigation Properties/Lookups and the like, so we wrote this cache system to limit the number of calls to the database. public class DBCache<TContext, TKey, T> : ICache<TKey, T> where T : class, IDbPk<T>, IAutoInclud...
One of the things that I'm doing to teach myself is converting some numerical methods from existing Python code (they seem to me to lend themselves to functional programming quite well). I'd like to know how I can improve the general style of my code. In particular, I feel like I'm overusing brackets, that I should be ...
I am using Node.js Express.js node-mysql.js async.js I am making multiple asynchronous queries to my DB, but every query relies on the previous one's results, so I decided to use the waterfall method. Right now, my code looks like this (I simplified it with only 2 queries, but there are more): async.waterfall([ ...
I am using the following query which is causing issues. Note following points: I am using 4 tables in this query: message_share messages myusertable friends What I am trying to do in this query is to display messages, and share messages of users who are friend with each other. This is similar to Facebook wall where...
This helper method is designed to make stubbing ICommands simpler. Do you see any problems with this implementation? public static ICommand GenerateCommandStub( Action<object> executeAction = null, Func<object, bool> canExecuteFunc = null) { var commandStub = MockRepository.GenerateStub<ICommand>(); ...
Still pursuing the white rabbit, I had an IPresenter interface implementation featuring this method: Private Sub ExecuteAddCommand() Dim orderNumber As String If Not RequestUserInput(prompt:=GetResourceString("PromptExcludedOrderNumberMessageText"), _ title:=GetResourceString("AddPr...
I have coded this mess of JavaScript and a bit of jQuery. Everything here works perfect as intended, however it is a real mess. What would be the best way to clean this up with best practices and such? $.getJSON("People.json", function(data) { $.each(data.People, function(i, PersonObj) { var P...
This method is used to check a URL and return the time it takes to check and the HTTP status code: public static String urlCheck(String url) { try { URL urlToCheck = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlToCheck.openConnection(); connection.setRequestMethod("GET...
I created a program that picks a champion for a role on the game League of Legends using arrays and random numbers. Is there a quicker and more efficient way of doing this? There is one form that contains this: namespace Random_Champ_Picker_V2 { public partial class Form1 : Form { public Form1() { Initi...
I have a toy app that contains: editText1 for entering a number. Uses inputType of number. editText2 for entering a second number. Uses inputType of number. adderButton for triggering addition. textVeiw for displaying the result of the addition. I know: The naming could be better I should check for overflow/underfl...
We have implemented a process using C# and ReportViewer to create PDFs by the LocalReport.Render method. When we have to process a big file, say more than 20000 records, the process fails with an OutOfMemoryException. I know there may be lot of causes for this error, but I want to know if the below code is okay or if y...
The problem is, I have to limit the results to only 10 by default and add a "Load More" button to display 10 more results each time when user click the button. But I'm worried about users having their JavaScript disabled, because in that case, users won't be able to see more blogs. But I can also use MVC Razor Syntax c...
Function to use several blocks of if:elif:else: that all take slightly different conditional statements. I'm trying to format integers into a 2 digit string, adding a leading 0 for single digits. It is working great, but there has to be DRY way of doing the same thing. Also, the timezone formatting is a bit of a mes...
I'm currently looking to try learn CSS properly and I'm looking to recreate the following image using CSS: Now I've managed to recreate the image (sort of) what I am looking to know though is based on my code what am I doing wrong/what would be the best practice. Many solutions fix a problem I want to know if my solut...
I have the following header included in some of my projects so that I can add a little color to the terminal output. Here is how it would be used: fprintf(stdout, "Recognized text: %s\n", text ?: RED_TEXT("No text recognized.")); color.h: /** * @file color.h * @brief Defines all of the ANSI terminal escape codes t...
Given a list of Players with score, I want to find the ones with the highest score. There can be multiple players with the same score. I'm doing it like this now: class Player { final String name; final int score; Player(String name, int score) { this.name = name; this.score = score; } ...
In attempting to decouple the object from the messaging I came up with the following short code for adding publish-subscribe functionality to a Python script. from collections import defaultdict Topics = defaultdict(set) def subscribe(obj, message): """Adds key-value pairs to the Topics dict. Keys are message...
In my web site, I created a carousel. Just now, I realized that I most likely repeated myself with this code. I would like to learn how to DRY up this code. Here is my view file (.html.erb) format: <div class="carousel-inner"> <div class="item active"> <%= link_to image_tag(image_path("#{@title}/1.jpg")), home_p...
I'm writing a Ruby script to reverse engineering message log files. They come from an external system with the following characteristics: Each line of the log file has at least one message. Each line of the log file can have multiple messages. Each message consists of a set of numbers separated by spaces (e.g. 30 0 ...
I had designed a simple case class that looks like this: case class StreetSecondary(designator: String, value: Option[String]) I needed to add validation (to prevent invalid instances from ever being constructed). So, I then modified the class to look like this: case class StreetSecondary(designator: String, value...
I've designed a library for connecting Objective-C (and now Swift) apps to Microsoft SQL Server 2005+. (I believe there are other databases it works with, but I've only tested with MSSQL.) The project is available on Github here, and while users are fully capable of downloading the uncompiled project, my recommended o...
Consider a coding system for alphabets to integers where 'a' is represented as 1, 'b' as 2, .. 'z' as 26. Given an array of digits (1 to 9) as input, write a function that prints all valid interpretations of input array. Input: {1, 1} Output: ("aa", 'k") [2 interpretations: aa(1, 1), k(11)] Input: {1, 2, 1} Ou...