texts: Function caller (to multiple receivers) interface

texts:
This class is designed to call a similar function of multiple objects of multiple classes using a single interface (it is not for calling functions that return a value).

A potential usage will be sending same data to multiple writers (log writer, HTML generator and styled printer to console).

Tested with Python 3.4.2

I've also included a test/example in the below code:

"""
caller module:
Contains Caller class - call multiple other classes or modules with
similar function definitions, (it is not for calling functions that
returns a value)

Author : Bhathiya Perera
"""
class Caller():
    """call other classes or modules with
       similar function definitions"""
    def __init__(self, *receivers):
        """Initialize

        Parameters :
            receivers - va-arg receivers (can be objects, modules,
                        another caller , ....)
        """
        self._names = []
        self._receivers = receivers

    def __getattr__(self, name):
        """Get attribute of a given name
        This will return 'self' therefore it can be called later
        """
        self._names.append(name)
        return self

    def __call__(self, *args, **kw):
        """This class is callable with any arguments or key-value arguments
        It will then be posted to all receivers
        """
        if len(self._names) == 0:
            raise Exception("Cannot call")

        method_name = self._names.pop()
        for receiver in self._receivers:
            method = getattr(receiver, method_name)
            method(*args, **kw)

        return self

if __name__ == "__main__":
    # -------------------------------------------------
    # Test its usage
    class Receiver1():
        def a(self, arg):
            print ("Receiver1 - a", arg)

        def b(self, arg):
            print ("Receiver1 - b", arg)

    class Receiver2():
        def a(self, arg):
            print ("Receiver2 - a", arg)

        def b(self, arg):
            print ("Receiver2 - b", arg)

    class Receiver3():
        def a(self, arg):
            print ("Receiver3 - a", arg)

        def b(self, arg):
            print ("Receiver3 - b", arg)

    c = Caller(Receiver3())
    d = Caller(Receiver1(), Receiver2(), c)
    d.a("hello a")
    d.b("hello b")
    print ("-----")
    d.a.b.a.b.a.b.a("a")("b")("c")("d")("e")("f")("g")

If it was executed as a module it will print:

Receiver1 - a hello a
Receiver2 - a hello a
Receiver3 - a hello a
Receiver1 - b hello b
Receiver2 - b hello b
Receiver3 - b hello b
-----
Receiver1 - a a
Receiver2 - a a
Receiver3 - a a
Receiver1 - b b
Receiver2 - b b
Receiver3 - b b
Receiver1 - a c
Receiver2 - a c
Receiver3 - a c
Receiver1 - b d
Receiver2 - b d
Receiver3 - b d
Receiver1 - a e
Receiver2 - a e
Receiver3 - a e
Receiver1 - b f
Receiver2 - b f
Receiver3 - b f
Receiver1 - a g
Receiver2 - a g
Receiver3 - a g

Review for Python conventions and anything else.


texts: Java binary search (and get index if not there) review

texts:
I want to do binary search and if the target is not there get the index of where it should have been.

This is the code I came up with. It seems correct. Is there any problem? Can it be improved?

private int binarySearch(String[] sortedArray, String target, int start, int end) {

  if(start <= end){
     int mid = (start + end)/2;
     if(sortedArray[mid].equals(target)){
         return mid;
     }
     else if (target.compareTo(sortedArray[mid]) < 0){
         return binarySearch(sortedArray, target, start, mid - 1);
     }
     else{
         return binarySearch(sortedArray, target, mid + 1, end);
     }
  }

  return start;
}


texts:
I have written a program in golang which checks the mongodb is running or not using commands. But I'm not sure that the program is sufficient or there is something that needs to change in the program. Can you review my code so I can be sure that my code does not have any error or doesn't break if there is any problem at all?

Code

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

/*
*Function check mongodb is running? if not running then it will help to run it by command
*/
func main() {
    status := ExecuteCommand("systemctl is-active mongod")
    if status == true {
    fmt.Println("Connected")
    } else {
        fmt.Println("disconnected")
        status = ExecuteCommand("echo <password> | sudo -S service mongod start")
        if status == true {
            fmt.Println("Connected")
        }
    }
}

/*
* Function to execute the command using golang code.
*
* Params command type string
*
* Used by main func
*
* Returns nil (if no error)
* or      err type error (if error occurs)
*/
func ExecuteCommand(command string) bool {
    cmd := exec.Command("sh", "-c", command)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return false
    }
    return true
}

Golang playground


texts:
I was recently working on a project where I had the following setup:

from stargaze.sg import SGObject
from stargaze.constants import NegInf, Infinite, PATH_CLAMPED, PATH_REVERSIBLE, PATH_ACCELERATABLE
from stargaze.utils import clamp

__all__ = [
    'PathIdentifier', '_basePath', '_clampedPath', '_reversiblePath',
    '_acceleratablePath', 'Path'
    ]

class PathIdentifier(SGObject):
    """
    INTERNATL: The base identifier class for a class object.
    """
    OBJ_REPR_PREFIX = "StarGaze Path:: "

class _basePath(PathIdentifier):
    def __init__(self, **config):
        self._time = 0
        self.speed = config['speed']

    def __move__(self):
        self._time += self.speed

class _clampedPath(PathIdentifier):

    def __init__(self, **config):
        start = config['start']
        end = config['end']
        if start > end:
            errmsg = "Start point cannot be greater " \
                     "than the end point."
            raise ValueError(errmsg)
        self._time = start
        self.end = end

        self.finished = False

    def __move__(self):
        if self.finished:
            return

        if self._time >= self.end:
            self.finished = True

class _reversiblePath(PathIdentifier):

    def __init__(self, **config):
        self.direction = 1

    def __move__(self):
        if self.direction == 1 and self._time >= 1:
            self.direction = -1
            self.speed *= -1
        elif self.direction == -1 and self._time <= 0:
            self.direction = 1
            self.speed *= -1

class _acceleratablePath(PathIdentifier):

    def __init__(self, speed, acceleration, min_speed=NegInf, max_speed=Infinite):
    def __init__(self, **config):
        self.accel = config['acceleration']

        self.min_speed = config.get('min_speed', NegInf)
        self.max_speed = config.get('max_speed', Infinite)

    def __move__(self):
        if self.accel != 1:
            self.speed = clamp(self.accel * self.speed,
                self.max_speed,
                self.min_speed)

class Path:

    def __init__(self, flags, **config):
        _basePath.__init__(self, **config)
        if flags & PATH_CLAMPED:
            _clampedPath.__init__(self, **config)
        if flags & PATH_REVERSED:
            _reversiblePath.__init__(self, **config)
        if flags & PATH_ACCELERATABLE:
            _acceleratablePath.__init__(self, **config)

        self.flags = flags

    def move(self):
        flags = self.flags

        if flags & PATH_CLAMPED:
            _clampedPath.__move__(self)

        if flags & PATH_REVERSED:
            _reversiblePath.__move__(self)

        if flags & PATH_ACCELERATABLE:
            _acceleratablePath.__move__(self)

None of the code is relevant, you won't have to be able to run any of it to answer my question. What I do in this code essentially is I create classes that define their own __init__ and __move_ methods, but I don't call them from instances of their class. Instead, I call them as class methods acting on the instance of another class. Is this bad style in Python? How else might I achieve what I was trying to do here?


texts:
CreateUser function assumes the data being delivered via parameters are clean and gets called or initiated from the Business Manager (another class). This function is responsible to do the following things:

Fetch the Connection String
Open the database connection
Start the transaction
Inserts a user record
Loop through User Role entity list and Insert all the records
Commits the transaction
Finally or Catch Code block gets executed

I would like to identify is this a correct way of implementing Unit of Work pattern? Is there any catch in my implementation? Comments are written through out the code. By the way, am not using Entity Framework (using Dapper) and don't have an intention to use it.

using System;
using System.Collections.Generic;
using System.Data;
using Application.Entities.Interfaces;
using Dapper;

namespace Application.DataStore.UnitOfWork
{
    public class UserUnitOfWork
    {
        private IDbConnection connection;
        private IDbTransaction transaction;

        #region CreateTenant
        public void CreateUser(IUserEntity userEntity, IEnumerable<IUsersUserRoleEntity> usersUserRoleListEntity)
        {
            try
            {
                //fetching the connection string from the config file.
                this.connection = new DbConnectionHelper.DbConnectionHelper().GetDbConnection();

                //open the connection
                this.connection.Open();

                //start the transaction
                this.transaction = this.connection.BeginTransaction();

                //insert into user table
                int? userId = this.connection.Insert(userEntity, transaction);

                //multiple inserts in a loop for user roles
                foreach (var userRole in usersUserRoleListEntity)
                {
                    //assign UserId before the insert
                    userRole.UserId = userId.Value;

                    //insert into user role table
                    this.connection.Insert(userRole, transaction);
                }

                //commit
                this.transaction.Commit();
            }
            catch (Exception ex)
            {
                this.transaction.Rollback();
                throw ex;
            }
            finally
            {
                this.transaction.Dispose();  //Transaction dispose
                this.transaction = null;

                this.connection.Close();
                this.connection.Dispose();
                this.connection = null;
            }
        }
        #endregion
    }
}


texts: Concatenate several CSV files in a single dataframe

texts:
I have currently 600 CSV files (and this number will grow) of 50K lines each i would like to put in one single dataframe.
I did this, it works well and it takes 3 minutes :
colNames = ['COLUMN_A', 'COLUMN_B',...,'COLUMN_Z']
folder = 'PATH_TO_FOLDER'

# Dictionnary of type for each column of the csv which is not string
dictTypes = {'COLUMN_B' : bool,'COLUMN_D' :int, ... ,'COLUMN_Y':float}

try:
   # Get all the column names, if it's not in the dict of type, it's a string and we add it to the dict
   dictTypes.update({col: str for col in colNames if col not in dictTypes})
except:
    print('Problem with the column names.')

# Function allowing to parse the dates from string to date, we put in the read_csv method
cache = {}
def cached_date_parser(s):
    if s in cache:
        return cache[s]
    dt = pd.to_datetime(s, format='%Y-%m-%d', errors="coerce")
    cache[s] = dt
    return dt

# Concatenate each df in finalData
allFiles = glob.glob(os.path.join(folder, "*.csv"))
finalData = pd.DataFrame()
finalData = pd.concat([pd.read_csv(file, index_col=False, dtype=dictTypes, parse_dates=[6,14],
                    date_parser=cached_date_parser) for file in allFiles ], ignore_index=True)

It takes one minute less without the parsing date thing. So i was wondering if i could improve the speed or it was a standard amount of time regarding the number of files. Thanks !


texts: A program with a function that converts a string of digits into an integer value

texts:
Here is a programming task:

Write a program with a function that converts a string of digits into an integer value. Do not use the strtol() function or any other standard C library function. Write your own!

I wanted this program to work perfectly with no errors. First I did the power function (power) and then next is function that return the length of a string (lent) and lastly is function that gives the value of asciicode (ascton).
In the main function there is a loop for the string where it multiple the value of how much zeros in has after it. For example, the string is "1100" so the first 1 is 1000 then this value is stored in variable z, and then this works for the other character and add it to variable z. At the end it return z as an integer of the string.
Is this code efficient, or did I use the "long way"? Please give me some hints how I can write better, cleaner and more readable code. Any feedback is appreciated.
#include <stdio.h>
#include <math.h>

int powe(int ex , int po)
{
  int z = 1;
  for (int i = 0; i < po; i++)
  {
    z = z * (10 * 1);
  }
  return z;
}

int lent (char a [20])
{
  int i=0;
  int l = 0;
  for(i=0 ; a[i] != '\0';i++)
  {
    l++;

  }
  return l;
}

int ascton (int a)
{
  int asciicode[10] = {48,49,50,51,52,53,54,55,56,57};
  for(int i = 0; i < 10; i++)
  {
    if (a == asciicode[i])
    {a = i;
     break;}
    else continue;
  }
  return a;
}

int main(void) {

  int z = 0;
  char sn[20];
  printf("enter your string number!:");
  scanf("%s",sn);

  int s = lent(sn);

  for(int i = 0; sn[i] != '\0';i++)
  {
    int k = 0;
    k = ascton(sn[i]);
    z = z + (k * powe(10, s-1));
    s = s-1;

  }
 printf("%d",z);
}
```


texts:
I have implemented a dynamic array based stack. Can someone point out any pitfalls or things that can be done better?

MyStack.h

#ifndef MYSTACK_H
#define MYSTACK_H

#include <iostream>
#include <stdexcept>

template<class T>
class MyStack
{

private:

    T* m_array;

    int m_count;

    int m_max_size;

    static const int m_growth_factor = 2;

    static const int m_initial_max_size = 10;

public:

    MyStack();

    inline MyStack(const MyStack<T> &rhs) { *this = rhs; }

    void operator=(const MyStack<T> &rhs);

    MyStack(int initial_max_size);

    ~MyStack();

    void push(T data);

    void pop();

    void clear();

    inline bool empty() { return m_count == 0; }

    inline T& top() { return m_array[m_count - 1]; }

    inline int size() { return m_count; }

private:

    void init();

    void increase_array_size();
};

template <class T>
MyStack<T>::MyStack() : m_count(0), m_max_size(m_initial_max_size)
{
    init();
}

template <class T>
MyStack<T>::MyStack(int initial_max_size) : m_count(0), m_max_size(initial_max_size)
{
    init();
}

template <class T>
MyStack<T>::~MyStack()
{
    delete [] m_array;
}

template <class T>
void MyStack<T>::init()
{
    m_array = new T[m_max_size];
    m_count = 0;
}

template <class T>
void MyStack<T>::increase_array_size()
{
    m_max_size = m_growth_factor * m_max_size;
    T* tmp = new T[m_max_size];

    for(int i = 0; i < m_count; i++)
        tmp[i] = m_array[i];

    delete [] m_array;

    m_array = tmp;
}

template <class T>
void MyStack<T>::push(T data)
{
    if(m_count == m_max_size)
        increase_array_size();
    m_array[m_count++] = data;
}

template <class T>
void MyStack<T>::pop()
{
    if(m_count == 0)
        throw std::underflow_error("Underflow Exception!!!");
    m_count--;

}

template <class T>
void MyStack<T>::clear()
{
    delete [] m_array;
    m_max_size = m_initial_max_size;
    init();
}

template <class T>
void MyStack<T>::operator=(const MyStack<T> &rhs)
{
    if(this != &rhs)
    {
        delete [] m_array;
        init();
        for(int i = 0; i < rhs.m_count;i++)
        {
            this->push(rhs.m_array[i]);
        }

    }
}
#endif // MYSTACK_H

main.cpp

#include <iostream>
#include "MyStack.h"

using namespace std;

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

    MyStack<int> stack;
    int sum = 0;

    for(int i = 0; i < 15; i++)
        stack.push(i);

    while(!(stack.empty()))
    {
        sum += stack.top();
        stack.pop();
    }

    cout << "sum: " << sum << endl;

    stack.push(10);
    stack.push(20);

    stack.top() -= 5;

    cout << "stack.top() is now " << stack.top() << endl;

    MyStack<char> stack2;

    stack2.push('t');
    stack2.push('s');
    stack2.push('e');
    stack2.push('T');

    while(!(stack2.empty()))
    {
        cout << stack2.top();
        stack2.pop();
    }
    cout << endl;

    stack2.push('A');
    stack2.push('B');
    stack2.push('C');

    stack2.clear();

    stack2.push('D');
    stack2.push('E');
    stack2.push('F');

    while(!(stack2.empty()))
    {
        cout << stack2.top();
        stack2.pop();
    }
    cout << endl;

}

Output:

sum: 105
stack.top() is now 15
Test
FED


texts: Loading div sections from separate files

texts:
I am loading divs from separate HTML files into a div on the index.html page.

This is being done using jQuery's .load(). There is however, a lot of repetition and I'm wondering if there is a cleaner way to achieve this.

The HTML:

  About
  Help
  Contact

The JS:

$(document).ready( function() {
    $("#about").on("click", function() {
        $("#target").load("../pages/theAboutPage.html");
    });
    $("#help").on("click", function() {
        $("#target").load("../pages/theHelpPage.html");
    });
    $("#contact").on("click", function() {
        $("#target").load("../pages/theContactPage.html");
    });
});


texts: Convert a start and end date chosen by a user to epoch

texts:
This method allows the user to choose a start and end date in human readable form, then convert it to epoch. The method will return a array of longs composed by the epoch start date and the epoch end date.

I handle some exception so if the user types anything else than the date it will end the iteration and start again. If the end date is before the start date it will start again...

private static long[] rectime_choice_period() {
    long epochstart = 0;
    long epochend = 0;
    boolean confirm = true;

    String datetimeend = null;
    String datetimestart = null;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (confirm){

        //enter start date
        System.out.print("\nChoose start date (MM/dd/yyyy hh:mm:ss): ");
        try{
            datetimestart = br.readLine();
        }catch (IOException e){
            System.err.println(e.getClass().getName()+": "+e.getMessage() + "\n\n\n");
            continue;
        }

        //enter end date
        System.out.print("\nChoose end date (MM/dd/yyyy hh:mm:ss): ");
        try{
            datetimeend = br.readLine();
        }catch (IOException e){
            System.err.println(e.getClass().getName()+": "+e.getMessage() + "\n\n\n");
            continue;
        }

        //convert to epoch
        try{
            epochstart = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(datetimestart).getTime() / 1000;
            epochend = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(datetimeend).getTime() / 1000;
        }catch (ParseException e){
            System.err.println("Error entered date cannot be converted!");
            continue;
        }catch (Exception e){
            System.err.println(e.getClass().getName()+": "+e.getMessage() + "\n\n\n");
            continue;
        }

        if ((epochend - epochstart) > 0){
            System.out.println("Start time :" + epochstart + "\tEnd time : " + epochend);
            confirm = false;
        }else {System.err.println("Wrong date! Start date should be before end date!");}

    }

    long[] period = {epochstart, epochend};
    return period;
}

But I am looking to optimize this code, maybe avoid the loop or the continue statement, I checked on google way to improve java code but nothing was really interesting. So any idea? Something I made wrong?


texts: Applying scalar multiplication to matrix

texts:
This is one of my first programs in C. Please review and help me improve it. I create a matrix and apply scalar multiplication on it. Then I print the result.

#include <stdio.h>

int main(void)
{
    void scalarMultiply(int matrix[3][5], int scalar);
    void displayMatrix (int matrix[3][5]);

    int sampleMatrix[3][5] = {
        7,16,55,13,12,12,10,52,0,7,-2,1,2,4,9
    };

    printf("Original matrix:\n");
    displayMatrix(sampleMatrix);

    scalarMultiply (sampleMatrix, 2);
    printf ("\nMultiplied by 2:\n");
    displayMatrix (sampleMatrix);
    scalarMultiply (sampleMatrix, -1);
    printf ("\nThen multiplied by -1:\n");
    displayMatrix (sampleMatrix);
    return 0;

}

// Function to multiply a 3 x 5 array by a scalar
void scalarMultiply (int matrix[3][5], int scalar)
{
    int row, column;
    for ( row = 0; row < 3; ++row )
        for ( column = 0; column < 5; ++column )
            matrix[row][column] *= scalar;
}
void displayMatrix (int matrix[][5])
{
    int row, column;
    for ( row = 0; row < 3; ++row) {
        for ( column = 0; column < 5; ++column )
            printf ("  %i", matrix[row][column]);
        printf ("\n");
    }
}


texts: Get username from full name - PowerShell function

texts:
I would like your opinion of my PowerShell function. Does it follow conventions, and what could can I do to improve it. It is made to create LDAP friendly username from a full name in Serbian language.
function Get-UsernameFromFullName
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $FullName,

        [Parameter(Position = 1, Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [ValidateSet('First', 'Last')]
        [string]
        $LastNamePosition = 'First'
    )

    $usernameComponents = $FullName.ToLower().Split(" ")

    switch ($LastNamePosition)
    {
        'First' { $firstName = $usernameComponents.Length -1; $lastName = 0 }
        'Last'  { $firstName = 0; $lastName = $usernameComponents.Length -1 }
        Default { $firstName = $usernameComponents.Length -1; $lastName = 0 }
    }

    $chars = ($usernameComponents.Get($firstName) + "." + $usernameComponents.Get($lastName)).ToCharArray()

    foreach($char in $chars)
    {
        switch($char)
        {
            'ć' { $segment = "c" }
            'č' { $segment = "c" }
            'đ' { $segment = "dj" }
            'š' { $segment = "s" }
            'ž' { $segment = "z" }
            default { $segment = $char }
        }
        $Username += $segment
    }
    return $Username
}

Here is a link to GitHub page of the actual .psm1 file.
This is an example of the function usage:
Get-UsernameFromFullName -FullName "Čedomir Đorđević"

cedomir.djordjevic
Get-UsernameFromFullName -FullName "JANKOV ZORAN"

zoran.jankov
Get-UsernameFromFullName -FullName "Stojić Gradimir"

gradimir.stojic
Get-UsernameFromFullName -FullName "Vučićević R Željko"

zeljko.vucicevic
Get-UsernameFromFullName -FullName "Magda Boškić" -LastNamePosition Last

magda.boskic


texts: Finding all intervals that match predicate in vector

texts:
I have a function find_all_intervals_below that iterates through a vector and finds all the index intervals of at least a given length where each element within the interval is below a given threshold.

struct Interval {
    int start;
    int end;
};

std::vector<Interval>
find_all_intervals_below(const std::vector<int> &v, const int &threshold,
                         const int &min_length) {
    auto start_position { 0 };
    auto end_position { 0 };
    std::vector<Interval> intervals;
    bool found_start { false };

    for (auto current_pos = 0; current_pos < v.size(); ++current_pos) {
        if (v[current_pos] <= threshold and not found_start) {
            start_position = current_pos;
            end_position = 0;
            found_start = true;
        } else if (found_start and v[current_pos] > threshold and end_position == 0) {
            end_position = current_pos;
            if (end_position - start_position >= min_length) {
                Interval interval;
                interval.start = start_position;
                interval.end = end_position;
                intervals.push_back(interval);
            }
            start_position = 0;
            found_start = false;
        }
    }
    if (found_start and end_position == 0 and v.size() - start_position >= min_length) {
        end_position = v.size();
        Interval interval;
        interval.start = start_position;
        interval.end = end_position;
        intervals.push_back(interval);
    }
    return intervals;
}

This function works perfectly fine, I would just like to get some input from others as I imagine there is likely much more succinct ways of doing this. search_n from STL looks like it might be a solution but I couldn't figure out how to use it for my case.

EDIT: I need the solution to be C++11 compatible, unfortunately.

Test example

const auto min_len { 3 };
const auto threshold { 3 };
const std::vector<int> v { 4, 2, 1, 1, 4, 1, 2, 4 };

const auto actual { find_all_intervals_below(v, threshold, min_len) };
const std::vector<Interval> expected { Interval(1, 4) };

assert(actual == expected);


texts: Validate destinations of a piece in a board game

texts:
I'm programming a board game called Djambi, where most of its pieces can move like the queen from chess. I created a list to save all valid destinations of a piece, which can be in 8 different directions, so I used 8 for loops, but the code of each loop is almost identical:

This is the loop for possible movements to the right:

count = 0
for j in range(y+1,9):
    if P == 3 and count == 2:
        break

    if re.search(r'[■]',board[x][j]):
        pos = str(x)+str(j)
        destinations.append(pos)
    elif re.search(r'\d', board[x][j]):
        if re.search(r'' + chip[0], board[x][j]) or P == 1 or P == 0:
            break
        else:
            pos = str(x)+str(j)
            destinations.append(pos)
            break
    elif re.search(r'[░]',board[x][j]):
        if P == 0:
            pos = str(x)+str(j)
            destinations.append(pos)
            break
        else:
            break
    else:
        if P == 2:
            pos = str(x)+str(j)
            destinations.append(pos)
        else:
            continue

    count += 1

The loop for movements to the left can be simplified with the one above, but the problem is for the loops for movements up

count = 0
for i in range(x+1,9):
    if P == 3 and count == 2:
        break

    if re.search(r'[■]',board[i][y]):
        pos = str(i)+str(y)
        destinations.append(pos)
    elif re.search(r'[\d]',board[i][y]):
        if re.search(r'' + chip[0], board[i][y]) or P == 1 or P == 0:
            break
        else:
            pos = str(i)+str(y)
            destinations.append(pos)
            break
    elif re.search(r'[░]',board[i][y]):
        if P == 0:
            pos = str(i)+str(y)
            destinations.append(pos)
            break
        else:
            break
    else:
        if P == 2:
            pos = str(i)+str(y)
            destinations.append(pos)
        else:
            continue

    count += 1

and down, because the order of variables that change is different, also for diagonal movements:

count = 0
for i,j in zip( range(x+1,9) , range(y+1,9) ):
    if P == 3 and count == 2:
        break

    if re.search(r'[■]',board[i][j]):
        pos = str(i)+str(j)
        destinations.append(pos)
    elif re.search(r'[\d]',board[i][j]):
        if re.search(r'' + chip[0], board[i][j]) or P == 1 or P == 0:
            break
        else:
            pos = str(i)+str(j)
            destinations.append(pos)
            break
    elif re.search(r'[░]',board[i][j]):
        if P == 0:
            pos = str(i)+str(j)
            destinations.append(pos)
            break
        else:
            break
    else:
        if P == 2:
            pos = str(i)+str(j)
            destinations.append(pos)
        else:
            continue

    count += 1

x and y are the fixed coordinates of the original position of
the chip
i and j are the variable coordinates
board is a matrix of 9x9 dimensions

I want to know if there is a way to implement a kind of function of method or whatever Python can provide to simplify the code above in one chunk, and call it depending of what is needed, in this case, calling it 8 times.

The code works, I just want to know how to simplify it and make it more understandable.


texts: Moving repeated files from one folder to another

texts:
I want to scan my whatsapp images folder and move all the repeated images to folder named recycle bin to delete them later:

<?php

$dir    = 'C:\wamp\www\whatsapp';
$files = scandir($dir);

$x = 0;

foreach($files as $f1)
{

    $crc1 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f1))));

    unset($files[$x]);

    $j = 0;

    foreach($files as $f2)
    {

        $crc2 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f2))));

        if($crc1 == $crc2){

            rename("whatsapp/".$f2, "recycle bin/".$f2);

            unset($files[$j]);
        }

        $j++;
    }

    $x++;
}

exit('Done');

Does this code seems to be trusted to move only the repeated images without any mistakes?


texts: Manipulate Hash to typecast true/false for certain values

texts:
is there a better why how can I refactor this code, making sure that values in a Hash are typecasted to true/false if their value is '1' or '0' while leaving unaltered the rest?

I'm using Ruby 2.0.0 if that matters, and I'd like to improve this code.

  def transform
    hsh = {}
    preferences.each do |k, v|
      v = case v
      when '1'
        true
      when '0'
        false
      else
        v
      end
      hsh[k.to_sym] = v
    end
    hsh
  end

updated with benchmarks

All right, here's the performance test based on the replies so far:

class Test
  HSH = {"xxx"=>"xxx-rrr", "yyy"=>"0", "rrr"=>"1", "nnn"=>"0", "kkk"=>"1", "iii"=>"1", "lll"=>"default", "mmm"=>"76", "www"=>"1"}

  def self.transform_case
    hsh = {}
    HSH.each do |k, v|
      v = case v
      when '1'
        true
      when '0'
        false
      else
        v
      end
      hsh[k.to_sym] = v
    end
    hsh
  end

  def self.transform_ternary
    Hash[ HSH.map { |k, v| [k.to_sym, v == '1' ? true : v == '2' ? false : v ] } ]
  end

  def self.transform_fetch
    special_values = {"1" => true, "0" => false}
    Hash[HSH.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]
  end

  def self.transform_negation
    Hash[ preferences.map {|k,v| [k.to_sym, !!v]} ]
  end
end

Benchmark.bm(20) do|b|

  b.report('case') do
    1500.times { Test.transform_case }
  end

  b.report('ternary') do
    1500.times { Test.transform_ternary }
  end

  b.report('fetch') do
    1500.times { Test.transform_fetch }
  end

  b.report('negation') do
    1500.times { Test.transform_negation }
  end
end

                           user     system      total        real
case                   0.010000   0.000000   0.010000 (  0.009282)
ternary                0.010000   0.000000   0.010000 (  0.013794)
fetch                  0.010000   0.000000   0.010000 (  0.012804)
negation               0.010000   0.000000   0.010000 (  0.010760)

It appears that my original implementation is faster. Or is the BM test wrong?


texts:
I have a text file that contains name, age, salary, hoursWorked, randomText and are filled with different delimiters.

Text file:

susan:25-2600,28[asd]
mary:21-2200,38[asd]
john:23-3400,46[asd]

Instead of breaking them into individual strings using the code shown below:

string name,age,salary,hoursWorked,randomText;
ifstream readFile("textfile.txt");

while(getline(readFile,line))   {
    stringstream iss(line);
    getline(iss, name, ':');
    getline(iss, age, '-');
    getline(iss, salary, ',');
    getline(iss, hoursWorked, '[');
    getline(iss, randomText, ']');
}
readFile.close();

What are some better strategies other than coding it this way?

Side note

I declared all the variables to strings because of the getline() method.


texts: Functional Programming: int to bignum conversions

texts:
I'm doing an exercise where I need to convert int to bignum in OCaml, for example:

123456789 -> {neg:false; coeffs:[123;456;789]}

There were a lot of things going inside my head when writing the function, and it was a load of fun. However, I'm not really sure if this is the cleanest, and fastest way to do this.

type bignum = {neg: bool; coeffs: int list};;
let base = 1000;;

let fromInt (n: int) : bignum =
  let rec aux num:int list=
    if num==0 then
       []
    else
       abs (num mod base) :: aux (num/base)
  in
  {neg=n<0; coeffs=List.rev (aux n)}
;;

fromInt turns an int to a bignum. Things to note:

I decided to mod the number with the base, and then divide the number
by the base and use that as the input. This is so I can avoid having to do exponents on ints. Was actually pretty excited when I realized that.
Used abs on (num mod base) every recursive call. Do you think there is a cleaner way of doing this? The the reason I didn't abs it on the first call was because (-max_int) <> min_int
As you can see I'm using List.rev because I do it in reverse order. This is so I can avoid having snoc lists. I'm not really sure if it's the only way though so feel free to note me.

And here is toInt, which turns a bignum into an int.

let toInt (b: bignum) =
  let rec aux (b:int list) (p:int)=
     match b with
     |hd::[]-> Some (hd*p)
     |hd::tl-> (match aux tl (p*base) with
        |Some c-> let bint = (hd*p) in
                  if bint < hd then None
                  else Some (bint+c)
        |None -> None)
     |[]->Some 0
  in
  let {neg=n; coeffs=x} = b in
  let c = List.rev x in
     match aux c 1 with
     |Some c-> if n then Some (-c) else Some c
     |None -> None
;;

I'm particularly not fond of the nested match statements, and there is probably still room for cleanup. Is there?


texts:
I needed a way to update a parameter in the URL, or add it if it doesn't exist, but keep any other variables the same value.  I built this function to do the task, and while it works, I feel like it's taking longer than it should.  Does anyone have any suggestion on what I could change or a faster method?

function changeURLParameter(sVariable, sNewValue)
{
    var aURLParams = [];
    var aParts;
    var aParams = (window.location.search).substring(1, (window.location.search).length).split('&');

    for (var i = 0; i < aParams.length; i++)
    {
        aParts = aParams[i].split('=');
        aURLParams[aParts[0]] = aParts[1];
    }

    if (aURLParams[sVariable] != sNewValue)
    {
        if (sNewValue.toUpperCase() == "ALL")
            aURLParams[sVariable] = null;
        else
            aURLParams[sVariable] = sNewValue;

        var sNewURL = window.location.origin + window.location.pathname;
        var bFirst = true;

        for (var sKey in aURLParams)
        {
            if (aURLParams[sKey])
            {
                if (bFirst)
                {
                    sNewURL += "?" + sKey + "=" + aURLParams[sKey];
                    bFirst = false;
                }
                else
                    sNewURL += "&" + sKey + "=" + aURLParams[sKey];
            }
        }

        return sNewURL;
    }
}


texts:
This is my sound system that allows for the following functionality:

One master volume that controls every sound.
A function to stop/pause every playing sound
A function to control every instance of a sounds volume(@creation)
A function to stop/pause every instance of the same sound
Sounds that are playing are kept in a list to keep track of.
retrieve a list of specified sounds playing
Retrieve a list of every sound playing

How could I possibly improve the code, or the system itself? I could possibly allow the user to define layers to encapsulate sectors of sound and not just the same instance. I could probably make a user.

  // exponentially decrease sounds
  this.Sound.masterVolume = function(v){ masterVolume = Math.pow(v,2);};
  this.Sound.instanceVolume = function(name, v){ instanceVolume[name] = Math.pow(v,2);};
  this.Sound.masterStop = function(){
    liveSounds.forEach(function(snd){
      snd.pause();
      snd.onended();
      snd.currentTime = 0;
    });
  }
  this.Sound.masterPause = function(){
    liveSounds.forEach(function(snd){
      snd.pause();
    });
  };
  this.Sound.instanceStop = function( name ){
    var match = sounds[name].src;
    liveSounds.forEach(function(snd){
      if( snd.src !== match ) return;
      snd.pause();
      snd.onended();
      snd.currentTime = 0;
    });
  };
  this.Sound.instancePause = function( name ){
    var match = sounds[name].src;
    liveSounds.forEach(function(snd){
      if( snd.src !==  match ) return;
      snd.pause();
    });
  }
  this.Sound.instanceGetLive = function( name ){
    return liveSounds.filter(function(snd){
      return( snd.src === match );
    });
  }
  this.Sound.masterGetLive = function(){
    return liveSounds.splice();//only a copy.
  }

  this.sound = function(name){
    var snd = new Audio( sounds[name].src ),
        that = this;
    snd.volume = instanceVolume[name] || 1;
    snd.play = function(){
      this.volume *= masterVolume;
      Audio.prototype.play.apply(this);
      liveSounds.push(this);
      this.onended = function(){ liveSounds.splice( liveSounds.indexOf(snd), 1 );};
    };
    return snd;
  };


texts: Handling periods ('.') in CSV column names with Pandas

texts:
I'm reading and processing a fairly large csv using Pandas and Python 3.7. Header names in the CSV have periods in them ('full stops', Britons say). That's a problem when you want to address data cells by column name.

test.csv:

"name","birth.place","not.important"
"John","",""
"Paul","Liverpool","blue"

# -*- coding: utf-8 -*-

import pandas as pd

infile = 'test.csv'
useful_cols = ['name', 'birth.place']
df = pd.read_csv(infile, usecols=useful_cols, encoding='utf-8-sig', engine='python')

# replace '.' by '_'
df.columns = df.columns.str.replace('.', '_')

# we may want to iterate over useful_cols later, so to keep things consistent:
useful_cols = [s.replace('', '') for s in useful_cols]

# now we can do this..
print(df['birth_place'])

# ... and this
for row in df.itertuples():
    print(row.birth_place)

# ain't that nice?

It works, but since Pandas is such a powerful library and the use case is quite common, I'm wondering if there isn't an even better way of doing this.


texts:
I am learning some OOP on PHP and I have developed some sample code to practise.

Ignoring the functionality, I just want to learn the "best" or "better" way to write OOP codes in PHP.

The following is my code and I hope anyone who has been doing PHP can help to review or comment for any improvements or weaknesses on my code.

I want to develop my style of code in which copy-and paste is minimum and functionality expandability is rich. For example, the execute() function in the UserDB class is basically the same function and can be used widespread in many diff db class. Do I need to copy and paste the code again or should I just moved this piece of code to abstract class?

How can I optimized my code to made it better for future functionalities such as other select, insert, update and delete while maintaining readability and still within OOP standards?

<?php

    require_once "sys_config.php";
    require_once "general.inc";
    $para[":user"]= "%";

    $dataset = UserFactory::getUsers($para);

    var_dump($dataset);

?>

UserFactory class

<?php

    class UserFactory{

        public static function getUsers($para)
        {
            $db = new UserDB("CALL getUsers(:user)",$para); //sp

            $objs = $db->execute();
            if(!empty($objs))
                foreach( $objs as $obj)
                {
                    $users[] = new user($obj);
                }
            return $users;
        }

    }

?>

UserDB class

<?php

    Class UserDB extends Database{

        protected $conn;
        protected $SQL;
        protected $para;

        function __construct($SQL, $para)
        {
            parent::__construct();

            $this->conn = parent::getConn();
            $this->SQL = $SQL;
            $this->para = $para;
        }

        function execute()
        {

            $query = $this->conn->prepare($this->SQL);
            if(!empty($this->para))
                foreach($this->para as $key=>$val)
                {
                    $query->bindParam($key,$val);
                }
            $results = $query->execute();

            $dataset = null;

            if($results)
            {
                while($row = $query->fetch(PDO::FETCH_OBJ))
                {
                    $dataset[]=$row;
                }
            }

            unset($this->conn);

            parent::__destruct();

            return $dataset;

        }

    }

?>

Database abstract class

<?php

    abstract Class Database{

        protected $conn;

        function __construct()
        {
            $this->conn = new PDO ("mysql:host=".DB_LOCATION.";dbname=".DB_NAME,DB_USER,DB_PASS);

        }

        function __destruct()
        {
            unset($this->conn);

        }

        function getConn()
        {
            return $this->conn;
        }

        abstract function execute();
    }

?>

User object class

<?php

    class User{

        private $fullname;
        private $id;

        function __construct($userObj)
        {
            $this->fullname = $userObj->fullName;
            $this->id = $userObj->id;
        }

        function setFullname($fullname)
        {
            $this->fullname = $fullname;
        }

        function getFullname()
        {
            return $this->fullname;
        }

        function setId($id)
        {
            $this->id = $id;
        }

        function getId()
        {
            return $this->id;
        }
    }

?>


texts: Python script that getting list of all files with specific ext starting from the current folder. Using timer for reporting about the process

texts:
I am using a function that returns a list of all files (full path for each of them) with the given extension in the given folder and all subfolders.
As the process is quite long and user can get feeling that the app freezes, every 5 seconds I write to the output the name of the file the script is working on.
The code below works fine. But I am sure it is not the most readable and effective way to write it. So I am eager for feedback and advice.
Note: I tend to import as little modules as possible. os and time for this task is enough, I think.
import os
import time

def all_files_list(checkpath):
    '''Creates list of all files in subfolders of the given folder.
    Counts only .png'''
    lastTimer = time.time()
    result_list = []
    if checkpath:
        for root, dirs, files in os.walk(checkpath):
            for x in files:
                if x[-4:] == ".png":
                    if time.time() - lastTimer2 > 5:
                        lastTimer2 = time.time()
                        print('Working on ' + os.path.join(root, x))
                    result_list.append(os.path.join(root, x))
    return result_list

It creates a list of all files. Then depending on the task settings this list is filtered by specific parameters (i.e. by the language code in specific part of the path name). Then there are many options available of what can be done with the files. Copy in some structure, comparing the same files in the next folders, etc.


texts:
Can the following code snippet be optimized or am I doing it right?

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<mask id="a">
<circle cx="50" cy="50" r="50" fill="#fff"/>
<rect x="50" width="5" height="100%"/>
</mask>
<rect width="100" height="100" fill="gray" mask="url(#a)" />
</svg>

http://jsfiddle.net/5z4npr5L/6/

I don't want to use a path because I want it readable.


texts: Is this an efficient way of mounting a file-system via SSH (SSHFS)?

texts:
#!/usr/bin/python3

# Description: Python script that will mount FTP-Server via SSHFS protocol
import sys
import os
import subprocess

def mount():
#Function for mounting the networked drive
    if os.path.exists('/home/user/MNT/MEDIA/'):
        print('Network drive is mounted')
        un = input("To unmount type U/u \n")
        if un == "u" or un == "U":
            subprocess.call(['sudo fusermount -u /home/user/MNT/'], shell=True)
        else:
            pass
        exit(0)
    if not os.path.exists('/home/user/MNT/MEDIA/'):
        IP = input("Type I/i for local connection, E/e for external\n")
        if IP == "i" or IP == "I":
            subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 user@10.0.0.100:/media/Hitachi/ /home/user/MNT'], shell=True)
        if IP == "e" or IP == "E":
            subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 user@xxxxxxxx.com/media/Hitachi/ /home/user/MNT'], shell=True)
        elif IP == "": #returns if null value
            return mount()

def makedir():
#Function to check and see if directory is created and if not create it
    if not os.path.exists('/home/user/MNT/'):
        subprocess.call(['sudo mkdir /home/user/MNT/'], shell=True)
    if os.path.isdir('/home/user/MNT/'):
        mount()

makedir()

EDITED:

def sshfs():
#function to mount network drive
    while True:
        user = input("Type 'i' for internal, 'e' for external connection\n")
        fs = File_System.get(user.lower()) #Get value from the dict called File_System
        if fs is None:
            print("Invalid option, enter either 'i' for internal or 'e' for external\n")
        else:
            subprocess.call(["sudo sshfs -o uid=1000 -o gid=1000 -o idmap=user -o default_permissions -o allow_other -p 100 %s %s" % (fs, Local_Mount)], shell=True)
            exit(0)


texts:
I'm only two weeks into learning Java and just finished creating my first program.  I have a feeling I've added unnecessary things, but not sure. I'd like someone to take a look at it and let me know if there are ways to simplify or approach the code.  Basically, I'm just trying to create a simple GPA calculator.

import java.util.Scanner;

class GpaCalculator {

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        char c1;
        double gpa;
        double g1, g2, g3, g4, g5, g6;

        g1 = 0;
        g2 = 0;
        g3 = 0;
        g4 = 0;
        g5 = 0;
        g6 = 0;

        System.out.println("What is your grade for class 1?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g1 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g1 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g1 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g1 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g1 = 0;
        }
        System.out.println("What is your grade for class 2?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g2 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g2 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g2 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g2 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g2 = 0;
        }
        System.out.println("What is your grade for class 3?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g3 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g3 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g3 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g3 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g3 = 0;
        }
        System.out.println("What is your grade for class 4?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g4 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g4 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g4 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g4 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g4 = 0;
        }
        System.out.println("What is your grade for class 5?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g5 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g5 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g5 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g5 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g5 = 0;
        }
        System.out.println("What is your grade for class 6?");
        c1 = myScanner.findWithinHorizon(".", 0).charAt(0);
        if (c1 == 'a' || c1 == 'A') {
            g6 = 4;
        }
        if (c1 == 'b' || c1 == 'B') {
            g6 = 3;
        }
        if (c1 == 'c' || c1 == 'C') {
            g6 = 2;
        }
        if (c1 == 'd' || c1 == 'D') {
            g6 = 1;
        }
        if (c1 == 'f' || c1 == 'F') {
            g6 = 0;
        }

        gpa = (g1 + g2 + g3 + g4 + g5 + g6) / 6;

        System.out.println("Your GPA is " + gpa + ". ");

        if (gpa > 3.00) {
            System.out.println("Gret job, you're on your way to success.");
        } else if (gpa > 2.00) {
            System.out.println("You did OK, but better than average.");
        } else {
            System.out.println("You didn't do too well. You should look into getting a tutor.");
        }
    }
}


texts:
I am working on a speech reorganization project. I have a util class that consists of three methods: check if a microphone exists, check microphone availability, and check text-to-speech availability. Can anyone review my code?

public class MediaUtil {

    //returns whether a microphone exists
    public boolean getMicrophoneExists(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
    }

    //returns whether the microphone is available
    public static boolean getMicrophoneAvailable(Context context) {
        MediaRecorder recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        recorder.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
        boolean available = true;
        try {
            recorder.prepare();
        }
        catch (IOException exception) {
            available = false;
        }
        recorder.release();
        return available;
    }

    //returns whether text to speech is available
    public static boolean getTTSAvailable(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        List<ResolveInfo> speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
        if (speechActivities.size() != 0) return true;
        return false;
    }


texts:
The title says it all. I'm reading "The Rust Programming Language" 2nd ed. right now, and just finished the "Collections" chapter. I know there's a ton of Pig Latin code here, but I think Rust deserves a separate question.

use std::io;
use std::iter::FromIterator;

fn main() {
    println!("Enter the string to be Pig-latinized");

    let mut input = String::new();

    io::stdin().read_line(&mut input)
        .expect("Failed to read from stdin");

    let s: Vec<char> = input.chars().collect();
    let mut new_s: Vec<char> = Vec::new();
    let consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q',
    't', 'r', 's', 'v', 'w', 'x', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
    'T', 'R', 'S', 'V', 'W', 'X', 'Z'];

    let mut i = 0;

    while i < s.len() {

        if !s[i].is_alphabetic() {
            new_s.push(s[i]);
            i += 1;
            continue;
        }

        let first_letter = s[i];
        let mut appendage: Vec<char> = "-hay".chars().collect();
        if consonants.contains(&first_letter) {
            appendage[1] = first_letter;
            i += 1;
        }

        while s[i].is_alphabetic() && i < s.len() {
            new_s.push(s[i]);
            i += 1;
            continue;
        }

        new_s.append(&mut appendage);
    }

    println!("{}", String::from_iter(new_s));
}

The code feels clunky, but I don't really know how to make it better. I'd love to see an idiomatic Rust solution!


texts:
I recently became interested in back end web frameworks in python, but I didn't want to use django or flask. (I want to make something similar to django or flask) So I decided to make my own. This is what I have so far. I have been programming for nearly two years and I mostly do c++. But I would like to improve my python. What can I do to improve this, or my python in general? Thanks!

import socket as Socket

class Server:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.__run_allowed = True
        self.__HTTP_response_codes = {200: " OK", 404: " Not Found"}
        self.__socket = Socket.socket(Socket.AF_INET, Socket.SOCK_STREAM)

    def run(self):
        self.__socket.bind((self.host, self.port))
        self.__socket.listen(1)
        while self.__run_allowed:
            connection, address = self.__socket.accept()
            request = connection.recv(1024).decode("utf-8")
            webpage = request.split(' ')[1].split('?')[0].lstrip('/')
            docInfo = self.__getDocumentInfoTuple__(webpage)
            header = self.__generateHTTPResponseHeader__(docInfo[1], docInfo[2])
            connection.send(header + docInfo[0])
            connection.close()

    def __getDocumentInfoTuple__(self, page):
        print(page)
        html = None
        return_code = 200
        content_type = "text/html"
        try:
            with open(page) as file:
                html = str.encode(file.read())
        except:
            with open("404.html") as file:
                html = str.encode(file.read())
                return_code = 404
            print("Failed to find requested page!\nDefaulting to PageNotFound.html...")
        if page.endswith(".html"):
            content_type = "text/html"
        elif page.endswith(".css"):
            content_type = "text/css"
        elif page.endswith(".js"):
            content_type = "text/javascript"
        return (html, return_code, content_type)

    def __generateHTTPResponseHeader__(self, HTTP_response_code, content_type):
        header = b"HTTP/1.1 " + str.encode(str(HTTP_response_code)) + str.encode(self.__HTTP_response_codes[HTTP_response_code]) + b"\r\n"
        header += b"Content-Type: " + str.encode(content_type) + b"; Encoding: UTF-8\n\n"
        return header

def main(`enter code here`):
    server = Server("127.0.0.1", 8080)
    server.run()

if __name__ == "__main__":
    main()


texts: Animating one of three boxes based on a form value

texts:
Is there a better way to do this without using if or case statements?

var val = ui.value,
$box = $('#message');
switch(true) {
  case (val > 50):
    $box.hide();
    animations.animateBox($box.html('you have chosen XN'));
    break;
  case (val < 50):
    $box.hide().delay(300);
    animations.animateBox($box.html('you have chosen VN'));
    break;
  default:
    $box.hide();
    animations.animateBox($box.html('you have chosen PN'));
}


texts:
for the following function

#!/usr/bin/ruby -w
e=0
g=0
h=1
while h < 10000000
    a = h
    f=0
    while f !=1 && f!= 89
        d=0
        f=0
        while a.to_s[d] != nil
            e = a.to_s[d]
            b = e.to_i
            f += b**2
            d+=1
        end
        a = f
        f = 89 if [4,16,37,58,20,42,145].include? f
    end
    h += 1
    g+=1 if f == 89
end
p g

this is a porject i'm working for a certain programming practice website which i will not mention by name so my solution can't be found on google, but it's the 92nd problem. it runs about three times slower than i would like, everything that i have tried to speed it up with ends up adding a few seconds instead of subtracting, and that icludes storing values in arrays for later comparisons, any suggestions?
run time is 3:10 and the result is 8581146
the purpose of this code is to find square digit chains from one to ten thousand that either end up in one or eighty-nine and to run a count of how many end at eightnine and out put the total when the program finishes. i get the square digit result for a number by first converting it into a string and converting individual chars back into nums and running it repeatedly, i have an if statement to catch f if it hits any of the numbers on the eighty-nine loop so i can shave off a few cycles here and there.


texts: Reading SQL file using injection and utility reader

texts:
I've come up with a way to externalize and read in my .sql files instead of having them in-code as strings.  Note that I'm keeping the .sql file in the same package as the DAO (NOT separated into a separate resources folder).

I'm curious what others think about this methodology.

The sqlStatement is inject on class load (which because this is managed by Spring, on application start).  It will call the static method SqlReader.getStatement(), passing in the file name.

Data Access

@Repository
public class TestDAO {

    @Value("#{sqlReader.getStatement('com/mycompany/selectStatement.sql')}")
    private String selectStatement;

The SqlReader is a Utility class located in another package.

public class SqlReader {

    public static String getStatement(final String file) {

        try {
            return FileUtils.readFileToString(new ClassPathResource(file).getFile(), StandardCharsets.UTF_8);
        } catch (IOException exception) {
            Logger.error("IOException reading file [" + file + "].", exception);
            throw new IllegalStateException("Error reading for file [" + file + "]", exception);
        }
    }
}

Updated: updated the error handling. also, made SqlReader a Spring component, which cleans up the @Value expression by removing the necessity to lookup the SqlReader by type (Spring can find it by it's bean name now).


texts:
Can you please point out any problems with this C forward list with remove node functionality?

I believe this can be way simpler ( removeNode function ) but I somehow cannot grasp it

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

struct node
{
  int val;
  struct node* next;
};
typedef struct node node;

node* newNode(int val)
{
  node* n = (node*)malloc(sizeof(node));
  n->val = val;
  n->next = NULL;
  return n;
}

void printList(node* head)
{
  if (head == NULL) return;

  do
  {
    printf("%d, ", head->val);
    head = head->next;
  } while (head->next);

  printf("\n");
}

void clean(node* head)
{
  while (head)
  {
    node* curr = head;
    if (head->next == NULL)
    {
      free(head);
      return;
    }

    head = head->next;
    free(curr);
  }
}

void insert(node* head, int val)
{
  while (head)
  {
    if (head->next)
    {
      head = head->next;
    }
    else
    {
      head->next = newNode(val);
      return;
    }
  }
}

void removeIf(node** head, int val)
{
  if (head == NULL) return;
  if (*head == NULL)
  {
    head = NULL;
    return;
  }

  while (*head && (*head)->val == val)
  {
    if ((*head)->next == NULL)
    {
      free(*head);
      *head = NULL;
      return;
    }
    node* tofree = *head;
    *head = (*head)->next;
    free(tofree);
  }

  node* curr = (*head)->next;
  node* prev = *head;

  while (curr)
  {
    if (curr->next == NULL) return;

    if (curr->val == val)
    {
      prev->next = curr->next;
      node* tofree = curr;
      curr = curr->next;
      free(tofree);
    }
    else
    {
      prev = prev->next;
      curr = curr->next;
    }
  }
}

int size(node* root)
{
  if (root == NULL) return 0;
  int sz = 1;
  while (root->next)
  {
    root = root->next;
    ++sz;
  }

  return sz;
}

void tests();

int main()
{
  tests();
}

/*
 * Here are the tests for lists functionalities
 */
void tests()
{
  {
    node* root = newNode(1);
    insert(root, 2);
    assert(size(root) == 2);
    clean(root);
  }
  {
    node* root = newNode(8);
    insert(root, 2);
    insert(root, 2);
    assert(size(root) == 3);
    clean(root);
  }
  {
    node* root = newNode(8);
    insert(root, 123);
    insert(root, 123);
    insert(root, 123);
    insert(root, 123);
    assert(size(root) == 5);
    clean(root);
  }
  {
    node* root = newNode(8);
    insert(root, 123);
    assert(size(root) == 2);
    removeIf(&root, 1);
    assert(size(root) == 2);
    clean(root);
  }
  {
    node* root = newNode(1);
    insert(root, 1);
    insert(root, 1);
    insert(root, 1);
    insert(root, 2);
    insert(root, 3);
    insert(root, 3);
    insert(root, 4);
    insert(root, 4);
    insert(root, 5);
    assert(size(root) == 10);
    removeIf(&root, 1);
    assert(size(root) == 6);
    clean(root);
  }
  {
    node* root = newNode(1);
    insert(root, 1);
    insert(root, 1);
    insert(root, 1);
    insert(root, 2);
    insert(root, 3);
    insert(root, 3);
    insert(root, 4);
    insert(root, 4);
    insert(root, 5);
    assert(size(root) == 10);
    removeIf(&root, 3);
    assert(size(root) == 8);
    clean(root);
  }
  {
    node* root = newNode(1);
    insert(root, 1);
    assert(size(root) == 2);
    removeIf(&root, 1);
    assert(size(root) == 0);
    clean(root);
  }
  {
    node* root = newNode(1);
    insert(root, 1);
    insert(root, 1);
    insert(root, 1);
    assert(size(root) == 4);
    removeIf(&root, 1);
    assert(size(root) == 0);
    clean(root);
  }
}


texts:
Could this be made more efficient, and/or simpler?  It's a path-finding function.  It seems to work, but do you see any potential cases where it could fail?

// Searches for a path from [start] to [end].
// Predicate [passable] should take an std::pair<int,int> and return true if the node is passable.
// Nodes in path are stored in [out].
// Return value is a pair.  With first being a bool to indicate if a path was found,
// and second an iterator for the end of the path
template<typename OutputIterator, typename PassablePR>
std::pair<bool, OutputIterator> ShortestPath(std::pair<int,int> start, std::pair<int,int> end, PassablePR passable, OutputIterator out)
{
    typedef std::pair<int,int> node;

    std::pair<bool, OutputIterator> ret(false, out);

    // queue of nodes expanding out from the starting point
    std::queue<node> q;

    // keep track of visited nodes so we don't visit them twice
    std::vector<node> visited_nodes;
    auto visited = [&visited_nodes] (node n) {
        return std::find(visited_nodes.begin(), visited_nodes.end(), n) != visited_nodes.end();
    };

    // link child nodes to parents
    std::map<node,node> path_tree;

    q.push(start);
    while(q.empty() == false)
    {
        auto parent = q.front();
        if(passable(parent) && !visited(parent))
        {
            visited_nodes.push_back(parent);

            if(parent == end)
            {
                ret.first = true;
                std::vector<std::pair<int,int>> path;
                auto i = path_tree.find(parent);
                while(i != path_tree.end())
                {
                    path.push_back(i->first);
                    parent = i->second;
                    path_tree.erase(i);
                    i = path_tree.find(parent);
                }

                // path is currently from end to start, so reverse it
                std::copy(path.rbegin(), path.rend(), ret.second);

                return ret;
            }

            auto child(parent);

            // node to the left
            --child.first;
            q.push(child);
            if(path_tree.find(child) == path_tree.end())
                path_tree[child] = parent;

            // right
            child.first += 2;
            q.push(child);
            if(path_tree.find(child) == path_tree.end())
                path_tree[child] = parent;

            // above
            --child.first;
            --child.second;
            q.push(child);
            if(path_tree.find(child) == path_tree.end())
                path_tree[child] = parent;

            // and below
            child.second += 2;
            q.push(child);
            if(path_tree.find(child) == path_tree.end())
                path_tree[child] = parent;
        }
        q.pop();
    }
    return ret;
}

Testing it out:

int main()
{
    int grid[5][5] =
    { { 0, 1, 0, 0, 0 },
      { 0, 0, 0, 1, 0 },
      { 0, 1, 0, 1, 0 },
      { 0, 1, 0, 1, 0 },
      { 0, 0, 0, 1, 0 } };

    std::vector<std::pair<int,int>> path;

    auto ret = ShortestPath(std::pair<int,int>(0,0), std::pair<int,int>(4,4),
        [&grid] (std::pair<int,int> n) -> bool {
            if(ben::WithinBoundsInclusive(std::pair<int,int>(0,0), std::pair<int,int>(4,4), n) == false)
                return false;
            return grid[n.first][n.second] == 0;
        },
        std::back_inserter(path));

    if(ret.first)
    {
        std::cout << "Path found\n";

        std::for_each(path.begin(), path.end(),
            [](std::pair<int,int> n) {
                std::cout << '(' << n.first << ',' << n.second << ")\n";
            });
    }
    else
        std::cout << "Path not found\n";
}


texts: What is the idiomatic Rust way to write this naive JavaScript token scanner code fragment?

texts:
I am learning Rust and finding it quite a difficult but rewarding and fun challenge to learn how to write idiomatic and succinct, clean code in it.

I have written the following simple naive JavaScript scanner code as an exercise to learn some basics of Rust.  While it works, it feels like it is far from ideal Rust code.

Are there better ways to write these simple functions?  A few things that stand out to me are:

The loops and pattern matching feel more verbose than they could be
The use of the Chars iterator feels almost right but somehow off

In particular, the scan_identifier function is very clumsy since the iterator can't rewind already consumed characters in the string

Note I am a compiler dev and know that this isn't great scanner code.  That is not the point of this exercise.  I am looking to learn how to do Rust basics through practice.

fn scan_identifier(first: char, chars: &mut std::str::Chars) {
    let mut identifier = String::new();
    identifier.push(first);

    let mut id_chars = chars.clone();
    while let Some(c) = id_chars.next() {
        match c {
            'a'...'z'|'A'...'Z'|'0'...'9' =>
                identifier.push(c),
            _ => break,
        }
    }
    println!("{}", identifier);
    chars.nth(identifier.chars().count() - 2);
}

fn scan_string(chars: &mut std::str::Chars) {
    let mut string = String::new();
    while let Some(c) = chars.next() {
        match c {
            '\'' => { println!("'{}'", string); return; },
            _ => string.push(c),
        }
    }
    println!("unterminated string! '{}", string);
}

fn scan(src: &str) {
    let mut chars = src.chars();
    while let Some(c) = chars.next() {
        match c {
            '(' => println!("("),
            ')' => println!(")"),
            ';' => println!(";"),
            '\'' => scan_string(&mut chars),
            _ => scan_identifier(c, &mut chars),
        }
    }
}

fn main() {
    let input = "print('Hello, world!');";
    println!("Input:\n\n{}\n\nTokens:\n", input);
    scan(input);
}


texts: Multi-threaded client/server/rate_controller testing harness

texts:
Context
Further to this question there was some discussion regarding "circular buffer" vs "time_slice" approach to rate control.
So I worked up this simple multi-threaded client / server simulation as a testing harness.

Usual coding style feedback please
Does this allow us to answer the question of "is timeslice good enough or do we need circular buffer". - could easily substitute the circular buffer rate_controller from answer in above question for comparison

My proposed answer is: If there are signifcant clients (> 50?) then statistics smooth things out to the point where you can't tell the difference.
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <thread>

namespace os {

class server {
public:
  void req(char ch) {
    std::lock_guard<std::mutex> lg(mut);
    std::cout << ch << std::flush; // visual representation of making a server request
  }

private:
  std::mutex mut; // only one shared server instace, must ensure thread-safe access
};

class rate_controller {
  using clk_t = std::chrono::system_clock;

public:
  rate_controller(unsigned limit, long time_slice_ms, long rnd_offset_ms)
      : n_(limit), time_slice_ms_(time_slice_ms), rnd_offset_ms_(rnd_offset_ms) {}

  bool check() {
    auto duration_since_epoch = clk_t::now().time_since_epoch();
    long curr_time_slice =
        (rnd_offset_ms_ +
         std::chrono::duration_cast<std::chrono::milliseconds>(duration_since_epoch).count()) /
        time_slice_ms_; // intentional integer division

    if (curr_time_slice != last_time_slice_) {
      last_time_slice_ = curr_time_slice;
      count_           = 0;
    }
    ++count_;
    return (count_ <= n_);
  }

private:
  unsigned n_;
  long     time_slice_ms_;
  long     rnd_offset_ms_;
  long     last_time_slice_ = 0;
  unsigned count_           = 0;
  ;
};

class client {
public:
  explicit client(server& s, char ch) : s_(s), ch_(ch) {}

  void run() {
    using std::chrono::milliseconds;
    using std::this_thread::sleep_for;

    for (int i = 0; i < 100; ++i) {
      if (in_burst) {
        sleep_for(milliseconds(in_burst_delay_dist(reng)));
        if (burst_prob_dist(reng) < 10) in_burst = false;
      } else {
        sleep_for(milliseconds(out_of_burst_delay_dist(reng)));
        if (burst_prob_dist(reng) < 20) in_burst = true;
      }

      // wait until our rate controller permits this request. / 20 => 5% "accuracy".
      while (!rc.check()) sleep_for(milliseconds(time_slice_ms / 20));

      s_.req(ch_);
    }
  }

private:
  std::mt19937                       reng{std::random_device{}()};
  std::uniform_int_distribution<int> in_burst_delay_dist{1, 1000};
  std::uniform_int_distribution<int> out_of_burst_delay_dist{1, 50};
  std::uniform_int_distribution<int> burst_prob_dist{1, 100};

  const long      time_slice_ms = 200;
  rate_controller rc{1, time_slice_ms, std::uniform_int_distribution<long>{0, time_slice_ms}(reng)};

  server& s_;
  char    ch_;

  bool in_burst = false;
};

struct worker {
  explicit worker(server& s, char ch) : c(s, ch), t([this]() { this->c.run(); }) {}
  client      c;
  std::thread t;
};

}  // namespace os

int main() {
  constexpr int max_workers = 10 + 26 + 26;

  // compile time construction of some one character thread indentifiers
  // rather than a messy literal array initiliaser list
  constexpr std::array<char, max_workers> thread_ids = []() {
    auto cs = decltype(thread_ids){};
    int  i  = 0;
    for (int c = '0'; c <= '9'; ++c) cs[i++] = c;
    for (int c = 'A'; c <= 'Z'; ++c) cs[i++] = c;
    for (int c = 'a'; c <= 'z'; ++c) cs[i++] = c;
    return cs;
  }();

  using os::server, os::worker;

  server              serv;
  std::vector<worker> workers;
  workers.reserve(max_workers);
  for (int i = 0; i < max_workers; ++i) workers.emplace_back(serv, thread_ids[i]);
  for (auto& w: workers) w.t.join();
}


texts: Using HttpServltRequest to store a Request Scope map cache

texts:
I'm playing with CDI interceptors and thought use a interceptor to cache some methods in a managed bean:

@RequestCache
public long getTotalVendidosDia(Produto produto) {
    long ini = System.currentTimeMillis();
    try {
        sleep();
        return produto.getValor().longValue();
    } finally {
        countGetTotalVendidosDia++;
        getTotalVendidosDiaTotalTime += (System.currentTimeMillis() - ini);
    }
}

Interceptor code:

public static final String MAP_NAME = RequestCacheInterceptor.class.getName() + "_map_cache";

@AroundInvoke
public Object executeEntry(InvocationContext invocationContext) throws Exception {
    Map<Key, Result> mapCache = getMapCache();
    Key key = new Key(invocationContext);
    Result result = mapCache.get(key);
    if (result == null) {
        long ini = System.currentTimeMillis();
        result = new Result(invocationContext.proceed());
        result.time = System.currentTimeMillis() - ini;
        mapCache.put(key, result);
    }
    result.count++;
    return result.object;
}

private Map<Key, Result> getMapCache() {
    Map<Key, Result> map = (Map<Key, Result>) getRequest().getAttribute(MAP_NAME);
    if (map == null) {
        map = Collections.synchronizedMap(new HashMap<RequestCacheInterceptor.Key, Result>());
        getRequest().setAttribute(MAP_NAME, map);
    }
    return map;
}

private HttpServletRequest getRequest() {
    return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}

private class Result {
    long count = 0;
    long time;
    Object object;

    public Result(Object object) {
        super();
        this.object = object;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + getOuterType().hashCode();
        result = prime * result
                + ((this.object == null) ? 0 : this.object.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Result other = (Result) obj;
        if (!getOuterType().equals(other.getOuterType()))
            return false;
        if (object == null) {
            if (other.object != null)
                return false;
        } else if (!object.equals(other.object))
            return false;
        return true;
    }
    private RequestCacheInterceptor getOuterType() {
        return RequestCacheInterceptor.this;
    }

}

private class Key {
    Method method;
    Object[] params;

    public Key(InvocationContext invocationContext) {
        this(invocationContext.getMethod(), invocationContext.getParameters());
    }

    public Key(Method method, Object[] params) {
        super();
        this.method = method;
        this.params = params;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + getOuterType().hashCode();
        result = prime * result
                + ((method == null) ? 0 : method.hashCode());
        result = prime * result + Arrays.hashCode(params);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Key other = (Key) obj;
        if (!getOuterType().equals(other.getOuterType()))
            return false;
        if (method == null) {
            if (other.method != null)
                return false;
        } else if (!method.equals(other.method))
            return false;
        if (!Arrays.equals(params, other.params))
            return false;
        return true;
    }

    private RequestCacheInterceptor getOuterType() {
        return RequestCacheInterceptor.this;
    }

}

Is it a problem to use that approach?


texts: Fast distance calculation for Starcraft2 bot

texts:
I am coding a bot for Starcraft 2, in which many distances have to be calculated every frame.

Here is the part of the library that is being used and I want to improve: https://github.com/Dentosal/python-sc2/blob/develop/sc2/position.py

I built a new class Points that inherits from np.ndarray.
It is not yet connected to the rest of the library, but the functions are done. I removed the functions furthest_to, further_than and so on because the closer-versions are basically the same execpt a -1 or <.

Are these functions implemented in most efficient way? Is there a way to improve the parts that look like this:

find = np.where(np.any(M < distance, axis=1))
selection = np.array([self[i] for i in find[0]])

Any other comments or suggestions are also welcome :)

from typing import Any, Dict, List, Optional, Set, Tuple, Union  # for mypy type checking

import numpy as np
from scipy.spatial.distance import cdist

from position import Point2

class Points(np.ndarray):
    def __new__(cls, units_or_points):
        obj = np.asarray(units_or_points).view(cls)
        return obj

    def closest_to(self, point: Point2) -> Point2:
        """Returns the point of self that is closest to another point."""
        if point in self:
            return Point2(tuple(point))
        deltas = self - point
        distances = np.einsum("ij,ij->i", deltas, deltas)
        result = self[np.argmin(distances)]
        return Point2(tuple(result))

    def closer_than(self, point: Point2, distance: Union[int, float]) -> "Points":
        """Returns a new Points object with all points of self that
        are closer than distance to point."""
        position = np.array([point])
        M = cdist(self, position)
        find = np.where(np.all(M < distance, axis=1))
        selection = np.array([self[i] for i in find[0]])
        return Points(selection)

    def in_distance_between(
        self, point: Point2, distance1: Union[int, float], distance2: Union[int, float]
    ) -> "Points":
        """Returns a new Points object with all points of self
        that are between distance1 and distance2 away from point."""
        p = np.array([point])
        M = cdist(self, p)
        find = np.where(np.any(np.logical_and(distance1 < M, M < distance2), axis=1))
        selection = np.array([self[i] for i in find[0]])
        return Points(selection)

    def sort_by_distance_to(self, point: Point2, reverse: bool = False) -> "Points":
        """Returns a new Points object with all points of self sorted by distance to point.
        Ordered from smallest to biggest distance. Reverse order with keyword reverse=True."""
        deltas = self - point
        distances = (1 if reverse else -1) * np.einsum("ij,ij->i", deltas, deltas)
        result = self[distances.argsort()[::-1]]
        return Points(result)

    def closest_n_points(self, point: Point2, n: int) -> "Points":
        """Returns a new Points object with the n points of self that are closest to point."""
        deltas = self - point
        distances = np.einsum("ij,ij->i", deltas, deltas)
        result = (self[distances.argsort()[::-1]])[-n:]
        return Points(result)

    def in_distance_of_points(self, points: "Points", distance: Union[int, float]) -> "Points":
        """Returns a new Points object with every point of self that
        is in distance of any point in points."""
        M = cdist(self, points)
        find = np.where(np.any(M < distance, axis=1))
        selection = np.array([self[i] for i in find[0]])
        return Points(selection)

    def n_closest_to_distance(self, point: Point2, distance: Union[int, float], n: int) -> "Points":
        """Returns a new Points object with the n points of self
        which calculated distance to point is closest to distance."""
        deltas = self - point
        distances = np.absolute(distance - np.einsum("ij,ij->i", deltas, deltas))
        result = (self[distances.argsort()[::-1]])[-n:]
        return Points(result)


texts: Regex to remove inline javascript from string

texts:
I need to remove inline javascript for a given string. Examples:

If user typed:

I should need to convert into

I created this PHP code and it works(apparently without issues):

http://writecodeonline.com/php/

function test_input($input){
  //I have a list with all events but for this example I used two
  $html_events = 'onload|onclick';
  $pattern = "/(<[A-Z][A-Z0-9]*[^>]*)($html_events)([\s]*=[\s]*)('[^>]*'|\"[^>]*\")([^>]*>)/i";
  $replacement = '$1$5';
  while( preg_match($pattern, $input) ){
    $input = preg_replace($pattern, $replacement, $input);
  }
  return htmlentities($input);
}

echo test_input(''). '
';
echo test_input(''). '
';
echo test_input('
hello buddies
'). '
';

I'm just looking for improvements or use cases that I did not supporting or that break my regex. I would appreciate if you tell me:

This: test_input('something bad'); breaks your regex.

Or if found an improvement that in a benchmark demonstrate better performance I should be happy to apply it as long as it does not break use cases already supported.

Thank You!

Update
I finally used htmlpurifier


texts:
I've seen many, many UoW+Repository implementations. Whenever one was built on top of Entity Framework, I'd cringe at the added complexity.

Sure the complexity buys you (sometimes) full decoupling from Entity Framework, which in theory would possibly allow swapping EF for, say, NHibernate, or even "downgrade" to a lower-level ADO.NET solution.

But most people implement an IUnitOfWork interface for the sole purpose of enabling easier testability - I'm one of those. I'm not buying the "dude I can swap my ORM without touching the rest of my app" argument, simply because it's more often than not, a theoretical advantage, if not a plain lie.

So I like to keep it stupid simple (KISS), and only do the minimum needed to enable mocking of my DbContext class - here's a real-world IUnitOfWork interface I've written in a recent project:

  IUnitOfWork interface

public interface IUnitOfWork
{
    int SaveChanges();
    IDbSet<TEntity> Repository<TEntity>() where TEntity : class;
}

Entity Framework's DbContext is a unit of work, and IDbSet<TEntity> is a repository. So instead of going all out and writing a generic repository and adding a considerable amount of useless complexity (useless in the sense that I don't need that to enable mocking my DbContext), I'm making my DbContext-derived class implement my IUnitOfWork interface:

  CallAssistantContext class

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class CallAssistantContext : DbContext, IUnitOfWork
{
    public CallAssistantContext(string connectionString)
        : base(connectionString)
    { }

    public IDbSet<TEntity> Repository<TEntity>() where TEntity : class
    {
        return base.Set<TEntity>();
    }

    public IDbSet<CustomerServiceCall> CustomerServiceCalls { get; set; }

    public IDbSet<CallType> CallTypes { get; set; }
    public IDbSet<ContactType> ContactTypes { get; set; }
    public IDbSet<IssueType> IssueTypes { get; set; }

    public IDbSet<Customer> Customers { get; set; }
    public IDbSet<CustomerStore> CustomerStores { get; set; }
    public IDbSet<SalesRep> SalesReps { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

The "client code" depends on an abstraction - the IUnitOfWork interface, and can very easily be constructor-injected with a mock implementation in unit tests:

public class MainWindowViewModel : ViewModelBase
{
    private readonly IUnitOfWork _context;

    public MainWindowViewModel(IUnitOfWork context)
    {
        _context = context;
    }

Querying the context doesn't look too complicated either:

var cutoffDate = DateTime.Now.Subtract(TimeSpan.FromDays(7));
ServiceCalls = _context.Repository<CustomerServiceCall>()
                        .Where(e => e.CallStart >= cutoffDate)
                        .ToList();

So, is anything blatantly wrong with this approach? Here I've injected the UoW/context directly where it's needed - in a bigger project I would have created a "service" and constructor-injected the UoW there instead.


texts: Three methods to serialize 7-, 6-, and 3-dimensional int arrays

texts:
Here's some code I wrote which sends multi-dimensional arrays to a file, is there any way I can make a generic method?

public void sendSevenToFile(int[][][][][][][] seven, String filename) throws IOException {
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
    outputStream.writeObject(seven);
}

public void sendSixToFile(int[][][][][][] six, String filename) throws IOException {
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
    outputStream.writeObject(six);
}

public void sendThreeToFile(int[][][] three, String filename) throws IOException {
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(filename));
    outputStream.writeObject(three);
}


texts: Checking whether if start and end has equal number of non-zero integers and contains 3 or more 0 in the center

texts:
An array is said to be hollow if it contains 3 or more zeros in the
  middle that are preceded and followed by the same number of non-zero
  elements. Write a function named isHollow that accepts an integer
  array and returns 1 if it is a hollow array, otherwise it returns 0.
  The function signature is int isHollow(int[ ] a).

  Note:  Please do not use any String functions. No sorting allowed. No additional arrays or data structures allowed.

  Test Cases:

  isHollow({1,2,4,0,0,0,3,4,5}) returns true
  isHollow({1,2,4,0,0,0,1,0,3,4,5}) returns false
  isHollow({1,2,0,0,0,3,4,5}) returns false
  isHollow({1,2,4,9, 0,0,0,3,4,5}) returns false
  isHollow({1,2, 0,0, 3,4}) returns false

private static int isHollow(int[] array) {
    int length = array.length;
    int startCount = 0;
    int endCount = 0;
    int zeroCount = 0;
    int nonZeroCount = 0;

    if (array[0] == 0 || array[length - 1] == 0) return 0;

    for (int i = 0; i < length; i++) {
        if (array[i] != 0) {
            startCount++;
        } else {
            break;
        }
    }
    for (int i = 0; i < length; i++) {
        if (array[i] == 0) {
            zeroCount++;
        } else {
            nonZeroCount++;
        }
    }

    for (int i = length - 1; i >= 0; i--) {
        if (array[i] != 0) {
            endCount++;
        } else {
            break;
        }
    }

    if (startCount == endCount && (startCount + endCount) == nonZeroCount && zeroCount >= 3) {
        return 1;
    }
    return 0;
}


texts:
I am a beginner in python. I found this problem in the book Automate the Boring Stuff with Python. How can I improve this program using latest version of python.

def generateCollatzSequence(number):
    print(str(number) + " ")

    while number != 1:
        if number % 2 == 0:
            number = number / 2
            print(str(number) + " ")

        elif number % 2 == 1:
            number = (3 * number) + 1
            print(str(number) + " ")

#print("Enter number: ")
inputNumber = int(input("Enter number: "))
generateCollatzSequence(inputNumber)


texts:
I wrote a function for drawing a table for data that comes from file:

import data_manager
import os

table = data_manager.get_table_from_file('games.csv')

len_of_longest_name = 0
i = 0
while i < len(table):
    if len_of_longest_name < len(table[i][1]):
        len_of_longest_name = len(table[i][1])
    i += 1

i = 0
len_of_longest_studio = 0
while i < len(table):
    if len_of_longest_studio < len(table[i][2]):
        len_of_longest_studio = len(table[i][2])
    i += 1
print("/", 6 * "-", "|", (len_of_longest_name - 2) * "-", "|", (len_of_longest_studio - 2) * "-", "|", "---", "\\")

# constructing string

i = 0
while i < len(table):
    string = '|'
    string += table[i][0] + '|'
    if len(table[i][1]) < len_of_longest_name:
        spaces = (len_of_longest_name - len(table[i][1])) * ' '
        string += table[i][1] + spaces + '|'
    else:
        string += table[i][1] + '|'
    if len(table[i][2]) < len_of_longest_studio:
        spaces = (len_of_longest_studio - len(table[i][2])) * ' '
        string += table[i][2] + spaces + '|'
    else:
        string += table[i][2] + '|'
    string += table[i][3] + '|'
    if len(table[i][4]) < 2:
        string += table[i][4] + ' |'
    else:
        string += table[i][4] + '|'
    if i < len(table) - 1:
        print(string)
        print("|", 6 * "-", "|", (len_of_longest_name - 2) * "-", "|", (len_of_longest_studio - 2) * "-", "|", "---", "|")
    else:
        print(string)
    i += 1
print("\\", 6 * "-", "|", (len_of_longest_name - 2) * "-", "|", (len_of_longest_studio - 2) * "-", "|", "---", "/")

The code works as I want but I think there's a better (shorter) method to do the same. Could you show me the method?

The output looks like this:


texts: Checking whether a list is sorted, ascending or descending

texts:
What is the best way to conditionally use an operator? All 3 methods seemed acceptable to me, and the last 2 better.

If you're curious: I've got a list which is unsorted, and many other lists which may or may not contain a smaller selection of sorted indices referencing the unsorted list. Processed data is being identified as lists which contain sorted references.

I've tried an anonymous function...

if reverse:
    list_is_sorted = lambda unsorted, indices:    \
                     all(unsorted[indices[i]] >=  \
                         unsorted[indices[i + 1]] \
                         for i in xrange(len(indices) - 1)))
else:
    list_is_sorted = lambda unsorted, indices:    \
                     all(unsorted[indices[i]] <=  \
                         unsorted[indices[i + 1]] \
                         for i in xrange(len(indices) - 1)))
list_is_sorted()

And an evaluated expression and...

if reverse:
    my_operator = '>='
else:
    my_operator = '<='
eval('all(unsorted[indices[i]] %s  \
          unsorted[indices[i + 1]] \
          for i in xrange(len(indices) - 1))' % my_operator)

Assigning an operator like this:

import operator
if reverse:
    my_operator = lambda x, y: operator.ge(x, y)
else:
    my_operator = lambda x, y: operator.le(x, y)
all(my_operator(unsorted[indices[i]], unsorted[indices[i + 1]]) \
    for i in xrange(len(indices) - 1)))


texts: Mapping & Sorting Randomly Generated Numbers

texts:
Below is the assignment I was given and the coding is what I have came up with. I would appreciate criticism on how I did and on ways to have gone differently about it.

  You want to number your random list numbers, so use an iterator to put the list numbers into a map (but keep the list).  The key will be the number the random number was generated in starting at 1 (ex. 1, 2, 3, etc., since these are not just index numbers).  The value will be the random number.  Use an iterator to print the two fields lined up on the right with field widths in two columns with the numbers labeled with centered column headings of Key and Value.

  Since the list is easier to work with, lets work with the list to perform some calculations.  You will sort the numbers in your list. Then use iterators, algorithms, and list functions (not the user's input variable) to find the sum, mean (average), median (middle value - find the size and move up half way), range (difference between highest and lowest), and a random number from a random spot from your list of random number (get a random number (in the proper range) with  rand() and move up that many spots in your list).  Then print the labeled values (with the mean to three decimal places).

  Now, use your iterator to put the now sorted list numbers back into the map (which will change the original map's order).  The key will still be numbers starting at 1.  The value will now be the random number in their sorted order.  Again, use an iterator to print the two fields lined up on the right with field widths in two columns with the numbers labeled with column headings of Key and Value.

#include <bits/stdc++.h>
using namespace std;

int main() {

    cout << "Enter the length of list: ";
    int n;
    cin >> n;

    std::vector<int> v(n);

    cout << "The random generated numbers are: \n";

    for (int i = 0; i < n; i++) {
        int x = rand() % 151;
        cout << std::setw(10);
        cout << i << " ";
        cout << std::setw(10);
        cout << x << endl;
        v[i] = x;
    }
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += v[i];

    cout << "The sum: " << sum << endl;
    cout << "The mean: " << sum / n*1.0 << endl;

    sort(v.begin(), v.end());
    cout << "The median: " << v[n / 2] << endl;

    return 0;
}


texts:
Here is my code for making an Hour Glass pattern with odd or even input using Python.  I think I could make it simpler.

Here's the output example:

And then, here is my code:

def evenGlassHour(target):
 jsp=1
 jtop=target
 jbot=2
 jbotspace=int(target/2)
 eventarget=int(target/2)
 temp=""
 for i in range(eventarget):
     for j in range(i):
         temp+=" "
     for jsp in range(jtop):
         temp+="@"
     jtop-=2
     temp+="\n"
 for i in range(eventarget-1):
     for j in range(jbotspace-2):
         temp+=" "
     for j in range(jbot+2):
         temp+="@"
     jbot+=2
     jbotspace-=1
     temp+="\n"

 print(temp)

def oddGlassHour(target):
 jsp=1
 jtop=target
 jbot=1
 jbotspace=int(target/2)
 oddtarget=int(target/2)
 temp=""
 for i in range(oddtarget):
     for j in range(i):
         temp+=" "
     for jsp in range(jtop):
         temp+="@"
     jtop-=2
     temp+="\n"
 for i in range(oddtarget+1):
     for j in range(jbotspace):
         temp+=" "
     for j in range(jbot):
         temp+="@"
     jbot+=2
     jbotspace-=1
     temp+="\n"

 print(temp)

target=int(input("Input : "))

if(target%2==0):
 evenGlassHour(target)
else:
 oddGlassHour(target)

And this is the result from my code:

 Input : 6
 @@@@@@
  @@@@
   @@
  @@@@
 @@@@@@

 Input : 7
 @@@@@@@
  @@@@@
   @@@
    @
   @@@
  @@@@@
 @@@@@@@


texts: Changing php.ini with code in a LEMP stack on Debian systems

texts:
This is how I establish a Debian LEMP and use code to change php.ini directives, as part of php-fpm.

Please review the way I change php.ini. I believe my approach here is bad because I edit a conf file directly instead overriding somewhere.

apt-get upgrade nginx mysql-server php-fpm php-mysql php-mbstring php-mcrypt -y
sed -i "s/post_max_size = .M/post_max_size = 200M/ ; s/upload_max_filesize = .M/upload_max_filesize = 200M/" /etc/php/*/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" /etc/php/*/fpm/php.ini


texts: csview: A tiny utility to view csv files

texts:
Seeing a csv in table form is nicer then viewing it as row text, for example the csv from Calculate food company sales for the year (with headers added by me) looks much nicer in this table form than in plain-text:

    Kind
 Brand
 Sales in 2014
 Sales in 2015

    Cereal
Magic Balls
2200
2344

    Cereal
Kaptain Krunch
3300
3123

    Cereal
Coco Bongo
1800
2100

    Cereal
Sugar Munch
4355
6500

    Cereal
Oats n Barley
3299
5400

    Sugar Candy
Pop Rocks
546
982

    Sugar Candy
Lollipop
1233
1544

    Sugar Candy
Gingerbud
2344
2211

    Sugar Candy
Respur
1245
2211

    Chocolate
Coco Jam
3322
4300

    Chocolate
Larkspur
1600
2200

    Chocolate
Mighty Milk
1234
2235

    Chocolate
Almond Berry
998
1233

    Condiments
Peanut Butter
3500
3902

    Condiments
Hot Sauce
1234
1560

    Condiments
Jelly
346
544

    Condiments
Spread
2334
5644

To view a .csv file, I just translate it into HTML and call the browser on it.

The code is short because the task is simple, but I feel like it could be written better:

"""
This utility shows a csv file in table format
by translating it to html and calling the browser on the newly created file.

The html file is not deleted after being viewed
and has name `original_file.split('.')[0] + '.html'`

Example usage:
  python3 csview.py example.csv
"""
import webbrowser
import sys

def csv_to_html(csv):
    START = '''
\n\n'''
    END = '''

'''

    lines = [line for line in csv.split("\n") if line]

    html_lines = ["" + lines[0].replace(',', '	\n') + '	'] +\
                 ["" + line.replace(',', '	\n') for line in lines[1:]]
    body = '
\n' + '\n
\n\n
\n'.join(html_lines)
    return START + body + END

if __name__ == "__main__":
    html_filename = sys.argv[1].split('.')[0] + '.html'
    with open(html_filename, "w+") as out_file:
        with open(sys.argv[1]) as in_file:
            out_file.write(csv_to_html(in_file.read()))
    webbrowser.open(html_filename)


texts:
Following is the graph I used to create adj list.

The code should follow all the best practices of C++ 14 and stl.

map is used instead of vector to keep label.

Any suggestions for better implementation are welcome.
.h

#pragma once

#include <iostream>
#include <vector>
#include <list>
#include <unordered_map>
#include <algorithm>

using std::unordered_map;
using std::list;
using std::pair;
using std::cout;
using std::endl;
using std::make_pair;
using std::for_each;

class AdjList
{
private:

    typedef pair<int, char> edge;
    unordered_map<char , list <edge> > adjList;

public:
    void createGraph();
    void printGraph();
    void test();
};

.cpp

#include "AdjList.h"

void AdjList::createGraph()
{
    list<edge> A;
    A.push_back(make_pair(3, 'B'));
    A.push_back(make_pair(2, 'E'));

    list<edge> B; //B points nowhere

    list<edge> C;
    C.push_back(make_pair(1, 'A'));

    list<edge> D;
    D.push_back(make_pair(4, 'C'));

    list<edge> E;
    E.push_back(make_pair(4, 'D'));

    adjList['A'] = A;
    adjList['B'] = B;
    adjList['C'] = C;
    adjList['D'] = D;
    adjList['E'] = E;

}

void AdjList::printGraph()
{
    for each (auto elem in adjList)
    {
        cout << elem.first << " -> ";

        for_each(elem.second.begin(), elem.second.end(), [](auto val) {

            cout << val.second << "(" << val.first << "), ";

        });

        cout << endl;
    }
}

void AdjList::test()
{
    createGraph();
    printGraph();
}

test() is called from main to test.

Output:

  A -> B(3), E(2),

  B ->

  C -> A(1),

  D -> C(4),

  E -> D(4),