texts: High CPU utilisation for Logs Manager shell script

texts:
I have written a shell script to manage the tcpdump pcap logs and syslog files in my Linux board, so as to maintain the disk usage to maximum of 70%.

The script checks for the disk usage every minute and as soon as the disk goes higher than 70%, it deletes all the oldest files that are not in use until the disk usage goes back to 70%.

#!/bin/ash

#Gives the file that is currently in use by the process
logmgr_get_current_file_name() {
    PROC_NAME=$1
    instance=$2

    pid=$(ps | grep $PROC_NAME | grep -v grep | awk 'NR=='$instance'{print $1}')

    fds=$(ls /proc/$pid/fd)

    for fd in $fds;
    do
        last=$fd
    done

    current_file=$(ls /proc/$pid/fd/$last -l | awk 'BEGIN {FS="->"} {printf $2}')
}

#checks whether the file we are deleting is in use by the process
logmgr_is_file_in_use() {
    num_of_instances=1
    logmgr_get_current_file_name $1 $num_of_instances
    if [ $current_file = $2 ]; then
        return 1
    else
       return  0
    fi
}

# iterate through all possible instances of tcpdump
# for each instance .. get the file in use
# check if [ $file_in_use == $to_delete ] ; then
# return 1
# else
# return 0
logmgr_get_files_in_use() {
    i=1
    is_file_inuse=0

    num_of_instances=$(ps | grep tcpdump| grep -v grep | wc -l)

    while [ $i -le $num_of_instances ];
    do
        logmgr_get_current_file_name $1 $i
        if [ "$current_file" = "$2" ]; then
            is_file_inuse=1
            break
        fi
                i=`expr $i + 1`
        done
        return $is_file_inuse
}

logmgr_delete_oldest() {

    oldest=$(ls -lht $2 | awk 'END{print $9}')
    to_delete=$2$oldest

    if [ "$1" != "tcpdump" ] ; then
        logmgr_is_file_in_use $1 $to_delete
        ret_val=$?
    else
        logmgr_get_files_in_use $1 $to_delete "tcpdump"
        ret_val=$?
    fi

    #if the file is not in use, then delete it
    if [ $ret_val -eq 0 ]; then
        echo "$to_delete deleted"
        rm -fr $to_delete
        sleep $cpu_relaxation_secs
    fi

}

logmgr_get_disk_usage() {
    diskusage=$(df -h $1 | awk 'END {print $5}' | awk 'BEGIN {FS="%"} {print $1}')
    echo $diskusage
}

    ##requires repeated execution######
logmgr_run() {

    sleep_secs=0

    while [ 1 ] ;
    do
        syslog_dir_is_ok=0
        tcpdump_dir_is_ok=0

        syslog_disk_usage=`logmgr_get_disk_usage $syslog_dir`
        tcpdump_disk_usage=`logmgr_get_disk_usage $tcpdump_dir`

        if [ $syslog_disk_usage -le $NORMAL_DISK_USAGE ] ; then
            syslog_dir_is_ok=1
        fi

        if [ $tcpdump_disk_usage -le $NORMAL_DISK_USAGE ] ; then
            tcpdump_dir_is_ok=1
        fi

        if [ $syslog_dir_is_ok -eq 0 ] && [ $tcpdump_dir_is_ok -eq 0 ] ; then
            break
        fi

        if [ $syslog_dir_is_ok -eq 0 ] ; then
            num_files=`ls -lht $syslog_dir | wc -l`
            logmgr_delete_oldest "syslogd" $syslog_dir $num_files
        fi

        if [ $tcpdump_dir_is_ok -eq 0 ] ; then
            num_files=`ls -lht $tcpdump_dir | wc -l`
            logmgr_delete_oldest "tcpdump" $tcpdump_dir $num_files
        fi
    done
}

##Default values##

max_file_safe=100
cpu_relaxation_secs=1
timer_secs=60   # one minute
KEEP_CHECKING=1
NORMAL_DISK_USAGE=20

# read the configuration file
syslog_dir=`uci get syslog.slog.directory`
syslog_dir=`dirname $syslog_dir`"/"`basename $syslog_dir`"/"
tcpdump_dir=`uci get tcpdump.tcpdump.log_dir`
tcpdump_dir=`dirname $tcpdump_dir`"/"`basename $tcpdump_dir`"/"

#while [ $KEEP_CHECKING -eq 1 ]
while :
do
    logmgr_run
    sleep $timer_secs
done

The script is sequential and works perfectly fine but the CPU utilisation gets higher to about 75% while running the script. I tried to remove all the redundancies in script but still not successful in achieving the desired result.

I am sure there are ways with which I can achieve this, but am not sure how. Please suggest some ways to optimise this script and reduce my CPU utilisation.


texts:
I've been playing around and reading up on some sorting algorithms, and I've decided to try writing my own.  It turned out to be quite fast (compared to the others shown in the image below).

I'm very curious to know a little bit about it:

Does my algorithm already have a name?
What are the downsides to it (other than it being really stupid to sort { 900000, 1 } with it)?
Why is it not a good solution in general?
Any suggestions for optimisation?

static int[] MySort(int[] input)
{
    int minValue = input.Min() - 1;
    int[] tempArr = new int[input.Max() - minValue];
    //{1,3,3,5}   becomes:
    //{1,0,2,0,1} one 1's, two 3's, one 5's.
    for (int i = 0; i < input.Length; i++)
        tempArr[input[i] - minValue - 1] += 1;
    //AddNumbers to old array. and add minValue.

    int g = 0;
    for (int j = 0; j < tempArr.Length; j++)
    {
        if (tempArr[j] != 0)
        {
            for (int i = 0; i < tempArr[j]; i++)
            {
                input[g] = j + minValue + 1;
                g++;
            }
        }
    }
    return input;
}

Performance screenshot:


texts:
We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.

gHappy("xxggxx") → true
gHappy("xxgxx") → false
gHappy("xxggyygxx") → false

I have written two functions to solve this problem, but I have some concerns:

Of the one with Regex, I don't like all the special cases.
Of the one with iteration, I don't like the weird helper method.

Both pass a fair number of tests and work correctly. Which one is better?

regex_geppy.rb

def geppy(string)
  return true if ! string.include?('g')
  return false if [0, 1].include?(string.length)
  return false if string.length == 2 && string != 'gg'
  return (not string.match("[^g]g[^g]"))
end

array_geppy.rb

def non_wrap_get(array, index)
  index < 0 ? nil : array[index]
end

def geppy(string)
  string
    .chars
    .each_with_index
    .all? { |curr, i|
      curr == 'g' ?
        non_wrap_get(string, i - 1) == 'g'  || non_wrap_get(string, i + 1) == 'g'
        : true
    }
end

geppy_tests

geppy("xxggxx") #=> true
geppy("xxgxx") #=> false
geppy("xxggyygxx") #=> false
geppy("g") #=> false
geppy("ag") #=> false
geppy("gg") #=> true
geppy("") #=> true
geppy("ab") #=> true
geppy("aaaa") #=> true
geppy('g'*1000) #=> true


texts:
I wrote yet another optimized single-threaded Eratosthenes Sieve implementation in C:

erato.c

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

#define N 1000000000
#define num_t unsigned long

int main() {
    register char *b = malloc(N * sizeof(char));
    for(num_t i = 0; i ^ N; ++i)
        b[i] = !(i & 1);

    // printf("2\n");
    for(num_t i = 3; i ^ 1 ^ N; i += 2) {
        if(!b[i - 2]) {
            // printf("%llu\n", i);
            const num_t increment = i << 1;
            num_t j = i;
            while(j < N) {
                b[j - 2] = 1;
                j += increment;
            }
        }
    }
    free(b);
    return 0;
}

The output is omitted because it takes most of the time to process.

Optional flags: -O3

Performance

The sieve covers first 1.000.000.000 numbers in

  11.14s user 0.32s system 99% cpu 11.465 total

Could you please help me to improve my programming/mathematical skills by reviewing this piece of code?


texts: Length of a C string, capped to some maximum

texts:
If I have a oneliner in C such as

size_t maxSizeOf(const char *s)
{
     return strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s);
}

would it be better to have a macro defined such that

#define MAX_SIZE_OF(s) (strlen(s) > M_MAX_SIZE ? M_MAX_SIZE : strlen(s))

or would it be better to have

size_t maxSizeOf(const char *s)
{
     size_t len = strlen(s);
     return len > M_MAX_SIZE ? M_MAX_SIZE : len;
}

Also, is there a way to turn the second function into a macro for maximum efficiency?


texts: Array-based unordered list implementation in Java

texts:
This class, UnorderedList, implements an Unordered list in Java. In this class, duplicates are allowed. remove(argument) will delete the first occurrence of the argument. I was wondering to add other functions named add(int index, int data) and set(int index, int data) or not. Since the class is unordered, I thought I would not need it. The size of the class is limited although that does not concern me (UnorderedLinkedList coming up next).

I tried to make sure all the functionality and behaviours are correct. If this class is lacking any method(s) and/or correct usage of exception and anything else please comment below. Any kind of suggestions and advice is appreciated.

//Node class

package lists.arrayLists.unorderedList;

public class Node
{
    private int data;

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

    public int getData()
    {
        return data;
    }
}

//UnorderedList class

package lists.arrayLists.unorderedList;

import java.lang.IndexOutOfBoundsException;
import java.util.NoSuchElementException;

public class UnorderedList
{
    public static final int MAX_SIZE = 100;
    private int size;
    private Node[] nodeElements;
    private int currentIndex;                           // to navigate/iterate over list

    public UnorderedList()
    {
        nodeElements = new Node[MAX_SIZE];
    }

    public boolean isFull()
    {
        return (size() == MAX_SIZE);
    }

    public boolean isEmpty()
    {
        return (size() == 0);
    }

    public int size()
    {
        return size;
    }

    public boolean add(int data)
    {
        try
        {
            Node node = new Node(data);
            nodeElements[size++] = node;
            return true;
        }
        catch (IndexOutOfBoundsException ex)
        {
            System.out.println(ex.getMessage());
            throw new IndexOutOfBoundsException();
        }
    }

    public void remove(int data)
    {
        int index = locate(data);
        try
        {
            nodeElements[index] = nodeElements[size() - 1];
            size--;
        }
        catch (IndexOutOfBoundsException ex)
        {
            throw new NoSuchElementException();
        }
    }

    public boolean find(int data)
    {
        boolean found = false;
        try
        {
            if(locate(data) >= 0)
            {
                found = true;
            }
            return found;
        }
        catch (NoSuchElementException ex)
        {
            throw new NoSuchElementException();
        }
    }

    // locate function looks for an element in the array, if there is one then returns its index
    private int locate(int data)
    {
        int i = 0;
        int index = -1;
        boolean found = false;
        while (i < size() && !found)
        {
            if (data == nodeElements[i].getData())
            {
                found = true;
                index = i;
            }
            i++;
        }
        return index;
     }

    //Navigator methods

    public void reset()
    {
        currentIndex = 0;
    }

    public boolean hasNext()
    {
        return (currentIndex == size());
    }

    public void next()
    {
        if (!hasNext()) currentIndex++;
    }

    public int currentElement()
    {
        return nodeElements[currentIndex].getData();
    }
}


texts: Hovering over images to show another image whilst fading in & out

texts:
I'm trying to figure out how to correctly hover over an image to fade in another image and when you move your mouse out, it would go fade back to the normal image.

$(document).ready(function(){

$('img').hover(
    function(){
        $(this).stop().fadeOut(function(){
        var $temp = $(this).attr('src');
        $(this).attr('src', $(this).attr('data-alt-src'));
        $(this).attr('data-alt-src', $temp);
        });

        $(this).fadeIn();
    },
    function(){
        $(this).stop().fadeOut(function(){
        var $temp = $(this).attr('data-alt-src');
        $(this).attr('data-alt-src', $(this).attr('src'));
        $(this).attr('src', $temp);
        });

        $(this).fadeIn();

    }
);
});
#main-wrapper {
width: 970px;
margin: 0 auto;
text-align: center;
}

img {
width: 200px;
}
<!DOCTYPE html>

    <title>Hover In/Out</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles.css">

So far, it works as it should with one minor defect. If I were to quickly hover my mouse over the image and out, it would stay in the second image. I initially wanted to hover over the image to show the other image and then when I hover out from the image it would go back to its initial image.


texts: HackerRank Implement Queue using two stacks Solution

texts:
Challenge

Problem Statement - Implement a Queue using two Stacks

I implemented dequeue() in \$O(1)\$ at the cost of enqueue() in \$O(n)\$

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;

struct Queue{
    stack<int> s1,s2;

    int dequeue(){
        int x = s1.top();
        s1.pop();
        return x;
    }

    void peek(){
        cout<< s1.top()<<"\n";
    }

    void enqueue(int data){
        while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
        }

        s1.push(data);

        while(!s2.empty()){
            s1.push(s2.top());
            s2.pop();
        }
    }
};

int main() {
    int t; cin>>t;
    Queue q;

    while(t--){
        int k; cin>>k;
        switch(k){
            case 1:
                int x; cin>>x;
                q.enqueue(x);
                break;
            case 2:
                q.dequeue();
                break;
            case 3:
                q.peek();
        }
    }
    return 0;
}

There are 15 test cases. This code runs properly for the first 5 test cases then I get a 'Time Limit Exceeded' message for the rest of test cases.

This means the complexity of my program is too much.

So I tried reversing it, I made enqueue() as \$O(1)\$ and dequeue() as \$O(n)\$ but even that did not change anything.

What should I do to reduce time complexity of this code?


texts: How can I ensure some structure for classes for a plug-in system written in Python?

texts:
I have written a toolkit (hwrt) which has a plugin system. One type of plugin is a feature (see this) for many of them.

There are some restrictions of feature classes. I expect some structure amongst them:

# Every feature class must have a __str__, __repr__ function so that error
# messages can help you to find and fix bugs in features.
# Every feature class must have a __call__ function which is used to get the
# features value(s) for a given recording.
# Every feature class must have a get_dimension function so that the total
# number of features can be calculated and checked for consistency.
#
# * __call__ must take exactly one argument of type HandwrittenData
# * __call__ must return a list of length get_dimension()
# * get_dimension must return a positive number
# * have a 'normalize' attribute that is either True or False

I have a lot of lines starting with

def __call__(self, handwritten_data):
    assert isinstance(handwritten_data, HandwrittenData.HandwrittenData), \
        "handwritten data is not of type HandwrittenData, but of %r" % \
        type(handwritten_data)

which I would like to write in a shorter notation.

Currently, my classes all inherit from object. I thought about changing that to letting them inherit from a Feature class, but I'm not too sure how I should write it. This was one try:

import abc

class Feature:
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def __call__(self):
        pass

    @abc.abstractmethod
    def get_dimension(self):
        pass

I expected that if I let a class which did not implement get_dimension inherit from Feature that I would get an assertion error as soon as the class is used, but nothing happened.

How can I rewrite the code to have less repetitions and to check for more mistakes programmatically instead of just giving this long comment and hoping that the user implements everything?


texts:
I have implemented the structure below at least 5 times, and it is getting cumbersome.  Is there a better approach?
Current code-segment implemented
public XmlNodeList Templates {
  get {
    return this.GetElementsByTagName( "Templates" );
  }
  set {
    foreach( UITemplateAssoc nd in value ) {
      this.AddTemplate( nd );
    }
  }
}
public UITemplateAssoc GetTemplate (string name) {
  foreach( UITemplateAssoc nd in this.Templates ) {
    if( nd.Name == name ) {
      return nd;
    }
  }

  return null;
}
public void AddTemplate ( UITemplateAssoc val ) {
  for( int i = this.Templates.Count - 1 ; i >= 0 ; i-- ) {
    if( this.Templates[i].Name == val.Name ) {
      this.ReplaceChild( val , this.Templates[i] );
      return;
    }
  }

  this.AppendChild( val );
}


texts:
I wrote a code that requests user input and then converts binary to bcd then back to binary using bitwise operations.
While I think my code is good I want to know if there is a better way to write the code.
Is there also a way to keep the code mostly the same but getting rid of the arrays for printing out the bit positions?

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

#define UINT_MAXIMUM 4294967294
#define MAX_NUMBER 99999999

void printBits(unsigned long number);
unsigned long convertBinaryToBCD(unsigned long number);
unsigned long convertBCDToBinary(unsigned long number);
unsigned long printNumber(unsigned long input)
{
  printf(" Input: ");
  printf("%10lu", input);
  printBits(input);
  unsigned long output_bcd = convertBinaryToBCD(input);
  unsigned long  output_binary = convertBCDToBinary(output_bcd);
  printf("   BCD: ");

  if(output_bcd != UINT_MAX)
  {
    printf("%10lu", output_bcd);
    printBits(output_bcd);
  }
  printf("Binary: ");
  if(output_binary != UINT_MAX)
  {
    printf("%10lu", output_binary);
    printBits(output_binary);
  }
  return 0;
}
void printBits(unsigned long number)
{
    int bit_position[32];
    printf(" - ");
    int counter = 0;
    for(counter = 32; counter > 0; counter--)
    {
        bit_position[counter] = number % 2;
        number = number / 2;
    }
    for(counter = 1; counter <= 32; counter++)
    {
        if(counter == 9 || counter == 17 || counter == 25)
        {
            printf(" | ");
        }
        if(counter == 5 || counter == 13 || counter == 21 || counter == 29)
        {
            printf(" ");
        }
        printf("%d", bit_position[counter]);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
  unsigned long number;

  number = strtoul(argv[1], NULL, 10);

  if(number > UINT_MAXIMUM)
  {
    printf("too big\n");
    return 0;
  }
  printNumber(number);

  return 0;
}

unsigned long convertBinaryToBCD(unsigned long number)
{
  if (number > MAX_NUMBER)
  {
    return UINT_MAX;
  }
  if(number < 100)
  {
    return (((number/10)+((number/100)*6))*16)+(number%10);
  }
  unsigned long sub_number_one = ((number / 12) << 5);
  unsigned long sub_number_two = (number % 10) ;
  unsigned long temporary;
  while(sub_number_two != 0)
  {
    temporary = sub_number_one & sub_number_two;
    sub_number_one = sub_number_one ^ sub_number_two;
    sub_number_two = temporary << 1;
  }
  return sub_number_one;
}

unsigned long convertBCDToBinary(unsigned long number)
{
  if (number == UINT_MAX)
  {
    return UINT_MAX;
  }
  if(number < 100)
  {
    return (((number >> 8) * 100) + ((number >> 4) * 10) + (number & 0xF));
  }

  unsigned long sub_number_one = (number >> 8) * 100;
  unsigned long sub_number_two = (number & 0x0F);
  unsigned long temporary;
  while(sub_number_two != 0)
  {
    temporary = sub_number_one & sub_number_two;
    sub_number_one = sub_number_one ^ sub_number_two;
    sub_number_two = temporary << 1;

  }
  return sub_number_one;
}


texts: Delete node from singly linked list with tail pointer in C

texts:
I'm trying to implement a single linked list based on Linus' comments about double pointers.

In my case I'm also using a tail pointer and I'm wondering if there's a better way to update the tail pointer which does not require the conditional below?

I'm still new to C so any other critique is appreciated (I do realise I'm not freeing the memory for the node in the delete function, I'm leaving that to the caller in case they want to do something else with the node)

typedef struct lrsll_node {
    struct lrsll_node *next;
    char *data;
} lrsll_node;

typedef struct lrsll_list {
    lrsll_node *head;
    lrsll_node *tail;
} lrsll_list;

lrsll_node *lrsll_delete(lrsll_list **list, char *data) {
    lrsll_node **node = &(*list)->head;
    while (*node && strcmp((*node)->data, data) != 0) {
        node = &(*node)->next;
    }
    if (*node == NULL)
        return NULL;

    lrsll_node *deleted = *node;
    *node = deleted->next;

    //is there a way to get rid of this conditional check
    //using pointers in a more intelligent manner?
    if (deleted == (*list)->tail) {
        (*list)->tail = NULL;
    }

    return deleted;
};


texts: Justifying a string followed by a number

texts:
I started practicing on HackerRank to see how my learning is going on with Java.
I wrote this code for problem which involved input having:

  String with maximum length of 10, followed by
  A 3 digit or lesser integer

Examples: "java 100", "Amazing 98"

Expected output:

  String should be left-justified with trailing white spaces till 15th character
  Leading digit of integer starts at 16th place with leading zeroes if it is less than 3 digits(padding) to make up for 18 characters

Examples: "java           100", "Amazing        098"

package HackerRank;

import java.util.ArrayList;
import java.util.Scanner;

public class IOFormatting {
    public ArrayList<String> getAllLines(){
        ArrayList<String> allInputs = new ArrayList<String>();
        Scanner getIp = new Scanner(System.in);
        while(getIp.hasNext()) {
            allInputs.add(getIp.nextLine());
        }
        getIp.close();
        return allInputs;
    }

    public ArrayList<Character> getTheInputAsArrayList(String input) {
        ArrayList<Character> inputLine = new ArrayList<Character>();
        for(int itr1=0;itr1<input.length();itr1++) {
            inputLine.add(input.charAt(itr1));
        }
        return inputLine;
    }

    public ArrayList<Character> formatTheArrayList(ArrayList<Character> inputLine){
        int itr2 = getBreakPoint(inputLine);
        for(int itr3=itr2+1;itr3<15;itr3++) {
            inputLine.add(itr3,' ');
        }
        return inputLine;
    }

    public int getBreakPoint(ArrayList<Character> inputLine){
        for(int itr2=0;itr2<=10;itr2++) {
            if(inputLine.get(itr2) == ' ') {
                return itr2;
            }
        }
        return 0;
    }

    public ArrayList<Character> doIntegerPadding(ArrayList<Character> inputLine){
        int padSize = 18 - inputLine.size();
        if(padSize>0) {
            for(int itr4=15;itr4<=14+padSize;itr4++) {
                inputLine.add(itr4,'0');
            }
        }
        return inputLine;
    }

    public String convertToFinalString(ArrayList<Character> inputLine) {
        String outputString = "";
        StringBuffer sb = new StringBuffer();
        for (Character s : inputLine) {
             sb.append(s);
        }
        outputString = sb.toString();
        return outputString;
    }

    public static void main(String args[]) {
        IOFormatting io = new IOFormatting();
        ArrayList<String> allInputs = io.getAllLines();
        System.out.println("================================");
        for(int mainItr=0;mainItr<allInputs.size();mainItr++) {
            String input = allInputs.get(mainItr);
            ArrayList<Character> inputLine = io.getTheInputAsArrayList(input);
            inputLine = io.formatTheArrayList(inputLine);
            inputLine = io.doIntegerPadding(inputLine);
            String outputString = io.convertToFinalString(inputLine);
            System.out.println(outputString);
        }
        System.out.println("================================");
    }
}


texts:
Below is the code I wrote to perform basic Trigonometry without using the math module(except for 1 place) for the purpose of teaching myself basic trig and to improve my python. I have never taken a trig class, so please consider this fact when explaining some fallacies in my trig logic, and please help me correct it.
I would like feedback on

The architecture of the code. I find my use of dictionaries handling the return of data very restrictive and would like to know how better to handle output or returning of values.
The usage of **kargs, is this proper utilization? Is there a different way to write these functions where I can input large amounts of (undermined) data?
Lines 47-64, better ways to write the block of if/elif statements for readability and functionality.

#!/usr/bin/env python3

import math

def sin(*args, **kwargs):
    degrees = kwargs.get('degrees', None)
    opposite = kwargs.get('opposite', None)
    hypotenuse = kwargs.get('hypotenuse', None)

    if degrees:
        return math.sin(math.radians(degrees))
    elif opposite and hypotenuse:
        return(opposite / hypotenuse)

def cos(*args, **kwargs):
    degrees = kwargs.get('degrees', None)
    adjacent = kwargs.get('adjacent', None)
    hypotenuse = kwargs.get('hypotenuse', None)

    if degrees:
        return math.cos(math.radians(degrees))
    elif adjacent and hypotenuse:
        return(adjacent / hypotenuse)

def tan(*args, **kwargs):
    degrees = kwargs.get('degrees', None)
    adjacent = kwargs.get('adjacent', None)
    opposite = kwargs.get('opposite', None)

    if degrees:
        return math.tan(math.radians(degrees))
    elif opposite and adjacent:
        return(opposite / adjacent)

def find_missing_side(*args, **kwargs):
    sin = kwargs.get('sin', None)
    cos = kwargs.get('cos', None)
    tan = kwargs.get('tan', None)
    opposite = kwargs.get('opposite', None)
    hypotenuse = kwargs.get('hypotenuse', None)
    adjacent = kwargs.get('adjacent', None)

    if sin and hypotenuse:
        opposite = sin * hypotenuse
        return {'opposite': opposite}
    elif sin and opposite:
        hypotenuse = opposite / sin
        return {'hypotenuse': hypotenuse}
    elif cos and adjacent:
        hypotenuse = adjacent / cos
        return {'hypotenuse': hypotenuse}
    elif cos and hypotenuse:
        adjacent = cos * hypotenuse
        return {'adjacent': adjacent}
    elif tan and opposite:
        adjacent = opposite / tan
        return {'adjacent': adjacent}
    elif tan and adjacent:
        opposite = tan * adjacent
        return {'opposite': opposite}

def pythagorean(*args, **kwargs):
    opposite = kwargs.get('opposite', None)
    hypotenuse = kwargs.get('hypotenuse', None)
    adjacent = kwargs.get('adjacent', None)

    if hypotenuse and opposite:
        adjacent = math.sqrt(hypotenuse * hypotenuse - opposite * opposite)
    elif adjacent and opposite:
        hypotenuse = math.sqrt(adjacent * adjacent + opposite * opposite)
    elif hypotenuse and adjacent:
        opposite = math.sqrt(hypotenuse * hypotenuse - adjacent * adjacent)

    return {'hypotenuse': hypotenuse, 'adjacent': adjacent,
            'opposite': opposite}

if __name__ == "__main__":
    # Testing sin, cos, tan functions.
    print(sin(degrees=35))  # Answer is .57
    print(sin(opposite=2.8, hypotenuse=4.9))

    print(cos(degrees=35))  # Answer is .82
    print(cos(adjacent=4.0, hypotenuse=4.9))

    print(tan(degrees=35))  # Answer is .70
    print(tan(opposite=2.8, adjacent=4.0))

    # Testing find_missing_side function.
    print(find_missing_side(sin=sin(degrees=35), opposite=2.8))
    print(find_missing_side(cos=cos(degrees=35), hypotenuse=4.9))
    print(find_missing_side(tan=tan(degrees=35), adjacent=4.0))

    # Testing pythagorean function.
    hypotenuse = find_missing_side(sin=sin(degrees=35), opposite=2.8)
    print(pythagorean(opposite=2.8, hypotenuse=hypotenuse['hypotenuse']))


texts: Checking to see if a string is alphabetic

texts:
public class Alphabet {

 public static void main(String[] args) {
 checkAlphabetic("fdsfsfds+");

 }

 public static boolean checkAlphabetic(String input) {
 char[] chars = input.toCharArray();
 int count = 0;

 for (int i = 0; i < input.length(); i++) {
 if (Character.isLetter(chars[i])) {
 count = 1;
} else {

count = 0;
break;
}
}

if (count >= 1) {
System.out.println("alphabetic word");
return true;
} else {
System.out.println("word is not alphabetic");
return false;
}

}
  }

I know people will say to use regex as it's more efficient but our tutor wanted us to use loops, as we haven't learned about regex yet (old school course).


texts:
I define my canvas as you normally would, but I also include a bunch of different makeshift canvases:

var graphicOne = document.createElement("canvas");
var graphicOneDraw = graphicOne.getContext("2d");

// etc... (eg. graphicTwo)

Then I render all of these canvases, like so:

function preRender() {
  graphicOne.width = 24;
  graphicOne.height = 24;

  graphicOneDraw.beginPath();
  graphicOneDraw.fillStyle = '#0000ff';
  graphicOneDraw.arc(12, 12, 12, 0, Math.PI * 2, true);
  graphicOneDraw.fill();

  // etc... (eg. graphicTwo)
}

In the main loop, my game logic is called before I render it on canvas:

ctx.drawImage(graphicOne, player.x - 12, player.y - 12);

// etc... (eg. graphicTwo) and other things that needs to be rendered

The graphics I need to render is actually more CPU/GPU intensive; this is just a bare bones example so you get the gist of it. But over to the question: Is there a better way to go about this?


texts:
var fruitList = [];
var fruitExpired = GetFruitStatus();
var fruitName = "Mango";
var companyName = "Limited";

if(fruitExpired)
{
   var expiredCrateId = GetExpiredCrate().ID;
   list.push({
    expiredCrate : expiredCrateId,
    fruitName : name,
    fruitCompany : companyName
   });
}
else
{
   var CrateId = GetCrate().ID;
   list.push({
    crateId : expiredCrateId,
    fruitName : name,
    fruitCompany : companyName
   });
}

Can I bring list.push outside if else ? this will help remove duplicate code, only difference is that if expired I am adding property  expiredCrate : expiredCrateId, otherwise  crateId : expiredCrateId,


texts: Simple Form Starts Long Running Task and Watches Progress

texts:
Want to level up my skills. It hits a php script that starts a long running export that can take few minutes to few hours. The export script outputs a progress file that this form's javascript uses for the progress bar.

How maintainable is this? What can I do to improve?

<link rel="stylesheet" href="/css/minified.css">

<form id="exportForm">
  <input id="submitBtn" class="btn btn-primary" type="submit" value="Start Export">
</form>

  <progress id="progressBar" class="" value="0"></progress>


texts: How to get the Split value from collection?

texts:
I have the following key value pair in an array, and am trying to extract and load them into a collection.

The below code is working but it can be optimized using Linq:

string _data = "Website=url:www.site1.com,isdefault:true,url:www.site2.com,isdefault:true";

List<WebSiteAddress> _websiteList = new List<WebSiteAddress>() ;
WebSiteAddress _website = new WebSiteAddress();

string[] _websiteData = _divider[1].Split('=');
string[] _WebsiteKeyValuePair = _websiteData[1].Split(',');

for (int j = 0; j < _WebsiteKeyValuePair.Length; j++)
{
    string key = _WebsiteKeyValuePair[j].Split(':')[0];
    string value = _WebsiteKeyValuePair[j].Split(':')[1];

    if (key.ToLower() == "url")
    {
        _initWebsite.Url = value;
    }
    else if (key.ToLower() == "isdefault")
    {
        _website.IsDefault = Convert.ToBoolean(value);
        _websiteList.Add(_website);
    }
}


texts:
I wrote a stored procedure that will do a merge of two tables:

CREATE PROCEDURE [dbo].[merge_tables]
-- Add the parameters for the stored procedure here
@SourceTable varchar(50),
@DestinationTable varchar(50),
@PrimaryKey varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @update_query varchar(max) =
    (select Concat('SET ', string_agg(cast(@DestinationTable + '.[' + name + '] = '+ @SourceTable +'.[' + name +']' as varchar(max)),','))
    from sys.columns
    WHERE object_id = OBJECT_ID(@DestinationTable) and name != @PrimaryKey and generated_always_type = 0 and system_type_id != 189 and is_identity = 0);

DECLARE @insert_query varchar(max) = (select Concat('([', string_agg(cast(name as varchar(max)),'],['), '])', ' VALUES ([', string_agg(cast(name as varchar(max)),'],['), '])')
    from sys.columns
    WHERE object_id = OBJECT_ID(@DestinationTable) and generated_always_type = 0  and is_identity = 0 and system_type_id != 189);

DECLARE @merge_query varchar(max) = 'MERGE ' + @DestinationTable +
' USING ' + @SourceTable +
' ON (' + @SourceTable + '.' + @PrimaryKey + ' = ' + @DestinationTable + '.' + @PrimaryKey + ')' +
' WHEN MATCHED THEN UPDATE ' + @update_query +
' WHEN NOT MATCHED BY TARGET THEN INSERT ' + @insert_query +
' WHEN NOT MATCHED BY SOURCE THEN DELETE;';
select @merge_query;
EXEC(@merge_query)
END
GO

It appears to work. Is there any way in which this code can be improved? Also, I am not sure how to make this work with compound keys, but that might be off topic for this site.


texts: ResourceManager class consisting of multiple singletons

texts:
I've implemented a class, which provides access to different static resources, which are used by different frontends. I'm hesitating, because in Java getters and setters are quite wide spread. So my question is, if this code smells bad?

public class ResourceManager {
    public static final Preferences Preferences = new Preferences();
    public static final ResourceBundle Texts = ResourceBundle.getBundle("com.stackexchange.resources.Language");

    public static Image getImage(String name) {
        Image retVal = null;

        try {
            retVal = ImageIO.read(ClassLoader.getSystemResource(name));
        } catch (IOException e) {
            // ToDo Use logging functionality
        }

        return retVal;
    }

    private ResourceManager() {
    }

    public static class UserInterface {
        public static final Font titleFont = new Font("default", Font.PLAIN, 18);
    }
}


texts:
I am making a number uncovering app. The program takes in an equation that has numbers hidden as letters, like:
abc + d = efg - hi

and it will return all the strings like
290 + 6 = 347 - 51
290 + 7 = 348 - 51
250 + 6 = 347 - 91
250 + 7 = 348 - 91
290 + 4 = 365 - 71
270 + 4 = 365 - 91
290 + 4 = 375 - 81
280 + 4 = 375 - 91
290 + 7 = 358 - 61
260 + 7 = 358 - 91
290 + 5 = 376 - 81
280 + 5 = 376 - 91
490 + 6 = 527 - 31
...

But there can will be duplicated strings. For example, when I input
a + b = c

the program returns
...
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
...

I know that I can put all the strings into set and then iterate through the set again to print out the strings, but I want to know if that is necessary.
Perhaps in my program there is an unnecessary loop or such that is causing the duplicated strings, which in turns makes its performance slower? If so, I would like to know the proper way of doing it.
Here is my code:
from itertools import permutations
from re import findall

ope = '+-*/( ).='
var = 'abcdefghijklmnopqrstuvwxyz'
num = '1234567890'

while True:
    while True:
        whole = input(">>> ") # User inputs equation here
        if any(c not in ope + var + num for c in whole): # Makes sure that all the characters are valid
            print(f'You may only use: {ope}{var}{num}')
            continue
        chars = list({char for char in whole if char in var}) # Extract all the mystery numbers

        if len(chars) > 10: # There are only 10 different digits, so the user may only input 10 different mystery numbers
            print('Enter at most 9 different letters.')
            continue
        while len(chars) < 10: # If there are less that 10 different mystery numbers
            chars.append(None) # add None until the length of the list is 10

        # From here to the break is to check if the syntax works, so a bit processing time is used on the first permutation of chars
        exp = whole
        for i, v in enumerate(chars):
            if v:
                exp = exp.replace(v, str(i))

        if all(int(e[0]) for e in findall('\d+', exp)):
            try:
                eval(exp.replace('=', '=='))
            except SyntaxError:
                print('Invalid Syntax')
                continue
        break # If not continue was hit, that means that the equation is valid

    for p in permutations(chars):
        exp = whole
        for i, v in enumerate(p):
            if v:
                exp = exp.replace(v, str(i))
        if all(int(e[0]) for e in findall('[\d\w]+', exp)): # If all the individual numbers don't begin with 0
            if eval(exp.replace('=', '==')): # If the equation is correct
                print(exp) # Print the equation


texts: Simulating the radioactive decay of atoms using a random number generator

texts:
I've found two ways of writing the same program (one that only uses local variables, but no methods other than the main one) and other that uses one instance variable that is used in two methods.

This program aims to simulate the radioactive decay of atoms and uses a random number generator.

Here are the two versions of the code:

/*
 * File: HalfLife.java
 *
 * This program simulates the decaying process of radioactive atoms that
 * have a half life of one year. The program will show the amount of atoms
 * remaining at the end of each year until all atoms has decayed
 */

import acm.program.*;
import acm.util.RandomGenerator;

public class HalfLife extends ConsoleProgram {

    /* Number of atoms */
    private static final int NATOMS = 10000;

    public void run() {
        println("There are " + NATOMS + " atoms initially.");
        int remainingAtoms = NATOMS;
        int year = 0;
        while (remainingAtoms > 0) {
            /* Simulate decaying process for each atom. Each atom has a 50% chance of decay. */
            for (int i = remainingAtoms; i > 0; i--) {
                if (rgen.nextBoolean()) {
                    remainingAtoms--;
                }
            }
            year++;
            println("There are " + remainingAtoms + " atoms at the end of year " + year);
        }
    }

    /* Create an instance variable for the random number generator */
    private RandomGenerator rgen = RandomGenerator.getInstance();
}

That one had only local variables, now for the other one (I removed comments in this one since it's redundant):

public class AtomicReduction extends ConsoleProgram {

    private static final int BEG_ATOMS = 10000;

    public void run () {
        int nYears = 1;
        println ("There are " + BEG_ATOMS + " atoms in the beginning");
        while (nAtoms > 0) {
            println ("There are " + (atomicRed (nAtoms)) + " atoms at the end of year " + nYears);
            nYears++;
        }
    }

    private int atomicRed (int initialAtoms) {
        for (int i = 0; i < initialAtoms; i++) {
            boolean isReduced = rGen.nextBoolean();
            if (isReduced) nAtoms--;
        }
        return nAtoms;
    }

     private int nAtoms = BEG_ATOMS;

     private RandomGenerator rGen = RandomGenerator.getInstance();
}

Which is "the better" version? And why?  I kind of prefer the first one because it keeps everything local, however the latter has more decomposition and can be potentially easier to understand (with proper comments).

Note: this makes use of ACM libraries so the main method is public void run.


texts:
How can I DRY these scopes?

  scope :reputed, -> {
    joins{reputations.outer}.
    where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ?', LOWEST_VOTE, true]}
  }

  scope :reputed_or_mine, ->(user) {
    joins{reputations.outer}.
    where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ? OR purchases.user_id = ?', LOWEST_VOTE, true, user.id]}
  }


texts: Better way to check if Javascript Date object exists

texts:
When a button is pressed, an animation loop is triggered.  At the start of the loop, I create a new time object.

I also have a pause button.  A problem was created when paused and then started as the Date object would be recreated each time.

The variable is global and not defined to be anything.  I could set it to 0 and run the conditional test on that instead, but either way there has to be a cleaner way of doing this.  Apologies, I'm quite new to JS.

The code works, but it's ugly (in my opinion):

var t;//not defined

//for starting the animation
startSim.onclick = function(){

    if(t == undefined){
        //get time object
        t = new Date();
    }

    //other code...

}

EDIT:  In case the question is unclear - I'm checking to see if the Date object has been created by finding out if the variable is undefined or not.  What I'm asking is simply Is there a way to find out if the Date object already exists that doesn't rely on checking if the var is undefined.
There is little code as the above is the only relevant part, I can post the rest but it's pointless as not required.  (I've added a little more to show structure but I don't think it's required to understand the question)


texts:
I have a class which takes the method address and arguments, and executes it later when told to do so.

' need to turn option strict off due to Execute method executing late-bound code
Option Strict Off

Public Class WorkItem
    Private Action As Object
    Private Args() As Object

    Public Overloads Sub [Set](action As Action)
        SetArgs(action)
    End Sub

    Public Overloads Sub [Set](Of T)(action As Action(Of T), arg As T)
        SetArgs(action, arg)
    End Sub

    Public Overloads Sub [Set](Of T1, T2)(action As Action(Of T1, T2), arg1 As T1, arg2 As T2)
        SetArgs(action, arg1, arg2)
    End Sub

    '*** more overloads of [Set] method go here...

    Private Sub SetArgs(ByVal action As Object, ParamArray args() As Object)
        Me.Action = action
        Me.Args = args
    End Sub

    Public Sub Execute()
        '-- early binding doesn't work
        'DirectCast(Me.Action, Action(Of T)).Invoke(Args(0))

        '-- this works, but forces me to to keep option strict off
        Select Case Args.Length
            Case 0 : Me.Action.Invoke()
            Case 1 : Me.Action.Invoke(Args(0))
            Case 2 : Me.Action.Invoke(Args(0), Args(1))
            Case 3 : Me.Action.Invoke(Args(0), Args(1), Args(2))
            Case 4 : Me.Action.Invoke(Args(0), Args(1), Args(2), Args(3))
        End Select
    End Sub
End Class

Here is some tester code:

Public Class Form1
    Dim TheTask As WorkItem

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TheTask = New WorkItem
        TheTask.Set(AddressOf DummyProc, TextBox1)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TheTask.Execute()
    End Sub

    Private Sub DummyProc(arg As TextBox)
        Threading.Thread.Sleep(1000)
        Debug.Print("work completed")
    End Sub
End Class

All this works with OPTION STRICT OFF

The WorkItem class obviously doesn't work with OPTION STRICT ON, due to the late-bound call in Execute method.

Is there any way I can convert the late-bound call to early binding?


texts: Listening from Mongodb always and triggering

texts:
I am using classes for the first time. In this program I want the object to run infinitely so that any change in the MongoDB will trigger the function and do the necessary processing.

I am little confused about the using of the self. Please give me feedback on my code.Thanks!

class first_level:

    def __init__(self):

        import pymongo
        connection = pymongo.MongoClient("mongodb://localhost")

        self.test_3_dec = connection.test_3_dec
        self.test1 = self.test_3_dec.test1
        self.test2 = self.test_3_dec.test2

    def listener_function(self):

        cursor = self.test2.find({},{"check_bit":True,"_id":True})

        for bit in cursor:
            if bit["check_bit"]==0:
                self.update_function(bit["check_bit"],bit["_id"])

    def update_function(self,value,value2):

        self.test1.insert({"_id":value2,"bit":value})

        self.test2.update({"_id":value2},{"$set":{"check_bit":1}})

obj = first()

while True:
    obj.listener_function()


texts:
I would like some tips on how I could simplify my code. Basically what I am trying to do is to input 10 numbers in an array but this looks messy so I am trying to change it to look less messy.

Imports System

Public Module Module1

Public Sub Main()
    Dim score(10) as decimal
    Console.WriteLine("Enter the score")
    score(0) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(1) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(2) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(3) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(4) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(5) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(6) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(7) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(8) = Console.ReadLine
    Console.WriteLine("Enter the score")
    score(9) = Console.ReadLine
    Console.WriteLine(score(0) + score(1) + score(2) + score(3) + score(4) + score(5) + score(6) + score(7) + score(8) + score(9))

End Sub


texts:
To learn Scala, coming from Java and Python, I'm attempting to program an implementation of Conway's Game of Life.

I've implemented two different approaches so far, with the first being so bad I'm not even going to ask for review.

The second is a bit cleaner, and produces the correct output, but since I'm new to Scala, I want to know a more Scala-centric way to write things.

I'm also curious about feasibility for my third approach to this game, such as a bit-map approach to neighborhoods, and value caching.

What I want to know is:

Does my implementation fit well with the Scala way of writing code?
Can my code by reduced and made more concise than it already may or may not be?
Would representing all outcomes as a 9-bit map, then pre-caching all 512 possible outcomes have a positive or negative effect on performance?

The code in question is here, and also on Github.

package com.himself12794.main

import scala.collection.mutable.HashMap

object GameLife2 {

  def mappify(str: String, pad: Char = ' ') = {
    val its = new HashMap[(Int,Int), Boolean]
    var x,y = 0
    var items = str.stripMargin split("\n") toBuffer
    val m = items.reduceLeft((a,b) => a max b ).length
    if (items.length < 100) 0 to 100 - items.length foreach { _ => items append ""  }
    items = items map { _ padTo(100, pad) }
    items foreach { z => z foreach { c => its put((x,y),c == 'X'); x += 1}; y += 1; x = 0 }
    its
  }

}

class GameLife2(m: String, val living: Char = 'X', val dead: Char = ' ') {

  private var cells = GameLife2.mappify(m, dead)
  private val hw = cells.keySet reduceLeft { (a,b) => (a._1 max b._1, a._2 max b._2) }
  val height = hw._2 + 1
  val width = hw._1 + 1

  def getCount(x1: Int, y1: Int) = {
    var am = 0
    for {
      x <- x1 - 1 to x1 + 1
      y <- y1 - 1 to y1 + 1
    } {
      if (x > -1 && y > -1 && x < width && y < height && (x,y) != (x1,y1) && this(x,y)) am += 1
    }
    am
  }

  def apply(x: Int, y: Int) = {
    cells.get((x,y)).get
  }

  def doCycle = {
    val cp = cells.clone
    cells foreach {
      cell => {
        val coords = cell._1
        val c = cell._2
        val am = getCount(coords._1, coords._2)

        if (c && (am < 2 || am > 3)) cp.put(coords, false)
        else if (am == 3) cp.put(coords, true)

      }
    }; cells = cp
  }

  def clearConsole = print("\n" * 9)

  def getCells = cells
}


texts: Nested for-loop to create list of lists - Python

texts:
I have posted the below also at stackoverflow in this thread, but a poster there recommended I post this here.  Thanks for any suggestions.

I have the below code, and as someone new to Python, I was hoping for suggestions on making it more Pythonic.  Posters in this thread have provided very helpful numpy and list comprehension solutions; however, I'd like to improve my more basic nested loop solution solely for the sake of becoming better with basic Python tasks (please do let me know if I should have posted this in the prior thread instead of starting a new semi-duplicate...apologies if that's what I should have done).

Here's the current code (which works as desired):

sales_data = [[201703, 'Bob', 3000], [201703, 'Sarah', 6000], [201703,
'Jim', 9000], [201704, 'Bob', 8000], [201704, 'Sarah', 7000], [201704,
'Jim', 12000], [201705, 'Bob', 15000], [201705, 'Sarah', 14000], [201705,
'Jim', 8000], [201706, 'Bob', 10000], [201706, 'Sarah', 18000]]

sorted_sales_data = sorted(sales_data, key=lambda x: -x[2])
date_list = []
sales_ranks = []

for i in sales_data:
    date_list.append(i[0])

sorted_dates = sorted(set(date_list), reverse=True)

for i in sorted_dates:
    tmp_lst = []
    tmp_lst.append(i)
    for j in sorted_sales_data:
        if j[0] == i:
            tmp_lst.append(j[1])
    sales_ranks.append(tmp_lst)

print(sales_ranks)

Any suggestions on making this more Pythonic (other than numpy or list comprehension solutions) would be greatly appreciated.  I am using Python 3.6.


texts:
I have the following code:

public EmployeeProcessOutput  RetrieveEmployee(EmployeeProcessInput input)
{
    var employee = input.Employee;

    if (input.EmployeeId == null)
        employee= CreateEmployee(employee);

    return new EmployeeProcessOutput
    {
        Employee = employee,
        State = "Stored"
    };
}

private Employee CreateEmployee(employee)
{
    //Call a service to create an employee in the system using the employee info
    //such as name, address etc and will generate an id and other employee info.
    var output = Service(employee)
    var employee = output.Employee;
    return employee;
}

Is there a clean way and of passing the employee parameter to the CreateEmployee method?  I feel that this line could be cleaner:

employee = CreateEmployee(employee);

Any thoughts?


texts: Extracting small word parts (quadgrams) from text using R

texts:
I would like to extracts small word parts (quadgrams) from text. Example:

hello world

results in:

_hel, hell, ello, llo_, lo_w ...

This my basic attempt thus far:

text <- "hello world"

number_of_characters <- nchar(text)
quad_gram_list <- ""[-1]

for (i in 1:number_of_characters) {

    end <- i + 3
    if (end > number_of_characters) {
        end <- number_of_characters
    }

    temp <- substring(text, i, end)

    if (nchar(temp) == 4) {
        quad_gram_list <- append(quad_gram_list, temp)
    }
}

Any improvement suggestions would be very much appreciated.


texts: Knuth-Morris-Pratt Search Algorithm 2 Python

texts:
I tried again to implement the algorithm. Just need someone to check my work. I hope I didn't miss anything but my long work hours recently have been pretty taxing on my brain so I honestly wouldn't be surprised if I messed up somehow.

def KMP_table(wrd):
    #example: B A A B D C B A A A C A B -> [-1, 0, 0, -1, 1, 2, -1, 0, 0, 0, 4, 5, -1]
    table = []
    position, candidate = 0, 0
    while position < len(wrd):
        if wrd[candidate] == wrd[position]:
            table.append(-1)
            candidate += (position - candidate)
        elif wrd[position] == wrd[position - candidate] or candidate == 0:
            table.append(0)
        else:
            table.append(position - candidate)
        position += 1

    return table

def KMP_search(wrd, str):

    if not wrd or not str:
        raise ValueError("Empty lists")

    w, s = 0, 0
    lenWrd, lenStr = len(wrd), len(str)
    wrdPos = []

    table = KMP_table(wrd)
    while (s + lenWrd-1) < lenStr:
        if wrd[w] == str[w + s]:
            if w == lenWrd - 1:
               wrdPos.append(s)
               s += 1
               w = 0
            else:
                w += 1
        else:
            if table[w] > 0:
                s += (w - table[w])
            elif w == 0:
                s += 1
            else:
                s += w
            w = 0

    return wrdPos


texts:
I'm developing, just for fun and learning, a TypeScript Class that creates an Array<Array<string>> that represents a pyramid. So, for length = 5 the array would look like :

[
  ['X', 'X', '0', 'X', 'X'],
  ['X', '0', '0', '0', 'X'],
  ['0', '0', '0', '0', '0']
]

The class constructor can take a few arguments:

The final array.
The length (width) of the pyramid, the "blank" String and the "piece" string

My implementation looks like:

PLUNKER

interface IPiramide {
    array?          : Array<Array<string>>,
    private blanco? :         string = 'X',
    private trozo?  :         string = 'O'
}

class Piramide implements IPiramide {

  constructor(piramide : IPiramide = {blanco : 'X', trozo : '0', ancho : 0}){

    this.blanco = piramide.blanco;
    this.trozo = piramide.trozo;

        if(piramide.array){
            this.array = piramide.array;
        }
        else if(piramide.ancho){
            this.build(piramide.ancho);
        }

    }

    static getInstance(ancho : number, blanco : string, trozo : string, inverse ? : boolean) : Piramide {
        return new Piramide({blanco, trozo}).build(ancho, inverse);
    }

    private build (ancho : number, inverse? : boolean = false) {
        this.array = [];
        let numberCount = ancho % 2 == 0 ? 2 : 1;
        let middle = Math.floor(ancho / 2);

        while (numberCount != ancho + 2){
            this.array.push(Array.from({length : ancho}, (el, idx)=>{
                let range = (ancho - numberCount)/2;
                return (idx < range || idx > ancho - range - 1)
                  ? this.blanco
                  : this.trozo;
            }));
            numberCount += 2;
        }
        inverse
          ? this.array = this.array.map((el, idx, arr)=>arr[arr.length - idx - 1])
          : this.array;
        return this;
    }

    public getArray (){
        return this.array;
    }

    public getTrozo() {
      return this.array[Math.floor(this.array.length/2)][Math.floor(this.ancho/2)];
    }

    public getBlanco(){
      if(this.array.length){
        return this.array[1][0];
      }
      return null;
    }

    public getAncho(){
      return this.array[0].length;
    }

    public getAlto(){
      return this.array.length;
    }

    toString(){
        return this.array.map( el=> el.join(' ')).join('\n');
    }

    isConcatenable (piramide : Piramide) : boolean {
      console.log('isConcat', this);
      return this.getAlto() == piramide.getAlto();
    }

    reverse() : Piramide{
      this.array = this.array.map( (el, idx, arr) => arr[arr.length - idx - 1]);
      return this;
    }

    concatRight (...piramides : Array<Piramide>) : Piramide {
      return new Piramide({
        array : this.array.map( (el, i)=> el.concat(...piramides.filter(this.isConcatenable.bind(this)).map( pir => pir.getArray()[i] ) ) ),
        blanco : this.blanco,
        trozo : this.trozo
      });
    }

    concatLeft (...piramides : Array<Piramide>) : Piramide {
      return new Piramide({
        array :  this.array.map( (el, i)=> [].concat(...piramides.filter(this.isConcatenable.bind(this)).map( pir => pir.getArray()[i] ) ) ).map( (el, i)=> el.concat(this.array[i])),
        blanco : this.blanco,
        trozo : this.trozo
      });
    }

    concatAbove(...piramides : Array<Piramide>) {
      return new Piramide({
        array : piramides.reduce( (arr, pir) => arr.concat(pir.getArray()) , []).concat(this.array),
        blanco : this.blanco,
        trozo : this.trozo
      });
    }

    concatBelow(...piramides : Array<Piramide>) {
      return new Piramide({
        array : this.array.concat(piramides.reduce( (arr, pir) => arr.concat(pir.getArray()) , [])),
        blanco : this.blanco,
        trozo : this.trozo
      });
    }

}

It works, but it seems to me that this could be improved (I feel weird with my constructor and static methods).

Could this code be improved?


texts: Distinct List of attribute values from XML, using a pre-defined set of attribute names

texts:
I have an XML stream that looks like the following (attribute and node quantity , and node depth reduced for demonstration purposes.)

<itinerary>
  <organizer>
    <company name="ACME" billingLocation="London" adminOffice="Manchester">
  </organizer>
  <traveller name="John Smith" homeCity="London" />
  <flight date="20160317" code="BA101" origin="London" destination="New York" />
  <vehicleHire start="20160317" end="20160317">
    <depot type="pickup" location="London" />
    <depot type="return" location="Heathrow" />
  </vehicleHire>
  <hotel location="New York" checkin="20160317" checkout="20160318" />
  <journey>
    <train date="20160318">
      <origin station="New York" />
      <destination station="Boston" />
    </train>
</itinerary>

I'd like to get a distinct list of attribute values where the attribute name is in (billingLocation,adminOffice,homeCity,origin,destination,location,station), but my final/actual list of attribute names will number around 30.

I have this C# code working using XmlDocument and an XPath query, but I'm unsure if this is the most efficient method.

XmlDocument xd = new XmlDocument();
xd.Load(customProvider.GetStream());
XmlNodeList nl = xd.SelectNodes(@"//@billingLocation|//@adminOffice|//@homeCity|//@origin|//@destination|//@location|//@station");
var lst = nl.Cast<XmlAttribute>().Select(a => a.Value).Distinct().ToList();

The final XML will be more complex and have a deeper hierarchy, and the attributes might occur across different nodes.

Is XmlDocument and XPath the most efficient aproach, or would Linq to XML perhaps be faster, and what would that look like?


texts:
I recently started learning python.

Requirements

Input: Integer between 1 and 3999
Output: String with Roman numerals

I would appreciate it if someone could have look at the code and give me any feedback. I am particularly interested in the Python specific improvements, as I mainly programmed in C before.

Edit: Any feedback on the algorithm is appreciated too.

import sys

symbols1 =     [(1,   "I"), (5,   "V"), (10,   "X")]
symbols10 =    [(10,  "X"), (50,  "L"), (100,  "C")]
symbols100 =   [(100, "C"), (500, "D"), (1000, "M")]

symList = [symbols1, symbols10, symbols100]

def digitToRomanSym (digit, symList):
    """ Converts a single digit into its roman symbols """
    one =  symList[0][1]
    five = symList[1][1]
    ten =  symList[2][1]

    switcher = {
        1: one,
        2: one + one,
        3: one + one + one,
        4: one + five,
        5: five,
        6: five + one,
        7: five + one + one,
        8: five + one + one + one,
        9: one + ten,
    }
    return switcher.get(digit, "")

def getRomanNumerals (n):
    """ Converts a number between 1 and 3999 into Roman numerals """
    maxNumber = symList[-1][-1][0] * 4 - 1 # A symbol can be repeated max 3 times e.g. MMM for 3000

    if (n > maxNumber):
        return "Number too big"

    if (n == 0):
        return "Number too small"

    i = 0
    romanStr = ""
    while (n > 0 and i < len(symList)):
        romanStr = digitToRomanSym(n % 10, symList[i]) + romanStr
        n /= 10
        i += 1

    if (n > 0):
        biggestSymbol = symList[-1][-1][1]
        romanStr = (n * biggestSymbol) + romanStr;

    return romanStr

if (len(sys.argv) == 2):
    number = int(sys.argv[1])
    print(getRomanNumerals(number))
else:
    print("Wrong number of arguments")


texts:
pfp.services.filterGroups.getNextFilterSetOptions()
        .done(function(values) {
            _.each(values.items,
                function(item) {
                    self.filteredItems.push(item);

                    if (self.selectAll()) {
                        self.tile.selectedValues.push(item.fieldValueId);
                    }
                });
        });

I have a lazy loading component in my web app that when scrolling to the bottom of the scrollable div, the aforementioned method is triggered which then pushes new values retrieved from the method to an assortment of arrays.  I feel like iterating over all of these values (which could be hundreds of values) and pushing individually to the assortment of arrays is overkill.  Is there a cheaper and more efficient way of doing this?

Refactor Attempt

Is this any better other than being slightly less code?

    pfp.services.filterGroups.getNextFilterSetOptions()
        .done(function(values) {
            self.filteredItems(self.filteredItems().concat(values.items));

            if (self.selectAll()) {
                self.tile.selectedValues(self.tile.selectedValues().concat(_.map(values.items, function(item) { return item.fieldValueId; })));
            }
        });


texts: (Codewars) Linked Lists - Remove Duplicates

texts:
Kata: https://www.codewars.com/kata/linked-lists-remove-duplicates/train/python

Description

  Write a RemoveDuplicates() function which takes a list sorted in increasing order and deletes any duplicate nodes from the list. Ideally, the list should only be traversed once. The head of the resulting list should be returned.

var list = 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5 -> null
removeDuplicates(list) === 1 -> 2 -> 3 -> 4 -> 5 -> null

  If the passed in list is null/None/nil, simply return null.

  Note: Your solution is expected to work on long lists. Recursive solutions may fail due to stack size limitations.

My Solution

class Node(object):
    def __init__(self, data, nxt=None):
        self.data = data
        self.next = nxt

def remove_duplicates(head):
    node = Node(None, head)
    st = set()
    while node.next:
        if node.next.data in st:
            tmp = node.next
            node.next = node.next.next
            del tmp
        else:
            st.add(node.next.data)
            node = node.next
    return head

I am interested in performance and adhering to best practices.


texts: Stream operation with two dimensional array

texts:
I am trying to find the best average score from below two dimensional array:

String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };

The output is: 80 (Arthit's score (60+100)/2)

Till now I solved this problem with below approach, however I am looking for elegant solution with stream:

public static void main(String[] args) {
        String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };

        int highestAvg = Integer.MIN_VALUE;
        Function<String[], Integer> function = new Function<String[], Integer>() {
            @Override
            public Integer apply(String[] t) {
                int sum = 0, count = 0;
                for (int i = 0; i < scores.length; i++) {
                    if (t[0].equals(scores[i][0])) {
                        count++;
                        sum += Integer.parseInt(scores[i][1]);
                    }
                }
                int avg = sum / count;
                return highestAvg < avg ? avg : highestAvg;
            }
        };
        System.out.println(Arrays.stream(scores).map(function).max((o1, o2) -> o1.compareTo(o2)).get());
    }

Would you please suggest, what's the better approach to handle two dimensional array using stream?

Note: I am not looking the exact solution, just looking your valuable suggestion.


texts: Faster way to copy rows of data to different sheets by column value

texts:
I'm trying to find a faster way to copy specific rows of a sheet to different sheets. Iterating through them as done in code below takes too much time it leads to timeout.
Some information about origin sheet:

Has already a blocked header
Has around 5000 rows
Column A has a header "Project"
Sheet is sorted by Column A

Goal is to copy range of all rows for each project from origin sheet to a blank sheet that is named from specific project - so all rows that has in column e.g. "ProjectA" in column A are in a sheet called "ProjectA".
Here is a code that is working, but it is using very slow iteration, so I'm waiting around 20 minutes or even get a timeout when I'm processing it:
 var sheet = SpreadsheetApp.getActiveSheet();
    var columnRoom = sheet.getRange("A:A").getValues();
    var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    var header = rows[0];
    var completedRooms = []
    var last = columnRoom[1][0]
    for (var i = 1; i < columnRoom.length; i++) {
        if (!completedRooms.includes(columnRoom[i][0])) {
            if (columnRoom[i][0] === "") {
                var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
            } else {
                var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
            }
            currentSheet.appendRow(header);
            currentSheet.appendRow(rows[i]);
            completedRooms.push(columnRoom[i][0])
            last = columnRoom[i][0]
        } else if (last == columnRoom[i][0]) {
            var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
            currentSheet.appendRow(rows[i]);
        }
    }

Is there a way to do it faster? I'm thinking about appending specific rows to a range and use copyTo but I can't arrange it, maybe use map function?


texts: Exception, errors handling, best practice in WebApi Core

texts:
I'm making my WebApi project.

My logic is, the controller didn't see data. It only triggers a service that returns objects to it. My simple method from TaskService looks like this:

public Task TakeTaskByUser(int taskId, string userId)
{
    var task = this.GetItem(taskId);

    if (task != null)
    {
        if (task.ApplicationUserId != null)
        {
            throw new TaskTakenByAnotherUserException();
        }

        task.ApplicationUserId = userId;
        task.StartTime = DateTime.Now;

        this.context.Entry(task).State = EntityState.Modified;
        this.context.SaveChanges();

        return task;
    }

    return null;
}

As you can see, in this method I try to find Task and attach Foreign Key to User by his UserId. If Task is already taken by another user, I throw a custom exception.

In my controller, Action looks like this:

[HttpPut("{taskId}/{userId}")]
[Authorize(Roles = "Developer, Manager")]
public IActionResult TakeTaskByUser([FromRoute] int taskId, [FromRoute] string userId)
{
    try
    {
        var task = this.taskService.TakeTaskByUser(taskId, userId.ToString());
        if (task != null)
        {
            return this.Ok(task);
        }

        return this.NotFound();
    }
    catch (TaskTakenByAnotherUserException)
    {
        return this.ValidationProblem();
    }
}

Is using a try-catch block in a controller good practice? Is using any exceptions in WebApi good, or I should use the method posted in this article (I like Level 1, seems easy and fun)?

How do I deal with errors that I know that can appear when someone sends a request?


texts: Composing URLs for fetching passenger fares from multiple providers

texts:
Can someone give me advice, how to make this code look nice?

def getFare(self, orig, dest, odate, idate, vid, pax, lang, epi, country_from, country_to):

    def create_link(link_str, API_url, dep_date, ret_date, magic_code, lang):
        '''
        :param link_str: str on which you will use format method
        :param API_url: on which url you should send request
        :param dep_date: departure date as strftime('%d.%m.%Y')
        :param ret_date: arrival date as strftime('%d.%m.%Y')
        :param magic_code: some numbers that identifies the request
        :param lang:
        :return: completed url for request
        '''
        kid_age = ''
        if len(pax['ages']) > 0:
            for age in pax['ages']:
                kid_age += str(age) + ','
            kid_age = kid_age[:-1]
        ages = 0 if kid_age == '' else kid_age
        trip_type = 'false' if idate else 'true'

        created_link = link_str.format(
            url=API_url,
            orig=orig,
            dest=dest,
            dep_date=dep_date,
            ret_date=ret_date,
            adults=pax['a'],
            children=pax['c'] + pax['i'],
            age=ages,
            trip_type=trip_type,
            magic_code=magic_code,
            epi=epi,
            curr=vendor_info[2],
            lang=lang
        )
        return created_link

    if vid == 1:
        user_id = 'some_id'
        new_url = 'http://www.www.www/search/results'
        idate = odate.strftime('%d.%m.%Y') if not idate else idate.strftime('%d.%m.%Y')
        format_url = '{url}/dc/{orig}/rc/{dest}/dd/{dep_date}/rd/{ret_date}/noa/{adults}/noc/{children}/ca/{age}/' \
                         'ow/{trip_type}/mid/{magic_code}/curr/{curr}/lang/{lang}'
        url = create_link(format_url, new_url, odate.strftime('%d.%m.%Y'), idate, user_id, lang)
    else:
        two_way = '/rd/%s' % idate.strftime('%d.%m.%Y') if idate else ''
        format_url = 'http://{url}/iws/search/dc/{orig}/rc/{dest}/dd/{dep_date}{ret_date}/' \
                         'noa/{adults}/noc/{children}/ca/{age}/ow/{trip_type}/mr/50/mid/{magic_code}/msparams/{epi}/' \
                         'curr/{curr}/lang/{lang}'
        url = create_link(format_url, vendor_info[0], odate.strftime('%d.%m.%Y'), two_way, vendor_info[1], lang)

    res = requests.get(url, timeout=(3.1, 30))

Is this a good idea to put a string and parameters for format method in different function and format the string in it?


texts:
Sometimes I have the need to call an async function from a non-async function and get the result back synchronously. Therefore I wrote the following helper function to be able to do this in one line.

public static T RunSync<T>(Func<Task<T>> taskConstructor)
{
    var signal = new ManualResetEventSlim();
    T result;
    Exception ex = null;
    ThreadPool.QueueUserWorkItem(async () =>
    {
        try
        {
            var task = taskConstructor();
            result = await task.ConfigureAwait(false);
        }
        catch (Exception iex)
        {
            ex = iex;
        }
        finally
        {
            signal.Set();
        }

    });
    signal.Wait();
    if (ex != null)
        throw ex;
    return result;
}

Is this ok to do or will it behave unexpectedly in some edge cases? I know that writing this kind of async functions in can be tricky and can easily deadlock. That's why I ran it inside a ThreadPool thread which should prevent any kind of deadlock.

I think that this is probably not the most performant way to do it, but preventing deadlocks is more important in my case.

I know that re-throwing an exception is not ideal, but I think this is a compromise I have to make here.


texts:
Mixed Duo String Generator
Hello again;

Previously my code was critique and I applied this feedback to form my new revised code for the Mixed Duo String Generator. In the code below I revised it to the best of my ability. I removed un-needed comments, keep variables in as small a scope as I could think of, removed un-needed functions, replaced manually typed values with constants, stuck with a consistent indexation, renamed variables with meaningful names, removed camel casing from variables name, nothing is unused, and finally attempted to remove all unnecessary usage of "!= or ==".

I am somewhat nervous but I humbly await judgement of the quality of my code.

#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>

std::string findPair2(std::string input){

    if (input.size() <= 4u) {
        return (input.size() == 4u && input[0] == input[2] && input[1] == input[3]) ? input : "";
    }

    const std::string ELEM_1 = "ELEMENT_1";
    const std::string ELEM_2 = "ELEMENT_2";
    const std::string FAILED = "FAILED";

    std::map<char,std::string> potential_second_element_status; /*The key value of the map represents the status of the
                                                                character being compared to the first element of the string*/
    std::string unique_charaters;
    std::string saved_failures = "";

    for(int i=0; i<input.size(); i++){ //get all the unique characters as they appear in chroniclogical order except the first character
        if((potential_second_element_status.find(input[i]) == potential_second_element_status.end())&&(input[i] != input[0])){
            potential_second_element_status[input[i]] = ELEM_1;
            unique_charaters += input[i];
        }
    }

    for(int i=0; i<input.size(); i++){
        if(saved_failures.size() == unique_charaters.size()){
            break;
        }
        if(input[i] == input[0]){
            for(int a=0; a<unique_charaters.size(); a++){
                if(potential_second_element_status.find(unique_charaters[a])->second == ELEM_2){
                    saved_failures += unique_charaters[a];
                    potential_second_element_status[unique_charaters[a]] = FAILED;
                }
                if(potential_second_element_status.find(unique_charaters[a])->second == ELEM_1){
                    potential_second_element_status[unique_charaters[a]] = ELEM_2;
                }
            }
        }
        else if(potential_second_element_status.find(input[i])->second == ELEM_2){
            potential_second_element_status[input[i]] = ELEM_1;
        }
        else if(potential_second_element_status.find(input[i])->second == ELEM_1){
            saved_failures += input[i];
            potential_second_element_status[input[i]] = FAILED;
        }
    }

    if(saved_failures.size() == unique_charaters.size()){
        char temp = input[0];
        input.erase(std::remove(input.begin(), input.end(), temp), input.end());
        input = findPair2(input);
    }
    else{
        for(int i=0; i<saved_failures.size(); i++){
            input.erase(std::remove(input.begin(), input.end(), saved_failures[i]), input.end());
        }
    }

    return input;
}
void autoStringRead2(){
    std::ifstream inputs( "pairs-in.txt" );
    std::string line;
    std::string output;
    std::string filename = "pairs-in.txt";
    std::fstream fs(filename, std::ios::in);
    std::ofstream results;

    results.open ("results.txt");

    if(!fs.is_open()){
       return;
    }

    while (inputs >> line) {
        output = findPair(line);
        results << output <<"\n";
        std::cout<< line << "\n";
        std::cout<< output << "\n";
    }

    //inputs.close();
    //results.close();
}
int main(){
    autoStringRead2();
    int read;
    std::cin >> read;
    return 0;
}


texts: Finding the bounding box of a polygon array

texts:
I have a Polygon array, and I need to get a Rectangle object which bounds all of the polygons inside the array. Think convex hull - except this is a rectangle and not a polygon.

Here's my current code which works:

public static Rectangle getBoundingBox(final Polygon[] polygons) {
    if (polygons == null) {
        return new Rectangle(-1, -1, 0, 0);
    }

    int minX = Integer.MAX_VALUE;
    int minY = Integer.MAX_VALUE;
    int maxX = Integer.MIN_VALUE;
    int maxY = Integer.MIN_VALUE;

    for (final Polygon polygon : polygons) {
        final Rectangle polygonBounds = polygon.getBounds();

        int ax = polygonBounds.x;
        int ay = polygonBounds.y;
        int bx = ax + polygonBounds.width;
        int by = ay + polygonBounds.height;

        minX = Math.min(ax, minX);
        minY = Math.min(ay, minY);
        maxX = Math.max(bx, maxX);
        maxY = Math.max(by, maxY);
    }

    final Rectangle boundingBox = new Rectangle(minX, minY, 1, 1);
    boundingBox.add(maxX, maxY);

    return boundingBox;
}

  Remember: Execution time is top priority for me


texts:
Are there any ways which I could improve and simplify this code? Is my code idiomatic Haskell?

Is the use of a lens library to change an element of a two-dimensional array unnecessary? If so, how could I replace it with a more elegant and simpler solution?

Do I need to make use of more types in order to make my code more understandable?

As a Haskell beginner, I am still trying to get used to the functional programming way and would appreciate it if answerers would provide a detailed and easy-to-understand answer (as well as references to materials which I could look up to learn more).

-- Tic Tac Toe implementation in Haskell.

module TicTacToe (
    newGame,
    isWin,
    move
) where

import Control.Lens
import Data.List
import Data.Maybe

-- Size of the grid
n :: Int
n = 3

data Player = X | O deriving (Show, Read, Eq)
type Marking = Maybe Player
type Position = (Int, Int)

type Grid = [[Marking]]

-- An empty grid of size n x n.
emptyGrid :: Grid
emptyGrid = replicate n $ replicate n Nothing

data Game = Game {
    board :: Grid,
    curTurn :: Player
} deriving Show

-- Initial game which board is of size n x n,
-- starting with O as the first player.
newGame :: Game
newGame = Game {
    board = emptyGrid,
    curTurn = X
}

getWinSeqs :: Grid -> [[Marking]]
getWinSeqs grid = horizontal ++ vertical ++ [fDiag, bDiag]
  where horizontal = grid
        vertical = transpose grid
        fDiag = zipWith (\ i x -> i !! (n - x - 1)) grid [0..]
        bDiag = zipWith (!!) grid [0..]

-- Check if a game has been won on a board.
isWin :: Game -> Maybe Player
isWin (Game grid _)
    | isWin' X  = Just X
    | isWin' O  = Just O
    | otherwise = Nothing
    where
        isWin' :: Player -> Bool
        isWin' player = any (all (== Just player)) $ getWinSeqs grid

-- Make the next move.
move :: Game -> Position -> Game
move (Game grid player) (i, j) = Game {
    board = nextGrid,
    curTurn = nextPlayer
} where
    nextGrid =
        if isNothing $ grid !! i !! j
        then set (ix i . ix j) (Just player) grid
        else error "position is occupied"
    nextPlayer
        | player == X = O
        | otherwise   = X


texts:
I have a program that starts a bunch of goroutines, feeds them data and when there is no more data, waits for the goroutines to finish. I use sync.WaitGroup. I am unsure if I am using correctly, in an idiomatic way or if there is a better solution.
Background
My real code reads a log file of disk-space and numbers of files backed up etc for several servers. The records are intermingled. From this data it produces a web-page report per server with graphs etc. It works but I believe I can more cleanly separate the functions if I use concurrency. This is a test program before I go ahead and refactor.
Code (72 lines including data)
package main

import (
    "fmt"
    "strconv"
    "strings"
    "sync"
)

func main() {
    p := newPool()
    defer p.Close()

    for _, line := range strings.Split(logData, "\n") {
        f := strings.Fields(line)
        yr, _ := strconv.Atoi(f[0])
        sub := f[1]
        amt, _ := strconv.Atoi(f[2])
        r := logRec{yr, sub, amt}
        p.Report(r)
    }
}

type logRec struct {
    when    int
    subject string
    amount  int
}

type pool struct {
    reporters map[string]chan logRec
    wg        *sync.WaitGroup
}

func newPool() pool {
    rs := make(map[string]chan logRec)
    var wg sync.WaitGroup
    return pool{reporters: rs, wg: &wg}
}

func (p *pool) Report(rec logRec) {
    if _, ok := p.reporters[rec.subject]; !ok {
        c := make(chan logRec)
        p.wg.Add(1)
        go func() {
            defer p.wg.Done()
            tot := 0
            for r := range c {
                tot += r.amount
            }
            fmt.Printf("Total for %s is %d\n", rec.subject, tot)
        }()
        p.reporters[rec.subject] = c
    }
    p.reporters[rec.subject] <- rec
}

func (p pool) Close() {
    for _, c := range p.reporters {
        close(c)
    }

    p.wg.Wait()
}

const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`

Output
Total for oranges is 8
Total for lemons is 16
Total for apples is 52

Question:
Can I improve this? Is there a better way to wait or a more idiomatic use of WaitGroups?


texts:
We would like for a code review for our Python code. The code is written in Python 3.7 and is part of a class handling HTTP cookies.

The code:

class CookieJar(object):
    def add_cookie_header(self, request):
        w_r = WrappedRequest(request)
        self.policy._now = self.jar._now = int(time.time())

        # the cookiejar implementation iterates through all domains
        # instead we restrict to potential matches on the domain
        req_host = request.hostname
        if not req_host:
            return

        if not IPV4_RE.search(req_host):
            hosts = potential_domain_matches(req_host)
            if '.' not in req_host:
                l_req_host = "%s%s" % (req_host, '.local')
                hosts += [l_req_host]
        else:
            hosts = [req_host]

        Cookies = []
        for hosti in range(len(hosts)):
            if hosts[hosti] in self.jar._cookies:
                Cookies.extend(self.jar._cookies_for_domain(hosts[hosti], w_r))

        ats = self.jar._cookie_attrs(Cookies)
        if ats:
            if w_r.has_header("Cookie") == False:
                w_r.add_unredirected_header("Cookie", "; ".join(ats))

        self.processed = self.processed + 1
        if self.processed % self.check_expired_frequency == 0:
            # This is still quite inefficient for large number of Cookies
            self.jar.clear_expired_cookies()

The class CookieJar has other fields and methods, obviously, but they shouldn't be reviewed, so they're not provided here.
You can assume all required imports are present at the top of the file and all referenced methods and fields do exist.

How can we make our code more elegant, efficient and maintainable?


texts: Calculate min/max values for signed or unsigned integral number with any valid number of bits (up to 64)

texts:
This came up when I answered another post.

Is there a better way?

public class Bits
{
    public static void MinMaxI(ulong _bits, out long _min, out long _max)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        _min = (long)1 << (int)(_bits - 1);
        _max = -1 - _min;
    }

    public static long MinI(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        return (long)1 << (int)(_bits - 1);
    }

    public static long MaxI(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 2 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("2 <= _bits <= 64"));
        }

        return -1 - ((long)1 << (int)(_bits - 1));
    }

    public static ulong MaxN(ulong _bits)
    {
        // ? unsigned range with at least one value bit
        if (_bits < 1 || _bits > 64)
        {
            throw new System.ArgumentOutOfRangeException("_bits", _bits,
             String.Format("1 <= _bits <= 64"));
        }

        return _bits == 64 ? ~(ulong)0 : ~(~(ulong)0 << (int)_bits);
    }
}


texts: Determine which sentences contain the set of phrases

texts:
I am trying to solve this HackerRank challenge which asks to write a function that prints the indexes of all sentences which contain the query words. For example, if the inputs to the function are:

textQueries(sentences, queries)
textQueries(['jim likes mary','kate likes tom', 'tom does not like jim'],['jim tom', 'likes'])

Then the function will print

2
0 1

If there is no sentence contains the query words, -1 will be printed

The constraints for the inputs are:

The length of the sentences and queries lists will not exceed 10000.
The number of words in any sentence or query is from 1 to 10 words.
Each word has at most 11 characters.
No word appears in more than 10 sentences.
Each word consists of uppercase and lowercase English letters only.

My attempt so far is to create a hashmap which maps each single query word with a set that contains the indexes to the sentences which contain that word, then I intersect those sets with each other to get the final set. My code runs fine, but it is slow for large test cases. Is there any way I can have it optimized?

def textQueries(sentences, queries):
    word_map = {}
    for query in queries:
        query_words = query.split()
        final_set = set([])
        set_modified = False
        for query_word in query_words:
            if query_word in word_map:
                if len(final_set) == 0 and not set_modified:
                    final_set = word_map[query_word]
                    set_modified = True
                    continue
                elif len(final_set) == 0 and set_modified:
                    break
                else:
                    final_set = final_set.intersection(word_map[query_word])
                    continue
            else:
                sentences_contain_word = []
                for index, sentence in enumerate(sentences):
                    words = sentence.split()
                    if query_word in words:
                        sentences_contain_word.append(index)
                        if len(sentences_contain_word) >= 10:
                            break
                word_map[query_word] = set(sentences_contain_word)
                if len(final_set) == 0 and not set_modified:
                    final_set = word_map[query_word]
                    set_modified = True
                elif len(final_set) == 0 and set_modified:
                    break
                else:
                    final_set = final_set.intersection(word_map[query_word])
        if len(final_set) == 0:
            print(-1)
        else:
            for index in sorted(final_set):
                print(str(index), end=' ')
            print()


texts: To update or to delete? That is the Query

texts:
I'm currently developing a method which performs an update of some data; much like the following simplified logic:

boolean updateRequired = (currentValue == null && newValue != null);
boolean deleteRequired = (currentValue != null && newValue == null);

if(updateRequired || deleteRequired) {

    // ...

}

Which probably is fine enough by itself. However, I can't loose the feeling that I'm somehow re-inventing the wheel. The above is just simplified, current/new-Value are strings if that matters.

Is there any way to make this more neat?


texts:
According to shootout.alioth.debian.org, Racket is not much slower than C#, at least in the same order of magnitude due to its JIT compiler.

However, I'm seeing at least two degrees of magnitude slowdown in my implementation of the RC4 cipher in C# vs. Racket.

(Disclaimer: I am not using RC4, in this case a hilariously puny 16-bit version, to ensure any type of confidentiality. It is only used as a fast traffic obfuscating layer - that's why I need it to be fast!)

My (Typed) Racket code is here: https://github.com/quantum1423/Kirisurf-Official/blob/master/src/arcfour.rkt

The relevant portion:

;Returns a stateful function which encrypts one byte of data with the given key
(define (make-rc4 keyd)

  (define key keyd)

  (define S
     (make-bytes 256 0))
  (for ([i 256])
    (bytes-set! S i i))
  (define j 0)
  (for ([i 256])
    (set! j
          (unsafe-fxmodulo
           (unsafe-fx+ j
                       (unsafe-fx+ (bytes-ref S i)
                                   (bytes-ref key (unsafe-fxmodulo i (unsafe-bytes-length key)))))
         256))
    (define tmp (unsafe-bytes-ref S i))
    (unsafe-bytes-set! S i (bytes-ref S j))
    (unsafe-bytes-set! S j tmp))

  (set! j 0)
  (define i 0)

  (: Sr (Integer -> Integer))
  (define (Sr x) (unsafe-bytes-ref S x))

  (: toret (Integer -> Integer))
  (define (toret c)
    (set! i (unsafe-fxmodulo (unsafe-fx+ 1 i) 256))
    (set! j (unsafe-fxmodulo (unsafe-fx+ j (Sr i)) 256))
    (define temp (Sr i))
    (unsafe-bytes-set! S i (Sr j))
    (unsafe-bytes-set! S j temp)
    (bitwise-xor (Sr (unsafe-fxmodulo (unsafe-fx+ (Sr i) (Sr j)) 256)) c))
  toret)

My old C# code is here: https://github.com/quantum1423/Kirisurf-Official/blob/a04136569025f046872c3cf7fd07955f60bf49dc/Tunnel.cs (scroll to line 398 for the RC4State object)

To put things in perspective, my C# code is always I/O-bound and uses imperceptible CPU. My Racket code vrooms my CPU full and pulls an incredibly slow 700 KiB each second.


texts: Im trying to place multiple dots on a grid with pygame, and it keeps returning a missing value error

texts:
My goal is to find where the ones are in a list and display a circle at that point.
I have a list of 64 zeros in dot1, and I copy it to dot2 after every iteration. I then want to switch zeros out in dot1 for ones, find where they are, and draw a circle.
while g >= 1:
    pygame.draw.circle(window,(255,255,0),(dot2.index("1"),dot2.index("1")),50)
        dot2.remove("1")
        g = g-1

Im trying to loop the cycle to find a one, draw a circle, and delete the one. G is the total number of ones in the list, and when I set G to one, it starts the loop, does what I want it to, and then says that it cant find a "1". Im new to python and pygame, so I don't really know where I went wrong.


texts: velocity profile of laminar flow in a pipe

texts:
for a university project I want to compute the laminar flow velocity at 7 points in a cross-section of a pipe. Later we want to use this data for a flow animation.

Inputs of my function are the diameter and length of the pipe, the viscosity of the fluid, the pressure difference and the average velocity.

For the calculation I only need the pressure difference or the average velocity. So I have to set either the pressure difference or the average velocity to False.

Do you have any idea how I can improve the code?

import numpy as np

def flow(diameter, viscosity, len_pipe, dp, v_average):
    radius = diameter / 2.
    x = np.linspace(-radius, radius, 7)

    if not v_average and dp:
        dpdx = dp / float(len_pipe)
        v = radius**2 / (4*viscosity) * (-dpdx) * (1-(x/radius)**2)
        vmax = max(v)
        v_average = vmax / 2
    elif not dp and v_average:
        vmax = 2 * v_average
        dpdx = -4 * vmax * viscosity / radius**2
        dp = dpdx * len_pipe
        v = radius**2 / (4*viscosity) * (-dpdx) * (1-(x/radius)**2)

    return dp, v_average, x, v, vmax


texts: Refactoring fixed static adding items to new List

texts:
I am not sure how to approach this it fixed item adding to the list of object. I have the slot of ads, that have to be prepulated so they could be selected based on front end parameter. So basically few of these ads can be picked on the website and be positioned. How could this list be simplified, because now it is block of repeated code.

private static List<AdItem> GetAdSlotItems()
{
    var s = "";
    return new List<AdItem>()
    {
        new AdItem { Type = AdType.LeftSky, Container = "div-ad-skyscraper-l", Sizes = new List<List<int>> { new List<int>() { 120, 600 }, new List<int>() { 160, 600 } }, Position = new List<Position>() { new Position() { Id = AdType.LeftSky.ToString(), Value = AdPosition.left.ToString() } } },
        new AdItem { Type = AdType.RightSky, Container = "div-ad-skyscraper-r", Sizes = new List<List<int>> { new List<int>() { 120, 600 }, new List<int>() { 160, 600 } }, Position = new List<Position>() { new Position() { Id = AdType.RightSky.ToString(), Value = AdPosition.right.ToString() } } },
        new AdItem { Type = AdType.LeaderBoard, Container = "div-ad-leaderboard", Sizes = new List<List<int>> { new List<int>() { 300, 250 } }, Position = new List<Position>() { new Position() { Id = AdPosition.inline.ToString(), Value = AdPosition.inline.ToString() } } },
        new AdItem { Type = AdType.BillBoard, Container = "div-ad-billboard", Sizes = new List<List<int>> { new List<int>() { 728, 90 }, new List<int>() {970, 250 }, new List<int>() { 300, 50 } }, Position = new List<Position>() },
        new AdItem { Type = AdType.MPU1, Container = "div-ad-rectangle-e1", Sizes =  new List<List<int>> { new List<int>() {300, 250 }, new List<int>() { 300, 600 } }, Position = new List<Position>() { new Position() { Id = AdType.MPU1.ToString(), Value = AdPosition.mpu1.ToString() } } },
        new AdItem { Type = AdType.MPU1, Container = "div-ad-rectangle-e2", Sizes =  new List<List<int>> { new List<int>() {300, 250 }, new List<int>() { 300, 600 } }, Position = new List<Position>() { new Position() { Id = AdType.MPU2.ToString(), Value = AdPosition.mpu2.ToString() } } },
        new AdItem { Type = AdType.MPU1, Container = "div-ad-rectangle-e3", Sizes =  new List<List<int>> { new List<int>() {300, 250 }, new List<int>() { 300, 600 } }, Position = new List<Position>() { new Position() { Id = AdType.MPU3.ToString(), Value = AdPosition.mpu3.ToString() } } },
        new AdItem { Type = AdType.WallPaper, Container = "div-ad-wallpaper", Sizes = new List<List<int>> { new List<int>() { 1, 1 } }, Position = new List<Position>() }
    };
}


texts:
For my game I have a function that resolves FireOrders between units. The function is being called a ton of times and it's only being extended from various classes.

I have this: doDamage() for a Particle-Parent, a Matter-Parent and so on (5 in total).

The functions are the same, except for a very little if/else part that splits up a number into two different numbers.

It is very annoying to me to have this "long" function in every weapon class and I would like to somehow outsource the actual damage-determination part, because basicly this is what's different for the weapon classes and the remaining function is entirely the same.

However, I'm unable to come up with a way to outsource this tiny element. I tried to write two functions (getArmourDamage() and getStructDamage()), but it is not working since both values depend on each other, hence a single function return value won't suffice.

function doDamage($fire){
 // this is being called in context Particle::doDamage, Matter::doDamage, Explosive::doDamage etc

    for ($i = 0; $i < $fire->shots; $i++){
        if ($fire->rolls[$i] <= $fire->req){
            $destroyed = false;
            $shielDmg = 0;
            $armourDmg = 0;
            $structDmg = 0;
            $totalDmg = $this->getDamage($fire) * $this->getDamageMod(); // INT

            $armour = $fire->target->getStructureById($fire->hitSection);
            $hitSystem = $fire->target->getHitSystem($fire);
            $remInt = $hitSystem->getRemainingIntegrity();
            $negation = $armour->getRemainingNegation($fire) * $hitSystem->getArmourMod(); // INT

             // VARIABLE PART
                if ($totalDmg <= $negation/2){
                    $armourDmg = ceil($totalDmg/2);
                }
                else {
                    $armourDmg = ceil(min($totalDmg, $negation));
                    $structDmg = ceil($totalDmg - $armourDmg);
                }
             // ENDS HERE

            if ($remInt - $structDmg < 1){
                $destroyed = true;
                $hitSystem->destroyed = true;
                Debug::log("overkill for: ".($structDmg - $remInt));
            }

            $dmg = new Damage(
                -1,
                $fire->id,
                $fire->gameid,
                $fire->targetid,
                $armour->id,
                $hitSystem->id,
                $fire->turn,
                $fire->rolls[$i],
                $fire->weapon->type,
                $totalDmg,
                $shielDmg,
                $structDmg,
                $armourDmg,
                0,
                $negation,
                $destroyed,
                "",
                1
            );
            $fire->damages[] = $dmg;
            $hitSystem->damages[] = $dmg;
            $armour->damages[] = $dmg;
            Debug::log("armour rem: ".$armour->getRemainingIntegrity()." / ".$armour->integrity.", now adding: ".$armourDmg);
        }
    }
    return true;
}

For reference, these are the various differences per class:

   particle
                if ($totalDmg <= $negation/2){
                    $armourDmg = ceil($totalDmg/2);
                }
                else {
                    $armourDmg = ceil(min($totalDmg, $negation));
                    $structDmg = ceil($totalDmg - $armourDmg);
                }

   matter
                $armourDmg = $negation / 2;
                $structDmg = $totalDmg - $armourDmg;

   ballistic
                $armourDmg = min($totalDmg, $negation *2);
                $structDmg = $totalDmg - $armourDmg;


texts: What's the most optimal way to see if a string is included in a list of strings?

texts:
Something that has bugged me for a while, is what way is best to perform a conditional where a string is compared to other strings.

Here is some sample code.  This code is just for illustration purposes.

The 3 methods I use are

Do a word for word comparison.  This is probably the most optimal, but ugliest code
Create an array on the fly and do a comparison
Have a predefined array.  This is probably better placed in an external file for easier maintainability.

I just wanted to see what your takes are on this, and if there is an even better way to do it.  I know Enums would probably work well here as well.

    private bool IsWordBad(string word)
    {
        //First Method
        if (word == "Foo" || word == "Bar" || word == "FooBar")
        {
            return true;
        }

        //Second Method
        if ((new[] { "Foo", "Bar", "FooBar" }).Contains(word))
        {
            return true;
        }

        //Third Method
        var badWords = new[] { "Foo", "Bar", "FooBar" };
        if (badWords.Contains(word))
        {
            return true;
        }
        return false;
    }