texts:
This is my first class. I've been working a while on it, some functions are future ideas and are right now just bare bones and intended to be worked on later. I'm really looking for a good review of what I have so far, I've never done this before so hopefully I'm off to a decent start. I tried to log my errors as well and handle them by skipping but annotating which values are trouble. Also first time using *args in my functions.

class Matrix():

    def __init__(self, height, width):
        self.rows = [[0]*width for i in range(height)]
        self.height = height
        self.width = width

    def __str__(self):
        s = "\n" + "\n".join([str(i) for i in [rows for rows in self.rows] ]) + "\n"
        return s

    def __repr__(self):
        return (f'{self.__class__.__name__} ({self.height!r} , {self.width!r})')

    def len(self):
        return self.height * self.width

    def __add__(self, matrix2):
        return

    def __mul__(self, matrix2):
        return

    def remove(self, item):
        return

    def fill_matrix(self, fill_list):
        index = 0
        for i in range(len(self.rows)):
            try:
                for j in range(len(self.rows[i])):
                    self.rows[i][j] = fill_list[index]
                    index += 1
            except IndexError:
                print (f"Matrix not filled \nMatrix fill stopped at: row {i}, Column {j}")
                break
        return fill_list[index:]

    def add_value(self, *args):
        log = []
        for arg in args:
           try:
               arg_size = len(arg)
           except TypeError:
               log.append(f'Parameter must be sequence, skipped: {arg}')
               continue

           try:
               if arg_size == 3:
                       self.rows[arg[0]] [arg[1]] = arg[2]
               else:
                   log.append(f'Parameter has too little or too much data, skipped: {arg}')
           except  IndexError:
               log.append(f'Location parameters are out of range, skipped: {arg}')
           except TypeError:
               log.append(f'Location indicies must contain integral types, skipped: {arg}')

        return log

myMat = Matrix(5,5)
overflow = myMat.fill_matrix([i for i in range(26)])

print(myMat)

Errors =  myMat.add_value((-1,3,500), (0,0,3),(51,5, 7), (1, 2, 667), [3,4,676], (1), (1,"a", 1), (1,1, "£"))
print(myMat)


texts:
Could someone tell me their opinion on my leaderboard system?

library

#!/usr/bin/env python3
def write_score(score, name, scores, filename, splitter=','):
    """writes a score with a name to a file, in a specified format"""
    score_tuple = (score,name)
    scores.append(score_tuple)
    with open(filename,'w') as f:
        for s in scores:
            f.write(str(s[0]) + splitter + s[1] + '\n')
        f.close()

def read_scores(filename, splitter=','):
    """reads scores and names from a file, and returns a list of each"""
    with open(filename) as f:
        raw_scores = f.read().strip().split('\n')
        f.close()

    scores = []
    names = []

    for score in raw_scores:
        score_split = score.split(splitter)
        scores.append(int(score_split[0]))
        names.append(score_split[1])
    return scores, names

def sort_scores(scores, names,reverse_bool=True):
    """sorts the scores from greatest to least and returns in a list of tuples format"""
    zipped = sorted(list(zip(scores,names)), reverse=reverse_bool)
    return zipped

def print_scores(score_list, seperator=' ', top_amount=5):
    """prints the number of leaderboard scores stated"""
    for score_tuple in score_list[:top_amount]:
        print(str(score_tuple[0]) + seperator + score_tuple[1])

def has_better_score(score, scores, leaderboard_len=5):
    """returns if the score should be written to a file"""
    if (len(scores) > leaderboard_len and score >= scores[leaderboard_len - 1][0]) or len(scores) <= leaderboard_len:
        return True
    return False

leaderboard.txt

123 | jimmy
16 | bill
12 | Pete
10 | Jim2
10 | Jim
6 | henry is cool
5 | Bob
3 | Jane
223 | billy

Small Program

import leaderlib as ll
if __name__ == '__main__':
    try:
        while True:
            scores, names = ll.read_scores('leaderboard.txt',' | ')
            sorted_scores = ll.sort_scores(scores, names)
            ll.print_scores(sorted_scores, ' = ', 5)

            new_name = input('Name > ')
            new_score = int(input('Score > '))
            if ll.has_better_score(new_score, sorted_scores, 5):
                ll.write_score(new_score, new_name, sorted_scores, 'leaderboard.txt', ' | ')
            else:
                print('not on the leaderboard...')
            print('\n\n\n')
    except KeyboardInterrupt:
        exit()


texts:
char* join(char** strings, size_t num_strings, char* seperator)
{
    int cache = 0;
    int count = 0;
    for(int i = 0; i < num_strings; i++){
        cache += strlen(strings[i]);
    }
    char * joined = malloc((cache + num_strings * strlen(seperator) + 1) * sizeof(char));
    for(int j = 0; j < num_strings; j++){ //big loop
        if(j != 0){
            int j = 0;
            while(j < strlen(seperator)){ //inserting seperators
                joined[count] = seperator[j];
                count++;
                j++;
            }
        }
        int insert_string = 0;
        while( insert_string < strlen(strings[j])){ //inserting strings
            joined[count] = strings[j][insert_string];
            insert_string++;
            count++;
        }
    }
    joined[count] = 0; //Zero Termination
    return joined;
}

I wrote this join() function, which creates a string from num_strings with specified separator, for example *. Is there a way to make this more concise?  Also is the termination correct?


texts:
I'm wondering what the best approach might be.

One approach is to chain cachedPromise and "regular", thus, if cachedPromise fails, we call a regular one (and caching results).

The second is to have a wrapper function, something like a decorator in python, and being able to wrap any promise-returning function when needed.

Here's code illustrating both approaches:

// this is for node.js environment
// in modern browsers Promise is already implemented
// as a standard feature
var Promise = require('bluebird');

var cachedPromise = {
    _cache: {},
    get: function(key) {
        var isCached = this._cache.hasOwnProperty(key);
        var data = this._cache[key];
        return new Promise(function(resolve, reject) {
            isCached ? resolve(data) : reject();
        });
    },
    store: function(key, value) {
        this._cache[key] = value;
    }
}

var WrappedPromise = function(promiseFunc) {
    var cache = {};
    return function(key) {
        if (cache.hasOwnProperty(key)) {
            return Promise.cast(cache[key]);
        } else {
            var promise = promiseFunc(key);
            return promise.then(function(data) {
                cache[key] = data;
                return promise;
            });
        }
    }
}

var mockRequestPromise = function(name){
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve({'name': name});
        }, 1000);
    });
}

var requestChained = function(name) {
    return cachedPromise.get(name).catch(function() {
        var promise = mockRequestPromise(name);
        return promise.then(function(data) {
                   cachedPromise.store(name, data);
                   return promise;
               })
    });
}

var requestWrapped = WrappedPromise(mockRequestPromise);

If you have any considerations regarding this issue, I will be much obliged.


texts:
I updated my class with more functionality, but I kind if feel like it's a mess or that it can at least be improved by a bit readability, efficiency and/or DRY wise.

Anybody who could see if that can be done?

Any other suggestions are also welcome.

class Validator
{
    private $errors = [];
    private $rules  = [];

    public function getErrors($rulename = null)
    {
        if ($rulename) {
            return isset($this->errors[$rulename]) ? $this->errors[$rulename] : null;
        }

        return $this->errors;
    }

    # rules will be checked against in order as specified
    public function setRule($name, Array $rules, $required = true)
    {
        if (!array_key_exists($name, $this->rules)) {
            foreach ($rules as $rule) {
                if (!$rule instanceof IRule) {
                    throw new Exception('Array must only contain instances of IRule.');
                }
            }

            $this->rules[$name]['rules'] = $rules;

            if ($required === true) {
                $this->rules[$name]['required'] = 'Must not be null or empty.';
            } elseif ($required === false) {
                $this->rules[$name]['required'] = false;
            } else {
                $this->rules[$name]['required'] = (String) $required;
            }
        } else {
            throw new Exception(sprintf('Rule %s already exists.', $name));
        }
    }

    public function validate($rulename, $input)
    {
        if ($this->rules[$rulename]['required']) {
            if (empty($input)) {
                $this->errors[$rulename][] = $this->rules[$rulename]['required'];
            }

            foreach ($this->rules[$rulename]['rules'] as $rule) {
                try {
                    $rule->check($input);
                } catch (Exception $e) {
                    $this->errors[$rulename][] = $e->getMessage();
                }
            }

            if (isset($this->errors[$rulename])) {
                return false;
            }
        } elseif (!empty($input)) {
            foreach ($this->rules[$rulename]['rules'] as $rule) {
                try {
                    $rule->check($input);
                } catch (Exception $e) {
                    $this->errors[$rulename][] = $e->getMessage();
                }
            }

            if (isset($this->errors[$rulename])) {
                return false;
            }
        }

        return true;
    }

    public function dump()
    {
        print_r($this->rules);
    }
}


texts:
So I'm making a program that is a serial port wedge. In other words I want it to listen to a serial port. If data comes in, wait a given amount of time, then play a sound and finally send the data out.

All of those things have a abstract class associated with it. I'm thinking that I might eventually want to monitor USB:HID things so I made a IInput class which has abstract methods of Open, Close, ToXmlString, ParseXmlString and has a event of DataAvailable. I extend that class with ComPortInput.

This is the question of it: Do I subscribe to my data event in the Open method, then unsubscribe in close? Or should I just have it in the initializer. I have a GUI that a user can change any of the 4 elements on this wedge at any time. But I'm not sure what would be the cleanest way of doing this. I'm thinking that the GUI would always create a new instance of my ComPortInput class. Part of me wants to force that GUI to have another method like Check Input. which in this case if the COM port was invalid or busy it would return false. Then instead of making a ComPortInput I would then want a NoInputInput class (for when I don't want to port forward) If I did it this way then I could get rid of my null checks on the serial port (Much desired) but is that too tricky? (as in too hard to read?) I'm thinking that if i do that I could put in my constructor of ComPortInput to Assert not null of the SerialPort. To me this looks better

public ComPortInput(SerialPort sp, int delay) : base(delay)
{
    if (sp == null)
        throw new System.ArgumentNullException("Serial port can not be null");

    LibraryTrace.Start("ComPortInput", delay);

    serialPort = sp;
    serialPort.DataReceived += sp_DataReceived;

    LibraryTrace.End("ComportInput");
}
~ComPortInput()
{
    serialPort.Dispose();
}

My thoughts on this way, though, is that it might be hard to have a abstract CheckValidity... Hmm just thought as I was typing what if I put a params object[] args for CheckValidity and just have the comport i could try a few things and return true or false. Then if I ever decide to accept other types of input I could do something similar (such as if it was USB:HID I could accept the PID/VID) What do you guys think? Am I on the right track?


texts:
This is a program which you can get the next "different", i.e. elements in A[] can be identical, permutation at each call. I've written a C++ program for the same purpose in 2018, but I found it unreadable, readability = NULL, so here is a new one.
Any critical comment and answer will be welcomed :)
next_different_permutation.c:
#include <stdbool.h>

void pswap(int *l, int *r) {
    int temp = *l;
    *l = *r;
    *r = temp;
}

void reverse(int A[], int l, int r) {
    int size = (r-l+1);
    for (int i = 0; i < size/2; ++i)
        pswap(&A[l+i], &A[r-i]);
}

bool next_different_permutation(int A[], int l, int r) {
    if (r-l+1 <= 1)
        return false;                           // return false when [l,r] is(or back to) an increasing interval.
    int j = -1;                           // j will point to the highest peak of the interval [i,r].
    for (struct{int i, j;}                           // this for will find the first increasing [i,j] from r to l.
        z = {r-1, r}; z.j != l; --z.i, j=--z.j)
        if (A[z.i] < A[z.j]) {                           // find the maximal decreasing interval [j,r].
            int k = r;                           // after swap (i, k), interval [j,r] remains decreasing.
            while (!(A[z.i] < A[k]))                           // find the first A[k] where A[k] > A[z.i].
                --k;
            pswap(&A[z.i], &A[k]);
            reverse(A, z.j, r);
            return true;                           // when success we go, the z.i, z.j will be initialized in next call.
        }
    reverse(A, j, r);                           // Recover the A[l]>=A[l+1]>=...>=A[r]-array back to the increasing order.
    return false;
}

Usage:
#define ARRAY_SIZE 3
int A[ARRAY_SIZE]

void next_different_permutation_test_distinct() {
    for (int i = 0; i < ARRAY_SIZE; ++i)
        A[i] = i+1;
    do {
        print_array(A, ARRAY_SIZE, PRINT_WIDTH);
    } while (next_different_permutation(A, 0, ARRAY_SIZE-1));
    // the order will back to A[l]<A[l+1]<...<A[r]
}

void next_different_permutation_test_some_identical() {
    for (int i = 0; i < ARRAY_SIZE; ++i)
        A[i] = rand()%RAND_MOD;
    do {
        print_array(A, ARRAY_SIZE, PRINT_WIDTH);
    } while (next_different_permutation(A, 0, ARRAY_SIZE-1));
}


texts: HackerRank Algorithm Challenge 1: Insertion sort

texts:
This is my solution for HackerRank's first "Algorithm Challenge, Insertion Sort Part 1". The challenge is to sort the array from least to greatest, the input being an array in sorted order, except for the last entity, i.e. {2, 3, 4, 5, 6, 7, 8, 9, 1}

It works fine, but it's definitely not an optimal solution. Could anybody provide any insights on how I should look at it so as to optimize it? This is for learning purposes, so I can apply the same concepts to future code.

   static void insertionSort(int[] ar) {
          int i, j;
          int inserted = 0;
          i = ar[ar.length-1];

          for (j = ar.length-2; j > -1; j--){
              if (ar[j] > i){
                  ar[j+1] = ar[j];
                  printArray(ar);
              } else if (ar[j] <= i){
                  ar[j+1] = i;
                  inserted = 1;
                  break;
              }
          }

          if(inserted == 0){
              ar[0] = i;
          }

          printArray(ar);
   }

This is the rest of the code, but it's preset and is already available:

 static void printArray(int[] ar) {
     for(int n: ar){
        System.out.print(n+" ");
     }
       System.out.println("");
  }

  public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       int[] ar = new int[n];
       for(int i=0;i<n;i++){
          ar[i]=in.nextInt();
       }
       insertionSort(ar);
   }


texts:
I'm making a very basic user system, and this is what I have so far:

<?php

/* The class for constructing any user's information
 */

    class User {

        protected $userId, $email, $userGroup;

        protected function getEmail() {
            return $this->email;
        }

        protected function getUserId() {
            return $this->userId;
        }

        public function __construct($userId, $email, $emailGroup) {
            $this->userId = $userId;
            $this->email = $email;
            $this->userGroup = $emailGroup;
        }

        // Method for checking whether user can view a specific page
        public function canViewPage($pageId) {
            $userGroup = new UserGroup($this->userGroup);
            if($userGroup->canViewPage($pageId)) {
                return true;
            }else{
                return false;
            }
        }

        // Method for checking permissions
        public function hasPermissions($alias) {
            /* alias is the name of the permissions. ie can-book
            * create usergroup object based on current user's usergroup */

            $userGroup = new UserGroup($this->userGroup);
            if($userGroup->hasPermissions($alias)) {
                return true;
            }else{
                return false;
            }
        }

    }

    class UserMapper {
        // database connection
        private $db;

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

        public function findByUserId ($userId) {
            $userObject = new User();
            $q = $this->db->prepare("SELECT userId, email, userGroup FROM user WHERE userId = :userId");
            $q->bindValue(":userId", $id);
            $q->setFetchMode( PDO::FETCH_INTO, $userObject);
            $q->execute();
            $q->fetch(PDO::FETCH_INTO);
            return $userObject;

        }
    }
?>

Then on my main script, I include the user.class.php (as shown above) and do this:

<?php
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
    $getUser = new UserMapper($dbh);
    $user = $getUser->findByUserId(41);
    echo $user->getEmail();
?>

Is this all correct? Or have I misunderstood? Is there a way of simplifying this? I've tried to keep the code as simple as possible.  Am I correct for having getters (getEmail, etc.) as well as methods such as canViewPage, within the user class?

Also, should it be:

$userGroup = new UserGroup($this->userGroup);

or should I do something like this again?

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(PDO::ATTR_PERSISTENT => true));
        $getUserGroup = new UserGroupMapper($dbh);
        $userGroup = $getUserGroupMapper->findByUserId($this->userGroup);

Is there a simpler way?


texts: Calculating pi by adding areas of thin rectangles

texts:
I wrote a small program for fun to try to prove Pi by taking a certain precision and radius and using it to calculate the area of the circle. My method should be giving me an area that is just slightly larger than the actual area of the circle, approaching the actual area as the precision gets smaller.

The funny thing is that this area should always be larger than the actual area, but when I set the precision to be less than 1.0e-9L (say 1.0e-10L), I get a result smaller than 3.141592654. Can you look at my code and tell me where I messed up if anywhere?

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <future>

using namespace std;

namespace Settings{
    register constexpr long double precision = 1.0e-10L;
    register constexpr long double radius = 1.0e0L;
}

// Make the math cleaner
inline long double SQUARE(register long double Val) { return Val * Val; }

// Main calculate function
long double get_Area(register long double radius = Settings::radius);

int main()
{
    time_t benchmark = time(0);
    register long double area = get_Area();
    register long double pi = area / SQUARE(Settings::radius);

    cout << "Pi should be around:" << setprecision(50) << pi << endl << endl;
    cout << "It took " << time(0) - benchmark << " to complete the calculation" << endl;
    system("pause");

    return 0;
}

long double get_Area(register long double radius)
{
    register long double area = 0.0e0L, max_Area = SQUARE(radius);

    // Allow for threading
    register auto part = [](register long double start_point, register long double end_point, register long double m_Area){
        register long double area = 0.0L, y = 0.0L;

        for ( register long double x = start_point; x < end_point; x += Settings::precision ){
            y = sqrt(m_Area - SQUARE(x));
            area += y * Settings::precision;
        }

        return area;
    };

    // Divide the problem into eight parts since my pc has eight threads
    future<long double> A1 = async(launch::async, part,                   0.0L, (1.0L / 8.0L) * radius, max_Area);
    future<long double> A2 = async(launch::async, part, (1.0L / 8.0L) * radius, (2.0L / 8.0L) * radius, max_Area);
    future<long double> A3 = async(launch::async, part, (2.0L / 8.0L) * radius, (3.0L / 8.0L) * radius, max_Area);
    future<long double> A4 = async(launch::async, part, (3.0L / 8.0L) * radius, (4.0L / 8.0L) * radius, max_Area);
    future<long double> A5 = async(launch::async, part, (4.0L / 8.0L) * radius, (5.0L / 8.0L) * radius, max_Area);
    future<long double> A6 = async(launch::async, part, (5.0L / 8.0L) * radius, (6.0L / 8.0L) * radius, max_Area);
    future<long double> A7 = async(launch::async, part, (6.0L / 8.0L) * radius, (7.0L / 8.0L) * radius, max_Area);
    future<long double> A8 = async(launch::async, part, (7.0L / 8.0L) * radius,                 radius, max_Area);

    area = A1.get() + A2.get() + A3.get() + A4.get() + A5.get() + A6.get() + A7.get() + A8.get();

    return area * 4.0L;
}


texts: C++ heap CPS: Continuation Passing Style with Recursion

texts:
I am willing to see how to write readable and efficient continuations on the heap in c++. I am not quite satisfied.

The following is just an exercise: it is coded for fun. I post the code here because I am not really satisfied. I am looking for suggestions.
I picked up the simplest algorithm: measuring the length of a list and I wrote few recursive implementations. The plain one is len().

Then I wrote lenK() i.e. len() in CPS. This is quite straightforward, I think this code is fine. Isn't it?

When it comes to Kontinuations on the heap, I had to write the continuation K as a class (fine) but I had to use virtuality to let the compiler understand what I wanted (if I use templates the compiler cannot understand that my program eventually terminates and for each call create a new type). I have the strong impression that my solution is not elegant and is not efficient. Is there a better way to implement CPS on the heap?

#include <iostream>
#include <functional>
#include <memory>

struct List;
bool isEnd(const List& l);
double getHead(const List& l);
List* getTail(const List& l);

//////////////////////////////////////////////////////////////////////////////

int len(const List& l, int val=0){
    if (isEnd(l))
        return val;
      return len(*getTail(l),
                 ++val);
}

//////////////////////////////////////////////////////////////////////////////

double lenK(const List& l, std::function<int(int)> k){
    if (isEnd(l))
        return k(0);
    return lenK(*getTail(l), [k](int a){return k(a+1);} );
}

//////////////////////////////////////////////////////////////////////////////
class IntInt{
   public:
      virtual ~IntInt()=default;
      virtual int operator()(int)=0;
};

using funcPtr = std::unique_ptr<IntInt>;

class IntID : public IntInt{
   public:
      int operator()(int a){ return a;}
};

class K : public IntInt{
   public:
      K( funcPtr&& k) : k_(std::move(k)){}
      int operator()(int a){ return (*k_)(a+1);}
   private:
      funcPtr k_;
};
//////////////////////////////////////////////////////////////////////////////

double lenKheap(const List& l, funcPtr&& k){
    if (isEnd(l))
        return (*k)(0);
    List* myTail = getTail(l);
    funcPtr myK = std::make_unique<K>(std::move(k));
    // Without tail call optimization we run out of stack space as for lenK and len.
    return lenKheap(*myTail,
                    std::move(myK));
}

void checkLenFunctions(const List& myL){

    std::cout << len(myL) << std::endl;

    auto intId = [](int x){return x;};
    std::cout << lenK(myL, intId ) << std::endl;

    std::cout << lenKheap(myL, std::make_unique<IntID>()) << std::endl;
}

If you want to experiment without bothering with the task of implementing the List class and functions, I provide you with an implementation of it. But this is not part of the review:

struct List{
    List(double d, List* l) : d_(d), l_(l){}
    List() : d_(0.0), l_(this){}
    double d_;
    List* l_;
};

bool isEnd(const List& l){
    if (l.l_ == &l)
        return true;
    return false;
}
double getHead(const List& l){
    if (!isEnd(l))
        return l.d_;
    throw "EndOfList";
}
List* getTail(const List& l){
    if (!isEnd(l))
        return l.l_;
    throw "EndOfList";
}

int main(){
    List myL;
    List myL1 = List(1.0, &myL);
    List myL2 = List(2.0, &myL1);
    List myL3 = List(3.0, &myL2);
    List myL4 = List(4.0, &myL3);

    checkLenFunctions(myL4);

    return 0;
}


texts:
Weekly Employee Report Generator PowerShell Script
Description
This script is used for generating a Markdown template file for weekly employee reports. In Settings.cfg file you can define the name and title of the employee, report title and report folder name, starting hour and working time, and the names of the days of the week, to cover all the languages. When you run the script it will first try to find existing file for current week and open it in the the default Markdown editor, and if it does not exist it will create one for current week, and then it will open newly created file.
Settings Example
EmployeeName = John Doe
EmployeeTitle = System Administrator
ReortFolderName = Weekly Reports
ReportTitle = Weekly report
StartingTime = 09:00
WorkingTime = 8
MondayName = Monday
TuesdayName = Tuesday
WednesdayName = Wednesday
ThursdayName = Thursday
FridayName = Friday
SaturdayName = Saturday
SundayName = Sunday

PowerShell Script
$Date = Get-Date
$DayDecrement = 0
$Settings = Get-Content -Path "$PSScriptRoot\Settings.cfg" | ConvertFrom-StringData

switch ($Date.DayOfWeek) {
    'Monday' {
        $DayDecrement = 0
    }
    'Tuesday' {
        $DayDecrement = -1
    }
    'Wednesday' {
        $DayDecrement = -2
    }
    'Thursday' {
        $DayDecrement = -3
    }
    'Friday' {
        $DayDecrement = -4
    }
    'Saturday' {
        $DayDecrement = -5
    }
    'Sunday' {
        $DayDecrement = -6
    }
}
$MondayDate = $Date.AddDays($DayDecrement).ToString("dd.MM.yyyy.")
$SundayDate = $Date.AddDays($DayDecrement + 6).ToString("dd.MM.yyyy.")
$Settings = Get-Content -Path "$PSScriptRoot\Settings.cfg" | ConvertFrom-StringData

$ReportTitle = $Settings.ReportTitle + " $MondayDate - $SundayDate"
$Documents = [environment]::getfolderpath("mydocuments")
$ReportFolderName = $Settings.ReortFolderName
$ReportFullName = "$Documents\$ReportFolderName\$ReportTitle" + "md"

if (-not (Test-Path -Path $ReportFullName)) {
    $DaysOfWeek = @(
        $Settings.MondayName
        $Settings.TuesdayName
        $Settings.WednesdayName
        $Settings.ThursdayName
        $Settings.FridayName
        $Settings.SaturdayName
        $Settings.SundayName
    )

    $Employee = "> " + $Settings.EmployeeName + " - " + $Settings.EmployeeTitle

    $ReportBody = "# $ReportTitle`n`n$Employee`n`n------`n`n"
    foreach ($Day in $DaysOfWeek) {
        $ReportBody += "## $Day " + $Date.AddDays($DayDecrement).ToString("dd.MM.yyyy.")
        $DayDecrement ++
        $ReportBody += "`n`n------`n`n"
        for ($Hour = 0; $Hour -lt $Settings.WorkingTime; $Hour ++) {
            $Start = ([datetime]::ParseExact($Settings.StartingTime, "HH:mm", $null)).AddHours($Hour).ToString("HH:mm")
            $End = ([datetime]::ParseExact($Settings.StartingTime, "HH:mm", $null)).AddHours($Hour + 1).ToString("HH:mm")
            $ReportBody += "### $Start - $End`n`n- `n`n"
        }
        $ReportBody += "------`n`n"
    }

    New-Item -Path $ReportFullName -Force
    Add-Content -Path $ReportFullName -Value $ReportBody
}

Start-Process $ReportFullName

Generated Report Example
Question
I am planning on creating a GUI for editing Settings.cfg file, and to have the option to select work days so not the whole week is created, just the days you work on. I would like your opinions on my little project and how to improve it.


texts: Rule of Three for non-circular singly linked list

texts:
Here is a non-circular, singly linked list data structure (with no headers). This is done using a pre-C++11 standard. Is there a more efficient way/shorter way of writing this (especially the copy assignment operator which contains duplicate code from the copy constructor and clear() method)?

template<typename T>
class linked_list{
    class node {
    public:
        T data;
        node *next;

        node() :
            data(T()),
            next(NULL)
            { }

        node(const T &data, node *next) :
            data(T(data)),
            next(next)
            { }
    }; // class node
protected:
    node *mFirst;
    size_t mSize;
public:
    /** Empty Constructor */
    linked_list():
        mFirst(NULL),
        mSize(0) {}

    /** Array Constructor */
    linked_list(T* others, size_t n) {
        for (int i = 0; i < n; i++) {
            mFirst = new node(*others, mFirst);
            others++;
        }
    }

    /** Copy Constructor*/
    linked_list(const linked_list &other):
        mFirst(NULL),
        mSize(other.mSize)
        {
        node *p = other.mFirst;
        while (p != NULL) {
            mFirst = new node(p->data, mFirst);
            p = p->next;
        }
        if (mFirst != NULL){
            node *q, *prev;
            p = mFirst;
            q = p->next;
            p->next = NULL;
            prev = p;
            p = q;
            for (int i = 1; i < mSize; i++) {
                q = p->next;
                p->next = prev;
                prev = p;
                p = q;
            }
            mFirst = prev;
        }
    }

    /** Destructor */
    ~linked_list(){
        clear();
    }

    /** Copy Assignment Operator*/
    linked_list &operator=(const linked_list &other) {
        if (this != &other) {
            // allocate and copy from other to r
            mSize = other.mSize;
            node *p = other.mFirst, *r = NULL;
            while (p != NULL) {
                r = new node(p->data, r);
                p = p->next;
            }
            if (r != NULL){
                node *q, *prev;
                p = r;
                q = p->next;
                p->next = NULL;
                prev = p;
                p = q;
                for (int i = 1; i < mSize; i++) {
                    q = p->next;
                    p->next = prev;
                    prev = p;
                    p = q;
                }
                r = prev;
            }

            // deallocate current
            node *q;
            p = mFirst;
            while(p != NULL) {
                q = p->next;
                delete p;
                p = q;
            }

            // replace
            mFirst = r;
        }
        return *this;
    }

    void clear() {
        node *q, *p = mFirst;
        while(p != NULL) {
            q = p->next;
            delete p;
            p = q;
        }
        mFirst = NULL;
        mSize = 0;
    }


texts:
Before you can do any sort of card game, you must first write some code to define your deck of cards.

One thing I've noticed in looking at some of Apple's Swift interfaces is that they very much so like to use extensions.  This is probably good.  In the big picture long term, it's a really good way of allowing ever-expanding classes while actually keeping individual source code files quite tidy.

I also wanted to try something out with Swift enums and iterating through every value in them...

The Basics

enum Suit

enum Suit: String {
    case Clubs = "Clubs"
    case Diamonds = "Diamonds"
    case Hearts = "Hearts"
    case Spades = "Spades"
    case __EXHAUST = ""
}

enum Rank

enum Rank: String {
    case Ace = "Ace"
    case Two = "Two"
    case Three = "Three"
    case Four = "Four"
    case Five = "Five"
    case Six = "Six"
    case Seven = "Seven"
    case Eight = "Eight"
    case Nine = "Nine"
    case Ten = "Ten"
    case Jack = "Jack"
    case Queen = "Queen"
    case King = "King"
    case __EXHAUST = ""
}

struct Card

struct Card {
    let suit: Suit
    let rank: Rank
}

The Extensions

Suit: FowardIndexType

extension Suit: ForwardIndexType {
    func successor() -> Suit {
        switch self {
        case .Clubs: return .Diamonds
        case .Diamonds: return .Hearts
        case .Hearts: return .Spades
        case .Spades: return .__EXHAUST
        case .__EXHAUST: return .__EXHAUST
        }
    }
}

Rank: ForwardIndexType

extension Rank: ForwardIndexType {
    func successor() -> Rank {
        switch self {
        case .Ace: return .Two
        case .Two: return .Three
        case .Three: return .Four
        case .Four: return .Five
        case .Five: return .Six
        case .Six: return .Seven
        case .Seven: return .Eight
        case .Eight: return .Nine
        case .Nine: return .Ten
        case .Ten: return .Jack
        case .Jack: return .Queen
        case .Queen: return .King
        case .King: return .__EXHAUST
        case .__EXHAUST: return .__EXHAUST
        }
    }
}

Card: Printable, DebugPrintable

extension Card: Printable, DebugPrintable {
    var description: String {
        get {
            return self.rank.rawValue + " of " + self.suit.rawValue
        }
    }
    var debugDescription: String {
        get {
            return self.rank.rawValue + " of " + self.suit.rawValue
        }
    }
}

Array

extension Array {
    mutating func shuffle() {
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            swap(&self[i], &self[j])
        }
    }
}

Int

extension Int {
    func repeat(function: () -> ()) {
        for _ in 1...self {
            function()
        }
    }
}

Example Usage

Constructing the Deck

var deck: [Card] = Array<Card>()
for suit in Suit.Clubs...Suit.Spades {
    for rank in Rank.Ace...Rank.King {
        let newCard = Card(suit: suit, rank: rank)
        deck.append(newCard)
    }
}

Shuffling the Deck

3.repeat({deck.shuffle()})

Printing the entire Deck

for card in deck {
    println(card)
}

Conforming to the ForwardIndexType protocol is what allows the ... and ..< syntax for loops.  The unfortunate downside is that for an enum, we must include one extra value in order to actually iterate through the entire enumeration, per this StackOverflow question.  This seems like a bug that will hopefully be fixed.

I think this is a good foundation for a deck of playing cards in Swift.

Including Jokers might prove difficult.  I'm not sure whether it could be done very from this structure.  And working with extensions means that as we add additional functionality to a card or the enums, we can do it cleanly in new source code files without mucking around with this file.


texts:
On some video from CPPcon, some one said that there should be variadic overload for operator+ as it can solve allocation when there are multiple + with the containers like std::string. So I just gave it a try, but I am not seeing a major performance boost. Are there any other ways to improve this?

#include <string>
#include <string_view>
#include <string.h>

using string_type = std::string_view;

inline std::string::size_type total_len(const string_type& str) {
    return str.length();
}

template<typename... String>
inline std::string::size_type total_len(const string_type& str, const String... strs) {
    return str.length() + total_len(strs...);
}

inline void append(size_t l, std::string& str1, const string_type& str2) {
    memcpy(str1.data() + l, str2.data(), str2.size());
    l += str2.size();
}

template<typename... String>
void append(size_t l, std::string& str1, const string_type& str2, String... strs) {
    void * p1 = str1.data() + l;
    const void * p2 = str2.data();
    memcpy(p1,p2, str2.size());
    l += str2.size();
    append(l, str1, strs...);
}

template<typename... String>
std::string StrCat(const string_type& str1, const string_type& str2, const String... strs) {
    std::string answer(total_len(str1, str2, strs...), 0);
    append(0, answer, str1, str2, strs...);
    return answer;
}

int main()
{
  StrCat("Hello, ","name","!\n");
}


texts: Anatomy of a string-reversal program with less coupling

texts:
I'm currently trying to improve my C understanding. Would you mind telling me if there are good/bad things that I did here? (I implemented a function to reverse a string in place).

For example things I feel uncomfortable with:

I forwarded pointers to a buffer so that I could loosen the coupling of different parts of the program, is it a bad thing to forward many times a pointer?
I would like to set the functions I extracted to a header, somehow but I don't know if this is stupid or not

Here is what I came up with so far with my main.c file (the actual implementation of reverse_str is not what I want to focus on so I did not include it):

#include "reverse_str.h"

const long unsigned MAX_BUFFER_SIZE = 100;

void remove_new_line(char *buffer, const unsigned length)
{
        long unsigned buffer_last_index = length - 1;

        if (buffer[buffer_last_index] == '\n')
                buffer[buffer_last_index] = '\0';
}

char * get_buffer()
{
        char *buffer = malloc(MAX_BUFFER_SIZE * sizeof (*buffer));
        return buffer;
}

unsigned read_input(char *buffer, const long unsigned size)
{
        fgets(buffer, size, stdin);
        return strlen(buffer);
}

char * get_input()
{
        char *buffer = get_buffer();
        const unsigned length = read_input(buffer, MAX_BUFFER_SIZE);

        remove_new_line(buffer, length);

        return buffer;
}

char * ask_for_input()
{
        printf("Enter a string, whatever\n");
        char *buffer = get_input();

        return buffer;
}

void manipulate(char * buffer)
{
        reverse_str(buffer);
}

void show_result(char *buffer)
{
        printf("After: %s\n", buffer);
}

// I know it is a bit redundant, but it keeps symetry with ask_for_input
void clear(char *buffer)
{
        free(buffer);
}

int main()
{
        char *buffer = ask_for_input();
        manipulate(buffer);
        show_result(buffer);
        clear(buffer);

        return 0;
}


texts: Find largest connected cells of value 1 or greater

texts:
My goal is to find the largest connected "cell" of 1's in a matrix.

My approach has been to search the surrounding area of a cell that is not on a border and then if it hasn't been visited, and has a value of 1, increment the group.  I am absolutely sure that there are better, more recursive solutions out there, but I would greatly appreciate if someone would at least point me in the right direction.  I feel as though I'm getting closer.  Algorithms are still very new to me.

Example test case

[[0, 0, 1, 1],
 [0, 0, 1, 0],
 [0, 0, 1, 1],
 [0, 0, 0, 0]];

Answer is 5 because there are 5 connected 1s of the largest group

    <html>
<head>
</head>
<body>
<script type="text/javascript">
test = [[0, 0, 1, 1],
        [0, 0, 1, 0],
        [0, 0, 1, 1],
        [0, 0, 0, 0]];

// Answer should be 5

var Cell = function(x, y, val) {
    this.row = x;
    this.col = y;
    this.val = val;
    this.visited = false;
}

Cell.prototype.visit = function() {
    this.visited = true;
}

var CellMatrix = function(arr) {
    inst = [];
    for(i=0; i < arr[0].length; i++) {
        for(k=0; k < arr.length; k++) {
            inst.push(new Cell(i, k, arr[i][k]));
        }
    }
    this.length = inst.length;
    //console.log(inst);
    return inst;
}

function find(row, col, cells) {
    for(i=0; i < cells.length; i++) {
        cell = cells[i];
        if((cell.row == row) && (cell.col == col) && (!cell.visited))
            return cell;
        else {
            continue;
        }
    }
    return false;
}

function findLargestGrouping(cells, rows, cols) {
    console.log(cells);
    groups = []
    for(i=0; i < cells.length; i++) {
        cell = cells[i];
        // not a border cell
        if( (cell.row > 0) && (cell.row < (rows - 1))  )
        {
            if( (cell.col > 0) && (cell.col < (cols - 1)) ) {
                // console.log("cell at row " + cell.row + " col " + cell.col + " and val " + cell.val);
                groups.push(searchNeighbors(cell, cells));
            }
        }
        else { continue; }
    }
    return Math.max.apply(Math, groups);
}

function searchNeighbors(cell, matrix) {
    neighbors = [[cell.row - 1, cell.col - 1], // top left
                [cell.row - 1, cell.col], // top center
                [cell.row - 1, cell.col + 1], // top right
                [cell.row, cell.col - 1], // center left
                [cell.row, cell.col + 1], // center right
                [cell.row + 1, cell.col - 1], // bottom left
                [cell.row + 1, cell.col], // bottom center
                [cell.row + 1, cell.col + 1]];

    results = 0;
    for(i=0; i < neighbors.length; i++) {
        _row = neighbors[i][0];
        _col = neighbors[i][1];
        _cell = find(_row, _col, matrix);
        console.log("cell at row " + cell.row + " col " + cell.col + " and val " + cell.val);
        if(_cell) {
            if(!_cell.visited) {
                _cell.visit();
                results += 1;
            }
        }
    }
    return results;
}

window.onload = function() {
    matrix = new CellMatrix(test);
    results = findLargestGrouping(matrix, 4, 4);
    console.log(results);
}
</script>
</body>
</html>


texts:
I wrote a doge meme generator in racket some time ago, mainly as a joke, and I would like some criticism about the general style and what could be improved.

Here is how the program output looks :

plainDoge.jpg refers to a plain image for the doge meme (700 * 525)

#lang racket
(require racket/gui
         racket/draw)

;keywords definitions
;TODO random capitalisation for first letter
(define doge-keywords
  '("such" "much" "so" "very"))
(define wow
  "Wow")

(define user-keywords
  '())
(define colors
  '("red" "magenta" "blue" "green" "yellow" "cyan" "white"))

(define (random-member my-list)
  ;gives a random member from a list
  (car
   (shuffle my-list)))

(define (make-sentence keyword)
  ;make a sentence
  (string-append
   (random-member doge-keywords)
   " "
   keyword))

;TODO add max count
(define (make-sentences my-list)
  ;make a list of sentences
  (if (null? my-list)
      ;return a list containing this message
      '()
      ;else
      (cons wow
            (map make-sentence
                 (shuffle my-list)))))

;frame
(define (create-parent-frame)
  (new frame%
       [label "racket-doge"]
       [width 700]
       [height 600]
       [style (list 'no-resize-border)]))

;canvas
(define (main-canvas parent-frame to-draw)
  (new canvas% [parent parent-frame]
       [min-height 500]
       [paint-callback
        (lambda (canvas dc)
          (send dc draw-bitmap to-draw 0 0))]))

;horiz panel
(define (create-horiz-panel parent-frame)
  (new horizontal-panel% [parent parent-frame]))

;font management
(define (set-font my-dc)
  (send my-dc set-font
        (make-font #:size (+ 20 (random 5))
                   #:family 'decorative
                   #:face "Comic Sans MS"
                   #:weight 'bold)))

;draw on doge
(define (draw-text-with-keywords kwd my-dc)
  ;draw the text on my-dc
  (for-each
   (lambda (kw)
     (set-font my-dc)
     (send my-dc set-text-foreground (random-member colors))
     (send my-dc draw-text kw (random 700) (random 500)))
   (make-sentences kwd)))

;text edit
(define (create-user-entries horiz-panel)
  (new text-field%
       ;[enabled #f]
       [label "user-keywords :"]
       [init-value (string-join user-keywords ", ")]
       [parent horiz-panel]))

(define (parse-user-input user-entries)
  (string-split (send user-entries get-value) ", "))

;buttons
(define (gen-again-but horiz-panel user-entries my-dc p-frame)
  (new button% [label "Wow !"]
       ;generate again
       [parent horiz-panel]
       ;[enabled #f]
       [callback
        (lambda (b e)
          (send my-dc draw-bitmap (read-bitmap "plainDoge.jpg") 0 0)
          (draw-text-with-keywords
           (parse-user-input user-entries) my-dc)
          (send p-frame refresh))]))

(define (save-but doge horiz-panel)
  (new button% [label "Save"]
       ;Save the bitmap to a file
       [parent horiz-panel]
       [callback
        (lambda (b e)
          (send doge save-file
                "./generated_doge.png"
                'png))]))

;let's make the GUI and run the whole program
(define (make-gui)
  (let
      ([p-frame (create-parent-frame)])
    (let
        ([doge (read-bitmap "plainDoge.jpg")])
      (main-canvas p-frame doge)
      (let
          ([horiz-panel (create-horiz-panel p-frame)])
        ;let's create a drawing context and draw on it
        (let
            ([my-dc (new bitmap-dc% [bitmap doge])])
          (let
              ([user-entries (create-user-entries horiz-panel)])
            (draw-text-with-keywords
             (parse-user-input user-entries) my-dc)
            (gen-again-but horiz-panel user-entries my-dc p-frame)
            (save-but doge horiz-panel)))))
    (send p-frame show #t)))

(make-gui)


texts: Killing a tunnel and establishing a tunnel through SSH

texts:
I have two functions right now:

TUNNEL_COMMAND = "ssh -L 27017:localhost:27017 username@ip -f -N"

def kill_tunnel():
    p = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
        if TUNNEL_COMMAND in line:
            pid = int(line.split()[1])
            print "killing pid", pid
            os.kill(pid, signal.SIGKILL)

def connect_tunnel():
    subprocess.Popen(TUNNEL_COMMAND)

connect_tunnel() establishes the connection, which I am ok with, but kill_tunnel() looks very ugly. Is there a better way to find the PID of a process based off the command?


texts:
I have created a common C file for a basic client server. It works fine on my Linux setup. Please provide your comments/suggestions on how the code can be optimized/enhanced.

After compiling we need to give parameters "s" or "c" to executable from the command line to run it as a server or client respectively. The client connects to the server at the default IP of 192.168.7.2.

#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"
#include"pthread.h"
#include"netdb.h"
#include"errno.h"
#include"signal.h"

#define PORT 4444
#define BUF_SIZE 2000
#define CLADDR_LEN 100
#define MAX_ALLOWED_CONNECTIONS 5
char * whoAmI;
int sockfd, len, ret, newsockfd;

void * receiveMessage(void * socket) {
 int sockfd, ret;
 char buffer[BUF_SIZE];
 sockfd = (int) socket;
 memset(buffer, 0, BUF_SIZE);
 for (;;) {
  memset(buffer, 0, BUF_SIZE);
  ret = recvfrom(sockfd, buffer, BUF_SIZE, 0, NULL, NULL);
  if (ret < 0) {
   printf("Error receiving data!\n");
  } else {
   if(*whoAmI == "c") {
        printf("server: ");
    }
    else {
        printf("client: ");
    }
   fputs(buffer, stdout);
   //printf("\n");
  }
 }
}

void  INThandler(int sig)
{
    printf("Closig all sockets");
    close(newsockfd);
    close(sockfd);
    exit(0);
}
void main(int argc, char**argv) {
 struct sockaddr_in addr, cl_addr;

 char buffer[BUF_SIZE];
 pid_t childpid;
 char clientAddr[CLADDR_LEN];
 pthread_t rThread;

 /* install signal handler to close sockets on ctrl+c from user */
 signal(SIGINT, INThandler);

if (argc < 2) {
  printf("Needs arguments: 0==Server; 1==client\n");
  exit(1);
}

whoAmI = argv[1];

printf("whoami = %s \n", whoAmI);
 sockfd = socket(AF_INET, SOCK_STREAM, 0);
 if (sockfd < 0) {
  printf("Error creating socket!\n");
  exit(1);
 }
 printf("Socket created...\n");

 memset(&addr, 0, sizeof(addr));

// start of server
if ((strcmp(whoAmI, "s") == 0) ) {
 addr.sin_family = AF_INET;
 addr.sin_addr.s_addr = INADDR_ANY;
 addr.sin_port = PORT;

/* Naming the socket */
 //strcpy(addr.sun_path,"server_socket");

     ret = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
     if (ret < 0) {
      printf("%s",strerror(errno));
      printf("Error binding!\n");
      exit(1);
     }
     printf("Binding done...\n");

     printf("Waiting for a connection...\n");
     listen(sockfd, MAX_ALLOWED_CONNECTIONS);

     len = sizeof(cl_addr);
     newsockfd = accept(sockfd, (struct sockaddr *) &cl_addr, &len);
     if (newsockfd < 0) {
      printf("Error accepting connection!\n");
      exit(1);
     }

     inet_ntop(AF_INET, &(cl_addr.sin_addr), clientAddr, CLADDR_LEN);
     printf("Connection accepted from %s...\n", clientAddr);
    }//end of server
    else {
//start of client
    addr.sin_family = AF_INET;
     addr.sin_addr.s_addr = inet_addr("192.168.7.2");
     addr.sin_port = PORT;
           ret = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));
         if (ret < 0) {
          printf("Error connecting to the server!\n");
          exit(1);
         }
         printf("Connected to the server...\n");
    //very important step
    newsockfd = sockfd;
// end of client
    }

 memset(buffer, 0, BUF_SIZE);
 printf("Enter your messages one by one and press return key!\n");

 //creating a new thread for receiving messages from the client
 ret = pthread_create(&rThread, NULL, receiveMessage, (void *) newsockfd);
 if (ret) {
  printf("ERROR: Return Code from pthread_create() is %d\n", ret);
  exit(1);
 }

 while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
  ret = sendto(newsockfd, buffer, BUF_SIZE, 0, (struct sockaddr *) &cl_addr, len);
  if (ret < 0) {
   printf("Error sending data!\n");
   exit(1);
  }
 }

 close(newsockfd);
 close(sockfd);

 pthread_exit(NULL);
 return;
}


texts: Limit HTTP request rate for spray/akka-http

texts:
I want to limit the request rate in a spray/akka-http route. I'm not an expert with both scala and spray/akka but learning. So I came up with the following custom directive:

  trait RequestRateLimiter[T] {
    def check(ctx: RequestContext, realIp: Option[RemoteAddress], proxiedIp: Option[RemoteAddress]) : RequestRateResult[T]
  }

  sealed trait RequestRateResult[T]
  case class Pass[T](result: T) extends RequestRateResult[T]
  case class Block[T](rejection: Rejection) extends RequestRateResult[T]

  def limit[T](requestRateLimiter: RequestRateLimiter[T]): Directive1[T] = {
    def remoteAddress: Directive1[Option[RemoteAddress]] = optionalHeaderValuePF { case `Remote-Address`(address) ⇒ address }
    def xForwardedFor: Directive1[Option[RemoteAddress]] = optionalHeaderValuePF { case `X-Forwarded-For`(Seq(address, _*)) ⇒ address }
    extract(identity) flatMap { ctx =>
      remoteAddress.flatMap { realIp =>
        xForwardedFor.flatMap { proxiedIp =>
          requestRateLimiter.check(ctx, realIp, proxiedIp) match {
            case Pass(result)     => provide(result)
            case Block(rejection) => reject(rejection)
          }
        }
      }
    }
  }

The custom directive takes an instance of an RequestRateLimiter which keeps track of the request rate based on the RequestContext and RemoteAddress. The RequestRateLimiter then decides if the request should be passed or blocked.
I'm not quiet happy with the RequestRateLimiter because it's too generic. It can be anything that either provides something or rejects.

I also posted a Gist (feel free to share, use and improve).

What do you think of the directive? Anything that could be improved?


texts:
I have a simple task.

Array of people object comes in, up to a thousand.
Need to iterate over it, and create a custom payload for external service.

I have created a working solution, but I would like to see if I am totally off course, and what changes should I make.
I have reduced non-important details from the code (errors, and similar), so it might not work. But the point is to show how it works, and hopefully get some advice.
User struct {
   Name        string  `json:"name"`
   Lastname    string  `json:"lastname"`
 }

func HandleLambda(event events.SQSEvent) {
 var userRecords []map[string]interface{}

 for idx := range event.Records {
  record := event.Records[idx]
  ev, err := e.NewEvent(record.Body)

  if err != nil {
    continue
  }

  u, err := repository.NewUser(ev)

  if err != nil {
        continue
  }

  user := make(map[string]interface{})
  user["1"] = u.Name
  user["2"] = u.Lastname

  userRecords = append(userRecords, user)
  }

 uJSON, _ := json.Marshal(userRecords)
 // I send this to external service

 }

External service is using numbers as keys, that's why I need "1" and "2". I do not have control over it.
That's the way it works.


texts:
I am currently learning how to use PDcurses in VC++ 2015 Community, and I noticed that menu.h is not implemented so I decided to extend the library for my own use (feel free to just copy the code if it's what you were looking for).

The only question I have is: was my use of namespaces (both named and unnamed) correct? And is this a good approach as I do not see a reason to make a singleton or something involving classes?

NOTE: I did research the web about dividing functions into namespaces like I did in the code, but I can't find if it's the correct approach for this specific task.

menu.h

#ifndef MENU_H
#define MENU_H

#include "curses.h"

namespace menu
{
    int renderMenu(WINDOW* menu_win, const char* title, const char* items[], int n_items);
    WINDOW* menuWin(const char* title, const char* items[], int n_items, int y, int x);
    void initMenu();
}

#endif

menu.cpp

#include "menu.h"
#include <string>

namespace
{
    void renderItems(WINDOW* win, int selected, const char* items[], int n_items)
    {
        for (int index{}; index < n_items; ++index) {
            if (index == selected) {
                wattron(win, A_BOLD);
                mvwprintw(win, 3 + index, 2, items[index]);
                wattroff(win, A_BOLD);
            }
            else
                mvwprintw(win, 3 + index, 2, items[index]);
        }

        wrefresh(win);
    }

    int navigateMenu(WINDOW* win, const char* items[], int n_items)
    {
        int selected{};
        renderItems(win, selected, items, n_items);

        keypad(win, TRUE);
        while (true) {
            switch (wgetch(win)) {
              case KEY_DOWN:
                    if (selected < n_items - 1)
                        ++selected;
                    else
                        selected = 0;
                  break;
              case KEY_UP:
                    if (selected > 0)
                        --selected;
                    else
                        selected = n_items - 1;
                  break;
                case 10: /*enter key*/
                    return selected;
                    break;
            }

            renderItems(win, selected, items, n_items);
        }
    }
}

int menu::renderMenu(WINDOW* menu_win, const char* title, const char* items[], int n_items)
{
    std::string separator{ '+' + std::string(getmaxx(menu_win) - 2, '-') + '+' };
    mvwprintw(menu_win, 1, (getmaxx(menu_win) - strlen(title)) / 2, title);
    wborder(menu_win, '|', '|', '-', '-', '+', '+', '+', '+');
    mvwprintw(menu_win, 2, 0, separator.c_str());
    wrefresh(menu_win);

    return navigateMenu(menu_win, items, n_items);
}

WINDOW * menu::menuWin(const char* title, const char* items[], int n_items, int y, int x)
{
    int width{};
    for (int index{}; index < n_items; ++index)
        if (width < static_cast<int>(strlen(items[index])))
            width = strlen(items[index]);
    if (width < static_cast<int>(strlen(title)))
        width = strlen(title);
    width += 4;

    int height{ 4 + n_items };

    return newwin(height, width, y, x);
}

void menu::initMenu()
{
    curs_set(FALSE);
    noecho();
    cbreak();
    refresh();
}

source.cpp <--example of use

#include "menu.h"
#include <string>

int main()
{
    const char* items[]{
        {"option a"},
        {"option b"},
        {"option c"}
    };

    const char* title{ "Main Menu" };

    initscr();
    menu::initMenu();

    WINDOW* menu = menu::menuWin(title, items, 3, 2, 2);
    int choice = menu::renderMenu(menu, title, items, 3);
    /*use choice to preform an action*/

    mvprintw(0, 0, "%s was chosen.", items[choice]);
    refresh();

    getch();
    endwin();
    return 0;
}


texts: Analyzing records of London Underground outages

texts:
You have a file that describes historic data of the London Underground showing dates when stations have been unavailable. The file contains these fields, separated by a pipe character:

  Date: Format of this is mm-dd-yyyy.
  Line: Each line has a unique name. For example, “Northern”.
  Station: Each station has a unique name. For example, “Angel”.
  Notes: Describes the outage

  Here is an example of one entry in the file, which shows that the Northern Line was not operating at Bank on 23 August 2019 due to a function at London Bridge.

08-23-2019|Northern|Bank |No service on Bank branch due to birthday booking at London Bridge station.

  Write a script that solves the following problems:

  Display each station that was affected by an outage on 10 July 2019.
  Between 10 July 2017 and 14 November 2017, which lines had outages and what was the number of stations affected?

I was able to complete both problems but the review of the work said it was done poorly.

# I created a test input file in the same folder as a proxy input.

import datetime  # import built in datetime module for problem 2
with open('input.txt') as file:  # read the input file into a list of lines
    file_input = file.read().splitlines()

# split the file input on the pipe
LonUndOutages = []
for var in file_input:
    LonUndOutages.append(var.split("|"))

# creating empty lists for the answers for Problem 2
Prob1Output = ""
LonUndStations = []
LonUndLines = []

# solving problem 1 and prep for the answers for Problem 2
print("Problem 1:")
for line in LonUndOutages:
    if line[0] == "07-10-2019":
        Prob1Output = Prob1Output + line[2] + "was affected by an outage on July 10, 2019\n"
    line[0] = datetime.datetime.strptime(line[0], '%m-%d-%Y')  # convert the date in line[0] to a datetime object
    if datetime.datetime(2017,7,10) < line[0] < datetime.datetime(2017,11,14):
        # the above line checks if line[0] is in the time range july 10 2017 to nov 14, 2017
        if line[1] not in LonUndLines:  # ensures LonUndLines doesnt have duplicates
            LonUndLines.append(line[1])  # adds each line that had an outage to a list
        if line[2] not in LonUndStations:  # ensures LonUndStations doesnt have duplicates
            LonUndStations.append(line[2])  # adds each station that had an outage to a list

if not Prob1Output:
    print("There were no stations affected by an outage on July 10, 2019")
else:
    print(Prob1Output)
print()
print("Problem 2:")
print("The following lines had outages:")
print(*LonUndLines, sep=', ')
print("During the period between July 10, 2017 and November 15, 2017 there were " + str(len(LonUndStations))
      + " station(s) affected")


texts:
I have written this code and I wonder if there is a better way to do absolutely any of it. Also, if there is any way to optimise it or if there is a problem please also tell me preferably with fixed code as I am still sort of a beginner. It is one of my first school projects and I would like to show my teacher that I really now Python. What it is supposed to do is take an input which is a YouTube and give a response based on the input. I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to impliment it that would be great! I am also thinking of using a switch statement (which might be the same as a dictionary lookup) that I know from my experience with JavaScript. The code is below:

import random

def test():
    youtuber = input('Enter your favourite youtuber:  ')
    youtuber = youtuber.lower()
    favouriteYoutuber = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']

    if youtuber == 'dr. phil':
        print('You are an awesome lad!')
    elif youtuber == 'james charles':
        print('Errmm. Ok...')
    elif youtuber == 'bloamz':
        print('Ok then.')
    elif youtuber == 'ali a':
        print('I mean. Thats old but ok...')
    elif youtuber == 'jacksepticeye':
        print('Thats kinda cool')
    elif youtuber == 'will smith':
        print('Thats different. I rate that')
    elif youtuber == 'jack black':
        print('you have good taste')
    elif youtuber == 'jack white':
        print('I like him as well')
    elif youtuber == 'dr. mike':
        print('so you like learning then')
    elif youtuber == 'morgz':
        print('I mean just leave now')
    else:
        print('I dont know that one. Ill check them out')

    print('my favourite youtuber is ' + random.choice(favouriteYoutuber))

def try_again():
    again = True
    while again:
        test()
        while True:
            try:
                print("")
                print("Would you like to try again?")
                maybe = input("Y/N ")
                maybe = maybe.lower()
            except ValueError:
                print("That is not a valid option")
                print("")
                continue
            if maybe in ('y','n'):
                if maybe == "n":
                    print("")
                    again = False
                elif maybe == "y":
                    print("")
                break

    else:
        print("Thank you for using this app!")
try_again()


texts: A C program to find all factorions using a hash table

texts:
The objective of this program is to find all factorions, which are numbers equal to the sum of the factorials of their digits.

I am seeking suggestions on how to improve the performance of this code, as well as stylistic advice.

#include <stdio.h>
#include <stdlib.h>
#define base 10 //We are working in base 10
#define upper_bound 2540160 //This is 7 x 9! because a factorion can have at most seven digits.
//If it has d digits, it must satisfy the inequality 10^{d-1} < n <= 9!d, which isn't satisfied above d = 8
#define expected_no_of_answers 5 //I chose 5 somewhat arbitrarily. I knew beforehand there are only four answers in base 10

//Function prototype
void create_hash_table(int[]);
void get_fact_digit_sum(int[],int[]);
void display_answers(int[]);

int main()
{
    int hash_table_fact[base], answers[expected_no_of_answers]; //Creating a hash table where t[n] -> n!

    create_hash_table(hash_table_fact);

    get_fact_digit_sum(answers,hash_table_fact);

    display_answers(answers);

    return 0;
}

void create_hash_table(int hash_table_fact[])
{
    int i = 1, fact = 1;
    hash_table_fact[0] = 1; //0! = 1

    for(i = 1; i < base; i++)
    {
        fact = fact*i;
        hash_table_fact[i] = fact;
    }
}

void get_fact_digit_sum(int answers[], int hash_table_fact[])
{
    int answerCount = 0, i = 1, temp, sum;

    //Combing through the search space to search for factorions
    for(i = 1; i <= upper_bound; i++)
    {
        temp = i;
        sum = 0;
        //Getting the sum of the factorials of the digits
        while(temp != 0)
        {
            sum = sum + hash_table_fact[ (temp%base) ];
            temp = temp/base;
        }
        if(sum == i)
        {
            answers[answerCount++] = i;
        }
    }

    //Placing a 0 at the end to mark the end of the array
    answers[answerCount] = 0;
}

void display_answers(int answers[])
{
    int i;

    for(i = 0; answers[i] != 0; i++)
    {
        printf("%d\t",answers[i]);
    }
}


texts: UICollectionViewCell's content layout misbehaves when UICollectionView scrolls to the top of the screen

texts:
UICollectionViewCell's content misbehaves ,
the layout animates,
when UICollectionView scrolls to the top of the screen.

I am asking here, because it looks like an apple's bug.

looks like squeezed in the following gif, the cell's label laid down.

I solved it by

- (void)viewDidLoad {
    [super viewDidLoad];
     // comment the following line
    // self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

I use UIScrollViewContentInsetAdjustmentNever, to avoid the collectionView's content insets.

Like the following image

In order to keep both, I add one line _collectionView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);

Tested on iPhones: iPhone 7 ( 11.4.1 ), iPhone XS Max ( 12.1 )

Any other ideas?


texts: Optimizing a jquery user interface application

texts:
I'm working on a javascript intensive user-interface application. (At least it's intensive for me, it's my first serious javascript project).

I have a few jquery functions going whenever a div is rolled over or mouseout. For example there are some divs which are draggable objects, and so when they are mouseovered, the cursor must look ready to move. But my interface so slow that my boss thinks my code isn't working, when in fact it is, but it's just slow and so the user has to sometimes wait upto 2-3 seconds for the cursor to look as expected, or for a div to look as expected. Just an example. My code is something like below, I can't reproduce it entirely or properly since my company has copyrights on this, so I've written some lines as comments just to give a clear idea of the way I'm doing things. There's more to it, but this is basically what it's like:

$.fn.extend({
    mouseoverBox: function() {
    return this.each(function() {
        var $this = $(this);
                if(!$this.hasClass('ready'))
                {   if($this.hasClass('activated'))
                    {
                        $this.removeClass('activated');
                    }
                    $this.addClass('ready');
                }
                var img_id = $this.children('.theimg').attr('id');
                //someitem.children('somechildren').remove();
                //someitem.append(somemenu div)
                //$this.draggable();
                //$this.resizable();
                if($this.hasClass('unlocked'))
                {
                    $this.draggable( "option", "disabled", false );
                    $this.resizable( "option", "disabled", false );
                }
                $this.bindUnlock();
            });
     }
// end mouseoverBox
});

Now this is just the mouseoverBox function, which is triggered like myBox.mouseoverBox(). on the mouse over event. Then of course this plugin is calling bindUnlock() which has simple operations like changing classes and adding classes to a menu. Also, before any mouseover, there's usually been a mouseout out of another div... so as you can see there's a lot of stuff happening. There aren't usually more than 10 interactive divs on at any one moment though. How can I optimize this kind of code? I haven't given every specific but trust me most of the relevant is pretty much just like this.

I've already gzipped my javascript, css, images and fonts. I also tried minifying using the Yahoo Compressor but it actually bloated one of my files instead of compressing it.


texts: Printing a heartbeat (heart star) animation

texts:
Here is a C program to print a heart star animation using a while loop written by myself.
I've tested it on Ubuntu 18.04 (Bionic Beaver) and Ubuntu 20.04 (Focal Fossa).
To animate it, I print a sequence of heart star patterns in different sizes.
#include <stdio.h>
#include <unistd.h>

int main() {
    int i, j, h, k = 0;

    while (k < 99) {
        /* code */
        h = k % 3;
        printf("\e[1;1H\e[2J");
        printf("\e[?25l");

        i = 0;
        while (i < 3) {
            j = 0;
            while (j < (2 - i) * 2 + h) {
                printf(" ");
                j++;
            }

            j = 0;
            while (j < (i + 2) * 2 - h * 2) {
                printf("* ");
                j++;
            }

            j = 0;
            while (j < (2 - i) * 2 + 1 + h) {
                printf("  ");
                j++;
            }

            j = 0;
            while (j < (i + 2) * 2 - h * 2) {
                printf("* ");
                j++;
            }

            printf("\n");
            i++;
        }
        i = 0;
        while (i < 9) {
            j = 0;
            while (j < i * 2 + h * 2) {
                printf(" ");
                j++;
            }
            j = 0;
            while (j < 17 - i * 2 - h * 4) {
                printf("* ");
                j++;
            }
            printf("\n");
            i++;
        }

        fflush(stdout);
        usleep(200000);
        k++;
    }
}


texts: Checking that data has been created in multiple tables

texts:
I have 4 tables that I want to check for data. When there are Rows in all the tables, I want to print a message for success. When there aren't any rows in any table I print an error (when 1 or more table is missing data), I want to warn (unless they are all missing data).

The following script does exactly what I want but I think it could be done in a clearer, more succinct manner.

USE STG_RM_Connector
GO

DECLARE @tblAttCode sysname, @tblAttSess sysname, @tblStaffServ sysname, @tblStuSer sysname
DECLARE @rowCntAttCode int,  @rowCntAttSess int, @rowCntStaffServ int, @rowCntStuSer int

SET @tblAttSess = 'Attendance Session Pupil Data'
SET @tblAttCode = 'Attendace Code Service Attendace Codes'
SET @tblStaffServ = 'Staff Service Staff Members'
SET @tblStuSer = 'Student Service Pupil Data'

SELECT @rowCntAttCode = SUM(PART.rows)
FROM sys.tables TBL
INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblAttCode
AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

SELECT @rowCntAttSess = SUM(PART.rows)
FROM sys.tables TBL
INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblAttSess
AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

SELECT @rowCntStaffServ = SUM(PART.rows)
FROM sys.tables TBL
INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblStaffServ
AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

SELECT @rowCntStuSer = SUM(PART.rows)
FROM sys.tables TBL
INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id
INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id
AND PART.index_id = IDX.index_id
WHERE TBL.name = @tblStuSer
AND IDX.index_id < 2
GROUP BY TBL.object_id, TBL.name;

IF @rowCntAttCode = 0 AND @rowCntAttSess = 0 AND @rowCntStaffServ = 0 AND @rowCntStuSer = 0
BEGIN
 RAISERROR ('Failed to pull data for all tables', 16, 1)
END
ELSE IF @rowCntAttCode = 0 OR @rowCntAttSess = 0 OR @rowCntStaffServ = 0 OR @rowCntStuSer = 0
    BEGIN
        RAISERROR ('Failed to pull data for one of the RM staging tables', 10, 1)
    END
ELSE
BEGIN
  PRINT 'Successfully pulled data for all RM staging tables'
END
GO


texts: Using an extension method for a small helper task that (ab)uses the fact that the object is not dereferenced

texts:
I've recently got into an habit where I've used extension methods for giving things fluent-like properties - such as the below example or as another example entity.AssertNotNull()

public static class GenericHelper
{
    public static void AssignOrThrowIfNull<T>(this T obj, ref T assignTo, string paramName)
    {
        if (obj == null)
            throw new ArgumentNullException(paramName, "Unallowed null argument of type: " + typeof(T).FullName);
        assignTo = obj;
    }
}

This is then used as follows:

public class SmtpClient

public SmtpServerAddress Server
{
    get { return smtpServer; }
}

private SmtpServerAddress smtpServer;

public SmtpClient(SmtpServerAddress smtpServer)
{
    smtpServer.AssignToOrThrow(ref this.smtpServer, "smtpServer");
}

as opposed to

public SmtpClient(SmtpServerAddress smtpServer)
{
    if(smtpServer == null)
        throw new ArgumentNullException("smtpServer");
}

Do you think this is readable? Is it in any way preferable to regular checks everywhere? The fact that I can't really decide if I like it or not makes me nervous, so I'd like some external input!

UPDATE:

Yes, you made me open my eyes. Hopefully, you will agree with me that the following is a bit more agreeable. I used expressions because I want to include as much information as possible in the exception.

public static class Require
{
    public static void That(Expression<Func<bool>> func)
    {
        if (!func.Compile()())
            throw new ContractException("Contract not fulfilled: " + func.Body, func);
    }
}

Atleast I think this makes it a bit clearer, even though the lambda syntax is not very nice (I don't think smtpServer != null can be inferred to an Expression).

Require.That(() => smtpServer != null);
SmtpServer = smtpServer;

Since I compile the expression each time, there will surely be some performance penalty.


texts: What is better? For-loops or generator expressions (in cases like this)

texts:
Which version of this code is better?

Ver 1.

a = 0
for i in xrange( 1000 ):
    if i % 3 == 0 or i % 5 == 0:
        a += i
print a

Ver 2.

from operator import add
print reduce( add,
              ( i for i in xrange( 1000 )
                if i % 3 == 0 or i % 5 == 0 ) )

Things I like about version one is that it is more readable, but it creates requires a variable. If you had to choose, which one would you argue is better?


texts:
Please review this code.

#include <iostream>
#include <vector>

bool is_prime(int x)
{
    int flag = 1;
    for (int i = 2; i <= x/2; i++)
    {
        if (x % i == 0)
        {
            flag = 0;
            break;
        }
    }
    if (flag == 1)
    {
        return true;
    }
    else if (flag == 0)
    {
        return true;
    }
}

void find_prime_factors(int n, std::vector<int>& vec)
{
    int val = n;
    for (int i = 2; i <= n; i++)
    {
        if (is_prime(i))
        {
            while (val % i == 0 && val != 1)
            {
                vec.push_back(i);
                val = val/i;
            }
            if (val == 1)
            {
                break;
            }
        }
    }
}

int main()
{
    int n;
    std::cout << "Enter number\n";
    std::cin >> n;
    std::vector<int> prime_factors;
    find_prime_factors(n, prime_factors);
    std::cout << "Prime Factors of " << n << ":\n";
    for (int i = 0; i < prime_factors.size(); i++)
    {
        std::cout << prime_factors[i] << " ";
    }
    std::cout << "\n";
}


texts: Converting a list of lists to a list of objects

texts:
I have some code that does what I want - it just doesn't feel correct for being done in JavaScript.

What it does is take data that is like this:

   var data = [['Marker', 'sampleName1', 'sampleName2'],
     ['CCR4', 71.6, 83.4],
     ['CD27', 42.3, 76.2]];

And create a list of objects that looks like this (to use the plot.ly JavaScript library):

[{x:['CCR4', 'CD27'], y:[71.6,42.3], name: 'sampleName1'},
{x:['CCR4', 'CD27'], y:[83.4,76.2], name: 'sampleName2'}]

What I have is this:

var bData = [];
for (var i=0; i < data.length; i++) {
        var row = data[i];
        if (i ==0) {
                //Handle creation of objects
                for (var k = 1; k < row.length; k++) {
                        var obj = {name : row[k], type:'bar', x:[], y:[]};
                        bData.push(obj);
                }
        } else {
                var marker = row[0];
                for (var k=1; k < row.length; k++) {
                        var obj = bData[k -1];
                        obj.x.push(marker);
                        obj.y.push(row[k]);
                }
        }
}

What would be a better, more legible approach to this?


texts: Equality comparison for a surname value object class

texts:
I asked this question yesterday: Entity and Value Object are not part of the Ubiqtious language. Should this stop me from using them?.

I originally decided to introduce a ValueObject class as described here: Generic Value Object Equality, which contained equality methods for all value objects i.e. all Value Objects inherited from ValueObject the value object class. However, this approach was criticised.

Please see the code below:

public sealed class Surname : IEquatable<Surname>
{
    private readonly string _value;
    public Surname(string surname)
    {
        if (surname.Length==0)
            throw new ArgumentException("Invalid value.", "Surname");
        this._value = surname;
    }

    public string Value
    {
        get { return _value; }
    }

    public static bool operator ==(Surname surname1, Surname surname2)
    {
        if (!ReferenceEquals(surname1, null) &&
            ReferenceEquals(surname2, null))
        {
            return false;
        }
        if (ReferenceEquals(surname1, null) &&
             !ReferenceEquals(surname2, null))
        {
            return false;
        }
        return surname1.Equals(surname2);
    }

    public static bool operator !=(Surname surname1, Surname surname2)
    {
        return !(surname1== surname2);
    }

    public bool Equals(Surname other)
    {
        if (other != null)
        {
            return _value == other._value;
        }
        return base.Equals(other);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Surname);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + _value.GetHashCode();
            return hash;
        }
    }
}

It is a DDD Value Object for a Surname.

I have added some methods for equality and:

I would like some feedback on the quality of them.
This question (point one) links to a presentation by Eric Evans where he appears to advise against introducing equality for Entities.  Is it advisable to always compare entities by reference these days?


texts: Python Sum of Pairs Codewars Solution requires optimization

texts:
Sum of Pairs
Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)

sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * entire pair is earlier, and therefore is the correct answer
== [3, 7]

Negative numbers and duplicate numbers can and will appear.

NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

def sum_pairs(ints, s):
    '''
    Params:
        ints: list[int]
        s: int --- sum
    Return
        First two values from left in ints that add up to form sum
    '''
    ints_dict = {k:v for v,k in enumerate(ints)} # O(n)
    earliest_ending_idx = float('inf')
    earliest_pair = None
    for idx, num in enumerate(ints): # O(n)
        if idx >= earliest_ending_idx:
            return earliest_pair
        try:
            second_num_idx = ints_dict[s-num]
            if second_num_idx != idx:
                if max(second_num_idx, idx) < earliest_ending_idx:
                    earliest_ending_idx = max(second_num_idx, idx)
                    earliest_pair = [num, s-num]
        except KeyError:
            # s-num not in dict
            pass
    return earliest_pair

It seems to me that my code is O(n) in time complexity but I can't submit the solution since it took too long to run. Am I mistaken in my analysis and is there a better way to solve this problem?


texts:
For my programming class, we have been tasked with creating a Sudoku solver; the first step of the project was to create a program which would display the game board based on input provided by the user.

import math #To be used later

def board_filler():
    """Creates the sudoku board from user input"""
    board = [[], [], [], [], [], [], [], [], [], [], []]
    for x in enumerate(board):
        #If it is one of the rows that have lines, add them
        if ((x[0] + 1) % 4) == 0:
           for y in range(11):
               board[x[0]].append("-")
        else:
            for y in range(11):
                #If it is a column that has lines in it, add them
                if ((y + 1) % 4) == 0:
                    board[x[0]].append("|")
                else:
                    #Repeat until an inout has been entered
                    z = True
                    while z:
                        z = False
                        if x[0] > 7:
                            xRead = x[0] - 1
                        elif x[0] > 3:
                            xRead = x[0]
                        else:
                            xRead = x[0] + 1
                        if y > 7:
                            yRead = y - 1
                        elif y > 3:
                            yRead = y
                        else:
                            yRead = y + 1
                        number = input("Please enter a number for the square in column %s and in row %s, if there is no number, just hit enter:" %(xRead, yRead))
                        #Trys to make it a number, then checks to see if it is a number 1 to 9
                        try:
                            number = int(number)
                            if number > 9 or number < 1:
                                z = True
                                print("Please enter a number between 1 and 9")
                            else:
                                board[x[0]].append(number)
                        #If it is not a number, check if its empty
                        except (TypeError, ValueError):
                            #If its empty, add a space
                            if len(number) == 0:
                                board[x[0]].append(" ")
                            #If not ask for a number
                            else:
                                z = True
                                print("Please enter a number")
    return board

def board_printer(board):
    """Prints the sudoku board"""
    #Turns board into str to make the .join work
    for x in enumerate(board):
        for y in enumerate(board):
            board[x[0]][y[0]] = str(board[x[0]][y[0]])
    #Prints the board
    for x in enumerate(board):
        print(" ".join(board[x[0]]))

board_printer(board_filler())

A few notes for review:

The board_filler function feels quite bloated.
I don't like the way I implemented xRead and yRead.

How can I improve my code?


texts:
I need to create a byte array with 100 bytes from a string. The length of the string is unknown but it is always less than 100 bytes. So if the string is 65 bytes then i need the array to be 35 zero bytes and then the String bytes to follow.

At the moment i have something like this, that does the job, but maybe something prettier and optimized is possible :)

    String string = "asdf";
    byte[] stringBytes = string.getBytes();
    ByteArrayOutputStream outputStream = outputStream = new ByteArrayOutputStream();
    outputStream.write(new byte[100 - stringBytes.length]);
    outputStream.write(stringBytes);
    byte[] result = outputStream.toByteArray();


texts: Extract html content based on tags, specifically headers

texts:
I want the function to take as an input json file containing html_body with its corresponding url and return list of tuples containing headers and their corresponding url (so could be tuple with one item as a list of the headers).

So far I have been able to do so, but I'm missing some headers and more over, I'm sure that this code can be improved.

Commented out possible extensions for <h2> headers extraction, and a different regex pattern I tried.

A taste of the source:

[["<body class=\" catalog-category-view categorypath-sale-html category-sale\">\n<script type=\"text/javascript\">\n//<![CDATA[\nif (typeof(Varien.searchForm) !== 'undefined') {\n    Varien.searchForm.prototype._selectAutocompleteItem = function(element) {\n        var link = element.down();\n        if (link && link.tagName == 'A') {\n            setLocation(link.href);\n        } else {\n            if (element.title){\n                this.field.value = element.title;\n            }\n            this.form.submit();\n        }\n    };\n    Varien.searchForm.prototype.initAutocomplete = function(url, destinationElement) {\n        new Ajax.Autocompleter(\n            this.field,\n            destinationElement,\n            url,\n            {\n                paramName: this.field.name,\n                method: 'get',\n                minChars: 2,\n                frequency: .3,\n                updateElement: this._selectAutocompleteItem.bind(this),\n                onShow : function(element, update) {\n                    if(!update.style.position || update.style.position=='absolute') {\n                        update.style.position = 'absolute';\n                        Position.clone(element, update, {\n                            setHeight: false,\n                            offsetTop: element.offsetHeight\n                        });\n                    }\n                    Effect.Appear(update,{duration:0});\n                }\n\n            }\n        );\n    };\n    Autocompleter.Base.prototype.markPrevious = function() {\n        if (this.index > 0) {\n            this.index--;\n        } else {\n            this.index = this.entryCount - 1;\n        }\n        var entry = this.getEntry(this.index);\n        if (entry.select('a').length === 0) {\n            this.markPrevious(); // Ignore items that don't have link\n        }\n    };\n    Autocompleter.Base.prototype.markNext = function() {\n        if (this.index < this.entryCount - 1) {\n

Code:

from pandas import DataFrame, Series
from tqdm import tqdm
import html5lib
import re
from bs4 import BeautifulSoup

def get_headers_from_json(local_path):
"""
The function takes a json file with html_body and returns a list of headers.
It parses the headers, based on tags starting with 'h'.
It also parses urls and return them in a tuple: (headers, url)
"""
data = json.loads(open(local_path).read())
pattern = "h1" # | h2 | h3"
# pattern = re.compile("^(?!.*(href)).*^h", re.IGNORECASE)
headers_urls = []
all_headers = []
for x in tqdm(data):
    soup = BeautifulSoup(x[0], 'html.parser')
    html_headers = soup.find_all(re.compile(pattern))
    all_headers.append(html_headers)
    url = x[1]
    tuple_title_url = all_headers, url
    headers_urls.append(tuple_title_url)
return headers_urls

PS - I checked the following links but couldn't find a great solution:
HTML tag encoder
HTML parsing algorithm for extracting <a> tags
Scraping HTML using Beautiful Soup


texts:
def factorial(t,n):
    if n == 1 : return t

    else: x = (t * (n-1))

    n = n-1

    return factorial(x,n)

print factorial(6,6)

I can't seem to figure out a way to just stick to requiring one parameter input while keeping the program small. I also want the function to remain recursive (trying to work on my recursive thinking).

If you have any other cooler simplifications or other fancy methods, please show it off.


texts: Checking if a number is Armstrong number or not

texts:
here is another basic interview question that I had:

Armstrong Numbers

public class ArmstrongCheck {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    if (!in.hasNextInt()) {
      System.out.println("error");
    }

    int number = in.nextInt();

    armstrong(number);
    System.out.println(armstrong(number));
  }

  private static String armstrong(int number) {
    double sum = 0.0;
    int oldNumber = number;

    while (number > 0) {

      int temp = number % 10;
      number = number / 10;
      sum = sum + Math.pow(temp, 3);
    }

    if (sum == oldNumber) {
      return "armstrong number";
    } else {
      return "not armstrong  number";
    }
  }
}

code is working but I want to simplfy/improve it, any suggestions?


texts: Is this a correct knockout ViewModel setup?

texts:
This is my first time using knockout. I'm reading/writing a JSON file with a fair bit of nested data. I had no problem creating the ViewModel to just write to the file, but now that I'm reading the data into my model also, I've had to write a few if/else statements to handle the different cases. Not sure if this is the right way to do it.

I've got a ViewModel with a function to add a new record, and to save the data. The 3 functions above are used for mapping the data.

function Survey(name, panes, tester)
{
  this.name = ko.observable(name);
  this.panes = ko.observableArray([new Pane(panes)]);
  this.tester = ko.observable(tester);
}

function Pane(panes)
{
  //var panesCount = panes.length;
  //console.log(panes[0].type);
  if (panes) {
    this.type = ko.observable(panes[0].type);
    this.head = ko.observable(panes[0].head);
    this.content = ko.observable(panes[0].content);
    this.options = ko.observableArray([new PaneOptions(panes[0].options)]);
  }
  else {
    this.type = ko.observable();
    this.head = ko.observable();
    this.content = ko.observable();
    this.options = ko.observableArray([new PaneOptions()]);
  }
}

function PaneOptions(options)
{
  //console.log(options);
  if (options) {
    this.data = ko.observable(options[0].data);
    this.target = ko.observable(options[0].target);
  }
  else {
    this.data = ko.observable();
    this.target = ko.observable();
  }
}

function SurveyViewModel()
{
  var self = this;
  self.surveys = ko.observableArray([]);

  $.getJSON("create/fetch", function(data) {
    //console.log(data.surveys[0].name);
    if (data) { // check if json file is empty
      for (var i=0; i < data.surveys.length; i++) {
        console.log(i);
        self.surveys.push(new Survey(data.surveys[i].name, data.surveys[i].panes, data.surveys[i].tester))
      }
    }
  });

  self.addSurvey = function ()
  {
    self.surveys.push(new Survey());
  };

  self.saveUserData = function()
  {
    var data_to_send = ko.toJSON(self);
    $.post("create/save", data_to_send, function(data) {
      console.log("Your data has been posted to the server!");
    });
  }

}

var vm = new SurveyViewModel();
ko.applyBindings(vm);

Here you can see the JSON representation:

{
    "surveys": [
        {
            "name": "My First Survey1",
            "panes": [
                {
                    "type": "question1",
                    "head": "Heading Text1",
                    "content": "multichoice1",
                    "options": [
                        {
                            "data": "Time",
                            "target": 2
                        }
                    ]
                }
            ],
            "tester": "default"
        },
        {
            "name": "My Second Survey2",
            "panes": [
                {
                    "type": "response2",
                    "head": "Heading Text2",
                    "content": "multichoice2",
                    "options": [
                        {
                            "data": "Time",
                            "target": 2
                        }
                    ]
                }
            ],
            "tester": "default2"
        },
        {
            "name": "My Third Survey3",
            "panes": [
                {
                    "type": "thanks3",
                    "head": "Heading Text3",
                    "content": "multichoice3",
                    "options": [
                        {
                            "data": "Time",
                            "target": 2
                        }
                    ]
                }
            ],
            "tester": "default3"
        }
    ]
}

Any input is greatly appreciated!


texts:
Below I have coded a simple command system that passes a string to a method and checks if the first word split by (' ') is a key in the registered commands dictionary, if it is, it executes the class that is stored as the dictionary entry's value.

few examles of what is typed for commands

@mycommand hello
:ohnicecommand John
.setamount 10000

CommandHandler.cs:

using System;
using System.Collections.Generic;

namespace Sirius.Base.Game.Habbo.Commands
{
    using Commands;
    using Commands.Habbo;
    using Other.GameClients;

    internal class CommandHandler
    {
        private readonly Dictionary<string, ICommand> _commandsRegistered;

        internal CommandHandler()
        {
            _commandsRegistered = new Dictionary<string, ICommand>();

            RegisterCommands();
        }

        private void RegisterCommands()
        {
            RegisterCommand(":info", new InfoCommand());
        }

        public bool IsCommandInput(Player player, string input)
        {
            ICommand command;

            var cmdString = input.Split(' ')[0];

            if (!_commandsRegistered.TryGetValue(cmdString, out command))
            {
                return false;
            }

            if (command.PermissionRequired != "" && !player.GetPlayerData().GetPermissions().HasCommand(command.PermissionRequired))
            {
                return false;
            }

            if (command.NumberOfParameters < input.Split(' ').Length)
            {
                player.SendWhisper("Invalid command syntax -- " + cmdString + " " + command.CommandParameters);
                return true;
            }

            DateTime lastExecuted;

            if (player.GetPlayerData()._commandCooldowns.TryGetValue(cmdString, out lastExecuted))
            {
                var commandSpan = DateTime.Now - lastExecuted;

                if (command.CommandCooldown && commandSpan.TotalSeconds < (command.CommandCooldownMs / 1000))
                {
                    player.SendNotification("You're cooling down from this command! [" + commandSpan.TotalSeconds + "/" + (command.CommandCooldownMs / 1000) + "]");
                    return true;
                }
            }
            else
            {
                player.GetPlayerData()._commandCooldowns.Add(cmdString, DateTime.Now);
            }

            command.ProcessCommand(player);

            return true;
        }

        private void RegisterCommand(string commandName, ICommand command)
        {
            _commandsRegistered.Add(commandName, command);
        }
    }
}

ICommand:

namespace Sirius.Base.Game.Habbo.Commands.Commands
{
    using Other.GameClients;

    internal interface ICommand
    {
        void ProcessCommand(Player player);
        string PermissionRequired { get; }
        int NumberOfParameters { get; }
        string CommandParameters { get; }
        string CommandDescription { get; }
        bool CommandCooldown { get; }
        int CommandCooldownMs { get; }
    }
}

InfoCommand (just 1 of many commands)

using System;
using System.Text;

namespace Sirius.Base.Game.Habbo.Commands.Commands.Habbo
{
    using Other.Communication.Packets.Outgoing.Notifications;
    using Other.GameClients;

    internal sealed class InfoCommand : ICommand
    {
        public string PermissionRequired => "";
        public int NumberOfParameters => 0;
        public string CommandParameters => "";
        public string CommandDescription => "Lets you view information about the server.";
        public bool CommandCooldown => true;
        public int CommandCooldownMs => 5000;

        public void ProcessCommand(Player player)
        {
            // do what ever you want the command to do here...
        }
    }
}