texts: Simplify and prettify function looking for max value in a list and modifying some underlying values within that list

texts:
This function is used to modify values in list List<GoogleUsageMapping> and prepare them for entering into billing system.

I'm hoping this function can be more simplified and prettified, logic works.
Function needs to keep track of maxValue and if the maxValue is of type LOGICAL_SIZE. Would love to eliminate one of the for-loop if possible for instance.

private void checkForOverage(List<GoogleUsageMapping> records) {
    BigDecimal highestQuantity = new BigDecimal(0);
    GoogleUsageMapping recordHighestQuantity = null;
    for (GoogleUsageMapping record : records) {
        if (record.getUsage().getQuantity().compareTo(highestQuantity) > 0) {
            highestQuantity = record.getUsage().getQuantity();
            recordHighestQuantity = record;
        }
    }

    if (recordHighestQuantity.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
        s_logger.info("Overage scenario accord LOGICAL_SIZE: " + recordHighestQuantity.getUsage().getQuantity() + " greater than ALLOCATED_SIZE");
        for (GoogleUsageMapping record : records) {
            if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
                continue;
            }
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}

modified version:

private void checkForOverage(List<GoogleUsageMapping> records) {
    GoogleUsageMapping recordUsageHighestQuantity = Collections.max(records, Comparator.comparing(c -> c.getUsage().getQuantity()));

    if (recordUsageHighestQuantity.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
        s_logger.info("Overage scenario accord LOGICAL_SIZE: " + recordUsageHighestQuantity.getUsage().getQuantity() + " greater than ALLOCATED_SIZE");
        for (GoogleUsageMapping record : records) {
            if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
                continue;
            }
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}


texts:
I wrote a C++ program for 99 Bottles of Beer, but it's kind of messy. Is there any way I can make it short and cleaner and more easier to read?

/*
 * Write a program that prints out the entire lyrics to a full rendition of "99 bottles of beer"
 */

#include <iostream>

using namespace std;

int main (void)
{
    int bottle = 99;
    while (bottle > 0)
    {
        cout << bottle << " bottles of beer on the wall, "
             << bottle << " bottles of beer." << endl;

        bottle--;

        cout << "Take one down and pass it around, " << bottle << " "
             << "bottles of beer on the wall.\n" << endl;

        if (bottle == 1)
        {
            break;
        }

    }

    cout << "1 bottle of beer on the wall, 1 bottle of beer." << endl
         << "Take one down and pass it around, no more bottles of beer on the wall.\n" << endl
         << "No more bottles of beer on the wall, no more bottles of beer." << endl
         << "Go to the store and buy some more, 99 bottles of beer on the wall.";

    return 0;
}


texts: Comparing performance between thread, task, parallel

texts:
I wrote some function to compare the duration taken for 1000 loops. Just wondering if the comparison is right? For the thread, I want to set to maximum 3 thread. Thread is core, right? Task took the longest time which seems not correct.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Multithreading_Loop
{
class Program
{
    static void Main(string[] args)
    {
        //PrintLoopWithoutThread();
        //PrintLoopWithThread();
        //PrintLoopWithTaskWaitAll();
        //PrintLoopWithParallelFor();
        PrintLoopWithParallelForEach();
    }

    /// <summary>
    /// Elapsed time: 4.13 seconds
    /// </summary>
    private static void PrintLoopWithoutThread()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        for (var x = 1; x <= 1000; x++)
        {
            Console.WriteLine($"Worker Id: {Thread.CurrentThread.ManagedThreadId}");
            Console.WriteLine(x);
        }

        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalSeconds);
    }

    /// <summary>
    /// Elapsed time: 11.4 seconds
    /// </summary>
    private static void PrintLoopWithThread()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Thread t1 = new Thread(PrintLoopWithoutThread);
        t1.Start();
        Thread t2 = new Thread(PrintLoopWithoutThread);
        t2.Start();
        Thread t3 = new Thread(PrintLoopWithoutThread);
        t3.Start();
        t1.Join();
        t2.Join();
        t3.Join();

        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalSeconds);
    }

    /// <summary>
    /// Elapsed time: 15.5 seconds
    /// </summary>
    private static void PrintLoopWithTaskWaitAll()
    {
        Task task1 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
        Task task2 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
        Task task3 = Task.Factory.StartNew(() => PrintLoopWithoutThread());

        Task.WaitAll(task1, task2, task3);

    }

    /// <summary>
    /// Elapsed time: 2.2 seconds
    /// </summary>
    private static void PrintLoopWithParallelFor()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        Parallel.For(0, 999, x =>
        {
            Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + x);
        });

        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalSeconds);
    }

    /// <summary>
    /// Elapsed time: 2.0 seconds
    /// </summary>
    private static void PrintLoopWithParallelForEach()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        var data = Enumerable.Range(0, 999);

        // If computer has 4 cores and you want to use the maximum 4,
        // then put MaxDegreeOfParallelism = 4
        Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
        {
            Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + i);
        });

        sw.Stop();
        Console.WriteLine(sw.Elapsed.TotalSeconds);
    }

}
}


texts:
I created a brainfuck interpreter in javascript. It works good to me as I have seen no bugs in my compiler. I like to get a suggestion and review from you to what should this compiler improve.

Here's the short code:

function bf(str, input){

var array = str.split("");

var memory = [0];

var pointer = 0;

var result = [];

var open = [];

for(var i = 0; i < array.length; i++){

  if(array[i] == ">"){

    pointer++;

    if(memory.length-1 < pointer){

     memory.push(0);

    }

  }else if(array[i] == "<"){

    if(pointer > 0){

     pointer--;

    }else{

     throw "Overflow Error at " + i

    }

  }else if(array[i] == "+"){

    if(memory[pointer] < 255){

      memory[pointer]++;

    }else{

      memory[pointer] = 0;

    }

  }else if(array[i] == "-"){

    if(memory[pointer] > 0){

      memory[pointer]--;

    }else{

      memory[pointer] = 255;

    }

  }else if(array[i] == "."){

    result.push(String.fromCharCode(memory[pointer]));

  }else if(array[i] == ","){

    memory[pointer] = input.shift().charCodeAt(0);

  }else if(array[i] == "["){

    if(open.length){

      if(open[open.length-1] != i){

        open.push(i);

      }

    }else{

      open.push(i);

    }

  }else if(array[i] == "]"){

    if(open.length){

      if(memory[pointer]){

        i = open[open.length - 1];

      }else{

        open.pop();

      }

    }

  }

}

return result;

}


texts: Calculating the average of all nodes in a Binary Search Tree using visitors

texts:
I'm required to calculate the average value of all nodes in a BST using a Visitor, I'm not sure if I did this correctly or if i could just calculate the average with inOrder() and therefore I'm not really utilizing the visitor.

import java.util.*;

public class Node{

    int val;
    Node left;
    Node right;
    private static int sum;
    private static int count;
    private static double average;

    public Node(int val){
        this.val = val;
    }

    public int getVal(){
        return val;
    }

    public interface Visitor {
        int visit(Node node);
    }

    static class NodeVisitorImpl implements Visitor{
        @Override
        public int visit(Node node) {
            return node.getVal();
        }
    }

    public void insert(int toInsert) {
        if (toInsert < this.val) {
            if (this.left == null) {
                this.left = new Node(toInsert);
            } else {
                this.left.insert(toInsert);
            }
        } else if (toInsert > this.val) {
            if (this.right == null) {
                this.right = new Node(toInsert);
            } else {
                this.right.insert(toInsert);
            }
        } else {
            System.out.println("Shouldn't have the same value");
        }

    }

    public static void inOrder(Node root){
        if (root == null) {
            return;
        }
        Visitor visitor = new NodeVisitorImpl();
        sum += visitor.visit(root);
        count++;
        average = sum/count;
        inOrder(root.left);
        inOrder(root.right);
    }

    public static void main(String[] args){
        Node root = new Node(4);
        root.insert(2);
        root.insert(1);
        root.insert(3);
        root.insert(6);
        root.insert(5);
        root.insert(7);

        inOrder(root);
        System.out.println(average);
    }

}


texts:
I completed the "Nested Lists" challenge on HackerRank, and would love any feedback on my code.

My program is fed text with the number of students in a classroom, the name of a student, and their grade. For example:

4
Shadab
8
Varun
8.9
Sarvesh
9.5
Harsh
10

The code should return the student with the second lowest grade. Here's the output using the above input:

Varun

Here is my code:

def secondlow(students):
    grades = []
    for student in students:
        grades.append(student[1])
    sort_grades = sorted(grades)
    seclow_grade = sort_grades[0]
    for grade in sort_grades:
        if grade != seclow_grade:
            seclow_grade = grade
            break
    seclow_stud = []
    for student in students:
        if student[1] == seclow_grade:
            seclow_stud.append(student[0])
    for name in sorted(seclow_stud):
        print(name)

students = []
for pupil in range(int(input())):
    new_stud = [input(), float(input())]
    students.append(new_stud)
secondlow(students)


texts: Earliest time frog can jump to the other side of a river in C#

texts:
I'm new to C#, I programmed a little in Java in the past. I had the two previous exercises reviewed here (permCheck, cyclicRotation, with a 100% score, just like this one), and I'm applying what the accepted answers contributed to me.
Even though the site expects names like public int solution(int X, int[] A), I refactored the code after it was accepted, and applied those contributions I mentioned.
Is this how professional code should look like in terms of quality, or are there still things to improve in solutions of easy exercises like this written by me?

Task description

A small frog wants to get to the other side of a river. The frog is
initially located on one bank of the river (position 0) and wants to
get to the opposite bank (position X+1). Leaves fall from a tree onto
the surface of the river.
You are given an array A consisting of N integers representing the
falling leaves. A[K] represents the position where one leaf falls at
time K, measured in seconds.
The goal is to find the earliest time when the frog can jump to the
other side of the river. The frog can cross only when leaves appear at
every position across the river from 1 to X (that is, we want to find
the earliest moment when all the positions from 1 to X are covered by
leaves). You may assume that the speed of the current in the river is
negligibly small, i.e. the leaves do not change their positions once
they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In second 6, a leaf falls into position 5. This is
the earliest time when leaves appear in every position across the
river.
Write a function:
class Solution { public int solution(int X, int[] A); }
that, given a non-empty array A consisting of N integers and integer
X, returns the earliest time when the frog can jump to the other side
of the river.
If the frog is never able to jump to the other side of the river, the
function should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above.
Write an efficient algorithm for the following assumptions:
N and X are integers within the range [1..100,000]; each element of
array A is an integer within the range [1..X].

/// <summary>
/// Check if a given array contains the integers 1..N
/// </summary>
/// <returns>
/// -1 if <paramref name="fallenLeaves"/> does not contain all integers
///     1..N, where N = <paramref name="requiredAmountOfLeaves"/>
/// a possitive int i, if the required amount of ints were present at
///     <paramref name="fallenLeaves"/>
/// </returns>

const int FROG_CANT_JUMP_TO_THE_OTHER_SIDE = -1;

public static int GetSecondsRequired
    (int requiredAmountOfLeaves, int[] fallenLeaves)
{
    bool[] leavesAsSteps = new bool[requiredAmountOfLeaves + 1];
    int espectedSum = 0, correctSum = 0;
    for (int i = 1; i <= fallenLeaves.Length; i++)
    {
        if (i <= requiredAmountOfLeaves)
        //get summatory of 1..N
            correctSum += i;
        if (fallenLeaves[i - 1] <= requiredAmountOfLeaves &&
            !leavesAsSteps[fallenLeaves[i - 1]])
        {
        //accumulate where the expected leaf fell and set its location to true
            espectedSum += fallenLeaves[i - 1];
            leavesAsSteps[fallenLeaves[i - 1]] = true;
        }
        if (espectedSum == correctSum && i >= requiredAmountOfLeaves)
        //if all the espected leaves fell, then return the array's
        //index where the last expected leaf was found
            return i - 1;
    }
    return FROG_CANT_JUMP_TO_THE_OTHER_SIDE;
}


texts: Parsing a string to get the values of certain attributes

texts:
I have written a small method that extracts certain information from a string. An example of such a string is

"Some text BLA/123/5345/349230498 some more text PNR: 12345678, Name: John, CallName: Peter, TimeStamp: 01.10.2015"

Now I need certain information from this string, e.g. the PNR, Name, CallName, and TimeStamp (as string). Right now the method looks like this:

/// <summary>
/// Reads the value of a specified attribute from the log entry.
/// </summary>
/// <param name="identifier">The prefix used in the string (e.g. "Name" in "Name: John").</param>
/// <returns>The value of the attribute (e.g. "John" bei "Name: John".</returns>
private string GetValueFromMessage(string identifier)
{
  int index = this.Message.IndexOf(identifier) + identifier.Length + 2;

  if (index != -1)
  {
    char c = this.Message[index];
    string result = string.Empty;

    while (c != ',')
    {
      result += c;
      index++;
      if (index < this.Message.Length)
      {
        c = this.Message[index];
      }
      else
      {
        break;
      }
    }

    return result;
  }

  return null;
}

Some parts that I don't like about my code, and don't know if they're done correctly:

It looks too long/not elegant to me. Specifically, I think the loop could be done more efficiently. I tried different loops, also tried with a line of the form c = this.Message[++index], but then I ran into problems at the end of the string.
I want to get rid the double usage of c = this.Message[index] somehow.
Is it even good style to return null if there is no occurrence of the attribute? (As info: this can happen, but maybe it would be smarter to return string.Empty then?)
Should I use this.Message instead of just Message when it is a public property of the surrounding class?
I also want to get rid of the if statement (and the ugly break) inside the loop if possible, but didn't really find a way yet.

Maybe something along the lines of

while (index < this.Message.Length && c != ',')

would work?


texts: Reference wrapper for functions overloadings and universal references

texts:
I have design a little class to allow to overload a function with universal references for a known type, but I'm not sure if that class will work as expected in any contexts.

The indended purpose is to allow overload a ''universal reference'' templated function, for specific types:

template<class arg_t>
void fun(arg_t&& obj); // obj will be just forwarded

// Overload for std::string but unaware of qualifiers, for
// forwarding purposes.
template<class arg_t = std::string¿?>
void fun(arg_t&& str);

C++ currently doesn't offer any feature to allow that (templated qualifiers). So, my class is like a std::reference_wrapper, but transporting in a second template parameter the decayed type, to write things like:

// Overloads the generic version for a std::string qualified family.
template<class qualified_t>
void fun(uref<qualified_t, std::string> uref)
{ fun2(uref.get()); } // No need to do std::forward

The get() return type will be std::string&, std::string const& or std::string&&.

That is the best I was able to achieve:

template<class ref_type_t, class type_t = std::decay_t<ref_type_t> >
class uref
{
    ref_type_t o;

public:
    using type = type_t;
    using ref_type = ref_type_t;

    static_assert(std::is_reference<ref_type>::value,
                  "ref_type must be a reference");

    explicit uref(ref_type t) : o(std::forward<ref_type>(t)) {}

    ref_type get() { return std::forward<ref_type>(o); }
    type const& get() const { return o; }

    template<class T, class =
        std::enable_if_t<std::is_convertible_v<ref_type, T>
                    and !std::is_same_v<std::decay_t<T>, type>> >
    operator T() const { return get(); }

    template<class T, class =
        std::enable_if_t<std::is_convertible_v<type const&, T>
                    and !std::is_same_v<std::decay_t<T>, type>> >
    operator T() { return get(); }

    operator type const&() const & { return o; }
    operator type&() & { return o; }
    operator ref_type() && { return std::forward<ref_type>(o); }
};

template<class type>
uref<type&&> make_uref(type&& t)
{ return uref<type&&>(std::forward<type>(t)); }

The way of using it is:

void client(float) { std::cout << "Floating" << std::endl; }

void client(std::string const&)
{ std::cout << "From const char* to std::string" << std::endl; }

template<class param_t>
auto service(param_t&& arg)
{ return client(make_uref(std::forward<param_t>(arg))); }

template<class ref_t>
void client(uref<ref_t, std::string>)
{ std::cout << "Specific" << std::endl; }

int main()
{
    service(3);
    service(std::string("Hi!"));
    service("Hi!");
    service(3.f);

    return 0;
}

Since uref saves the original reference type on the first template parameter T, and with get() you get the reference as-is, and you can have different "universal reference" overloads for different ''decayed'' types. With the conversion operators, the client can receive the type without begin wrapped, the conversion will free the reference bound on the service parameter. You can still use the reference wrapper to construct other objects to any convertible-to type.

The question is, is desirable to have such an object? Can be seen as an anti-pattern? For example, the two overloads, receiving a std::string and uref<T, std::string>, can confused the reader, specifically, when each one of them will be called.

Any downside of this design?


texts: Reference enum values in Angular template without aliasing the enum type

texts:
Is there a way to improve this code? I'd like to use the enum type PaymentMethoddirectly in the angular template without renaming it to _PaymentMethod.

export enum PaymentMethod {
    CreditCard,
    EFT
}

@Component()
export class PaymentComponent {
    // ReSharper disable once InconsistentNaming
    _PaymentMethod = PaymentMethod;

    paymentMethod: PaymentMethod;
}

<ng-template *ngIf="paymentMethod == _PaymentMethod.CreditCard">
   Enter your card details
</ng-template>


texts: Computing the distance and weight matrix of a graph

texts:
I would like to create an igraph object. First, I set up the size of igraph object — n, m, then create a random matrix. As a result matrix B will be filled. Matrix B is the adjacency matrix for the igraph object. Inside for-loops I compute the distance d (scalar) and the weight matrix W. I would like to improve the perfomance of calculation. I think it is possible because I have used 4 for-loops in my code:

n <- 6
m <- 7

mat <- matrix(sample(0:255, n*m, replace=T), nrow = n, ncol = m)
R <- 2

a <- 1
b <- 1

d <- 0
e <- 0
g <- 0

W <- matrix(0, n, m)
B <- matrix(0, n*m, n*m)

for (i in 1:n){
for (j in 1:m){
  for (i0 in 1:n){
  for (j0 in 1:m){
            d <- ((i0 - i)^2+(j0 - j)^2)^(1/2)
            e <- ifelse(d <= R, 1, 0)
            g <- abs(mat[i,j] - mat[i0,j0])
            W[i0,j0] <- e * ((a*g)^2 + (b*d)^2)^(1/2)
  } # for i0
  } # for j0
  B[m * (i-1)+j,] <- c(t(W))

} #for_j
} #for_i

Could anyone please give me an idea how to rewrite the above code with fewer or no for-loops?


texts: Change a string into a function/def activator

texts:
import random

import string

# every def from 'def nothing()' to 'def wxyz()' Print out several lines of text, printing: keyword 1, call number, phone number and keyword 2
def nothing():
    print("keyword: (nothing)\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def abc():
    print("keyword: abc\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def deft():
    print("keyword: deft\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def ghi():
    print("keyword: ghi\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def jkl():
    print("keyword: jkl\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def mno():
    print("keyword: mno\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def pqrs():
    print("keyword: pqrs\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def tuv():
    print("keyword: tuv\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

def wxyz():
    print("keyword: wxyz\ncalls: 1\n" + str(random_number()) + "\nkeyword: exit\n")

# keywords that are accepted and not denied
accepted_keywords = {
    0: nothing,
    1: abc,
    2: deft,
    3: ghi,
    4: jkl,
    5: mno,
    6: pqrs,
    7: tuv,
    8: wxyz
}

# creates a random phone number
def random_number():
    string = []
    x = 0
    while x != 10:
        x += 1
        number = str(random.randrange(0, 10))
        string.append(number)
    return str('(' + string[0] + string[1] + string[2] + ')' + string[3] + string[4] + string[5] + '-' + string[6] + string[7] + string[8] + string[9])

# these two things pick a random value & key from the accepted_keywords() dictionary then calls that value & key
#tester = random.randrange(len(accepted_keywords))
#accepted_keywords[tester]()

# randomizes letter so it can be aproved or denied
def random_keyword():
    keyword = ''
    chrt_count = random.choice([3,4])
    for i in range(chrt_count):
        lowercase = string.ascii_lowercase #lowercase letters
        random_letter = random.randrange(len(lowercase)) # chooses random character from var lowercase which is converted to a number based on its place in alphabet
        keyword_letter = lowercase[random_letter] # grabs the letter from lower using the number from var random_letter to located the place value of a letter
        keyword += keyword_letter
    while True:
        if keyword in accepted_keywords.values():
            print("keyword: " + keyword + "\n*Approved*\n")
            break
        else:
            print("keyword: " + keyword + "\nDenied\n")
            break

random_keyword()

Here is the scenario, I am using python 3.x and I am supposed use cases but since Python does not use cases, I had to use a dictionary.
My problem is that I have a function named wxyz() and I created another function named random_keyword that picks random letters from the alphabet, one at a time, and adds it into a variable named keyword that is a blank string. So by the time random_keyword has ran its course, keyword will have 3 or 4 random letters in it. For now let’s say that those random letters are “wxyz”, which is a string. Then I go through if keyword in accepted_key: print .... The problem is that keyword is a string, therefore it does not match the wxyz in accepted_keywords. Is there a way to turn a string into a function/def activator?


texts:
I'm wondering how I can improve this class, for instance:

Should local variables such as allInput that are passed in to more than one function be instance variables?
Should functions like determineMeetingFormat and parseParticipants be called directly into the Meeting constructor or be assigned to local constants that clearly defines what's being returned?
Would it be better to make location and description optional Strings rather than empty strings?
Is making all my functions and instance variables static the best way to make this behave like a static class?

/**

/**
     Parses calendar entry to create a Meeting object.

 - parameter calendarEvent: The calendar entry we want to parse
 - returns: A Meeting Object with the relevant information extracted from the calendar entry.
 */
static func parse(calendarEvent: EKEvent) -> Meeting {
    let location = calendarEvent.location ?? ""
    let description = calendarEvent.notes ?? ""

    let allInput = "\(calendarEvent.title)\n\(location)\n\(description)"
    let parsedHostCodes = parseHostCode(from: allInput)
    let parsedPasscodes = parseParticipantCode(from: allInput, hostCodes: parsedHostCodes)
    let parsedPhoneNumbers = parsePhoneNumber(from: allInput, codes: parsedPasscodes + parsedHostCodes)
    let meetingFormat = determineMeetingFormat(input: allInput, parsedPhoneNumbers: parsedPhoneNumbers)

    return Meeting(
        UUID: calendarEvent.eventIdentifier,
        title: calendarEvent.title,
        description: description,
        location: location,
        host: retrieveHost(from: calendarEvent.organizer),
        startTime: calendarEvent.startDate,
        endTime: calendarEvent.endDate,
        allday: calendarEvent.isAllDay,
        passcodes: parsedPasscodes,
        hostcodes: parsedHostCodes,
        phoneNumbers: parsedPhoneNumbers,
        attendees: parseParticipants(from: calendarEvent.attendees),
        isAtt: allInput.contains(pattern: attRegex),
        meetingFormat: meetingFormat)
}


texts: Removing duplicates from an array quickly

texts:
Array.prototype.unique = function() {
    var a = [], // uniques get placed into here
        b = 0; // counter to test if value is already in array 'a'

    for ( i = 0; i < this.length; i++ ) {
        var current = this[i]; // get a value from the original array

        for ( j = 0; j < a.length; j++ ) { // loop and check if value is in new array
            if ( current != a[j] ) {
                b++; // if its not in the new array increase counter
            }
        }

        if ( b == a.length ) { // if the counter increased on all values
                               // then its not in the new array yet
            a.push( current ); // put it in
        }

        b = 0; // reset counter
    }

    this.length = 0; // after new array is finished creating delete the original array
    for ( i = 0; i < a.length; i++ ) {
        this.push( a[i] ); // push all the new values into the original
    }

    return this; // return this to allow method chaining
}

I'm expecting this to be a slow checker especially because there is no sorting first.  I'm interested in improving my sorting abilities etc so I thought I would get an early review.


texts:
I was wondering if there is a better way to write the following code? The code is working, I am looking for better technique to achieve the functionality, if any exists. Never mind the classes that are not shown, indentation, class names, etc. I am focused mostly on the functionality.

JsFilddle

                    Top Tree Node

                            Child 1

                                            Child 1.1

                    Last Node


texts: Website Navigation Bar - Potential code soup

texts:
I've had a bit of help designing the header for a website here: http://jsfiddle.net/gxLt5/21/

It looks and works exactly how I had hoped. That said, I do feel like the code is a bit grotty, and I'm sure there is a more elegant solution to achiving the same result.

Could anyone please give me some feedback on the HTML and CSS so see if it can be improved or restructured?

HTML

A

B

 Test Test

Log out

CSS

/* 1.0 Resets
************************************/
 * {
    margin: 0;
    padding: 0;
}
ul {
    font-size: 0;
}
html, body {
    height: 100%;
    max-height: 100%;
}
body {
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 13px;
    background-color: white;
}
li {
    list-style: none;
}
a {
    text-decoration: none;
}
/* 2.0 Layout
************************************/
 .header {
    background-color: #9B59B6;
    height: 50px;
}
.logo {
    height: 50px;
    margin-bottom: 30px;
}
.navigation {
    position: absolute;
    display:inline-block;
    z-index: 1000;
        width: 100%;
}
.navigation li:not(:last-child){
   float:left
}
.navigation li a {
    display: block;
    height: 50px;
    line-height: 50px;
    color: #fff;
    font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 14px;
    padding-left: 30px;
    padding-right: 30px;
    opacity: 0.7;
}
.navigation li a:hover, .navigation li.active a {
    opacity: 1;
}
.navigation li span {
    display: inline-block;
    background: url(http://i.imgur.com/R6Fjt4e.png) no-repeat left center;
    width: 16px;
    height: 16px;
    /*overflow:hidden;*/
    margin-right: 16px;
}
.container {
    padding-top: 14px;
}
.dialog {
    display: none;
}
/* 4.0 Navigation Styles
************************************/
 #dashboard span {
    background-position: -64px -0px;
}
#vacancies span {
    background-position: -160px 0;
}
#candidates span {
    background-position: -32px -0;
}
#company span {
    background-position: -288px 0;
}
#account span {
    background-position: -128px 0;
}

.right {
    float: right;
}
nav ul ul {
    display: none;
}
nav ul li:hover > ul {
    display: block;
    position: absolute;
    background-color: #9B59B6;
}
.dropdown li {
    display: block;
}


texts:
I have a scenario when I want to have a HashSet<ITrackableObjectData>, where ITrackableObjectData has string TypeName and object Id readonly immutable properties. Id is a primitive value, ie. string, int, long, Guid etc.

I want to use these equality rules:

If the TypeName property is different, should anyway be considered non-equal.
If the Id is zero, null etc, should use the base object hashcode (reference equal).
If Id is not zero, then it should compare the TypeName and Id.

I created the following comparer to provided to the HashSet's constructor, and I'd like to hear from you of any improvements/vandalism in my code. As you can see I'm using the GetHashCode in the Equals method, is this a bad-idea?
Note that these are my equality requirements in my scenario.

class ITrackableObjectDataComparer : EqualityComparer<ITrackableObjectData>
{
  public override bool Equals(ITrackableObjectData x, ITrackableObjectData y) =>
    GetHashCode(x) == GetHashCode(y);

  public override int GetHashCode(ITrackableObjectData obj)
  {
    if (obj == null) return 0;
    var typeHash = obj.TypeName == null ? 0 : obj.TypeName.GetHashCode();
    var idHash = obj.Id == null ? 0 : obj.Id.GetHashCode();
    idHash = idHash == 0 ? obj.GetHashCode() : idHash;
    return typeHash ^ idHash;
  }
}

Note that this EqualityComparer is a private class and is only meant to serve the purpose of this specific HashSet which is not exposed at all.
In fact I don't also really care about the Equals, but rather about the GetHashCode, so I know whether an object with my specs have already been added to a HashSet.

Update:

This is basically the equality checker that fulfills my requirements (but again, I don't need an equality comparer, I need a hash equality-comparer)

public override bool Equals(ITrackableObjectData x, ITrackableObjectData y)
{
  if (x == y) return true; //ref eq.
  else if (x == null)
    return y == null;
  else if (y == null)
    return false;
  else if (x.TypeName != y.TypeName)
    return false;
  else
  {
    if (x.Id == null)
      return y.Id == null;
    else if (y.Id == null)
      return false;
    else
    {
      int xId = x.Id.GetHashCode(),
          yId = y.Id.GetHashCode();
      if (xId == 0 || yId == 0)
        return x.Equals(y); //use default eq.
      else
        return xId == yId;
    }
  }
}


texts: How do you name a something as approximately equal?

texts:
Let's say I following have code:
private bool ErrorLogExists(LogEvent logEvent, DateTime filterStart)
{
    var startTimeFrom = logEvent.StartTime.TruncateMilliseconds();
    var startTimeTo = startTimeFrom.AddSeconds(1);

    return _existingErrorLogs.Any(x =>
        x.Name == logEvent.Name &&
        x.EventDateTime >= filterStart &&
        x.EventDateTime >= startTimeFrom &&
        x.EventDateTime <= startTimeTo);
}

The problem is that I think it is terrible.

I might just rename startTimeFrom and startTimeTo and remove :
x.EventDateTime >= filterStart &&

as a cached view is already returned and it is no longer needed there.

I am tempted to write :
public static class DoubleExtensions
{
    internal const double AcceptableTolerance = .0005;
    public static bool IsApproximately(this double thisValue, double thatValue, double tolerance = AcceptableTolerance)
    {
        return Math.Abs(thisValue - thatValue) <= tolerance;
    }
}
public static class DatetimeExtensions
{
    public static bool IsApproximately(this DateTime thisTime, DateTime thatTime, double toleranceInSeconds = DoubleExtensions.AcceptableTolerance)
    {
        var thisTimeInSeconds = thisTime.AsTotalSeconds();
        var thatTimeInSeconds = thatTime.AsTotalSeconds();

        return thisTimeInSeconds.IsApproximately(thatTimeInSeconds, toleranceInSeconds);
    }

    public static double AsTotalSeconds(this DateTime thisTime)
    {
        return (thisTime - DateTime.MinValue).TotalSeconds;
    }
}

so I could instead use
private bool ErrorLogExists(LogEvent logEvent, DateTime filterStart)
{
    return _existingErrorLogs.Any(x =>
        x.Name == logEvent.Name &&
        x.EventDateTime.IsApproximately(logEvent.StartTime));
}

Reason why I would leave AsTotalSeconds as public, is that I would use it in tests. As in test tests, I already seem to have this partly supported. If I assume that I have:
var thisTimeInSeconds = thisTime.AsTotalSeconds();
var thatTimeInSeconds = thatTime.AsTotalSeconds();
var acceptableTolerance = .0005;

I could write :
Assert.That(thisTimeInSeconds, Is.EqualTo(thatTimeInSeconds).Within(acceptableTolerance);
thisTimeInSeconds.Should().BeApproximately(thatTimeInSeconds, acceptableTolerance);

The problem that I am facing is that
x.EventDateTime.IsApproximately(logEvent.StartTime))

has arguably even worse readability. People doing my code review might say :

"WTF is this?" / "WTF is that?" (I admit, I picked names so I could say that)
Why do we need IsApproximately?
Why is that an extension method and not a class method?
Is that DateTimes responsibility to know about this?
Is the logic change necessary?
Fine, you have DateTimeExtensions, why do you need DoubleExtensions?

My question is: How would you refactor this code?

Edit:
What I have currently:
    private bool ErrorLogExists(LogEvent logEvent)
    {
        var errorLogToleranceInMilliseconds = Properties.Settings.Default.ErrorLogToleranceInMilliseconds;
        var eventDateTimeFrom = logEvent.StartTime.AddMilliseconds(-errorLogToleranceInMilliseconds);
        var eventDateTimeTo = logEvent.StartTime.AddMilliseconds(errorLogToleranceInMilliseconds);

        return _existingErrorLogs.Any(x =>
            x.Name == logEvent.Name &&
            x.EventDateTime >= eventDateTimeFrom &&
            x.EventDateTime <= eventDateTimeTo);
    }

... it's a bit better.


texts: Recursive function to get unique properties

texts:
I just wanted to share my newly created JavaScript code. This code is responsible for passing back only the unique elements for a given array. This one is quite useful when you have a huge array and you store objects with huge arrays.

Use case: you want to sort out all unique object to do provide a filtering mechanism based on the chips!

Like the array is the following:

[
    {
        "name": "custom object1",
        "chips": [
            {
                "name": "hello"
            },
            {
                "name": "war"
            }
        ]
    },
    {
        "name": "custom object2",
        "chips": [
            {
                "name": "hello"
            },
            {
                "name": "option"
            }
        ]
    }
]

The function:

function getUnique(array, props, level = 0) {
    var retArray = [];
    array.forEach(function (element) {
        var index = props[level];
        if (Array.isArray(props) && props.length - 1 > level) {
            if (element[index] !== undefined) {
                var res = getUnique(element[index], props, level + 1);
                res.forEach(function (subelement) {
                    if (!retArray.some(function (arrayItem) {
                        return arrayItem === subelement;
                    })) {
                        retArray.push(subelement);
                    }
                });
            }
        } else {
            if (element[index] !== undefined && !retArray.some(function (arrayItem) {
                return arrayItem === element[index];
            })) {
                retArray.push(element[index]);
            }
        }
    });
    return retArray;
}

How to call the function:

getUnique(array, ['chips', 'name']);

That's it in a nutshell. What do you think? Any suggestions or advice?


texts: Sequential and parallel addition of 2 vectors

texts:
I have done sequential and parallel addition of 2 vectors that I have filled with some dummy values. I am also measuring the time of execution for both, sequential and parallel execution.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
#include <chrono>
#include <cassert>
#include <thread>

#define NUM_OF_THREADS 8
#define VECTOR_SIZE    512

using time_point = std::chrono::high_resolution_clock::time_point;

template<typename T>
std::vector<T> operator+(std::vector<T> const& first, std::vector<T> const& second)
{
    assert(first.size() == second.size());

    std::vector<T> result;
    result.reserve(first.size());

    std::transform(first.begin(), first.end(), second.begin(), std::back_inserter(result), std::plus<T>());
    return result;
}

template<typename T>
void parallel_addition(std::vector<T>& result,
                       std::vector<T> const& first,
                       std::vector<T> const& second,
                       size_t lower_bound,
                       size_t upper_bound)
{
    for (size_t i = lower_bound; i < upper_bound; i++)
    {
        result[i] = first[i] + second[i];
    }
}

int main(int argc, char *argv[])
{
    std::vector<int> first_vec, second_vec;

    /* Filling up the vectors with dummy values */
    for (int i = 1; i <= VECTOR_SIZE; i++)
    {
        first_vec.push_back(i);
        second_vec.push_back(i);
    }

    /* Sequential addition of vectors */
    time_point t1_seq = std::chrono::high_resolution_clock::now();
    std::vector<int> sequential_result = first_vec + second_vec;
    time_point t2_seq = std::chrono::high_resolution_clock::now();
    auto duration_seq = std::chrono::duration_cast<std::chrono::microseconds>(t2_seq - t1_seq).count();
    std::cout << "Sequential addition of vectors - execution time: " << duration_seq << "us" << std::endl;

    /* Parallel addition of vectors */
    std::vector<std::thread> threads;
    std::vector<int> parallel_result(VECTOR_SIZE);

    time_point t1_par = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < NUM_OF_THREADS; i++)
    {
        threads.push_back(std::thread(parallel_addition<int>,
                                      std::ref(parallel_result),
                                      first_vec,
                                      second_vec,
                                      i * (VECTOR_SIZE / NUM_OF_THREADS),
                                      (i + 1) * (VECTOR_SIZE / NUM_OF_THREADS)));
    }

    for (auto &thread : threads)
    {
        thread.join();
    }

    time_point t2_par = std::chrono::high_resolution_clock::now();
    auto duration_par = std::chrono::duration_cast<std::chrono::microseconds>(t2_par - t1_par).count();
    std::cout << "Parallel (" << NUM_OF_THREADS << " threads) addition of vectors - execution time: " << duration_par << "us" << std::endl;

    return 0;
}

Despite style review, can you also tell me if there is another, better, approach to addition of two vectors in multiple threads?
My intention was to write in C++17.


texts: Project Euler 81 (minimum path sum through a matrix)

texts:
Problem Statement:

  In the 5 by 5 matrix below,

131   673 234 103 18
201   96  342 965 150
630   803 746 422 111
537   699 497 121 956
805   732 524 37  331

  the minimal path sum from the top left to
  the bottom right, by only moving to the right and down, is

131 → 201 → 96 → 342 → 746 → 422 → 121 → 37 → 331

  and is equal to 2427.

  Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix,
  from the top left to the bottom right by only moving right and down.

Algorithm:

I used a dynamic programming approach to this problem

Accumulate the sum for the top row (going right till the end)
Accumulate the sum for the left column (going down till the end)
For each (i, j) pair, I add the minimum of the left cell and the upper cell
The result is stored in the last (i, j) pair

Code:

from itertools import accumulate # Note this was added in Python 3.3

def min_path_sum(matrix):
    """Returns the minimum path sum of a matrix moving only down and right"""
    size = len(matrix)
    if size == 0:
        return 0

    matrix[0] = list(accumulate(matrix[0][i] for i in range(size)))

    for i in range(1, size):
        matrix[i][0] += matrix[0][i-1]

    for i in range(1, size):
        for j in range(1, size):
            matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])
    return matrix[size-1][size-1]

if __name__ == '__main__':
    with open("matrix.txt") as file:
        matrix = []
        for line in file:
            matrix.append(list(map(int, line.strip().split(","))))
        print(min_path_sum(matrix))

I'm looking for a general code review.


texts: Find every possible pair of numbers that sum up to n number

texts:
I have this following code which find every possible pair of numbers that sum up to n number

lst = [int(input()) for i in range(int(input()))]
num = int(input()) #Amount to be matched
cnt = 0
lst = list(filter(lambda i: i <= num, lst)) #Remove number that more than `num`
for i in lst:
    for j in lst:
        if i+j == num:
            cnt += 1
print(int(cnt/2))

For example, if I enter

5 #How many numbers
1 < #Start of number input
4 <
5
7
1 < #End of number input
5 #Amount to be matched

It will return 2 because there is two pair that their sum is equal to 5 (1,4) and (4,1) (The number I marked with < ).

The problem is the complexity is O(n2) which will run slow on large input. I wanted to know if that is there a way to make this run faster?

Another example:

10 #How many numbers
46 #Start of number input
35
27
45
16
0 <
30 <
30 <
45
37 #End of number input
30 #Amount to be matched

The pair will be (0, 30) and (0, 30) which will return 2.


texts: Powershell SMTP report with attachment issues needs corrections

texts:
I created this tiny script to full fill a repeated request from audit. I want to expand it but ran into an issue with file creation.
This code will create the $attachment in the directory it is run from. When using ISE it stores the $attachment to the system32 folder. When run from the script repository it leaves the file in the same directory. The goal is for the file to be attached and emailed out not leaving any remnants behind. This script is used in many functions for auditing so I will be using this as a "standard" process for automating audit reports. I am very new to scripting but looking for all feedback!!
Eventually there will be multiple attachments to be added and this run weekly. Right now they are all individual scripts that are run as requested.
    #Run Cleanup for ISE Variables using Preloaded Profile
#Cleanup
#Mailsettings
$SmtpSender = "Email@mail.com"
$SmtpReceiver = "User@mail.com"
$SmtpSubject = "User accounts enabled-Auditonly"
$SmtpBody = "Attached is run from PDQ using script Users.enabled-Auditonly.ps1"
$Smtpservr = "smtp.mail.com"
#Variables
$attachment = New-Item "Users.enabled-Auditonly$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv" -ItemType File

Get-ADuser -Filter * -Properties Name, SamAccountName,Description, Enabled | Select Name, SamAccountName,Description, Enabled |
export-csv $attachment
#Grabs the attachment from the above location and emails it out.
Send-MailMessage -Attachments $attachment -Body $SmtpBody -BodyAsHtml -From $SmtpSender -To $SmtpReceiver -Subject $SmtpSubject -SmtpServer $Smtpservr


texts: Javascript to change element property based on user input

texts:
In the code below, I take the number of square the user wants, then calculate the size of each square (so that they all fit in the container.)

I then define var square as in the 3rd line of code. I find this string pasting technique very hard to read and error-prone. The general question is thus: Is there a better way to define an element using user input?

var genGrid = function(num_square) {
    var square_size = ($(".grid_container").height() / num_grid) + "px";
    var square = "

";

    $("body").append($(square));
};


texts: Checking if two dates are within 15 minutes of each other

texts:
The following code compares two dates and checks if they are within 15 minutes of each other, with a tolerance of a second. All of the test cases below pass with the existing solution. The question is can it be improved by making it more efficient and/or elegant given the following test cases.

TestId, whenCreated, whenToCompareTo, expected Outcome

[(1, "01/01/2017 15:00:00", "01/01/2017 15:15:00", true)]
[(2, "01/01/2017 15:00:00", "01/01/2017 15:00:00", true)]
[(3, "01/01/2017 15:00:00", "01/01/2017 15:16:00", false)]
[(4, "01/01/2017 15:00:00", "01/01/2017 14:59:59", false)]
[(5, "01/01/2017 15:00:00", "01/01/2017 15:14:59", true)]
[(6, "01/01/2017 15:00:00", "01/01/2017 15:16:01", false)]
[(7, "2017-01-01T15:00:00.0000001", "2017-01-01T15:15:00.0000002", true)]
[(8, "2017-01-01T15:15:00.5170000", "2017-01-01T15:15:00.4537587", true)]
[(9, "2017-01-01 15:00:00", "2017-12-31 15:00:00", false)]
[(10, "2018-05-06T13:30:43.2200000", "2018-05-06T13:30:42.9978916", true)]

And here is the code that is doing the comparison:

public bool IsTokenAlive(DateTime timeToCompareTo)
{
    var isDateEarlier = DateComparison(timeToCompareTo, Created);
    var isCompareTimeOfDayEarlier = DateTimeOfDayComparison(timeToCompareTo, Created);
    var isExpired = AbsoluteSecondsComparison(timeToCompareTo, Created);
    var isAlive = isDateEarlier && (isCompareTimeOfDayEarlier || GetTotalSeconds(timeToCompareTo, Created) < 1) && isExpired;

    return isAlive;
}

private static bool DateComparison(DateTime timeToCompareTo, DateTime created)
{
    return DateTime.Compare(timeToCompareTo.Date, created.Date) >= 0;
}

private static bool DateTimeOfDayComparison(DateTime timeToCompareTo, DateTime created)
{
    //We are interested to compare up to the seconds, we are not interested in milliseconds
    return TimeSpan.Compare(StripMilliseconds(timeToCompareTo).TimeOfDay, StripMilliseconds(created).TimeOfDay) >= 0;
}

private static bool AbsoluteSecondsComparison(DateTime timeToCompareTo, DateTime created)
{
    return GetTotalSeconds(timeToCompareTo, created) < MaxTimeInSecondsTokenIsAlive;
}

private static DateTime StripMilliseconds(DateTime dateTime)
{
    return dateTime.AddTicks(-(dateTime.Ticks % TimeSpan.TicksPerSecond));
}

private static double GetTotalSeconds(DateTime timeToCompareTo, DateTime created)
{
    return (timeToCompareTo - created).Duration().TotalSeconds;
}

The Created property is set when the object is created and it will always be the timestamp of the server.


texts: Two BDD unit tests for an account repository with identical code

texts:
I am testing my repository class:

interface AccountRepository{
    void save(Account account);
    Optional<Account> findById(Long id);
}

And when writing tests, I ended up with two semantically different tests, but they essentially contain exactly the same code:

@DisplayName("user exists -- account does not exist -- save persists")
@Test
void save_userExistsAccountDoesNotExist_persisted() {
    //arrange
    User existingUser = userRepo.save(new User("John", "Smith"));
    Account account = new Account(existingUser, null);
    //act
    repo.save(account);
    //assert
    assertThat(repo.findById(account.getId())).contains(account);
}

@DisplayName("user exists -- account exists -- findById finds")
@Test
void findById_userExistsAccountExists_found() {
    //arrange
    User existingUser = userRepo.save(new User("John", "Smith"));
    Account existingAccount = repo.save(new Account(existingUser, null));
    //act & assert
    assertThat(repo.findById(existingAccount.getId())).contains(existingAccount);
}

I don't really want to remove one of them because that serves different purposes in my head but I am worried that I may have understood something wrong.


texts: Return the indices of the two numbers such that they add up to a specific target

texts:
(...as I learn Kotlin) I want to get the indices of the two numbers such that they add up to a specific target from a given array of integers.

Solution:

fun sum(values: Array<Int>, result: Int): Array<Int> {
  for ((i, e1) in values.withIndex()) {
    for ((j, e2) in values.drop(i + 1).withIndex()) { // ...or: values.drop(i + 1).forEachIndexed { j, e2 ->
      //println("$i : $e1 >> $j : $e2")
      if (e1 + e2 == result) {
        return arrayOf(i, i + j + 1)
      }
    }
  }
  return emptyArray()
}

Test cases:

class SumTest {
  @Test
  fun testSum() {
    Assert.assertArrayEquals(sum(arrayOf(4, 7, 9, 10, 6, 34), 10), arrayOf(0, 4))
    Assert.assertArrayEquals(sum(arrayOf(5, 7, 9, 10, 21, 34), 43), arrayOf(2, 5))
    Assert.assertArrayEquals(sum(arrayOf(2, 7, 11, 15), 9), arrayOf(0, 1))
    Assert.assertArrayEquals(sum(arrayOf(2, 7, 8, 6, 20), 11), emptyArray())
  }
}

I know this is a pretty simple algorithm, but I would like to avoid the return arrayOf(i, i + j + 1) and modifying the values array in the second loop (values.drop(i + 1).withIndex()) if possible. A functional-towards approach would be great!


texts: Representing a queue as a procedure with local state

texts:
From SICP:

  Exercise 3.22.  Instead of
  representing a queue as a pair of
  pointers, we can build a queue as a
  procedure with local state. The local
  state will consist of pointers to the
  beginning and the end of an ordinary
  list. Thus, the make-queue procedure
  will have the form

(define (make-queue)
  (let ((front-ptr ...)
        (rear-ptr ...))
    <definitions of internal procedures>
    (define (dispatch m) ...)
    dispatch))

  Complete the definition of make-queue
  and provide implementations of the
  queue operations using this
  representation.

I wrote the following solution:

(define (make-queue)
  (let ((front-ptr '())
        (rear-ptr '()))
    (define (set-front-ptr! ptr) (set! front-ptr ptr))
    (define (set-rear-ptr! ptr) (set! rear-ptr ptr))
    (define (empty?) (null? front-ptr))
    (define (front-queue)
      (if (empty?)
          (error "FRONT called with an empty queue" front-ptr)
          (car front-ptr)))
    (define (insert! item)
      (let ((new-pair (cons item '())))
        (cond ((empty?)
               (set-front-ptr! new-pair)
               (set-rear-ptr! new-pair)
               dispatch)
              (else
               (set-cdr! rear-ptr new-pair)
               (set-rear-ptr! new-pair)
               dispatch))))
    (define (delete!)
      (cond ((empty?)
             (error "DELETE! called with an empty queue" first-ptr))
            (else
             (set-front-ptr! (cdr front-ptr))))
      dispatch)
    (define (print) front-ptr)
    (define (dispatch m)
      (cond ((eq? m 'insert!) insert!)
            ((eq? m 'front-ptr) front-ptr)
            ((eq? m 'rear-ptr) rear-ptr)
            ((eq? m 'empty?) empty?)
            ((eq? m 'delete!) delete!)
            ((eq? m 'print) print)
            (else (error "No such procedure: dispatch" m))))
    dispatch))

(define q1 (make-queue))
((((q1 'insert!) 'a) 'print))
((((q1 'insert!) 'b) 'print))
((((q1 'delete!)) 'print))
((((q1 'delete!)) 'print))

How can it be improved?


texts:
I'd like to get a review for the function build_list() which reads a file containing words (separated by spaces) and returns a linked-list of words:

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

typedef struct ListNode {
    char* word;
    struct ListNode *next;
} ListNode;

typedef struct List {
    ListNode *head;
    ListNode *tail;
} List;

List* build_list(char* fileName)
{
    FILE* file = fopen(fileName, "r");
    assert(file != NULL);

    List* list = malloc(sizeof(List));
    assert(list != NULL);
    list->head = NULL;
    list->tail = NULL;

    char c;
    int word_size = 1;
    char* word = malloc(word_size);
    int word_count = 0;

    while ((c = fgetc(file)) != EOF)
    {
        assert(!ferror(file));

        while (c != ' ' && c != EOF)
        {
            if (word_count == word_size)
            {
                word_size += 1;
                word = realloc(word, word_size);
                assert(word != NULL);
            }

            word[word_count++] = c;

            c = fgetc(file);
            assert(!ferror(file));
        }

        word = realloc(word, word_size + 1);
        word[word_size] = '\0';

        ListNode *node = malloc(sizeof(ListNode));
        assert(node != NULL);
        node->next = NULL;
        node->word = word;

        if (list->head == NULL)
        {
            list->head = node;
            list->tail = node;
        }
        else
        {
            list->tail->next = node;
            list->tail = node;
        }

        if (c == EOF)
            break;

        word_count = 0;
        word_size = 1;
        word = malloc(word_size);

    }

    free(word);

    assert(!ferror(file));

    return list;
}


texts: Merging directories and keep files that have more lines

texts:
Goal

My goal is to merge directories. Whenever a file has the same name in two or more directories, then only the one that has the highest number of lines should be kept. If both files have the same number of files and differ then an error message should be thrown. Note that files having more lines are also bigger (in my specific case) which might be another way to compare files having the same name.

My Code

Here is my code that I think works fine

### Parameters ###

GeneralPath="/Users/remi/Documents/Biologie/Vancouver/PhD/Thesis/BackgroundSelection/Simulations/s_and_Pi/outputs/4.0.2_1.0.5/"

cd ${GeneralPath}
Directories=( HR OR OS ) # Array of directories ot be merged with the destination directory
Destination=HS
errorFile="${GeneralPath}MergeDirs.err"

### Do Stuff ###

for d in ${Directories[@]};do
    echo "${d}"
    cd $d
    for f in *; do
        echo "      ${f}"
        if [ ! -f "../${Destination}/${f}" ];then
            echo cp1
            cp ${f} ../${Destination}/
        else
            nblinesFrom=$(wc -l ${f} | awk -F" " '{print $1}')
            nblinesDest=$(wc -l "../${Destination}/${f}" | awk -F" " '{print $1}')
            if [ ${nblinesFrom} -gt ${nblinesDest} ]; then
                echo cp2
                cp ${f} ../${Destination}/
            elif [ ${nblinesDest} -gt ${nblinesFrom} ];then
                echo "Destination is bigger - nothing to do"
            else
                DoTheyDiffer=$(diff ${f} "../${Destination}/${f}" | wc -l)
                if [ ${DoTheyDiffer} -gt 0 ];then
                    echo "${f} and ../${Destination}/${f} diff but have the same number of lines" >> ${errorFile}
                fi
            fi
        fi
    done
    cd ..
done

My code seems quite complicated and I feel like a good combinaison of find -exec, awk, cp and diff might do something much more fancy.


texts: BeautifulSoup web spider for driver links

texts:
The following spider will grab some driver links, OS version, and the name.
All the info is in a table class, but some pages might be a little different in the location and Number of cells in each row.

I can't post the HTML page, but the main problem I'm facing now is that sometimes the number of the row I need is in cell 0 or 1. I know it should be simple to make the spider check but I just can't think of a way to make it into the current spider.

import bs4

def bkc_spider(path, start, stop):
    """BKC Spider - grabs driver names, links and OS version from BKC releases"""
    ver_lst = ['Win7', 'Win8.1', 'Win10', 'WinT', 'WinN']
    file = open(path, 'rb')
    drivers = {}
    rng_lst = [str(x) for x in range(start, stop)]

    soup = bs4.BeautifulSoup(file)

    table = soup.findAll('table')[0]
    for row in table.findAll('tr'):
        cells = row.findAll('td')
        if len(cells) > 4:
            cell_num = cells[1].get_text(strip=True)
            if any(cell_num == n for n in rng_lst):
                drv_name = cells[2].get_text(strip=True)
                drivers[drv_name] = {'links': []}
                for pTag in cells[4].findAll('p'):
                    try:
                        link = pTag.findNext('a')
                        link_os = pTag.find('span', {'class': 'MsoHyperlink'}).span.get_text(strip=True)
                        if any(link_os == ver for ver in ver_lst):
                            drivers[drv_name]['links'].append(link['href'] + " | " + link_os)
                        else:
                            drivers[drv_name]['links'].append(link['href'])
                        continue
                    except AttributeError:
                        drivers[drv_name]['links'].append(link['href'])
                        continue
    for x in drivers:
        print(x)
        for y in drivers[x]:
            print(drivers[x][y])
        print('\n')
    return drivers

html_file = r"BKC.htm"
bkc_spider(html_file, 6, 31)


texts: Simple server using async and HttpListener

texts:
I have a program that controls a custom machine. I wanted to add some simple HTTP comms so I could control it from the network or other programs.

My server class is:

public class Server
{
    private volatile bool stop = true;
    private Action<string> methodOne;

    public Server(Action<string> methodOne)
    {
        this.methodOne= methodOne;
    }

    public async Task StartAsync()
    {
        var prefix = "http://localhost:5005/";
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(prefix);
        try
        {
            listener.Start();
            stop = false;
        }
        catch (HttpListenerException hlex)
        {
            return;
        }
        while (listener.IsListening)
        {
            var context = await listener.GetContextAsync();
            try
            {
                await ProcessRequestAsync(context);
            }
            catch (Exception ex)
            {
                Console.WriteLine("# EXCEPTION #   " + ex.StackTrace);
            }
            if (stop == true) listener.Stop();
        }
        listener.Close();
    }

    public void Stop()
    {
        stop = true;
    }

    private async Task ProcessRequestAsync(HttpListenerContext context)
    {
        // Get the data from the HTTP stream
        var body = await new StreamReader(context.Request.InputStream).ReadToEndAsync();
        HttpListenerRequest request = context.Request;

        if (request.RawUrl.StartsWith("/methodOne"))
        {
            //Get parameters
            var options = context.Request.QueryString;
            var keys = options.AllKeys;
            //Run function
            methodOne("some method parameter");
            //Respond
            byte[] b = Encoding.UTF8.GetBytes("ack");
            context.Response.StatusCode = 200;
            context.Response.KeepAlive = false;
            context.Response.ContentLength64 = b.Length;
            var output = context.Response.OutputStream;
            await output.WriteAsync(b, 0, b.Length);
            context.Response.Close();
        }
    }
}

I initialise the Server by passing it the delegate for the function in the main view model that will be called, then start itwith server.StartAsync();

VS2017 gives me some advice that I didn't await server.StartAsync(); so thread will continue, but that is the functionality I want.

Any problems with making a server like this, using async and having it run on the main thread? All the server does is call methods in the view model, and there will usually be just one connection. The advantage for me is that being all on the same thread I don't have to worry about dispatching etc.


texts: Take element of a Set collection depending on the value of another element

texts:
I had to populate the fields of a Service object using a Set (HashSet) with any configuration parameters -> ConfigurationMap (Class with 2 attributes: key and value).
The problem is that the attribute quantity of Service object can be set from two distinct parameters ("service_quantity" or "publications_amount") based on the value of another parameter("type").
I've gotten it to work with the code below, but I think it's pretty messy and inefficient.
Is there any way to make it more readable considering that the methods signatures are invariable?
@Override
protected void populateServiceConfigurationData(Service theService, Set<ConfigurationMap> configurationParams) {
    boolean publishService = false;
    for (ConfigurationMap configParam : configurationParams) {
        String paramValue = configParam.getValue();
        String paramKey = configParam.getKey();
        setFieldValue(theService, paramKey, paramValue);
        if("type".equals(paramKey) && paramValue.equals("20")) {
            publishService = true;
        }
    }

    if(publishService) {
        for (ConfigurationMap configParam : configurationParams) {
            String paramKey = configParam.getKey();
            if(paramKey.equals("publications_amount")) {
                String paramValue = configParam.getValue();
                setFieldValue(theService, paramKey, paramValue);
            }
        }
    }
}

@Override
public void setFieldValue(Service service, String paramKey, String paramValue) {
    if ("type".equals(paramKey)) {
        service.setType(Integer.valueOf(paramValue));
    }
    if ("service_quantity".equals(paramKey) || "publications_amount".equals(paramKey)) {
        service.setQuantity(Integer.valueOf(paramValue));
    }
    if ("gateway_id".equals(paramKey)) {
        service.setGatewayId(paramValue);
    }
    if ("comissions".equals(paramKey)) {
        service.setCommissions(paramValue);
    }
}


texts:
Below is a portion of the code i have written to scrape the bikesales.com.au website for details of bikes for sales (The full code is here). This finds all the 'href' attributes on each search page and tries to request the html for each href corresponding to each bike for sale. My code works correctly, however I had to add some retry attempts with exponential backoff to avoid the following error:

ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)

The code works correctly, however I would like to avoid the backoff approach if possible.

from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup

def get_html_content(url, multiplier=1):
    """
    Retrieve the contents of the url.
    """
    # Be a responisble scraper.
    # The multiplier is used to exponentially increase the delay when there are several attempts at connecting to the url
    time.sleep(2*multiplier)

    # Get the html from the url
    try:
        with closing(get(url)) as resp:
            content_type = resp.headers['Content-Type'].lower()
            if is_good_response(resp):
                return resp.content
            else:
                # Unable to get the url response
                return None

    except RequestException as e:
        print("Error during requests to {0} : {1}".format(url, str(e)))

if __name__ == '__main__':

    baseUrl = 'https://www.bikesales.com.au/'
    url = 'https://www.bikesales.com.au/bikes/?q=Service%3D%5BBikesales%5D'

    content = get_html_content(url)
    html = BeautifulSoup(content, 'html.parser')
    BikeList = html.findAll("a", {"class": "item-link-container"})

    # Cycle through the list of bikes on each search page.
    for bike in BikeList:

        # Get the URL for each bike.
        individualBikeURL = bike.attrs['href']
        BikeContent = get_html_content(baseUrl+individualBikeURL)

        # Reset the miltipler for each new url
        multiplier = 1

        ## occasionally the connection is lost, so try again.
        ## Im not sure why the connection is lost, i might be that the site is trying to guard against scraping software.

        # If initial attempt to connect to the url was unsuccessful, try again with an increasing delay
        while (BikeContent == None):
            # Limit the exponential delay to 16x
            if (multiplier < 16):
                multiplier *= 2
            BikeContent = get_html_content(baseUrl+individualBikeURL,multiplier)

My question is, Is there something that i am missing in the implementation of the request? or, is this just a result of the site denying scraping tools?


texts: Is there something wrong with my remove-duplicates implementation in Scheme?

texts:
For an assignment I handed in this code to remove duplicates from a stream.

 (define (remove-duplicate lst)
  (cond ((stream-null? lst) '())
        ((not (member-stream? (stream-car lst) (stream-cdr lst)))
         (cons-stream (stream-car lst) (remove-duplicate (stream-cdr lst))))
        (else (remove-duplicate (stream-cdr lst)))))

(define (member-stream? item x)
  (cond ((stream-null? x) #f)
        ((eq? item (stream-car x)) x)
        (else (mems item (stream-cdr x)))))

Appearantly this isn't an ideal way to do this, but I can't see why. I tested it with a stream of numbers, and it correctly removed the duplicates and returned a stream.

stream-cons, stream-car, stream-cdr and stream-null are defined in the SICP book.


texts:
I'm doing a code-challenge problem:

Input
The first line consists of an integer T (T ≤ 100) which represents the number of test cases. Each test case consists of an integer N (5 ≤ N ≤ 100.000) which represents the number of integers, followed by a line that consists of N integers Ai (0 ≤ Ai ≤ 1000) separated by a space.
Output
For each test case, print in a line an integer that represents the sum of 5 largest numbers.

My code (below) works for small tests, but on the online judge, it resulted in Time Limit Exceeded. Some approaches I've tried that I think speed up the program (need confirmation):

Changing language from C++ to C (does it give significant boost?)
When calculating the sum, I use while instead of for loop (which one is more effective?)

#include <stdio.h>

int main () {
    int testCases;
    scanf("%d", &testCases);

    for (int i = 1; i <= testCases; i++) {
        int size, sum, temp, k, limit;
        sum = 0;
        temp = 0;
        scanf("%d", &size);

        int array[size];

        for (int i = 0; i < size; i++) {
            scanf("%d", &array[i]);
        }

        for (int i = 0; i < size; i++) {
            for (int j = i+1; j < size; j++) {
                if (array[j] < array[i]) {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                } else {
                    continue;
                }
            }
        }

        k = size - 1;
        limit = size - 6;

        while (k > limit) {
            sum += array[k];
            k--;
        }

        printf("%d\n", sum);
    }
}


texts:
Is this a correct way to copy elements from array origin to array location?
  #include <stdio.h>
   void copy(const int *origin, int *location, int n){
   int i;
   for(i=0;i<n;i++){
    location[i]=origin[i];
    }
  }


texts: Strictly typed dynamic proxy to call dynamic object

texts:
GitHub and NuGet

I would like to use DynamicObject derived types to execute  REST API/NodeJS module calls. It would also help to capture API shape in a strictly typed manner, so here comes an interface proxy which hides low level machinery allowing to do tricks like this:

[TestMethod]
public void Call()
{
    dynamic c = new ExpandoObject();
    c.Add = (Func<int, int, int>)((a, b) => a + b);

    ICalculator proxy = Proxy.Create<ICalculator>(c);
    Assert.AreEqual(3, proxy.Add(1, 2));
}

public interface ICalculator
{
   int Add(int a, int b);
}

Library code is:

using Castle.DynamicProxy;
using Dynamitey;
using System;

namespace Dynoproxy
{
    public static class Proxy
    {
        public static T Create<T>(this object source) where T : class
        {
            var proxyGenerator = new ProxyGenerator();
            return proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(
                ProxyGenerationOptions.Default,
                new Interceptor(source));
        }

        class Interceptor : IInterceptor
        {
            public Interceptor(object target) => Target = target;
            object Target { get; }
            public void Intercept(IInvocation invocation) =>
                invocation.ReturnValue = Dynamic.InvokeMember(
                    Target, invocation.Method.Name, invocation.Arguments);
        }
    }
}


texts:
I'm running a package that downloads data from the internet.  This package makes logging calls from different modules.

Suppose I have a package 'demopackage'.  Here is how my logging is currently set up. Is it possible to improve this way of working?  The main.py script runs triggered by a cron job.

demopackage/init.py

""" __init__.py """

import logging
from demopackage.core import Logs

Logs.config_root_logger()

I set up 3 handlers, a console handler with color, a file handler, and an email handler for critical log entries (Amazon SES handler).  I would prefer the stream and file handler to inherit a handler like the email handler.

demopackage/core.py

import boto.ses
import coloredlogs

class Logs:
    fs_head = '%(asctime)s.%(msecs)03d %(levelname)1.1s L%(lineno)d '
    fs = fs_head + '%(filename)s %(funcName)s %(name)s | %(message)s'
    dfs = '%d/%m/%y %H:%M:%S'
    formatter = demopackage.logging.Formatter(fmt=fs, datefmt=dfs)

    @staticmethod
    def config_root_logger():
        log = demopackage.logging.getLogger()
        # configure file handler
        logpath = demopackage.os.path.join('demopackage.log')
        rfh = demopackage.logging.handlers.RotatingFileHandler(logpath)
        rfh.maxBytes = 1000000000  # about 1 GB
        rfh.backupCount = 2
        rfh.mode = 'a'
        rfh.setFormatter(Logs.formatter)
        rfh.setLevel('INFO')
        log.addHandler(rfh)

        # configure email handler
        smtp_handler = Logs.demopackage_SESHandler()
        smtp_handler.setFormatter(Logs.formatter)
        smtp_handler.setLevel('CRITICAL')
        log.addHandler(smtp_handler)
        # configure root logger StreamHandler
        # blue, cyan, green, magenta, red, white and yellow
        level_dict = {'debug': {'color': 'blue'},
                      'info': {'color': 'green'},
                      'warning': {'color': 'yellow'},
                      'error': {'color': 'red', 'bold': True},
                      'critical': {'color': 'magenta', 'bold': True}}
        field_dict = {'asctime': {'color': 'green'},
                      'levelname': {'color': 'white', 'bold': True},
                      'lineno': {'color': 'red'},
                      'filename': {'color': 'cyan'},
                      'funcName': {'color': 'magenta'},
                      'name': {'color': 'green'}}
        coloredlogs.install(fmt=Logs.fs, datefmt=Logs.dfs,
                            level_styles=level_dict,
                            field_styles=field_dict)
        log.info('stream handler initialized with coloredlogs module')
        log.info('root logger file handler to {}'.format(logpath))
        log.info('root logger smtp handler for AWS SES')

    class demopackage_SESHandler(demopackage.logging.Handler):
        """
        A handler class which sends an email to Amazon SES for logging events.
        """
        def __init__(self):
            """ Initialize the handler. """
            demopackage.logging.Handler.__init__(self)

        def emit(self, record):
            """
            Emit a record.
            Format the record and send it to the specified addressees.
            """
            try:
                key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                conn = boto.ses.connect_to_region(
                    'eu-west-1',
                    aws_access_key_id='XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
                    aws_secret_access_key=key)
                message = self.format(record)
                subject = 'Critical error in ' + record.pathname
            conn.send_email('from@sender.com', subject, message,
                            'to@receiver.com')
            except Exception:
                self.handleError(record)

logging calls in any module:

import demopackage

log = demopackage.logging.getLogger('dwh.get_data.py')

log.info('some text')
log.error('some error raising an exception')
log.critical('critical error with email alert')


texts: Using Data.Array to solve Sierpinski in Haskell

texts:
Here is an earlier attempt to solve the original problem:
Solving Sierpinski Triangle in Haskell

I was never satisfied with my solution and found it was awkward and twisty. Here is another attempt to solve the same problem using Data.Array and I found that by using mutable arrays the solution becomes much shorter and easy to read.

import qualified Data.Array as DA (Array, listArray, (//), assocs)
import qualified Data.List as DL (groupBy, intercalate)
import qualified Data.Function as DF (on)

type Point = (Int, Int)
data Triangle = Triangle { up :: Point, height :: Int } deriving Show
type Canvas = DA.Array Point Char

emptyCanvas maxLevel = DA.listArray ((0, 1-h), (h-1, h-1)) $ repeat '_'
  where
    h = 2^maxLevel -- 1*(2^maxLevel)

drawTriangle :: Triangle -> Canvas -> Canvas
drawTriangle (Triangle (r, c) h) canvas = foldr drawLine canvas $ map line [1..h]
  where
    line h = let h' = h-1 in [(r+h', j) | j <- [c-h'..c+h']]
    drawLine l c = c DA.// map (\p -> (p, '1')) l

drawCanvas :: Canvas -> IO ()
drawCanvas canvas = putStrLn pic
  where
    rows = DL.groupBy ((==) `DF.on` (fst . fst)) . DA.assocs
    pic = DL.intercalate "\n" $ map (map snd) (rows canvas)

split hLvl (r, c) = let w = 2^(hLvl-1) in [(r, c), (r+w, c-w), (r+w, c+w)]

splitSier maxLevel (sierLevel, ts) = (sierLevel+1, ts')
  where
    ts' = ts >>= (split (maxLevel-sierLevel))

mkSierpinski :: Int -> Int -> Canvas
mkSierpinski maxLevel sierLevel
  | maxLevel >= sierLevel = foldr drawTriangle c $ allTriangles
  | otherwise = c
  where
    c = emptyCanvas maxLevel
    (l', ts') = head $ drop sierLevel $ iterate (splitSier maxLevel) (0, [(0, 0)])
    allTriangles = map (\p -> Triangle p (2^(maxLevel-l'))) ts'

main = do
    sierLevel <- readLn
    drawCanvas $ mkSierpinski 5 sierLevel

The idea is to model the canvas by a 2-D array of Characters and attempt to draw easy individual triangles on top of the empty canvas. In this solution it starts with one big triangle and keep splitting to generate Sierpinski pattern. Another solution that I didn't post here attempts to solve it by starting with the smallest triangle at the top, and repeatedly copy what is current on canvas to its lower left corner and lower right corner. Both solutions look very similar at the end.

Please let me know if you have suggestions. Thank you in advance.


texts:
I recently submitted a code-challenge for an interview according to the following guidelines:

About

Write a function or method that accepts two mandatory arguments and returns a result.

Requirements:

Use Ruby or another language of your choosing, and write production quality code.
Your function or method should not use any date/time library.
The first argument is a time value in the form of a string with the following format: [H]H:MM {AM|PM}
The second argument is the number of minutes, as an integer value
The return value of the function should be a string of the same format as the first
argument, which is a result of adding the minutes to the time.

For example, add_minutes('9:13 AM', 10) would return 9:23 AM

Additional notes:

We just want to see how you code, so this exercise is not meant to be too hard or take too long.
If you spend an hour on this, stop coding and finalize by adding some notes about what you would do if you had more time.

Although my Ruby proficiency has somewhat atrophied due to primarily working with php for the last 8 months, I was able to produce the following well-within one-hour of beginning the challenge:

# FIRST ATTEMPT

# require 'time'

# def flux_capacitor(time,mins)
#   the_time = Time.parse(time.to_s)
#   mins = the_time + 10*60
# end

# FINAL REFACTOR

def flux_capacitor(time,mins)
  the_time = time.scan(/\d/).join('').to_i
  meridian = time.scan(/(A|M|P)/).join('')
  new_time = the_time + mins
  back_in_time = new_time.to_s.insert(-3,':') + " #{meridian}"
end

puts flux_capacitor("9:13 AM",10)
puts flux_capacitor("9:13 PM",10)
p flux_capacitor("10:13 PM",10).class

# DOX

# http://ruby-doc.org/core-2.2.3/Time.html
# https://www.ruby-forum.com/topic/125709
# https://www.ruby-forum.com/topic/104359
# http://apidock.com/ruby/String/insert
# http://rubular.com/

Simply-stated, is there a better approach?  I've asked others and they think my solution is fairly clean.  Obviously, I know my solution could benefit with a conditional statement for edge cases (e.g. flux_capacitor("9:50 AM", 15)).


texts: Order and visibility tracking algorithm (e.g. scope visibility)

texts:
I have a tree of objects.

Object id:0 Object type:0
  Object id:1 Object type:0
    Object id:3 Object type:0
  Object id:2 Object type:0
    Object id:4 Object type:0
    Object id:5 Object type:0

For each object I have a method that returns its "index" in the tree down to the root item.

Indices:

0 - 0
1 - 0 0
2 - 0 1
3 - 0 0 0
4 - 0 1 0
5 - 0 1 1

I need to be able to check for "visibility" from one object to another object, with the rules being pretty much identical to those of C/C++ scopes. E.g. the root item is like a global, so it should be visible to every other items, and items are only visible to items on their level or higher as long as they are in the same branch.

In short:

0 - visible to all
1 - visible to 2, 3, 4, 5
2 - visible to 4, 5
3 - visible to none
4 - visible to 5
5 - visible to none

After some trial and error I came up with this code, and it does seem to work as expected given the above tree hierarchy.

bool isVisibleTo(Node * accessor) {
    QList<uint> accessedI = getIndex();
    QList<uint> accessorI = accessor->getIndex();
    if (accessedI.size() > accessorI.size()) return false; // item is deeper than its accessor
    else if (accessedI.size() == accessorI.size()) { // same size - check if all but the last are compatible
        for (int i = 0; i < accessedI.size() - 1; ++i) if (accessedI.at(i) != accessorI.at(i)) return false; // indecies not identical
        if (accessedI.last() > accessorI.last()) return false; // identical, but accessor index is larger
    }
    for (int i = 0; i < accessorI.size() - (accessorI.size() - accessedI.size()); ++i) {
        if (accessedI.at(i) > accessorI.at(i)) return false; // wrong subtree
    }
    return true;
}

test output:

node  0 is visible to node  0
node  0 is visible to node  1
node  0 is visible to node  2
node  0 is visible to node  3
node  0 is visible to node  4
node  0 is visible to node  5
node  1 is visible to node  1
node  1 is visible to node  2
node  1 is visible to node  3
node  1 is visible to node  4
node  1 is visible to node  5
node  2 is visible to node  2
node  2 is visible to node  4
node  2 is visible to node  5
node  3 is visible to node  3
node  4 is visible to node  4
node  4 is visible to node  5
node  5 is visible to node  5

But still, I am fairly new and inexperienced to programming, so any notes, corrections and recommendations are welcome.


texts:
I have written the Rabin-Miller test in Python and ported it to C. But somehow, the C version is ~20 times slower on my system, and I am not sure how. Anyway, here is my code.

Python

import random
import time

def rabin_miller(n):
    if n in [2, 3, 5]:
        return True
    if n < 2 or n % 2 == 0:
        return False

    s = 0
    d = n - 1
    while d % 2 == 0:
        s += 1
        d >>= 1

    for k in range(2 ** 4):
        a = random.randrange(2, n - 1)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        c = False
        for r in range(s - 1):
            x = pow(x, 2, n)
            if x == 1:
                return False
            if x == n - 1:
                break
        else:
            return False
    return True

for i in range(10000):
    rabin_miller(i)

C

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

long mod_pow(long b, long e, long m){
    if(m == 1)
        return 0;
    long c = 1;
    for(long i = 0; i < e; i++)
        c = (c * b) % m;
    return c;
}

int rabin_miller(long n){
    if(n == 2 || n == 3)
        return 1;
    if(n < 2 || n % 2 == 0)
        return 0;

    long s = 0, d = n - 1, k = 10, a, x, stop;
    while(d % 2 == 0)
        s += 1, d >>= 1;

    srand(time(NULL));
    for(long i = 0; i < k; i++){
        a = (long) (((float) rand() / RAND_MAX) * (n - 3)) + 2;
        x = mod_pow(a, d, n);
        if(x == 1 || x == n - 1)
            continue;
        stop = 1;
        for(long r = 0; r < s - 1; r++){
            x = mod_pow(x, 2, n);
            if(x == 1)
                return 0;
            if(x == n - 1){
                stop = 0;
                break;
            }
        }
        if(stop){
            return 0;
        }
    }
    return 1;
}

int main(int argc, char *argv[]){
    for(long i = 1; i < 10000; i++){
        rabin_miller(i);
    }
    return 0;
}


texts: WIP library that will encrypt some text for the purpose of obfuscating my code


texts: Response structure with populated fields

texts:
I am working on a backend for an application using a microservice framework with Sequelize and it is populating in the following way (it does based on the table field):

{
   "resourceId":{
      "name":"Serra Eléctrica",
      "unitId":{
         "id":2,
         "name":"Hora"
      },
      "resourceTypeId":{
         "id":8,
         "name":"Patrimoniais"
      }
   },
   "quantity":8,
   "price":"9.00",
   "vat":"0.00"
}

The frontend developer said that this is bad because the objects are inside fieldId like resourceId.unitId.id instead of resource.unit.id. Is this really bad or is it actually irrelevant?


texts: Finding person with most medals in Olympics database

texts:
I have an Olympics database from each Olympic year and I want to find the person that has won the most medals.  The main problem is that I'm basically querying the same sub-query twice in SUBSET1 and SUBSET2. How would I go about making this more efficient?

Select athlete  FROM ( Select athlete, Sum(total_medals) as total_medals
from Olympics Group by athlete) as SUBSET1 Where total_medals =
( Select Max( total_medals ) FROM ( Select Sum(total_medals) as total_medals
from Olympics    Group by athlete ) as SUBSET2);


texts: How can I optimize this combination method?

texts:
I have this method that is working perfectly fine, but it's very slow, and sometimes I have to wait 15 minutes to get a good result, which is ok.  I'm wondering if I can make it faster.

Basically I'm running best fleet simulations, and I pre-calculate the possible ship combinations for specific voyages, but then I have to get the best fleet combinations for multiple voyages.

Obviously I can't use the same captain or crew in different ships because the voyages take place at the same time, and that's why there's some more conditions in each inner loop.

private static Ship[] GetBestFleet3(IList<Voyage> voyages)
{
    var bestRate = 0;
    var worstVariance = 100.0;
    Ship[] fleet = null;
    foreach (var ship0 in voyages[0].Ships)
    {
        foreach (var ship1 in voyages[1].Ships.Where(s1 => !s1.Equals(ship0)))
        {
            foreach (var ship2 in voyages[2].Ships.Where(s2 => !s2.Equals(ship0) && !s2.Equals(ship1)))
            {
                var variance = Statistics.Variance(ship0, ship1, ship2);
                var rate = ship0.Rate + ship1.Rate + ship2.Rate;
                if (rate >= bestRate || rate == bestRate && variance < worstVariance)
                {
                    bestRate = rate;
                    worstVariance = variance;
                    fleet = new[] { ship0, ship1, ship2 };

                    if (ship0.Rate >= 100 && ship1.Rate >= 100 && ship2.Rate >= 100)
                    {
                        return fleet;
                    }
                }
            }
        }
    }
    return fleet;
}

voyages is basically an array of voyages with possible ship combinations for each voyage.

Gist with all the relevant project files: https://gist.github.com/alfaproject/cb68e6fa1c21e1f93bf7


texts: Traversing two trees until a common value has been found

texts:
I am traversing two objects that may share a common ancestor. To make the code small enough to show here, I have changed it into two dictionaries with values. As you can see, a_d and b_d are the inverse of each other. The idea is to step into each dictionary step by step until we find an overlapping value for the two. At each step the 'distance' is increased.

For the example case get_distance('b', 'y'), the output will print (comments added):

# init
start= b
end= y

# both a and b changed value (dist +1 for both) but no overlap found
start= c
end= x

# both a and b changed value (dist +1 for both) and an overlap was found!
start= d
end= d

Found overlap d
connected True

I hope that it is clear what this code does and what I am trying to do. Please keep in mind that the actual code works with elaborate objects and their properties, but the idea is similar. The issue that I am having is that the code is very repetitive and probably not as efficient as it could be. But I am not sure how I can improve on it. Ideas welcome!

def get_distance(start, end):
    start_d = {
        'a': 'b',
        'b': 'c',
        'c': 'd',
        'd': 'x',
        'x': 'y',
        'y': 'z',
        'z': 'z'
    }

    end_d = {
        'z': 'y',
        'y': 'x',
        'x': 'd',
        'd': 'c',
        'c': 'b',
        'b': 'a',
        'a': 'a'
    }

    connected = False
    start_dist = 0
    end_dist = 0
    while True:
        print('start=', start)
        print('end=', end)
        print()

        # Check whether a and b are the same, if so break
        if start == end:
            print(f"Found overlap {end}")
            connected = True
            break
        # Check whether the next a value is the same as b, if so break and increase a_dist
        elif start_d[start] == end:
            print(f"Found overlap {end}")
            start_dist += 1
            connected = True
            break
        # Check whether the next b value is the same as a, if so break and increase b_dist
        elif end_d[end] == start:
            print(f"Found overlap {start}")
            end_dist += 1
            connected = True
            break

        # If for a and b all options are exhausted, break
        if start == start_d[start] and end == end_d[end]:
            break

        # If a is not exhausted, get its dict value and increase distance
        if start != start_d[start]:
            start_dist += 1
            start = start_d[start]

        # If b is not exhausted, get its dict value and increase distance
        if end != end_d[end]:
            end_dist += 1
            end = end_d[end]

    dist = start_dist + end_dist
    print('connected', connected)
    return dist

if __name__ == '__main__':
    dist = get_distance('b', 'y')


texts:
I've written a short library for manipulating matrices for 3D drawing. I've tried to strike a balance between speed and readability. Anything to improve?

%!
%mat.ps
%Matrix and Vector math routines

/ident { 1 dict begin /n exch def
    [
    1 1 n { % [ i
        [ exch % [ [ i
        1 1 n { % [ [ i j
            1 index eq { 1 }{ 0 } ifelse % [ [ i b
            exch % [ [ b i
        } for % [ [ b+ i
        pop ] % [ [ b+ ]
    } for % [ [b+]+ ]
    ]
end } def

/rotx { 1 dict begin /t exch def
    [ [ 1  0      0         ]
      [ 0  t cos  t sin neg ]
      [ 0  t sin  t cos     ] ]
end } def

/roty { 1 dict begin /t exch def
    [ [ t cos      0  t sin ]
      [ 0          1  0     ]
      [ t sin neg  0  t cos ] ]
end } def

/rotz { 1 dict begin /t exch def
    [ [ t cos  t sin neg  0 ]
      [ t sin  t cos      0 ]
      [ 0      0          1 ] ]
end } def

/.error where { pop /signalerror { .error } def } if

/dot { % u v
    2 copy length exch length ne {
        /dot cvx /undefinedresult signalerror } if
    % u v
    0 % u v sum
    0 1 3 index length 1 sub { % u v sum i
        3 index 1 index get exch % u v sum u_i i
        3 index exch get % u v sum u_i v_i
        mul add % u v sum
    } for % u v sum
    3 1 roll pop pop % sum
} bind def

% [ x1 x2 x3 ] [ y1 y2 y3 ]  cross  [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2-x2*y1 ]
/cross { % u v
    dup length 3 ne 2 index length 3 ne or {
        /cross cvx /undefinedresult signalerror } if
    % u v
    exch aload pop 4 3 roll aload pop % x1 x2 x3 y1 y2 y3
    [
        5 index 2 index mul % ... [ x2*y3
        3 index 6 index mul sub % ... [ x2*y3-y2*x3
        5 index 5 index mul % ... [ x2*y3-y2*x3 x3*y1
        8 index 4 index mul sub % ... [ x2*y3-y2*x3 x3*y1-x1*y3
        8 index 5 index mul % ... [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2
        8 index 7 index mul sub % ... [ x2*y3-y2*x3 x3*y1-x1*y3 x1*y2-x2*y1
    ]
    7 1 roll 6 { pop } repeat
} bind def

/transpose { STATICDICT begin
    /A exch def
    /M A length def
    /N A 0 get length def
    [
    0 1 N 1 sub { /n exch def
        [
        0 1 M 1 sub { /m exch def
            A m get n get
        } for
        ]
    } for
    ]
end } dup 0 6 dict put def

/matmul { STATICDICT begin
    /B exch def
    B 0 get type /arraytype ne { /B [B] def } if
    /A exch def
    A 0 get type /arraytype ne { /A [A] def } if
    /Q B length def
    /R B 0 get length def
    /P A length def
    Q A 0 get length ne {
        /A A transpose def
        /P A length def
        Q A 0 get length ne {
            A B end /matmul cvx /undefinedresult signalerror
        } if
    } if

    [
    0 1 P 1 sub { /p exch def % rows of A
        [
        0 1 R 1 sub { /r exch def % cols of B
            0
            0 1 Q 1 sub { /q exch def % terms of sum
                A p get q get
                B q get r get mul
                add
            } for
        } for
        ]
    } for
    ]

end } dup 0 10 dict put def

%u v {operator}  vop  u(op)v
%apply a binary operator to corresponding elements
%in two vectors producing a third vector as result
/vop { 1 dict begin
    /op exch def
    2 copy length exch length ne {
        /vop cvx end /undefinedresult signalerror
    } if

    [ 3 1 roll % [ u v
    0 1 2 index length 1 sub { % [ ... u v i
        3 copy exch pop get % u v i u_i
        3 copy pop get      % u v i u_i v_i
        op exch pop         % u v u_i(op)v_i
        3 1 roll            % u_i(op)v_i u v
    } for % [ ... u v
    pop pop ]

end } def

%length of a vector
/mag { 0 exch { dup mul add } forall } def

/elem { % M i j
    3 1 roll get exch get % M_i_j
} def

/det {
    dup length 1 index 0 get length ne { /det cvx /typecheck signalerror } if
    1 dict begin /M exch def
        M length 2 eq {
            M 0 0 elem
            M 1 1 elem mul
            M 0 1 elem
            M 1 0 elem mul sub
        }{
            M length 3 eq {
                M aload pop cross dot
            }{ /det cvx /rangecheck signalerror } ifelse
        } ifelse
    end
} def


texts:
Description

  A robot lands on Mars, which happens to be a cartesian grid; assuming that we hand the robot these instructions, such as LFFFRFFFRRFFF, where "L" is a "turn 90 degrees left", "R" is a "turn 90 degrees right", and "F" is "go forward one space, please write control code for the robot such that it ends up at the appropriate-and-correct destination, and include unit tests.

Here is an example output with command "FF":

[0, 2]

Code

class Robot {
  private int x;
  private int y;
  private int currentDirection;

  Robot() {
    this(0, 0);
  }

  Robot(int x, int y) {
    this.x = x;
    this.y = y;
    currentDirection = 0;
  }

  public void move(String moves) {
    for (char ch : moves.toCharArray()) {
      if (ch == 'R') currentDirection += 1;
      if (ch == 'L') currentDirection -= 1;

      currentDirection = currentDirection % 4;

      if (ch != 'F') continue;

      System.out.println(currentDirection);
      if (currentDirection == 0) {
        y += 1;
      } if (currentDirection == 1) {
        x += 1;
      } if (currentDirection == 2) {
        y -= 1;
      } if (currentDirection == 3) {
        x -= 1;
      }
    }
  }

  public void reset() {
    x = 0;
    y = 0;
    currentDirection = 0;
  }

  public String position() {
    return x + ":" + y;
  }
}

class Main {
  public static void main(String[] args) {
    Robot robot = new Robot();
    robot.move("FF");
    System.out.println(robot.position()); // 0,2
    robot.reset();
    System.out.println(robot.position()); // 0,0
    robot.move("FFRF");
    System.out.println(robot.position()); // 1,2
    robot.reset();
    robot.move("FFRRRFF");
    System.out.println(robot.position()); // -2,2
  }
}

How can I make this code more object oriented?


texts: Method that compares the scores of two players

texts:
I tackled this problem today and was wondering how I could possibly improve this code.
The objective of the method is to return an array with the respective scores of each player. The method takes three values from 2 users. a0,a1,a2 are all scores from player a. b0,b1,b2 are all scores of player b.

A player is awarded a point if their score of the same category is bigger than the score of the player.
For example to determine who got a better first score we must compare a0 with b0 and so on forth.

Here is my code:

static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2){
        int p1 = 0;
        int p2 = 0;
        if(a0 > b0){
            p1++;
        }else if(a0 < b0){
            p2++;
        }

        if(a1 > b1){
            p1++;
        }else if(a1 < b1){
            p2++;
        }

        if(a2 > b2){
            p1++;
        }else if(a2 < b2){
            p2++;
        }

        return new int[]{p1,p2};

    }


texts: Number of way to render an amount of money

texts:
I made an algorithm to train my skill in dynamic programming and I would like to have feed back on it. This algorithm takes a money system (int) and have a certain amount of money to render.

Do you see any problems in this code?

public static int wayToRenderMemo(int[] array, int i, double cost, HashMap memo) {
    if(i>=array.length) {
        return 0;
    }
    else if(cost < 0) {
        return 0;
    }
    else if(cost == 0) {
        return 1;
    }
    else if(memo.containsKey(String.valueOf(i)+":"+String.valueOf(cost))) {
        return (int) memo.get(String.valueOf(i)+":"+String.valueOf(cost));
    }
    else {
        int res = 0;
        for(int j = 0; j < array.length; j++) {
            res += wayToRenderMemo(array, i+j, cost-array[j], memo);
        }
        memo.put(String.valueOf(i)+":"+String.valueOf(cost), res);
        return res;
    }
}

public static void main(String []args) {
    int[] array = {1, 2, 5, 10, 20, 50, 100};

    double amountOfMoneyToRender = 20;
    System.out.println("Number of way to render "+amountOfMoneyToRender+"€ with the following system : "+Arrays.toString(array));
    HashMap memo = new HashMap();
    long t3 = System.currentTimeMillis();
    System.out.println(wayToRenderMemo(array, 0, amountOfMoneyToRender, memo));
    long t4 = System.currentTimeMillis();
    double time2 = (t4-t3)/1000.0;
    System.out.println("Result found in : "+time2+"seconds");
}


texts: Comparing values of equal-length tuple and list

texts:
I have a function that compares the values of a tuple and a list of equal length. It compares each value in combination to see if it is equal to its respective value in the path or if the value in combination is '*', that is valid.

So for example: combination=('dog', 'cat', '*'), path=['dog', 'cat', 'bird'] would return True.

What I have is below and works fine, but is there a better way to accomplish this?

def _is_valid_combination(combination, path):
    """
    Check if the combination is valid for the path

    Keyword arguments:
    combination -- tuple of pattern combination
    path -- list of the actual path
    """
    index = 0
    for part in combination:
        if (part == path[index]) or ('*' == part):
            index += 1
            continue
        else:
            return False
    return True