instruction
stringlengths
71
71.9k
I'm working on some code that has the following pattern of conditionals inside it. It doesn't look great, but it doesn't look terrible. Please, shed some light on the underlying reason this is not passing my smell test. I'd love to see some alternatives. I'm guessing it's because it's completely ignoring a certain per...
I'm beginning the long process of refractoring an Android app written entirely in SpaghettiJava™. I've been programming for a relatively short period of time (two years), and have tried refactoring the code base multiple times, but always get hung up on the wrong things and end up making very slow progress. I've just f...
I am trying to optimize the following switch statement, but I'm having a brain fart about how to do it. Here's the code: $('.newsroom-tabs div.pane-content ul li').click(function(){ // get the class name of the clicked link var className = $(this).attr('class'); // variable so that jQuery isn't traversing the DOM each ...
I'm a beginner and just finished my first Tic Tac Toe program. I was looking to get some feedback on some of the portions that seem a bit repetitive. Is there a way to make this more dry vs. hard coding? ///////TicTacToe/////////// //////////BOARD ASSIGNMENT//////////// var a = "a"; var b = "b"; var c = "c"; var d = "...
I am developing a simple macro that enables Python style 'with' in C++. I have shamelessly prefixed the macro name with BOOST_ - primarily because there's a similarity to BOOST_FOREACH, and because I didn't want to call it plain WITH. The motivation are familiar bugs like these: void bug1() { std::unique_lock<std::...
I have a short snippet of code that simply computes a weighted average for surrounding elements in a square matrix. The actual implementation that I'm working on is not an average (more complex equation), but I am using this one to figure out how to handle various performance hinderances. A few notes about my system: ...
It's a simple version of LZW compression algorithm with 12 bit codes. I want to know what's good and what's bad about this code. Be as picky as you like. // Compile with gcc 4.7.2 or later, using the following command line: // // g++ -std=c++0x lzw.c -o lzw // //LZW algorithm implemented using fixed 12 bit codes. ...
This JavaScript object is part of a mobile application that rolls dice for our D&D games. Here are some example of possible inputs from the user: 2d4 2d4 + 3d6 2d4 + 3d6 + 12 function DiceRoller() { this.rollDices = function(input){ var parsedInput = input.split("+"); var totalScore = 0; ...
This program is supposed to have 3 parts to it. 2 classes and 1 test program which I have created. My code for the program runs and works fine. However, I based my program off a different UML diagram. I had to go back and add more modules based on the UML diagram that my professor gave the class. My program still runs ...
I've got a class called Movie and within this class I use an AsyncTask to get a Bitmap from a url passed in the constructor. To store the image I use new DownloadImage().execute(url).get();. However I'm concerned about this blocking the UI Thread as now its a synchronous call. Is there another way I can go about saving...
I've been working on this day and night and, since I'm a newbie, I can't seem to figure this out. I have a map with 27 states. Each, on click, show the highlighted state and an info box. Also, I have 27 links that, on click, do the same as the above. So, I wrote a huge code and got it to work fine, but I'd like to resu...
I am trying to find a specific header string from different Maps (LEDES1998Bheaders, LEDES98BIheaders and LEDES98BI_V2headers) in an errorMessage depends on the parcel type and if the errorMessage has the specific header string I need to replace it with the corresponding value. public class ErrorMessageConverter { ...
I've been messing around with templates in C++14 and C++1z recently, and since I have somewhat of an obsession with optimization (and since my field of work relates to it) I decided to try to implement an optimized class for evaluating Chebychev polynomials of the first kind. I eventually want to work this class into a...
I have the following code to loop through a directory of folders and print all folders names with their paths in a worksheet. This is a follow up question to this one: Excel VBA - Get Folder Names Looking for code optimization for faster and better performance. Sub PrintFolders() Dim wb As Workbook Dim ws As W...
The April 2015 Community Challenge requires building a calculator. Implement a simple calculator Where the definition of "simple" is whatever you make it - only supports basic arithmetic operators? Fine. It supports scientific notation, exponents and trigonometry? Fine! Takes input from the console? Fine! Toggle...
The previous iteration at Natural merge sort Now my code relies on C++14 and looks like: natural_merge_sort.h: #ifndef NATURAL_MERGE_SORT_H #define NATURAL_MERGE_SORT_H #include <algorithm> #include <iterator> /******************************************************************************* * Implements a simple, arra...
Continuing working on Natural merge sort, I have parallelized it. Requires \$\Theta(N)\$ space and runs in $$\Omega(N + \frac{N}{P}) \cap \mathcal{O}(N + \frac{N}{P}\log_2\frac{N}{P})$$ time, where \$P\$ is the amount of cores available. parallel_natural_merge_sort.h: #ifndef NATURAL_MERGE_SORT_H #define NATURAL_MERGE_...
The following code will read a db, show the contents to the user and provide instruments to edit them. This has been tested and works well. model.php <?php class Collega { private $host="localhost"; private $user="root"; private $pwd=""; private $attiva=false; public function connetti () { ...
I am trying to solve a variant of the very popular question in which we find the number of distinct valid paths on a directed graph. The graph's nodes make up a m x n lattice (grid), and the edges only lead down and right. The goal is to find how many distinct paths start at the top left corner of and end in the bottom...
I need to decode and encode TLV (Tag, Length, Value) data which is a composite part-whole tree structure. Tag1 Len1 Tag2-Len2-Value2 Tag3-Len3-Value3 ... TagN-LenN-ValueN ------------------------Value1------------------------ Therefore, I've decided to use the Composite pattern for the TLV objects: typed...
From this library I wrote, I have created this function in Swift, but I'm not happy with the implementation. Can anyone suggest a better way to do this? I really don't like changing counters inside for-loops... extension Array { /// Removes all items that conform to the given closure mutating func removeAll(cl...
I am using the ruby sunspot gem to create a search users function on my site. It works fine and the users controller for the index page where there is a search form is this def index if params[:search].nil? @users = nil else @search = User.search do fulltext params[:search] end @users = @search.results.p...
I've recently read the books Clean Code and Effective Java. I am a huge fan of Object-Oriented Java. I am trying to write as professionally as possible. I have been an Android Developer for 20 months now. Here is a class that I wrote that is supposed to communicate with Google Static Maps API. Is this code Clean, Effec...
I'm using a doubly linked list container I've written as the working example. The textbook I'm using is from 2001, so feel free to point out where later versions of the C++ standard should be used instead. Notes: List::iterator functionality mimics pointer arithmetic. Unlike most containers, list beginning is marked ...
I'm developing a big (for me, as a beginner) terminal program "Brainfuck - The Game", in which you have to complete Brainfuck challenges. I would like your review on existing code (and project structuring) before I continue to expand it even more. main.py """ Brainfuck - the game. """ def main (): """ The main fun...
By N-by-N puzzles I mean f.e. a 3x3 sliding puzzle with one blank space (so a 8-puzzle) or a 4x4 sliding puzzle (so a 15-puzzle). When I try to solve certain puzzles some take no time but others take to much time to the point that I run out of memory. I think it's due to how I calculate the manhattan distance. Below y...
I am starting to play with POST request to save in my server the user token so I can send push notifications in Swift (this is the Swift code). This is the PHP file that processes the request (please note that I will improve it using prepare statements to prevent SQL injection): <?php error_reporting(E_ALL); ini_set("...
For several days I was messing around trying to create a markdown parser. This is the best I could come up without using regex. I was wondering if I'm on the right track.(I only covered the *,** case ) var str = "**f*"; function parser() { var i; var string = ' '; for (i = 0; i < str.length; i++) { ...
I want to save my users tokens id into my database using POST request in Swift (here PHP code here). I am a bit confused about synchronous and asynchronous request. Is this code the right way to do it? would the app crash if there is a connection problem while it is sending the synchronous request shall I use an api...
What are the issues/better ways to do this? I was just trying to implement this for practice and learn C++. Can anyone suggest efficient implementations of other functions such as count, size, all, none, etc? #define NO_OF_BITS (8 * sizeof(unsigned int)) #include <iostream> #include <assert.h> template<ssize_t n> cla...
I need a second set of eyes to look at my twitter bootstrap 3 header. I would welcome some insight on the code structure and methodology as it relates to bootstrap best practices and efficiency. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edg...
I needed to create a program which reads in a series of Excel files in folders typically structured something like this. rootDir Control 0hr.xls 24hr.xls 48hr.xls 72hr.xls 0.01um 0hr.xls 24hr.xls 48hr.xls 72hr.xls 0.1um 0hr.xls 24hr.xls 48hr.xls 7...
I've been doing some self-imposed exercises to get accustomed to Python and below is my code. import random from random import randint from random import randrange from mainlist import legendaryitems from mainlist import waystodie from mainlist import powerup from mainlist import mood from mainlist import ponder import...
I am very interested in inventing the best way possible for rendering bitmaps on-screen using the base drawing functions (putpixel(x, y), lineto(x, y), moveto(x, y), setpen(r, g, b, transp, size) ) You don't need to use graphic library to have them. You can call BIOS interrupt or initialize registers manually to set t...
I want to create an adjacency list based on data I get from a text file. Could I make this simpler? #include <iostream> #include <fstream> #include <sstream> using namespace std; struct Vertex; struct Edges; struct Edges { // edges link the vertex Vertex * linkTo; // pointer to vertex node Edges * ne...
I've made an interpreted language that's like Brainfuck except it has keywords instead of characters. Here's an explanation of the commands, and how to run it. add_ostream - Add the ASCII value of the current cell to the output stream. chg_size & [position]; - Change the current position on the stack. reset_stack; - R...
Someone asked me We know that \$12^2 = 144\$ and that \$38^2 = 1444\$. Are there any other perfect squares in the form? Here is my code: public class OneFours { public static void main(String args[]) { final int power_of_ten = 8; int num = 14; for (int i = 0; i <= Math.pow(10, power_of_ten); i++) { ...
Even though I have asked a question here related to my app using Swing and creating JPanel, I still have other ones about best practice making applications. I'm using Java 8. I have this class screening which contains Film and Auditorium classes. At the moment the class looks like this: Screening.java package cinema.sc...
There is nothing wrong, but is there a nicer way to re-write this program? public IEnumerable<Employee> InsertEmployee(dynamic employees) { var newEmployeeRecord = new List<Employee>(); foreach (dynamic employee in employees) { newEmployeeRecord.Add( ...
This MVC4 controller method, which uses EF6, is taking a long time to run (over 2 seconds). I've added verbose comments for the purpose of this post only. public async Task<ActionResult> Index() { // Get a list of all the classes I teach. var myClasses = await CurrentUser.GetClassesAsync(db); // Get a list of al...
I have written an attendance calculator that compares a set of rules against an employee's attendance record and determines what level of progressive discipline that employee is at (how much trouble they are in). Information: The rules are provided as a JSON object whose information comes from inputs on the page The ...
My code first creates a Point object. Then it creates a 25 x 25 array of ASCII in a string where _ marks a miss and the point's symbol (in this case "X") marks a hit. Then, the user can move the point with the arrow keys and it rerenders. This code is probably really badly written and terrible, but it works. I need som...
I have written some code for inserting a label at runtime that has its content set to a string array into a datagrid row. All of this will initiate when certain radio buttons are checked. The code is working perfectly fine, but I need to improve this code as I am learning C#, WPF and datagrid. I know there can be a cer...
The author of my book does not release odd-numbered solutions to students, so I can't check my solutions. I was wondering if there was a better way to solve this problem without simply printing out the square roots. Here is the question: (Game: locker puzzle) A school has 100 lockers and 100 students. All lockers ar...
I have created the following function in Swift for this library I am writing, which joins two arrays on a key (extracted using given closures), and then groups them by key in a [T:[S]] where S is the result type (also through a given closure). extension Array { /// Joins the array with another array on a specific k...
Where I work, we have 3 forms for leavers: HR, IT and rota. Lots of questions are duplicated across all 3 forms. So I thought, why not fill ONE form out, remove all duplicate questions, and simply split out the answers into formats that match original forms? I combined the form questions, then wrote a script to get th...
For a small administrative program, I have to be able to register people and their data. But, files are sometimes created through a phone call "on the fly" and then later certain data is added to the file to complete it. For this reason I started making my Person class with different constructors and I was chaining the...
This is a simple Rock - Paper - Scissor game. I'm trying to find a better way to write the algorithm and keeping the scoreboard. #!/usr/bin/python # import random import os import json import pprint #-------------------------------------------------# def main(): user, sys = 0, 0 name = os.getlogin() while T...
This isn't meant as a scheduler for just any job. The job that I need to schedule here is very specific for an application I'm writing for one of my clients. The scheduler will run as a console application because it's comparatively lightweight. The application will be started with Windows (startup items in the Registr...
I have this code that duplicates a byte array 5 times. class Multiple { public static void main(String[] args) { byte[] result = new byte[] {0x41,0x42,0x43,0x44}; int len = result.length; byte[] multipled = new byte[len*5]; for (int i = 0; i < 5; i++) { for (int j = 0; j...
I whipped a reasonably fast brute-force perfect number finding function in Haskell, after seeing a similar thing in mathematica. It works in under 3 seconds when I search up to 1000, but 10000 is too much. isDivisor :: Integral a => a -> a -> Bool isDivisor n a = mod n a == 0 sumDivisors :: Integral a => a -> a sumDiv...
I would like to know whether I applied the SOLID principle and the repository pattern the right way. My code should derive exchange rates from a database and do basic currency conversions. The database table is very easy. I assume I have a base currency and all exchange rates are against the base currency. So the datab...
I have some experience with OOP but I'm very new to game programming. For a school assignment, here's my first attempt at making a "real" game containing Entities, a game engine, game loop and the likes. I wanted to know if I used those concepts correctly, and would love to have some tips on things I could've done bet...
I am using a simple page with 2 pullout functions, one on the left and one on the right side. I would like to simplify or combine the two functions into one and make one pullout close, when I click on the other one, so that only one can be seen at a time. Here is a Fiddle: http://jsfiddle.net/schakalwal/gwu2gob3/ JavaS...
based on this answer I modified my code. Is this the correct approach now? func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { var userId = "001" //I just use it as USER number 1 let token = deviceToken.hexString() var postBody = NS...
I have two xml files, about 500mb each, an old and a new. I want to find out what items have been added or removed in the new.xml compared with the old.xml. I had some help on this code and I'm a bit new to C++ but I was wondering if this is the optimal way to approach a problem such as this. #include <set> #include <s...
I require hundreds of equal, small sized buffers in my current project. The bulk of the computation in the program operates on data stored directly in those containers, so high performance is imperative. As the number of the buffers stays constant at runtime, my current approach is to use a std::vector<std::deque<MyObj...
I am going through the Java CodingBat exercises. Here is the one I have just completed: Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string. Here is my code: public int sumDigits(String str) { StringBuilder strAp...
I have this piece of code in my Node.js API and I feel like it could (should) be optimized. var apiRouter = express.Router(); apiRouter.route('/user/:username') .put(function(req, res) { User.findOne({ username: req.params.username }).exec(function(err, user) { if (err) { res.send(err); ...
Given two arrays of elements: aaabbccdefaa zzzccddafgzz I want to check whether these two arrays are equivalent up to a relabeling. My strategy is to map them into a canonical form and then check whether they share the same canonical form: # Convert aaabbccdefaa -> 000112234500 canonical <- function(input){ output ...
(Game: locker puzzle) A school has 100 lockers and 100 students. All lockers are closed on the first day of school. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denoted L2, and closes every other locker. Student S3 begins ...
I am going through the Java CodingBat exercises. Here is the one I have just completed: Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping. For example, sameEnds("abXab") is "ab".] Here is my code: public String sameEnds(String string) { int ...
Using Python's Beautiful Soup, I analyze a number of html files (internally: soup). They are all a little different and my target comes in four different tags - or not at all. In two cases, my target may not be there but the tags may exists. In this case I find a ↵ . Here I got a very ugly code to check for them: #1: i...
I'm refactoring an old gateway and came across the following method: def apply_limit_and_offset(options) limit = options[:limit] offset = options[:offset] @result = if offset @result.drop offset else @result end @result = if limit @result.first limit else @result end @result end @...
I'm solving exercise 3 from lecture 3 of Berkeley's CS 61A (2012): Fill in the definition of map_tuple. map_tuple takes in a function and a tuple as arguments and applies the function to each element of the tuple. def map_tuple(func, tup): """Applies func to each element of tup and returns a new tuple. >>> a =...
I did the exercise below to practice. Can someone help me to shorten or improve the code in a simple way for a beginner? The exercise is: Given 2 int values, return whichever value is nearest to the value 10, or return 0 in the event of a tie. public int Closer(int a, int b) { Console.WriteLine(Closer(8, 1...
I listen on a port via multi thread async socket. That port receives requests over XDomainRequest. I received the complete data each time till now but I don't trust this code because it may not work in some cases. (network traffic etc.) Here is my StateObject: public class StateObject { public Socket workSocket = ...
This is supposed to get a single value from the DB. What should I consider next? How can I upgrade it? public static String GetConnectionString() { return ConfigurationManager.ConnectionStrings["xxx"].ConnectionString; } public static String GetProviderName() { r...
I don't think I am using the MVC concept in Ruby on Rails properly. Model accesses db, controller works on logic and view displays information/data. But in my code, my Model code is empty. Can anyone please help in analyzing on how I can use MVC correctly? Model: class Product < ActiveRecord::Base end Controller: clas...
I am going through the CodingBat exercises for Java. Here is the task I have just completed: Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. And here is my code: public int sumNumbers(String str){ int tot...
Please review my Adjacency Matrix class based on this code. Since I use std::vector to create the matrix, I would like to store as many nodes as possible. Is it OK to use std::size_t all over the code? Are using 1 for connected and 0 for not connected a bad idea? class AdjMatrix { public: AdjMatrix(const std::si...
I'm working on something for my school's laptops that will disable videos/games between 8:00 AM and 3:15 PM. Due to the giant time gap, I will not be waiting to see if the code functions properly or not. What I want to know is if my code will function properly, as I'm not good enough at JavaScript to know myself. funct...
I would like to greatly reduce verbosity of following code fragment. What I'd like to do: Reduce number of occurrences of MaterialRangedParam<Value> and MaterialParam<Value>. C++ has typedef. C# doesn't. Is there keyword for own type of a class? Remove operator !=, operator ==, GetHashCode and Equals and make compiler...
This code simulates a polygon (say a triangle) with a person at each vertex, every person is looking at the next adjacent vertex/person. They all start moving towards each other with a constant velocity "trying to chase other". I could not understand this conceptually so I created an applet in Java to help me understan...
This is an online problem. The challenge is to print the kth prime number, for each k given in the input (1 ≤ k ≤ 15000). The first line of input indicates the number of inputs on the subsequent N lines. Example input: 4 1 2 3 4 Example output: 2 3 5 7 (the 1st 2nd 3rd and 4th prime numbers). #include <stdio.h>...
I watched a presentation by Dave Thomas on Elixir where he gave an example problem that he solved using functional programming. He mentioned using Ruby to solve the same problem, but did not show an example. I decided to give it a try. The problem goes something like this: For a list (Ruby doesn't have lists, but for o...
I currently have a working code that does exactly what I want it to do, loops through a particular part of an excel document looking for certain keywords, then pasting those keywords into a separate sheet in the excel spreadsheet. It is just very long and doesn't allow for any more than 20 repetitions. I was wondering ...
Does this extension method contain unnecessary work? - Thanks for reviewing Scenario - A series of tables are Key-Value pairs (Int "Id" / nvarChar "Title"). This extension method "dots-off" any integer ("Id") and provide the corresponding string value ("Title") given a target "type" Used in aspx-code-behind. An extens...
Just for practice, I am writing a tic tac toe game in Python 3.4. My main goal is to make expandable, for example allowing larger boards and more than two players. The way my project is arranged is something like: lib.py - All the functions and classes needed for a tictactoe game ai.py - Functions for the artificia...
The exercise 1.3 of the book Structure and Interpretation of Computer Programs asks the following: Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. My answer is this: squareTwoLargest(X, Y, Z, R) :- ( X > Y -> A = X, B = Y ; A =...
I was writing a program in C++11 to find top k words from a file. I think priority queues will give the optimal solution so I implemented using that. The code works and compiles. Could anyone please review this and suggest some more C++11/14-ish things to do? I also have some specific questions: Is there way in C++11...
How do I make this efficient? #include <stdio.h> #define MAX 1000000000 int main() { int n,temp,prod,i,j=0; scanf("%d",&n); for(i=1;i<MAX;i++) { temp=i; prod=1; while(temp!=0) { prod=prod*(temp%10); temp=temp/10; } if(prod==n) ...
I have some fascination with terrain generators, so I whipped up this generator in Python. The way it works is pretty simple, but I figure that I should give an explanation for those who don't want to try and figure it out. The initial 2D terrain array is generated with a provided width and height, and then filled ent...
My Python-based web server (Tornado module) is pretty complex and keeps going down (seems like usually in the middle of the night), so here's a bash script that kills the process, restarts and emails and txt messages me: #!/bin/bash NOTIFYEMAIL=<my_email_address> SMSEMAIL=<cell_phone_number>@<carrier> # ie. pm.sprint.c...
I am challenging myself to try to attempt to write a function that is as efficient, portable and failsafe as possible. The function is very simple and just converts a string (or wstring) to lowercase. Are there any improvements you think I could make and any errors I have done? #ifdef UNICODE typedef std::wstring tstr...
I am working through a new challenge on CodeEval.com and I think I am getting a correct result but I can't get through their grader. I am not exactly sure where error is. I didn't post this on stack overflow because I also would like to get your opinion on the code and the algorithm that I came up to solve this. Thi...
My teacher wants us to create a program that runs n games of war and calculates the average number of battles, wars and double wars that occurred. He has very specific rules (not necessarily the actual rules of war). I know there's some redundant code in the deck building and splitting for each game, but that's how he ...
I'm solving exercise 2 from lecture 3 of Berkeley's CS 61A (2012): Write a function min_element that returns the minimum element in a tuple. def min_element(tup): """ Returns the minimum element in tup. >>> a = (1, 2, 3, 2, 1) >>> min_element(a) 1 """ I know that Python has a built-in min functio...
I have a nested hazelcast distributed map: Map<CountryId, Map<CityCode, Map<data_key,data_value>>> where "data_key" is "population", "literacy_rate" and "gender_ratio". Below is the class where I have implemented a method which adds new city data to a specified country. import java.util.HashMap; import java.util.Map; ...
I am trying to create max-heap for practice. Are there any bugs? Are there ways that I can improve the code quality? public class MaxHeap <E extends Comparable<? super E>>{ List<E> list; public MaxHeap(E[] array){ this(Arrays.asList(array)); } public MaxHeap(List<E> list){ if(list == null) throw ...
I am doing a beginner C++ project and it's simply a library management system where a student will hire, give back a book, book and hire records are stored in a binary file etc. I'm approaching the project as though the project would be used by other developers and that I need to design the classes so they cannot be in...
I am using a CQRS type patter for querying data in my application. I am currently using entity framework to connect to the database. public class GetCustomerQuery : IQuery<Customer> { public string CustomerId { get; set; } } public class GetCustomerQueryHandler : IQueryHandler<GetCustomerQuery, Customer> { pu...
I keep forgetting that the standard join() can only take a single iterable, so I made a few functions that act recursively on any passed arguments. Somewhat ironically, the deep version of join() isn't called by the user, but only within the deep version of sum() - the standard sum() breaks and tells you to use join() ...
I'm writing code to compute a single value answer to a given numbers in integer array such that step sum is calculated till only 1 number is left. For example: Input: 3,5,2,6,7 Output is computed as: (3+5)+(5+2)+(2+6)+(6+7) It remains like this till I only have a single number left. 3 5 2 6 7 8 7 8 13 ...
I'm solving exercise 4 from Discussion 3 of Berkley's CS 61A (2012) (see page 4): Fill in the definition of cartesian_product. cartesian_product takes in two tuples and returns a tuple that is the Cartesian product of those tuples. To find the Cartesian product of tuple X and tuple Y, you take the first element in X a...
I am gradually completing the CodingBat exercises for Java. Here is the one I just did: Given an array of ints, return true if it contains no 1's or it contains no 4's. Here is my code: public boolean no14(int[] nums) { int oneCount = 0; int fourCount = 0; for (int i = 0; i < nums.length; i++) { ...
extension Array { func flatten<TResult>(transform: (T) -> TResult?, childArray: (T) -> [T]) -> [TResult] { var result = [TResult]() for original in self { let transformed = transform(original) if transformed != nil { result.append(transformed!) } ...
I am currently attempting to create a two SVG overlay / masking like the image below: I have created a SVG for the overlay. As it stands, I am trying to create two elements one for the green side and one for the blue side. For what I am trying to achieve, is this the best approach? If not, what is? Is it worth creati...
A long should be treated as a list of 32 unsigned numbers, each of them just two bit long. So 0x1234F... represents {0, 1, 0, 2, 0, 3, 1, 0, 3, 3, ...} and 0x55AA0... represents {1, 1, 1, 1, 2, 2, 2, 2, 0, 0, ...} Given two such lists, I need to compute the absolute values of the pairwise differences and sum them up....
Ι have the following database: SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; CREATE TABLE IF NOT EXISTS `Authors` ( `AutID` int(11) NOT NULL, `Name` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; INSERT INTO `Authors` (`Au...