texts: Preventing SQL injection by converting all characters to their ASCII values

texts:
In order to prevent SQL injection, I'm converting every character of a string to be inserted in the database into its ASCII value before performing the query. In order to read the value of the string from the database, I'm reversing the operation.

Is this method safe?

<?php
function toDatabase($string){
    $split = str_split(htmlspecialchars($string));
    $ascii = "";
    foreach($split as $letter){
        $ascii .= ord($letter).'-';
    }
    return $ascii;
}
function fromDatabase($string){
    $explode = explode("-",$string);
    $phrase = "";
    foreach($explode as $ascii_char){
        $phrase .= chr($ascii_char);
    }
    return $phrase;
}
$toBeInserted = toDatabase($_POST['comment']);
$connect = mysqli_connect("","","","");
$query = mysqli_query($connect,"INSERT INTO comments(comment) VALUES ('".$toBeInserted."')");
if(!$query){ die('Error!'); }
$fetch_query = mysqli_query($connect,"SELECT comment FROM comments");
if(!$fetch_query){ die('Error!'); }
while($assoc = mysqli_fetch_assoc($fetch_query)){
    echo fromDatabase($assoc['comment']).'<hr>';
}
?>


texts:
I have written small program in Python which reads the following file and stores the result into a dictionary. I am getting expected output but I think it can be done in a better way. I am using Python 3.
Input
check_name : xa25
not run:
del_l6w_
dl_l4w_
dl_l22w_
de_l3w_
ckt_pw_
ckt_pw_
run:
inv_w_
buf_w_
End

Code
import collections
def main():
    chk_cell = "input.txt"
    chk_cell_data = collections.defaultdict(dict)
    with open(chk_cell, "r") as fchk_cell:
        check_name = ""
        not_run_flag = False
        run_flag = False
        for data in fchk_cell.readlines():
            data = data.strip()
            if not data:
                continue
            if data.startswith('check_name'):
                data = data.split(":")
                check_name = data[1].strip()
                continue
            elif data.startswith('End') or '-' in data:
                check_name = ""
                not_run_flag = False
                run_flag = False
                continue
            elif data.startswith('not run'):
                chk_cell_data[check_name]['not_run'] = []
                not_run_flag = True
                continue
            elif data.startswith('run'):
                chk_cell_data[check_name]['run'] = []
                not_run_flag = False
                run_flag = True
                continue

            if not_run_flag:
                chk_cell_data[check_name]['not_run'].append(data)

            elif run_flag:
                chk_cell_data[check_name]['run'].append(data)
    print(chk_cell_data)

if __name__ == "__main__":
    main()


texts:
I'm trying to make a pathfinding algorithm for my project. I need it for a simulation and I need it to be fast!!!

I watched a few videos explaining the algorithm online and came up with the code below.

However, the performance varies a lot considering the start/finish points.
My project should have grids that go upwards of 500x500

A very slow example is the following, with a very small grid:

I have no idea what's making the algorithm so slow

Dir_Map = {
    "1": (1, 0),
    "2": (0, 1),
    "3": (-1, 0),
    "4": (0, -1),
    "5": (1, 1),
    "6": (-1, -1),
    "7": (1, -1),
    "8": (-1, 1)
}

class Node():
    def __init__(self, pos):
        self.x = pos[0]
        self.y = pos[1]
        self.g = 0
        self.h = 0
        self.f = 0
        self.beggining = 1
        self.parent = None

    def update(self, final):
        self.h = manhattan(self, final)
        self.f = self.f +  self.g

class Child(Node):
    def __init__(self, x, y, parent):
        Node.__init__(self, (parent.x + x, parent.y + y))
        self.g = abs(x) + abs(y) + parent.g
        self.beggining = 0
        self.came_from = (parent.x, parent.y)
        self.parent = parent

def sortbyF(node):
    return node.f

def manhattan(current, final):
    return abs(current.x - final.x) + abs(current.y - final.y)

def check_List(list, successor):
    for ind, val in enumerate(list):
            if (val.x, val.y) == (successor.x, successor.y):
                if val.f < successor.f:
                    return 1
    return 0

openlist = []
closedlist = []

def recursion(node):
    if node.beggining is 0:
        closedlist.append(node.came_from)
        recursion(node.parent)

def pfind(grid, start, finish):

    start_node = Node((start[0], start[1]))
    finish_node = Node((finish[0], finish[1]))
    Stop = 0
    openlist.append(start_node)

    while len(openlist) is not 0:
        current = openlist.pop(0)

        for dirs in Dir_Map.values():
            suc = Child(dirs[0], dirs[1], current)

            if grid[suc.x][suc.y] is not 1 and suc.x <= len(grid[:][1]) and suc.y <= len(grid[1][:]):
                suc.update(finish_node)

                if (suc.x, suc.y) == finish:
                    #Added so it adds the last step.
                    #New suc.came_from = finish
                    suc = Child(dirs[0], dirs[1], suc)
                    #retrace the path.
                    recursion(suc)
                    closedlist.reverse()
                    return closedlist

                if check_List(openlist, suc):
                    continue

                openlist.append(suc)

            else:
                 continue

        openlist.sort(key=sortbyF)

    return None

grid = [[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 1, 1, 0],
        [0, 0, 1, 0, 0, 0, 1, 0],
        [0, 0, 1, 0, 0, 0, 1, 0],
        [0, 0, 1, 1, 1, 1, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]]

print(pfind(grid, (0,0), (4,3)))


texts:
I'm looking for ways to optimize a program in C++ I wrote to count all the duplicates in a string and print the duplicated letters and the number of times my program takes all 256 ASCII inputs and only prints the duplicates once with the max number of duplicates. I had a really hard time writing it and needed to ask for help and a few people had some things to say about my design. You can read it here if you like.

How can I write my design better? And what can I do in the future to write better programs in class and in the workplace?

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
vector <char> alreadyprintedcharacters;
void findrepeats(string const&);
int main()
{
    string input;
    cout << "Enter the input : ";
    getline(cin, input);
    findrepeats(input);
    return 0;
}
void findrepeats(string const &in)
{
    int trackerOfDuplicates = 0;
    int asciiArray[256];
    char ch;
    int charconv;
    for (int i = 0; i < 256; i++) // creates my refference array for the comparison and sets all the values equal to zero
        asciiArray[i] = 0;
    for (unsigned int i = 0; i < in.length(); i++)
    {
        ch = in[i];
        charconv = static_cast<int>(ch);
        asciiArray[charconv]++;
        /*if (asciiArray[charconv] == 0)
        {
            asciiArray[charconv] = 1;
        }
        else if (asciiArray[charconv] > 0)
        {
            asciiArray[charconv] = asciiArray[charconv]++;
        }*/

    }
    bool trip = false;
    for (unsigned int i = 0; i < in.length(); i++)
    {
        char static alreadyprinted;
        char ch = in[i];

        if ((asciiArray[ch] > 1) && (ch != alreadyprinted) && (find(alreadyprintedcharacters.begin(), alreadyprintedcharacters.end(), ch)== alreadyprintedcharacters.end()))
        {
            cout << in[i] << " : " << asciiArray[ch] << endl;
            trip = true;
            alreadyprinted = ch;
            alreadyprintedcharacters.push_back(alreadyprinted);
        }

    }
    if (trip == false)
        cout << "No repeated characters were found.\n";
}


texts:
I want to pass the param from the request on the scope method in the model and serve it as json to be rendered by select2. Which is better?
1. Pass request from the controller like this
controller:
public function selectJson(Request $request)
{

    $request = Customer::getSelect2($request)

    return \Response::json($request);
}

model:
public function scopeGetSelect2($query, $request)
{
    $customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".$request->q."%");

    if($request->city_id)
    {
        $customers = $query->where("city_id", $request->city_id);

    }
    $customers = $customers->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return $formatted_tags;
}

2. Use request() helper in the model
Controller:
public function selectJson()
{

    $request = Customer::getSelect2()

    return \Response::json($request);
}

Model:
public function scopeGetSelect2($query)
{
    $customers = $query->select('id','name')->orderBy('name','asc')->where("name", "like", "%".request()->q."%");

    if($request->city_id)
    {
        $customers = $query->where("city_id", request()->city_id);

    }
    $customers = $customers->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return $formatted_tags;
}

Which is better in performance and best practice? And should I format the return in the model like above codes or in the controller like below:
public function selectJson()
{

    $customers = Customer::getSelect2()->limit(5)->get();
    $formatted_tags = [];

    foreach ($customers as $customer) {
        $formatted_tags[] = ['id' => $customer->id, 'text' => $customer->name];
    }

    return \Response::json($formatted_tags);
}

Or any other method or concern that I need to know?
Thanks in advance


texts:
I am new to programming (less than a year), and I would like to improve.

I solved a problem on CodeWars and copied both my solution and the top voted solution below. I listed specific questions after my solution.

I would like to know, what would be considered the better overall solution in a real production environment? Is abstracting the way I did better (even if I did not execute correctly)? Could someone provide advice to help me improve?

Description:

  There is a house with 4 levels. In that house there is an elevator.
  You can program this elevator to go up or down, depending on what
  button the user touches inside the elevator.

  levels can be only numbers: 0,1,2,3

  buttons can be strings: '0','1','2','3'

  possible return values are numbers: -3,-2,-1,0,1,2,3

  If the elevator is on the ground floor(0th level) and the user touches
  button '2' the elevator must go 2 levels up, so our function must
  return 2.

  If the elevator is on the 3rd level and the user touches button '0'
  the elevator must go 3 levels down, so our function must return -3.

  If the elevator is on the 2nd level, and the user touches button '2'
  the elevator must remain on the same level, so we return 0.

  We cannot endanger the lives of our passengers, so if we get erronous
  inputs, our elevator must remain on the same level.

  So for example:

  goto(2,'4') must return 0, because there is no button '4' in the    elevator.
  goto(4,'0') must return 0, because there is no level 4.
  goto(3,undefined) must return 0.
  goto(undefined,'2') must return 0.
  goto([],'2') must return 0 because the type of the input level is    array instead of a number.
  goto(3,{}) must return 0 because the type of the input button is    object instead of a number.

Top Voted Solution

def goto(level, button)
  return 0 unless (0..3).include?(level) && ('0'..'3').include?(button)
  button.to_i - level
end

My Solution

def goto(level, button)
  inputs_types_are_accepted = (level.is_a? Integer) && (button.is_a? String)
  if inputs_types_are_accepted
    current_floor, desired_floor = level.to_i, button.to_i
    if current_floor.between?(0, 3) && desired_floor.between?(0, 3)
      floor_change = desired_floor - current_floor
      return floor_change
    else
      return 0
    end
  else
    return 0
  end
end

With a method this small, is it correct to abstract the way I did?
If I change if current_floor.between?(0, 3) && desired_floor.between?(0, 3) to if (current_floor && desired_floor).between?(0, 3) then I failed some tests. Is there a clearer way to represent this?
Is there a way to remove one set of else return 0 end? I tried and failed tests.


texts: Creating List of String elements that occur a certain amount of times using only the List ADT

texts:
I am tasked with creating a list with no duplicates of all String elements, in this case first names, of an ArrayList. The method is passed a threshold, and the method must store the first name if it has occurred at least the amount of the threshold. The restriction is that I am only allowed to use the List ADT. I have this code storing it in a ArrayList and it works, but I am worried about the algorithmic complexity which seems to be \$O(n^2)\$ as a worst case. Is there a more efficient way of writing this method?

static List<String> commonFirstNames(ArrayList<Student> students, int threshold) {
    ArrayList<String> results = new ArrayList<String>();

    String[] nameArray;
    String firstName;
    int counter = 0;
    for (int i = 0; i < students.size(); i++) {
        nameArray = students.get(i).getName().split(" ");
        firstName = nameArray[0];

        boolean isInResults = results.contains(firstName);
        if (!isInResults) {
            for (int j = i; j < students.size(); j++) {
                String[] otherNameArray = students.get(j).getName().split(" ");
                String otherFirstName = otherNameArray[0];

                if (otherFirstName.equals(firstName)) {
                    counter++;
                }
            }
            if (counter >= threshold) {
                results.add(firstName);
            }
        }
            counter = 0;
    }

    return results;
}


texts: Implementing Flask create_app function with SqlAlchemy

texts:
I have a simple Flask app that realises rest-api with SQLAlchemy. I have written this create_app function:

views.py

def create_app(config):
   app.config.from_object(config)
   url = config.DATABASE_URI
   engine = create_engine(url)
   Base.metadata.create_all(engine)

   Base.metadata.bind = engine
   DBSession = sessionmaker(bind=engine)
   session = DBSession()
   app.db_session = session
   return app

and a typical view looks like:

views.py

@app.route('/restaurants', methods=['GET', 'POST'])
def all_restaurants_handler():
    if request.method == 'GET':
        # RETURN ALL RESTAURANTS IN DATABASE
        restaurants = app.db_session.query(Restaurant).all()
        return jsonify(restaurants=[i.serialize for i in restaurants])

So, when I write tests, I can pass to create_app function test configuration. Although this works, I have some doubts regarding design of this solution.
First of all, I don't like that I need to use app.db_session in order to get the session. Second, I am not sure if it's a good decision to initialize db in the create_app function.


texts:
For a small project, I had to implement Caesar encryption in Swift(4). I'm mainly looking for performance optimizations.

This whole code should be copy and pasteable in a playground and is functioning as expected as far as I can see.

import Foundation

let caesarNumber:Int = 7;

let alphabet_array:[Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

func encode(inputString: String) -> String {
   var resultString:String = ""

   for char in inputString {
       for i in 0...(alphabet_array.count-1) {
           if (char == alphabet_array[i]) {
               if (i + caesarNumber < alphabet_array.count-1) {
                   resultString.append(alphabet_array[i+caesarNumber])
               }
               else {
                   let subscripture:Int = (i+caesarNumber)%alphabet_array.count
                   resultString.append(alphabet_array[subscripture])
               }
           }
       }
   }
   return resultString
}

func decode(inputString: String) -> String {
   var resultString:String = ""

   for char in inputString {
       for i in 0...(alphabet_array.count-1) {
           if (char == alphabet_array[i]) {
               if (i - caesarNumber >= 0) {
                   resultString.append(alphabet_array[i-caesarNumber])
               }
               else {
                   resultString.append(
                      alphabet_array[alphabet_array.count+(i-caesarNumber)])
               }
           }
       }
   }
   return resultString
}

   let encodedString = encode(inputString: "zacharias")
   let decodeString = decode(inputString: encodedString);


texts:
This is my first little python project. I want to get to a point where i can solve chess puzzles like this one from puzzling.stackexchange. I want to be able to change the board size to something like 15*15 or 3*7 and still all rules to apply.

So far, you can just run the file and it gives all possible moves for a knight on a random starting position. You can also put it a given position in string form like "A5" for the variable "startKnight".

What can I do better? The letter number swap function to swap between the chess and matrix connotation looks so big and ugly...
The knightmoves function looks good to me, but maybe you can tell me what to improve :)

from random import randint

def letterNumberSwap(x):
    # change letters to numbers and vice versa
    if x == "A":
        return 1
    elif x == "B":
        return 2
    elif x == "C":
        return 3
    elif x == "D":
        return 4
    elif x == "E":
        return 5
    elif x == "F":
        return 6
    elif x == "G":
        return 7
    elif x == "H":
        return 8
    elif x == 1:
        return "A"
    elif x == 2:
        return "B"
    elif x == 3:
        return "C"
    elif x == 4:
        return "D"
    elif x == 5:
        return "E"
    elif x == 6:
        return "F"
    elif x == 7:
        return "G"
    elif x == 8:
        return "H"
    else:
        print("Something is wrong.")

moveList = [] # list of moves in matrix connotation
possibleMoves = [] # list of moves in chess connotation

def knightMoves(position):
    # calculate all knight moves from position
    column, row = list(position.strip().upper())
    column = letterNumberSwap(column)
    c,r = int(column), int(row)
    if (0 < (c - 2) <= 8):
        if (0 < (r - 1) <= 8):
            moveList.append([c - 2, r - 1])
        if (0 < (r + 1) <= 8):
            moveList.append([c - 2, r + 1])
    if (0 < (c - 1) <= 8):
        if (0 < (r - 2) <= 8):
            moveList.append([c - 1, r - 2])
        if (0 < (r + 2) <= 8):
            moveList.append([c - 1, r + 2])
    if (0 < (c + 1) <= 8):
        if (0 < (r - 2) <= 8):
            moveList.append([c + 1, r - 2])
        if (0 < (r + 2) <= 8):
            moveList.append([c + 1, r + 2])
    if (0 < (c + 2) <= 8):
        if (0 < (r - 1) <= 8):
            moveList.append([c + 2, r - 1])
        if (0 < (r + 1) <= 8):
            moveList.append([c + 2, r + 1])
    for entry in moveList:
        # back to chess connotation
        possibleMoves.append(letterNumberSwap(entry[0])+str(entry[1]))

randomStart = str(letterNumberSwap(randint(1,8)))+str(randint(1,8))
startKnight = randomStart
knightMoves(startKnight)
print("A Knight on " + startKnight + " can go to:")
for entry in possibleMoves:
    print(entry,end = ' ')


texts: Extension of PHP `round()` for PHP_ROUND_UP and PHP_ROUND_DOWN - follow-up

texts:
The original question can be found here.

While looking at PHP.net this afternoon, I saw a comment in round() for two functions for rounding UP and DOWN (as opposed to just HALF_UP and DOWN).  I liked the suggestion, but wanted a solution that was one function, instead of 3.

The comment that sparked this for me is here.

I removed unnecessary preg_replace and got clever with xor to ensure mimicking round() behavior with negative numbers. As for the two empty() checks, these ensure less overhead than arithmetic if the provided number is 0. But I am open to arguments to remove them.

define('PHP_ROUND_UP',   11);
define('PHP_ROUND_DOWN', 12);

function fround($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
    if (is_numeric($number) && !empty($number)) {
        switch($mode) {
            case PHP_ROUND_UP:
            case PHP_ROUND_DOWN:
                if (!empty($precision)) {
                    $precision = pow(10, (int) $precision);
                    $number *= $precision;
                }
                if ($mode == PHP_ROUND_UP xor ($number < 0)) {
                    $number = ceil($number);
                } else {
                    $number = floor($number);
                }
                if (!empty($precision) && !empty($number)) {
                    $number /= $precision;
                }
                break;
            default:
                $number = round($number, $precision, $mode);
                break;
        }
    }
    return (float) $number;
}


texts:
In many of my personal projects, I have a login system very similar to the one I am about to describe. I understand how difficult correctly implementing authorization systems can be. I do this as a hobby and if I can do this securely myself, I would very much like to. (At work, I avoid homebrewed login solutions). I want to know if my approach is secure, and how I can improve it. I am using PHP 5.6 and the CodeIgniter 3 framework.

On register, I use password_hash with PASSWORD_BCRYPT.
Usernames must be unique, case insensitive (john and jOhN can't both
exist).
I only allow an IP to login x amount of time in x minutes (failed or
pass because alt accounts are usually discouraged). I have similar
restrictions on registering accounts.
I set a max password length of 64 and perform trim on start and end.
On login, I use password_verify to compare database result of
username row with user input.

For completeness, here is the most relevant (but not all) parts of auth code.

This is my controller

public function login()
{
    // Check if this is ip has logged in too many times
    $ip = $_SERVER['REMOTE_ADDR'];
    $timestamp = date('Y-m-d H:i:s', time() - $this->login_limit_window * 60);
    $route_url = 'user/login';
    $check_request_results = $this->main_model->check_request_route($ip, $route_url, $timestamp);
    if (count($check_request_results) > $this->login_limit && !is_dev()) {
        echo 'Too many login attempts from this IP. Please wait ' . $this->login_limit_window . ' minutes.';
        die();
    }

    // Validation
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[32]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|max_length[64]|callback_login_validation');

    // On fail set fail message and redirect to map
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('failed_form', 'login');
        $this->session->set_flashdata('validation_errors', validation_errors());
        redirect(base_url(), 'refresh');
        return false;
    }
    // Success
    redirect(base_url(), 'refresh');
}

// Validate Login Callback
public function login_validation($password)
{
    // Get other parameters
    $username = $this->input->post('username');
    // Compare to database
    $result = $this->user_model->login($username, $password);
    // Username not found
    if (!$result) {
        $this->form_validation->set_message('login_validation', 'Invalid username or password');
        return false;
    }
    // Password does not match
    else if (!password_verify($password, $result['password'])) {
        $this->form_validation->set_message('login_validation', 'Invalid username or password');
        return false;
    }
    // Success, do login
    $sess_array = array(
        'id' => $result['id'],
        'username' => $result['username']
    );
    $this->session->set_userdata('logged_in', $sess_array);
    return true;
}

And this is my model

// Login database call
function login($username, $password)
{
   $this->db->select('*');
   $this->db->from('user');
   $this->db->where('username', $username);
   $this->db->limit(1);
   $query = $this->db->get();
   if ($query->num_rows() == 1) {
       $result = $query->result_array();
       return isset($result[0]) ? $result[0] : false;
   }
   else {
       return false;
   }
}


texts:
I am looking for any performance insights or better coding style for my rendering method.

public Bitmap bmp;
public void render()
{
    Brush[] brushes = new SolidBrush[NumOfShapes];
    PointF[][] points = new PointF[NumOfShapes][];
    float[] tensions = new float[NumOfShapes];

    // We have multiply shapes, every shape has parameters for brush,points,tension
    for (int i = 0; i < NumOfShapes; i++)
    {
        int curT = i * ParameterNumber;
        brushes[i] = getBrush(curT); // get value and clip it if need
        points[i] = getPoints(curT);
        tensions[i] = getTension(curT);
    }

    using (Graphics graphics = Graphics.FromImage(bmp))
    {
        graphics.Clear(Color.Black);
        graphics.SmoothingMode = Globals.smoothingMode;
        for (int i = 0; i < NumOfShapes; i++)
        {
            graphics.FillPolygon(brushes[i], points[i]);
            // I also use shapes bellow
            //graphics.FillClosedCurve(brushes[i], points[i]);
            //graphics.DrawPolygon(new Pen(brushes[i],tensions[i]), points[i]);
            //graphics.FillClosedCurve(brushes[i], points[i], FillMode.Alternate, tensions[i]);
            //graphics.DrawCurve(new Pen(brushes[i], tensions[i]), points[i]);
        }

        graphics.Flush();
    }
}

With this, I am currently getting ~2000 bitmaps per second.

Generated bitmap is not displayed, I just get pixels with Marshal.Copy() and dispose bitmap. So is there a quicker way to render bitmap from shapes and get pixels.

private SolidBrush getBrush(int curT)
{
    parameters[curT] = clippingColor(parameters[curT]);
    parameters[curT + 1] = clippingColor(parameters[curT + 1]);
    parameters[curT + 2] = clippingColor(parameters[curT + 2]);
    parameters[curT + 3] = clippingColor(parameters[curT + 3]);
    Color color = Color.FromArgb(Convert.ToInt32(parameters[curT]), Convert.ToInt32(parameters[curT + 1]), Convert.ToInt32(parameters[curT + 2]), Convert.ToInt32(parameters[curT + 3]));
    return new SolidBrush(color);
}

private float getTension(int curT)
{
    parameters[curT + 4] = clippingTension(parameters[curT + 4]);
    return Convert.ToSingle(parameters[curT + 4]);
}

private PointF[] getPoints(int curT)
{
    PointF[] tempPoints = new PointF[(ParametersNum - 5) / 2];
    int pointsIndex = 0;
    int endSize = curT + ParametersNum;
    for (int j = curT + 5; j < endSize; j += 2)
    {
        parameters[j] = clippingPointsX(parameters[j]);
        parameters[j + 1] = clippingPointsY(parameters[j + 1]);
        tempPoints[pointsIndex] = new PointF(Convert.ToSingle(parameters[j]), Convert.ToSingle(parameters[j + 1]));
        pointsIndex++;
    }
    return tempPoints;
}

Update

I change bitmap pixel format to Format32bppPArgb and added rendering settings to graphics object as described in this guide: Rendering fast with GDI+ - What to do and what not to do! With this I am getting around ~2300 rendered bitmaps per second.

graphics.CompositingMode = CompositingMode.SourceOver;
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.PixelOffsetMode = PixelOffsetMode.None;
graphics.InterpolationMode = InterpolationMode.Default;


texts: SQL query for selecting count from grouped columns of latest records

texts:
I have this table on SQL:

record_type | user | date
type_1      | user1| 2018-09-27T09:13:15.946545
type_2      | user1| 2018-09-27T09:13:30.052329
type_1      | user1| 2018-09-27T09:11:18.724686
type_2      | user1| 2018-09-27T08:11:18.724686
type_1      | user2| 2018-09-25T09:13:15.946545
type_2      | user2| 2018-09-25T09:13:30.052329
type_1      | user2| 2018-09-25T09:11:18.724686
type_2      | user2| 2018-09-25T08:11:18.724686

I need to count how many users for a record_type have data older than X days.
Expected result for record older than a day is:

record_type | count
type_1      | 2
type_2      | 2

This is my query:

select record_type, count(*)
from (select record_type, user, max(date) as MaxDate
      from table
      group by record_type, user
      having to_timestamp(max(date), 'YYYY-MM-DD HH24:MI:SS.M') < NOW() - interval '15' day
      order by MaxDate desc
) as test
group by record_type;

This works, but I wonder if there's a better way?


texts: Superscript all numeric characters after ^ in an excel cell

texts:
I have material property entries in a cell those look something like this:

cell.value="O2 Permeability [cm^3/m^2]"

The goal is to format the numeric value after each ^ to be superscripted and to remove all ^.

Here my code:

Public Function FormatSuperscript(cell As Range) As Boolean
Dim i As Integer
Dim value As String
Dim cnum As New Collection
Dim num As Integer
Dim clen As New Collection

value = cell.value

num = 0

' first count the amount of ^

num = InStr(num + 1, value, "^")
If num <> 0 Then
    cnum.Add num
    ' count the length of the numeric entry
    clen.Add SuperScriptLength(value, num)
End If

While num <> 0
    num = InStr(num + 1, value, "^")
    If num <> 0 Then
        cnum.Add num
        ' count the length of the numeric entry
        clen.Add SuperScriptLength(value, num)
    End If
Wend

' remove all ^
cell.value = Replace(value, "^", vbNullString)

' go through all ^ places and superscript the length of the numeric entry from there on
For i = 1 To cnum.count
    cell.Characters(Start:=cnum(i) - i + 1, Length:=clen(i)).Font.Superscript = True
Next i

FormatSuperscript = True

End Function
Private Function SuperScriptLength(value As String, StartCharacter As Integer) As Integer
Dim s As String
Dim c As Integer
Dim i As Integer

c = 0
s = Right(value, Len(value) - StartCharacter)
While StringPop(s) = "-" Or IsNumeric(StringPop(s))
    c = c + 1
    s = Right(s, Len(s) - 1)
Wend

SuperScriptLength = c
End Function

Private Function StringPop(ByRef s As String) As String
StringPop = Left(s, 1)
End Function

Any suggestions on how to improve the run time on it?


texts: Remove all vowels from a string except an initial character

texts:
I've written the following code where all vowels are removed from a string except if the string starts with a vowel then this vowel is maintained.

def removeVowels(string):
    output = string[0]

    for char in string[1:]:
        if char.lower() not in 'aeuio':
            output += char
    return output

I was wondering if it's possible to use a list comprehension for this?


texts: App for a tabletop RP that generates hits and misses for weapons

texts:
I'm looking for tips on cleaning this up. I think it's legible, but it sure ain't pretty. In particular, I'd love to clean up the hitCheck function. I've dealt with switches before in other languages, so I was kind of stuck on trying simulating that. getReady looks messy to me, but I'm not sure how I'd go about tidying that up either.

import random
import time

def hitCheck(rng, acc):
    hitTotal = acc + rng
    if hitTotal > 190:
        print("CRIT! HEADSHOT!")
        return 5
    if 160 < hitTotal < 191:
        print("Lethal!")
        return 4
    if 120 < hitTotal < 161:
        print("Severe!")
        return 2
    if 80 < hitTotal < 121:
        print("Ouch!")
        return 1
    if 40 < hitTotal < 81:
        print("Grazed!")
        return 0.5
    if 0 < hitTotal < 41:
        print("Miss!")
        return 0

def firing(begin):
    print("BANG!")
    #end & start variables are used to tell how fast the user is pressing the key.
    #The faster they go, the more inaccurate their shots.
    end = time.time()
    accuracy = int((end - begin) * 60)
    if accuracy > 100:
        accuracy = 100
    #print("Accuracy: ", accuracy)
    #Not sure if this 'luck' generator is mathematically different
    #from just using 'int((random.random() * 100))'.
    luck1 = int((random.random() * 50))
    luck2 = int((random.random() * 50))
    luck = luck1 + luck2
    #print("Luck: ", luck)
    return hitCheck(luck, accuracy)

#Here's the main part of the app.
def getReady():
    running = False
    while not running:
        i = 0
        downed = 0
        total = 0
        while True:
            print("\n")
            total = input('Max attempts: ')
            print("\n")
            if total == '' or int(total) < 0:
                print("Value must be higher than 0!")
            else:
                total = int(total)
                break

        print("Fire away!")
        while i < total:
            #Other half to figuring out the accuracy.
            start = time.time()
            input()
            downed += firing(start)
            i += 1
            print(total - i, " shots left.")
            time.sleep(0.1)

        #Print the results!
        print("\n")
        print("Injuries:", int(downed))
        print("You felled", round(downed / 5), "foes!")
        print("\n")

        #Shall we continue?
        while True:
            running = input("More? yes / no: ")
            if running in ('no', 'n'):
                running = True
                break
            elif running in ('yes', 'y'):
                running = False
                break
            else:
                continue

getReady()


texts: Transform Bitmap object into jagged array of RGB tuple values

texts:
I've been working on this module with the assistance of codereview, and based on the responses and my own research, this is my project so far. The goal behind the code is that it starts with a .NET bitmap object, extracts the byte array of image data from the bitmap, then transforms it into an array of arrays or matrix.

The idea behind putting the bitmap data into the matrix is that I want to be able to use a simple representation of a coordinate, like Array[10][20], to get the RGB value for the pixel located at the (10, 20) coordinate. Rather than using a proper 2D array, I'm choosing to use an array of arrays, or "jagged" array, for speed concerns.

Your assistance with sanity, style, F# conventions, and any other problems you spot is appreciated in helping further refine this algorithm.

open System
open System.Drawing
open System.Drawing.Imaging
open System.Runtime.InteropServices

module ImageSearch =
    let LoadBitmapIntoArray (pBitmap:Bitmap) =
        let tBitmapData = pBitmap.LockBits( Rectangle(Point.Empty, pBitmap.Size),
                                            ImageLockMode.ReadOnly,
                                            PixelFormat.Format24bppRgb )

        let tImageArrayLength = Math.Abs(tBitmapData.Stride) * pBitmap.Height
        let tImageDataArray = Array.zeroCreate<byte> tImageArrayLength

        Marshal.Copy(tImageDataArray, 0, tBitmapData.Scan0, tImageArrayLength)
        pBitmap.UnlockBits(tBitmapData)

        pBitmap.Width, tImageDataArray

    let Transform2D ( (pArrayWidth:int), (pArray:byte[]) ) =
        let tHeight = pArray.Length / ( pArrayWidth * 3 ) // 3 bytes per RGB

        let tImageArray = [|
            for tHeightIndex in [ 0 .. tHeight - 1] do
                let tStart  = tHeightIndex * pArrayWidth
                let tFinish = tStart + pArrayWidth - 1
                yield [|
                    for tWidthIndex in [tStart .. 3 .. tFinish] do
                        yield ( pArray.[tWidthIndex]
                              , pArray.[tWidthIndex + 1]
                              , pArray.[tWidthIndex + 2] )
                |]
        |]

        tImageArray

    let SearchBitmap (pSmallBitmap:Bitmap) (pLargeBitmap:Bitmap) =

        let tSmallArray = Transform2D <| LoadBitmapIntoArray pSmallBitmap
        let tLargeArray = Transform2D <| LoadBitmapIntoArray pLargeBitmap

        let mutable tMatchFound = false


texts: Wrapping single line string to multiple lines with specific length

texts:
Problem

A single line should be separated by Environment.NewLine so that each row has a length of columns (expect for the last one that may be shorter).

Below is my solution:

    public static string Wrap(this string singleLineString, int columns)
    {
        if (singleLineString == null)
            throw new ArgumentNullException("singleLineString");
        if (columns < 1)
            throw new ArgumentException("'columns' must be greater than 0.");

        var rows = Math.Ceiling((double)singleLineString.Length/columns);
        if (rows < 2) return singleLineString;

        var sb = new StringBuilder();

        for (int i = 0; i < rows; i++)
        {
            if (i > 0) sb.Append(Environment.NewLine);
            var index = i*columns;
            var length = Math.Min(columns, singleLineString.Length - index);
            var line = singleLineString.Substring(index, length);
            sb.Append(line);
        }

        return sb.ToString();
    }

Even if the problem is really simple, there are lots of thinkable approaches to solve it. Is there simpler / more elegant solution than the one above?


texts: PHP program which extracts attribute lists from custom tag

texts:
PHP program which extracts attribute list from the custom tag. It also strips out the single and double quote if it exists around attribute value.

<?php

function parseAnswerTag($tag)
{
    // input => <answer scale="10" points="7">
    // ouput => ["scale"=>10, "points"=>7]
    // get the answer tag and parse out the attributes of answer tag
    $returningObj = array();
    //get the splitted string as an array
    $arr = splitByDelimiter(array('delimiter' => " ", 'string'=> $tag));
    // sliced the array to just have attributes otherwise will have answer element too
    foreach (array_slice($arr, 1) as $key => $value)
    {
        $arr[$key] = splitByDelimiter(array('delimiter' => "=", 'string'=> $value));
        if(in_array('scale', $arr[$key]) or in_array('points', $arr[$key]))
        {
            // check to see if single or double quote exist in value of key
            if(preg_match("/['\"]/",$arr[$key][1]))
            {
                // makes a call to strip out the quotes
                $returningObj[$arr[$key][0]] = stripQuotes($arr[$key][1]);
            }
        }
    }
    // returns the associate key of attribute in the tag
    return $returningObj;
}

function stripQuotes($str)
{
    // input => "10"
    // output => 10
    // gets attribute with value and returns unquote string
    var_dump(strpos($str, "'") === FALSE);
    $start_point = 0;
    $end_point = 0;
    if(strpos($str, "'") !== FALSE)
    {
        $start_point = strpos($str, "'");
        $end_point = strpos($str, "'", $start_point+1);
    }
    elseif (strpos($str, '"') !== FALSE)
    {
        $start_point = strpos($str, '"');
        $end_point = strpos($str, '"', $start_point+1);
    }
    return substr($str, $start_point+1, $end_point - ($start_point+1));
}

function splitByDelimiter($input)
{
    //gets a associate array with delimiter and string {text value to be splitted}, split them by passed delimiter and return them
    // $input['delimiter'] => value splitted by and $input['string'] => value to be splitted
    return explode($input['delimiter'], $input['string']);
}

Can you please give me some constructive suggestions so that I can improve?


texts:
I am preparing for interviews where my code would be judged based on optimizations, OOP concepts, code readability as well as my knowledge of JAVA and design patterns.

What comments will you give in code review for the below code?

This is my code for Kth Largest element in an Array.
The logic is to create a K size max heap, and then add the smallest K elements to the heap.
Total array size can be equal to INT_MAX and k can be as small as 2

import java.util.Comparator;
import java.util.PriorityQueue;

public class CustomArray {

    class DecreasingComparator implements Comparator<Long> {

        @Override
        public int compare(Long firstNumber , Long secondNumber) {
            return (int) (secondNumber - firstNumber);
        }
    }

    public long findKthLargestElement(long[] input, int k) {
        if(k < 1 || k > input.length) {
            throw new IllegalArgumentException("Invalid k, should be between 1 and arra length");
        }

        PriorityQueue<Long> heap = new PriorityQueue<>(k, new DecreasingComparator());

        for(int i=0; i<k;i++) {
            heap.add(input[i]);
        }
        for(int i=k; i<input.length;i++) {
            if(heap.peek() > input[i]) {
                heap.poll();
                heap.add(input[i]);
            }
        }

        return heap.poll();
    }
}


texts: First missing positive with only primitives

texts:
As soon as I saw the First missing positive question, I decided to write my own method for this before writing my review on the question.

Judge me by the same standards as bazang wants to be judged, i.e. As if this was written for a big company such as Google for an interview.

I wasn't sure how the input 7, 8, 9 should be treated so to make it a bit harder for myself I gave myself the requirement that it should return 10.

@Test
public void test() {
    Assert.assertEquals(3, missingInt(new int[]{ 1, 2, 0 }));
    Assert.assertEquals(4, missingInt(new int[]{ 1, 2, 3 }));
    Assert.assertEquals(2, missingInt(new int[]{ 3, 4, -1, 1 }));
    Assert.assertEquals(10, missingInt(new int[]{ 7, 8, 9 }));

    Assert.assertEquals(5, missingInt(new int[]{ 3, 4, 2, 7, 6, 1 }));
    Assert.assertEquals(5, missingInt(new int[]{ 3, 4, 2, 7, 6, 1, -4 }));
}

public int missingInt(int[] array) {
    boolean[] foundIntegers = new boolean[array.length];
    int smallestPositive = Integer.MAX_VALUE;

    for (int i : array) {
        if (i > 0 && i < smallestPositive)
            smallestPositive = i;
    }

    for (int i : array) {
        if (i < smallestPositive)
            continue;

        int index = i - smallestPositive;
        if (index < foundIntegers.length)
            foundIntegers[index] = true;
    }

    for (int i = 0; i < foundIntegers.length; i++) {
        if (!foundIntegers[i])
            return i + smallestPositive;
    }
    return foundIntegers.length + smallestPositive;
}


texts: Batch program to xcopy from host PC to remote destination with multi-processing

texts:
This is a batch program to xcopy from host PC to remote destination with multi-processing.

Kepler, Python-3.x are my environment.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on Carnival http://ask.python.kr/users/6970/carnival/

import os
import os.path
import csv
import re

from multiprocessing import Process, Lock

class Server:
    def __init__(self, addr, path):
        self.addr = addr
        self.path = path

def distribute_file(server_list, pathname):
    print("Read from {}".format(pathname))

    with open(pathname, 'rb') as inFile:
        buffer = inFile.read()

    for server in server_list:
        remotepath = "//%s/%s/%s" % (server.addr, server.path, pathname)
        print ("Write to {}".format(remotepath))
        with open(remotepath, 'wb') as outFile:
            outFile.write(buffer)

def multi_distribute_file(lo, server, dirpath, filename, path):
    lo.acquire()

    pathname = os.path.join(dirpath, filename)
    print("Read from {}".format(pathname))

    with open(pathname, 'rb') as inFile:
        buffer = inFile.read()

    if(path == ''):
        remotepath = "//%s/%s/%s" % (server.addr, server.path, filename)
    else:
        remotepath = "//%s/%s/%s/%s" % (server.addr, server.path, path, filename)

    print ("Write to {}".format(remotepath))
    with open(remotepath, 'wb') as outFile:
        outFile.write(buffer)

    lo.release()

def make_dir(server_list, path):
    for server in server_list:
        dirpath = "//%s/%s/%s" % (server.addr, server.path, path)
        d = os.path.dirname(dirpath)
        if not os.path.exists(d):
            os.makedirs(d)
            print ("Make dir {}".format(d))
        else:
            print ("dir {} already exists.".format(d))

        if not os.path.exists(dirpath):
            os.makedirs(dirpath)
            print ("Make dir {}".format(dirpath))
        else:
            print ("dir {} already exists.".format(dirpath))

def dist_files(server_list, subdir):
    for dirpath, dirnames, filenames in os.walk(subdir):

        l = re.findall(r"[\w']+",subdir)
        m = re.findall(r"[\w']+",dirpath)
        path = ''
        if(l != m):
            path = m[len(m)-1]

        make_dir(server_list, path)
        for filename in filenames:
            for server in server_list:
                lock = Lock()
                Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, path)).start()

def get_server_list(filename):
    mydictionary = []
    csvFile = csv.reader(open(filename, "r"))
    for row in csvFile:
      mydictionary.append(Server(row[0], row[1]))
      print("{}, {}".format(row[0], row[1]))

    return mydictionary

if __name__ == '__main__':
    server_list = get_server_list('client_list.csv')
    dist_files(server_list, 'C:\\Users\\Public\\Test')

client_list.csv

  192.168.10.100, Test
  192.168.10.101, Test
  192.168.10.102, Test


texts: LeetCode: Increasing Order Search Tree C#

texts:
https://leetcode.com/problems/increasing-order-search-tree/

Please review for performance

  Given a binary search tree, rearrange the tree in in-order so that the
  leftmost node in the tree is now the root of the tree, and every node
  has no left child and only 1 right child.

  Constraints:

  The number of nodes in the given tree will be between 1 and 100. Each
  node will have a unique integer value from 0 to 1000.

using System.Collections.Generic;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/increasing-order-search-tree/
    /// </summary>
    [TestClass]
    public class IncreasingBstTest
    {
        [TestMethod]
        public void ExampleTest()
        {

                //      5
                //     / \
                //    3   6
                //   / \   \
                //  2   4   8
                // /      / \
                // 1     7   9

            TreeNode root = new TreeNode(5);
            root.left = new TreeNode(3);
            root.left.left = new TreeNode(2);
            root.left.right = new TreeNode(4);
            root.left.left.left = new TreeNode(1);

            root.right = new TreeNode(6);
            root.right.right = new TreeNode(8);
            root.right.right.left = new TreeNode(7);
            root.right.right.right = new TreeNode(9);
            var forEach = new InOrderForEach();
            root = forEach.IncreasingBST(root);

            int res = 1;
            var curr = root;
            while (curr != null)
            {
                Assert.AreEqual(res, curr.val);
                curr = curr.right;
                res++;
            }
        }
    }

    }

    public class InOrderForEach
    {
        public TreeNode IncreasingBST(TreeNode root)
        {
            if (root == null)
            {
                return null;
            }
            List<int> vals = new List<int>();
            InOrder(root, vals);
            var ans = new TreeNode(0);
            TreeNode curr = ans;
            foreach (var v in vals)
            {
                curr.right = new TreeNode(v);
                curr = curr.right;
            }
            return ans.right;
        }

        private void InOrder(TreeNode root, List<int> vals)
        {
            if (root == null)
            {
                return;
            }
            InOrder(root.left, vals);
            vals.Add(root.val);
            InOrder(root.right, vals);
        }

    }
}


texts: Filling in the card expiry date from transaction data

texts:
I'm integrating my app with a payment gateway, and have the following code which returns an array to populate the transaction info:

function populate_transaction_info($data)
{
  extract($this->extract_model_data($data));

  // set to empty array to ensure run-able code
  $transaction_info = [];

  return array_merge($transaction_info, [
    'pan' => $card_data['card_number'],
    'expdate' => $this->build_expiry_date_string($card_data['card_exp']),
    'cust_id' => $person['email'],
    // ... more params here, not relevant for question
  ]);
}

// shown for context / run-ability
function extract_model_data($data)
{
  return [
    'person' => $data['Person'],
    'card_data' => $data['CreditCard']],
  ];
}

My question pertains to the build_expiry_date_string(), defined as:

function build_expiry_date_string($card_expiry)
{
  return $card_expiry['month'] . substr($card_expiry['year'], -2);
}

I'm passing $card_data['card_exp'] into the function, but I'm wondering if the function itself should be the only thing that knows that it needs to look in the card_exp index of the array? So for example, should I refactor as:

...
'expdate' => $this->build_expiry_date_string($card_data),
...

function build_expiry_date_string($card_data)
{
  return $card_data['card_exp']['month'] . substr($card_data['card_exp']['year'], -2);
}

If yes, why?


texts: Object to object mapping verification - is this extension method useful?

texts:
In our .NET tests we use NSubstitute & ExpectedObjects.

Testing object expectations involves hand crafting large anonymous objects and when new properties are added we need to go back to these anonymous objects & update them.

Attempting below to get a fluent Object to DTO builder - which fails when a property is missed.

Here is the implementation:

        //CustomerCreatedEvent has all below properties
        var exp1 = @event.ToDto<CustomerCreatedEvent,CustomerDetail>(
            x=> x.AggregateId.As("CustomerId"),
            x => x.Email, // comment this out and test FAILS -> CustomerDetail.Email required
            x => x.FirstName,
            x => x.Surname);

        var exp2 = new {
                CustomerId= @event.AggregateId,
                @event.Email,      // comment this out and test still passes
                @event.FirstName,
                @event.Surname};

        exp1.ToExpectedObject().ShouldMatch(actual);
        exp2.ToExpectedObject().ShouldMatch(actual);

I have 2 questions:

Is my code just adding 'noise'?
Is the implementation code below sound?

public static TResult ToDto(this TSource obj, params Expression>[] items) where TSource : class
    {
        var eo = new ExpandoObject();
        var props = eo as IDictionary;

    foreach (var item in items)
    {
        var member = item.Body as MemberExpression;
        var unary = item.Body as UnaryExpression;
        var body = member ?? (unary != null ? unary.Operand as MemberExpression : null);

        if (member != null && body.Member is PropertyInfo)
        {
            var property = body.Member as PropertyInfo;
            props[property.Name] = obj.GetType()
                .GetProperty(property.Name)
                .GetValue(obj, null);
        }
        else
        {
            var property = unary.Operand as MemberExpression;
            if (property != null)
            {
                props[property.Member.Name] = obj.GetType()
                    .GetProperty(property.Member.Name)
                    .GetValue(obj, null);
            }
            else
            {
                var compiled = item.Compile();
                var output = (KeyValuePair<string, object>)compiled.Invoke(obj);
                props[output.Key] = obj.GetType()
                .GetProperty(output.Value.ToString())
                .GetValue(obj, null);
            }
        }
    }

    TResult result = Activator.CreateInstance<TResult>();
    foreach (var item in props)
    {
        result.GetType().GetProperty(item.Key).SetValue(result, item.Value, null);
    }

    return result;
}

}


texts: Increase performance of Bayesian likelihood equation

texts:
I need to calculate a Bayesian likelihood in its negative logarithmic form:

$$-\ln L = N\ln M -\sum\limits_{i=1}^{N} \ln\left\{P_i \sum\limits_{j=1}^M \frac{\exp\left[ -\frac{1}{2}\left(\sum_{k=1}^D \frac{(f_{ik}-g_{jk})^2}{\sigma_{ik}^2 + \rho_{jk}^2}\right) \right]}{\prod_{k=1}^D \sqrt{\sigma_{ik}^2 + \rho_{jk}^2}} \right\}$$

where these $$P_i\;\;;\;\; f_{ik} \;\;;\;\; \sigma_{ik}^2\;\;;\;\; g_{jk}
\;\;;\;\; \rho_{jk}^2$$ are all known floats. This is my code:

import numpy as np

# Define random data with correct shapes.
N, M = np.random.randint(10, 1000), np.random.randint(10, 1000)
D = np.random.randint(2, 5)
f_N, g_M = np.random.rand(N, D, 2), np.random.rand(M, D, 2)
P_i = np.random.uniform(0., 1., N)

# N summatory.
# Store here each 'i' element from the M summatory.
sum_Mi = []
for f_i in f_N:

    # M summatory.
    sum_M_j = 0.
    for g_j in g_M:

        # Obtain ijk element inside the M summatory
        D_sum, sigma_ijk = 0., 1.
        for k, f_ik in enumerate(f_i):
            # Where: f_ik[0] = \f_{ik}       ; g_j[k][0] = \g_{jk}
            # and:   f_ik[1] = \sigma_{ik}^2 ; g_j[k][1] = \rho_{jk}^2
            D_sum += np.square(f_ik[0] - g_j[k][0]) / (f_ik[1] + g_j[k][1])
            sigma_ijk = sigma_ijk * (f_ik[1] + g_j[k][1])

        sum_M_j += np.exp(-0.5 * D_sum) / np.sqrt(sigma_ijk)

    sum_Mi.append(sum_M_j)

sum_Mi_Pi = P_i * sum_Mi
# Remove 0. elements before applying the logarithm below.
sum_N = sum_Mi_Pi[sum_Mi_Pi != 0.]

# Final negative logarithmic likelihood
lik = len(f_N) * np.log(len(g_M)) - sum(np.log(sum_N))
print(lik)

I'm after an optimization done at the code level, ie: not using multi-threading.

I've tried numpy broadcasting on the inner loop

# Obtain ijk element inside the M summatory
D_sum = sum(np.square((f_i[:, 0] - g_j[:, 0])) / (f_i[:, 1] + g_j[:, 1]))
sigma_ijk = np.prod(f_i[:, 1] + g_j[:, 1])

but that actually takes a longer time to complete than using the for loop!

I also tried using the logsumexp function from scipy combined with the broadcasted arrays:

# Store here each 'i' element from the M summatory.
sum_N = 0.
# N summatory.
for f_i in f_N:

    # M summatory.
    A, B = [], []
    for g_j in g_M:
        # Obtain ijk element inside the M summatory
        A.append(sum(
            np.square((f_i[:, 0] - g_j[:, 0])) / (f_i[:, 1] + g_j[:, 1])))
        B.append(np.prod(f_i[:, 1] + g_j[:, 1]))

    sum_N += logsumexp(-.5 * np.array(A), b=1. / np.sqrt(B))

# Final negative logarithmic likelihood
lik = len(f_N) * np.log(len(g_M)) - sum(np.log(P_i[P_i != 0.])) - sum_N
print(lik)

This resulted in a marginal improvement over just using broadcasting, but still slower than the original code.


texts:
I have an ASP.NET MVC3 web application that displays a list of parts (a part is a simple entity with a number and a description).

I have updated the action method to support filtering and paging:

[HttpGet]
public ViewResult Index(int page = 1, int pageSize = 30, string filter = "All")
{
    IEnumerable<Part> parts;
    int totalParts;

    var acceptableFilters = new string[] {
        "All", "123", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
        "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    // This checks that the filter value received by the method is an acceptable value.
    // E.G. If a user types in a value in the query string that is not contained in the
    // array above, then the filter is reset to 'All' and all records are queried.
    if (!acceptableFilters.Contains(filter))
    {
        filter = "All";
    }

    if (filter == "All")
    {
        parts = Database.Parts
            .OrderBy(p => p.Number)
            .Skip((page - 1) * pageSize)
            .Take(pageSize);

        totalParts = Database.Parts.Count();
    }
    else if (filter == "123")
    {
        var numbers = new string[]{"1","2","3","4","5","6","7","8","9","0"};

        parts = Database.Parts
            .OrderBy(p => p.Number)
            .Where(p=> numbers.Contains(p.Number.Substring(0,1)))
            .Skip((page - 1) * pageSize)
            .Take(pageSize);

        totalParts = Database.Parts
            .Count(p => numbers.Contains(p.Number.Substring(0, 1)));
    }
    else
    {
        parts = Database.Parts
            .OrderBy(p => p.Number)
            .Where(p => p.Number.StartsWith(filter))
            .Skip((page - 1) * pageSize)
            .Take(pageSize);

        totalParts = Database.Parts.Count(p => p.Number.StartsWith(filter));
    }

    PartsListViewModel viewModel = new PartsListViewModel()
    {
        Filter = filter,
        PageInfo = new PageInfo(page, pageSize, totalParts),
        Parts = parts,
    };

    return View(viewModel);
}

The idea is this:

If the filter is equal to 'All' then query all records.
If the filter is equal to '123' then query all records that start with a number.
If the filter is equal to a letter (A, B, C) then query all records that begin with said letter.

Once the required records have been queried I then need to do some calculations to determine how many pages I have and how many items to display on each page.

This works perfectly but I do not like the code I currently have, specifically the if statement that determines the Linq query to be used as the majority of the code is identical except for the where clause (or lack of where clause if all records are being pulled down). I also don't like the fact that I have to run each query twice: once to get the records and a second time to determine the total record set size.

So, is there a better way of achieving the same result? can the Linq queries be restructured in a more elegant way to reduce the redundant code or is this the best way?


texts:
router/article.js
// =============================== GET / WITH PAGINATION ==============================

router.get('/?:page', async (req, res) => {
  const { page } = req.params; // current Page
  const { size } = req.params; // items per page
  const limit = size || 5; // if size isn't specified, set size to 5
  const offset = page ? (page - 1) * limit : 0; // skip previous items
  const navBarIndexLimit = 4; // how many page indexes to show in navigation bar like < 1 2 3 4 >
  const navBarIndexOffset = Math.floor(page / navBarIndexLimit); // offset previous indexes like < 5 6 7 8 >
  const navBarIndexArray = []; // index for navigating pages in view

  // fetch articles
  const articles = await Article.findAndCountAll({
    include: User,
    raw: true,
    nest: true,
    limit,
    offset,
  });
  const totalPage = Math.ceil(articles.count / limit);

  // if at last page, show previous indexes
  if (page >= totalPage) {
    for (let i = 0; i < navBarIndexLimit; i += 1) {
      const prevPage = page - i;
      navBarIndexArray.push(page - i);
      if (prevPage <= 0) {
        break;
      }
    }
    navBarIndexArray.sort();
  }

  // set index bar
  else {
    for (let i = 0; i < navBarIndexLimit; i += 1) {
      const nextPage = i + navBarIndexOffset * navBarIndexLimit;
      if (nextPage > totalPage) {
        break;
      }
      navBarIndexArray.push(nextPage + 1);
    }
  }

  articles.index = navBarIndexArray;
  res.render('article/article_home.hbs', { articles });
});

article.home.hbs

    <-

  {{#each articles.index as |key|}}

    {{key}}

  {{/each}}

    ->

I've managed to paginate my articles and while it is working, I have a strong feeling that I made the pagination navigation bar part extremely complicated and I'm sure there would be a better way.
Using Express, Sequelize and Handlebars


texts: Project Euler # 29: Distinct powers in Python

texts:
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

  2 ** 2 = 4, 2 ** 3 = 8, 2 ** 4 = 16, 2 ** 5 = 32
  3 ** 2 = 9, 3 ** 3 = 27, 3 ** 4 = 81, 3 * 5 = 243
  4 ** 2 = 16, 4 ** 3 = 64, 4 ** 4 = 256, 4 ** 5 = 1024
  5 ** 2 = 25, 5 ** 3 = 125, 5 ** 4 = 625, 5 ** 5 = 3125

  If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

  4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

  How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

from time import time

def distinct_terms(n):
    """Assumes n an integer > 1.
    returns the sequence generated of a ** b for a and b in range(n)"""
    return (x ** y for x in range(2, n + 1) for y in range(2, n + 1))

if __name__ == '__main__':
    time1 = time()
    print((len(set(distinct_terms(100)))))
    print(f'Time: {time() - time1}')


texts:
SUMMER OF '69: Return the sum of the numbers in the array, except
  ignore sections of numbers starting with a 6 and extending to the next
  9 (every 6 will be followed by at least one 9). Return 0 for no
  numbers.

My solution:

def summer_sum(a_list):
    """
    Use a stack to solve the problem.

    1. If current num is '6', push '0' on the stack.
    2. If current num is not '6' and the stack is empty, add it.
    3. If current num is '9' and the stack is not empty, pop the stack.
    """

    exclude_stack = []
    total = 0

    for num in a_list:
        if num == 6:
            exclude_stack.append(0)

        elif not len(exclude_stack):
            total += num

        elif num == 9 and len(exclude_stack):
            exclude_stack.pop()

    return total

Questions:

Is this implementation correct?
Is the time complexity of the this implementation O(n)?
Is there a better/faster way to solve the problem?


texts:
I wrote a script that you can use to open the file explorer from command line like

e db --> opens my Dropbox folder (e.cmd is the name of the script)
e bin --> opens my script folder

(I’m not very happy with the way I define the relationship mnemonic <--> folder.)
Remarks, anyone?

@ECHO OFF

SET "target=%~1"

if "%target%" EQU "" (
    ECHO No target specified.
    EXIT /B
)

SET folder=""
CALL :set_folder_%target% 2> nul
if %folder% EQU "" (
    ECHO Invalid target %target%.
    EXIT /B
)

explorer %folder%
EXIT /B

:set_folder_db
SET folder="D:\Alex\Dropbox" & EXIT /B

:set_folder_bin
SET folder="D:\Alex\Scripts\Bin" & EXIT /B

...


texts: Advent of Code 2017 Day 5 (part 2) in Functional Programming (FP)

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 2nd part of Day 5):

https://adventofcode.com/2017/day/5

  --- Part Two --- Now, the jumps are even stranger: after each jump, if the offset was three or more, instead decrease it by 1. Otherwise,
  increase it by 1 as before.

  Using this rule with the above example, the process now takes 10
  steps, and the offset values after finding the exit are left as 2 3 2
  3 -1.

  How many steps does it now take to reach the exit?

I'm doing the 2nd part of Day 5. You can only access the 2nd part once you solved the 1st part.

To access the 2nd part type in this number 376976 or check out the solution here: Advent of Code 2017 Day 5 (part 1) in Functional Programming (FP)

First my procedural solution:

  const parsedInput = input => input
    .split('\n')
    .map(c => parseInt(c));

  function jumper(maze) {
    let stepNumber = 0;
    let position = 0;
    do {
      const newOffset = maze[position] >= 3 ?
        maze[position] - 1 :
        maze[position] + 1;
      const oldPosition = position;
      position = position + maze[position];
      maze[oldPosition] = newOffset;
      ++stepNumber;
    } while (position < maze.length);
    return stepNumber;
  }
  console.log("solution ", jumper(parsedInput(INPUT)));

The code above has got more operation than in the first part of this riddle. But it's way faster and shorter than the functional approach of the 1st problem (Advent of Code 2017 Day 5 (part 1) in Functional Programming (FP)).

My FP solution:

  const parsedInput = input => input
    .split('\n')
    .map(c => parseInt(c));

  const jumper = input => {
    const currentMaze = input.maze;
    const currentPosition = input.position;
    const currentStepNumber = input.stepNumber;

    if (currentPosition >= currentMaze.length) {
      showAnswer(currentStepNumber);
    }

    const newOffset = currentMaze[currentPosition] >= 3 ?
      currentMaze[currentPosition] - 1 :
      currentMaze[currentPosition] + 1;
    const maze = currentMaze
      .slice(0, currentPosition)
      .concat(newOffset)
      .concat(currentMaze.slice(currentPosition + 1));
    const position = currentPosition + currentMaze[currentPosition];
    const stepNumber = currentStepNumber + 1;
    setTimeout(() => jumper({
      /*removes call stack -> infinite recursion without built in Tail Call Optimization*/
      maze, position, stepNumber
    }), 0);
  };
  const showAnswer = res => console.log(res);
  const startMaze = parsedInput(INPUT);

  jumper({
    maze: startMaze,
    position: 0,
    stepNumber: 0
  });

The FP solution is longer and slower. I couldn't solve it without recursion. After a while you hit the stack size. Thanks to Thanks to @Blindman67 he suggested a workaround with setTimeout.

Do you know an FP approach that is faster and shorter than the procedural one?


texts: Optimizing javascript/jquery code for HTML creation with JSON

texts:
I use the following code to populate my HTML with JSON. The problem is that I'm afraid this code will be inefficient if the number of records that I get from the service call are large (200 or more).

Are there ways I can change my code to make sure this won't be an issue?  Or is my code fine as it stands?


texts:
I defined a function that multiplies its argument by 3:

coffee> foo = (x) -> x * 3
[Function]

We can call it with an input of 1:

coffee> foo(1)
3

However, when I tried with a non-Number type:

coffee> foo("3")
9

This behavior appears wrong to me since a String cannot be multiplied by a Number.

To fix it, I'd add something like this:

foo = (x) ->
  if typeof x is 'number'
    x * 3
  else
    throw new Error("not a number:"  + x)

Is there a cleaner way to do this in CoffeeScript?


texts:
In a far away dystopian world, the measure of the quality of a person’s life is the numbers of likes he gets for an article about their life. For a person to stay alive, he has to acquire at least L number of likes before D days pass.

  People in this world employ various techniques to increase the number of likes. One of the famous ones is to dis-like and re-like their own article once per day. On doing so you can assume that the number of likes for the post increase by a constant factor C.

  So if one starts with S likes on Day-1, he would have D2 = S + C * S likes on Day-2, D3 = D2 + D2 * C on Day-3 etc. You are to answer if the person would survive at the end of Day-D or not.

  Input

  First line contains a single positive integer T denoting the number of test cases. The following T lines represent a test case each. Each test case contains 4 space-separated integers L, D, S and C.

  Output

  For each test case, print a single line containing “ALIVE AND KICKING” if the person would live, otherwise print, “DEAD AND ROTTING”.

  Constraints

  1 <= T <= 1000

  1 <= L <= 1000000000

  1 <= D <= 1000000000

  1 <= S <= 1000000000

  1 <= C <= 1000000000

  Sample cases:

  Input

  2

  5 1 5 1

  10 2 2 2

  Output

  ALIVE AND KICKING

  DEAD AND ROTTING

#include <stdio.h>

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        long long int l,d,s,c;
        scanf("%lld%lld%lld%lld",&l,&d,&s,&c);
        long long int i;
        long long int x=s;
        for(i=2;i<=d;i++)
            x*=(1+c);
        if(x>=l)
            printf("ALIVE AND KICKING\n");
        else
            printf("DEAD AND ROTTING\n");
    }
    return 0;
}

How do I improve efficiency so that the time limit does not get exceeded?


texts: Automatically turn on Computer from Raspberry Pi (based on user presence in home)

texts:
I know the code is full of useless data and stylistic and analysis errors and I'd really love and appreciate to have a pro's idea about it so I can learn to code (and think) better.

import os, time
from ConfigParser import SafeConfigParser
configfilename = "imhome.ini"
scriptpath = os.path.abspath(os.path.dirname(__file__))
configfile = os.path.join(scriptpath, configfilename)
parser = SafeConfigParser()
parser.read(configfile)
ip_smartphone = parser.get('imhome', 'ip_smartphone')
mac_address_pc = parser.get('imhome', 'mac_address_pc')
hometime_path = parser.get('imhome', 'hometime_path')
in_path = parser.get('imhome', 'in_path')
mp3_path = parser.get('imhome', 'mp3_path')
maximum_time_before_logout = parser.get('imhome', 'maximum_time_before_logout')
if os.path.exists(hometime_path) == False:
        os.system ("touch " + str(hometime_path))
if os.path.exists(in_path) == True:
        os.system ("rm " + str(in_path))
finished = 1
while finished == 1:
    check_presence = os.system ("ping -w 1 " + str (ip_smartphone) + " >/dev/null")
    file_modification_time = (os.path.getmtime(hometime_path))
    file_delta_time = time.time() - file_modification_time
    if check_presence == 0 :
            os.system ("rm " + str(hometime_path))
            change_arrived=("echo " + str(check_presence) + " > hometime")
            os.system (change_arrived)

            if os.path.exists(in_path) == False:
            # You can add any custom commands to execute when home below this row

                os.system ("etherwake " + str(mac_address_pc))
                os.system ("mpg123 " + str(mp3_path) + " >/dev/null")
                os.system ("touch " + str(in_path))
            # stop adding commands

    elif check_presence == 256 and file_delta_time > int(maximum_time_before_logout):
        if os.path.exists(in_path) == True:
                    os.system ("rm " + str(in_path))


texts: Prime Sieve in Rust (Sieve of Eratosthenes)

texts:
I am learning Rust and I decided to make a prime sieve program. It works and has comparable performance to my equivalent C program.

I am new to Rust so I would like some feedback on my code. In particular, is my code in the correct Rust style?

I am aware of some changes to make the algorithm faster, but I would prefer feedback on the style of Rust code instead.

use std::env;
use std::fs::File;
use std::io::{Write, BufWriter};

fn prime_sieve(n: usize, ofile: &String) -> u32 {
    let f = File::create(ofile).expect("Unable to create file");
    let mut f = BufWriter::new(f);

    let mut prime_mask: Vec<bool> = vec![true;n];
    prime_mask[0] = false;
    prime_mask[1] = false;
    let mut p = 2;  // First prime number

    let mut count = 0;  // Total number of primes found
    let mut i;

    // Main sieve loop
    while p<n {
        if prime_mask[p] {
            f.write_all(format!("{}\n",p).as_bytes())
                .expect("Unable to write to file");
            count+=1;
            i=2*p;
            while i<n {
                prime_mask[i] = false;
                i += p;
            }
        }
        p+=1;
    }
    count
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let n: usize = args[1]
        .trim()
        .parse()
        .expect("Wanted a number");
    let ofile = &args[2];
    let np = prime_sieve(n,ofile);
    println!("Found {} primes less than {}. Wrote to {}", np, n, &args[2]);
}


texts:
Any suggestions for improving this? I'm hoping for some JavaScript object structure / code integrity type recommendations rather than style or CSS.

var list = [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'Åland Islands', code: 'AX'},
    {name: 'Albania', code: 'AL'},
    {name: 'Algeria', code: 'DZ'},
    {name: 'American Samoa', code: 'AS'},
    {name: 'AndorrA', code: 'AD'},
    {name: 'Angola', code: 'AO'},
    {name: 'Anguilla', code: 'AI'},
    {name: 'Antarctica', code: 'AQ'}
];

function Autocomplete(selector){

    this.list = list;

    this.box = document.getElementById(selector);

    this.dropdown = null;

    this.init = function(){
        this.box.addEventListener("keyup", this.boxKeyUp);
        this.dropdown = document.createElement("ul");
        this.dropdown.setAttribute('class','drop');
        document.body.appendChild(this.dropdown);
        this.updateList();
    };

    this.updateList = function(){
        this.dropdown.innerHTML = "";
        var value = this.box.value;
        for(var i=0; i < this.list.length; i++){
            var name = list[i].name.toLowerCase();
            var idx = name.indexOf(value);
            if(idx===0){
                var item = document.createElement('li');
                item.appendChild(document.createTextNode(list[i].name));
                this.dropdown.appendChild(item);
            }
        }
    };

    this.boxKeyUp = function(){
        if(this.box.value===""){
            this.dropdown.style.display = "none";
            return true;
        }
        this.updateList();
        this.dropdown.style.display = "block";
    }.bind(this);

    this.init();

    return this;
}
var ac = new Autocomplete("inputbox");
input {
    width: 200px;
}

input, .drop {
    margin: 0;
    padding: 0;
    padding: 6px;
    font-size: 16px;
    font-family: "helvetica neue", helvetica, sans-serif;
}

.drop {
    display: none;
    list-style-type: none;
    list-style-position: inside;
    border: 1px solid #eee;
}
<input type="text" name="inputbox" id="inputbox">


texts:
I had to calculate the difference between Chicago Board of Trade grain futures prices using VB.net and came up with the following (admittedly clunky) solution.  It's a little tricky because CBOT prices, as posted, mix octal and decimal numbers.  Anyway, here is my code for you to enjoy and tear apart:

   Public Function GrainSubtraction(ByVal numberOne As Double, ByVal numberTwo As Double) As Double

    ' This is a somewhat convoluted function to subtract CBOT grain prices ... but it seems to work
    ' It assumes the numbers have no decimals - that is, if the price of corn is $4.75 3/4 per bushel, this number is represented as 4756 where the last digit (6) represents 6/8

    ' Basically, we perform octal subtraction on the smallest unit digit and regular decimal subtraction on the remaining digits
    ' I use arrays to do this so I can isolate each digit - there is probably a more efficient way to do this, though - I'm not a quant

    Dim tempOne As Double = 0.0
    Dim tempTwo As Double = 0.0

    Dim inverted As Boolean = False 'Flags whether the second number is larger than the first
    Dim answer As Double = 0.0 ' This will be our ultimate response
    Dim multiplier As Double = 1.0

    ' Here, we compare the two numbers and invert them if the second number is largest then the first

    If numberOne = numberTwo Then Return 0.0

    If numberOne < numberTwo Then
        tempOne = numberTwo
        tempTwo = numberOne
        inverted = True
    Else
        tempOne = numberOne
        tempTwo = numberTwo
    End If

    Dim lengthOne = CStr(tempOne).Length ' How many digits in number one?
    Dim lengthTwo = CStr(tempTwo).Length

    Dim I As Integer = 0
    Dim errorFlag As Boolean = False 'Let's us know whether we hit an error with this number

    Dim numberLength As Integer
    If lengthOne > lengthTwo Then numberLength = lengthOne Else numberLength = lengthTwo

    ' Create our array
    Dim numberOneArray(numberLength) As Integer
    Dim numberTwoArray(numberLength) As Integer
    Dim answerArray(numberLength) As Integer ' This will hold our answer as an array

    ' Set Array Values To Zero
    For I = 0 To numberLength - 1
        numberOneArray(I) = 0
        numberTwoArray(I) = 0
    Next

    For I = 0 To lengthOne - 1
        numberOneArray(I) = tempOne Mod 10
        tempOne = Int(tempOne / 10)
    Next

    For I = 0 To lengthTwo - 1
        numberTwoArray(I) = tempTwo Mod 10
        tempTwo = Int(tempTwo / 10)
    Next I

    ' This is where we do the actual analysis

    For I = 0 To numberLength - 1

        If I = 0 Then ' We're doing Octal subtraction here

            If numberOneArray(I) >= numberTwoArray(I) Then
                answerArray(I) = numberOneArray(I) - numberTwoArray(I)
            Else
                If I = numberLength Then
                    errorFlag = True
                Else
                    numberOneArray(I) = numberOneArray(I) + 8
                    numberOneArray(I + 1) = numberOneArray(I + 1) - 1
                    answerArray(I) = numberOneArray(I) - numberTwoArray(I)
                End If
            End If

        Else ' We're doing Decimal subtraction here

            If numberOneArray(I) >= numberTwoArray(I) Then
                answerArray(I) = numberOneArray(I) - numberTwoArray(I)
            Else
                If I = numberLength Then
                    errorFlag = True
                Else
                    numberOneArray(I) = numberOneArray(I) + 10
                    numberOneArray(I + 1) = numberOneArray(I + 1) - 1
                    answerArray(I) = numberOneArray(I) - numberTwoArray(I)
                End If
            End If

        End If

    Next

    multiplier = 1

    If errorFlag = True Then Return 0.0

    For I = 0 To numberLength - 1
        answer = answer + (answerArray(I) * multiplier)
        multiplier = multiplier * 10
    Next

    If inverted = True Then answer = -answer
    Return answer

End Function


texts:
write an algorithm for: x / 2 + 100 * (a + b) - 3 / (c + d) + e * e
knowing that: a, c - word, b, d - byte, e - doubleword, x - qword
    mov eax, dword [x]
    mov edx, dword [x + 4] ; edx:eax = x
    mov ebx, 2
    idiv ebx ; eax = edx:eax / ebx = x / 2
    mov ebx, eax ; save the result in ebx so we can do the other operations
    mov al, [b]
    cbw ; ax = b
    add ax, [a] ; ax = a + b
    mov dx, 100
    imul dx ; dx:ax = ax * dx = 100 * (a + b)
    push dx
    push ax
    pop eax ; 100 * (a + b)
    add ebx, eax ; ebx = x / 2 + 100 * (a + b)
    mov al, [d] ; al = d
    cbw ; ax = d
    add ax, word [c] ; ax = c + d
    mov cx, ax ; cx = c + d
    mov ax, 3
    cwd
    idiv cx ; ax = dx:ax / cx
    cwd
    push dx
    push ax
    pop eax ; eax = 3 / (c + d)
    sub ebx, eax
    mov eax, ebx
    cdq ; edx:eax = x / 2 + 100 * (a + b) - 3 / (c + d)
    mov ebx, eax
    mov ecx, edx ; ecx:edx = x / 2 + 100 * (a + b) - 3 / (c + d)
    mov eax, [e]
    imul dword [e] ; edx:eax = e * e
    add eax, ebx
    adc edx, ecx
    mov dword [result + 0], eax
    mov dword [result + 4], edx

did I make it unnecessarily complicated?


texts: Inefficient DNA heterodimerization script

texts:
I have stuck with this script it would be great if you could help me with your inputs. My problem is that I think the script is not that efficient - it takes a lot of time to end running.
I have a fasta file with around 9000 sequence lines (example below) and What my script does is:

reads the first line (ignores lines start with >) and makes 6mers (6 character blocks)
adds these 6mers to a list
makes reverse-complement of previous 6mers (list2)
saves the line if non of the reverse-complement 6mers are in the line.
Then goes to the next line in the file, and check if it contains any of the reverse-complement 6mers (in list2). If it does, it discards it. If it does not, it saves that line, and reads all reverse complement 6-mers of the new one into the list2 - in addition to the reverse-complement 6-mers that were already there.

my file:
>seq1
TCAGATGTGTATAAGAGACAGTTATTAGCCGGTTCCAGGTATGCAGTATGAGAA
>seq2
TCAGATGTGTATAAGAGACAGCGCCTTAATGTTGTCAGATGTCGAAGGTTAGAA
>seq3
TCAGATGTGTATAAGAGACAGTGTTACAGCGAGTGTTATTCCCAAGTTGAGGAA
>seq4
TCAGATGTGTATAAGAGACAGTTACCTGGCTGCAATATGGTTTTAGAGGACGAA

and this is my code:
import sys
from Bio import SeqIO
from Bio.Seq import Seq

def hetero_dimerization():
    script = sys.argv[0]
    file1 = sys.argv[1]
    list = []
    list2 = []
    with open(file1, 'r') as file:
        for record in SeqIO.parse(file, 'fasta'):
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 6])
                if len(kmer) == 6:
                    list.append(kmer)
            #print(record.seq)
            #print(list)

            for kmers in list:
                C_kmer = Seq(kmers).complement()
                list2.append(C_kmer[::-1])
            #print(list2)

            cnt=0
            if any(items in record.seq for items in list2):
                cnt +=1

            if cnt == 0:
                print('>'+record.id)
                print(record.seq)

if __name__ == '__main__':
    hetero_dimerization()


texts:
The concept is very, very simple: let's do merging run by run (a run is a range without decrement).

template <class RandomIt>
void RunAwareMergeSort(RandomIt first, RandomIt last) {
    RandomIt m_first(first); // the begin of first run of merge
    RandomIt i(first); // the locater
    while (true) {
        while (++i < last && !(*i < *(i-1))); // locate the first run
        if (!(i < last)) { // i has located the end of the last run
            if (m_first == first) return; // the range has only one run; sorting completed
            else { // the range has odd number of runs
                m_first = i = first; // start over
                continue;
            }
        }
        RandomIt m_middle(i); // the end of first run of merge; the begin of second run of merge
        while (++i < last && !(*i < *(i-1))); // locate the second run
        std::inplace_merge(m_first, m_middle, i); // merge
        if (i < last) m_first = i; // next
        else m_first = i = first; // start over
    }
}

Best-case time complexity: \$O(n)\$ (which is better than typical merge sort)
Average-case time complexity: \$O(n \log n)\$
Worst-case time complexity: \$O(n \log n)\$
Worst-case space complexity: \$O(n)\$
Stability: true

This is slower than Timsort, right?


texts:
I have a command called sprinkle. I'm not going to explain anything about it, because I want whoever that reviews the code to also tell me how much of the command documentation they understood.

Here is what I need help with:

Is the documentation good enough? Is it too verbose?
Does the constant domainName help you understand the code below, or is it useless?
Should the transformations array be passed around instead of being defined as a global variable?
What else can I improve in the code?

// The sprinkle command allows the user to define some transformations in a file called test.txt.
// The user can then provide some domain names such as 'go' and the application will randomly transform it, using the transformations defined in test.txt.
// Every transformation in the test.txt file must have an asterisk (*) in place of the domain name. For example, if the test file contains:
//
// *-is-awesome.com
//
// love-*.net
//
// lets-*.org
//
// Then, if the user enters 'go' in the command line, the output could be something like:
//
// go-is-awesome.com
package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strings"
    "time"
)

const (
    domainName = "*"
)

var transformations []string

func main() {
    var err error

    transformations, err = readLinesFromFile("test.txt")
    if err != nil {
        log.Fatal(err)
    }

    inputScanner := bufio.NewScanner(os.Stdin)
    for inputScanner.Scan() {
        fmt.Println(applyRandomTransformation(inputScanner.Text()))
    }
}

// readLinesFromFile reads a file into an array. Each element in the array is one line of the text file.
func readLinesFromFile(path string) ([]string, error) {
    var lines []string
    file, err := os.Open("test.txt")
    if err != nil {
        return nil, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }

    return lines, nil
}

// applyRandomTransformation randomly chooses a transformation from the list of transformations, and replaces the '*' in the transformation with input
func applyRandomTransformation(input string) string {
    rand.Seed(time.Now().UnixNano())
    transformation := transformations[rand.Intn(len(transformations))]
    return strings.Replace(transformation, domainName, input, -1)
}


texts:
I came up with the following code to convert a rgba color to an argb color:

public static int ToARGB(int rgba){
    return (rgba << (3*8)) | ((rgba>>8) & 0x00FFFFFF);
}

I used the bitmask 0x00FFFFFF since the rightshift in C# pads with the most significant bit of the number to be shifted. I tested this methode and it seems to work, but I need to be sure I am not missing a case where this is garbage. Any thoughts on my code please?


texts:
This is my first OOP PHP library and wanted to get advice on how I can improve what I wrote. This is what I needed to do:

I'm also not sure on what it meant by "proportionally resize the shape up or down, given a floating-point scale factor" I think what I did what it meant but I could be wrong.

  Build a simple PHP library for defining 2-dimensional geometric shapes and making basic calculations with them.

  For each shape, the library should be able to do the following:

  calculate the area
  calculate the perimeter
  proportionally resize the shape up or down, given a floating-point scale factor

<?PHP
echo "Circle
";
$circle = new circle(5);
$circle->getArea();
$circle->getPerimiter();
$circle->scale(up, .5);
$circle->getArea();
$circle->getPerimiter();

echo "
Right Triangle
";
$rt = new RightTriangle(4, 5);
$rt->getArea();
$rt->getPerimiter();
$rt->scale(up, .5);
$rt->getArea();
$rt->getPerimiter();

class Circle {
    public function __construct( $radius )
    {
        $this->radius = $radius;
    }
    public function getArea()
    {
        echo pow($this->radius, 2) * M_PI."
";
    }
    public function getPerimiter()
    {
        echo 2 * M_PI * $this->radius."
";
    }
    public function scale($direction, $scale)
    {
        if($direction == 'up')
        {
            $this->radius = $this->radius + ($this->radius * $scale);
        }
        else
        {
            $this->radius = $this->radius - ($this->radius * $scale);
        }
    }
}

class RightTriangle {
    public function __construct( $a, $b )
    {
        $this->a = $a;
        $this->b = $b;
    }
    public function getArea()
    {
        echo ($this->a*$this->b/2)."
";
    }
    public function getPerimiter()
    {
        echo $this->a + $this->b + sqrt(pow($this->a, 2) + pow($this->b, 2))."
";
    }
    public function scale($direction, $scale)
    {
        if($direction == 'up')
        {
            $this->a = $this->a + ($this->a * $scale);
            $this->b = $this->b + ($this->b * $scale);
        }
        else
        {
            $this->a = $this->a - ($this->a * $scale);
            $this->b = $this->b + ($this->b * $scale);
        }
    }
}
?>


texts:
I was messing around with Javascript in Khanacademy the other day and this "monstrosity" was born. It's a terrain generator that uses a simplified version of the random walk method.

// current tile position
var BlockX = 200;
var BlockY = 200;

// tile size
var SizeX = 2;
var SizeY = 2;

// min and max X positions
var MinX = 0;
var MaxX = 400;

// min and max Y positions
var MinY = 0;
var MaxY = 400;

// possible position changes
var BlockPosChanges = [-1, 1, 0];

// repeats and max repeats
var MaxRepeats = round(random(10*100, 10*1250)); // Do not change! This is at the max safe amount
var Repeats = 0;

// set the background
background(0, 13, 255);

// main program loop
while(Repeats < MaxRepeats) {

    // possible color ranges
    var RedRange = round(random(45, 70));
    var BlueRange = round(random(165, 100));
    var GreenRange = round(random(20, 50));

    // draw a tile
    noStroke();
    fill(RedRange, BlueRange, GreenRange);
    rect(BlockX, BlockY, SizeX, SizeY);

    // change the current tile position
    BlockX += BlockPosChanges[floor(random() * BlockPosChanges.length)];
    BlockY += BlockPosChanges[floor(random() * BlockPosChanges.length)];

    // test if at edge
    if(BlockX <= MinX || BlockX >= MaxX) {
        break;
    }

    // test if at edge
    if(BlockY <= MinY || BlockX >= MaxY) {
        break;
    }

    // increment repeats
    Repeats++;
}

Since this version of Javascript has features that may not be included in other variants, you can test this program here in Khanacademy. What can I improve here?


texts: Easier ways to make an RPG dice roller code?

texts:
I'm new to programming and this is the first thing I'm doing on my own. I would appreciate it if you could point me ways to optimize this RPG dice roller code in Python!
import random

def dice_reader():

##this should read messages like '2 d 6 + 3, 5 d 20 + 2 or just 3 d 8'##
    message = input('>')
    reader = message.split(' ')
    times = reader[0]
    sides = reader[2]
    output_with_modifier = []
    result = []

    if len(reader) == 5:
        modifier = reader[4]
    else:
        modifier = 0

    for output in range(int(times)):
        output = random.randint(1, int(sides))
        result.append(output)
        output_with_modifier = [(int(x) + int(modifier)) for x in result]
    print(f' Dice rolls: {tuple(result)}')
    if modifier != 0:
        print(f' With modifier: {tuple(output_with_modifier)}')

    end = False
    while end == False:
        dice_reader()
        end_message = input('Again? ')
        if end_message.lower() == 'no':
            end = True
    else:
        pass


texts: Applying a currency symbol based on a tested string value

texts:
My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a NSDictionary object and then depending upon the value prefix a UILabel with $, £, ¥ currency symbols.

I've just shown 2 examples below.  I have more currencies and the code is very long.

if ([[item objectForKey:@"currency"] isEqualToString:@"EUR"]) {

    NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}

if ([[item objectForKey:@"currency"] isEqualToString:@"GBP"]) {
    NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}
if ([[item objectForKey:@"currency"] isEqualToString:@"USD"]) {
    NSString *priceConvertToStr = [NSString stringWithFormat:@"$%@", [[item objectForKey:@"price"]stringValue]];

    NSString *priceStringFix = [priceConvertToStr
                                stringByReplacingOccurrencesOfString:@"(null)" withString:@""];

    priceLabelText.text = priceStringFix;
    [imgView2 addSubview:priceLabelText];

}


texts:
I have this piece of code, and I want to make if the way I'm calculating the time complexity is valid:

void traverse() {
    int currSum = 0;
    for(int i = 0; i < original.length; i++) {
        currSum = original[i];
        for(int j = i + 1; j < original.length; j++) {
            if(max <= currSum) {
                max = currSum;
            }
            currSum += original[j];
        }

        if(max <= currSum) {
            max = currSum;
        }
    }
}

I was thinking it'd be something along the lines of: (n - 1) + (n - 2) + (n - 3) ... etc but wasn't sure if that's correct.


texts:
I'm trying to call a promise recursively. If I get a responseData with a key error I want to call the promise again and again until I don't get it.

  _getUser (url) {
    console.log('fetching url', url)
    return fetch(`$(url)/api`, {
      method: 'POST',
      headers: {},
      body: '{"key" : "body"}'
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log('Getting responseData', responseData)
      if (responseData[0].error) {
        alert(responseData[0].error.description)
        return _getUser(url)
      } else alert('User Created')
    })
    .catch((error) => {
      console.log(error)
    })
  }

Is this the best way to call a promise recursively to do what I want?


texts:
I am trying to find a N number of leading zeros from the output of the sha1 hash function. I would like N to go up to 10 or 9. Currently I can get to 7 in about 7 minutes (even though is not always that fast), but already 8 takes forever. The input to the sha1 must be a combination between an input_str and a random generated string.
Here is my code:
import os
import base64
import hashlib
import time

def gen_keys_06(_urandom=os.urandom, _encode=base64.b64encode):
    while True:
        yield _encode(_urandom(4)).decode('ascii')

def search_matching_random_str(input_str, zeroes, _sha1=hashlib.sha1):
    leading_zeros = "0"*zeroes
    for my_random_str in gen_keys_06():
        input_str_my_random_str = "".join([input_str, my_random_str])
        hashval = _sha1(input_str_my_random_str.encode('utf-8')).hexdigest()
        if hashval[:zeroes] == leading_zeros:
            return hashval, my_random_str

def get_time(input_data, zeroes):
    start = time.perf_counter()
    val, random_str = search_matching_random_str(input_data, zeroes)
    print(f'hash: {val}')
    print(f'random_str: {random_str}')
    finish = time.perf_counter()
    print(f'Finished in {round(finish-start, 2)} seconds(s)')

if __name__ == '__main__':

    first_str = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx"
    get_time(first_str, 4)

On what should I work to make it faster?


texts: POSIX shell compatible and POSIX conforming dirname implementation

texts:
The discussion in the comments of this answer made me wonder how hard it would be to write a built-in only version of dirname.

This is what I ended up with but I'm reasonably confident it should be able to be improved (I haven't spent much time thinking about it yet).

Any improvements/suggestions are welcome.

#!/bin/sh

p=$1
alt=$2
skip78=

stripslashes() {
    i=$1
    while [ "$i" != "$o" ]; do
        o=$i
        i=${i%/}
    done
    eval "$2=\$i"
}

[ "$p" = '//' ] || {
    case "$p" in
        *[!/]*|'')
            stripslashes "$p" p
            case "$p" in
                */*)
                    p=${p%/*}
                    ;;
                *)
                    p=.
                    skip78=skip78
                    ;;
            esac
            ;;
        *)
            p=/
            skip78=skip78
            ;;
    esac
}
[ -n "$skip78" ] || {
    { [ "$p" != '//' ] || [ -z "$alt" ]; } && {
        stripslashes "$p" p
        [ -z "$p" ] && p=/
    }
}

printf -- %s\\n "$p"

The POSIX spec for dirname is:

  If string is //, skip steps 2 to 5.
  If string consists entirely of <slash> characters, string shall be set to a single <slash> character. In this case, skip
  steps 3 to 8.
  If there are any trailing <slash> characters in string, they shall be removed.
  If there are no <slash> characters remaining in string, string shall be set to a single <period> character. In this case, skip steps 5 to 8.
  If there are any trailing non- <slash> characters in string, they shall be removed.
  If the remaining string is //, it is implementation-defined whether steps 7 and 8 are skipped or processed.
  If there are any trailing <slash> characters in string, they shall be removed.
  If the remaining string is empty, string shall be set to a single <slash> character.

Update: Made a gist.


texts:
I have this code for reading Twitter users from a text file represented by integers in the format "int (space) int", where the first int is the ID of
the user doing the following and the second int is the user being followed. It works for small files but takes a really long time with larger files. What can I do to make it more efficient?

users is an ArrayList

public void open() {
    try {
        if (file.exists()) {
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            String[] strings;
            while ((line = bufferedReader.readLine()) != null) {
                strings = line.split(" ");
                String user1 = strings[0];
                String user2 = strings[1];

                if (!users.toString().contains(user1)) {
                    TwitterUser tUser1 = new TwitterUser(
                            Integer.parseInt(user1));
                    users.add(tUser1);
                    TwitterUser tUser2 = new TwitterUser(
                            Integer.parseInt(user2));
                    tUser1.follow(tUser2);
                } else {
                    TwitterUser target = null;
                    for (TwitterUser i : users)
                        if (i.toString().equals(user1))
                            target = i;
                    TwitterUser tUser3 = new TwitterUser(
                            Integer.parseInt(user2));
                    target.follow(tUser3);

                }

            }
            fileReader.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}