texts: Maintainability with lots of lookups, checks and inserts

texts:
I have the following method in a Controller in Laravel 5.3.

The method is supposed to be in two other controllers and all three Controller methods will receive the needed arguments in different ways.

I'm unsure if this would be a good fit for a Service Container or how I should handle it.

public function newSurvey(Request $request)
{

    // Some validation for the input

    $delay = 0;
    if( $request->has('delay') ) {
        $delay = $request->get('delay') * 60;
    }

    if($request->has('template')) {
        $template = $this->application->templates()->where('slug', $request->get('template'))->first();
    }
    else
    {
        if(count($this->application->templates) == 0)
        {
            return response()->json(['error' => 'You need to create a Survey Template to send out new Surveys'], 422);
        }
        $template = $this->application->templates()->where('default', true)->first();
    }

    if(!$person = $this->application->persons->where('email', mb_strtolower($request->get('email')))->first())
    {
        $person = new Person();
        $person->name = $request->get('name');
        $person->email = mb_strtolower($request->get('email'));
        $person->key = Uuid::uuid4()->toString();
        $this->application->persons()->save($person);
    }

    if(!$person->active)
    {
        return response()->json(['error' => 'Recipient is inactive and cannot be contacted anymore'], 422);
    }

    if($person->updated_at->diffInDays(Carbon::now()) < $this->application->cooldown)
    {
        return response()->json(['error' => 'Recipient has already received a survey wihtin the cooldown period'], 422);
    }

    $person->touch();

    $survey = new Survey([
        'key' => Uuid::uuid4()->toString(),
        'template_id' => $template->id,
        'person_id' => $person->id,
        'name' => $request->get('name', null),
        'email' => $request->get('email'),
        'order' => $request->get('order', null),
        'segment' => $request->get('segment', null),
    ]);

    $this->application->surveys()->save($survey);

    $when = \Carbon\Carbon::now()->addSeconds($delay);
    Mail::to($survey->email, $survey->name)->later($when, new NewSurvey($survey));

    return response()->json(['survey_id' => $survey->key], 200);
}


texts: Reading two .dat files for calculating location distance

texts:
I'm creating a program that reads data from two .dat files: one for food-bank location and the other for residence.  Right now, the program can calculate the distance between food-bank and residence and insert it into a distances vector.

My concerns are:

Is my logic right?
Can I determine the distance, in miles, between each location in residences and the closest food bank in foodbanks?  Note: the function will calculate in meters.

#include <iostream>
#include <math.h>
#include <fstream>
#include <vector>
#include<iterator>

using namespace std;

struct Foodbank
{
    double x;
    double y;

    //input stream overload
    friend std::istream &operator>>(std::istream &is, Foodbank &f) {
        return is>>f.x>>f.y;
    }
    //output stream overload
        friend std::ostream &operator<<(std::ostream &os, Foodbank const &f) {
            return os << f.x  << "\t"<< f.y<<"\t";

        }
};
struct Residence
{
    double x;
    double y;
    //input stream overload
    friend std::istream &operator>>(std::istream &is, Residence &r) {
        return is>>r.x>>r.y;
    }
    //output stream overload
    friend std::ostream &operator<<(std::ostream &os, Foodbank const &r) {
        return os << r.x  << "\t"<< r.y<<"\t";

    }
};

double distanceCalculate(double x1, double y1, double x2, double y2);
int main(int argc, const char * argv[])
{

    ifstream foodbankFile("foodbanks.dat");
    ifstream residenceFile("residences.dat");

    //vectors data
    vector<Foodbank> foodbankData;
    vector<Residence> residenceData;
    vector<double> distances;

    copy(std::istream_iterator<Foodbank>(foodbankFile),
         std::istream_iterator<Foodbank>(),
         std::back_inserter<std::vector<Foodbank>>(foodbankData));
      std::cout<<"read "<<foodbankData.size()<<" data: "<<std::endl;

    copy(std::istream_iterator<Residence>(residenceFile),
         std::istream_iterator<Residence>(),
         std::back_inserter<std::vector<Residence>>(residenceData));

    std::cout<<"read "<<residenceData.size()<<" data: "<<std::endl;
    for(auto r:residenceData)
    {
        for(auto f:foodbankData)
        {
            //std::cout<<f.x <<", "<<f.y <<", "<<std::endl;
            distances.push_back(distanceCalculate(f.x,f.y,r.x,r.y));
        }
        //std::cout<<r.x <<", "<<r.y <<", "<<std::endl;
    }

     std::cout<<"read "<<distances.size()<<" data: "<<std::endl;
    return 0;
}

// the distance in metres
double distanceCalculate(double x1, double y1, double x2, double y2)
{
    double x = x1 - x2;
    double y = y1 - y2;
    double dist;

    dist = pow(x,2)+pow(y,2);           //calculating distance by euclidean formula
    dist = sqrt(dist);                  //sqrt is function in math.h

    return dist;
}


texts:
I have a regex pattern that will match some elements from a string and give them a particular name. For example, #^(?<foo>.*)$# will match the whole string and name it foo.

My problem is that the matches also contain the "classic", numbered matches.

For example:

<?php

$pattern = '#^(?<foo>.*)$#';
$str = '123';
$matches = null;
preg_match($pattern, $str, $matches);
print_r($matches);

will print:

Array
(
    [0] => 123
    [foo] => 123
    [1] => 123
)

As all the matches will always be named, I decided to manually remove the numbered indexes from $matches in order to clean things up:

<?php

$pattern = '#^(?<foo>.*)$#';
$str = '123';
$matches = null;
if (preg_match($pattern, $str, $matches))
{
    foreach ($matches as $key => $value)
    {
        if (is_int($key))
            unset($matches[$key]);
    }
}
print_r($matches);

Which prints:

Array
(
    [foo] => 123
)

It works, but I feel that it can be improved. Is there a better way to do this, especially without the foreach loop?

In practice, $pattern and $str can be much more complicated than the example I gave and I want this to be executed as fast as possible.


texts:
Problem 22, here, asks the following:

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

  What is the total of all the name scores in the file?

My solution is as follows:

import re
import string

def create_names_list(file_name):
    #create a names list parsing
    names = open(file_name).read()
    names = re.findall(r'"(.*?)"', names)
    names.sort()
    return names

def name_weights(file_name):
    #fetch name-list
    names = create_names_list(file_name)

    #create a letters dictionary e.g. {'A' : 1, 'B' : 2, ... 'Z' : 26}
    letters = string.ascii_uppercase
    letters_map_reversed = dict(enumerate(letters))
    letters_map = {value: key+1 for key, value in letters_map_reversed.iteritems()}

    # sum all letters using letter score * index
    return sum(letters_map[char]*(names.index(name)+1) for name in names for char in name)

  %timeit name_weights('names.txt')

  1 loops, best of 3: 1.18 s per loop

I noticed in the thread for the solutions that many python solutions appeared to be in the 8-12ms range, 10x faster than my solution. As a result I was concerned with the performance of my solution.

Two things I've done to attempt to tweak my solution are changing the letters_map[char] portion to just be ord(char)-64 which I noticed a few people were using. It seems like a clever, certainly shorter, way of getting the number value that I hadn't thought of. It didn't alter performance though, which makes me think my problem is with the final expression that uses a nested for loop to multiply all the characters in all the words by the given weight and letter_mapping number. It seems as though other solutions made similar use of nested for loops, but I noticed that nobody had used index() in order to get the numeric index of the name in the list. I wonder if that is what is causing performance, but I suspect it may also just be my misunderstanding of how to structure these nested for loops optimally (for instance I could have used enumerate() on names in addition to on letters in order to get the index in a dictionary which would forgo the need to use index().

Aside: I've intentionally used regular expressions here instead of .strip() and .replace() in order to just get an idea for what regular expressions are and how they work (in addition to perhaps there being non-zero improvements because RE is implemented in C right?) The file parsing itself doesn't really effect performance I've noticed, but any input on what is standard python convention and when to use strip() and built-in string methods vs. python's re module is helpful there is very welcome.

General code criticism as well as specific syntax very welcome.


texts: PHP Factory Pattern : Should I use `create()` or `__invoke()`?

texts:
I currently had a colleague reviewing my code and he had a comment on a factory class I created. It's very simple:

class ResponseFactory
{
    public function create(array $curlInfo, array $rawResponse): ResponseInterface
    {
        return new Response($curlInfo, $rawResponse);
    }
}

$responseFactory = new ResponseFactory();
$response = $responseFactory->create(...);

His comment was that I should use the __invoke()-method of PHP. In that case, the code would look like this:

class ResponseFactory
{
    public function __invoke(array $curlInfo, array $rawResponse): ResponseInterface
    {
        return new Response($curlInfo, $rawResponse);
    }
}

$responseFactory = new ResponseFactory();
$response = $responseFactory(...);

Now I am wondering: is this just a matter of taste? Or is there real benefit in using __invoke() over a public create()-method?

Any thoughts or insights on this matter are more than welcome. I'm really trying to find good use cases for the __invoke()-method, but I'm not sure if a factory is one of them.


texts:
I have written a simple spinner wrapper, but was wondering if any of you could think of any ways to make it more robust. It only handles strings at the moment.

MySpinner:

package a.b.c;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MySpinner extends Spinner {

    // constructors (each calls initialise)
    public MySpinner(Context context) {
        super(context);
        this.initialise();
    }
    public MySpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.initialise();
    }
    public MySpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.initialise();
    }

    // declare object to hold data values
    private ArrayAdapter<String> arrayAdapter;

    // add the selected item to the end of the list
    public void addItem(String item) {
        this.addItem(item, true);
    }
    public void addItem(String item, boolean select) {
        arrayAdapter.add(item);
        this.setEnabled(true);
        if (select) this.selectItem(item);
        arrayAdapter.sort(new Comparator<String>() {
            public int compare(String object1, String object2) {
                return object1.compareTo(object2);
            };
        });
    }

    // remove all items from the list and disable it
    public void clearItems() {
        arrayAdapter.clear();
        this.setEnabled(false);
    }

    // make the specified item selected (returns false if item not in the list)
    public boolean selectItem(String item) {
        boolean found = false;
        for (int i = 0; i < this.getCount(); i++) {
            if (arrayAdapter.getItem(i) == item) {
                this.setSelection(i);
                found = true;
                break;
            }
        }
        return found;
    }

    // return the current selected item
    public String getSelected() {
        if (this.getCount() > 0) {
            return arrayAdapter.getItem(super.getSelectedItemPosition());
        } else {
            return "";
        }
    }

    // allow the caller to use a different DropDownView, defaults to android.R.layout.simple_dropdown_item_1line
    public void setDropDownViewResource(int resource) {
        arrayAdapter.setDropDownViewResource(resource);
    }
    // internal routine to set up the array adapter, bind it to the spinner and disable it as it is empty
    private void initialise() {
        arrayAdapter = new ArrayAdapter<String>(super.getContext(), android.R.layout.simple_spinner_item);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        this.setAdapter(arrayAdapter);
        this.setEnabled(false);
    }
}

To use:

Use a.b.c.MySpinner instead of Spinner in your XML layout file
Set up a variable, mMySpinner = (MySpinner)findViewById(R.id.spinner);
You can then use all the functions which should be self-explanatory
If there are no items in the list, the spinner is disabled to prevent untoward events

mMySpinner.clearItems() - to remove all the items
mMySpinner.addItem("Blue") - to add Blue as an item in list (items are sorted by abc)
mMySpinner.selectItem("Red") - to make the indicate item the current selection
mMySpinner.getSelected() - to return the current selected item string


texts: Finding all upper/lower case combinations of a word

texts:
For every word there are 2^n different ways of writing the word if you take into account upper/lower case letters. Eg for "word" we can write;

word
Word
wOrd
WOrd
woRd
WoRd
etc

I've written this code to calculate all the combinations. Is there any way I can improve the performance? Profiling tells me that this method takes 99.9% of the execution time of my program (which measures password strength).

String word = "word";
int combinations = 1 << word.length();

for (int i=0; i<combinations; i++) {
  StringBuilder buf = new StringBuilder(word);
  for (int j=0; j<word.length(); j++) {
    if ((i & 1<<j) != 0) {
      String s = word.substring(j, j+1).toUpperCase();
      buf.replace(j, j+1, s);
    }
  }
  System.out.println(buf);
}


texts: Maximize the number of PyGame sprites, with collision detection

texts:
I was trying to see what is the highest number of moving and colliding boxes (sprites) I could get in pygame?  So that I could start working on game I want,  I searched google and I found different people do it as a challenge, trying to get to the highest number of sprites. But none of them use the colliding, they just make a high number of sprites with no for loop inside the main loop.

The highest number I could get before it started to lag was just 260, which is too low for the game I want to start making.

Here is my code:

import pygame
from pygame.locals import*
import time
screen=pygame.display.set_mode((1250,720))
class Box(pygame.sprite.DirtySprite):
    def __init__(self,posx,posy):
        pygame.sprite.DirtySprite.__init__(self)
        self.image= pygame.Surface ([40,40]).convert_alpha()
        self.image.fill((250,0,0))
        self.rect=self.image.get_rect()
        self.rect.center=(posx,posy)
    def update (self):
        self.dirty=1
pygame.init()
clock=pygame.time.Clock()
boxs=pygame.sprite.LayeredDirty()
while True :
    start = time.time()
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type==pygame.QUIT :
            pygame.quit()
            quit()
        if event.type== pygame.MOUSEBUTTONDOWN and event.button == 1:
            box=Box(event.pos[0],event.pos[1])
            inside=pygame.sprite.spritecollideany(box,boxs )
            if not inside :
                boxs.add(box)
        elif event.type== pygame.MOUSEBUTTONDOWN and event.button == 3:
            print (boxs)
        elif event.type==KEYDOWN:
            if event.key==K_SPACE:
                boxs.empty()
    for box in boxs :
         if box.rect.y<650 :
##             touch= pygame.sprite.spritecollideany(box, boxs)
##             if touch==box:
##this way above didnt work for me because the box will cross any other box added to the group after it
##for example the box number 3 in the boxs will cross box number 4,5,6,7,8,9,........
             touch= pygame.sprite.spritecollide(box, boxs,False)
             if (len(touch))<2:# i do this because (touch) will always return that the box touch it self
                               # but when its touch more then one then i know it touch other box so it will not move
                               # and i feel that there is much faster way to do this check then my way :(
                 box.rect.move_ip(0,1)
    boxs.update()
    dirty=boxs.draw(screen)
    pygame.display.update(dirty)
    clock.tick(60)
    end = time.time()
    print (end-start)
#the best until time totally turn to 0.02xxxx = 260 sprite

So what else I could do to have more then 260 moving and colliding boxes at 60 fps without lag?


texts:
The powers of 2 are trivial to factor because all powers of 2 have one 1-bit and the rest 0-bits. Just iterate minus one 0-bit as follows: 10000,1000,100,10,1. And then convert the binary strings into base-10 and you got the factors for powers of 2.

Example

import operator
from operator import mul
from functools import reduce
import time

print('Find the factors of a power of 2')
print('This input number must be a power of 2')
X = 32

binary = "{0:b}".format(int(X))
l = len(binary)

# Checking if input is power of 2
# All binary strings that are a power of 2 must
# have only ONE 1 bit

if binary.count(str(1)) == 1:
  print('yes, this is a power of two')
else:
  print('no, this is not a power of 2')
  quit()

start = (round(time.time() * 1000000))
count = 0
result = [];
for j in range(0, l):
        count = count + 1
        # create list of factors called result
        result.append(int(binary[0:l-count], 2))
        if len(result) == l-1:
          # I don't want to forget X itself is a factor
          result.append(X)
          end = (round(time.time() * 1000000))
          break

print(result)
print('Factoring took', end-start, 'microseconds')

Output

Find the factors of a power of 2
This input number must be a power of 2
yes, this is a power of two
[16, 8, 4, 2, 1, 32]
Factoring took 0 microseconds

Question

What better names could I use to define my variables, and what could make the program run faster?

Is there a more efficient implementation to decide if a number is a power of 2?


texts:
So I want ask if I'm doing it right way.

Im still learning..

I want check textarea duplicates and alert if duplicate and remove it.

$(document).ready(function(){
  $('#lol').keypress(function(){
    var data = $('#lol').val().split('\n');
    var result = data.filter((word, i, arr) => arr.indexOf(word) === i);
    $('#lol').val(result.join('\n'));
    data.unique();
  });
});

(function() {
    "use strict";

    Array.prototype.unique = function unique() {
        var self = this;
        return self.filter(function(a) {
            var that = this;
            // console.log(that);
            if(!that[a]) {
                return that[a] = true;
            } else {
                alert("duplicate");
                return that[a] = false;
            }
        }, {});
    }
})();


texts:
I attempted the 3-Sum problem on Leetcode, where the problem asks to find all possible triplets of numbers in a given list such that their sum is 0. My code worked, but it exceeded the time limit for 2 of the 313 cases. I believe my solution is in \$O(n^2)\$, but I think there is a line in my code where I sort a triplet within a for-loop, which might change the time complexity.

Here is the problem statement from Leetcode:

  Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

  Note: The solution set must not contain duplicate triplets.

class Solution:
    def threeSumHelper(self, nums, target):
        D = {}
        n = len(nums)
        solutions = []
        for x in range(n):
            complement = target - nums[x]
            if complement in D.values():
                solutions.append([complement, nums[x]])
            D[x] = nums[x]
        return solutions

    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        D = {}
        n = len(nums)
        solutions = {}
        key = 0
        for x in range(n - 2):
            target = -(nums[x])
            pairs = self.threeSumHelper(nums[x+1:n], target)
            if not len(pairs) == 0:
                for pair in pairs:
                    pair.append(nums[x])
                    pair.sort()
                    if not (pair in solutions.values()):
                        if key in solutions:
                            key += 1
                        solutions[key] = pair
        return list(solutions.values())

The algorithm basically iteratively takes one number out of the list of numbers provided and sees whether there are two numbers in the remaining list that sum to the negative of the removed number (so that all three numbers sum to 0). This is done using a dictionary. Then, to avoid repetition, I sort the solutions and store them in a dictionary and return the list of values in the dictionary.

I just want to know if there is any way to make my code faster either by eliminating the need to sort each triplet or otherwise?


texts:
I tried to solve some Euler's problems, this is the solution I found for problem #3 with Python. The problem asks:

  The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

How can I improve my code?

def get_largest_prime2(value):
    start = time.clock() #used to measure the execution time
    divisors = []  #this list will be filled with all number's divisors
    i = 1
    while value != 1:
        while value%i == 0: #check if the value can be divided by i and, if so, iterate the process.
            value = (value // i)
            divisors.append(i)
            if i == 1 : break #it's needed to avoid an infinity loop
        if i >= 3: i += 2 #when i is bigger than 3, search divisors among odd numbers( this reduces the search field)
        else: i += 1
    print( time.clock()-start)
    return max(divisors) #returns the max prime divisors


texts:
In this problem we are asked:

Given a set, S, of n distinct integers, print the size of a maximal
subset, S', of  where the sum of any two numbers in it is not evenly
divisible by k.

Code
My idea is that the only relevant part are the remainders with respect to k. Additionally, for each number there is only one number that can sum up to k. So the problem can be reduced to counting the number of numbers with the same remainder and comparing to the count of its complement, and accumulating the one with the maximum value. The following picture explains the idea, for the following remainders and a value of k = 5, we need to count +1 for the 0, and then add the maximum between each pair to get the total size of the maximum set.

Also, the numbers whose remainder is 0 and the number which is the double of k can only be included once in the set.
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

int non_divisible_subset_size(int k, std::vector<int> &v) {
    if (v.begin() == v.end()) return 0;
    // Checking the remainder allows to group different numbers which have the same influence
    std::for_each(v.begin(), v.end(), [&k](auto& x){x%=k;});
    std::sort(v.begin(),v.end());
    int max_count{0};
    // Only one of the elements with remainder 0 can be added
    if (*v.begin()== 0) ++max_count;
    // Each element has only one complement that can sum up to k
    // The complement of a number betwen 0 to k/2 is located from k/2 to k-1
    // Therefore we only need to loop from (0 to k/2]
    for(auto it_lower=std::upper_bound(v.begin(),v.end(),0);
        *it_lower <= k/2;
        it_lower=std::upper_bound(v.begin(),v.end(),*it_lower))
    {
       auto it_upper = std::upper_bound(v.begin(),v.end(),*it_lower);
       int count;
       if (*it_lower*2 == k) {
           count = 1;
       }
       else {
           count = it_upper-it_lower;
       }
       int complement = k-*it_lower;
       auto it_lower_comp = std::lower_bound(v.begin(),v.end(),complement);
       auto it_upper_comp = std::upper_bound(v.begin(),v.end(),complement);
       int count_comp = count;
       if (*it_lower_comp == complement) {
           if (complement*2 == k) {
               count_comp = 1;
           }
           else {
               count_comp = it_upper_comp - it_lower_comp;
           }
       }
       max_count += std::max(count,count_comp);
    }
    return max_count;
}

int main() {
    int n, k; std::cin >> n >> k;
    std::vector<int> v;
    v.reserve(n);
    while(n--) {
        int x; std::cin >> x;
        v.push_back(x);
    }

    int result = non_divisible_subset_size(k, v);
    std::cout << result << std::endl;
    return 0;
}

Questions
The code works and I get the correct results, but it seems to be too slow to past the tests of the challenge, I'm not sure how could I optimize the speed or what is making my code so slow. I guess the slowest part is computing the remainders, maybe is not a good idea, I'm not sure. Any proposal or comment?


texts:
The task was to build a knight_moves method which when called would display the simplest path from one given square to the other given square.

My Solution:

class Square
  attr_accessor :x, :y, :children, :parent
  def initialize(x,y, parent=nil)
    @x = x
    @y = y
    @children = []
    @parent = parent
  end
end

def create_children(board)
  potentials = []
  potentials.push(
    [board.x + 2, board.y + 1],
    [board.x + 2, board.y - 1],
    [board.x + 1, board.y + 2],
    [board.x + 1, board.y - 2],
    [board.x - 2, board.y + 1],
    [board.x - 2, board.y - 1],
    [board.x - 1, board.y + 2],
    [board.x - 1, board.y - 2]
    )

  valid_children = potentials.select do |space|
    space[0].between?(0,8) &&
    space[1].between?(0,8)
  end

  valid_children = valid_children.map do |space|
    Square.new(space[0], space[1], board)
  end
  @children = valid_children
end

def knight_moves(first_square,final_square)
  first_children = Square.new(first_square[0],first_square[1])
  create_children(first_children)
  bfs(final_square, @children)
end

def bfs(search_value,children)
  queue = children

  loop do
    current = queue.shift
    if [current.x,current.y] == search_value
      display_path(current)
      break
    else
      create_children(current).each {|child| queue << child}
    end
  end
end

def display_path(current)
  parent = current.parent
  array = []
  while !parent.nil?
    array << [parent.x,parent.y]
    parent = parent.parent
  end
  array.reverse!
  array << [current.x,current.y]
  puts "Your path is:"
  array.each {|i| p i}
end

Method Call

knight_moves([2,5],[4,7])


texts: Thread synchronization and happens-before relation in simple examples

texts:
I wrote those examples to show different approaches to sharing results between threads. The whole code is on GitHub. All examples should return "Hello world".

Are these OK from the perspective of data visibility?

The most hardcore one:

import com.google.common.util.concurrent.Uninterruptibles;

import java.util.concurrent.TimeUnit;
public class WaitNotifyExample {

    static String result1;
    static String result2;

    private static final Object object = new Object();

    public static void main(String[] args) {

        Thread producer1 = new Thread() {
            @Override
            public void run() {
                Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
                result1 = "Hello";
                synchronized (object) {
                    object.notify();
                }
            }
        };

        Thread producer2 = new Thread() {
            @Override
            public void run() {
                Uninterruptibles.sleepUninterruptibly(400, TimeUnit.MILLISECONDS);
                result2 = "world";
                synchronized (object) {
                    object.notify();
                }
            }
        };

        producer1.start();
        producer2.start();

        synchronized (object) {
            while(true) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    System.out.println("Interrupted!");
                }

                System.out.println("Notified!");

                if(result1 != null && result2 != null) {
                    System.out.println(result1 + " " + result2);
                    break;
                } else {
                    System.out.println("Not ready");
                }
            }
        }

    }
}


texts:
I'm looking to optimize a simple sum calculator used in Project Euler+. The premise is simple: Find the sum of all the numbers divisible by 3 or 5 under X.

At first I did it like so:

def main(testCases):
    final_answer = []
    for x in range(testCases):
        answer = 0
        test = long(input())
        for num in range(test):
            if (num % 5 == 0 or num % 3 == 0):
                print(num)
                answer += num
        final_answer.append(str(answer))
    print('\n'.join(final_answer))
main(input())

Which worked alright. Then I realized it couldn't handle anything like 10,000,000,000 at all, which was bad, so I tried:

def main(testCases):
    for x in range(testCases):
        answer = 0
        num = input()

        Temp = (num - 1) // 3
        answer += (Temp * (3 + Temp * 3)) // 2
        Temp = (num - 1) // 5
        answer += (Temp * (5 + Temp * 5)) // 2
        Temp = (num - 1) // 15
        answer -= (Temp * (15 + Temp * 15)) // 2
        print answer
main(input())

Which was way faster / capable of giant numbers. However, it seems really ugly and unoptimized, but maybe it's in my head. Can anyone help me optimize my answer?

Sample

Input:

2
10
100

Output:

23
2318


texts: Finding common Integers between two lists

texts:
Write a method numInCommon that takes two Lists of integers as
  parameters and returns the number of unique integers that occur in
  both lists. Use one or more Sets as storage to help you solve this
  problem.

  For example, if one list contains the values [3, 7, 3, -1, 2, 3, 7, 2,
  15, 15] and the other list contains the values [-5, 15, 2, -1, 7, 15,
  36], your method should return 4 (because the elements -1, 2, 7, and
  15 occur in both lists).

I'd like feedback on how to make this code better. Are there better ways to do it? If I wasn't following the prompt (e.g. no set required), how could I find the common elements in the laziest, most efficient, best optimized, etc. way? Last but not least, does my code have any major bugs?

public static int numInCommon(List<Integer> list1, List<Integer> list2) {
        if (list1.isEmpty() || list2.isEmpty()) {
            return 0;
        } else {
            Set<Integer> setCommon = new HashSet<Integer>();
            for (Integer val : list1) {
                // add the values of list1 to the set
                setCommon.add(val);
            }
            int common = 0;
            for (Integer val : list2) {
                if (setCommon.contains(val)) {
                    // if a value in list2 exists in the set, increase common
                    common++;
                    setCommon.remove(val);
                }
            }
            return common;
        }
    }


texts: POSIX shell function for asking questions

texts:
I've written a tiny function for asking questions intended for my POSIX shell scripts, where I often need user input.

The function takes 2+ arguments, where:

Is a string containing the question.
, 3., ... = arguments containing the right answers (case insensitive)

I also changed my style by a bit, no longer use ${var} instead of just $var.

The requirement was simple: Check for exactly the answers given. So, not matching yeahh if given answer is yeah.

I also included a maybe performance-wise quick test if the user answer is in the list of answers, so answering no will not make the script iterate through all the answers and just dies at that check.

#!/bin/sh
set -u
confirmation ()
# $1    = a string containing the question
# $2,.. = arguments containing the right answers (case insensitive)
{
    question=$1; shift
    correct_answers=$*
    correct_answers_combined=$( printf '%s' "$correct_answers" | sed 's/\( \)\{1,\}/\//g' )
    printf '%b' "$question\\nPlease answer [ $correct_answers_combined ] to confirm (Not <Enter>): "
    read -r user_answer

    # this part is optional in hope it would speed up the whole process
    printf '%s' "$correct_answers" | grep -i "$user_answer" > /dev/null 2>&1 ||
        return 1

    # this part iterates through the list of correct answers
    # and compares each as the whole word (actually as the whole line) with the user answer
    for single_correct_answer in $correct_answers; do
        printf '%s' "$single_correct_answer" | grep -i -x "$user_answer" > /dev/null 2>&1 &&
            return 0
    done

    # this might be omitted, needs verification, or testing
    return 1
}

# EXAMPLE usage, can be anything, DO NOT review this part please
if confirmation 'Is dog your favorite pet?' y yes yep yeah
then
    tput bold; tput setaf 2; echo 'TRUE: You just love dogs! :)'; tput sgr0
else
    tput bold; tput setaf 1; echo 'FALSE: Dog hater, discontinuing! :('; tput sgr0
    exit 1
fi
# do other stuff here in TRUE case
echo 'And here comes more fun...'


texts: Checking if a string matches an array of valid characters

texts:
I am wondering what a better solution would be for this bit of code:

public static void main( String[] args )
{
    String name = "hello, ddd";

    boolean[] success = new boolean[ name.length() ];
    for( char character: VALID_CHARS ) {
        for( int index = 0; index < name.length(); index ++ ) {
            if( name.charAt( index ) == character ) {
                success[ index ] = true;
            }
        }
    }

    boolean failed = false;
    for( boolean b: success ) {
        if( ! b ) {
            failed = true;
        }
    }

    System.out.println( "You" + ( failed ? " failed": " succeeded" ) + "." );
}

I have an array of valid characters that can be used for a name object, I want to check if each index of the string is valid, if each index is valid return true, otherwise return false. Any help / guidance is appreciated!


texts:
I'm building an API wrapper for a bookkeeping SOAP API.

I have some questions regarding bast practice for structure of the wrapper and for error handling.

For now i've structured it like this:

EconClient.php

class EconClient {

    public function __construct()
    {
        $wsdlUrl = 'https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL';
        $this->client = new SoapClient($wsdlUrl, array("trace" => 1, "exceptions" => 1));
    }

    public function connectWithToken($token, $appToken)
    {
        $this->client->ConnectWithToken(array('token' => $token, 'appToken' => $appToken));
    }

    public function debtor()
    {
        $this->debtor = new Debtor($this->client);
        return $this->debtor;
    }

    public function debtorGroup()
    {
        $this->debtorGroup = new DebtorGroup($this->client);
        return $this->debtorGroup;
    }
}

Debtor.php

class Debtor {

    public function __construct($client)
    {
        $this->client = $client;
    }

    public function get($param, $value)
    {
        return $this->client->Debtor_GetData(array('entityHandle' => $this->getHandle($param, $value)))->Debtor_GetDataResult;
    }

    public function getHandle($param, $value)
    {
        switch ($param) {
            case 'number':
                return $this->client->Debtor_FindByNumber(array('number' => $value))->Debtor_FindByNumberResult;
                break;
            case 'email':
                return $this->client->Debtor_FindByEmail(array('number' => $value))->Debtor_FindByEmailResult;
    }
}

Is there any way i could structure this so i would'nt have to pass in the $client into the resource classes?

The only response i can get from the SOAP client except from data in case of success is exceptions. If i'm trying to fetch an ID that doesn't exist i will get an exception too. Should i try and catch these exceptions in for example Debtor.php? Or how could i structure error handling?


texts: Project Euler #14 - Longest Collatz Sequence in Python

texts:
I recently solved Project Euler Problem 14 in Python:

  The following iterative sequence is defined for the set of positive
  integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1)
  contains 10 terms. Although it has not been proved yet (Collatz
  Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

But my code takes around 45 seconds to run. I'm looking for some basic ways to make my code more efficient, specifically in the function which calculates each sequence. I have heard in other answers that I should store operations that have already been completed, but how would I do this? I also feel like the method I use for sorting the sequence numbers is clunky and could be optimized.

My code:

import time
start = time.time()

def collatzSeq (n):
    chainNumber = 1
    n1 = n
    while n1 != 1:
        if n1 % 2 == 0:
            n1 = n1/2
            chainNumber += 1
        else:
            n1 = (3*n1) + 1
            chainNumber += 1
    return [chainNumber, n]

fullList = []
for i in range(2, 1000000):
    fullList.append(collatzSeq(i))
sortedList = sorted(fullList, reverse=True)
print(sortedList[:1])

print('Time:', 1000*(time.time() - start))


texts:
The idea of this class is I would be able to limit the use of an API/method by sending it a key which would be an IP address or username and it would tell me if they are under the rate limit.

require 'time'

class RateLimit
    def initialize(time, limit)
        @reset_on = Time.now + time
        @limit = limit
        @keys = {}
    end

    def increment(key)
        reset if Time.now >= @reset_on

        if @keys[key] == nil
            @keys[key] = 1
        else
            @keys[key] += 1
        end
        return @keys[key] >= @limit
    end

    def current_level(key)
        reset if Time.now >= @reset_on
        return @keys[key]
    end

    def is_limited?(key)
        reset if Time.now >= @reset_on
        return @keys[key] != nil && @keys[key] >= @limit
    end

    def reset
        @reset_on = Time.now + @limit
        @keys = {}
    end
end

To me this seems like some pretty clean code but are there any issues I have missed or things that could be done better?


texts:
I have Matlab code that is very inefficient and I need to run it several times.
The code is basically a big parfor loop which I guess there is almost impossible to get around.

The code starts by loading several parameters and 4-D matrices, and then needs to make a few interpolations. All need to be done 5000 times (thus the parfor loop).

I simplified the code the most I could without taking out the key ingredients.

load file

nsim = 5000
T = 12;
N = 1000;

cumQx = cumsum(Qx);
cumQz = cumsum(Qz);
cumQs = cumsum(Qs);

for k=1:nsim
st(k).ksim    = kstar*ones(N, T);
st(k).Vsim  = zeros(N,T);
st(k).Psim = zeros(N,T);
end

parfor k = 1:nsim

    sysrand  = rand(T, 1);
    idiorand = rand(N, T);
    sigmarand = rand(T,1);

    xid = zeros(T, 1);
    zid = zeros(N, T);
    sid = zeros(T,1);
    xid(1) = 8;
    zid(:, 1) = 5;
    sid(1) = 1;
    % Initializing the simulation

    simx    = zeros(T,1);
    zsim    = ones(N,T)*zbar;
    simsx    = zeros(T,1);

    % Construct 3-D grid using 'ndgrid'
    [ks,zs] = ndgrid(kgrid,z);

    for j = 2:T
            sid(j) = find(cumQs(:, sid(j-1)) >= sigmarand(j), 1);
            simsx(j-1) = sigmax(sid(j));

             xid(j) = find(cumQx(:, xid(j-1)) >= sysrand(j), 1);
             simx(j-1) = x(xid(j));

             for n = 1:N
                 zid(n, j)   = find(cumQz(:, zid(n, j-1)) >= idiorand(n, j), 1);
                 zsim(n,j-1) = z(zid(n, j));
             end
            st(k).ksim(:,j)      = interpn(ks, zs , squeeze(kprime(:,xid(j),:,sid(j))),   st(k).ksim(:,j-1),zsim(:,j-1),'linear');       % K
            st(k).Vsim(:,j)      = interpn(ks, zs , squeeze(V(:,xid(j),:,sid(j))),        st(k).ksim(:,j-1),zsim(:,j-1),'linear');       % V
            st(k).Psim(:,j)      = interpn(ks, zs , squeeze(P(:,xid(j),:,sid(j))),        st(k).ksim(:,j-1),zsim(:,j-1),'linear');       % P

    end;

end

Here is a link for the matrices needed to run the code. Also a dropbox link here.

Is there any better way of doing this that would significantly reduce the computation time? My guess is no.


texts:
I tried to implement a very simple color flood fill to experiment a bit with Javascript. All comments about the code are welcome but I am especially interested in performance as it seems to be a bit slow. The browser tools only tell me that there is apparently a bunch of minor garbage collecting going on.

function setPixelColor(cvs, data, row, col, color) {
  const [red, green, blue] = color;
  data[4 * (row * cvs.width + col)] = red;
  data[4 * (row * cvs.width + col) + 1] = green;
  data[4 * (row * cvs.width + col) + 2] = blue;
  data[4 * (row * cvs.width + col) + 3] = 255;
}

function getPixelColor(cvs, data, row, col) {
  return [data[4 * (row * cvs.width + col)],
          data[4 * (row * cvs.width + col) + 1],
          data[4 * (row * cvs.width + col) + 2]];
}

function arr_eq(arr1, arr2) {
  if(arr1.length != arr2.length) {
    return false
  }

  for(let i=0; i<arr1.length; i++) {
    if(arr1[i] !== arr2[i]) {
      return false
    }
  }

  return true;
}

(function () {
  const cvs = document.getElementById("paint");
  const ctx = cvs.getContext('2d');

  // black background
  ctx.fillStyle='black';
  ctx.fillRect(0, 0, cvs.width, cvs.height);

  const imageData = ctx.getImageData(0, 0, cvs.width, cvs.height);
  const data = imageData.data;

  const start = [[40, 40, [255, 0, 0]],
                 [10, 20, [0, 255, 0]],
                 [23, 42, [0, 0, 255]],
                 [300, 333, [255, 255, 0]],
                 [200, 333, [255, 0, 255]]];

  for(point of start) {
    let [r, c, v] = point;
    setPixelColor(cvs, data, r, c, v);
  }

  let queue = start.slice(0); // clone

  while(queue.length > 0) {
    p = queue.shift();
    let [r,c] = p;
    const vcur = getPixelColor(cvs, data, r, c);
    for (const n of [[r+1,c], [r-1,c], [r,c+1], [r,c-1]]) {
      const [rn, cn] = n;
      if (rn >= 0 && rn < cvs.height && cn >= 0 && cn < cvs.width) {
        const vn = getPixelColor(cvs, data, rn, cn);
        if (arr_eq(vn, [0, 0, 0])) {
          setPixelColor(cvs, data, rn, cn, vcur);
          queue.push(n);
        }
      }
    }
  }

  for(point of start) {
    let [r, c, v] = point;
    setPixelColor(cvs, data, r, c, [0, 0, 0]);
  }

  ctx.putImageData(imageData, 0, 0);
})();
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>test</title>
  </head>
  <body>
  <canvas id="paint" width=500px height=500px />
  <script src="test.js"></script>
  </body>
</html>


texts:
I have this code:
if(listObj.Any(x => x.id < 0))
{
    foreach(ModelClass item in listObj)
    {
        if(item.id < 0)
        {
            // code to create a new Obj in the database
        }
    }
}

But, should I use like this?
foreach(ModelClass item in listObj)
{
    if(item.id < 0)
    {
        // code to create a new Obj in the database
    }
}

NOTE: It's unusual to exist id < 0 (I use this to create a temp id for manipulation in the page), but there is a possibility.

Extra info that I found:

Query transformations are syntactic
IMPROVE YOUR LINQ WITH .ANY()
MSDN Documentation - Enumerable.Any Method


texts: Improving the load time of a commit list for a specific branch and tag from a SVN repo

texts:
My app lists commits from a specific branch and tag on a SVN repo.
The commit list is afterwards transferred to the front end which is a web app.

The method for retrieving the commits takes a rather long time, around half a minute when there are around 100 commits associated with a tag.

I am using SVNKit to communicate with the SVN repository.

<dependency>
    <groupId>org.tmatesoft.svnkit</groupId>
    <artifactId>svnkit</artifactId>
    <version>1.2.3.5521</version>
</dependency>

Here are the 2 methods responsible for getting the commit list:

/**
 * get a list of all commits associated with a branch and a specific tag
 * @param branch
 * @param tag
 * @return list<Commit>
 * @throws SVNException
 */
public List<Commit> getBranchCommits(String branch, Tag tag) throws SVNException{

    List<Commit> commitList=new ArrayList<Commit>();
    @SuppressWarnings("unchecked")
    Collection<SVNLogEntry> logEntries = repository.log(new String[] {"/Assurance/branches/"+ branch }, null, -1, tag.getRevision(), true, true);

    for (Iterator<SVNLogEntry> entries = logEntries.iterator(); entries.hasNext();) {
        SVNLogEntry logEntry = (SVNLogEntry) entries.next();
        if(logEntry.getAuthor() == null || "SVN_LOGON".equals(logEntry.getAuthor().toUpperCase()))
            continue;
        Commit commit=constructCommit(logEntry);
        commitList.add(commit);
    }
    return commitList;
}

/**
 * construct the object Commit from a svn log entry
 *
 * @param logEntry
 *            a svn log entry
 * @return a constructed object Commit
 * @throws SVNException
 */
private Commit constructCommit(SVNLogEntry logEntry) throws SVNException {

    Commit commit = new Commit(logEntry.getRevision(), logEntry.getDate(), logEntry.getAuthor(), logEntry.getMessage());

    @SuppressWarnings("unchecked")
    Iterator<SVNLogEntryPath> changedPaths = logEntry.getChangedPaths().values().iterator();
    while (changedPaths.hasNext()) {
        SVNLogEntryPath entryPath = changedPaths.next();
        SVNNodeKind nodeKind=repository.checkPath(entryPath.getPath(), -1);
        if ( nodeKind != SVNNodeKind.DIR) {
            commit.getChangedPathList().add(new ChangedPath(entryPath.getPath(), entryPath.getType(), entryPath.getCopyPath()));
        }
    }
    commit.getChangedPathList().sort( new Comparator<ChangedPath>() {
        public int compare(ChangedPath o1, ChangedPath o2) {
            return o1.getPath().compareTo(o2.getPath());
        }
    });

    return commit;
}

Waiting for half a minute or even more is rather unpleasant.
Do you have any suggestions for improving this code to make it work faster?


texts: Decimal number to binary number conversion in JavaScript

texts:
I made this decimal to binary conversion as an exercise for myself and because it is obviously often asked during job interviews / tests.

Any hints concerning possible improvements welcomed.

// -- START : Testing the function --------
var display = document.querySelector('div');
var result = '';
var n = 255;
var maxSpace = n.toString().length;

// Assigning wrong parameter.
console.log('Result empty: ' + getBinaryNumber());
console.log('Result string: ' + getBinaryNumber('abc'));

// Helper function: Avoiding "stairs".
function getSpaces(count, someChar) {

  if (!count) return '';

  var ret = '';

  for (var i = 0; i < count; i++) {
    ret += someChar;
  }

  return ret;
}

var spaces = getSpaces(maxSpace, '0');

for (var i = 0; i <= n; i++) {
  result +=
    (spaces + i).slice(- maxSpace) +
    ' : ' + getBinaryNumber(i, ' ') + '
';
}

display.innerHTML = result;
// -- END : Testing the function --------

// Converts a decimal number to a binary number.

// -- Parameter --------------------------
// Number - The decimal number to convert.

// -- Return -----------------------------
// String - The number in it's binary
// represention.
// On error:
// Returns an empty string.

function getBinaryNumber (decimalNumber, separator) {
  // Parameter check
  if (decimalNumber === 0) return 0;

  if (!decimalNumber) return '';

  if (isNaN(decimalNumber)) return '';

  separator = separator || '';
  // Local variables
  var ret = [];
  var bit = decimalNumber % 2;

  ret.push(bit);

  decimalNumber = ~~(decimalNumber / 2);

  while (decimalNumber > 1) {
    bit = decimalNumber % 2;
    ret.push(bit);

    decimalNumber = ~~(decimalNumber / 2);
  }

  if (decimalNumber > 0) ret.push(decimalNumber);

  return ret.reverse().join(separator);
}


texts: Function to format numbers with thousand separators and decimals

texts:
I've wroted this function because I was getting trouble using toLocaleString() in google-apps-script, and after some refactorings I got to a working code:

function neat(numToFormat,prefThousands, prefDecimals) {

    var thousandSep = prefThousands == undefined ?  "." : prefThousands;

    var decimalSep = prefDecimals == undefined ?  "," : prefDecimals;

    function parseInput(numToFormat) {
        var isNumber = typeof(numToFormat) == 'number';
        var numberToFixed;
        if(isNumber){
            numberToFixed = numToFormat.toFixed(2);
        } else {
            //replacing "," for parseFloat precision
            if(numToFormat.indexOf(",") >-1){
                numToFormat = numToFormat.replace(",",".");
            }
          numberToFixed = parseFloat(numToFormat).toFixed(2);
        }
        return numberToFixed;
    }

    function placeThousands(wholesPart){
        /* To add thousands separators.
         * it iterates throught the
         * number in chunks of len 3.
         * adding a the setted prefered thousand separator.
         * just needed if wholesPart.length >=4
         *
         */
        var wholesLength = wholesPart.length;
        var wholesModulo = wholesLength % 3;
        //benefits from the mod equaling the slice end size needed
        //and if mod == 0 fstChunk = ""
        var fstChunk = wholesPart.slice(0,wholesModulo);
        var placed =wholesModulo !=0 ? fstChunk+thousandSep : fstChunk;
        for (var i=wholesModulo;i<wholesLength;i+=3) {
            var nextLoop = i+3;
            if(nextLoop<wholesLength) {
                var sliceBy = wholesPart.slice(i,nextLoop);
                placed += sliceBy +thousandSep;
            } else {
                sliceBy = wholesPart.slice(i,wholesLength);
                placed += sliceBy;
            }
        }
        return placed;
    }
    var numberToFixed = parseInput(numToFormat);
    var decimalPart = numberToFixed.slice(-3).replace('.',decimalSep);
    var wholesPart = numberToFixed.slice(0,(numberToFixed.length - 3));
    var needThousands = wholesPart.length >=4;
    var neat = needThousands ? placeThousands(wholesPart) + decimalPart : wholesPart + decimalPart;
    if(numberToFixed>= 9007199254740991){
        neat= "This number is too big, neatnumbers can't handle it";
    } else if(neat == "NaN") {
        neat= "neatnumbers only deals with numbers";
    }
    return neat;
}

It's restricted to 9007199254740991 because calling parseFloat() even on integers bigger than that is imprecise.

Speed is not an issue, I coded solo, so commenting is somewhat distressing since I'm afraid to restate the code.
But I'm open for criticizing on any aspects.


texts: sum of multiple piecewise functions python

texts:
suppose I have a few lists
b_wi=[[1,2,3,4],[6,7,8,9,10,11]] #b_wi is a subset of x
f_wi=[[5,4,2,7,9],[5,4,3,7,2,3,4]]
x=[[1,2,3,4,5,6,7,8,9,2,5,3],[1,24,36,42,35,6,7,8,91,2,5,3]]
#the following two are step functions formed by the above lists.

'''
F1 = f_wi[0][0] if x< b_wi[0][0] ;
     f_wi[0][1] if  x< b_wi[0][0] <=x< b_wi[0][1];
      ...;
     f_wi[0][-1] if x>= b_wi[1][-1]

F2 = f_wi[1][0] if x< b_wi[1][0] ;
     f_wi[1][1] if  x< b_wi[1][0] <=x< b_wi[1][1];
      ...;
     f_wi[1][-1] if x>= b_wi[1][-1]
'''

Now I want to get max (F1+F2) and the corresponding interval. I did some searching and found this : Evaluate sum of step functions
However, since the length of intervals is not the same for these step functions, I cannot apply the solution in the link directly. Instead, I did this:
import numpy as np
from pandas.core.common import flatten
def func(x,b,f):
    return f[np.searchsorted(b,x,side='right')]

intval= np.unique(list(flatten(b_wi)))
x=np.concatenate(([-10000],(intval[:-1]+intval[1:])/2,[10000]))  #b_wi is a subset of x. That is why I can use this.
a=np.zeros((len(x)))
for b, f in zip(b_wi,f_wi):
    a=a+ func(x,b,np.asarray(f))
print(a/2)

Now I get can get the maximum of (F1+F2) using
np.amax(a)

and I can get the interval as well.
This is just a simple example I used to illustrate my question. My actual lists are longer than these and there are 100000 step functions. Since I 'flatten' 'b_wi' in order to find the corresponding interval, the length of 'intval' becomes too large. Hence, my method is too slow. Does anyone know how I could speed it up? I feel like I am using the wrong method. Thank you very much.


texts: Properly managing a collection from deserialized XML file throughout app's lifetime

texts:
I'm developing a WinForms app to manage some settings and profiles for multiple video games. The list of video games is specified by the user, and I'm trying to figure out how to properly maintain that list/collection throughout the lifetime of my application.

I decided on an XML file to manage the games list which looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<Games>
  <Game>
    <Name>NBA 2K13</Name>
    <FolderPath>C:\Games\NBA2K13</FolderPath>
  </Game>
  <Game>
    <Name>First Person Shooter</Name>
    <FolderPath>C:\Games\FPS</FolderPath>
  </Game>
</Games>

It was suggested to me that I should not continually read/write to the XML file; instead, I should load the XML file into a collection (I'm using serialization for this), let the app work off of the collection, and then persist the collection back to the XML file when the app is closed. For the game collection class (Games), I'm also treating it as a hybrid "repository" (see the Add() method).

I came up with the following classes for that:

public class Game
    {
        [XmlElement("Name")]
        public string Name { get; set; }
        [XmlElement("FolderPath")]
        public string FolderPath { get; set; }

        public Game() {}

        public Game(string name, string folder)
        {
            Name = name;
            FolderPath = folder;
        }
    }

[XmlRootAttribute("Games")]
    public class Games
    {
        public Games()
        {
            Items = new List<Game>();
        }

        [XmlElement("Game")]
        public List<Game> Items { get; set; }

        public void Add(Game game)
        {
            if (!Items.Any(g => g.Name.EqualsIgnoreCase(game.Name)))
            {
                if (Directory.Exists(game.FolderPath))
                    Items.Add(game);
                else
                    MessageBoxUtil.ShowError("Invalid directory entered.");
            }
            else
                MessageBoxUtil.ShowError("Game names must be unique. " + game.Name + " already exists.");
        }
    }

This code seems to work fine, and loading/persisting the data is working as planned (I'd still appreciate suggestions on whether this is a good approach). What I'm struggling with is how to maintain that collection throughout the app's lifecycle. Right now, there are 2 forms that need access to this collection (Games class). Should the Games class be made static since the Items collection is derived from a single XML file and could possibly be considered global data? Would it be better to implement the singleton pattern and pass around a single instance of Games?


texts:
Edit: Licensed source can be found here.

The intent behind this class is to allow different game systems to run at their own clock rate. The physics integration rate should not be connected to the screen refresh rate, for instance. Instancing this class should allow for accurate, independent timing of separate systems.

Does this code meet that requirement?

An additional feature added while writing was access to the object's tps property, allowing for changes to operating rate during use.

from datetime import datetime

class Ticker:

    # 1,000,000; a one followed by six zeroes
    microseconds_per_second = 1000000

    def __init__(self, tps=1):
        self.tps = tps
        self._last_mark = 0
        self._accumulator = 0

    @property
    def tps(self):
        return self._tps

    @tps.setter
    def tps(self, ticks_per_second):
        assert int(ticks_per_second) == ticks_per_second
        assert 0 < ticks_per_second
        self._tps = ticks_per_second

    @property
    def last_mark(self):
        return self._last_mark

    @property
    def _microseconds_per_tick(self):
        return Ticker.microseconds_per_second / self.tps

    def tick(self):
        """Returns the number of unprocessed ticks.

        First call will initialize clock by setting first mark.
        This first call will return -1. All other calls will
        return an integer greater than or equal to zero.

        """
        if not self.last_mark:
            # Set firt time mark and exit.
            self._last_mark = datetime.now()
            return -1

        # Get dt, the change in time, and update mark.
        next_mark = datetime.now()
        dt = next_mark - self._last_mark
        self._last_mark = next_mark

        # Increment accumulator by change in time:
        #   1) the seconds, which are converted to microseconds.
        #   2) the microseconds, which total less than one second.
        self._accumulator += (dt.seconds * Ticker.microseconds_per_second)
        self._accumulator += dt.microseconds

        # Drain full ticks from accumulator and return count.
        ticks_elapsed = 0
        while self._accumulator >= self._microseconds_per_tick:
            self._accumulator -= self._microseconds_per_tick
            ticks_elapsed += 1
        return ticks_elapsed


texts: How to write this method with similar checks and multiple returns more elegantly?

texts:
I have written the following method which works as expected. But is there a way to write this more elegantly in Java 8? Appreciate any feedback. Thanks.

private String get(Details details, Value value){
    Type type = Type.getEvent(details.getType());

    if(type != null){
        if("SAMPLE".equals(type.typeDesc())){
            if(SPIN.equals(details.getSpin())){ // this if looks very similar to last line..
                return BACKUP + SAMPLE + value.getId();
            }
            return DEFAULT_VAL + SAMPLE + value.getId();
        }
        return value.getRoute();
    }
    return StringUtils.contains(details.getSpin(), SPIN) ? BACKUP : DEFAULT_VAL;
}


texts:
I have 25 branches but I'm only allowed to have 12 branches maximum. The objective of this task was to cancel out unnecessary punctuation, find the common elements that exist in the sentence and dictionary and then to translate the result into English into the other language or the other language to English, depending on what we are given. How do I lessen the number of branches of code I have?

sentence = "?hello boolean bring, !mango! and, country ban,ana wish yum  apple!"
dictionary = "a aa apple banana pear strawberry mango country wish boolean bring"
punctuation = "?!,"
language = "English"

"""answer = buwulean bringah mango countryeeh wishey apple"""

"""The above lines aren't in my final code, this is just for information
about what I'm trying to solve for."""

def translate(sentence, dictionary, punctuation, language):
    """R"""

    sentence = ' '.join([x.strip(punctuation) for x in sentence.split()])
    """Removing unnecessary punctuation"""

    dictionary = dictionary.split()
    sentence = sentence.split()
    result = []

    for element in sentence:
        if element in dictionary:
            result.append(element)

    result2 = []

    for word in result:
        if language == "English":
            if word[-1] == "y":
                word = "{}eeh".format(word)
                result2.append(word)
            elif word[-3:] == "ing":
                word = "{}ah".format(word)
                result2.append(word)
            elif word[-2:] == "sh":
                word = "{}ey".format(word)
                result2.append(word)
            elif "oo" in word:
                word = word.replace("oo", "uwu")
                result2.append(word)
            elif word == "is":
                word = "oy"
                result2.append(word)
            elif word == "are":
                word = "argh"
                result2.append(word)
            elif word == "he" or word == "she" or word == "it":
                word = "hana"
                result2.append(word)
            elif word == "his" or word == "her":
                word = "hami"
                result2.append(word)
            elif word == "ham" or word == "sausage" or word == "bacon":
                word = "{}!".format(word)
                result2.append(word)
        else:
            if word[-3:] == "eeh":
                word = word[:-3]
                result2.append(word)
            elif word[-2:] == "ah":
                word = word[:-2]
                result2.append(word)
            elif word[-2] == "ey":
                word = word[:-2]
                result2.append(word)
            elif "uwu" in word:
                word = word.replace("uwu", "oo")
                result2.append(word)
            elif word == "oy":
                word = "is"
                result2.append(word)
            elif word == "argh":
                word = "are"
                result2.append(word)
            elif word == "hana":
                word = "he"
                result2.append(word)
            elif word == "hami":
                word = "his"
                result2.append(word)
            elif word == "ham!":
                word = "ham"
                result2.append(word)
            elif word == "sausage!":
                word = "sausage"
                result2.append(word)
            elif word == "bacon!":
                word = "bacon"
                result2.append(word)
            else:
                result2.append(word)
    return " ".join(result2)

translated = translate(sentence, dictionary, punctuation, language)
print(translated)

"""The last two lines are also not in my final code"""


texts:
I created a simple 15-line number guessing game in Python 2.7:

# Guess the number game
username = raw_input("What is your name? -> ")
guess = input("%s, I'm thinking of a number between 1 and 10. -> " % username)

answer = 7 # sets the answer
answer = guess

if guess < 7:
    print "That's too low."

if guess > 7:
    print "That's too high."

if guess == 7:
    print "Good. Thanks for playing."

What is a proper way I could make it a little more efficient?


texts: Implementation of LinkedList C++ using friend

texts:
I am implementing my own linkedlist in C++ as part of a class assignment. My main concern isn't with the style of the code nor the pros/cons of including or not including certain features as I am still developing member functions.

I would mainly like to know if my approach of declaring LinkedList as a friend of Node is reasonable. My decision for doing this comes from the fact that there is absolutely no need for anything to access my Node class besides LinkedList (e.g. I don't want to be able to create a Node object in main). When I do this, however, I find myself no longer needing public and private access modifiers for Node. Furthermore, I don't particularly need getter/setter methods as I can just access Node's member variables directly from LinkedList (you can see below that I don't call Node::getVal() or Node::getNext() once).

Coming from the world of Java, it seems really strange to ever access an object's internal data directly without getters/setters. What do you guys think? Does this friend relation make sense?

template <typename T> class Node
{
    friend class LinkedList<T>;
    // private:
        Node<T>* next;  // CAN ACCESS MEMBERS DIRECTLY BECAUSE OF FRIEND DECLARATION
        T value;
    // public:
        Node<T>(T valuep)
        {
            value = valuep;
            next = NULL;
        }
        void insert(T valuep)
        {
            if(next == NULL)
            {
                next = new Node<T>(valuep);
                return;
            }
            else
            {
                next->insert(valuep);
            }
        }

        T getVal() // DON'T NEED BECAUSE OF FRIEND DECLARATION
        {
            return value;
        }
        Node<T>* getNext() // DON'T NEED BECAUSE OF FRIEND DECLARATION
        {
            return next;
        }
};

template <typename T> class LinkedList
{
    private:
        Node<T>* head;
    public:
        LinkedList<T>()
        {
            head = NULL;
        }
        ~LinkedList<T>()
        {
            Node<T>* currentNode = head;
            while(currentNode!=NULL)
            {
                Node<T>* next = currentNode->next;
                delete currentNode;
                currentNode = next;
            }
        }
        void insert(T valuep)
        {
            if (head == NULL)
            {
                head = new Node<T>(valuep);
                return;
            }
            else
            {
                head->insert(valuep);
            }
        }

        void print()
        {
            Node<T>* temp = head;
            while(temp!=NULL)
            {
               std::cout << temp->value << std::endl; // ACCESS Node's MEMBERS DIRECTLY
               temp = temp->next; // ACCESS Node's MEMBERS DIRECTLY
            }
        }

        void update(int indexp, T valuep)
        {
            if(indexp==0)
            {
                head->value = valuep; // ACCESS Node's MEMBERS DIRECTLY
            }
        }
};


texts: Function which removes a given word from a string

texts:
Any improvements? Please review.

It could be faster if I use own strstr function which searches from the end (less memory to move) but I wanted to use only the standard functions.

char *removestr(char *str, const char *word)
{
    char *ptr = str;
    size_t len = strlen(word);
    while((ptr = strstr(ptr, word)))
    {
        if(isalnum(*(ptr + len)) || (str != ptr && isalnum(*(ptr -1))))
        {
            ptr += len;
        }
        else
        {
            memmove(ptr, ptr + len, strlen(ptr + len) + 1);
        }
    }
    return str;
}


texts:
Below is my answer to the Google Code Jam's answer to the Store Credit. As usual the code run's perfectly well, however, my credit_pos function gives a warning when returning the temp array..

  You receive a credit C at a local store and would like to buy two
  items. You first walk through the store and create a list L of all
  available items. From this list you would like to buy two items that
  add up to the entire value of the credit. The solution you provide
  will consist of the two integers indicating the positions of the items
  in your list (smaller number first).

  Input

  The first line of input gives the number of cases, N. N test cases
  follow. For each test case there will be:

  One line containing the value C, the amount of credit you have at the store.
  One line containing the value I, the number of items in the store.
  One line containing a space separated list of I integers. Each integer P indicates the price of an item in the store.

  Each test case will have exactly one solution.

Link to the question

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>

int * credeit_pos(std::vector<int> v, int n, int credit);

int main(int argc, char ** argv) {

    std::ifstream infile(argv[1]);
    if(!infile) {
        std::cout << "could not open " << infile <<std::endl;
        exit(EXIT_FAILURE);
    }
    std::ofstream outfile (argv[2]);
    if(!outfile) {
    std::cout << "could not open " <<outfile << std::endl;
        exit(EXIT_FAILURE);
    }

    int num_cases, i=0, n_items, credit;
    infile >> num_cases;
    while(i < num_cases){
        infile >> credit;
        infile >> n_items;
        int price;
        std::vector<int> prices;
        for(int j=0; j<n_items; j++){
            infile >> price;
            prices.push_back(price);
        }
        int * loc = credeit_pos(prices, n_items, credit);
        outfile <<"Case #"<< i+1 <<": " << loc[0] <<" "<< loc[1] << std::endl;
        i++;
    }
}

int * credeit_pos(std::vector<int> prices, int n_items, int credit){
    int  temp[2];
    for(int i=0; i<n_items-1; i++){
        for(int j=i+1; j<n_items; j++){
            if(!(prices[i] + prices[j] == credit))
                ;
            else {
                temp[0] = i + 1, temp[1] = j + 1;
            }
        }
    }
    return temp;
}


texts:
I'll gladly appreciate it if you could review my code below and let me know if they are sufficiently secure.

My main website and these scripts will use same database, so I need to make sure they are sufficiently secure before I put them live.

Since I cannot post more than two links, I'll post my Anti-SQL Injection script, and below are the actual two scripts.

<?php
if (!function_exists('sql_inject_chec')) {
function sql_inject_chec(){
 // Anti-SQL Injection
 $badwords = array("--",";","'",'"',"DROP",
                   "SELECT", "UPDATE", "DELETE",
                   "drop", "select", "update", "delete",
                   "WHERE", "where","exec","EXEC",
                   "procedure","PROCEDURE");
 foreach($_REQUEST as $value)  {
  foreach($badwords as $word)
   if(substr_count($value, $word) > 0) {
    die("SQL Эnjection Denemesi Yaptэnэz... ama Baюarэsэz Oldunuz ;)");
    }
  }
 }
}
sql_inject_chec();
?>

Ingame registration - SCRIPT

Score display - SCRIPT


texts: C++ templated singleton class - properly destroyed?

texts:
I have written a templated singleton class in C++ but I am afraid that it is not properly destroyed. Can you advise me on that ?

my singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H

template <typename T>
class Singleton
{
public:
    static T& Instance();

protected:
    virtual ~Singleton();
    inline explicit Singleton();

private:
    static T* _instance;
    static T* CreateInstance();
};

template<typename T>
T* Singleton<T>::_instance = 0;

#endif // SINGLETON_H

singleton.cpp

#include "singleton.h"
#include <cstdlib>

template <typename T>
Singleton<T>::Singleton()
{
    assert(Singleton::_instance == 0);
    Singleton::_instance = static_cast<T*>(this);
}

template<typename T>
 T& Singleton<T>::Instance()
{
    if (Singleton::_instance == 0)
    {
        Singleton::_instance = CreateInstance();
    }
    return *(Singleton::_instance);
}

template<typename T>
inline T* Singleton<T>::CreateInstance()
{
    return new T();
}

template<typename T>
Singleton<T>::~Singleton()
{
    if(Singleton::_instance != 0)
    {
        delete Singleton::_instance;
    }
    Singleton::_instance = 0;
}

and that's how I call it (with normal - not templated or anything - class Game )
Singleton<Game>::Instance().run();


texts:
I am looking for ways to improve the code that I wrote for this.

  Consider a simple vending machine class. The machine accepts tokens
  and dispenses cans of refreshing beverages. Write a complete class (on
  the next page) as described below:

  The class has two instance data fields; one to keep track of the number of cans in the machine and one to keep track of the number of
  tokens (think coins) collected.
  There should be two constructors. One takes no arguments and starts with 50 cans and zero tokens. The other takes one argument, the
  initial number of cans in the machine.
  There should be a method to purchase a drink which adds one token to the machine and subtracts one can – assuming there are still cans in
  the machine to be purchased.
  There should be one method to add cans to the machine.
  There should be separate methods to return the number of cans remaining and the number of tokens collected.
  Write a toString( ) method to allow for easy printing of a vending machine object

public class Vendingmachine
{
    private int tokens;
    private int cans;

    public Vendingmachine()
    {
        tokens=0;

        cans=50;
    }

    public Vendingmachine( int ca)
    {
        tokens=0;

        cans=ca;

        System.out.printf(" The constructor for this %s\n", this);
    }
    public void setTokens( int coins)
    {
            tokens = coins;
    }

    public void setCans ( int ca)
    {
        cans = ca;
    }

    public void purchase( int coins)
    {
        tokens = coins;
        if (tokens >=1)
            cans = cans-tokens;
        if (cans == 0)
        addCans();
    }

    public int getTokens()
    {
        return tokens;
    }

    public int getCans()
    {
        cans = cans- tokens;
        return cans;
    }

    public void addCans()
    {

            cans =50;
    }

    public String toString()
    {
    String str = "You have purchased "+ cans  + " cans and have entered the following amount of coins: " + tokens;
    return str;
    }

}


texts: Script to load the ISS location and data

texts:
I wrote a script to fetch the location for the ISS using two simple APIs.

This is my first time writing a python script. Any advice or modifications would be highly appreciated. How is the code, and where are the areas I can improve upon?

This code is also on GitHub.

import urllib.request # to make requests to the api
import json # to parse the json response
import reverse_geocoder as rg # to get address from location

url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url) # request the api, returns a JSON object
json_result = json.loads(response.read()) # read the JSON object

# Separate different values based on keys.
people = json_result['people'] # people currently in space
number_in_space = json_result['number'] # total people in space
print("People in space : ", number_in_space)
print("----NAMES----")

for p in people:
    print(p['name'])

# ISS data
iss_url = "http://api.open-notify.org/iss-now.json"
iss_response = urllib.request.urlopen(iss_url)
iss_json_result = json.loads(iss_response.read())
# Store the positions
latitude = iss_json_result['iss_position']['latitude'] # store the latitude
longitude = iss_json_result['iss_position']['longitude']
print("Latitude: ", latitude," -- ", "Longitude: ", longitude)

address = rg.search((latitude, longitude)) # Get the address from location tuple returns a list
address_name = address[0]['name']
address_admin1 = address[0]['admin1']
address_admin2 = address[0]['admin2']
address_cc = address[0]['cc']
print("----Address----")
print(address_name, ", ", address_admin1, address_admin2, address_cc)


texts: Entity collection best practice (separation of concerns, dependency injection, ...)

texts:
I build a collection to ensure only valid entities in an array so I don't have to validate after every function / method call as I could rely on the collection to have only valid entities stored.

class WorldCollection implements Collection, ArrayAccess {

    private $container = array();
    private $oValidator;

    public function __construct (Validator $oWorldValidator) {
        $this->oValidator = $oWorldValidator;
    }

    public function offsetExists ($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetGet ($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * READ ME
     */
    public function offsetSet ($offset, $value) {
        $this->oValidator->validate($value)
        if (is_null ($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetUnset ($offset) {
        unset($this->container[$offset]);
    }
}

As I want to separate concerns and follow dependency injection I inject the Validator in the constructor of the collection and validate in the ofsetSet method to ensure only valid values will be stored.

class WorldValidator implements Validator {

    public function validate($aWorld) {
        if (!is_array($aWorld)) {
            throw new WorldValidationException('invalid type', WorldValidationException::ERROR_CODE_INVALID_TYPE);
        }

        return true;
    }
}

(The validator is simplified for example purpose.)

Did I seperate it right? Or should I handle this
kind of validation differently?
Should I catch the validation exception to not disturb the program
flow? If so should I store the exception and offer a getErrors
method?
Should I rename the collection ValidWorldCollection and extend
from WorldCollection?
Should the InvalidWorldException extend RuntimeException or
LogicException? Same for WorldValidationException in the
validator
Should I create a World Class and exclude the Validation from the
Collection using instanceof ?
Should I have used a more appropriate Spl DataStructure?
(SplObjectStorage?)  Or is it all a waste of time?


texts: PowerShell Export-CSV with Cultural Awareness

texts:
I recently had a requirement to export data to CSV in a different culture & hit an issue (see https://stackoverflow.com/a/40871162/361842).

Here's my workaround:

function ConvertTo-SpecifiedCulture {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)]
        [PSObject]$InputObject
        ,
        [Parameter(Mandatory)]
        [string]$CultureCode
        ,
        [Parameter(ParameterSetName='DefaultParameter', Position=0)]
        [System.Object[]]$Property
    )
    begin {
        [System.Globalization.CultureInfo] $Culture = [System.Globalization.CultureInfo]::GetCultureInfo($CultureCode)
    }
    process {
        if($Property -eq $null) {$Property = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames}
        $Result = new-object -TypeName PSObject -Property @{}
        $Property | Foreach-Object -Process {
            $Result | Add-Member -MemberType NoteProperty -Name $_ -Value ($InputObject."$_").ToString($Culture)
        }
        $Result
    }
}

#example usage:
Get-Process | select -first 2 | ConvertTo-SpecifiedCulture -CultureCode 'fr' | ConvertTo-CSV -Delimiter ';'
#note that CPU is displayed with a comma instead of a period when converted from EN to FR.

I've also created a proxy function for this:

# $MetaData = New-Object System.Management.Automation.CommandMetaData (Get-Command  ConvertTo-CSV)
# [System.Management.Automation.ProxyCommand]::Create($MetaData)
function ConvertTo-CulturedCSV {
    [CmdletBinding(DefaultParameterSetName='Delimiter', HelpUri='http://go.microsoft.com/fwlink/?LinkID=135203', RemotingCapability='None')]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [psobject]
        $InputObject,

        [Parameter(Mandatory,Position=1)]
        [string]
        $CultureCode,

        [Parameter(ParameterSetName='Delimiter', Position=2)]
        [ValidateNotNull()]
        [char]
        $Delimiter,

        [Alias('NTI')]
        [switch]
        $NoTypeInformation
    )

    begin
    {
        try {

            [System.Object[]]$Property = $null
            [System.Globalization.CultureInfo] $Culture = [System.Globalization.CultureInfo]::GetCultureInfo($CultureCode)
            $PSBoundParameters.Remove('CultureCode') | Out-Null

            $outBuffer = $null
            if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
            {
                $PSBoundParameters['OutBuffer'] = 1
            }
            $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('ConvertTo-Csv', [System.Management.Automation.CommandTypes]::Cmdlet)
            $scriptCmd = {& $wrappedCmd @PSBoundParameters }
            $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
            $steppablePipeline.Begin($PSCmdlet)
        } catch {
            throw
        }
    }

    process
    {
        try {
            if($Property -eq $null) {$Property = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames}
            $Fields = new-object -TypeName PSObject -Property @{}
            $Property | Foreach-Object -Process {
                $Fields | Add-Member -MemberType NoteProperty -Name $_ -Value ($InputObject."$_").ToString($Culture)
            }
            $steppablePipeline.Process($Fields)
        } catch {
            throw
        }
    }

    end
    {
        try {
            $steppablePipeline.End()
        } catch {
            throw
        }
    }
    <#

    .ForwardHelpTargetName ConvertTo-Csv
    .ForwardHelpCategory Cmdlet

    #>
}

Having to check whether $Property is null on each iteration seems clumsy; but as it's based on the pipeline input I can't think of a cleaner solution.

Also this is my first proxy function; so I've likely made some mistakes there.


texts: Comparing list elements in an effective way

texts:
I have a list of opened nodes, with each step about 3000 nodes are opened and I want to put to the opened list only those nodes that are not already there. For now I'm just comparing each new one to all of the ones already in the opened list and only add it if it's not there. But that is around n*3000^2 comparisons for the nth step and makes the progress slower and slower  each step. Is there a way to do it faster. Or at least is there a structure that would be better than ArrayList.

This is part of the bigger code, but basically the method I use:

public void addEverything() {
    List<gameState> list = current.neighbours;
    for (gameState state : list) {
        if (!isOpened(state)) {
            opened.add(state);
        }
    }
}
public boolean isOpened(gameState state) {
    for (int i = 0; i < opened.size(); i++) {
        if (state.isSame(opened.get(i)))
            return true;
    }
    return false;
}

As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same.


texts: Function that abbreviates a number (e.g. 1202 => 1.2K)

texts:
Like Twitter and Instagram and others I wanted to display numbers like 1.2K and 3.8M etc. My function works well enough but I would appreciate any input you may have.

function abbrNum (num) {
    if(typeof num !== 'number') {
        throw new TypeError('Expected a number');
    }

    var shortNumber;
    var exponent;
    var suffixes = ['K', 'M', 'B', 'T'];
    var size = (num + '').length;

    exponent = size % 3 === 0 ? size - 3 : size - (size % 3);

    if(num < 1000) {
        return num;
    } else {
        shortNumber = Math.round(10 * (num / Math.pow(10, exponent))) / 10;
    }

    if(exponent < 6) {
        shortNumber += suffixes[0];
    } else if(exponent < 9) {
        shortNumber += suffixes[1];
    } else if(exponent < 12) {
        shortNumber += suffixes[2];
    } else if(exponent < 16) {
        shortNumber += suffixes[3];
    }

    return shortNumber;
}

Update: This code (updated according to feedback) is available on npm.


texts:
As I am starting to be tired of reverse-searching in history for the C++ compile command, which I'm using - details on my flags are written here, I defined the following .bash_aliases function:

function compile-cpp {

    if [ -z "$1" ]
    then
    {
        echo "Need a file to compile as argument."
    }
    else
    {
        # extract file name from path
        filename=$(basename "$1")

        # cut the extension
        filename="${filename%.*}"

        # compile
        g++ $1 -std=c++14 -Wall -Wextra -Werror -Wpedantic -pedantic-errors -o "$filename"
    }
    fi

}

The goal was to take one cpp file as argument and compile it under the same name as the source's.

So, e.g. when I call:

compile-cpp delete.cpp

I expect it to output a file named as:

delete

In the same directory.

No problems, so far, detected by me, but as I am a C++ beginner, I can't know for sure, if this command will more or less always work.

Note: I don't wish to use a Makefile yet. The projects and various examples I work with are so little and there's so many of them, I believe it would be counterproductive.

I found the following question, probably trying to achieve somewhat similar thing:

Compile and run C++ code

But since I have different demands, looking at his code, I believe it is not its duplicate, in spite of having close to the same titles.


texts: Loop with enclosing items every 'n' steps

texts:
I'm listing elements with a foreach, and I would like to enclose items in something tag n by n:

$i = 0;
$open = $done = TRUE;
$n = 3;
$opening = "<div>";
$closing = "</div>";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff");

foreach($names as $name) { /** $condition was not a bool. My fault. */

    if($open && !($i % n)) {
        print $opening;
        $open = FALSE;
        $done = !$open;
    } elseif(!($i % n)) $done = FALSE;

    /** print element. */
    print $name;

    if(!$open && !($i % n) && !$done) {
        print $closing;
        $open = TRUE;
        $done = !$open;
    }

    $i++;

}

Do you think this snippet can be improved? It would be better to have fewer check variables such as $open or $done.


texts: Looping through questions and total score of correct answers

texts:
This loops through questions and the total score of correct answers:

AsClassName.prototype.getTotalScore = function() {
 var totalScore = 0;
 for (var i = 0; i < allQuestions.length; i++) {
  totalScore += allQuestions[i].getCalculatedScore();
   ExternalInterface.call("console.log", totalScore);
  if (currentModule.allQuestions[i].parent.questionCorrect == true) {
   knowledgePoints++;
   ExternalInterface.call("console.log", "Score Increased");
  } else {
   knowledgePoints--;
   ExternalInterface.call("console.log", "Score Decreased");
  }
 }
  debugLog("Total score: " + totalScore);
  return totalScore;
}

I have not worked with ActionScript for about 7 years. Does it have clean syntax, best practice etc? I am trying to 'add to the total score' with correct answers, and decrease with 'incorrect'.

My original Stack Overflow question describes my goal in full.


texts:
Here is my attempt at solving Project Euler problem 3. It works for test numbers up to 9 digits long, but overflows when I input the real 12-digit behemoth.

I've looked at other methods of solution, but I wanted to challenge myself to code one that doesn't search with unnecessary numbers - only primes - and never any of their factors.

I would sincerely appreciate it if someone with more coding experience could show me where in my program I am taking up a lot of memory/computational efficiency/etc.

#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
import numpy as np
import math

def lpf(n):
    orig=n #Store the original n as a reference.
    ceiling=int(math.floor(np.sqrt(n)))+1 #Don't check for prime factors larger than sqrt(n).
    thelist=[]
    for i in xrange(2,ceiling):
        thelist.append(i) #Make a list of integers from 2 up to floor(sqrt(n))+1.
    plist=[2]  #Initialize a running list of primes.
    pfpairs=[] #Initialize a list to store (prime factor, multiplicity) pairs.
    removed=[] #Initialize a list to store removed prime multiples.
    for p in plist:
        if p>=ceiling: #Again, don't check for prime factors larger than sqrt(n).
            break
        i=2
        pexp=0      #Set the multiplicity of the prime to zero initially.
        if n%p==0:  #If the prime divides n, set the new n to n/p and see if it divides again.
            #print n, p
            pexp=1
            n=n//p
            while True:
                if n%p==0: #As long as there is no remainder after division by p, keep dividing n by p,
                    n=n//p #making sure to redefine n and increment p's multiplicity with each successful divison.
                    pexp+=1
                else:
                    pfpairs.append((p,pexp)) #Once a divison fails, store the prime and its multiplicity.
                    break
        while (p*i)<=ceiling: #As long as the prime multiples dont exceed the ceiling,
            if (p*i) in removed: #if the current multiple has already been removed, move on.
                i+=1
            elif (p*i) not in thelist:
                i+=1
            else:
                removed.append(p*i) #Else, add that multiple to the removed pile, and then remove it from the list.
                thelist.remove(p*i)
                i+=1
        for number in thelist: #After all prime multiples (not including p*1) are deleted from the list,
            if number>p:       #the next number in the list larger than p is guaranteed to be prime, so set
                plist.append(number) #p to this new number and go through the logic again.
                break
    print '%d =' % orig, #Print the prime factorization of n to the user.
    for pair in pfpairs:
        if pair != pfpairs[-1]:
            print '(%d^%d) x' % (pair[0], pair[1]),
        if pair == pfpairs[-1]:
            print '(%d^%d)' % (pair[0], pair[1])
    return max(pfpairs, key = lambda pair: pair[0])[0] #Return the largest prime factor.

print lpf(78618449)

>>>
78618449 = (7^1) x (13^1) x (29^1) x (31^3)
31


texts: Correct implementation for background task execution in web application?

texts:
I have a simple servlet which merely serves some cached data back to the user.  I also have a background thread which runs at fixed intervals to refresh the cached data.  Is this a reasonable implementation?

@WebServlet("/CachingServlet")
public class CachingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static ScheduledExecutorService backgroundExecutor;
    private static String cachedData = "";

    public CachingServlet() {
        super();
    }

    @Override
    public void destroy() {
        backgroundExecutor.shutdown();
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        backgroundExecutor = Executors.newSingleThreadScheduledExecutor();
        backgroundExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                //implemention of fetchNewData() omitted for clarity
                cachedData = fetchNewData();
            }
        }, 0, 1, TimeUnit.HOURS);
        super.init();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException   {
        PrintWriter out = response.getWriter();
        out.println(cachedData);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    }
}


texts: Improving rendering performance of 2D Tile Game

texts:
I want to see if I can make any improvements to the rendering methods that are currently written. I've noticed when profiling this project that the CPU was allocating a fair percentage of the time towards rendering and was wondering if there were any improvements that I can make towards it.

Note: Below is my somewhat simple rendering method. I am rendering an ArrayList of tiles, few of these are transparent. This function (y*map.getMapWidth())+x) will return the index in the ArrayList to be rendered.

ImageManager is a class that stores cropped images from a spritesheet as a BufferedImage.

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

public class Game extends Canvas implements Runnable{

    private void renderTiles(Graphics g) {
        // the overlay variable determines if I need to render anything off screen
        // (True if player is moving)
        int overlay = 0;
        if (moving) {
            overlay = 1;
        }

        // the four variables below determine the starting/finishing x/y variables
        // to begin rendering
        int startX = -((xOffset/(Tile.TILESIZE*SCALE))+overlay);
        int finishX = -(((xOffset-(WIDTH*SCALE))/(Tile.TILESIZE*SCALE))-overlay);
        int startY = -((yOffset/(Tile.TILESIZE*SCALE))+overlay);
        int finishY = -(((yOffset-(HEIGHT*SCALE))/(Tile.TILESIZE*SCALE))-overlay);

        // to avoid crashes, the variables can't render what isn't there in the list
        if (startX < 0) {
            startX = 0;
        } if (finishX > map.getMapWidth()) {
            finishX = map.getMapWidth();
        } if (startY < 0) {
            startY = 0;
        } if (finishY > map.getMapHeight()) {
            finishY = map.getMapHeight();
        }

        // where the tiles are render. tiles are stored in an ArrayList so that
        // switching between maps is easier
        for (int y = startY; y < finishY; y++) {
            for (int x = startX; x < finishX; x++) {
                map.tile.get((y*map.getMapWidth())+x).render(g);
            }
        }
    }

    public void render(){
        BufferStrategy bs = this.getBufferStrategy();
        if(bs ==  null){
            createBufferStrategy(2);
            return;
        }
        Graphics g = bs.getDrawGraphics();
        // start rendering

        g.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
        renderTiles(g);
        player.render(g);
        g.dispose();
        bs.show();

    }
}

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public abstract class Tile {

    public static final int TILESIZE = 16;

    protected BufferedImage bi;
    protected ImageManager im;
    protected int x, y, oX, oY;
    protected Game game;

    public Tile(int x, int y, ImageManager im, Game game, BufferedImage bi){
        this.oX = x;
        this.oY = y;
        this.im = im;
        this.game = game;
        this.bi = bi;
    }

    public abstract void tick();
    public abstract void render(Graphics g);

}

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class WalkableTerrainTile extends Tile{

    public WalkableTerrainTile(int x, int y, ImageManager im, Game game, BufferedImage bi) {
        super(x, y, im, game, bi);
    }

    public void tick() {
        this.game  = game;
        x = oX + game.xOffset;
        y = oY + game.yOffset;
    }

    public void render(Graphics g) {
        g.drawImage(bi, x, y, Tile.TILESIZE * Game.SCALE, Tile.TILESIZE * Game.SCALE, null);
    }

}


texts: Which is the most correct pattern for using Stack.Pop?

texts:
There at least 2 patterns of using Stack.Pop

private Stack<T> availableResources;
...
if (availableResources.Count > 0)
{
  resource = availableResources.Pop();
  ...
}

private Stack<T> availableResources;
...
try
{
  resource = availableResources.Pop();
  ...
}
catch (InvalidOperationException e)
{
  ...
}

I'd like to ask people, which of 2 is preferable? If possible, argument your answer.


texts:
I made a 16 character code generator. It works like a charm now, but I was wondering if there's any way to do it more efficiently.

public partial class MainWindow : Window
{

    //Globals
    string[] Letters = new string[27] { "A", "B", "C", "D", "E", "F", "G", "H", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    string[] Numbers = new string[9] { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

    Random r = new Random();
    int i = 0;
    int a = 0;

    private string[] generateCode()
    {

        string[] RL = new string[9];
        string[] RN = new string[9];

        //Random letters
        while (i < 9)
        {
            RL[i] = Letters[r.Next(0, Letters.Length - 1)];
            i++;
        }
        //Random numbers
        while (a < 9)
        {
            RN[a] = Numbers[r.Next(0, Numbers.Length - 1)];
            a++;
        }

        TextBox.Text = String.Format("{0}{1}{2}{3}-{4}{5}{6}{7}-{8}{9}{10}{11}-{12}{13}{14}{15}", RN[0], RL[1], RN[1], RL[2], RN[2], RL[3], RN[3], RL[4], RN[4], RL[5], RN[5], RL[6], RN[6], RL[7], RN[7], RL[8], RN[8]);

        //Resetting the while loop
        i = 0;
        a = 0;

        //Clipboard
        Clipboard.SetText(TextBox.Text);
        Message.Content = ("Copied to clipboard!");

        return RL;
    }

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Generate_Click(object sender, RoutedEventArgs e)
    {
        generateCode();
    }


texts: Structured use of Android SQLite transactions

texts:
I got tired of following Android-SQLite's transaction idiom, briefly documented here.

It requires too much boilerplate code, IMHO, especially when you add the obligatory null checks. So I came up with this pattern, inspired by the Objective-C library FMDB:

// Inside the class that manages the database
interface Transaction {
    // return false to rollback
    boolean execute(SQLiteDatabase db);
}

boolean doTransaction(Transaction transaction) {
    boolean success = false;
    SQLiteDatabase db = null;
    try {
        db = mHelper.getWritableDatabase();

        if (db != null) {
            db.beginTransaction();

            success = transaction.execute(db);

            if (success) {
                db.setTransactionSuccessful();
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    return success;
}

Usage:

// In a method in that same database-managing class
doTransaction(new Transaction() {
    @Override
    public boolean run(SQLiteDatabase db) {
         // ... write to db ...
         return true; // or false to rollback
    }
});

Of course, both the Transaction interface and the doTransaction() method can be made available to other classes.

Does this look like a good idea? There are probably complex transactions that can't use it, but so far all of my transactions fit.

Am I missing something important with this pattern, like forgetting to close something, handle exceptions, etc? Or maybe it's just not "The Java Way" or "The Android Way" of doing things?