instruction
stringlengths
71
95.1k
In an effort to strengthen my functional programming, I'm reading Functional Programming in Scala. One of the assignments is to implement a function that does the same operation as containsSlice in the List API. @tailrec def hasSublist[T](list: List[T], currSub: List[T], origList: List[T], origSub: List[T]): Boolean ...
I am building out a MUD game engine and want my objects to communicate with each other. There is a wide range of message types that will be sent around, all of which implement IMessage. I adopted the Mediator pattern to facilitate passing the messages around to objects that have subscribed for publications. Is the pat...
GetBootstrap v2.7.0 Update from GetBootstrap v2.5 I add a progress bar feature in my console application customizer and update the #region grouping and convert the switch statement to Dictionary that suggested in the last version. For now I need help in reviewing my codes in ProgressBar.cs. You can also review my sou...
I'm rewriting GNU's coreutils in Go in order to learn Go better. I've implemented ttyname(3), and I'm looking for a general critique. I can't think of anything in particular I think I did poorly on. (Meaning nothing stands out to me -- I'm sure I messed something up.) I do return a pointer to a string instead of a stri...
Here is my dictionary: c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}} c_result2 = {"1": {"money": "89.46%"}, "2": {"finance": "10.54%"}} I want extract, first key value of 1 i.e. time, length of the dictionary may vary. My code: c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}} c_result2 ...
I have the below regex to match email address with atleast one @ and one . [-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4} Am wondering can it be simplified further to match email address with atleast one @ and one .?
I've decided to use some of my free time to create a simple game in Python. I chose Tic-Tac-Toe, but I decided not to make it too trivial. I made my game support any board size. I would greatly appreciate a code review. ## Tic-tac-toe game by Mateon1 try: raw_input except NameError: import sys print >> sys...
I'm using this code to find out the recurring dates, within a given range. Is this the correct way to find out the recurring dates within a range of dates? between[] contains all the dates calculated within the range provided by the user. I only pasted the code that is relevant to the recurrence part only. switch (true...
I'm creating the admin portion of a project. Specifically, I am wanting to allow the users to update the look-up tables for their areas of interest. All of my look-up tables have the same structure: TypeX Id int Description string Active DateTime Inactive Nullable<DateTime> CreatedBy string CreatedDate DateTime Modif...
In code I'm currently maintaining, there is a need to do very many repeated XOR operations of blocks of memory. The block size in my case is always 16 bytes. Because the code is executed very frequently, and because it's speed critical, I would like it to be as fast as possible. Ordinarily I'd write this in assembly...
A collection of sorting types as following insertion, radix, selection and heap sorts. How can i improve it? #include <algorithm> #include <functional> #include <type_traits> #include <iostream> template <typename Iterator> void radixSort(Iterator begin, Iterator end) { using value_type = typename std::iterator_t...
I wanted to write a program that performed a query to a database, then formatted the data before writing it to a file. I thus created 4 classes, which are: a main class a class dealing with the queries a class dealing with the database connection a class dealing with the formatting and writing of the data to a file D...
I have two goroutines that each need to return their results to the main function. These results are of different types. I have implemented a solution that uses a structure that holds these results. The structure is passed to the routines and each routine knows which field in the structure to use to save the results. I...
This is a function I just wrote with the goal to only load the desired information once, and if an error occurs, save it for later so that it can always be reported to a calling function. It does what I want but seems quite clumsy. std::wstring const& GetMuiFilePath() { static DWORD error = NO_ERROR; static std...
I'm running a simple Bash script that uses rsync to do an incremental backup of my web server every hour. What I'm looking for is an efficient algorithm to delete the proper backups so that in the end I keep: Hourly backups for 24 hours. Daily backups for 1 week. Weekly backups for 1 month. Monthly backups from that p...
I have made slight edits to a simple PHP contact form that I have found online. Can you see anything else that I could do to ensure that I am protected from email injections and spam? I have used trim, stripslashes and htmlspecialchars and made a simple question to act as spam prevention. <?php $myemail = "YOUR EMAIL ...
I recently wanted to determine the probability of generating a colliding string, given a character pool size, string length and number of strings to generate. I was led to the Birthday Problem, and came up with this code in PHP: function collision_probability($length, $count = 1) { $chars = '1234567890qwertyuiopa...
I wrote code for the following problem: Given a string, print out the number of deletions required so that the adjacent alphabets are distinct. Please suggest different methods by which I can increase the speed of execution. tst = int(input()) for i in range(0,tst): str = input() length = len(str) str = l...
Challenge: The Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. Consider a Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. My solution: import java.util.Arr...
I am currently writing a well.. manual testing site for a chat-based bot. The full code can be found on github. For that purpose I had to keep track of the messages currently in the "system". The stored message format is that of a simple and immutable class with non-complex fields. The code for this format is coming f...
I am working on a project that involves quite a lot of instantiated objects, with tons of properties, most of which have only a few possible values, so the prospect of saving on memory is quite significant. I wanted "portable" bitfields in order to be able to use raw binary serialization and deserialization, so memory ...
I feel like this bit of code could have been written more elegantly, especially with the huge if/else statements. Can somebody help me break this down? It would really help me out in the future. // Contact var c = 0; var contactHeight = $('#contact-keebs').outerHeight(); $('#mail-wrap').click(function (e) { e.prev...
I have to write an API for checked subtraction where the input minuend can be < 0 but subtrahend can't be < 0. I think I've covered all the cases of underflow and overflow. With given conditions the range of subtrahend is [Long.MIN_VALUE, Long.MAX_VALUE] and of minuend is [0, Long.MAX_VALUE]; with these limits overflow...
I am a self confessed jQuery novice but I am conscious of learning the correct techniques. When I can see repetition like this I just know that there must be a better way. jsFiddle $(document).ready(function() { var project1 = $('section').eq(0).offset(); var project2 = $('section').eq(1).offset(); var proj...
I've been programming Clojure for a little while and recently started learning Common Lisp. One of my favorite things about Clojure is the threading operator ->, which greatly simplifies long chains of nested function calls. Naturally I wanted to have this in Common Lisp. I found an implementation here: (defmacro -> (...
An interview question I got - Each element of an int array points to the another element, eventually creating a cycle. Starting at array[0], find the length of the cycle. Examples: Input: array = [1, 0] Output: 2 Input: array = [1, 2, 1] Output: 2 Note how element 3 is not part of the cycle Input: array = [1,...
Summary I'm getting ready to dive back into a "more proper" project, so I wanted to take a moment to get my TDD hat on before doing so. I decided to tackle this Roman Numeral Kata for practice. The purpose of the function is simply to take in a Long and output a string containing the equivalent Roman Numeral. I'm conf...
I am looking for improvements for this basic makefile and directory structure. I know this is overkill and could be compiled with one line in a flat directory structure, but I want to use this as a learning exercise. CC=g++ CFLAGS=-Wl,--no-as-needed -std=c++11 LIBS=-lpthread SRC=$(PWD)/src BUILDDIR=$(PWD)/build OUTDIR...
I currently have the following class that takes a custom file object as an argument and makes a copy of the file locally. class FileCopier def initialize(file_info_object) @file_info_object = file_info_object end def copy File.open(local_file_path, 'wb') do |f| read_file_in_chunks do |chunk| f.write ch...
As a beginner in coding, I have just written this code. The code should Add a form with a button to each user profile, it named Follow or Unfollow. It updates the user meta named "following" for the user who clicked the button. So we have to use the user IDs as a serialized array. Then we should use a query for the use...
I'm making a Java program that will analyze the given String by counting the lowercase, uppercase, numbers and special characters. Is there a way by making it functional? import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class PassTest { public static String pass...
I've been working on a registration form page in jQuery Mobile and I think I'm starting to get it fully complete. What I need feedback on is if I've forgotten anything in terms of accessibility, security (am I open to any SQL injections or other risks?) and just anything in general. It's my first time creating a prope...
My goal with the following code is to provide an extensible class that can be extended in order to read log files and transforms them into meaningful output. I'd like to have comments about the code itself, the test code, the javadoc and the overall structure. /** * Exception to indicate that there is no more input. ...
After much searching around the web, I couldn't find a single module which did a decent prettyXML or prettyHTML. Because: <node> <child> Text </child> </node> Is flat out ridiculous, and not a good use of space. <node> <child>Text</child> </node> Is much cleaner. That's what spurred this project. ...
I have this vbs file to check if a remote server is accessible. Can I simplify or refactor to make it more robust/efficient? const forReading = 1, forWriting = 2, forAppending = 8 public maxWaitTime maxWaitTime = 60 '1800 '30mins public connLogFileName connLogFileName = "connectionLog.txt" public pathToRemoteServer p...
I've been doing some programming challenges and problems lately and it seems like many involve primes. I concluded that I would benefit from optimizing how I'm checking for them. Currently I'm using the following method: private static boolean isPrime(int num) { if (num < 1) { throw new IllegalArgumentExcep...
This is a Rspec test for pagination in Rails project. I'm not sure if I should write the test in spec/requests or spec/controllers. And there must be a lot of thing that I had better to do. Which part of code should I refactor? spec/requests/companies_spec.r describe "Companies" do describe "GET /companies" do be...
This is my implementation of Project Euler #2 in C#. It takes 0 milliseconds to run, and I believe it is correct - I have seen nothing to indicate otherwise! By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. static void GetFibos(ref Lis...
I have just finished working on a Node.JS module that provides "multiple inheritance that works". I had some really specific requirements: Works in safe mode Auto-calling of parent constructors Makes sure that a constructor is only ever in the inheritance chain once Support for multiple inheritance Copying of class-wi...
A little context: Book has 411 Pages Read a random number of pages on the first day which is unknown Number of pages to read next day is the square of the sum of the digits of the page currently on I.e. on Page 36: read 81 pages next day On day 6 The square answer directly adds to current page number to make 411 Fini...
This code gets a state from a query string hash part, converts the hash part to a JavaScript object and then tries to get a view, dashboard or a mode value. If those keys are not present in object, it returns $.pulse.qs.views.home. Does this JavaScript code with ternary operator follow common best practices? It looks l...
For learning purposes, I am implementing certain code from Sedgewick & Wayne's Algorithms, Fourth Edition. Because of language features, a direct translation doesn't seem possible. For example, I believe the get method in their implementation of SequentialSearchST can return null for both value and reference types beca...
This is my implementation of Project Euler #7. Have I overdone it again? Is there anything else I should or should not do? It runs in 9 milliseconds on my computer. What is the 10001st prime number? static int NPrimeGenerator(int nPrime) { List<int> primes = new List<int>(); primes.Add(2); int nPrimeV...
I decided to solve a problem from Code Golf called the four fours. Problem description: The Four fours puzzle is a popular recreational mathematical puzzle that involves using exactly four 4s (and no other number) and a defined set of operations to reach every number from 0 to a given maximum. In this version, the onl...
This is my first submission and have completed one quarter of Java programming. I have an assignment to create a Palindrome Checker. Fairly straight forward, I had that portion of the code figured out in the first hour. However, in typical fashion (for me) I want my code to do a bit more. This is where I run into issue...
I have this implementation of a binomial heap providing insert, decrease-key and extract in logarithmic time. MinPriorityQueue.java: package com.stackexchange.codereview.ds; /** * This abstract class defines the API for the various minimum-priority queue * data structures. * * @author Rodion Efremov * @param <E>...
Given a sequence of heads and tails I want to find how many significant subsequences are in this sequence where the number of heads is not less than the number of tails. I want to achieve this in \$O(N \log N)\$ time. Example input: [ 'H', 'T', 'H', 'T', 'T', 'H' ] Example output: 11 Explanation: {H} {H} {H} {H, T} {...
This is my implementation of Dijkstra's algorithm in C++. Please clarify Whether the class design is proper or if it needs to be improved. I am just hard coding the vertex based on the priority of the vertex. Is there is any other way to implement it? Please provide some suggestions to optimize the code. class Verte...
Here's the problem for Java vs C++ (JAVAC): Java and C++ use different naming conventions: In Java a multiword identifier is constructed in the following manner: The first word is written starting from the small letter, and the following ones are written starting from the capital letter, no separators are used. All ...
I am creating a trivia game (purely for learning purposes) using AngularJS, NodeJS and MongoDB. My concern is related to the way I am organising the code in AngularJS. So far the game is functional, everything is working fine, but I know I am not doing it right. Directives should handle the DOM manipulation, but am doi...
I have this small generic path search library. It's not perfect at all, so I need some comments as to have a chance to improve it. com.stackexchange.codereview.graph.model: AbstractHeuristicFunction.java: package com.stackexchange.codereview.graph.model; public interface AbstractHeuristicFunction<T extends AbstractNod...
I have just started programming and we are being taught C++. After our 2nd lecture we were given an assignment to make a program that would take two values of time from the user (0 <= hr <= 12 and 0 <= min <= 60) and return the value of elapsed time. Since conditionals statements are not introduced yet, I am trying to...
I have 2 matrices. I have to calculate the euclidean distance between every row of matrix A and every row of matrix B. In the first solution I loop over the rows of the two matrices and for each row in matrix A, I take a row from B, take the square of the element wise subtraction, then sum it and take the square root....
I wrote a program, that gets a certain array and replaces each value in the array with the distance from it to the closest zero value. Time complexity is \$4n\$ => \$O(n)\$. (please correct me if I'm wrong, though). But I can't figure out what's my space complexity. The task was to make it as efficient (by time and spa...
Challenge: Count how much rain will be collected in the valleys between the peaks of a mountain range in a 2D world. The mountain range is defined by a single array of positive ints, where each element defines the height a peak. IE the array [1,2,1,2] would create the 2D slice: . m . m m m m m m = mountain . ...
The program reads a .txt file that contains lines of numbers. The first one has one number N and the second one has \$N\$ numbers as the first line says. The \$N\$ numbers is \$1 \le N \le 1.000.000\$. The program read the \$N\$ numbers in an array and performs the following procedure: Read the number one by one back...
Playing with a simple Java Point class where I would like to constrain the X and Y values to be doubles that must be in the range -10 to 10, inclusive. I've written some code, but it's been years since I've written java and I would like to know if this is how it would be written in modern Java: public class Point { ...
I started out practicing on implementing the builder pattern and somehow ended it up with this 2 hours later. It isn't really much, but it works and I'm hoping review should bring about a lot of insight. I'm curious in pinpointing: Which part(s) are well executed? I've never done anything 'game' like so I have no idea...
I received a task, of taking a known text file (Linux dictionary), use threads to count the different letters in it, and present the results in an array. The code doesn't have to be pretty, elegant, clean or short. The only demand is to count the letters correctly and do it as fast as possible. The file will be timed u...
This is an implementation of the Haversine formula in Microsoft Transact SQL. How can I simplify the function? CREATE FUNCTION dbo.Haversine(@point_a geography, @point_b geography) RETURNS FLOAT AS BEGIN DECLARE @result FLOAT DECLARE @lat1 FLOAT = @point_a.Lat DECLARE @lon1 FLOAT = @point_a.Long DECLARE...
This works for the most part. I am very new to programming so be aware. import java.util.*; public class HangManP5 { private static Scanner k; public static void main(String[] args) { int attempts = 10; int wordLength; boolean solved; k = new Scanner(System.in); System.out.println("Hey, what's your name?"); String n...
This function is meant to take an object, loop through the key-values and generate/build a HTML table at a particular ID: function insertBasicTable(basic_data, insert_id) { /* Insert the key/value pairs into a table element on the DOM. basic_data = object containing key/value pairs insert_id = the id on the DOM...
I recently tried to implement a simple hash table using Javascript. Could anyone help me review my implementation? //Hash Table Implementation var HashEntry = function(key, value) { this.key = key; this.value = value; this.nextEntry = undefined; }; HashEntry.prototype = { getKey : function() { return...
So, I began this challenge on CodeEval, which asks to print out the number of prime numbers less than any given integer N, where 0 < N < 4,294,967,295, ideally in O(N log N) time. I came up with this solution: import java.io.*; public class Main { public static void main (String[] args) throws IOException { ...
I am building this program in Python to generate 10 random arithmetic questions of either multiplication, addition or subtraction and then saves users scores to a .txt file. I just wanted some help condensing the code as I'm really stuck as of what to do with it. How can I combine the function (e.g. multiplication, add...
I'm making a data parser for road tax data (costs) which parses a JSON file with all weird variable names, which the customer gave me. The costs are different on each vehicle type. The costs at some vehicles are also splitted over the provinces. class RoadTaxDataParser { /** * @var array $data The data for ev...
I want to convert string arrays with following structure: static String[] lines = { "@1 var_decl name: testStr parent: @7", " srcp: Auto.cpp:6 " }; into Java objects with following stru...
Please review my code for preorder, inorder and postorder of a tree. I am using C++11 (or wanted to use), so let me know if anything is deviating from the C++11 standard. #include <iostream> #include <memory> using std::cout; using std::endl; using std::shared_ptr; struct node { int data; shared_ptr<node> lef...
Below is the code for stack along with one or two extra options. Kindly let me know if there are any concerns/critical issues. Below are the links for previous versions. Version 1.0 Version 1.1 Version 1.2 //*************Version 1.3: Begineer's Implementation of Stack ***************// #include <iostream> #include <f...
I'm looking for a review of the following code. Is there a better way to remove all properties that evaluate to truthy for a given function? Is there a better way to prevent a stack overflow in the recursive function? This is the entire Node.js module: // The removePropertiesWhereTruthy function accepts the following...
I want to create an extended disable/enable function in jQuery. This is working, but is this the best solution? Is each loop necessary? $.fn.ariaDisabled = function (isDisabled) { /// <summary> /// Sets the disabled state. /// </summary> return this.each(function () { v...
I setup my code at jsfiddle. Along the review I want to know the solution of a problem I'm facing in this code. On click the Edit button I want to enable the calendar which is disabled by default. And when it will be enabled user can select dates manually. Once user is done with selecting dates and will click the sav...
I'm trying to build my first object oriented system. I'm not sure that my register function below is the best way of approaching this within OOP. class User { public $username; private $email; private $password; public function register() { //Check if the username input is set. if(isset( $_POST['username...
I have tried to solve the following problem on SPOJ.com: You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ) A query is defined as follows: Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y } Given M queries, your program must output the results of these queries. When I run it,...
I've decided to write my first project in Python. I would like to hear some opinion from you. Description of the script: Generate Trivago URLs for 5 star hotels in specified city. Scrape these URLs to get prices. Save results as SQL queries in text file Execute queries from text file to upload results to database. Se...
This is a follow-up to Recursive binary search tree changes: Used raw pointers rather than std::unique_ptr const correctness Made variable names more beautiful implemented at() How can I improve this code? template<typename K, typename V> class binarySearchTree { struct Node { K key; V val; ...
I am trying to read a dynamic record length binary file, which has data like this: field1field2field3field4vector1vector2 Here, field3 defines the occurrence of vectors. For example, field3 is 2, then vector1&2 would be present and if the value is 3 then vector1,2&3 would be present. Let's say field1-4 is fixed, the l...
In my WP8 application I need to show a couple of radio buttons to let the user select a value out of an enum. I don't want to hardcode either the value or the text (description) showed to the user. I would like my Model/ViewModel drive them for me. As of now, this is what I have: //enum defined in model public enum Un...
This checks the intersection between a Ray and a Plane and between a Ray and a Quad (in 3D): import Linear data Ray a = Ray {rayPos :: V3 a, rayDir :: V3 a} data Plane a = Plane {planePos :: V3 a, planeNorm :: V3 a} type Quad a = V4 (V3 a) hitPlane :: (Num a, Fractional a) => Ray a -> Plane a -> V3 a hitPlane (Ray...
How can I improve the performance (in terms of computation time) of this code? # Settings const nbloci = 100 # length of the genome const N = 100 # Number individuals in the population const nbgenerations = 100 # number of generations const mu = 1/10^5 # mutation rate const s = 0.01 ...
This module allows to parse indented text file into Map from node to child nodes identified by Coordinate. This module seems way too complex - mainly because of managing stack that allows to "jump back" with decreasing indentation. How can I redesign it? sample input: a b c d e f produces: *Parse> parse tree f...
Write a function (in Haskell) which makes a list of strings representing all of the ways you can balance N pairs of parentheses: Example: balancedParens 0 [""] balancedParens 1 ["()"] balancedParens 2 ["()()","(())"] balancedParens 3 ["()()()","(())()","()(())","(()())","((()))"] My code produces the right answer ...
This seems to be working fine. I am pretty sure there is a better way to do it. How can my code be improved performance-wise? The main thing bothering me is the nested for-loop. function arithGeo (arr) { var isGeometric = false; var isArithmetic = false; var diff = arr[2] - arr[1]; var ratio = arr[2] / ...
I am a beginner, and I believe I made a simple and efficient program to do it in. I can add more methods for more detail for future updates, but it's a workable bit. import java.util.Random; import java.util.Scanner; public class TownGenerator { private static Scanner k; public static void main (String [] args) { ...
I have a MessageTree class that represents a binary tree of negative/positive. I'm looking to improve my walkTree method and make it more functional and succinct. Right now the try/catch is kind of ugly. The goal is to feed an array of "steps" (Array[Boolean]) that indicate whether to walk right or left through each no...
I am trying to solve the RIVALS problem on SPOJ: Starting from (0, 0), how many paths are there to reach point (X, Y), only taking one-unit steps moving to the right or up? Constraints: 0 ≤ X ≤ 106, 0 ≤ Y ≤ 106, answer is to be given modulo (109 + 7). I am facing a performance issue with accessing elements of a list. ...
I have set alert dialog on textview's onclicklistener, and there I have added some items using array adapter. Now what I want to do is check if the user selects an item from the alert dialog and clicks on submit. It should submit, otherwise not. But as per my if I select or not it displays message fill the details. bo...
I have about 1000 .xml files in different sub directories under one root folder. My root directory contains the below structure: RootDir\172\00ad8dc-bff\25.0.xml RootDir- The root directory for all my .xml files. 172- The sub directory of the "RootDir" directory. There are many such directories (I gave 172 as an examp...
Is there a better way to refactor the join and fetch the required attributes or is there any better option here? #student.rb class Student < ActiveRecord::Base has_many :subjects end #subject.rb Class Subject < ActiveRecord::Base belongs_to :student def self.get_all_subjects_and_student_info protocol_s...
I have the following function: def dnd_return(number,my_timeout): try: r =requests.get("https://dndcheck.p.mashape.com/index.php?mobilenos= {}".format(number), timeout =my_timeout) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as err: return "Error fetching DND info" ...
What are your opinions on my JavaScript function? Can my code below be refactored? var updatePrice = function () { var goPrice; var returnPrice; if (typeof scope.selectedGo !== 'undefined' && typeof scope.selectedReturn !== 'undefined') { for (var go in scope.gooffers) { if (scope.gooffe...
I am working on a parser that can parse log entries from a game called HearthStone, the overall idea is that it will read the log file live when the game is running, parses the log file and show interesting and useful data in real time. For this question I focus on the module that provides an API for the actual log ent...
I am wondering which method code is more "Pythonic": def load_job(self, identifier, job_name): i = 5 ex = None while i: try: for ep in iter_entry_points(group='core.account', name=identifier): self.modules[identifier] = ep # load_entry_point(ep.dist, 'core.acc...
In groovy I have a list of files A and also another list of files B. I want to remove all the files from A that have a filename that also occurs in the list of files B. I wrote the following code: List<File> removeByName(final List<File> files, final List<File> removalFiles) { final Set<String> removalNames = remov...
I have a configuration file which holds several file paths. If these paths are relative, I want them to be relative to the path of the configuration file (and not to the path of the user working directory ("user.dir")). Since it's not possible to change the working directory with Java, I've written this method: public ...
I got this requirement recently: Write some code that prints out the following for a contiguous range of numbers: the number 'fizz' for numbers that are multiples of 3 'buzz' for numbers that are multiples of 5 'fizzbuzz' for numbers that are multiples of 15 e.g. if I run the program over a range from 1-20 I should ...
I have the following code. Providing two objects cmd and this.xxx.properties, script detects the only property changed and mutate the input object (cmd). Script works fine but I would like to know if I could optimize or improve my code for speed. _deltaProperties: function (cmd) { var dataBefore = this.xxx...
Basically, I need to regroup keys by values from an object to an array An example worth a thousand words in my case, as I don't know how to clearly explain my problem. Here is my input object: { "Data 1": 0, "Data 2": 1, "Data 3": 3, "Data 4": 0 } What I should output: [ ["Data 1", "Data 4"], // da...
I'm new to Groovy, and coming from PHP it's been a rough transition. The code below works. However, I would appreciate feedback on how better to write it and follow good practice with Groovy. I anticipate doing a lot of Excel work in the future, and so tried to make this program reusable for more than just FizzBuzz. /*...
I'm new to Matlab and I would like to know tips in order to reduce the processing time of such program. The scheme of the actual code is very similar to typical C++ code and I would like to vectorize the for and if loops in order to decrease the processing time. The code is added just to make you know the overall idea ...