texts: Simple OOP currency converter - follow-up

texts:
This is a follow up question on this post
This is what I changed on my previous code:

I use Exchanger and PairCurrency class instead of Bank

I renamed addRate and addCommission to setRate and setCommission respectively

Exchanger object contains multiple PairCurrency objects which can be added to Exchanger by addPairCurrency() method.

This is my code and tests:
import pytest

class DuplicatePairError(Exception):
    pass

class Exchanger:
    def __init__(self):
        self.pair_currencies = []
        self.commission = 0.015

    def addPairCurrency(self, pair_object):
        if pair_object in self.pair_currencies:
            raise DuplicatePairError('Cannot add duplicate pair of currency')

        self.pair_currencies.append(pair_object)

    @property
    def last_pair(self):
        return self.pair_currencies[-1]

    def getRate(self, pair):
        for pair_obj in self.pair_currencies:
            if pair_obj.name == pair:
                return pair_obj.rate

    def convert(self, src_dest, amount):
        return amount / self.getRate(src_dest) * (1-self.commission)

    def editRate(self,new_object):
        for pair_obj in self.pair_currencies:
            if pair_obj.name == new_object.name:
                 pair_obj.rate = new_object.rate

class PairCurrency:

    def __init__(self, name):
        self.name = name

    def setRate(self, rate):
        self.rate = rate

    def editRate(self, new_rate):
        self.rate = new_rate

    def __eq__(self, object):
        return self.name == object

def test_canInitializePair_CurrenciesListInExhangeClass():
    exchanger = Exchanger()

    assert exchanger.pair_currencies == []

def test_canSetRateinPairCurrencyClass():
    USD_GBP = PairCurrency('USDGBP')
    USD_GBP.setRate(2)

    assert USD_GBP.name == 'USDGBP'
    assert USD_GBP.rate == 2

def test_canSetCommisionInExchanger():
    exchanger = Exchanger()

    assert exchanger.commission == 0.015

@pytest.fixture()
def USD_GBP():
    USD_GBP = PairCurrency('USDGBP')
    USD_GBP.setRate(2)
    return USD_GBP

@pytest.fixture()
def GBP_USD():
    GBP_USD = PairCurrency('GBPUSD')
    GBP_USD.setRate(0.5)
    return GBP_USD

@pytest.fixture()
def exchanger(USD_GBP,GBP_USD):

    exchanger = Exchanger()
    exchanger.addPairCurrency(USD_GBP)
    exchanger.addPairCurrency(GBP_USD)
    return exchanger

def test_canAddPairCurrencyinExchangerClass(exchanger, USD_GBP, GBP_USD):

    assert USD_GBP == exchanger.pair_currencies[-2]
    assert GBP_USD == exchanger.last_pair

def test_cannotAddDuplicatePair(exchanger, USD_GBP):
    USD_GBP2 = PairCurrency('USDGBP')
    USD_GBP2.setRate(5)

    exchanger = Exchanger()
    exchanger.addPairCurrency(USD_GBP)
    with pytest.raises(DuplicatePairError) as excinfo:
        exchanger.addPairCurrency(USD_GBP2)
    assert str(excinfo.value) == 'Cannot add duplicate pair of currency'

def test_canEditRateInPairCurrencyClass(USD_GBP):

    USD_GBP.editRate(3)
    assert USD_GBP.rate == 3

    USD_GBP.editRate(4)
    assert USD_GBP.rate == 4

def test_canEditRateinExhangerClass(exchanger):
    USD_GBP = PairCurrency('USDGBP')
    USD_GBP.setRate(5)
    exchanger.editRate(USD_GBP)
    assert exchanger.getRate('USDGBP') == 5

def test_canConvertInExchangerClass(exchanger, USD_GBP, GBP_USD):

    assert exchanger.convert(src_dest = 'USDGBP', amount = 100) == 49.25
    assert exchanger.convert(src_dest='GBPUSD', amount=100) == 197

I have few questions:

How good is my OOP design?

Is my test list fine?

Should I remove editRate() in PairCurrency and just keep editRate() in Exchanger?

Do my classes violate the SOLID Principle ?

What I have to fix to improve my code and OOP design ?


texts: Cracking the coding interview 1.7 - Rotate matrix by 90 degrees

texts:
The question asks to rotate an image/matrix by 90 degrees. Ideally it asks to do it in place but before that I decided to do it using extra space because this is my first time working with matrices.

question:
while using extra space, could this have been any better?

def rotate_m1(matrix, d):
    """
    with extra space
    for each row in the orginal matrix, the items position in that row
    will be its row in the new matrix. Its position in the new row will be determined
    by 'l' (matrix row length), which decrements after each loop.

    e.g.
    1,2
    3,4

    the loop goes through and maps the top row to the outside of a new matrix. i.e.

    i = 0 # row
    j = 0 # col // its postion in the row
    l = d-1 # d = the dimensions of the matrix
    matrix[i][j] = 1

    in the new matrix the postion of matrix[i][j] (1) will be:

    new_matrix[j][l]; j being its postion in its original row, so in this case 1 was in postion 0 in
    the original matrix, and l is the outermost row of the new matrix becuse (in this example) during
    the first loop l = 2-1.

    after the first row is mapped, we take one away from l to map the next row to the row before
    the outer most row in the new matrix (d-2)
    """

    m2 = [[0 for x in range(d)] for y in range(d)] # construct new matrix
    l = d-1

    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            m2[j][l] = matrix[i][j]

        l -= 1
    print m2

input/ouptut:

input:
[[1,2,3],
[4,5,6],
[7,8,9]]

output:
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]

I've added some extra info about how I came to the solution in the code comment.


texts:
Mostly robocop and hound give "line is too long" for such code statements. I just wanted to know which one is better and preferable way.

This one is a way to avoid making the message long so just do multiple string interpolation:

timeGet = "after #{getTime2(online, offline)}"

logs[index].extra = {message: "Camera came online #{timeGet}"}

This next one is to not do multiple string interpolation but just expand the JSON object to the new line to avoid "line is too long". What do you think is a good and preferable way of coding?

logs[index].extra = {
  message: "Camera came online after #{getTime2(online, offline)}"
}


texts:
Is this a good implementation?

static int[] mergeSort(int[] arr) {
    if (arr.length <= 1) {
        return arr;
    }

    int[] left, right;

    left = Arrays.copyOfRange(arr, 0, arr.length / 2);
    right = Arrays.copyOfRange(arr, arr.length / 2, arr.length);

    left = mergeSort(left);
    right = mergeSort(right);

    return merge(left, right, arr);

}

private static int[] merge(int[] left, int[] right, int result[]) {

    int i = 0, j = 0, z = 0;

    while (i < left.length && j < right.length) {
        if (left[i] <= right[j]) {
            result[z++] = left[i++];

        } else {
            result[z++] = right[j++];

        }
    }

    while (i < left.length) {
        result[z++] = left[i++];

    }
    while (j < right.length) {
        result[z++] = right[j++];

    }
    printArr(result);
    return result;

}


texts:
I was wondering if someone could look at my animation for me to see if I am doing it correctly.  I am currently programming a basic game in Java, nothing fancy though, and I just want to get the basics down before venturing into something more complex.

Right now, I want to animate a character's attack.  When the player left clicks, the character should go from looking like this:

To looking like this:

Currently, I am doing this by starting this thread when a left-click happens:

public class thread implements Runnable
{
    long swordTime = 250;
    public void run()
    {
        try {
            player.setAttacking(true);
            Thread.sleep(swordTime);
            player.setAttacking(false);
            Thread.yield();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Which changes a boolean variable attacking.  Afterwards, when the character is rendered again, attacking will be true, so the variable will be rendered as the image with this code:

public void render(Graphics g)
{

    if (attacking)
    {
        ImageIcon i = new ImageIcon("/Users/myName/Desktop/FarthornPics/charAttacking.png");
        Image attckImg = i.getImage();
        g.drawImage(attckImg, (int)Game.WIDTH/3, (int)y, null);
    }
    else
        g.drawImage(charImage, Game.WIDTH/3, (int)y, null);

Although this method works, I was wondering if there was a better way to accomplish this.  People often tell me that multi-threading is kind of a crude way to go about things, so I was looking for a better alternative (if this is not already the best).


texts: Creating an associated object on create/update

texts:
My app is setup where there are musical artists and albums have message boards through a has_one polymorphic association.

class Artist < ApplicationRecord
  has_one :board, as: :boardable, dependent: :destroy

  after_create -> (artist) { BoardGenerator.create(artist) }
  after_update -> (artist) { BoardGenerator.update(artist) }
end

class Album < ApplicationRecord
  has_one :board, as: :boardable, dependent: :destroy

  after_create -> (album) { BoardGenerator.create(album) }
  after_update -> (album) { BoardGenerator.update(album) }
end

class Board < ApplicationRecord
  belongs_to :boardable, polymorphic: true, optional: true
end

For every artist and album created, I'd like to create a message board associated to it. I decided to accomplish this using the after_create/after_udpate callbacks where business logic is extracted to a service object:

class BoardGenerator
  def self.create(boardable)
    boardable.board = Board.create(name: boardable.name)
  end

  def self.update(boardable)
    boardable.board.update_attribute(:name, boardable.name)
  end
end

One of my main concerns is that the create/update methods are dependent on both models having a name attribute. Is there any way to mitigate the risk of this ever changing between the two?

I'm trying to get in the habit of creating single responsibility models (hence the service object). Still new to the concept though. Can someone tell me if I'm on the right track and/or how to improve the code I have now?


texts:
I am learning Python and I tried to do a program to find K points from a set of N points, farthest as much as possible (I'm not sure if this is the case).

I'd like to know if my code is not redundant, or if the code can be improved.

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import euclidean

def dist_ponto_cj(ponto,lista):
    return [ euclidean(ponto,lista[j]) for j in range(len(lista)) ]

def ponto_mais_longe(lista_ds):
    ds_max = max(lista_ds)
    idx = lista_ds.index(ds_max)
    return pts[idx]

N = 80
K = 40
farthest_pts = [0]*K
print( 'N = %d, K = %d' % (N, K))

#x=[ np.random.randint(1,N) for p in range(N)]
#y=[ np.random.randint(1,N) for p in range(N)]
x=np.random.random_sample((N,))
y=np.random.random_sample((N,))
pts = [ [x[i],y[i]] for i in range(N)]

P0 = pts[np.random.randint(0,N)]
farthest_pts[0]=P0
ds0 = dist_ponto_cj(P0,pts)

ds_tmp = ds0
#print ds_tmp
for i in range(1,K):
    #PML =
    farthest_pts[i] = ponto_mais_longe(ds_tmp)
    ds_tmp2 = dist_ponto_cj(farthest_pts[i],pts)
    ds_tmp = [ min(ds_tmp[j],ds_tmp2[j]) for j in range(len(ds_tmp))]
    print ('P[%d]: %s' % (i,farthest_pts[i]))

#print farthest_pts

xf=[ farthest_pts[j][0] for j in range(len(farthest_pts))]
yf=[ farthest_pts[j][1] for j in range(len(farthest_pts))]

fig, ax = plt.subplots()
plt.grid(False)
plt.scatter(x,y,c='k',s=4)
plt.scatter(xf,yf,c='r',s=4)
plt.show()


texts: Makefile for C++ OpenGL with GLFW and glad

texts:
This is a makefile I wrote to compile a simple OpenGL test project which is going to use the libraries GLFW and the C library glad.c.

CC = gcc
CXX = g++

COMPILE_FLAGS = -Wall -ggdb -O3
LINK_FLAGS = -lglfw3 -lopengl32 -lglu32 -lgdi32

glfw = d:/external/glfw-3.1
glfw_inc = $(glfw)/include
glfw_lib = $(glfw)/lib64

glad = d:/external/glad-c
glad_inc = $(glad)/include

INCLUDES = -I$(glfw_inc) -I$(glad_inc)
LIBRARIES = -L$(glfw_lib)

cpp_files = main.cpp
objects = $(cpp_files:.cpp=.o)
headers =

all: main.exe

main.exe: $(objects) glad.o
        $(CXX) $(LIBRARIES) -o main.exe $(objects) glad.o $(LINK_FLAGS)

$(objects): %.o: %.cpp $(headers) makefile
        $(CXX) $(COMPILE_FLAGS) $(INCLUDES) -c -o $@ $<

glad.o: glad.c
        $(CC) $(COMPILE_FLAGS) $(INCLUDES) -c -o glad.o glad.c

Since this is basically the first makefile I wrote, I could surely use some criticism as to what is good style and what isn't. I also wonder if there is a more elegant way to handle the fact that glad is actually a C library and has to be compiled with gcc instead of g++, but g++ is used for everything else.


texts: Writing a set of JavaScript conditionals more efficiently

texts:
There must be a better way to write this, maybe with a switch statement (which for some reason I can't get to work).  Basically, if one of the conditionals is true then the class in the statement is executed.  So, in this case, one or any number of combinations could be true.

if (stepOneEdited) {
    $(stepOne).addClass("complete");
}
if (stepTwoEdited) {
    $(stepTwo).addClass("complete");
}
if (stepThreeEdited) {
    $(stepThree).addClass("complete");
}
if (stepFourEdited) {
    $(stepFour).addClass("complete");
if (stepFiveEdited) {
    $(stepFive).addClass("complete");
    $(stepSix).addClass("complete");
}


texts:
I have a very basic method at the moment that fills text boxes with data relevant to the selected company. I load the data into a DataGrid using this method;

CompanyDataService

namespace SdcDatabase.Controller
{
    class CompanyDataService
    {
        public DataTable GetCompanyList()
        {
            string constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
            using (var dbfCon = new OleDbConnection(constr))
            {
                dbfCon.Open();
                using (var myQuery = dbfCon.CreateCommand())
                {
                    myQuery.CommandText = "SELECT cm_name, cm_addr1, cm_addr2, cm_town, cm_county, cm_pcode, cm_tel1, cm_tel2, cm_fax, cm_email FROM compns ORDER BY cm_name";
                    var dTable = new DataTable();
                    var dataAdapter = new OleDbDataAdapter(myQuery);
                    dataAdapter.Fill(dTable);
                    return dTable;
                }
            }
        }
    }
}

After the data is inside the DataGrid I then load the data into the textboxes based upon the company selected. I do this using this method;

FillCompanyListTextBoxes

        private void FillCompanyListTextBoxes(object sender, SelectionChangedEventArgs e)
    {
        DataRowView dv = (DataRowView)dataGrid.SelectedItem;
        if (dv != null)
        {
            FillCompanyDetailsTextBoxes();
            compDetailsLabel.Content = "Details for: " + dv.Row.ItemArray[0].ToString();
            compNameTextBox.Text = dv.Row.ItemArray[0].ToString(); //Company Name
            compAddr1TextBox.Text = dv.Row.ItemArray[1].ToString(); //Company Addr1
            compAddr2TextBox.Text = dv.Row.ItemArray[2].ToString(); //Company Addr2
            compTownTextBox.Text = dv.Row.ItemArray[3].ToString(); //Company Town
            compCountyTextBox.Text = dv.Row.ItemArray[4].ToString(); //Company County
            compPcodeTextBox.Text = dv.Row.ItemArray[5].ToString(); //Company Post Code
            compTelTextBox.Text = dv.Row.ItemArray[6].ToString(); //Company Telephone
            compAltTelTextBox.Text = dv.Row.ItemArray[7].ToString(); //Company Alt Tel
            compFaxTextBox.Text = dv.Row.ItemArray[8].ToString(); //Company Fax
            compEmailTextBox.Text = dv.Row.ItemArray[9].ToString(); //Company Email
        }
    }

FillCompanyDetailsTextBoxes is simply a method that loads that data into textboxes in the next tabitem, allowing the user update the companies details if necessary.

I know the second method isn't great. It works and it doesn't look overly disturbing but many problems would be encountered if for some reason the column numbers changed and then all the text boxes would have a domino effect and all be in the wrong place.

Basically my question is this, is there a better way?


texts: Dispatcher for a JSON API without routes

texts:
I am using this code for a fast JSON API without routes.

Does this code contain any useless parts?  Is the class loader efficient enough? Are there any better options? Is ReflectionMethod slow if used once?

<?php

/*
 * Init stuff
 */

session_start();

define('ROOT', realpath( dirname(__FILE__) ) . '/');
set_include_path(ROOT . 'src/');

spl_autoload_extensions('.php');
spl_autoload_register();

ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
ini_set('display_errors',  1); //To change in prod to 0 <<<<<<<<<<<<<<<<<<<<<<<<<
ini_set('log_errors',      1);
ini_set('error_log',       ROOT . 'tmp/logs/application.log');

date_default_timezone_set('Europe/Paris');

/*
 * Process stuff
 */

$params      = explode( '/', trim( key($_GET), '/' ) );
$paramsCount = count($params);

if ($paramsCount >= 2) {
  try {
    $controllerMethod = new ReflectionMethod( '\app\controller\\' .
                                                  $params[1], $params[2]
                                                );

    if ($paramsCount - 2 >= $controllerMethod->getNumberOfRequiredParameters()) {

      \ens\controller\Request::$lang =& $params[0];
      \ens\controller\Request::$data =& $_POST;

      $response = $controllerMethod->invokeArgs( null, array_splice($params, 3) );

    } else {
      $response = array('status' => 400);
    }

  } catch (ReflectionException $e) {
    $response = array('status' => 300);
  }

} else {
  $response = array('status' => 301);
}

if (!headers_sent()) {
  header('Content-Type: application/json');
}

echo json_encode($response);


texts: Mouse input handler which exposes read-only mouse state data

texts:
I have a MouseInputHandler class that registers itself to an InputManager. When the InputManager class receives events they are forwarded to MouseInputHandler which changes its state to reflect the state of the mouse. A mouse as an input device provides a large number of different properties that should be easy to read, but impossible to write to.

The problem is that C++ fails to provide a keyword otherwise similar to const but that grants full write access to functions in the same scope.

class MouseInputHandler : public InputHandler
{
public:
    MouseInputHandler(ResourceContext &context)
        : btnLeft(btnLeft_), btnMiddle(btnMiddle_), btnRight(btnRight_),
          btnX1(btnX1_), btnX2(btnX2_), absX(absX_), absY(absY_), relX(relX_),
          relY(relY_), scrollX(scrollX_), scrollY(scrollY_) {}
    void handleEvent(SDL_Event &mouseEvent);
    void refresh();

    const Signal &btnLeft, &btnMiddle, &btnRight, &btnX1, &btnX2;
    const int32_t &absX, &absY, &relX, &relY, &scrollX, &scrollY;
protected:
    Signal btnLeft_, btnMiddle_, btnRight_, btnX1_, btnX2_;
    int32_t absX_, absY_, relX_, relY_, scrollX_, scrollY_;
};

Options I have identified at this point:

Declaring the members private or protected and providing public const references to the non-public members that only allow read access (as in the example above). However with 11 members, the class quicly becomes a mess, with 11 const references (that also require 11 reference initializations in the constructor's initializer list).
Adding getter methods for every member variable. More cumbersome than the const references, but with the (marginal) added benefit that the members are now accessible as functions.
Placing the buttons and integers in (private or protected) arrays and adding an enum that gives indexes to the array elements meaningful names. To access the members, two (one getter for buttons, other for ints) getter functions that take the index and return a const reference are added to the class. This seems to me quite complex and error prone in comparison to the other solutions.
Just not caring about const correctness at all and making the member variables fully accessible.
Refractoring the code. I don't see how one could refractor a mouse, or simplify the interface, but any suggestions are welcome.


texts:
Imagine you are a company that wants to assist some US-based companies
  to ship their goods to customers in Hamburg. To achieve this, lets
  assume that every order can be represented by a tuple (orderId,
  companyName, customerAddress, orderedItem).

  Thus, some sample data might look like this:

001, SuperTrader, Steindamm 80, Macbook
002, Cheapskates, Reeperbahn 153, Macbook
003, MegaCorp, Steindamm 80, Book "Guide to Hamburg"
004, SuperTrader, Sternstrasse 125, Book "Cooking 101"
005, SuperTrader, Ottenser Hauptstrasse 24, Inline Skates
006, MegaCorp, Reeperbahn 153, Playstation
007, Cheapskates, Lagerstrasse 11, Flux compensator
008, SuperTrader, Reeperbahn 153, Inline Skates

  Instructions:

  Using node.js, please implement a working solution to perform the following kind of operations on the data:

  show all orders from a particular company
  show all orders to a particular address
  delete a particular order given an OrderId
  display how often each item has been ordered, in descending order (ie in the above example, 2x for Macbook and Inline skates, 1x for the rest)

  Note:

  Please optimize your code and do not convolute it with handling
  exceptions/edge cases – we are more interested in readability for this
  solution.

Solution:

const data = [
  // orderId, company, custAddr, product
  ['001', 'SuperTrader', 'Steindamm 80', 'Macbook'],
  ['002', 'Cheapskates', 'Reeperbahn 153', 'Macbook'],
  ['003', 'MegaCorp', 'Steindamm 80, Book', 'Guide to Hamburg'],
  ['004', 'SuperTrader', 'Sternstrasse 125', 'Book "Cooking 101"'],
  ['005', 'SuperTrader', 'Ottenser Hauptstrasse 24', 'Inline Skates'],
  ['006', 'MegaCorp', 'Reeperbahn 153', 'Playstation'],
  ['007', 'Cheapskates', 'Lagerstrasse 11', 'Flux compensator'],
  ['008', 'SuperTrader', 'Reeperbahn 153', 'Inline Skates'],
];

// show all orders from a particular company
const allCompanyOrders = (orders, company) => { // O(n)
  return orders.filter((o) => o[1] === company);
};

// all orders to an address
const allOrdersToAddress = (orders, address) => { //O(n)
  return orders.filter((o) => o[2] === address);
};

// delete an order
const removeOrder = (orders, id) => { // O(n)
  const result = [];
  orders.forEach((o) => {
    if (o[0] !== id) {
      result.push(o);
    }
  });
  return result;
};

const itemsCount = (orders) => {
  const map = Object.create(null);
  orders.forEach((o) => {
    const name = o[3];
    const count = map[name] || 0;
    map[name] = count + 1;
  });
  return map;
};

//show often ordered items in descending ordered
const showMostFrequent = (orders) => {
  const map = itemsCount(orders);
  const result = [];

  const keys = Object.keys(map);
  for (let name of keys) {
    const count = map[name];
    result.push({name, count});
  }

  // O(nlogn) + O(n) memory
  return result.sort((a, b) => b.count - a.count)
    .map((o) => o.name);
};

console.log(allCompanyOrders(data, 'SuperTrader').length === 4);
console.log(allOrdersToAddress(data, 'Reeperbahn 153').length === 3);
console.log(removeOrder(data, '007').length === 7);
console.log(showMostFrequent(data));

Questions:

Should I preprocess data for optimisation at cost of memory?
Right now I have to use indexes everywhere which feels uncomfortable.


texts: Decorator to cache a function result for some time

texts:
I recently played around with a script that got some data from the Google API. As I didn't want to spam requests at the service (and potentially get blocked), I made this decorator, which caches the result of a function for a specified amount of time. Any call after the time-to-live (TTL) will call the function again.

This is the first decorator I wrote that takes an optional argument (the time to keep the cache). That code was taken from this StackOverflow answer by @Eric. I also couldn't abstain from using the new walrus operator (Python 3.8+), since I'm always looking for opportunities to use it in order to get a better feel for it.

Any and all advice on how to make this better or more readable are welcome.

from datetime import datetime
from functools import wraps

DEBUG = True

def temporary_cache(*args, ttl=60):
    """A decorator that ensures that the result of the function call
    is cached for `ttl` seconds (default: 60).

    Warning: The returned object is stored directly, mutating it also mutates the
    cached object. Make a copy if you want to avoid that.
    """
    def decorator(func):
        func.cache = None
        func.cache_time = datetime.fromordinal(1)

        @wraps(func)
        def inner(*args, **kwargs):
            if ((now := datetime.now()) - func.cache_time).total_seconds() > ttl:
                func.cache = func(*args, **kwargs)
                func.cache_time = now
            elif DEBUG:
                # for debugging, disable in production
                print("Cached", func.__name__)
            return func.cache
        return inner
    if len(args) == 1 and callable(args[0]):
        return decorator(args[0])
    elif args:
        raise ValueError("Must supply the decorator arguments as keywords.")
    return decorator

Example usages:

import time

@temporary_cache
def f():
    return datetime.now()

@temporary_cache(ttl=1)
def g():
    return datetime.now()

if __name__ == "__main__":
    print(f())
    # 2020-05-12 10:41:18.633386
    time.sleep(2)
    print(f())
    # Cached f
    # 2020-05-12 10:41:18.633386

    print(g())
    # 2020-05-12 10:41:20.635594
    time.sleep(2)
    print(g())
    # 2020-05-12 10:41:22.636782

Note that f was still cached, while g was not, because the TTL is shorter than the time between calls.


texts:
Here's a password generator I created.

### THIS PROGRAM WAS CREATED FOR LEARNING PURPOSES  ###
###   AND SHOULD NOT BE USED TO CREATE PASSWORDS!   ###

import string
from enum import Enum
from random import randint, shuffle, choice

class PasswordError(Exception):
    __module__ = Exception.__module__

# Types of characters possible
class Types(Enum):
    CAP = 'CAP' # Capital
    SMA = 'SMA' # Small
    DIG = 'DIG' # Digits
    SPE = 'SPE' # Special

# Characters for each type of possible characters
type_chars = {
    Types.CAP: string.ascii_uppercase,
    Types.SMA: string.ascii_lowercase,
    Types.DIG: string.digits,
    Types.SPE: '!()-.?[]_`~;:@#$%^&*='
}

def password_generator(min_length=6, max_length=20, caps=1, small=1, digits=1, special=1):
    types = {
        Types.CAP: caps,
        Types.SMA: small,
        Types.DIG: digits,
        Types.SPE: special,
    }

    num_chars = sum(list(types.values())) # Number of mandatory characters
    min_length = max(num_chars, min_length) # In case 'num_chars' is greater

    # Number of characters required for each possible type of character
    # Is greater than maximum possible length
    if min_length > max_length:
        raise PasswordError(f'No password with the given criteria')

    length = randint(min_length, max_length)

    # List that stores the "types" of possible character
    char_list = []

    # Mandatory requirements
    for typ, val in zip(types.keys(), types.values()):
        char_list.extend([typ] * val)

    # The remaining values to fill
    for rem in range(length - num_chars):
        char_list.append(choice(list(types.keys())))

    shuffle(char_list)

    password = ''

    for typ in char_list:
        password += choice(type_chars[typ])

    return password

if __name__ == '__main__':
    min_length = int(input('Minimum number of characters required: '))
    max_length = int(input('Maximum number of characters possible: '))

    print()

    caps = int(input('Number of capital letters required: '))
    small = int(input('Number of small letters required: '))
    digits = int(input('Number of digits required: '))
    special = int(input('Number of special characters required: '))

    print()

    number = int(input('Number of passwords required: '))

    print('\n' + '-' * 50 + '\n')
    print('   Here are your passwords: \n')

    for i in range(number):
        print(password_generator(min_length, max_length, caps, small, digits, special))

You can also modify the mandatory types of characters (Like 3 caps, 2 digits, etc). Also, minimum length and maximum length can be specified.

I think this code looks a bit ugly. How do I improve this?


texts: Checking winning conditions in a Connect Four game

texts:
I'm trying to refactor this C# code that uses one true brace style (it's enforced). I'm coming to C# from C++, in the former I could've made x and y to become i and j with reference assignment, but in C# it's not possible.

Should I take the (i_IsRow) condition to a method? it will have 5 parameters and 2 of them will be out parameters, this is definitely code smell...

private int checkRowsOrColsForWin(bool i_IsRow)
{
    int signCounter = 0;
    int x, y;

    for (int i = 0; i < m_Cols; i++)
    {
        for (int j = 0; j < m_Rows; j++)
        {
            if (i_IsRow)
            {
                x = i;
                y = j;
            }
            else
            {
                x = j;
                y = i;
            }

            signCounterLogic(m_Board[x, y], ref signCounter);

            if (Math.Abs(signCounter) == k_FourInARow)
            {
                break;
            }
        }
        if (Math.Abs(signCounter) == k_FourInARow)
        {
            break;
        }
    }
    return signCounter;
}


texts: Python: SQL Alchemy. Managing a many-to-many self related table

texts:
I am building Twitter. People can follow each other, and hence I have 2 tables, users and followers.

My current problem is that I feel like I'm doing too many SELECTs before doing anything useful. Is it common to have a SELECT on users to find the current user each time?

I have:

models.py

class User(Base):
    """Table schema containing profiles."""

    __tablename__ = "users"

    id = Column(String, primary_key=True)
    username = Column(String)
    created_date = Column(DateTime)

    following = relationship('User',
        secondary='followers',
        primaryjoin='User.id==Follower.user_id',
        secondaryjoin='Follower.follows_user_id==User.id'
    )

    followers = relationship(
        'User', secondary='followers',
        primaryjoin='User.id==Follower.follows_user_id',
        secondaryjoin='User.id==Follower.user_id'
    )

class Follower(Base):
    __tablename__ = 'followers'

    user_id = Column(String, ForeignKey('users.id'), primary_key=True)
    follows_user_id = Column(String, ForeignKey('users.id'), primary_key=True)
    created_date = Column(DateTime)
    updated_date = Column(DateTime)
    active = Column(Boolean, default=True)

    user_creating_following = relationship("User", primaryjoin="Follower.user_id==User.id")
    user_being_followed = relationship("User", primaryjoin="Follower.follows_user_id==User.id")

To follow a user, I created an endpoint, which ends up calling follow_user() function.

def follow_user(session, user_id, username_to_follow):
    # first check if user already follows the person trying to follow
    user_to_follow = session.query(User).filter(User.username==username_to_follow).first()

    if not user_to_follow:
        raise BadRequest("The user you are trying to follow doesnt exist")

    # Check not performing action on yourself
    if user_to_follow.id == user_id:
        # Can not perform this action on yourself
        raise BadRequest("You cannot follow yourself")

    follow = session.query(Follower).filter(
        and_(
            Follower.user_id==user_id,
            Follower.follows_user_id==user_to_follow.id
        )
    ).first()

    if follow:
        # Update the existing follow record
        follow.active = True
        follow.updated_date = datetime.now()
    else: # if the follow doesn't already exist, create it
        follow = Follower(
            user_id=user_id,
            follows_user_id=user_to_follow.id,
            created_date=datetime.now(),
            updated_date=datetime.now(),
            active=True
        )
    session.add(follow)
    session.commit()
    return

I wish I could write something like:

follow = session.query(Follower)\
.filter(Follower.user_creating_following.id==user_id)\
.filter(Follower.user_receiving_following.username==username_to_follow)

This would allow me to avoid the first query on the User altogether, but returns the error:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with
        Follower.user_creating_following has an attribute 'id'

Any other input is greatly appreciated.


texts: Display progress bar to show async request status using jQuery

texts:
Instead of using the ProgressBar plugin, this script displays the progress bar for async requests on the page. Could anyone provide any feedback on this, especially if there will be any issues like cross browser compatibility, etc?

       Loading...

//displays progress bar
$('.overlay').ajaxStart(function () {
       $(this).css({ height: $(document).height(), width: $(document).width() }).show();
       $(this).find(".progress").css({ top: $(window).height() / 2, left: $(window).width() / 2 });
       }).ajaxStop(function () {
       $(this).hide();
});

.overlay
{
    position: fixed !important;
    position: absolute; /*ie6*/
    width: 100%;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: #000;
    filter: alpha(opacity=20);
    opacity: 0.2;
    -moz-opacity: 0.2;
    -khtml-opacity: 0.2;
    -webkit-opacity: 0.2;
    z-index: 10004;
    display: none;
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20); /*ie6*/
}
.overlay .progress
{
    position: absolute;
    z-index: 10005;
    background: #fff;
    color: #000;
}


texts: Determining coefficient in geometric progression

texts:
For an assignment at Uni we had to code a program that takes numbers as input and determines the coefficient if they form a geometric progression once you declare EOF (ctrl+z). If the user inputs a number that doesn't belong to an already established progression the program breaks, telling us there's no geometric progression.

#include <stdio.h>
#include <math.h>

int main(){
int prevNum;
int Num;
scanf_s("%i", &prevNum);
scanf_s("%i", &Num);
int r = Num / prevNum;
prevNum = Num;
while ((scanf("%i", &Num) != EOF))
{
    if (Num / prevNum != r)
    {
        printf("No progression \n");
        return 0;
    }

    else prevNum = Num;

}
    printf("Progression with r=%i \n", r);
    return 0;
}

What I'd like to ask is whether there's a better, more practical way to fulfill the same task.


texts: ChocolatesByNumbers- Find the number of N chocolates in a circle

texts:
Recently, i have been indulging in a lot of codility challenges to improve my coding performance. For each of this exercise, I always aim for simple solutions as opposed to complicated ones that arrive at the same answer . The question is

  Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N − 1.

  You start to eat the chocolates. After eating a chocolate you leave only a wrapper.

  You begin with eating chocolate number 0. Then you omit the next M − 1 chocolates or wrappers on the circle, and eat the following one.

  More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).

  You stop eating when you encounter an empty wrapper.

  For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.

  The goal is to count the number of chocolates that you will eat, following the above rules.

Write a function:

class Solution { public int solution(int N, int M); }

  that, given two positive integers N and M, returns the number of chocolates that you will eat.

  For example, given integers N = 10 and M = 4. the function should return 5, as explained above.

  Assume that:

  N and M are integers within the range [1..1,000,000,000].
  Complexity:

  expected worst-case time complexity is O(log(N+M));
  expected worst-case space complexity is O(log(N+M))

I am  aware  a similar questions has been asked in java ChocolatesByNumbers
but my question is more directed to C#

public static int PrintNChocolatesInaCircle(int N, int M)
{
    int counter = 1;
    int start = 0;
    int value;
    while ((start + M) % N != 0)
    {
        value = (start + M) % N;
        start = value;
        counter++;
    }
    return counter;
}

Codility scored my code in terms of Correctness 100% but in terms of performance, it takes longer time to process large elements e.g N = (3^9)(2^14), M=(2^14)(2^14) for a large element and going a bit higher the performance declines.


texts: jQuery animation procedural approach, suggestions need

texts:
I'm kinda worried that the way I did my animation intro is a bit too heavy and is not optimized. Please review and let me know your thoughts.

$(document).ready(function() {

    introIconFirst();

    function introIconFirst() {
        $('h2.ribbon').css({
            'marginTop': '+30px',
            'opacity': '0'
        }).animate({
            marginTop: '0',
            opacity: '1'
        }, 1500, 'easeOutElastic', introIconSecond());
    }

    function introIconSecond() {
        $('#ico_website').rotate('0deg').css({
            'top': '+900px',
            'opacity': '0'
        }).animate({
            top: '50px',
            opacity: '1'
        }, {
            queue: false,
            duration: 1100,
            easing: 'easeOutElastic'
        }).animate({
            rotate: '-30deg'
        }, 1000, 'easeOutElastic', introIconThird());
    }

    function introIconThird() {
        $('#ico_rails').css({
            'top': '+900px',
            'opacity': '0'
        }).delay(300).animate({
            top: '145px',
            opacity: '1'
        }, 1400, 'easeOutElastic', introIconFourth());
    }

    function introIconFourth() {
        $('#ico_plane').css({
            'left': '255px',
            'top': '90px',
            'opacity': '0'
        }).delay(800).animate({
            top: '18px',
            left: '299px',
            opacity: '1'
        }, 600, 'linear');
    }

});


texts: Can this parser (concerning about infinite hierarchy of operators) be implemented purely in ReadPrec?

texts:
In Haskell, I tried to implement a parser for expressions containing hyperoperations, and finally succeeded. Valid expressions shall contain:

Parentheses.

Nonnegative integers.

Addition represented by +. It has precedence of 6, and its associativity shall be exploited.

Multiplication represented by *. It has precedence of 7, and its associativity shall be exploited.

Exponentiation represented by ^. It has precedence of 8.

Tetration represented by ^^. It has precedence of 9.

Pentation represented by ^^^. It has precedence of 10.

ad infinitum.

I was struggling for months to implement this with ReadPrec. It was truly a "Eureka" moment when I found that I have a workaround:
import Control.Monad
import Text.ParserCombinators.ReadPrec
import Text.Read
import Text.Read.Lex

hyperOp :: Int -> Integer -> Integer -> Integer
hyperOp 0 _ y = y + 1
hyperOp 1 x y = x + y
hyperOp 2 x y = x * y
hyperOp 3 x y = x ^ y
hyperOp n x 0 = 1
hyperOp n x y = hyperOp (n-1) x (hyperOp n x (y-1))

parseHyperOp :: Int -> ReadPrec Integer
parseHyperOp opn = parens . choice $
    lift readDecP
    : prec 6 (do
        m <- step (parseHyperOp opn)
        Symbol "+" <- lexP
        n <- parseHyperOp opn
        return (m + n))
    : prec 7 (do
        m <- step (parseHyperOp opn)
        Symbol "*" <- lexP
        n <- parseHyperOp opn
        return (m * n))
    : fmap (\c -> prec (7 + c) $ do
        m <- step (parseHyperOp opn)
        Symbol op <- lexP
        guard (replicate c '^' == op)
        n <- step (parseHyperOp opn)
        return (hyperOp (2 + c) m n)
        ) [1 .. opn]

highestOp :: String -> Int
highestOp "" = 0
highestOp ('^':str) = let
    (str1, str2) = span ('^'==) str
    in max (1 + length str1) (highestOp str2)
highestOp (_  :str) = highestOp str

parseOp :: Prec -> ReadS Integer
parseOp c str = readPrec_to_S (parseHyperOp (highestOp str)) c str

The trick is to find the highest operation within the input string. That makes the choice finite.
Still, I think it's quite ugly to use readPrec_to_S. Can this be implemented without using readPrec_to_S and co?


texts: TDD workflow best-practices for .NET using NUnit

texts:
I'm starting to dive into TDD with NUnit and despite I've enjoyed checking some resources I've found here at stackoverflow, I often find myself not gaining good traction.

So what I'm really trying to achieve is to acquire some sort of checklist/workflow —and here's where I need you guys to help me out— or "Test Plan" that will give me decent Code Coverage.

So let's assume an ideal scenario where we could start a project from scratch with let's say a Mailer helper class that would have the following code:

(I've created the class just for the sake of aiding the question with a code sample so any criticism or advice is encouraged and will be very welcome)

Mailer.cs

using System.Net.Mail;
using System;

namespace Dotnet.Samples.NUnit
{
    public class Mailer
    {
        readonly string from;
        public string From { get { return from; } }

        readonly string to;
        public string To { get { return to; } }

        readonly string subject;
        public string Subject { get { return subject; } }

        readonly string cc;
        public string Cc { get { return cc; } }

        readonly string bcc;
        public string BCc { get { return bcc; } }

        readonly string body;
        public string Body { get { return body; } }

        readonly string smtpHost;
        public string SmtpHost { get { return smtpHost; } }

        readonly string attach;
        public string Attach { get { return Attach; } }

        public Mailer(string from = null, string to = null, string body = null, string subject = null, string cc = null, string bcc = null, string smtpHost = "localhost", string attach = null)
        {
            this.from = from;
            this.to = to;
            this.subject = subject;
            this.body = body;
            this.cc = cc;
            this.bcc = bcc;
            this.smtpHost = smtpHost;
            this.attach = attach;
        }

        public void SendMail()
        {
            if (string.IsNullOrEmpty(From))
                throw new ArgumentNullException("Sender e-mail address cannot be null or empty.", from);

            SmtpClient smtp = new SmtpClient();
            MailMessage mail = new MailMessage();
            smtp.Send(mail);
        }
    }
}

MailerTests.cs

    using System;
    using NUnit.Framework;

    namespace Dotnet.Samples.NUnit
    {
        [TestFixture]
        public class MailerTests
        {
            [Test]
            public void SendMail_FromArgumentIsNotNull_ReturnsTrue()
            {
                // Arrange
                string argument = null;
                // Act
                Mailer mailer = new Mailer(from: argument);
                // Assert
                Assert.IsNotNull(mailer.From, "parameter 'from' cannot be null.");
            }

            [Test]
            public void SendMail_FromArgumentIsNotEmpty_ReturnsTrue()
            {
                // Arrange
                string argument = String.Empty;
                // Act
                Mailer mailer = new Mailer(from: argument);
                // Assert
                Assert.IsNotEmpty(mailer.From, "parameter 'from' cannot be empty.");
            }

            [Test]
            public void SendMail_FromArgumentIsNullOrEmpty_ThrowsException()
            {
                // Arrange
                dynamic argument = null;
                // Act
                Mailer mailer = new Mailer(from: argument);
                Action act = () => mailer.SendMail();
                // Assert
                Assert.Throws<ArgumentNullException>(new TestDelegate(act));
            }
        }
    }

So after having my first 2 failing tests the next obvious step would be implementing the functionality to make them pass, but, should I keep the failing tests and create new ones after implementing the code that will make those pass, or should I modify the existing ones after making them pass?

Any advice about this topic will really be enormously appreciated.


texts: Function to get specified key from /proc/cpuinfo

texts:
On Linux, the file /proc/cpuinfo returns a set of key-value pairs, where the key and value are separated by a colon and each pair has its own line. It's a bit more complicated than that in reality, but for my needs that's as complicated as it needs to be. (I have only one processor core.)

My goal is to write a function in bash that takes the key for one of those items and returns the value corresponding to that key. Here's my current function:

function get_cpuinfo_prop () {
    TARGET_LINE=$(cat /proc/cpuinfo | grep ^$1)
    IFS=':'
    read -ra PARTS <<< "$TARGET_LINE"
    PROP_VALUE=${PARTS[1]}
    echo $PROP_VALUE
}

And you'd call it like this:

$(get_cpuinfo_prop 'key_name')

Is there a better way of doing it? How could I improve this code? Additionally, I think this might be returning extra whitespace before the actual value. How can I trim those characters off the beginning/end?


texts: Get XML elements with a particular attribute value

texts:
I have the following code to find xml elements that have a particular attribute value:

IEnumerable<XElement> elems =
    xmlDoc.Descendants("elemName")
    .Where(x =>
        x.Attribute("attrName").Value
        .Equals(
            filename,
            StringComparison.OrdinalIgnoreCase
        )
    );

The problem is that if the element does not have that attribute, according to the docs, it will return null and we'll get a crash when we try to do null.Value.

I've rewritten it like this:

IEnumerable<XElement> elems =
     xmlDoc.Descendants("elemName")
     .Where(x =>
         ((x.Attribute("attrName") == null)
         ? ""
         : x.Attribute("attrName").Value).Equals(
             filename,
             StringComparison.OrdinalIgnoreCase
         )
     );

But I think it's a bit ugly. Is there an idiomatic way of doing this - I imagine this is a fairly common operation? I suppose I could just do a regular loop.


texts:
Introduction

This is Part 3 of my F# blockchain implementation. Previous parts:

Block and Blockchain
Transactions

Code

In this part I am implementing a wallet functionality. The code is based on a JavaScript blockchain implementation called naivecoin. The source code for naivecoin transactions can be found here.

namespace Blockchain.Core

open System.Security.Cryptography

open Helpers

type Wallet() =
    let keyName = "blockchain"

    member private this.Key =
        if CngKey.Exists(keyName) then
            CngKey.Open(keyName)
        else
            CngKey.Create(CngAlgorithm.ECDsaP521, keyName)

    member this.Address = this.Key.Export(CngKeyBlobFormat.EccPublicBlob).ToHex()

    member private this.GetBalance(address: string, unspentOutputs: UnspentTransactionOutput seq) =
        unspentOutputs
        |> Seq.filter (fun x -> x.address = address)
        |> Seq.map (fun x -> x.amount)
        |> Seq.fold (+) 0.0

    member private this.FindOutputsWithChangeForTransaction(transactionAmount: float, unspentOutputs: UnspentTransactionOutput seq) =
        let rec findOutputsWithChange currentAmount (unspentOutputs : UnspentTransactionOutput seq) (consumedOutputs : UnspentTransactionOutput seq) =
            if currentAmount >= transactionAmount then
                (consumedOutputs, currentAmount - transactionAmount)
            else if Seq.isEmpty unspentOutputs then
                failwith "Not enough coins to send transaction."
            else
                let currentOutput = unspentOutputs |> Seq.head
                findOutputsWithChange (currentAmount + currentOutput.amount) (unspentOutputs |> Seq.skip 1) (consumedOutputs |> Seq.append [| currentOutput |])

        findOutputsWithChange 0.0 unspentOutputs []

    member private this.CreateOutputs(receiverAddress: string, amount: float, change: float) =
        if change = 0.0 then
            Seq.ofArray [| { address = receiverAddress; amount = amount } |]
        else
            Seq.ofArray [| { address = receiverAddress; amount = amount}; { address = this.Address; amount = change } |]

    member this.CreateTransaction(receiverAddress: string, amount: float, unspentOutputs: UnspentTransactionOutput seq) =
        let myUnspentOutputs = unspentOutputs |> Seq.filter (fun x -> x.address = this.Address)
        let (consumedOutputs, change) = this.FindOutputsWithChangeForTransaction(amount, myUnspentOutputs)
        let unsignedInputs = consumedOutputs |> Seq.map (fun x -> { sourceOutputTransactionId = x.transactionId; sourceOutputIndex = x.outputIndex; signature = "" })
        let outputs = this.CreateOutputs(receiverAddress, amount, change)
        let processor = new TransactionProcessor()
        let transactionId = processor.GetTransactionId(unsignedInputs, outputs)
        let tempTransaction = { id = transactionId; inputs = unsignedInputs |> Array.ofSeq; outputs = outputs |> Array.ofSeq }
        let inputs = unsignedInputs |> Seq.mapi (fun i x -> { x with signature = processor.SignTransactionInput(tempTransaction, i, this.Key, myUnspentOutputs) })
        { tempTransaction with inputs = inputs |> Array.ofSeq }


texts:
defmodule Baby.Post do
  use Baby.Web, :model

  schema "posts" do
    field :cover, :string
    field :email, :string
    field :firstname, :string
    field :lastname, :string
    field :birthday_day, :integer
    field :birthday_month, :integer
    field :birthday_year, :integer
    field :description, :string
    field :phone, :string

    timestamps
  end

  @required_fields ~w(email firstname lastname birthday_day birthday_month birthday_year description phone)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> validate_length(:description, min: 280)
    |> validate_format(:email, ~r/@/)
    |> valid_phone(:phone)
  end

  @doc """
  Check if it's a valid french number
  """
  def valid_phone(changeset, field) do
    phone = get_field(changeset, field)

    unless phone === nil do

      if String.length(phone) !== 10  do
        add_error(changeset, field, "n'est pas valide")
      else
        changeset
      end

    else
      changeset
    end

  end

end

I'm trying to add a custom validation for the phone field. The code is working, but it's really crappy. I'm quite new with elixir and I'm a bit confused about the fact the return is the last expression evaluated. Can you help me to rewrite that valid_phone method ?


texts: Implementing Sieve of Eratosthenes faster

texts:
I wrote a version of sieve of eratosthenes:

number =100000000
def eratos_sieve(n:"find prime below this"=None):
        if not(n):
            n = number
        numbers = [x for x in range(0, n+1)]
        current_prime = 2
        sqrt_limit = int(math.sqrt(n))+1
        while numbers[current_prime] <= sqrt_limit:
            #(len(numbers)-1) is the actual size since
            #since, len([0,...,n])=n+1
            for i in range(current_prime, ((len(numbers)-1)//current_prime)+1):
                numbers[current_prime*i]=-1
            current_prime += 1
            for i in range(current_prime, sqrt_limit):
                if numbers[i]>0:
                    current_prime=i
                    break

        #this part is optional
        j = 0
        for i in range(len(numbers)):
            if numbers[i]>0:
                numbers[j]=numbers[i]
                j += 1
        #uptil here if later primes are to be found using indices
        #else all primes upto n are returned as a single list
        return numbers[1:j]

It seems to perform fast enough for my purposes. I'd like to get some review about it's performance since I'm a novice. Also, I'd like someone with enough memory (if possible) to run the below two tests:

import time
import math
num1 = 100000000 #100 million
num2 = 1000000000 #1 billion
start = time.perf_counter()
eratos_sieve(num1)
total_100_m = time.perf_counter()-start()

start = time.perf_counter()
eratos_sieve(num2)
total_1_b = time.perf_counter()-start()

print("For 100m it takes: ", total_100_m)
print("For 1b   it takes: ", total_1_b)


texts:
What do you think about this solution? I guess there are too many lists...

vowels = "aeiou"

def reverseVowels(string):
    vowels_list = []
    string_list = list(string)

    for index,letter in enumerate(string_list):
        if letter in vowels:
            vowels_list.append(letter)

    reversed_vowels_list = list(reversed(vowels_list))

    new_string_list = list(string_list)
    for index,vowel in enumerate(vowels_list):
        idx_vowel_in_string =  string_list.index(vowel)
        new_string_list[idx_vowel_in_string] = reversed_vowels_list[index]

    print new_string_list

reverseVowels("aupiple")


texts:
Recently, I have get familiar with Command Pattern implementation. I have a problem where I need to get a choice for user to select what kind of method to execute typing method name or number, which concerns to this concrete method execution. Everything will be OK if I don't need to create separate class for each method as it describes below:

public interface Order {
    void execute ();
}

// Receiver class.
class StockTrade {
    public void buy() {
        System.out.println("You want to buy stocks");
    }
    public void sell() {
        System.out.println("You want to sell stocks ");
    }
}

// Invoker.
class Agent {

    void placeOrder(Order order) {
        order.execute();
    }
}

//ConcreteCommand Class.
class BuyStockOrder implements Order {

    private StockTrade stock;

    public BuyStockOrder(StockTrade st) {
        stock = st;
    }
    public void execute() {
        stock.buy();
    }
}

//ConcreteCommand Class.
class SellStockOrder implements Order {
    private StockTrade stock;
    public SellStockOrder (StockTrade st) {
        stock = st;
    }
    public void execute() {
        stock.sell();
    }
}

// Client
public class Client {
    public static void main(String[] args) {
        StockTrade stock = new StockTrade();
        BuyStockOrder buyStockOrder = new BuyStockOrder(stock);
        SellStockOrder sellStockOrder = new SellStockOrder(stock);
        Agent agent = new Agent();

        agent.placeOrder(buyStockOrder ); // Buy Shares
        agent.placeOrder(sellStockOrder ); // Sell Shares
    }
}

How can I avoid too much class creation for each method that it will be also correct and flexible?


texts:
Objective: Create a heap sort that returns a unsorted list to sorted from greatest to least.

Does this implementation look correct? Do you have any tips for optimizing this?

'''HeapSort. Best: n log(n) Average: n log(n) Worst: n log(n) '''

#Calls heapify and returns sorted list from greatest to least.
def heapSort(list):
    result = []
    while list:
        result.append(heapify(list))
    return result

def heapify(struct):
    for x in range(len(struct),0,-1):
    #Base Case: Returns last integer when sequence reaches below 2
        if len(struct) < 2:
            return struct.pop(0)

        #Compares Tree Root Node vs Children.
        if struct[0] < struct[1]:
            temp = struct[0]
            struct[0] = struct[1]
            struct[1] = temp
        else:
        #Parent: x/2. Child: x-1. Compares child nodes vs parent nodes in Tree.
            if struct[x-1] > struct[x/2]:
                temp = struct[x-1]
                struct[x-1] = struct[x/2]
                struct[x/2] = temp
    return struct.pop(0)


texts:
I have a requirement where I need to extract pixels of a given rectangle within an image byte[].

More specifically I have an image where I have narrowed an area that I wish to return and keep and the remainder discard. In my case I'm performing face recognition in real time so I don't want to store unnecessary data but obviously this could be useful elsewhere.

public static byte[] ExtractPixelsFromImage(this byte[] pixels, int top, int left, int width, int height, int horizontalResolution)
{
    List<byte> result = new List<byte>();

    int bytesPerPixel = 4;
    int rowLength = horizontalResolution * bytesPerPixel;
    int rowLeftPixelStart = (rowLength * top) + (left * bytesPerPixel);

    for (int i = 0; i < height; i++)
    {
        int currentPixelStart = (rowLength * i) + rowLeftPixelStart;
        result.AddRange(pixels.Skip(currentPixelStart).Take(width * bytesPerPixel));
    }

    return result.ToArray();

}

This method has been responsible for the vast amount of CPU time my application is using and I'm hoping to improve this.

The obvious suggestion is to remove the LINQ, but beyond this, is there anything else that can be improved?


texts:
I do parsing of the string in order to find wrapped sub-string inside brackets of the first level. a+(b+(d-g))+g+d, in this case I will need to separate (b+(d-g)). Below is the function which i use for such situations. This function is invoked when i find any opening bracket (. I did profiling of the program and unfortunately it is one of the slowest parts.

Could you please advise how I can optimise the code?

Input

"(b+(d-g))+g+d"
 ^            ^
 |            +--------iterator `end_` points to the end of the expression
 +-------------iterator `tail_` points to beginning of the expression with brackets

Output

string with (b+(d-g))

side-effect

tail_ iterator

"(b+(d-g))+g+d"
         ^
         |
         +------iterator `tail_` points to the last correctly closed bracket.

Function

string get_between_brackets(string::iterator& tail_, const string::iterator& end_)
{
    string brackets_content;
    brackets_content.reserve(248); //cannot be longer than that
    if(distance(tail_, end_) >= 2)
    {
        uint br_cnt = 0;
        while(tail_ != end_)
        {
            const auto& chr = *tail_;
            switch(chr)
            {
                case '(': ++br_cnt; break;
                case ')': --br_cnt; break;
            }
            if(br_cnt >= 0)
                brackets_content.push_back(chr);

            if (br_cnt == 0)
                break;

            advance(tail_, 1);
        }
    } else throw std::invalid_argument("brackets tail is not long enough");
    return(brackets_content);
}


texts:
I was wondering what is the better way of writing? Having several variables to show the steps or rather do method chaining?

function count(string) {
    const array = string.split("");
    return array.filter(element => element === "a").length
}

function count(string) {
    return string
        .split("")
        .filter(element => element === "a")
        .length
}

Thank you in advance.


texts: Copying from a directory without using os.chdir()

texts:
The program should backup files in a source folder to a zip file in destination, and keep track of how many versions there are (which explains the shelve). In order to copy these files, apparently I have to change the cwd to the source path (folder), because otherwise the program will not detect them. While it may not seem to cause that much of an issue, my OCD triggers when I see the shelve files in the new .zip folder. I thought about adding lines to delete the shelve files, but I was wondering if there is some other way.

(This program is a project in a certain book I'm reading, and while the project demanded a more basic version of this, I like to take it a step forward.)

import os, shelve, zipfile

def backupToZip(folder, destination, copies=1):

#Folder
    fName= os.path.basename(folder)

#Shelfing for copy number
    namesNums = shelve.open('names')
    if fName not in namesNums:
        num= 1
        namesNums[fName]= num
    else:
        num= namesNums[fName]

#Producing zips
    os.chdir(folder)
    for i in range(int(copies)):
        zipPath= os.path.join(destination, fName+'_'+str(num)+'.zip')
        theZip= zipfile.ZipFile(zipPath, 'w')

        for foldername, subfolders, filenames in os.walk(folder):
            for filename in filenames:
                theZip.write(filename)
        num+=1

    namesNums[fName]= num
    namesNums.close()


texts: Bash script to open or close gnome-terminal with a single keybinding

texts:
I wanted to bind a single hot key to open and close gnome-terminal in a way similar to terminal emulators such as tilda or guake. I use Ubuntu, and have configured this script to be executed when I press the key F1

The script will focus or minimize the first gnome-terminal window that is running.
If no gnome-terminal is running, it will start a new one and place it in the top half of the screen.

#!/bin/bash
# Bind this script to a keyboard shortcut to add "pull-down" behaviour to
# the Gnome terminal similar to guake or tilda

# It seems to work with gnome-terminal or xfce4-terminal
# I haven't tested any other terminal emulators
TERMINAL_EMULATOR=gnome-terminal

function main {
  if [[ -z $(terminal_process) ]]; then
    # no running terminal emulator
    # open new terminal at top of the screen
    $TERMINAL_EMULATOR --geometry 80x1+0+0 &
    win_id=$(get_terminal_window)
    # set initial width to 100% and height to 45%
    xdotool windowsize $win_id $(absolute_window_size 100 45)
    xdotool windowactivate $win_id
  else
    win_id=$(get_terminal_window)
    if [[ $(xdotool getactivewindow) == $win_id ]]; then
      # if terminal window is active, mimize
      xdotool getactivewindow windowminimize
    else
      # if terminal window is inactive, bring in focus
      xdotool windowactivate $win_id
    fi
  fi
}

function terminal_process {
  # Is gnome-terminal already running
  echo $( ps aux | grep $TERMINAL_EMULATOR | grep -v grep)
}

function get_terminal_window {
  # get id of open terminal window. Will wait for window to open if neccessary
  echo $(xdotool search --onlyvisible --sync --limit 1 --class $TERMINAL_EMULATOR)
}

function absolute_window_size {
  # convert relative window size to absolute pixel size, based on screen res
  width_percent=$1
  height_percent=$2
  IFS=x
  screen_dimensions=$(xrandr | grep connected | grep -o '[1-9]\+x[0-9]\+')
  set $screen_dimensions
  echo $(($width_percent*$1/100)) $(($height_percent*$2/100))
}

main

As someone coming from python, bash feels quite unfamiliar, and I would like some feedback on whether this script follows best practices. I also wonder if there's anything that can be simplified without losing readability.


texts: Summing a sequence of fractions to a limit n

texts:
Your method should accept a real number as a parameter representing a limit, and should add and print terms of the sequence until the sum of terms meets or exceeds that limit. For example, if your method is passed 2.0, print terms until the sum of those terms is at >= 2.0. You should round your answer to 3 digits past the decimal point.

    The following is the output from the call sequenceSum(2.0);
    1 + 1/2 + 1/3 + 1/4 = 2.083

  If your method is passed a value less than 1.0, no output should be produced. You must match the output format shown exactly; note the spaces and pluses separating neighboring terms.

I'm wondering if there's anything I can do for the edge case of n = 1? It kinda just seems like it's hanging out at the end, and it looks a bit strange to me. Also, looking at the types for each value, I'm wondering if I need to think more about the data types I chose to use, in terms of should I use a double for this, or an int?.

I'd use methods to break out the functionality of my code, but the prompt only allows me to submit one method for this type of problem. Any feedback is appreciated!

public static void sequenceSum(double n){
    if(n > 1.0){
        int denominator = 1;
        double accumulator = 0;
        System.out.print("1");
        while(accumulator < n) {
            accumulator += ( 1.0 / denominator);
            if(denominator > 1.0){
                System.out.print(" + " + 1 + "/" + denominator);
            }
        denominator++;
        }
    System.out.printf(" = %1.3f", accumulator);
    } else if(n == 1.0){
        System.out.print("1 = 1.000");
    }
}


texts: Drawing a board for the board game GO (HTML canvas)

texts:
I am working on a GO game in JavaScript and drawing the board is important to be efficient because it gets ran multiple times a second. As when the user moves their mouse, it will simulate where their game piece is going to go, so the board must rebuild lots of times.

It looks ok at the moment, a bit long and it draws the numbers and letters on the outside even though that's constant, if you get what I mean. So that bit could be done better so it only writes that text once and then just resets the middle bit. I'm also trying to make it completely scalable, and I think I have done a good job so far.

If you want to try out the board of jsFiddle, I also included the functions to simulate dropping a game piece, if you want to comment on that. But this post was mainly just for drawing the board. For this code, I'll just put the drawing of the grid.

jsFIddle

var canvas = document.getElementById("game-canvas");
var context = canvas.getContext("2d");

var boardSize = 13;
var border = canvas.width / 10;
var boardWidth = canvas.width - (border * 2);
var boardHeight = canvas.height - (border * 2);

var cellWidth = boardWidth / (boardSize - 1);
var cellHeight = boardHeight / (boardSize - 1);

function drawGrid()
{
    var backgroundColor = '#F5DEB3';
    var gridColor = '#8B4513';

    context.fillStyle = backgroundColor;
    context.fillRect(0, 0, canvas.width, canvas.height);

    context.fillStyle = gridColor;

    for (var i = 0; i < boardSize - 1; i++) //Draws the board
    {
        for (var j = 0; j < boardSize - 1; j++)
        {
            context.fillRect(i * cellWidth + border, j * cellHeight + border, cellWidth - 1, cellHeight - 1);
        }
    }

    var quater = Math.floor((boardSize - 1) / 4);
    var markerSize = 8;
    var markerMargin = (markerSize / 2) + 0.5;

    context.fillStyle = backgroundColor;

    if (!!(boardSize % 2)) //If its an odd number eg (13 x 13), draw the middle marker
    {
        context.fillRect((((boardSize - 1) / 2) * cellWidth) + border - markerMargin, (((boardSize - 1) / 2) * cellWidth) + border - markerMargin, markerSize, markerSize);
    }
    //Draw the other 4 markers
    context.fillRect((quater * cellWidth) + border - markerMargin, (quater * cellWidth) + border - markerMargin, markerSize, markerSize);
    context.fillRect((((boardSize - 1) - quater) * cellWidth) + border - markerMargin, (quater * cellWidth) + border - markerMargin, markerSize, markerSize);

    context.fillRect((((boardSize - 1) - quater) * cellWidth) + border - markerMargin, (((boardSize - 1) - quater) * cellWidth) + border - markerMargin, markerSize, markerSize);
    context.fillRect((quater * cellWidth) + border - markerMargin, (((boardSize - 1) - quater) * cellWidth) + border - markerMargin, markerSize, markerSize);

    var size = canvas.width / 40;
    var textSpacing = 10;
    context.fillStyle = '#000000';
    context.font = size + "px Arial";

    //draw the numbers and letters
    for (i = 0; i < boardSize; i++)
    {
        context.fillText((i + 1), textSpacing, ((canvas.height - border) - (i * cellHeight)) + (size / 3));
        context.fillText((i + 1), canvas.width - (size + textSpacing), ((canvas.height - border) - (i * cellHeight)) + (size / 3));

        context.fillText((String.fromCharCode(97 + i)), (border + (i * cellHeight) + (size / 3)) - (size / 1.5), textSpacing + size);
        context.fillText((String.fromCharCode(97 + i)), (border + (i * cellHeight) + (size / 3)) - (size / 1.5), canvas.height - (textSpacing * 2));
    }
}


texts:
This is my implementation of Quick Sort Algorithm :
def quick_sort(sequence):
    if len(sequence)<= 1:
        return sequence
    else:
        pivot = sequence.pop() # To take the last item of "sequence" list

    greater =[]
    lower = []

    for n in sequence:
        if n > pivot :
            greater.append(n)
        else:
            lower.append(n)

""" return the quiqk sorted "lower" and "greater" lists ,and pivot as a list in between """
    return quick_sort[lower] + [pivot] + quick_sort[greater]

How can I improve it ?


texts: Linkedlist & hashmap _duplicates removal

texts:
I have implemented a LinkedList removal fo duplicates class by using HashMap.
Looking forward to your reviews.
Thanks.
package test;

import main.algorithms.LinkedListRemoveDuplicates;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class LinkedListRemoveDuplicatesTest {

    LinkedListRemoveDuplicates linkedListRemoveDuplicates;

    @Before
    public void setUp(){
        linkedListRemoveDuplicates = new LinkedListRemoveDuplicates();
    }

    @Test
    public void testRemoveDuplicates(){

        linkedListRemoveDuplicates.addBack(5);
        linkedListRemoveDuplicates.addBack(5);
        linkedListRemoveDuplicates.addBack(5);
        linkedListRemoveDuplicates.addBack(5);
        linkedListRemoveDuplicates.addBack(5);

        Assert.assertEquals(5, linkedListRemoveDuplicates.size());

        linkedListRemoveDuplicates.removeDuplicates();

        Assert.assertEquals(1, linkedListRemoveDuplicates.size());

    }
}

package main.algorithms;

import java.util.HashMap;

public class LinkedListRemoveDuplicates {

    Node head;

    int size;

    public void removeDuplicates() {

        HashMap<Integer,Integer> duplicatesList = new HashMap<>();

        Node currentNode = head;

        if(size==1){
            return;
        }
        //  2 1 3 1 2
        while(currentNode != null ){

            if(!duplicatesList.containsKey(currentNode.value)){
                duplicatesList.put(currentNode.value,1);
            }
            currentNode = currentNode.next;
            continue;
        }

        size = duplicatesList.size();
    }

    class Node{
        int value;
        Node next;
        public Node(int value){
            this.value = value;
        }
    }

    public void addBack(int i) {

        Node newNode = new Node(i);
        if(head == null) {
            head = newNode;
        }else{
            Node currentNode = head;
            while(currentNode.next != null){
                currentNode = currentNode.next;
            }
            currentNode.next = newNode;
        }
        size++;
    }

    public int size() {
        return size;
    }
}


texts: Find valid triples for a sorted list of integers (part 2)

texts:
Have some ideas to improve code from this discussion (Find valid triples for a sorted list of integers) and post new code in a new post.

The new idea is to try to remember where low bound searched last time, and when doing the search, only search from the lower bound where last search is satisfied, since with j increase each time, the 3rd dimension of satisfied triple could only increase. More specifically, these two lines,

    #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code
    upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j])

I'm working on a problem in which I have an input array, sorted positive unique integers, and have to try to find all possible triples \$(x,y,z)\$ which satisfy \$x+y>z\$ and \$x<y<z\$. For example, \$(1,2,3)\$ is not a valid triple since \$1+2\$ is not \$> 3\$, and \$(3,4,5)\$ is a valid triple since \$3<4<5\$ and \$3+4>5\$.

This code leverages binary search, and I'm wondering if this can be improved in terms of time complexity. Please also help to point out any code issues/bugs or improvement areas.

BTW, I am not using enumeration feature of Python since I want to keep j greater than i, and leverage the feature in my logics.

from __future__ import division

def findSum(numbers, startIndex, value):
    """
    find index whose value is less than input parameter value (as upper bound)
    ,and the greatest possible value possible
    :param numbers: sorted value to search, may contains duplicates
    :param startIndex: where to search from, inclusive
    :param value: upper bound to search
    :return: the index whose value is less than upper bound value
    """
    low = startIndex
    high = len(numbers) - 1
    while low <= high:
        mid = (low + high) // 2
        if numbers[mid] == value:
            while mid >= low and numbers[mid] == value:
                mid -= 1
            return mid if mid >= low else -1
        elif numbers[mid] > value:
            high = mid - 1
        else:
            low = mid + 1
    # while
    return low-1 if (low-1) >= startIndex else -1

def findTriagles(numbers):
    """
    :param numbers: could contains duplicate number, assume numbers are sorted
    :return: unique triples
    """
    results = set()
    for i in range(0, len(numbers)-2):
        upperBoundIndex=min(i+2, len(numbers)-1)
        for j in range(i+1, len(numbers)-1):
            #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code
            upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j])
            if upperBoundIndex != -1:
                for k in range(j+1, upperBoundIndex+1):
                    results.add((numbers[i],numbers[j],numbers[k]))

    return results

if __name__ == "__main__":
    #print findTriagles([4,5,6,7]) # output, set([(4, 6, 7), (4, 5, 7), (4, 5, 6), (5, 6, 7)])
    print findTriagles([4, 4, 6, 7]) # output, set([(4, 4, 6), (4, 4, 7), (4, 6, 7)])


texts:
I decided to write a function that would generate an index of the Fibonacci sequence making use of Python's mutable default parameter. It's inspired by a question I answered on Stack Overflow where someone was converting a script with this idea from JavaScript to Python and I wanted to expand on it to see how I could handle it.

I wanted to basically try calling an index of the list and if it doesn't exist, try generating it from the previous two indices. However if they don't exist, then keep going back until two existing cached results are found and work off of those. I wanted to guard against errors from exceeding the recursion depth without necessarily rejecting a number. For instance, calling fib(1800) immediately exceeds (my) recursion depth, but my while loop will allow you to get the result.

For values that prove too high, I reject them with a ValueError. Though this does print every line of the recursive call's error. I'd like to know how I can handle this raise better to avoid that.

I'd also like to know if I could actually increase the viable number, if there's a good way to calculate what is a reasonable number better. I currently halve the recursion limit value mostly for safety but I'm sure that's not the best way. I'm also interested to know about any potential dangers of the cache getting too large and how those should be dealt with.

from sys import getrecursionlimit

rec = getrecursionlimit() * 0.9

def fib(n, rec=rec, memo=[0,1]):
    """Return the sum of the fibonacci sequence up until n

    rec is the recursion limit, and should be left as default.
    memo is the cached list of fibonacci values.
    raises a ValueError if your value is too high.
    If that happens, call lower values to build up the cache first."""

    while (n - len(memo)) >= rec:
        rec /= 2
        try:
            fib(int(len(memo) + rec), rec)
        except RuntimeError:
            raise ValueError("Input is too high to calculate.")

    try:
        return memo[n]
    except IndexError:
        # Calculate the answer since it's not stored
        memo.append(fib(n - 1) + fib(n - 2))
        return memo[n]


texts: C# AES Encryption/Decryption or byte[] array with a custom Key/IV

texts:
I wanted to create an AES encryption service which will use a custom key/iv.
I want 2 methods: dycrypt/encrypt byte[]
The code works as expected, any remarks/issues?
public class AesGenericEncryptionService
{
    private readonly byte[] m_Key;
    private readonly byte[] m_IV;

    public AesGenericEncryptionService(byte[] key, byte[] iv)
    {
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException(nameof(key));
        if (iv == null || iv.Length <= 0)
            throw new ArgumentNullException(nameof(iv));

        m_Key = key;
        m_IV = iv;
    }

    public byte[] Encrypt(byte[] data)
    {
        byte[] encrypted;

        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.KeySize = m_Key.Length * 8;
            rijAlg.Key = m_Key;
            rijAlg.BlockSize = m_IV.Length * 8;
            rijAlg.IV = m_IV;

            using (ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV))
            {
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(data, 0, data.Length);
                        csEncrypt.FlushFinalBlock();

                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
        }

        return encrypted;
    }
    public byte[] Decrypt(byte[] cipher)
    {
        // Check arguments.
        if (cipher == null || cipher.Length <= 0)
            throw new ArgumentNullException(nameof(cipher));

        byte[] dycrypted = null;
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.KeySize = m_Key.Length * 8;
            rijAlg.Key = m_Key;
            rijAlg.BlockSize = m_IV.Length * 8;
            rijAlg.IV = m_IV;

            using (ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV))
            {
                using (MemoryStream ms = new MemoryStream(cipher))
                {
                    using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        dycrypted = new byte[cipher.Length];
                        var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);

                        dycrypted = dycrypted.Take(bytesRead).ToArray();
                    }
                }
            }
        }

        return dycrypted;
    }
}


texts:
From SICP:

  Exercise 2.60.  We specified that a
  set would be represented as a list
  with no duplicates. Now suppose we
  allow duplicates. For instance, the
  set {1,2,3} could be represented as
  the list (2 3 2 1 3 2 2). Design
  procedures element-of-set?,
  adjoin-set, union-set, and
  intersection-set that operate on this
  representation. How does the
  efficiency of each compare with the
  corresponding procedure for the
  non-duplicate representation? Are
  there applications for which you would
  use this representation in preference
  to the non-duplicate one?

I wrote the following solution (some parts came from the book):

(define (element-of-set? x set)
  (cond ((null? set) false)
        ((equal? x (car set)) true)
        (else (element-of-set? x (cdr set)))))

(define adjoin-set cons)

(define (intersection-set set1 set2)
  (cond ((or (null? set1) (null? set2)) '())
        ((element-of-set? (car set1) set2)
         (cons (car set1)
               (intersection-set (cdr set1) set2)))
        (else (intersection-set (cdr set1) set2))))

(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((null? set2) set1)
        (else (cons (car set1) (union-set (cdr set1) set2)))))1)


texts: Generating a valid course object in my data provider

texts:
I have an education API and a simple data provider to get myself a basic course.  How can I improve on this?  I feel my approach is lackluster here regarding generating the data for the course and may run into sync issues?

import models.educationapi.Course;

@RunWith(DataProviderRunner.class)
public class EducationAPIDataProvider {

    public static int educationIncrement = 0;
    public static final String COURSENAME = "save-course-n-";
    public static final String COURSEDESC = "save-course-d-";
    public static final String MODULENAME = "save-module-n-";
    public static final String LESSONNAME = "save-lesson-n-";
    public static final String OVER50CHARS = "over50charsover50charsover50charsover50charsover50chars";

    @DataProvider
    public static Object[][] basicCourse() {
        educationIncrement++;
        Course course = new Course(0, COURSENAME+educationIncrement, COURSEDESC+educationIncrement, 0, 1, false);
        return course == null ? new Object[][] {{null}} : new Object[][] {{course}};
    }

What is the best approach to generate a new course every time to ensure the data is going to be unique?  This will work, but I don't feel it's a smart way of doing things.  I am unsure of the best approach.


texts: Add/Remove class on scroll depending on scroll length

texts:
I am a jQuery beginner and would like some pointers on whether the following code could be made shorter, or there is a better way to get the same result.

jQuery(document).ready(function(){
     var aa=jQuery('#navigation-wrapper');
     var bb=jQuery('#top');
     jQuery(window).scroll(function(){

        if(jQuery("body").hasClass("home")){
            if(jQuery(this).scrollTop()>510){
                aa.addClass("navbar-fixed-top");
                //bb.css('marginTop', aa.height());
             }
            else{
                aa.removeClass("navbar-fixed-top");
                //bb.css('marginTop', 0);
            }
        }
        else {
           if(jQuery(this).scrollTop()>293){
             aa.addClass("navbar-fixed-top");
           //bb.css('marginTop', aa.height());
            }
            else{
                aa.removeClass("navbar-fixed-top");
                //bb.css('marginTop', 0);
            }
        }
     });
  });


texts: Addition/Deletion records based on method argument

texts:
I have one method for addition and deletion of the account records. It has method argument based on which addition or deletion happens.

Below is method

char ADD = 'Y';
char DELETE = 'N';
private void updateAccountDtls(AccountDtlsDTO accountDtlsDTO, char addOrDeleteRecord){
    if (ADD == addOrDeleteRecord) {
        //account addition related processing
    }
    else if (DELETE == addOrDeleteRecord) {
        //account deletion related processing
    }
}

which is consumed in switch like below

switch (action) {
        case SET:
            updateAccountDtls(accountDtlsDTO,ADD);
            break;
        case RESET:
             updateAccountDtls(accountDtlsDTO,DELETE);
            break;
        }

from performace perspective is this good practice to use character instaed of string for Yes/No?


texts:
I have created a cumulative profiler,
meaning it runs a function several times in a row and prints the cumulative profiler results.

it's python >= 3.6 specific, but you can remove nonlocal and the type hints for it work on older versions.

import cProfile, pstats
from typing import Union, List, Callable, Optional, Tuple, Any

DEFAULT_AMOUNT = 5

class ProfileFunc:
    def __init__(self, func: Callable, sort_stats_by: str):
        self.func: Callable = func
        self.profile_runs: List[cProfile.Profile] = []
        self.sort_stats_by: str = sort_stats_by

    def __call__(self, *args, **kwargs) -> Tuple[Any, pstats.Stats]:
        pr = cProfile.Profile()
        pr.enable()  # this is the profiling section
        retval = self.func(*args, **kwargs)
        pr.disable()

        self.profile_runs.append(pr)
        ps = pstats.Stats(*self.profile_runs).sort_stats(self.sort_stats_by)
        return retval, ps

def cumulative_profiler(amount_of_times: Optional[Union[Callable, int]] = DEFAULT_AMOUNT,
                        sort_stats_by: str='time') -> Callable:

    def real_decorator(func: Callable):
        def wrapper(*args, **kwargs):
            nonlocal func, amount_of_times, sort_stats_by

            profiled_func = ProfileFunc(func, sort_stats_by)
            assert amount_of_times > 0, 'Cant profile for less then 1 run'
            for i in range(amount_of_times):
                retval, ps = profiled_func(*args, **kwargs)
            ps.print_stats()
            return retval  # returns the results of the function

        return wrapper

    # in case you don't want to specify the amount of times
    if callable(amount_of_times):
        the_func = amount_of_times  # amount_of_times is the function in here
        global DEFAULT_AMOUNT
        amount_of_times = DEFAULT_AMOUNT
        return real_decorator(the_func)
    return real_decorator

Example

profiling the function baz

import time

@cumulative_profiler
def baz():
    time.sleep(1)
    time.sleep(2)
    return 1

baz()

baz ran 5 times and printed this:

         20 function calls in 15.003 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       10   15.003    1.500   15.003    1.500 {built-in method time.sleep}
        5    0.000    0.000   15.003    3.001 <ipython-input-9-c89afe010372>:3(baz)
        5    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

specifying the amount of times

@cumulative_profiler(3)
def baz():
    ...

One small problem is that pstats.Stats is called each time instead of only one time in the end. however I don't think it's an expensive operation and it doesn't affect the results.


texts:
I have the following code to share my website through some social networks when the user clicks some divs with the appropriate icons.

var loc = encodeURIComponent(document.location.href);
$(document).ready(function() {
  $("#shareFacebook").click(function() {
    window.open('https://www.facebook.com/sharer/sharer.php?u=' + loc, '_blank');
  });
  $("#shareTwitter").click(function() {
    window.open('https://twitter.com/share?url=' + loc + '&amp;text=myText', '_blank');
  });
  $("#shareGooglePlus").click(function() {
    window.open('https://plus.google.com/share?url=' + loc, '_blank');
  });
  $("#shareLinkedIn").click(function() {
    window.open('https://www.linkedin.com/shareArticle?mini=true&url=' + loc + '&title=mySite&summary=myText', '_blank');
  });
  $("#sharePinterest").click(function() {
    window.open('https://pinterest.com/pin/create/button/?url=http://mysite.com/logo.png&media=Logo&description=myText', '_blank');
  });
});

Facebook

Twitter

Google+

LinkedIn

Pinterest

(Even if the code works, for some reason, the snippet does not.)

Can it be made more efficient?


texts: JavaScript code for countdown function is maxing CPU usage

texts:
I have a script for a countdown function, which is using massive amounts of CPU power on my MBP.

The script updates the countdown display every second and is updating all piecharts as well.

    var options = {
        scaleColor: false,
        trackColor: 'rgba(255,255,255,0.3)',
        barColor: '#E7F7F5',
        lineWidth: 6,
        lineCap: 'butt',
        size: 95
    };

    $('#days').easyPieChart(options);
    $('#hours').easyPieChart(options);
    $('#minutes').easyPieChart(options);
    $('#seconds').easyPieChart(options);

function countdown(endT,callback) {
        var first_load = false;
        var days,hours,minutes,sec,timer;

        end = new Date(endT);

        end = end.getTime();                     //Get initial Date in Milliseconds
        if (isNaN(end)) {
            return;

        }
        var tot_current = new Date();
        var tot_remain = parseInt((end - tot_current.getTime())/1000);
        var tot_days = parseInt(tot_remain/86400);

        timer = setInterval(calculate,1000);
        function calculate(){
            var current = new Date();
            var remaining = parseInt((end - current.getTime())/1000); //remaining seconds

            if (remaining <= 0){
                clearInterval(timer);
                days=0;
                hours=0;
                minutes=0;
                sec=0;
                display(days,hours,minutes,sec);
                if (typeof callback === 'function' ) {
                    callback();
                }

            }else{

                days = parseInt(remaining/86400);
                remaining = (remaining%86400);
                hours = parseInt(remaining/3600);
                remaining = (remaining%3600);
                minutes = parseInt(remaining/60);
                remaining = (remaining%60);
                sec = parseInt(remaining);
                display(days,hours,minutes,sec);

            }
        }
        function display(days,hours,minutes,sec) {
            var dl = days.toString().length;
            if (dl == "1") {
                sl = 2;
            }else{
                if (isNaN(dl)) {
                    sl = 3;
                }
                sl = dl;
            }

            days_rem = ("00"+days).slice(-sl);
            hrs_rem = ("0"+hours).slice(-2);
            min_rem = ("0"+minutes).slice(-2);
            sec_rem = ("0"+sec).slice(-2);
            $("#days span").text(days_rem);
            $("#hours span").text(hrs_rem);
            $("#minutes span").text(min_rem);
            $("#seconds span").text(sec_rem);
            $("#days").data('easyPieChart').update((100/tot_days)*days_rem);

            // Disable animation for the first load
            if(hrs_rem == 23 && first_load) { $('#hours').data('easyPieChart').disableAnimation(); }
            $("#hours").data('easyPieChart').update((100/23)*hrs_rem);
            if(hrs_rem == 23 && first_load) { $('#hours').data('easyPieChart').disableAnimation(); }

            if(min_rem == 59 && first_load) { $('#minutes').data('easyPieChart').disableAnimation(); }
            $("#minutes").data('easyPieChart').update((100/59)*min_rem);
            if(min_rem == 59 && first_load) { $('#minutes').data('easyPieChart').enableAnimation(); }

            if(sec_rem == 59 && first_load) { $('#seconds').data('easyPieChart').disableAnimation(); }
            $("#seconds").data('easyPieChart').update((100/59)*sec_rem);
            if(sec_rem == 59 && first_load) { $('#seconds').data('easyPieChart').enableAnimation(); }

            first_load = true;
        }

    }

    var d = new Date(2015, 6, 10, 12, 7, 0, 0);
    countdown(d,null);

The code can be seen in action here.


texts: Filter for logging http request parameters

texts:
I have written a filter that intercepts http calls and logs request parameters.

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain filterChain) throws IOException,
        ServletException
    {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String uri = httpRequest.getRequestURI();
        String queryString = httpRequest.getQueryString();
        long startTime = System.currentTimeMillis();
        if (shouldBeRedirected(uri)) {
            String type = getType(uri);
            String redirectUrl = Util.getURLBasedUponStabilityLevel(Constants.STABILITY_LEVEL);
            ((HttpServletResponse) response).sendRedirect(redirectUrl + type);
            return;
        }
        filterChain.doFilter(httpRequest, httpResponse);
        long endTime = System.currentTimeMillis();
        Timestamp startTimestamp = Timestamp.getInstance(startTime);

        StringBuilder logString = new StringBuilder();
        logString.append("Request URL: ");
        logString.append(uri);
        logString.append(" Query String: ");
        logString.append(queryString);
        logString.append(" Session Id: ");
        logString.append(httpRequest.getRequestedSessionId());
        logString.append(" Took: ");
        logString.append(endTime - startTime);
        logString.append("milliseconds. ");
        logString.append(" StartTime: ");
        logString.append(startTimestamp);
        if(httpRequest.getMethod().equals("POST")){
            JSONObject postParameters = new JSONObject();
            Map parameterMap = httpRequest.getParameterMap();
            Iterator<Map.Entry<String, String[]>> it = parameterMap.entrySet().iterator();
            while (it.hasNext()) {
               Map.Entry<String, String[]> entry = it.next();
               if(entry.getValue().length == 1){
                   postParameters.put(entry.getKey(), entry.getValue()[0].toString());}
               else{
                  JSONArray valueList = new JSONArray();
                  for(String value : entry.getValue()){
                      valueList.add(value.toString());
                  }
                  postParameters.put(entry.getKey(), valueList);
               }
            }
            logString.append(" Post Parameters: ");
            logString.append(postParameters.toString());
        }
        LOG.info(logString.toString());
    }

Code looks a bit clumsy to me, any suggestions to improve this?


texts:
I made a pagination algorithm but in my opinion it is too complicated and it is quite difficult to be understood. This algorithm should show 5 pages where in the middle is the current page. It should also show two pages before and two pages after the selected page (if these pages exist).

So, I just want to generate the array which is underlined in the above picture.

Here is my code:

public class Pagination {

    private int totalPages;
    private int selectedPage;
    private int offset;

    public Pagination() {
    totalPages = 6;
    selectedPage = 4;
    offset = 5;
    }

    public static void main(String[] args) {
    Pagination pagination = new Pagination();

    System.out.println(pagination.buildPaginationConditions().toString());
    }

    private List<Integer> buildPaginationConditions() {

    if (selectedPage <= offset / 2) {
        return doShowFirstPages();
    }
    return buildPagination();
    }

    private List<Integer> doShowFirstPages() {

    List<Integer> pagination = new LinkedList<Integer>();

    for (int i = 1; i <= offset; i++) {
        if (totalPages >= i) {
        pagination.add(i);
        }
    }
    return pagination;
    }

    private List<Integer> buildPagination() {

    List<Integer> pagination = new LinkedList<Integer>();
    int delta = offset / 2; // How many pages to left/right
    int paginationMiddle = (int) Math.ceil((double) offset / 2);

    for (int i = 1; i <= offset; i++) {

        if (i < paginationMiddle) {
        pagination.add(selectedPage - delta);
        delta--;
        continue;
        }
        if (paginationMiddle == i) {
        pagination.add(selectedPage);
        delta = 1;
        continue;
        }
        if (totalPages >= selectedPage + delta) {
        pagination.add(selectedPage + delta);
        delta++;
        continue;
        }

        if (selectedPage >= totalPages - 1) {

        //If it is the last or the penultimate page shift the pages to the right woth 1/2 positions

        int noOfGapsInPagination = offset - pagination.size();
        int temp = new Integer(offset);
        for (int j = 0; j < noOfGapsInPagination; j++) {
            pagination.add(j, totalPages - (--temp));
        }
        break;
        }
    }

    return pagination;
    }
}

The algorithm works but I want to write that for loop from buildPagination() much more simpler because it looks too complicated now .

I know that I can to extract those pices of code from if conditions in smaller methods but it is not going to simplify the code to much. Do you have any suggestions?


texts:
I made a simple Python program which takes a list of unique numbers and orders them from smallest to greatest. The algorithm (which is actually quite similar to bubble sort) works like this:

Take the first number

If it is larger than the next number, switch them
If it is smaller than the next number, do nothing

Continue to next number until the algorithm has done this to everything in the list
Check if the list is in the correct order

If not, repeat the process
If it is, print out the list in order and time taken in seconds

import random
import time
import sys

sys.setrecursionlimit(10000)
value_list = []
# Create values
len_of_list = random.randint(8500, 10000)
for number in range(0, len_of_list):
    value_list.append(number)
random.shuffle(value_list)

def timeit(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print "The function {.__name__} took {:.15f} seconds to finish.".format(func, time.time() - start)
        return result
    return wrapper

def custom_sort():
    for index in range(0, len_of_list):
        if (index + 1) == len_of_list:
            if not check_results():
                custom_sort()
            elif check_results():
                print value_list
        else:
            if value_list[index] > value_list[index + 1]:
                smaller_val = value_list[index + 1]
                value_list[index + 1] = value_list[index]
                value_list[index] = smaller_val
            elif value_list[index] < value_list[index + 1]:
                continue

def check_results():
    for index in range(0, len_of_list):
        if (index + 1) == len_of_list:
            return True
        else:
            if value_list[index] < value_list[index + 1]:
                continue
            elif value_list[index] > value_list[index + 1]:
                return False

@timeit
def run():
    custom_sort()

run()

I have made a function called run() specifically so that @timeit only prints out one line stating how long it took to finish. custom_sort() sorts the numbers in the list for the first four bullets. check_results() checks if the list is in order like in the last three bullets. sys.setrecursionlimit(10000) is used so that I don't get a recursion error since the list can hold up to 10000 numbers.

Example output (due to reports of crashing, I will replace most of the values with ... , I hope you understand what the result should be):

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, ... 9669, 9670, 9671, 9672, 9673, 9674, 9675, 9676, 9677, 9678, 9679, 9680]
The function run took 24.037000179290771 seconds to finish.

Is there a way to shorten my code and make my algorithm faster? The slowest it has been is about 36 seconds to sort the maximum amount of numbers (10000).