texts:
I've created the function below to get the SHA-1 of the repository used by my CI server. The hash is then used to update the pass/fail status of the commit on GitHub.

I'm a python amateur. What stands out below?

def get_sha():
    root = os.environ["PWD"]
    repodir = os.listdir(root)[0]
    # /Library/Developer/XcodeServer/Integrations/Caches/6490b1f573dca4e4e0d988197ae6c225/Source/repo_name
    repo = os.path.join(root, repodir)
    sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo).decode('ascii').strip()
    return sha

Please advise on best practices, errors this might encounter, values I should be checking, etc.

EDIT:

Based on feedback I have revised it to the following:

def get_sha():
    for subdir in os.listdir('.'):
        if is_git_directory(subdir):
            return get_repo_sha(subdir)
    assert False

def is_git_directory(path = '.'):
    return subprocess.call(['git', '-C', path, 'status'], stderr=subprocess.STDOUT, stdout = open(os.devnull, 'w')) == 0

def get_repo_sha(repo):
    sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo).decode('ascii').strip()
    return sha


texts:
Code in Java but should be readable also for c#...

Let's assume I have a class with some reference types. Example:

class MyClass {
   private int uniqueId;
   private double doubleValue;
   private MyReferenceType refType1;
   // ...

   public MyClass(int id, double doubleValue, MyReferenceType refType){
      this.id = id;
      this.doubleValue = doubleValue;
      this.refType1 = refType;  // seems dangerous - I want to create new object with the same state instead of adding a reference to an existing one...
   }
   // ...
}

The question is what approach of constructing such an object do you prefer:

Option 1
In constructor:

public MyClass(int id, double doubleValue, MyReferenceType refType){
      // ...
      this.refType1 = new MyReferenceType(refType); // MyReferenceType has some "copy" constructor
}

In code:

MyClass mc = new MyClass(1, 1.0, someRefTypeInstance);

or

Option 2:
In constructor:

public MyClass(int id, double doubleValue, MyReferenceType refType){
      // ...
      this.refType1 = refType;
   }

In code:

MyClass mc = new MyClass(1, 1.0, new MyReferenceType(someRefTypeInstance));

Which approach do you find more reasonable and you use in practice?


texts: Print input one word per line (K&R 1-12 exercise) attempt

texts:
I'm currently trying to learn C from the K&R book, reading through and attempting the exercises. I came across exercise 1-12 yesterday and was a little stumped but managed to complete it. I was wondering if someone on here would help me improve it, and also guide me on how to approach testing something like this too.

The exercise is to write a program which "prints input one word per line".

#include <stdio.h>

#define TRUE 1
#define FALSE 0

int main(){

    int c, previous_space;

    previous_space = FALSE;
    while ( (c = getchar()) != EOF ){
        if ( c == ' ' || c == '\n' || c == '\t' ){
            if ( previous_space == FALSE ){
                putchar('\n');
            }
            previous_space = TRUE;
        }
        else{
            putchar(c);
            previous_space = FALSE;
        }
    }
    return 0;
}


texts: Allowing googlebot to crawl a password protected page

texts:
The below I have put together as an experiment, I have profiles on my site that are password protected. I would still like them to be crawled by google.

The script is taken from here and basically does a reverse dns lookup to verify if a googlebot is real or fake. I am then using this logic to allow google entry to my dynamic page by skipping the 'restrict-access.php' include which checks to see if someone is logged in or not.

My question is..
1. Is this viable?  2. is the code solid/safe?

<?php
function validateGoogleBotIP($ip)
{
    $hostname = gethostbyaddr($ip); //"crawl-66-249-66-1.googlebot.com"
    return preg_match('/\.googlebot\.com$/i', $hostname);
}
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Google') !== false) {
    if (validateGoogleBotIP($_SERVER['REMOTE_ADDR'])) {
        // its google - let them in
    } else {
        exit('You are not authorised to view this page');
    }
} else {
    require_once('php-includes/restrict-access.php');
    if (isset($_GET['user_id'])) {
        if (!ctype_digit($_GET['user_id']))
            exit('You are not authorised to view this page');
    } else {
        exit('You are not authorised to view this page');
    }
}
?>


texts: Find indices of first pair of numbers that sums to zero

texts:
Here is the task from a beginner's course:

  Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return nil.

This model solution does not use idiomatic Ruby, because at that point in the course, we had only learned traditional loops. I'm trying to go back now and understand how to use idiomatic Ruby to accomplish the same tasks.

Model solution:

def two_sum(nums)

idx1 = 0

while idx1 < nums.length

idx2 = idx1 + 1

while idx2 < nums.length

  if nums[idx1] + nums[idx2] == 0

    return [idx1, idx2]

  end

  idx2 += 1

end

idx1 += 1

end

return nil

end

My solution:

def two_sum(nums)

answer = []

nums.each_with_index do |num1, idx1|
    nums.each_with_index {|num2, idx2| answer.push(idx1, idx2) if (num1 + num2) == 0 }
end

    answer.empty? ? nil : answer[0..1]

end

The call of only the first two items in the answer array seems cheap. There must be a better way. I'm just not sure how to work through the array including the index, but also breaking as soon as the array hits a length of two, or however else one might define it.


texts: Repetitive then/catch method on Javascript

texts:
I have this function and looks ugly because there are a lot of "catch" doing the same. Any idea how to make it better?

saveUser: function(){
    let user_id = this.$route.params.user_id;
    let payload = this.user;

    updateUser(user_id, payload).then(response => {
        updateOrCreateAddresses(payload).then(response => {
            updateOrCreateBalances(payload).then(response => {
                this.success();
            }).catch(error => {
                this.showError(error)
            })
        }).catch(error => {
            this.showError(error)
        })
    }).catch(error => {
        this.showError(error)
    })
},


texts:
I struggled my way through the first quiz and here are the results.  Since I have some experience in jQuery I really wanted to use only vanilla JavaScript.  I know the code is pretty choppy and there is most likely a lot of room for improvement.

How can I make this code more succinct? What are some better practices that i can implement?

Here is a jsfiddle.

HTML:

How well do you know Matt

    <input type='submit' id='myBtn' value='' />

JavaScript:

var allQuestions = [
{
    question: "What is Matt favorite color?",
    choices: ["Blue", "Black", "Yellow", "Blank", "Clear" ],
    correctAnswer: 4
},
{
    question: "Who is Matt's Favorite fiction Author?",
    choices: ["Brennan Manning", "JD Salinger", "Stephen King", "Jack Kerouac"],
    correctAnswer: 3
},
{
    question: "What is Matt's favorite food?",
    choices: ["Pizza", "Wings", "Mexican", "Rally's"],
    correctAnswer: 0
}
];

var submitBtn = document.getElementById('myBtn');
var currentQuestion = 0;
var tally = 0;

var quizForm = document.getElementById('quiz');
var question;
var choices;
var radioButtons = document.getElementsByName('radioOption');
var index = 0;

function firstFunc() {
    if (currentQuestion === 0) {
        submitBtn.value = "Start Quiz";
    }
}

function askQuestion () {
    choices = allQuestions[currentQuestion].choices;
    question = allQuestions[currentQuestion].question;
    if (currentQuestion < allQuestions.length) {
        submitBtn.value = "Next";
        quizForm.innerHTML = "
" + question + "
";
        for (var i = 0; i < choices.length; i++) {
            quizForm.innerHTML += "<input type='radio' name='radioOption' value='" + choices[i] + "'/>" + choices[i] + "";
        }
        if (currentQuestion == allQuestions.length - 1) {
            submitBtn.value = "Submit";
        } else if (currentQuestion > allQuestions.length - 1) {
            calcQuiz();
        }
    }
}

function lookForChecked() {

    if (radioButtons.length > 1) {

            var checked = false;
        for (var i = 0; i < radioButtons.length; i++) {
            var selection = radioButtons[i];

             if (selection.checked) {

                var index = [i];
                if (i === allQuestions[currentQuestion].correctAnswer) {
                    tally++;

                }
                if (currentQuestion < allQuestions.length -1) {
                    currentQuestion++;

                } else {
                    console.log('you have ended the quiz');
                    calcQuiz();
                   return false;
                }
                break;
            }
        }
        if ($('input[name="radioOption"]:checked').length < 1) {
            alert('Please Make a Selection');
        }
    }
        askQuestion();
}

function calcQuiz() {
    quizForm.innerHTML = "
You have finished the quiz

You scored a total of " + tally + " out of " + allQuestions.length + "
";
    submitBtn.remove();
}
window.onload = firstFunc();
submitBtn.addEventListener('click', lookForChecked);


texts:
I have  following queries

First one using inner join

SELECT item_ID,item_Code,item_Name
FROM [Pharmacy].[tblitemHdr] I INNER JOIN  EMR.tblFavourites F ON I.item_ID=F.itemID
WHERE F.doctorID = @doctorId AND F.favType = 'I'

second one using sub query like

SELECT item_ID,item_Code,item_Name from [Pharmacy].[tblitemHdr]
WHERE item_ID IN
(SELECT itemID FROM EMR.tblFavourites
WHERE doctorID = @doctorId AND favType = 'I'
)

In this item table [Pharmacy].[tblitemHdr] Contains 15 columns and 2000 records. And [Pharmacy].[tblitemHdr] contains 5 columns and around 100 records. in this scenario which query gives me better performance?


texts: Most elegant image to image frame comparison algorithm

texts:
I'm interested in finding the most elegant and 'correct' solution to this problem. I'm new to JS/PHP and I'm really excited to be working with it. The goal is to compare the size of a given image to the size of a 'frame' for the image (going to be a <div> or <li> eventually) and resize the image accordingly. Users will be uploading images of many sizes and shapes and there are going to be many sizes and shapes of frames. The goal is to make sure that any given image will be correctly resized to fit any given frame. Additionally, images will be cropped with overflow:hidden; so they'll never be distorted. Final implementation will be in PHP, but I'm working out the logic in JS. Here's what I have:

//predefined variables generated dynamically from other parts of script, these are example values showing the 'landscape in landscape' ratio issue
var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300;
//check image orientation
if ( $imageHeight == $imageWidth ) {
    var $imageType = 1; // square image
} else if ( $imageHeight > $imageWidth ) {
    var $imageType = 2; // portrait image
} else {
    var $imageType = 3; // landscape image
};
//check frame orientation and compare to image orientation
if ( $height == $width) { //square frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) {
        $deferToHeight = true;
    } else {
        $deferToHeight = false;
    };
} else if  ( $height > $width ) { //portrait frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) )  {
        $deferToHeight = true;
    } else {
        if (($imageHeight / $height) < 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
} else { //landscape frame
    if ( ( $imageType === 1 ) || ( $imageType === 2 ) ) {
        $deferToHeight = false;
    } else {
        if (($imageWidth / $width) > 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
};
//set values to match (null value scales proportionately)
if ($deferToHeight == true) { //defer image size to height of frame
    $imageWidth = null;
    $imageHeight = $height;
} else { //defer image size to width of frame
    $imageWidth = $width;
    $imageHeight = null;
};

I've tested it with a bunch of different values and it works, but I have a suspicion that I could have implemented a much more elegant solution. What could I have done better?


texts: Video downloader app implemented in RxJs

texts:
I have used multiple map/flatmap combinations. Could anybody help me with the review?

var Rx = require('rx');
var RxNode = require('rx-node');
var request = require('request');
var _ = require('lodash');
var cheerio = require('cheerio');

exports.getResult = function(req, res) {
    var result = '';
    fetchContent({
            url: req.body.url
        }, req.body.season)
        .flatMap(getEpisodeRange)
        .map(formEpisodeUrl.bind(null, req.body.url, req.body.season))
        .flatMap(downloadHtml)
        .map(getGorillaUrl)
        .flatMap(postToGorilla)
        .map(getVideoUrl)
        .flatMap(prepareHtml)
        .subscribe(function(data) {
            result += data;
        }, function(error) {
            res.send(JSON.stringify(error))
        }, function() {
            res.send(result);
        });
}

function fetchContent(params) {
    console.log(params.url);
    var args = [].slice.call(arguments, 1)
    return Rx.Observable.create(function(observer) {
        request(params, function(error, response, body) {
            if (error) {
                observer.onError();
            } else {
                observer.onNext({
                    response: response,
                    body: body,
                    args: args
                });
            }
            observer.onCompleted();
        })
    });
};

function prepareHtml(url) {
    return `<a href=${url}></a>`;
}

function fileName(url, season, episode) {
    return Rx.Observable.just(url.split('/'))
        .last().map(function(name) {
            return name.replace('_', ' ').concat(` S${season}E${episode}`);
        });
}

function getVideoUrl(data) {
    var pattern = /"http(.*)(\.flv|\.mkv|\.mp4)"/;
    var matches = pattern.exec(data.body);
    if (matches && matches[0]) {
        return matches[0]
    } else {
        return null;
    }
}

function postToGorilla(url) {
    var params = {
        url: url,
        method: 'POST',
        headers: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        form: {
            op: 'download1',
            method_free: 'Free+Download',
            id: _.last(url.split('/')),
        }
    }
    return fetchContent(params)
}

function getGorillaUrl(data) {
    try {
        var $ = cheerio.load(data.body);
        var url = $('a[title="gorillavid.in"]').first().attr('href').split('=')[1]
        return url = new Buffer(url, 'base64').toString('ascii');
    } catch (error) {
        return Rx.Observable.just(null);
    }
}

function downloadHtml(url) {
    return fetchContent({
        url
    });
}

function formEpisodeUrl(url, season, episode) {
    return url.replace('/serie/', '/episode/').concat(`_s${season}_e${episode}.html`);
}

function getEpisodeRange(data) {
    var $ = cheerio.load(data.body);
    return _.range(1, ($('span').filter(function() {
        return $(this).text() === `Season ${data.args[0]}`;
    }).parents('h2').siblings('ul').children('li').length) + 1 || 0, 1);
}


texts:
I've started to get far more familiar with C (and coding in general) and the way to use function to my advantage to create more complex programs. As a way of doing something actually useful instead of my "Starting Programming with C: For Dummies" book I decided to make a simple program to help me cheat my way through maths class, a program that calculates the quadratic equation.
However due to the fact that I've never seen a piece of code that is longer than 60 lines outside of a youtube videos and my for Dummies book, I don't exactly know if the way I format functions is readable to other people.
/*El programa calcula la ecuación general de segundo grado,
no tiene mayor proposito más que practicar C y hacer trampa en los exámenes -w-,
trato de usar funciones claras para hacer más legible el código, tómese nota de que me gusta
main en primer lugar main y luego el resto de funciones.*/
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int a,b,c,total,resultado; //total se usa para el resultado de diferentes opercaciones de la ecuación, resultado es el resultado final de la ecuación
void value_input();
int discriminante(int b, int a, int c);
void display();
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
void main(){
        value_input();
        b=-b; //como todas las operaciones con "b" son su multiplicación *-1 y su cuadrado, decidí solo volver b negativo (o positivo dependiendo del caso)
        discriminante(b,a,c);

        display();
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//value_input solo le pregunta al usuario los valores de a, b y c en la ecuación y los aloca a las variables correspondientes.
void value_input(){
        printf("Dame el valor de a: ");
        scanf("%d", &a);
        printf("Dame el valor de b: ");
        scanf("%d", &b);
        printf("Dame el valor de c: ");
        scanf("%d", &c);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//La función calcula la discriminante y devuelve su valor
int discriminante(int b, int a, int c){
        int result;
        b*=b;
        c=4*a*c;
        total=b-c;
        return total;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//display calcula el divisor de la ecuación y determina como imprimir la ecuación basado en el discriminante
void display(){
        a*=2; //se calcula el divisor
        //se calcula valor del discriminante y dependiendo de éste se imprime el resultado
        if(total>0){    //es mayor que 0
                total=sqrt(total);
                printf("El resultado es: (%d±%d)/%d\n",b,total,a);
                }
        else if(total<0){       //es menor que 0
                total=abs(total);
                total=sqrt(total);
                printf("El resultado es: (%d±%di)/%d\n",b,total,a);
                }
        else if(total=0){       //es igual a 0
                printf("El resultado es: (%d\n",b/a);
                }
}

I think that it is mostly understandable for anyone that wants to review the code in general, but I think that it can become a little convoluted in some places, specially the display() function.
How could I make it clearer?


texts: Sorting Exclusive of Specified Indexes in List

texts:
To further generalize the algorithm (past the doc string): Given a list E(1) E(3) E(2) E(4) _ E(0) _ where E(N + 1) is ahead of E(N) when sorted and _ represents a "static element" (that is, an element whose index and value will remain unchanged despite the sorting), the list returned should be E(0) E(1) E(2) E(3) _ E(4) _.

In the following code, non-static elements would be the elements affected by the sorting, while a static element would be unaffected (i.e, an _).

def static_sort(old_list: list, static_index_list: list) -> list:
    """
    Returns a list whose non-static elements (defined to be the ones whose
    indexes are not specified in the static_index_list) are sorted in ascending order.
    The static elements (with indexes specified in the static_index_list) remain unchanged
    in both numeric value and index in the original list.

    static_sort([1, 9, 3, 5], [0, 2]) -> [1, 5, 3, 9]
    static_sort([0, 8, 2, 6], [2]) -> [0, 6, 2, 8]

    :param static_index_list: A list of indexes whose associated elements in
    old_list should be exclusive of the sorting in the rest of the list.
    :param old_list: The unsorted list, to-be sorted using the comparator and
    static_index_list.
    """

    sorted_list = []
    non_sort_subjects = list(map(lambda static_index: old_list[static_index], static_index_list))

    def sort_subject_filter(element):
        return element not in non_sort_subjects

    sort_subjects = sorted(list(filter(sort_subject_filter, old_list)))

    whole_index = sort_subject_index = 0
    while whole_index < len(old_list):
        if whole_index in static_index_list:
            sorted_list.append(non_sort_subjects[whole_index - sort_subject_index])
        else:
            sorted_list.append(sort_subjects[sort_subject_index])
            sort_subject_index += 1
        whole_index += 1

    return sorted_list

Reviews on the algorithm itself in addition to formatting/code style are appreciated.


texts: A different way to execute a hangman game

texts:
Most hangman implementations I have seen keep a list of characters the player has already guessed and compares them to the players current guess each time to see if they have already made the same guess.  My implementation checks if the word was changed after replacing any matches.  Is my implementation easier to understand as well as more efficient than this one Hangman game logicistics and cleanliness?

Side Question: Should I use static variables in loops?

Hangman

#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <random>
#include <string>

std::string replace_if_match(std::string& write, const std::string& read, const std::string& match)
{
    assert( write.length() >= read.length() );

    for( int search_pos{0}; (search_pos = read.find( match, search_pos )) != -1; ++search_pos){

        write.replace( search_pos, match.length(), match );
    }
    return write;
}

int main()
{
    std::ifstream file("word_list");
    assert( file.is_open() );

    std::vector<std::string> word_list;

    while( !file.eof() ){

        static std::string word;
        file >> word;
        word_list.push_back( word );
    }
    file.close();

    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(0, word_list.size() - 1);

    std::string unknown_word;

    std::string previous_word;

    std::string guessed_word;

    std::string guess;

    int num_of_guesses;

    int in_game{true};

    while( in_game )
    {
        unknown_word = word_list[dist(mt)];

        guessed_word = std::string().append( unknown_word.length(), '_' );

        num_of_guesses = 5;

        while( num_of_guesses > 0 && unknown_word != guessed_word )
        {
            std::cout << guessed_word << '\n';

            std::cout << "Number of Guesses Left: " << num_of_guesses << '\n';

            std::cout << "Enter a string as guess.\n";
            std::cin >> guess;

            previous_word = guessed_word;

            if( previous_word == replace_if_match( guessed_word, unknown_word, guess ) ){

                num_of_guesses--;
            }
        }
        if( guessed_word == unknown_word ){

            std::cout << "We did not have a noose for you any way.\n";
        }
        else{

            std::cout << "You loser, the word was " << unknown_word << "!\n";
        }
        std::cout << "Would you like to try another? <Yes: 1, No: 0>\n";
        std::cin >> in_game;
    }
}


texts:
I was writing a program that had a list of e-mail messages. It needed to group them into batches, with the condition that each batch must have at max 20 messages, and be maximally 50k in size (no individual message is bigger than 50k). Obviously itertools.groupby() is a candidate for this, but I really didn't want to keep around a key variable, so I decided to write my own batcher:

def batch(iterable, condition_func=(lambda x:True), max_in_batch=None):
    def Generator():
        nonlocal n, iterable, condition_func, max_in_batch
        num_in_batch = 1
        yield n
        while True:
            n = next(iterable)
            if num_in_batch == max_in_batch or condition_func(n):
                return
            num_in_batch += 1
            yield n

    n = next(iterable)
    while True:
        yield Generator()

Sample run:

>>> gen = batch(itertools.count(1),(lambda x:x%10==9),7)
>>> list(next(gen))
[1, 2, 3, 4, 5, 6, 7]
>>> list(next(gen))
[8]
>>> list(next(gen))
[9, 10, 11, 12, 13, 14, 15]
>>> list(next(gen))
[16, 17, 18]
>>> list(next(gen))
[19, 20, 21, 22, 23, 24, 25]
>>> list(next(gen))
[26, 27, 28]

What do you think? Is this Pythonic?


texts:
The end result I am trying to achieve is an array containing the total ordered qty for each product. I have been successful but the query takes about 20 minutes to run and I'm wondering if there is anyone who may know of some way of improving this? The details and current query are as follows:

All columns involved in a join or where clause are indexed.
Tables have been optimized.

orders_table:

2 million rows
duplicate product codes where more than one order has been made for the same product (these can be grouped by product_code and pack_size_ordering_unit)
has product code and barcode

product_table:

300 thousand rows
no duplicates
has product code and barcode
query should be run for products where the distribution route is not 'C'
query can be run for any products within any specified categories

product_pack_sizes:
- 2 million rows
- each product can be ordered in various pack sizes (e.g. 1 store pack of 4 units, 2 pallets of 84 units ect.)
- no duplicates only has barcode

SELECT product_table.ProductCode as product_code, SUM(grouped_store_orders_table.po_qty*product_pack_sizes.pack_size_qty) AS order_qty
FROM (SELECT orders_table.barcode, orders_table.po_qty, orders_table.po_ordering_unit
FROM orders_table
GROUP BY orders_table.barcode, orders_table.po_ordering_unit) AS grouped_store_orders_table
LEFT JOIN product_table
ON product_table.barcode = grouped_store_orders_table.barcode
LEFT JOIN product_pack_sizes
ON grouped_store_orders_table.barcode = product_pack_sizes.barcode AND grouped_store_orders_table.po_ordering_unit = product_pack_sizes.unit_of_measure
WHERE product_table.Category IN (2,3,4,5) AND product_table.DistroRoute <> 'C'
GROUP BY product_table.ProductCode

Execution plan:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    36756   Using temporary; Using filesort
1   PRIMARY product_table   ref barcode,Category    barcode 4   grouped_store_orders_table.article  1   Using where
1   PRIMARY product_pack_sizes  ref article,unit_of_measure article 4   trends.product_table.barcode    3
2   DERIVED orders_table    ALL NULL    NULL    NULL    NULL    2137680 Using temporary; Using filesort


texts: Frequency distribution of words and phrases

texts:
I need to find a way how to create a frequency distribution out of multilple text files. In fact I am asked to check the number of times a word or a phrase occurs in a txt file. The code should check from a predefinded list (my list is called l1) how often this word or phrase can be found in the doc. My output should look like the following:

UNIQA VERSICHERUNGEN:31.12.2008
acceptance  2
acceptance credit   0
acceptance sampling 0
accounting principles   10
accounting principles board 0
additional  30
corporate   36
corporate bond  0
corporate finance   0
corporate governance    15

My code looks as follows. It does what it should do, but it is very slow (takes about a minute per file to process).

    from collections import Counter
    from itertools import chain
    import re
    import os
    import glob
    from nltk.tokenize import *
    import nltk
    from os import listdir

    def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)

    def read_textfile(filename):
        # Reads the entire content of FILENAME and returns a non Ascii letters cleaned string
        infile = open(filename)
        contents = removeNonAscii(infile.read())
        infile.close()
        return contents

    def list_textfiles(directory, min_file_size):
        # Creates a list of all files stored in DIRECTORY ending on '.txt'
        textfiles = []
    for root, dirs, files in os.walk(directory):
        for name in files:
            filename = os.path.join(root, name)
            if os.stat(filename).st_size > min_file_size:
                textfiles.append(filename)
    return textfiles

def remove_punctuation1(text):
    # Removes all punctuation and conotation from the string and returns a 'plain' string
    punctuation = '®©™€â´‚³©¥ã¼•ž®è±äüöž!@#Â“§$%^*()î_+€$=¿{”}[]:«;"»\â¢|<>,.?/~`0123456789'
    for sign in punctuation:
        text = text.replace(sign, "")
    return text

def remove_punctuation2(text):
    # Removes all punctuation and conotation from the string and returns a 'plain' string
    punctuation2 = '-&'
    for sign in punctuation2:
        text = text.replace(sign, " ")
    return text

filepath_dict = "H:/MA Daske/Wordlists/IFRS.txt" # input filepath for the used wordlist (here external accounting dictionary)
directory = "H:/Converted Text/EU0_OM0_FY2001" # directory of the text files to be processed
min_file_size = 90000

l1 = remove_punctuation2(removeNonAscii(read_textfile(filepath_dict))).lower().split('\n') # externally created word/expression list

vocabulary_dict  = {k:0 for k in l1}

for filename in list_textfiles(directory, min_file_size):
    # inread each report as textfile, match tokenized text with predefined wordlist and count number of occurences of each element of that wordlist
    sample_text = remove_punctuation2(remove_punctuation1(read_textfile(filename).lower())).replace('\n', " ")
    #sample_text = remove_punctuation2(remove_punctuation1(sample_text)).replace('\n', " ")
    sample_text = ' '.join(sample_text.split())
    splitted = sample_text.split()
    c = Counter()
    c.update(splitted)
    #print(c)
    outfile = open(filename[:-4] + '_output' + '.txt', mode = 'w')
    string = str(filename)
    string_print = string[string.rfind('/')+1:string.find('-')] + ':' + string[-6:-4] + '.' + string[-8:-6] + '.' + string[-12:-8]
    samples = set(sample_text.split())
    for k in vocabulary_dict:
        spl = k.split()
        ln = len(spl)
        if ln > 1:
            check = re.findall(r'\b{0}\b'.format(k),sample_text)
            if check:
                vocabulary_dict[k] += len(check)
        elif k in samples:
            vocabulary_dict[k] += c[k]
    outfile.write(string_print + '\n')
    # line wise write each entry of the dictionary to the corresponding outputfile including comapany name, fiscal year end and tabulated frequency distribution
    for key, value in sorted( vocabulary_dict.items() ):
        outfile.write( str(key) + '\t' + str(value) + '\n' )
    outfile.close()


texts:
Is there a more efficient way to write this? Seems redundant to me:

    var leaves = $(".leaf");
    var trees = $(".tree");

    $(".my-class").on("click", function (e) {
        if ($(e.target).hasClass("leaf")) {
            trees.each(function() {
                $(this).attr("tabIndex", -1);
            });
            leaves.each(function() {
                $(this).attr("tabIndex", 1);
            });
        } else {
            trees.each(function() {
                $(this).attr("tabIndex", 1);
            });
            leaves.each(function() {
                $(this).attr("tabIndex", -1);
            });
        }
    });


texts: Userscript to add Prettify extensions on SE

texts:
I wrote a userscript (to be run with Greasemonkey/Tampermonkey on Stack Exchange sites) to include a Prettify extension and enable syntax highlighting for a language which isn't supported by default.

I have only occasionally dabbled in JavaScript, and I have never written a userscript before:

(function (func) {
    // helper for injecting the script into the page
    var script = document.createElement("script");
    // insert a script element...

    script.type = 'text/javascript';
    script.appendChild(
            // with a function which is called on document ready
            document.createTextNode("$(" + func + ")")
            );
    // run the script after other scripts
    document.body.appendChild(script);
})(function () {
    // Helper to check if post tags contain `vim`
    var tagsIncludeVim = function () {
        var tags = document.getElementsByClassName('post-tag');
        for (var i = 0; i < tags.length; i++) {
            var t = tags[i];
            if (t.textContent.includes("vim")) {
                return true;
            }
        }
        return false;
    };
    // Run by default only on (meta)vi.se, or if the post tags contain `vim`.
    if (!window.location.hostname.endsWith("vi.stackexchange.com") && !tagsIncludeVim()) {
        console.log('Not highlighting!');
        return;
    }

    var setLanguage = function () {
        var pres = document.getElementsByTagName('pre');
        for (var i = 0; i < pres.length; i++) {
            var p = pres[i];
            // If already highlighted or language has been specified manually
            if (/prettyprint(?:ed|-override)/.test(p.className)) {
                continue;
            }
            p.className = 'lang-vim prettyprint';
        }
        prettyPrint();
    };

    var langscript = document.createElement("script");
    langscript.type = 'text/javascript';

    /*
    Since Github blocks hotlinking of scripts, and I really don't feel
    like using a third-party site for it, I'll fetch the script
    manually...
    */
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            langscript.appendChild(document.createTextNode(xhr.responseText));
        }

        /*
        Need to ensure Prettify is loaded.
        See http://meta.stackexchange.com/a/278614/270345
        */
        StackExchange.using('prettify', function () {
            document.body.appendChild(langscript);
            observer = new MutationObserver(setLanguage);
            observer.observe(document.body, {childList: true});
        });
    };
    xhr.open("GET", "https://raw.githubusercontent.com/hail2u/google-code-prettify-language-handlers/master/lang-vim.js", true);
    xhr.send();
});

Intended targets:

Supported versions of Google Chrome and Firefox. IE is not in my mind.

Known problems:

At first run, syntax highlighting is enabled but for a default language. I think this is due to caching of some sort, since it works fine after a refresh. I don't think it's a bug in the code.

Future plans:

Add a UI to allow specifying alternate extension URLs and languages and disable the extension. (I'm not asking how to do that, but if there are parts of the code that should be encapsulated for that purpose, do tell.)


texts: Arduino project to indicate soil moisture using LEDs

texts:
I've recently started going through the Head First C book. I'd like to get up to speed in terms of writing good, idiomatic, modern C. I have read the first few chapters of the Modern C book too but found Head First to be a better introduction to the language.

The code below is for the first, bigger, arduino assignment. It's a pretty straight forward assignment, an LED should be used to indicate the soil moisture of a plant. I've gone beyond the base assignment by using a 3-color LED  where pin 11 should be high for green, 12 high for red and both high for orange.

This creates a bit of a challenge in creating a nice, consistent api which abstracts those details. I wanted to use pointers and pointer arithmentic in the solution just to get some exposure to them. I could probably re-write using arrays and avoid the need for 0 last elements although I would still need to deal with pointer decay.

Any pointers :-) on what could be changed to turn this into a good, idiomatic, modern solution? Regardless of pointer use or not.

int const RED[] = { 12, 0 };
int const GREEN[] = { 11, 0 };
int const ORANGE[] = { 11, 12, 0 };
int const DEFAULT_DURATION = 1000;
int const DEFAULT_COUNT = 1;

void blink(int color[]);
void blink(int color[], int duration, int count);
void blinkSequence(int* color[]);
void blinkSequence(int* color[], int duration, int count);
void on(int color[]);
void off(int color[]);

void setup() {
  // initialize LED Pins as output
  Serial.begin(9600);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
}

void loop() {
  int m = analogRead(0);
  int interval = 2000;
  Serial.print("Moisture is: ");
  Serial.println(m);
  if (m <= 580) {
    //Really Dry!: 580-
    int* seq[] = { RED, ORANGE, 0 };
    blinkSequence(seq, 150, 2);
    interval = 0;
  } else if (m <= 700) {
    //Needs water: 700 - 581
    blink(RED, 500);
    interval = 500;
  } else if (m <= 740) {
    //Could be wetter: 740 - 701
    blink(ORANGE, 4000);
    interval = 50;
  } else if (m <= 870) {
    //Happy range: 870 - 741
    blink(GREEN, 5000);
    interval = 50;
  } else {
    //Overwatered: 870+
    int* seq[] = { GREEN, ORANGE, 0 };
    blinkSequence(seq, 200, 5);
    interval = 3000;
  }

  delay(interval);
}

void blinkSequence(int* colors[], int duration, int count) {
  for (int i = count; i > 0; i--) {
    int** inner = colors;
    for(;*inner;inner++) {
      blink(*inner, duration);
    }
  }
}

void blink(int color[], int duration) {
  on(color);
  delay(duration);
  off(color);
}

void blinkSequence(int* colors[]) {
  for(;*colors;colors++) {
    blink(*colors);
  }
}

void blink(int color[]) {
  on(color);
  delay(DEFAULT_DURATION);
  off(color);
}

void on(int color[]) {
  for(;*color;color++) {
    digitalWrite(*color, HIGH);
    //Serial.print("HIGH:");
    //Serial.println(*color);
  }
}

void off(int color[]) {
  for(;*color;color++) {
    digitalWrite(*color, LOW);
    //Serial.print("LOW:");
    //Serial.println(*color);
  }
}


texts: Proper way to find newest file in a directory

texts:
I wanted to ask if this is a better way to find a latest file in given directory. This is my current approach:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.ZoneId;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesOperations {

    public static void main(String[] args) throws IOException {

        Set<Path> pathSet = getFilesFromDirectory("C:some/path/");

        iteratePaths(pathSet);

        getLatestFile(pathSet);
    }

    public static Set<Path> getFilesFromDirectory(String directory) {

        Set<Path> pathSet = new HashSet<>();

        Pattern pattern = Pattern.compile("(test\\d-)(\\d{12})(\\.txt)");
        Path lookUpPath = Paths.get(directory);

        Stream<Path> stream = null;
        try {
            stream = Files.find(lookUpPath, 1, (path, basicFileAttributes) -> {
                File file = path.toFile();
                return !file.isDirectory() && pattern.matcher(file.getName()).matches();
            });

            stream.forEach(path -> {
                pathSet.add(path);
            });

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

        stream.close();
        return pathSet;
    }

    public static void iteratePaths(Set<Path> pathSet) {
        pathSet.stream().forEach(path -> {
            System.out.println(path);
        });
    }

    public static Path getLatestFile(Set<Path> pathSet) throws IOException {

        long fileTime = 0;
        Path pathToReturn = null;
        BasicFileAttributes attr = null;

        for (Path path : pathSet) {
            attr = getBasicFileAttributes(path);
            if (attr.creationTime().toMillis() > fileTime) {
            fileTime = attr.creationTime().toMillis();
                pathToReturn = path;
            }
        }

        attr = getBasicFileAttributes(pathToReturn);
        System.out.println("Latest file: " + pathToReturn + " - " + attr.creationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        return pathToReturn;
    }

    private static BasicFileAttributes getBasicFileAttributes(Path pathToReturn) throws IOException {
        BasicFileAttributes attr;
        attr = Files.readAttributes(pathToReturn, BasicFileAttributes.class);
        return attr;
    }

}

I know this is quite simple without any sophisticated solutions, but it works. I hope you can point some places for improvements. If you have some ideas, how to refactor code to use more streams, it would be great (e.g. in getLatestFile() ).


texts: Speed Up Excel Macro - Autofilter Copying

texts:
I am using this code which works fine, but runs painfully slow.

The code filters an Excel Table and then extracts only certain columns and pastes them into another sheet (in a different order).

Could it be sped up perhaps with a multi-dimensional array?

With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
.EnableEvents = False
End With

Set lo_b1 = x_bf1.ListObjects(1)
s_date = CLng(ThisWorkbook.Names("in_fre_m").RefersToRange(1, 1))
s_des = ThisWorkbook.Names("dr_no").RefersToRange(1, 1)
s_code = ThisWorkbook.Names("dr_co").RefersToRange(1, 1)
lastrow_d = lo_dr.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Set pasterange1 = x_drill.Range("C" & lastrow_d)

    With lo_b1.Range
    .AutoFilter Field:=13, Criteria1:=s_code
    .AutoFilter Field:=1, Criteria1:="<=" & s_date
    End With

lastrow_s = lo_b1.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

If lastrow_s > 7 Then
    Set copyrange1 = x_bf1.Range("D8:D" & lastrow_s) 'Date
    Set copyrange2 = copyrange1.Offset(0, 1)  'Description
    Set copyrange3 = copyrange1.Offset(0, 16)  'Calculation
    Set copyrange5 = copyrange1.Offset(0, 5)  'Classification
    Set copyrange6 = copyrange1.Offset(0, 6)  'Notes
    Set copyrange7 = copyrange1.Offset(0, 11) '§
    Set copyrange8 = copyrange1.Offset(0, 12) 'Code
    Set copyrange9 = copyrange1.Offset(0, 20) 'Statutory
    Set copyrange10 = copyrange1.Offset(0, 14) 'Ref

    copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
    pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date
    pasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange5.SpecialCells(xlCellTypeVisible).Copy 'Account Name
    pasterange1.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange2.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange8.SpecialCells(xlCellTypeVisible).Copy 'Code
    pasterange1.Offset(0, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange7.SpecialCells(xlCellTypeVisible).Copy '§
    pasterange1.Offset(0, 5).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange3.SpecialCells(xlCellTypeVisible).Copy 'Calculation
    pasterange1.Offset(0, 6).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange9.SpecialCells(xlCellTypeVisible).Copy 'Statutory
    pasterange1.Offset(0, 7).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange6.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 8).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    Set copyrange1 = Nothing
    Set copyrange2 = Nothing
    Set copyrange3 = Nothing
    Set copyrange4 = Nothing
    Set copyrange5 = Nothing
    Set copyrange6 = Nothing
    Set copyrange7 = Nothing
    Set copyrange8 = Nothing
    Set copyrange9 = Nothing
    Set copyrange10 = Nothing
    End If


texts: X86 Feature detection in preparation for Long Mode

texts:
These are the three steps that need to be taken in order to successfully activate Long Mode. Error reporting is sparse as most real hardware for developing an OS is 64 bit but probably still a good idea to implement this verification procedure.

I did a little tweaking of some of the examples that can be found on the web either in whole or in part and believe 74 bytes might be as tight as it can get.

    PageZero    equ 0xb800
        ID  equ 0b100000

; AMD 24592 Rev 3.14 2007 Feature detection. Section 3.6 pg 74
; ------------------------------------------------------------

  ; A: Test if CPU supports CPUID

    pushfd          ; Save a current copy of flags

    ; Create a simplified pointer that becomes essentially SS:BX

    push    ss
    mov     bx, sp      ; BX will point to bits 23-16 of EFLAGS
    pop     ds

    ; Read flags, toggle (ID) and write back to flags.

    pushfd                  ; Get another copy of EFLAGS
    or      byte [bx], ID   ; Toggle bit 21 (ID) [bit 5 of BX]
    mov     al, [bx]        ; Save a copy
    popfd                   ; Write value back to EFLAGS

    ; Read flags again and if ID remains inverted, then processor supports CPUID.

    pushfd
    pop     dx              ; DX = Bits 15 - 0 of EFLAGS
    pop     dx              ; DX = Bits 16 - 31
    popfd                   ; Restore flags to original values
    xor     al, dl          ; Bit 4 of AL & DL is (ID)
    jz      TstExt

; As this error is very improbable, near center bottom there will be an uppercase "E"
; yellow on red, with two red flashing bars on each side.

FncErr: mov di, (22*80+39)*2 ; Point to center position of 21th row in video
        mov ax, PageZero     ; Page 0 of 80x26x16 (Mode 3)
        mov es, ax
        mov eax, 0x2e4684b1 ; This makes the desired character combination work
        stosd
        stosw

        cli
        hlt
        jmp     $ - 1       ; Just hang.

  ; B: Are extended functions supported

TstExt:
    mov     eax, 0x80000000
    push    eax
    cpuid           ; Extended function limit
    pop     edx
    cmp     eax, edx
    jb      FncErr

  ; C: Does processor support Long Mode.

    mov     al, 1       ; Set EAX = 0x80000001
    cpuid
    bt      edx, 29     ; 64 bit available if bit is on.
    jnc     FncErr


texts: Reverse each group of k elements in a list

texts:
Challenge
Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case represented by a comma separated list of numbers and the number k, separated by a semicolon.
Print the comma separated list of numbers after reversing.
If the number of elements is not a multiple of k, then the remaining elements should be unaltered.

Sample Input

1,2,3,4,5;2
1,2,3,4,5;3

Sample Output

2,1,4,3,5
3,2,1,4,5

Source
My Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No file path provided.");
            System.exit(1);
        }

        if (args.length >= 2) {
            System.out.println("Excessive arguments only the first will be considered.");
        }

        try (Scanner file = new Scanner(new File(args[0]))) {
            while (file.hasNextLine()) {
                System.out.println(reversed(file.nextLine()));
            }
        } catch (FileNotFoundException fnfe) {
            System.err.println("Could not find file.");
        }
    }

    private static String reversed(String line) {
        String[] helper = line.split(";");
        int k = Integer.parseInt(helper[1]);
        if (k == 0) {
            return helper[0];
        }
        return reversedByK(helper[0].split(","), k);
    }

    private static String reversedByK(String[] nums, int k) {
        StringBuilder result = new StringBuilder();
        for (int i = k - 1; i < nums.length; i += k) {
            for (int j = i; i - j <= k - 1; j--) {
                result.append(',').append(nums[j]);
            }
        }

        for (int i = nums.length - nums.length % k; i < nums.length; i++) {
            result.append(',').append(nums[i]);
        }
        return result.substring(1);
    }
}


texts:
Are there Rust features I could apply to optimize for simple test of a JPEG or PNG resized from 2000 x 2000 pixels to 150 x 150 pixels?

extern crate image;
use std::env;

fn main() {
    let mut args = env::args();
    args.next();
    let file_location = args.next().unwrap();
    let width = args.next().unwrap().parse().unwrap();
    let height = args.next().unwrap().parse().unwrap();

    let img = image::open(file_location.as_str()).unwrap();

    // img.resize(width, height, image::imageops::Lanczos3);
    img.thumbnail(width, height);
}


texts:
I was using a Boolean var for indication of loading so my code looked like this:
(this example is in angularjs but i think it can be relevant for any ajax call handlers)

//HTML:

...LOADING...

//JS:
//Init
$scope.isLoading = false;

//Executing http request:
$scope.isLoading = true;
mainService.post(alteredItems).then(function (response) {
init();
}).catch(function (err) {
  $scope.callBack(err);
}).finally(function () {
  $scope.isLoading = false;
});

function init() {
  $scope.isLoading = true; //another loading
  mainService.get().then(function (response) {
  if (response) {

  }
  $scope.isLoading = false;
  });
}

The problem I had was that if 1 ajax method will complete before the other one so the "isLoading" will be false, and the loader will not be displayed although the request has not yet ended.

I converted the $scope.isLoading to int. So now code looks like this:

//Init
$scope.isLoading = 0;

//Start any ajax call
$scope.isLoading++;

//Finish
$scope.isLoading--;

Which works great, also no need to change the html because of the casting.
I can't find a drawback in this approach and it seems better than the Boolean option.

What do you think?


texts:
Just over half way through in K&R, came across an exercise to convert from postfix ("reverse-Polish") notation to infix (standard) notation.

Basically I'm posting here to see if there is anything excessive in my code, or any way to reduce the amount of storage it takes up. It runs extremely fast and doesn't take up much space, but if space can be reduced I believe it always should be.

Also, I have tried to maintain the clearest readability and consistent style throughout my code, but I am new to C, so if there are certain style conventions I am breaking, let me know as well.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAXLEN 1000    // Maximum string length

int isOperator(int c);
void addPrecedence(char * infixExpr);
void pushExpression(char * infixExpr);
char * popExpression(void);

int main(int argc, char * argv[])
{
    // Only one argument is allowed
    if (argc != 2) {
        printf("Usage: evaluate [expression] from postfix to infix\n");
        return 1;
    }

    int i;
    char * expression = argv[1];
    char left[MAXLEN], right[MAXLEN], expr[MAXLEN];

    for (i = 0; expression[i] != '\0'; i++) {
        if (isalpha(expression[i]) || isdigit(expression[i])) {
            // Copy character into a string so it can be pushed onto the stack
            expr[0] = expression[i], expr[1] = '\0';
            pushExpression(expr);

        } else if (isOperator(expression[i])) {
            strcpy(right, popExpression());
            strcpy(left, popExpression());

            expr[0] = expression[i], expr[1] = '\0';
            strcat(left, expr);
            strcat(left, right);
            addPrecedence(left);
            pushExpression(left);

        } expr[0] = '\0';    // Reset expr character array
    }
    printf("%s\n", popExpression());
    return 0;
}

// Check if the character is a valid operator
int isOperator(int c)
{
    int i;
    char legalOps[] = {'+', '-', '*', '/'};

    for (i = 0; i < 4; i++)
        if (c == legalOps[i])
            return 1;
    return 0;
}

// Wrap the expression in paranthesis to maintain order of precedence
void addPrecedence(char * infixExpr)
{
    int i, needsPrecedence = 0;

    // Check if parens are even needed
    for (i = 0; infixExpr[i] != '\0'; i++) {
        if (infixExpr[i] == '(') {
            break;

        } else if (infixExpr[i] == '+' || infixExpr[i] == '-') {
            needsPrecedence = 1;
            break;
        }
    }
    // If parens are needed, insert them at the beginning and end
    if (needsPrecedence) {
        infixExpr[strlen(infixExpr)] = ')';
        for (i = strlen(infixExpr)-1; i >= 0; i--)
            infixExpr[i+1] = infixExpr[i];
        infixExpr[0] = '(';
    }
}

#define MAXEXPR 100    // Maximum expression stack value

// Create expression stack
char expressionStack[MAXEXPR][MAXLEN];
int currentExpr = 0;

// Push an expression (character array) onto the expression stack
void pushExpression(char * infixExpr)
{
    int i = 0;

    // Copy each character from infixExpr into the expression stack
    while (*infixExpr != '\0')
        expressionStack[currentExpr][i++] = *infixExpr++;

    // Delete any additional data from previous stack value
    expressionStack[currentExpr][i] = '\0';
    ++currentExpr;
}

// Return expression (character array) from top of stack
char * popExpression(void)
{
    // Return NULL if expression stack is empty
    if (currentExpr == 0 || expressionStack[currentExpr-1][0] == '\0') {
        return 0;

    } else {
        // Save expression to be returned, then delete it from the stack
        char * expr = expressionStack[--currentExpr];
        return expr;
    }
}


texts: Addition function for two Big Integers represented as std::string

texts:
This function is from my attempt to write a Big Integer class in C++.

Below, I have a simple addition function.
It takes two strings of arbitrary length which contains only digits (no
'-' sign as well). It returns the sum of the two integers.

Could someone help me optimize for performance?

Since this is my first attempt writing C++ code, I would love for some feedback and improvements in code clarity and style as well. Furthermore, any improvements in security and memory are also appreciated. Please assume that the input will be properly sanitized and no leading zeros are present. I have not included the entire class as it can work as a standalone function.

std::string BigInt::add(const std::string &a, const std::string &b) const
{
    //I think keeping the assignment and declaration of addend in
    // multiple lines prevents copy constructors, right?
    std::string result(a.size() > b.size() ? a:b);
    std::string addend;
    addend = a.size() > b.size() ? b:a;

    char carry = 0;
    char adder = 0;
    for(int cnt = (result.size() - 1); cnt >= 0; cnt--)
    {
        adder = result[cnt] - '0' + carry;
        //cnt is non-negative so it is safe cast
        if( (result.size() - addend.size()) <= static_cast<unsigned>(cnt))
        {
            adder += addend[cnt-(result.size()-addend.size())] - '0';
        }
        result[cnt] = adder%10 + '0';
        carry = adder/10;
    }
    //This propagates the final carry. O(n) insert, can maybe be optimized?
    if(carry)
    {
            result.insert(result.begin(), carry + '0');
    }
    return result;
}


texts: Stack implementation with StackInterface

texts:
The code that I wrote is as follows:

public  class Astack implements StackInterface {
private int sz;
private Object[] a;
private int topPosition = -1;
public Astack(int sz){
   a = new Object[sz];
   this.sz = sz;
}
public int size(){
return topPosition+1;
}
public boolean isEmpty(){
  if(topPosition == -1){
  return true;
}
  return false;
}
public void push(Object element) throws StackFullException{
  if(topPosition+1 == sz){
    throw new StackFullException("Stack Full.");
  }
  a[++topPosition] = element;
}
public Object top() throws StackEmptyException{
  if(topPosition == -1){
    throw new StackEmptyException("Stack already Empty");
  }
return a[topPosition];
}
public Object pop() throws StackEmptyException{
  if(topPosition == -1){
    throw new StackEmptyException("Stack already Empty");
  }
  return a[topPosition--];
}
}

The StackInterface that I wrote:

public interface StackInterface{
    public int size();
    public boolean isEmpty();
    public Object top() throws StackEmptyException;
    public void push(Object element) throws StackFullException;
    public Object pop() throws StackEmptyException;
}


texts: Small bash script to enhance virtual environments on directory navigation

texts:
Ages ago I made a small bash script which would add a command cdp, standing for "change directory - project".

What it did was simple, it added all folders in ~/projects as autocompletion and CD'd me into them using only the project folder's name.

Over time I switched to a different company where I started working with Python, thus needing virtual environments not to mess up my workstation, which led me to adding more functionalities to the script.

I rarely use bash to do anything, rather using Python or even PHP for simple CLI tasks. I was hoping for some input regarding my first ever bash script, though, so I can keep my terminal scripts in its native language.

I think some improvements could be the way I name and call functions, and the newly added command should probably be something other than an alias.

#!/usr/bin/env bash

funcCheckVirtualEnvironment()
{
    if [ -d "venv/" ]; then
        read -p "A virtual environment was found for this project, would you like to execute the activation script? [y/n]" -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            source venv/bin/activate
            if [ -e "requirements.txt" ]; then
                read -p "PyPi requirements were found, would you like to install any uninstalled packages? [y/n]" -n 1 -r
                echo
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    pip install -r requirements.txt
                fi
            fi
        fi
    fi
}

funcCDP()
{

    # Add more flags in future, maybe
    case "$1" in
    "-r" )
        funcCheckVirtualEnvironment
        return 0 ;;
    esac

    if [ -d ~/projects/$1 ]; then
        cd ~/projects/$1;
        funcCheckVirtualEnvironment
    else
        echo "Directory $1 does not exist!"
    fi

}

funcCD()
{
    if [ $1 == "-"] || [ -d $1 ]; then
        command cd "$@"
        if [ -d "venv/" ]; then
            funcCheckVirtualEnvironment
        fi
    else
        echo "No such file or directory: $1"
    fi
}

_cdp()
{
        local cur=${COMP_WORDS[COMP_CWORD]}
        COMPREPLY=( $(compgen -W '$(\ls ~/projects)' -- $cur) )
}
complete -F _cdp cdp
alias cdp=funcCDP
alias cd=funcCD


texts: What improvements can I make to avoid these If statments?

texts:
I have Model Object Car.

public class Car
{
  private String colour;
  private String make;
  private String yearOfMake;
}

Then a managed bean

public Class CarSearchManagedBean
{
  private Car car;

  @EJB
  private CarFacade carFacade;

  public String search()
  {
     this.car =carFacade.find(car);
     .....
  }
}

Then I have a JSF facelet with input fields connected to car object by backing bean and a search button linked to search method .There is no Ajax and use can provide values for any property and since there is no auto cleaning can possibly provide values more than one property but search only uses one.

Then before I show CarFacade I will show CarDao becasue I think makes more sense here.

public class CarDaoImpl implements CarDao
{
  public Car findByColour(Car car){
  //Calls a webservice method
  }
  public Car findByMake(Car car){
  //Calls a webservice method
  }
  public Car findByYearOfMake(Car car){
  //Calls a webservice method
  }

}

Now if the CarFacade I have this ugly if statment that I do not know how to avoid.

public class CarFacade

{
   @EJB
   CarDao carDao;

   public Car find(final Car car)
   {
      Car aCar ;
      //How can improve the design to avoid this If statment
      if (car.getColour()!=null)
      {
       aCar = carDao.findByColour(car)
      }
      else if (car.getMake()!=null)
      {
        aCar = carDao.findByMake(car);
      }
      else
      {
        aCar =carDao.findByYearOfMake(car);
      }
      return aCar;
   }
}


texts: Readable implementation of Trie in Python

texts:
Need reviews on my readable implementation of Trie. Also what other methods can or should be added to this data structure.

from collections import defaultdict

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def add(self, word):
        curr = self.root
        for letter in word:
            node = curr.children.get(letter)
            if not node:
                node = TrieNode()
                curr.children[letter] = node
            curr = node
        curr.end_of_word = True

    def search(self, word):
        curr = self.root
        for w in word:
            node = curr.children.get(w)
            if not node:
                return False
            curr = node
        return curr.end_of_word

    def all_words_beginning_with_prefix(self, prefix):
        curr = self.root
        for letter in prefix:
            node = curr.children.get(letter)
            if curr is None:
                raise KeyError("Prefix not in Trie")
            curr = node
        result = []

        def _find(n, p):
            if n.end_of_word:
                result.append(p)
            for k, v in n.children.items():
                _find(v, p + k)

        _find(curr, prefix)
        return result

class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.end_of_word = False

This is the calling client that can be used to test the code.

if __name__ == '__main__':
    trie = Trie()
    trie.add('foobar')
    trie.add('foo')
    trie.add('bar')
    trie.add('foob')
    trie.add('foof')

    print(list(trie.all_words_beginning_with_prefix('foo')))


texts: Recursive uniform cost search that needs to be optimized

texts:
I have this uniform cost search that I created to solve Project Euler Questions 18 and 67. It takes the numbers in the txt file, places them into a two dimensional list, and then traverses them in a uniform cost search (that I hoped was a kind of implementation of an a* search). It looks like this:

f = open('triangle.txt', 'r')
actualRows = [[n for n in p.split(" ")] for p in f.read().split('\n')]
actualRows.pop()
actualRows = [[int(n) for n in p] for p in actualRows]
rows = [[100 - n for n in p] for p in actualRows]

def astar(pq):
    m = min(pq,key=lambda w: w[3])
    if len(m[2]) + 1 is len(actualRows):
        return m
    pq.remove(m)
    toAdd = list(m[2])
    toAdd.append(m[0])
    pq.append((actualRows[m[4]+1][m[5]], rows[m[4]+1][m[5]], toAdd, m[3] + m[1], m[4]+1, m[5]))
    pq.append((actualRows[m[4]+1][m[5]+1], rows[m[4]+1][m[5]+1], toAdd, m[3] + m[1], m[4]+1, m[5]+1))
    return astar(pq)

# Each tuple is: (actualScore, minScore, previous, totalScore, y, x)
priorityQueue = [(actualRows[0][0], rows[0][0], [], 0, 0, 0)]
a = astar(priorityQueue)
print a
print str(sum(a[2]) + a[0])

I'm not asking for you to tell me how to solve the Problem, I just want to optimize this search so that it doesn't crash going past the 17th row of numbers. How would I optimize this? Or how would I write a proper uniform cost search?


texts: Finding the closest value in a collection in a game-server plugin implementation

texts:
I have an array of a instances of an enum type. A random double variable is initialized with a value between 0.... to 1, and should be used to get the closest value's enum instance to that randomly set double value.
The enum looks like this:
public enum TargetScope {

    CLEAN(1, 5040),
    FIRST(.888, 5046),
    SECOND(.777,5052),
    THIRD(.666,5058),
    FOURTH(.555, 5064),
    FIFTH(.444, 5070),
    SIXTH(.333, 5076),
    SEVENTH(.222, 5082),
    EIGHTH(.001, 5088);

    private int interfaceBase;
    private double time;

    TargetScope(double time,int interfaceIdBase) {
        this.time = time;
        this.interfaceBase = interfaceIdBase;
    }

    public int getTime() {
        return (int) this.time * TargetManager.TARGET_SEARCH_WAIT;
    }

    public int getInterfaceBase() {
        return this.interfaceBase;
    }

    public double getPercent() {
        return this.time;
    }
}

I have implemented an algorithm which does that, using the array and few temp variables:
public TargetScope getInterfaceScopeByTime() {
    double alpha = (double) this.time / TargetManager.TARGET_SEARCH_WAIT;

    TargetScope[] scopes = TargetScope.values();

    double delta = 1;
    TargetScope scope = null;

    for (int i = 0; i < scopes.length; i++) {
        double distance = Math.abs(scopes[i].getPercent() - alpha);
        if (distance < delta) {
            delta = distance;
            scope = scopes[i];
        }
    }

    return scope;
}

Basically it gets the closest Enum.getPercent() value in the list to alpha, and then returns the final closest TargetScope instance.
But I really feel bad about using this, where Java has an advanced collection API, which can be used better for this case, but I am not really as experienced with Collections API to use them for that.
Is there really a shorter way to perform this?
The idea behind this
I am working on a game-server plugin, which basically makes two players targets and have them fight each other. For a player to get a target, he needs his target-timer to hit 0, in order to let the system search for a target. Originally, the default target timer is 1000, each system cycle is 600ms, so 1000 is 10 minutes.
Each player has an interface that looks like a sliced circle to 8 pieces, something like this:

I need to let the interface know, what slices should be filled with colour, to let the player know when he can get his target. a fully coloured scope (circle) means that the timer hit 0.
Each interface slice has it's own id, as you see in the enum, int interfaceBase.
I need to update the player's interface, by using the player's current left time.
So if his time is 800, I do 800 / 1000, I get 0.8, now from the enums list, the closest enum is called SECOND because the closest value to 0.8 out of the list is 0.777, therefore when the server updates player's interface exactly when the timer is 800, then the interface will display one slice out of 8.
The interface updates every 10 seconds, per player (as in each player has its executor).


texts:
This is working code, but I want to simplify, correct, and improve the code.

window.addEvent = function(elem,type,callback) {
    var evt = function(e) {
        return callback.call(elem,e);
    };
    var cb = function(e) { return evt(e); };
    elem.addEventListener(type,cb,false);
    return elem;
};
window.findParent = function(child,filter,root) {
    do {
        if( filter(child)) return child;
        if( root && child == root) return false;
    } while(child = child.parentNode);
    return false;
};
function on(type, target, callback) {
  window.addEvent(document.body, type, function(e) {
    var s = window.findParent(e.srcElement || e.target, function(elm) {
        return elm.classList.contains(target);
    },this);

    if( s && callback ) {
        callback(e)
    }
  });
}
on("click", "page-link", function(e){
 console.log("hey its working");
});

In this example, I update the pagination with fetch, and I have to bind addEventlistener to every page link. I am thinking about, If its there a cleaner way, using the latest techniques?  (with pure Javascript)


texts:
I am trying to get a better understanding of the modular design pattern and I am using Requirejs to manage my dependencies.

I understand separating code into modules (using define with RequireJS) so they take on only single responsibilities and also splitting them into separate JavaScript files so Require JS can load them.

In my main.js, the entry points looks like this (which depends on work module).  For brevity, I have left out the require.config, paths, etc.:

require(
  ['work'],
  function(work) {
     var url = "urlstring";
     work.buildHTMLTable(url);
  }
);

the method buildHTMLTable will append html table to a div tag.

I want to build a re-usable generic js library that will handle vertical/horizontal scroll event and arrow key navigation event.  I need direction on how to incorporate these events.  The below method is working, but I wanted to make sure I was setting everything up correctly.

Should I have one define method that has a function which takes care of handling the scrolling like so?

define('scrollingGrid',
    ['jquery'],
    function ($) {

       var bindScroll = function (hs, vs) {

       $(hs).on('scroll', function (e) {

       }

       $(vs).on('scroll', function (e) {

       }

        }; return {
        bindScroll: bindScroll
        };

    }

);

and then I can call it from the main as so:

require(
      ['work', 'grid'],
      function(work) {
         var url = "urlstring";
         work.buildHTMLTable(url);

         grid.bindScroll('#hscroll', '#vscroll');

      }
    );

Should I also handle the arrow key navigation in the same scrollingGrid module (see below)?

require(
          ['work', 'grid'],
          function(work) {
             var url = "urlstring";
             work.buildHTMLTable(url);

             grid.bindScroll('#hscroll', '#vscroll');
             grid.bindArrow('#tab');

          }
        );

In summary, I am creating a re-usable JavaScript control that could handle events on an HTML table.  Is what I am doing okay or is there a better way?


texts: Creating membership list with Parallel.ForEach

texts:
I had a foreach loop which used to loop Membership users and create list of a custom class. Following was the for loop:

foreach (MembershipUser usr in userlist)
{
    userandGroup usrgp = new userandGroup();
    usrgp.id = ((Guid)usr.ProviderUserKey).ToString() ;
    usrgp.Name = usr.UserName;
    ProfileBase profile = ProfileBase.Create(usr.UserName);
    profile.Initialize(usr.UserName, true);
    // Following line takes approx 40ms to execute once.
    usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString();
    usrgp.type = "user";
    lst.Add(usrgp);
}

As the commented line used to take approx 40ms to execute, the whole loop for 40 users used to take approx 1600ms to execute.

I got suggestion to use Parallel.ForEach loop to reduce the execution time of the loop from this question

SO I updated the loop as:

    Object obj = new Object();
    Parallel.ForEach(userlist, (usr) =>
    {
        userandGroup usrgp = new userandGroup();
        usrgp.id = ((Guid)usr.ProviderUserKey).ToString();
        usrgp.Name = usr.UserName;
        ProfileBase profile = ProfileBase.Create(usr.UserName);
        profile.Initialize(usr.UserName, true);
        usrgp.type = "user";
        usrgp.DisplayName = profile.GetPropertyValue("FirstName").ToString() + " " + profile.GetPropertyValue("LastName").ToString();
        lock (obj)
        {
            lst.Add(usrgp);
        }
    });

The loop works. Now the performance is way better (Although not best). It now takes only 700ms to execute the loop.

But I am not sure if it is the correct way to write Parallel.ForEach loop as I am new to it. Kindly suggest if the code is right?


texts: How to put apt and python packages in a list and check if installed or not then install

texts:
I am not an expert in shell scripting,
I need help optimizing the shell script I wrote, This shell script I wrote is run by users on the client side who connect to our vpn server from the setting passed in the config.tar.
I check if pip or or tar or other packaches are installed if not isntalled than install it, I am doing it in separate if condition, what I want to achieve is I put the packages to check in a  listand then iterate if not installed than install it for all apt, pip or pip3 packages.
#!/usr/bin/env bash
set -

command=`which pip`

if [ "$command" = "" ]
then
    echo "The pip program not exist on this system."
    sudo apt-get install python-pip -y
    sudo apt install python3-pip -y
else
    echo "Pip is intalled."
fi
sudo apt install speedtest-cli
pip install -U pip
pip3 install mysql-connector-python
pip3 install pymysql
pip3 install sqlalchemy

TAR=`which tar`

if [ "$TAR" = "" ]
then
    echo "Tar is not installed,  installing now."
    sudo apt-get install tar -y
else
    echo "Tar is installed."
fi

# lets install requests
pip install requests

cd $HOME
echo "Iniating download..."
curl -sL "http://my.domain.com/config" -o "config.tar"

tar xvf config.tar
sudo chmod 604 ucc.py

if [ -e ucc.py ]
then
    echo "ucc.py installed."
else
    echo "ucc.py failed to download."
fi

if [ -e ucc.service ]
then
    echo "ucc.service installed."
else
    echo "ucc.service failed to download."
fi

sudo mv ucc.service "/lib/systemd/system/"

if [ -e client.conf ]
then
    sudo mv client.conf /etc/openvpn/
    echo "client.conf downloaded."
else
    echo "client.conf failed to download."
fi

sudo mv -f client.conf /etc/openvpn/

cd /etc/openvpn/

if [ -e client.conf ]
then
    echo "client.conf installed."
else
    echo "client.conf failed to download."
fi

sudo systemctl restart openvpn@client
sudo systemctl status  openvpn@client

any help will be greatly appreciated.


texts: N-Queens problem using other pieces using Go

texts:
I wrote a solution to a problem based on the N-Queens problem which should use more pieces than just queens. Problem is it's very slow, it probably has to do with how I modeled data and my lack of knowledge on how to compare boards without the possibility of extending from an interface compareTo as I would do in a language like Java.

This is the algorithm:

func Solution(board b.Board, pieces []rune, solutions *[]b.Board, testedConfigurations *[]b.Board) *[]b.Board {
    if len(pieces) != 0 {
        for i := 1; i < board.M; i++ {
            for j := 1; j < board.N; j++ {
                c := p.CreatePiece(pieces[0], i, j)
                if b.IsSafe(board, c) {
                    modifiedBoard := b.Place(board, c)
                    if len(pieces) != 1 {
                        if !contains(modifiedBoard, *testedConfigurations) {
                            *testedConfigurations = append(*testedConfigurations, modifiedBoard)
                            Solution(modifiedBoard, pieces[1:], solutions, testedConfigurations)
                        }
                    } else {
                        if !contains(modifiedBoard, *solutions) {
                            *solutions = append(*solutions, modifiedBoard)
                            println("Found Solutions", len(*solutions))
                        }
                    }
                }
            }
        }
    }
    return solutions
}

This is how I represent a piece in the board:

type Piece struct {
    Name rune
    Row  int
    Col  int
}

This is how I represent the board

type Board struct {
    M     int
    N     int
    Board [][]rune
    Used  []primitives.Attacks
}

This is the Attacks interface (I use it to check if a piece attacks another):

type Attacks interface {
    Attacks(piece Attacks) bool
    Row() int
    Col() int
    Name() rune
    ToString() string
}

This is what I use to check if a solution is already been used:

func contains(boardContains b.Board, testedConfigurations []b.Board) bool {
    for _, k := range testedConfigurations {
        if len(k.Used) == len(boardContains.Used) && EqualBoards(k.Board, boardContains.Board, k.M, k.N) {
            return true
        }
    }
    return false
}

And this is what I use to check if two boards are equal:

func EqualBoards(board1 [][]rune, board2 [][]rune, M, N int) bool{
    for i:=1; i< M; i++ {
        for j:=1; j< N; j++ {
            if board1[i][j]!=board2[i][j] {
                return false
            }
        }
    }
    return true
}

Here's the code


texts:
I am new to object oriented design with JavaScript and am trying to make a PublicGame class with some methods that puts itself in a map of games. It calls killGame on itself if there aren't enough players. I feel like my design is way off. I won't be able to test my design though until the rest of my group members finish their parts, so I could use some feedback.

Here's a link to my state diagram. Everything in yellow is the game.

'use strict';

// var GameSockets = require(‘GameSockets’);
var Games = {};
var id_counter = 0;
var minPlayers = 3;
var maxPlayers = 6;

function PublicGame (players) {
    this._id = id_counter++;
    this.players = players;
    this.gameSocket = new GameSockets.registerPlayers(this.players, this._id, this.playerDisconnects);

    this.judge = this.setJudge();

    this.killGame = function() {
        delete Games[this._id];
    };

    // When a player presses leave game
    this.playerExits = function(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove),1);

        // If less than min players
        if (this.players.length < minPlayers) this.killGame();

        // If less than max players
        if (this.players.length < maxPlayers) {
                this.needsPlayers = true;
        }

       gameSockets.kickPlayer(playerToRemove);
    };

    // When a player disconnects without warning, e.g. closes window
    this.playerDisconnects = function(playerToRemove) {
        // Delete player from players array
        this.players.splice(this.players.indexOf(playerToRemove),1);

        // If less than min players
        if (this.players.length < minPlayers) this.killGame();

        // If less than max players
        if (this.players.length < maxPlayers) {
                this.needsPlayers = true;
        }
    };

    this.selectJudges = function() {
        this.judge = this.players.pop();
        this.players = this.players.unshift(this.judge);
    };

    this.setWinner = function(winner) {
        this.winner = winner;
    };

    Games[this._id] = this;
}


texts: Function for accessing regression output

texts:
I just wrote this function for personal use only while working on a specific data project. I would be grateful for any feedback!

get.coef1 <- function(x) {
  x <- as.character(x)
  m.names <- paste("fit", x, letters[1:3], sep="")
  models3 <- matrix(numeric(12L), 3, 4)
  for (i in 1:3) {
    models3[i, ] <- summary(get(m.names[i]))$coefficients[2,]
  }
  return(models3)
}

Data to reproduce function above:

x <- rnorm(100)
y <- x^2/4
z <- rnorm(100)+y/100
w <- rnorm(100)

Edit1:
And three fitted regressions:

fit3a <- lm(y ~ x)
fit3b <- lm(y ~ x + z)
fit3c <- lm(y ~ x + z + w)

Whose coefficients on x I want to access viaget.coef1(3).


texts:
I'm going through the eBook Intro to App Development with Swift by Apple and I am making the Rock, Paper, Scissors app in lesson 20.
This is the assignment that I got:

[...] Name the enum Sign. Add a calculated property to give the emoji that represents the Sign.
[...]
You need to be able to compare two Sign instances to give a GameState.
For example, a player’s .rock and the app’s .paper would give you .lose.
Add an instance method to Sign that takes another Sign, representing the opponent’s turn, as a parameter. The method should return a GameState based on a comparison between self and the opponent’s turn. [...]

The code that I wrote works but I feel like this can be done a lot cleaner. Maybe it's Xcode's indentation that looks a bit weird to me, maybe there's a better solution?
I'll start with GameState.swift (these 4 gamestates were given in the instructions):
import Foundation

enum GameState {
    case start, win, lose, draw
}

And here's Sign.swift:
import Foundation

enum Sign {
    case rock, paper, scissors

    var emoji: String {
        switch self {
        case .rock: return ""
        case .paper: return "✋"
        case .scissors: return "✌"
        }
    }

    func beats(otherSign: Sign) -> GameState {
        switch self {
        case .rock: do {
            if otherSign == .paper {
                return .lose
            } else if otherSign == .scissors {
                return .win
            }
            return .draw
            }
        case .scissors: do {
            if otherSign == .rock {
                return .lose
            } else if otherSign == .paper {
                return .win
            }
            return .draw
            }
        case .paper: do {
            if otherSign == .rock {
                return .win
            } else if otherSign == .scissors {
                return .lose
            }
            return .draw
            }
        }
    }
}


texts: JavaScript Etch-A-Sketch implementation from The Odin Project

texts:
I'm working through the curriculum at The Odin Project. I recently completed the Etch-A-Sketch project and am looking for some help/feedback regarding my code. Specifically, I feel that the functions in my JavaScript contain too much repeat code. But, I'm having trouble understanding how to refactor the functions without breaking them.

Github HTML Preview

Full project code

const gridContainer = document.getElementById('gridContainer');

    function createGrid(size){
        let totalSquares = size * size;
        for (let i = 0; i < totalSquares; i++){
            const newSquare = document.createElement('div');
            newSquare.classList.add('newSquare');
            gridContainer.appendChild(newSquare);
            newSquare.addEventListener('mouseover', function(e){
            newSquare.style.backgroundColor = 'black';
            });

        }
        document.documentElement.style.setProperty("--rowNum", size);
        document.documentElement.style.setProperty("--colNum", size);
    }

    function pencilGrid(size){
        let totalSquares = size * size;
        for (let i = 0; i < totalSquares; i++){
            const newSquare = document.createElement('div');
            newSquare.classList.add('newSquare');
            gridContainer.appendChild(newSquare);
            newSquare.addEventListener('mouseover', function(e){
            newSquare.style.backgroundColor = 'black';
            newSquare.style.opacity -= '-0.1';
            });

        }
        document.documentElement.style.setProperty("--rowNum", size);
        document.documentElement.style.setProperty("--colNum", size);
    }

    function colorfulGrid(size){
        let totalSquares = size * size;
        for (let i = 0; i < totalSquares; i++){
            const newSquare = document.createElement('div');
            newSquare.classList.add('newSquare');
            gridContainer.appendChild(newSquare);
            newSquare.addEventListener('mouseover', function(e){
                let randomColor = Math.floor(Math.random()*16777215).toString(16);
            newSquare.style.backgroundColor = randomColor;
            newSquare.style.border = '0px';
            });

        }
        document.documentElement.style.setProperty("--rowNum", size);
        document.documentElement.style.setProperty("--colNum", size);
    }

    function clearGrid(){
        while (gridContainer.firstChild){
            gridContainer.removeChild(gridContainer.firstChild);
        }
    }

    createGrid(16);

    const newGridButton = document.getElementById('newGridButton');
    newGridButton.addEventListener('click', function(e){
        clearGrid();
        let newSize = prompt('New Grid Size:');
        createGrid(newSize);

    });

    const pencilButton = document.getElementById('pencilButton');
    pencilButton.addEventListener('click', function(e){
        clearGrid();
        let newSize = prompt('New Grid Size')
        pencilGrid(newSize);
    });

    const colorfulButton = document.getElementById('colorfulButton');
    colorfulButton.addEventListener('click', function(e){
        clearGrid();
        let newSize = prompt('New Grid Size')
        colorfulGrid(newSize);
    });


texts: Concurrent requests are not permitted in specific time period

texts:
In my web API, the client wants me to implement logic in order to control/block concurrent requests in a specific time period. I added RequestInterval which is 10 seconds in the appsettings of web config. I added the Authorization filter into my project. I tested, it looks working but I wonder if you can check and give me some feedback.

public class ValidIntervalFilter : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            double sec = Double.Parse(WebConfigurationManager.AppSettings["RequestInterval"].ToString());
            DateTime lastDateTime = DateTime.Now;
            DateTime requestDateTime = DateTime.Now;
            var terminal_number = HttpContext.Current.Request.Params["shopNo"];
            using (GameContext ctx = new GameContext())
            {
                //this will throw an exception
                var lastRequestTime = ctx.Database.SqlQuery<DateTime>(
                    "SELECT MAX([RequestDateTime]) FROM GameRequests WHERE[ShopNo] = @shopNo and RequestDateTime >= CONVERT(DATE, GETDATE())",
                    new SqlParameter("shopNo", terminal_number)).ToList();

                foreach (var time in lastRequestTime)
                {
                    lastDateTime = Convert.ToDateTime(time);
                }
                DateTime timeAfterInterval = lastDateTime.AddSeconds(sec);
                if (requestDateTime <= timeAfterInterval)
                {
                    var response = new HttpResponseMessage
                    {
                        StatusCode = (HttpStatusCode)429,
                        ReasonPhrase = "Too Many Requests",
                        Content = new StringContent("Concurrent requests are NOT permitted in " + sec + " seconds.")

                    };

                    actionContext.Response = response;
                }
            }
        }
    }

I changed the query and here is the updated code:

public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            double sec = Double.Parse(WebConfigurationManager.AppSettings["RequestInterval"].ToString());

            var terminal_number = HttpContext.Current.Request.Params["shopNo"];
            using (GameContext ctx = new GameContext())
            {

                var lastRequestTime = ctx.Database.SqlQuery<Int32>(
                    "SELECT DATEDIFF(SECOND, [RequestDateTime], GETDATE()) As [SecondsSinceLastRequest] FROM [dbo].[GameRequests] WHERE [ShopNo] = @shopNo AND DATEDIFF(SECOND, [RequestDateTime], GETDATE() ) < @delay",
                    new SqlParameter("shopNo", terminal_number), new SqlParameter("delay", sec)).ToList();

                if (lastRequestTime.Count > 0)
                {
                    var response = new HttpResponseMessage
                    {
                        StatusCode = (HttpStatusCode)429,
                        ReasonPhrase = "Too Many Requests",
                        Content = new StringContent("Concurrent requests are NOT permitted in " + sec + " seconds.")

                    };

                    actionContext.Response = response;
                }

            }
        }


texts: Sed script to update a version number in an RPM SPECS file

texts:
I have a specs file:

Name:           program
Version:        2.3.3
Release:        0
...

I want to update the version number every time it's built. I perform the build from a bash script so I'm calling sed to update the SPECS file and a "version" file which holds the version number.

I am using the following sed script to perform the update:

sed -ri 's/^(Version:\s+)([0-9.]+)/\1$version/g' SPECS/*.spec

with the $version being provided by the bash script.

It's designed to look for the correct line and replace the version portion while preserving whatever whitespace has been used. I use *.spec so that it will work with a spec file of any name.

I felt that a sed one-liner made the most sense given the requirement.


texts:
Could you tell me how to make it quality code?

<?php
class Game {
    public function __construct() {
        session_start();
    }
    public function play(){
        return '<input type="button" value="Play" onclick="window.location = \'?play=1\'">';
    }
    public function start($msg=null) {
        unset($_SESSION['bees']);
        $bee = new Bee();
        $bee->setType('queen');
        $this->addBee($bee,1);
        $bee->setType('worker');
        $this->addBee($bee,5);
        $bee->setType('drone');
        $this->addBee($bee,8);
        if($msg)
            return $msg;
        else {
            var_dump($_SESSION['bees']); // debug
            return 'Game started <input type="button" value="Hit" onclick="window.location = \'?hit=1\'">';
        }
    }
    public function hit() {
        $msg = '';
        if($_SESSION['bees'])
            $rd = array_rand($_SESSION['bees'],1);
        else
            $this->start('Game will start again');
        $_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['lifespan'] - $_SESSION['bees'][$rd]['hit'];
        if($_SESSION['bees'][$rd]['lifespan']<1) {
            $_SESSION['bees'][$rd]['bees'] -=1;
            $_SESSION['bees'][$rd]['lifespan'] = $_SESSION['bees'][$rd]['life'];
            switch($rd)
            {
                case 'queen': $msg .= $this->start('Game start again, the Queen is dead.'); break;
                default: $msg .= 'One \'' . $rd . '\' is gone';
            }
        }
        if($_SESSION['bees'][$rd]['bees']<1){
            unset($_SESSION['bees'][$rd]);
            $msg = 'The \'' . $rd . '\' team is gone';
        }
        var_dump($_SESSION['bees']); // debug
        return '<input type="button" value="Hit" onclick="window.location = \'?hit=1\'"> ' . $msg;
    }
    public function addBee(Bee $newbee, $number = 1) {
        $tipo = $newbee->getType();
        $bee = $newbee->get();
        $_SESSION['bees'][$tipo] = $bee;
        $_SESSION['bees'][$tipo]['bees'] = $number;
        $_SESSION['bees'][$tipo]['life'] = $newbee->getLifespan($tipo);
    }
}

class Bee
{
protected $_type = null;
protected $_types = array(
    'queen' => array(
    'hit' => 8,
    'lifespan' => 100
    ),
    'worker' => array(
    'hit'   =>  10,
    'lifespan' => 75
    ),
    'drone' => array(
    hit'    =>  12,
    'lifespan' => 50
    )
    );
    public function setHit(){}
    public function setLifespan(){}
    public function addNewType(){}
    protected function _set_hit(){}
    protected function _set_lifespan(){}
    protected function _add_new_type(){}
    public function getLifespan($type){
        if(array_key_exists($type,$this->_types))
            return $this->_types[$this->_type]['lifespan'];
        else
            throw new Exception('The Bee need to be a Queen, Worker or Drone');
    }
    public function getTypes() {
        return $this->_types;
    }
    public function getType() {
        return $this->_type;
    }
    public function setType($type) {
        if(array_key_exists($type,$this->_types))
            $this->_type = $type;
        else
            throw new Exception('The Bee need to be a Queen, Worker or Drone');
    }
    public function get() {
        return $this->_types[$this->_type];
    }
}
?>
<html>
<head>
<title>play Bee</title>
</head>
<body>
    <?php
        $game = new Game();
        if(isset($_GET['play']) && $_GET['play']) {
            echo $game->start();
        } else if(isset($_GET['hit']) && $_GET['hit']) {
            echo $game->hit();
        } else {
            echo $game->play();
        }
    ?>
</body>
</html>


texts: Identify and provide a list of commands whose execution will synchronize an "official" list of objects with a "personal" list of objects

texts:
Is the intent of this code obvious / clear? Please suggest any improvements.  This happens to be TypeScript, but is probably pretty familiar to anyone in the Java/C# world.

These are both private methods in a class whose constructor takes an "official" and "personal" object of "notifications".

private _calculateDifferences() {

    for (let officialCounter = 0; officialCounter < this._officialNotifications.length; officialCounter++) {

        this._processOneOfficialNotification(this._officialNotifications[officialCounter]);

    }
}

private _processOneOfficialNotification(officialNotification: RLEntities.UserNotificationItem): void {

    if (this._isUpdatedNotification(officialNotification)) {
        this._createUpdateCommand(officialNotification);
        this._markPersonalNotificationAsProcessed(officialNotification.ID); // personal and official notifications share an ID in common
    }

    else if (this._isNewNotification(officialNotification)) {
        this._createInsertCommand(officialNotification);
    }
    else {
        this._createDeleteCommand(officialNotification.ID);
    }
}


texts: Multiple if conditions in one block - looking for faster and more efficient code

texts:
i am looking for a faster and more efficient way of this code. What the code does is simply compares message context of (user, application, service and operation) and compares it with some rules.

private boolean match(Context messageContext, ContextRule contextRule) {
        if(contextRule.getMessageContext().getUser().equals(ContextRuleEvaluator.WILDCARD)
            || (contextRule.getMessageContext().getUser().equals(messageContext.getUser()))) {
          if(contextRule.getMessageContext().getApplication().equals(ContextRuleEvaluator.WILDCARD)
              || (contextRule.getMessageContext().getApplication().equals(messageContext.getApplication()))) {
            if(contextRule.getMessageContext().getService().equals(ContextRuleEvaluator.WILDCARD)
                || (contextRule.getMessageContext().getService().equals(messageContext.getService()))) {
              if(contextRule.getMessageContext().getOperation().equals(ContextRuleEvaluator.WILDCARD)
                  || (contextRule.getMessageContext().getOperation().equals(messageContext.getOperation()))) {
                return true;
              }
            }
          }
        }

        return false;
      }

Edit: Context and ContextRule are an interfaces

public interface Context {
   public String getUser();
   public void setUser(String user);
   public String getApplication();
   public void setApplication(String application);
   public String getService();
   public void setService(String service);
   public String getOperation();
   public void setOperation(String operation);
}

public interface ContextRule {
  public Context getMessageContext();
  public int getAllowedConcurrentRequests();
}

Any suggestions appreciated :)


texts:
I recently wrote a code in online recruitment test. It was very good.

With each question, there were associated space and time limits check. If our code executed correctly within both limits, only then we were given full marks otherwise 0.

Input: String consisting of ASCII characters.

Output: True if the string is balanced parenthesis wise and false otherwise.

I wrote the following code for the problem, but the problem is I got 0 marks because it said limits crossed, Optimization required.

import java.util.*;
import java.io.*;
class Prths
{
 private static Stack<Boolean> st=new Stack<Boolean>();
 public static void main(String []args)throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();
     boolean result=check(s);
     System.out.println(result);
 }
 public static boolean check(String s)
 {
     int i=0;
     while(i<s.length())
     {
         if(s.charAt(i)==')'&&st.isEmpty())
          return false;
         else if(s.charAt(i)==')')
          st.pop();
         else if(s.charAt(i)=='(')
          st.push(true);
         ++i;
     }
     if(st.isEmpty())
      return true;
     else return false;
 }
}


texts: Sorting an array of objects by a property which may be missing

texts:
Problem

I am sorting an array of objects. Each element may have a property called reference or it may be undefined. When defined, it is a user-provided string (which is why I use String.localeCompare()).

If the reference is not available, that element's relative position in the final list is irrelevant save that all blank references must appear grouped together at the end.

Implementation

function sort(searchResult) {
    const hasReference = searchResult
        .filter(taskCard => typeof taskCard.reference !== "undefined");

    const missingReference = searchResult
        .filter(taskCard => typeof taskCard.reference === "undefined");

    hasReference.sort(
        (tc1, tc2) => tc1.reference.localeCompare(tc2.reference)
    );

    return hasReference.concat(missingReference);
}

My Concerns

Is this an efficient way of solving this problem in terms of time?
I'm currently iterating over the initial array twice. Is there an elegant ES6 way to do this in a single pass that I'm not seeing?
I believe memory to be less of a concern (because I exactly double the amount of memory used while processing by generating two new arrays that together are the size of the original); am I correct?
Are there any scalability pitfalls doing it this way?
As usual, any other comments are welcome.