texts:
With twitter search the punctuation and special characters will be considered part of the term you're searching for, so searching for '#twitter!' will return '#twitter!', "twitter?', '#twitter', etc. What this module does is check if the search includes any type of punctuation searched with and if it does you can sort the array to add those tweets first. This code does the trick but I feel like there might be a cleaner way to do this. Right now I am just using array.sort and setting the array attributes index to 0 if it matches the regex which is looking for a punctuation used in the search and matching it with the tweets.

require 'twitter'

module TwitterSearch
  extend self

  TWITTER_CLIENT = Twitter::REST::Client.new do |config|
    config.consumer_key        = ""
    config.consumer_secret     = ""
    config.access_token        = ""
    config.access_token_secret = ""
  end

  # search returns
  # Check out what @researchgoddess is up to at #sourcecon!
  # What a welcome from @SourceCon! Thanks @CareerBuilder for hosting.#
  # RT @JRoberts257: Happy hour at #SourceCon! Thanks @CareerBuilder for
  # Happy hour at #SourceCon! Thanks @CareerBuilder for sponsoring. ht
  # @RT @cybsearchjoe: #SourceCon is rocking
  # etc

  def search(text)
    tweets = TWITTER_CLIENT.search("#{text} filter:images", result_type: "recent").take(30).collect do |tweet|
        "#{tweet.text}"
    end
    # looks to see if there is puncuation at the end of the text "!.?{}[]" It will ignore the # at the beginning
    tweets = sort_tweets(text, tweets) if text[1..text.length] =~ /[[:punct:]]/
    puts tweets
  end

  # sorts tweets based off index given in match_phrase
  def sort_tweets(text, tweets)
    tweets.sort do |phrase, other_phrase|
      match_phrase(phrase, text, tweets) <=> match_phrase(other_phrase, text, tweets)
    end
  end

  # if phrase matches punc_text(text) the phrase will be inserted at the beginning of the array else it will return its previous index.
  def match_phrase(phrase, text, tweets)
    phrase.match(/#{punc_text(text)}/i).nil? ? tweets.index(phrase) + 1 : 0
  end

  # adds backslash to punctuation '#sourcecon//?|!|.'
  def punc_text(text)
    text[1..text.length].gsub(/([[:punct:]])/){|punc| "\\#{punc}"}
  end
end

TwitterSearch.search('#sourcecon!')


texts: Initialize bunch of variables in constructor by extracting value from dictionary

texts:
I have a headers dictionary value being passed to one of my constructors and based on that dictionary value I am extracting individual headers I need and setting all my variables.

public Tester(IDictionary<string, StringValues> headers)
 {
     int textId = 0;

     if (headers == null)
     {
         ProcId = GenerateProcId();
         DbId = GenerateDbId();
         ThetaId = GenerateThetaId();
         return;
     }

     ProcIdHeader = GetHeaderValue(headers, PROC_HEADER);
     if (string.IsNullOrWhiteSpace(ProcIdHeader))
     {
         ProcId = GenerateProcId();
     }
     else
     {
         ProcId = ProcIdHeader;
     }

     DbIdHeader = GetHeaderValue(headers, DB_HEADER);
     if (string.IsNullOrWhiteSpace(DbIdHeader))
     {
         DbId = GenerateDbId();
     }
     else
     {
         DbId = DbIdHeader;
     }

     ThetaId = GenerateThetaId();

     var textIdStr = GetHeaderValue(headers, TEXT_HEADER);
     int.TryParse(textIdStr, out textId);
     TextIdValue = textId;
     TextId = textId;

     AlphaHeader = GetHeaderValue(headers, ALPHA_HEADER);
     if (!string.IsNullOrWhiteSpace(AlphaHeader))
     {
         AlphaContent = AlphaHeader;
     }

     TimeoutIdHeader = GetHeaderValue(headers, TIMEOUT_HEADER);
     if (!string.IsNullOrWhiteSpace(TimeoutIdHeader))
     {
         TimeoutId = TimeoutIdHeader;
     }

     FilterHeader = GetHeaderValue(headers, FILTER_HEADER);
     if (!string.IsNullOrWhiteSpace(FilterHeader))
     {
         FilterId = FilterHeader;
     }

     PreviewHeader = GetHeaderValue(headers, PREVIEW_HEADER);
     if (!string.IsNullOrWhiteSpace(PreviewHeader))
     {
         PreviewId = PreviewHeader;
     }

     AntHeader = GetHeaderValue(headers, ANT_HEADER);
     if (!string.IsNullOrWhiteSpace(AntHeader))
     {
         AntId = AntHeader;
     }
     LocalHeader = GetHeaderValue(headers, LOCAL_HEADER);
     AppHeader = GetHeaderValue(headers, APP_HEADER);
     if (!string.IsNullOrWhiteSpace(AppHeader))
     {
         AppId = AppHeader;
     }

     ContextHeader = GetHeaderValue(headers, CONTEXT_HEADER);
     if (ContextHeader != null)
     {
         try
         {
             ContextStr = JsonSerializer.Deserialize<ContextStr>(ContextHeader);
         }
         catch (Exception e)
         {
             ContextStr = new ContextStr();
         }
     }
     if (LocalHeader != null)
     {
         try
         {
             LocalStr = JsonSerializer.Deserialize<LocalStr>(LocalHeader);
         }
         catch (Exception e)
         {
             LocalStr = new LocalStr();
         }
     }
     PageHeader = GetHeaderValue(headers, PAGE_HEADER);
     if (!string.IsNullOrWhiteSpace(PageHeader))
     {
         PageStr = PageHeader;
     }
     ChannelId = GetHeaderValue(headers, CHANNEL_HEADER);
 }

 private string GetHeaderValue(IDictionary<string, StringValues> headers, string headerKey)
 {
     headers.TryGetValue(headerKey, out var headerValues);
     if (headerValues.Count > 0) return headerValues[0];
     return null;
 }

I wanted to see if there is any better way to rewrite the constructor logic that I have. As of now it looks very bulky with bunch of if/else block. Anything that can be improve in my code?

Note: It's a legacy code base system so changing whole design might be difficult but little refactoring by splitting it into various methods is possible.


texts:
I have a piece of code that tries to get some data from a different services, falling back to the next one if previous fails.

The code look a little bit ugly, though. Any suggestions on how to rewrite it in a more concise way?

(defn get-data [query]
  (let [data-cached (get-data-from-cache query)
        data-service-1 (if (nil? data-cached)
                         (get-data-service-1 query)
                         data-cached)
        data-service-2 (if (nil? data-service-1)
                         (get-data-service-2 query)
                         data-service-1)
        data (if (nil? data-service-2)
                   (get-data-service-3 query)
                   data-service-2)]
    data))


texts:
I have a short bash script that processes gigs and gigs of data.  I am looking for any improvements to make it faster.  This is my very first bash script so please be gentle. I am really only concerned about the while loop. The rest of it is fine I think. It's the while loop where the real work is done and could use the most enhancement.

#!/bin/bash

# This script will clean a WPA wordlist
# It will read every line of the given file
#       Remove all whitespace except for newlines
#       Delete the line if it is less than 8 chars or greater than 63
# It will then exit with time of execution

IFS=$'\n'       # make newlines the only separator

startTime=$(date)       # start time of execution
fileToClean=$1          # this is the file we will be sanatizing, 1st cmd line arg
deletedlines=0          # number of lines that did not meet WPA PSK critera
validlines=0            # number of lines that were valid PSKs  and added to file

if [ -z $fileToClean ]; then #No file specified
        echo ""
        echo "No file specified!"
        echo ""
        exit -1
fi

if [ ! -f $fileToClean ]; then #File does not exist
        echo ""
        echo "File not found!"
        echo ""
        exit  -1
fi

#By this point I am assuming I entered a valid file and will begin cleaning
echo ""
echo 'Cleaning word list: ' $1
echo "Start Time: " $startTime
echo ""

while read line; do  #read every line in file and save to var line

        line="${line##*( )}"        # trim leading whitespace
        line="${line%%*( )}"        # trim trailing whitespace

        if [ ${#line} -ge 8 ] && [ ${#line} -le 63 ]; then     # if trimmedline length >= 8 && <= 63
                echo  $line >> $outputfile
                ((validlines++))
                continue
        fi

        ((deletedlines++))

done <$fileToClean

utime="$( TIMEFORMAT='%lU';time ( ls ) 2>&1 1>/dev/null )"  # this stores the executio time in the var utime

echo "Processing completed, it took" $utime "and $deletedlines were deleted."
echo $validlines "were added to the output file "$outputfile" as they were valid PSKs"
echo ""


texts:
I have the following Matlab function:

function [res] = a3_funct(x)
    res = 0;
    for i = 1:size(x,1)
        res = res + abs(x(i))^(i+1);
    end
end

It's emulating this equation:

\$f(x) = \sum_{i=1}^{n}|x_i|^{i+1}\$

Here is an example use:

>> a3_funct([1,2,3]')

ans =

    90

I know I should be able to use the sum() function to make this faster, but how do I get the exponents in there?


texts:
This is a simple "Rock, Paper, Scissors" game I made in Python 3. Feel free to critique me and give suggestions on how can I improve my newbie coding skills.

import os
from random import randint

def ask_player():
    while True:
        print("Rock, paper or scissors?")
        ans = input(">")
        if ans in ('Rock', 'Paper', 'Scissors'):
            return ans

def results_msg(x, y, result):
    message = f"{x} beats {y}. You {result}!"
    return message

def comp_play():
    comp_choice = randint(0, 2)
    if comp_choice == 0:
        comp_choice = 'Rock'
    elif comp_choice == 1:
        comp_choice = 'Paper'
    else:
        comp_choice = 'Scissors'
    return comp_choice

def results(wins, losses, draws):
    player_choice = ask_player()
    comp_choice = comp_play()
    if player_choice == comp_choice:
        print("Draw. Nobody wins or losses.")
        draws += 1
    elif player_choice == 'Rock':
        if comp_choice == 'Paper':
            print(results_msg(comp_choice, player_choice, 'lost'))
            losses += 1
        else:
            print(results_msg(player_choice, comp_choice, 'won'))
            wins += 1
    elif player_choice == 'Paper':
        if comp_choice == 'Rock':
            print(results_msg(player_choice, comp_choice, 'won'))
            wins += 1
        else:
            print(results_msg(comp_choice, player_choice, 'lost'))
            losses += 1
    else:
        if comp_choice == 'Rock':
            print(results_msg(comp_choice, player_choice, 'lost'))
            losses += 1
        else:
            print(results_msg(player_choice, comp_choice, 'won'))
            wins += 1
    return wins, losses, draws

def play_again():
    while True:
        print("\nDo you want to play again?")
        print("[1] Yes")
        print("[2] No")
        ans = input("> ")
        if ans in '12':
            return ans

def main():
    wins = 0
    losses = 0
    draws = 0
    while True:
        os.system('cls' if os.name == 'nt' else 'clear')
        print(f"Wins: {wins}\nLosses: {losses}\nDraws: {draws}")
        wins, losses, draws = results(wins, losses, draws)
        if play_again() == '2':
            break

if __name__ == '__main__':
    main()

The follow-up is ""Rock, Paper, Scissors" game - follow-up".


texts:
I'm studying the C language with a Harvey Deitel book.

Trying to solve an exercise that asked to write a good sorting algorithm, I did this:

void sort(int v[], int d){

int max = 0;
for(int i = 0; i < d; i++){
    if(v[i] > max)max = v[i];
}

int v2[max+1];
int v3[max+1];
for(int i = 0; i < max+1; i++){
    v2[i] = -1;
    v3[i] = 0;
}

for(int i = 0; i < d; i++){
    if(v3[v[i]] == 0){
        v2[v[i]] = v[i];
        v3[v[i]]++;
    }
    else {
        v3[v[i]]++;
    }
}

int j = 0;
for(int i = 0; i < max+1; i++){
    if(v2[i] != -1){
        for(int k = 0; k < v3[i]; k++){
            v[j] = v2[i];
            j++;
        }
    }
}
}


texts: Middleware for authenticating GitHub webhooks

texts:
I'm currently working on a PSR-15 middleware for authenticating GitHub webhooks.

<?php

class Auth implements MiddlewareInterface, LoggerAwareInterface
{
    const LOG_MSG_MISSING_HEADER = 'Authentication failed, X-Hub-Signature missing';
    const LOG_MSG_SIGNATURE_NOT_MATCHING = 'Authentication failed, signature did not match';
    const LOG_MSG_SUCCESS = 'Authentication successful';

    use LoggerAwareTrait;
    private const SIGNATURE_NAME = 'X-Hub-Signature';
    private $responseFactory;
    private $secret;
    public function __construct(string $secret, ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
        $this->secret = $secret;
        $this->logger = new NullLogger();
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!$request->hasHeader(self::SIGNATURE_NAME)) {
            $this->logger->warning(self::LOG_MSG_MISSING_HEADER);
            return $this->responseFactory->createResponse(400, 'Bad Request');
        }

        $signature = $this->getSignature($this->secret, $request->getBody());

        if (!hash_equals($request->getHeader(self::SIGNATURE_NAME)[0], $signature)) {
            $this->logger->warning(self::LOG_MSG_SIGNATURE_NOT_MATCHING);
            return $this->responseFactory->createResponse(401, 'Unauthorized');
        }

        $this->logger->info(self::LOG_MSG_SUCCESS);
        return $handler->handle($request);
    }

    private function getSignature(string $secret, string $body): string
    {
        return 'sha1=' . hash_hmac('sha1', $body, $secret);
    }
}

I have removed comments and the use statements for the sake of brevity.
The complete code lives in this repo.

At the moment, I'm trying to figure out the best way to handle the case if the stream representing the request body is not seekable.

The problem this introduces is that when the handler is called, it might not be possible to rewind the stream.
This will, of course, makes it impossible for any subsequent handlers/middlewares to access the body content.

As I see it, there are two options:

Check if the stream is seekable and throw an exception if it's not.

This solution is simple and would not introduce any real complexity.
On the other hand, it shifts responsibility to the calling code, and that might not be the cleanest way of handling the issue.
Change the constructor signature to require a PSR-17 StreamFactory and use that to create a new seekable stream and copy the content from the original non-seekable stream to the new one.

Any feedback on this or any other part of the code is most welcome!


texts: A simple program with trains and inheritance

texts:
Here it is my program. I'm especially worried about the main because I know that one must be careful while instancing vectors of "inherited" objects. The code I have works fine (as far as I can see) but I saw the original program made by my teacher and his implementation of the vector in the main uses new and iterator. I'd like to have some piece of advice on how to improve!

#include <vector>
#include <iostream>
#include <cmath>

class Station {
private:
    double x_, y_;

public:
    Station(double x, double y) : x_(x), y_(y) { }
    Station(const Station & s) : x_(s.x_), y_(s.y_) { }

    // dichiarazione funzione globale
    friend double dist(const Station & s, const Station & t);
};

class Train {
private:
    double vm_;
public:
    Train(double vm) : vm_(vm) { }
    double getvm() {return vm_; }

    virtual double time_of_travel(const Station & s, const Station & t) {
        return( dist(s, t)/vm_);
    }
};

class Regionale : public Train {
public:
    Regionale() : Train(60.) { }
};

class Intercity : public Train {
private:
    Station stop_;
public:
    Intercity(const Station stop) : stop_(stop), Train(110.) { }

    double time_of_travel(const Station & s, const Station & t) {
        return( (dist(s, stop_) + dist(stop_, t))/this->getvm());
    }

};

double dist(const Station & s, const Station & t) {
    return(sqrt(pow(s.x_ - t.x_, 2) + pow(s.y_ - t.y_, 2)));
}

int main() {
    Station Milano (0. ,0.);
    Station Bergamo (35. ,25.);
    Station Piacenza (40. , -45.);

    std::cout << dist (Milano, Bergamo) << std::endl;
    std::cout << dist (Bergamo, Piacenza) << std::endl;
    std::cout << dist (Piacenza, Milano) << std::endl;

    Intercity i(Milano);
    Regionale r;
    std::vector<Train * > v = {&i, &r};

    for(auto elem : v) std::cout << elem->time_of_travel(Bergamo, Piacenza) << std::endl;

}


texts: "Backwards Read Primes" of Codewars powershell version

texts:
Link to problem: https://www.codewars.com/kata/5539fecef69c483c5a000015/train/powershell
I have a working solution in Codewars but my solution is slow for some reason and I need to improve the efficiency.
Please look over my solution and offer any suggestions on things I could do to improve what I have.
Instructions for problem:
Backwards Read Primes are primes that when read backwards in base 10 (from rightto left) are a different prime. (This rules out primes which are palindromes.)
Examples:
13 17 31 37 71 73 are Backwards Read Primes
13 is such because it's prime and read from right to left writes 31 which is prime too. Same for the others.
Task
Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one always being greater than or equal to the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers.
Example
backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967] backwardsPrime(501, 599) => []
Note for Forth
Return only the first backwards-read prime between start and end or 0 if you don't find any
Don't use Ruby Prime class, it's disabled.
backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]
Thanks.

$primes = @{ 2 = 2; 3 = 3; 5 = 5; 7 = 7; 11 = 11; 13 = 13; 17 = 17; 31 = 31; 37 = 37; 71 = 71; 73 = 73; 79 = 79; 97 = 97; 107 = 107; 113 = 113; 149 = 149; 157 = 157; 167 = 167; 179 = 179; 199 = 199 };

function backwards-prime($start, $stop)
{

    function revNum ([int] $n) {
        $numStr = $n.ToString();
        return ($numStr[-1..-($numStr.Length)] -join "") -as [int];
    }

    function isPrime ($num) {

        if ($primes.containsKey($num)) {
            return $true;
        }

        if ($num -lt 3) {
            return $num -gt 1;
        }

        if ($num % 2 -eq 0 -or $num % 3 -eq 0) {
            return $false;
        }

        $i = 5;

        while ($i * $i -le $num) {
            if ($num % $i -eq 0 -or $num % ($i + 2) -eq 0) {
                return $false;
            }

            $i += 6;
        }

        $primes[$num.ToString()] = $num;

        return $true;
    }

    $res = @();

    if($start % 2 -eq 0) { $start = $start + 1; }
    if($stop % 2 -eq 0) { $stop = $stop - 1; }

    for ($i = $start; $i -le $stop; $i += 2) {
        $nPrime = isPrime $i;
        $nReversed = revNum $i;
        $nPrimeReverse = isPrime $nReversed;

        if ($nPrime -and $nPrimeReverse -and $i -ne $nReversed -and $i -ge 13) {
            $res += $i;
        }
    }

    return ($res -join ", ").Trim();
}


texts:
Im working on a small desktop app which controls services on a server. For controlling services i am using ServiceController class. What i want to do is; testing my code and abstract the ServiceController  class from my code. So i did something like below.

  public interface IServiceControllerWrapper
{
    string ServerNameOrIP { get; }
    int Status { get; }
    bool CanStop { get;  }
    void StartService();

}

 public class ServiceControllerWrapper : IServiceControllerWrapper
{
    ServiceController _controller;
    const string ServiceName = "W3SVC";

    public ServiceControllerWrapper(string serverNameOrIP)
    {
        _controller = new ServiceController(ServiceName, serverNameOrIP);
    }

    public string ServerNameOrIP { get { return _controller.MachineName; } }

    public int Status
    {
        get
        {
            switch (_controller.Status)
            {
                case ServiceControllerStatus.ContinuePending:
                case ServiceControllerStatus.PausePending:
                case ServiceControllerStatus.Paused:
                    return 4;
                case ServiceControllerStatus.StopPending:
                case ServiceControllerStatus.Stopped:
                    return 0;
                case ServiceControllerStatus.StartPending:
                case ServiceControllerStatus.Running:
                    return 1;
                default:
                    return -1;
            }
        }
    }

    public bool CanStop
    {
        get
        {
            return _controller.CanStop;
        }
    }

    public void StartService()
    {
        _controller.Start();
    }

   //shortened

}

and i am using this class within another named ServerContext. Implementation is;

   public interface IServerContext
{
    string ServerName { get; }
    IServerContext Parent { get; }
    IServiceControllerWrapper Controller { get; }
    bool HasError { get; set; }
    int GetServiceStatus();
}

  public class ServerContext : IServerContext
{
    IServerContext _parent;
    IServiceControllerWrapper _controller;

    public ServerContext(IServerContext parent, IServiceControllerWrapper wrapper)
    {
        _parent = parent;
        _controller = wrapper;
    }

    public string ServerName { get { return _controller.ServerNameOrIP; }}

    public IServerContext Parent
    {
        get
        {
            return _parent;
        }
    }

    public IServiceControllerWrapper Controller
    {
        get
        {
            return _controller;
        }
    }

    public bool HasError { get; set; }

    public int GetServiceStatus()
    {
       return _controller.Status;
    }

 }

My question here is, i am tryint to test ServerContext and ServiceControllerWrapper but i cant manage to create fake objects. this test method always throws exception because ServerName is null.How can i arrange this code to pass test and or how can i test those classes?

      [Fact]
    public void ServerName_CannotBeEmpty()
    {
        Mock<IServiceControllerWrapper> _controller = new Mock<IServiceControllerWrapper>();
        ServerContext serverContext = new ServerContext(null, _controller.Object);
        //this code fails.
        serverContext.ServerName.Should().Not.Be.NullOrEmpty();
    }

Any suggestions are welcome.
Note: i am using moq,xunit and SharpTestsEx libraries for testing.


texts:
I have 18 RadioGroup. I am declaring the RadioGroup like this way

private RadioGroup kn1RadioGroup, kn2RadioGroup, kn4aRadioGroup,
kn4bRadioGroup, kn4cRadioGroup, kn4dRadioGroup, kn4eRadioGroup,
kn4fRadioGroup, kn4gRadioGroup, kn4hRadioGroup, kn4iRadioGroup,kn4jRadioGroup,ap2aRadioGroup,ap2bRadioGroup,
ap2cRadioGroup,ap2dRadioGroup,ap2eRadioGroup,pr1RadioGroup;

I have created getter and setter for these RadioGroup. And I am setting the RadioGroup id like this way

fragment.setKn1RadioGroup((RadioGroup) findViewById(R.id.kn1_radio_group));
fragment.setKn2RadioGroup((RadioGroup) findViewById(R.id.kn2_radio_group));
fragment.setPr1RadioGroup((RadioGroup) findViewById(R.id.pr1_radio_group));
fragment.setKn4aRadioGroup((RadioGroup) findViewById(R.id.kn4a_radio_group));
fragment.setKn4bRadioGroup((RadioGroup) findViewById(R.id.kn4b_radio_group));
fragment.setKn4cRadioGroup((RadioGroup) findViewById(R.id.kn4c_radio_group));
fragment.setKn4dRadioGroup((RadioGroup) findViewById(R.id.kn4d_radio_group));
fragment.setKn4eRadioGroup((RadioGroup) findViewById(R.id.kn4e_radio_group));
fragment.setKn4fRadioGroup((RadioGroup) findViewById(R.id.kn4f_radio_group));
fragment.setKn4gRadioGroup((RadioGroup) findViewById(R.id.kn4g_radio_group));
fragment.setKn4hRadioGroup((RadioGroup) findViewById(R.id.kn4h_radio_group));
fragment.setKn4iRadioGroup((RadioGroup) findViewById(R.id.kn4i_radio_group));
fragment.setKn4jRadioGroup((RadioGroup) findViewById(R.id.kn4j_radio_group));
fragment.setAp2aRadioGroup((RadioGroup) findViewById(R.id.ap2a_radio_group));
fragment.setAp2bRadioGroup((RadioGroup) findViewById(R.id.ap2b_radio_group));
fragment.setAp2cRadioGroup((RadioGroup) findViewById(R.id.ap2c_radio_group));
fragment.setAp2dRadioGroup((RadioGroup) findViewById(R.id.ap2d_radio_group));
fragment.setAp2eRadioGroup((RadioGroup) findViewById(R.id.ap2e_radio_group));

Is there any easy way to do it?


texts: A light/dark theme toggle react component

texts:
I have a dark theme toggle switch for my React component that works well, but I know the code could use some work. First I am checking to see what the users' preferences are for light/dark. Then I am setting in local storage what the user has chosen as a preference and then also checking for that value. I'm still learning and would like some feedback.

My requirements:

Needs to check the users' system preference for light/dark
Needs to persistently keep users light/dark preference throughout the site
Add class dark to the body tag in order to active all the CSS changes

import React, { Component } from "react";

class LightDarkToggle extends React.Component {

  componentDidMount() {
    let bodyClassList = document.body.classList;
    let themeSwitch = document.getElementById('switch-style');

      //Here we are checking the USERS' device settings for dark theme
      if(window.matchMedia('(prefers-color-scheme: dark)').matches) {
        bodyClassList.add('dark');
        themeSwitch.checked = true;
      }
      else if(window.matchMedia('(prefers-color-scheme: light)').matches) {
        bodyClassList.remove('dark');
        themeSwitch.checked = false;
      }

      //Persisting USERS' theme preference by checking the local storage we set
      if(window.localStorage.getItem('theme') === 'dark') {
        bodyClassList.add('dark');
        themeSwitch.checked = true;
      }
      else if(window.localStorage.getItem('theme') === 'light') {
        bodyClassList.remove('dark');
        themeSwitch.checked = false;
      }

  }

  handleClick() {
    document.body.classList.toggle('dark');

    if(document.getElementById('switch-style').checked === true){
      window.localStorage.setItem('theme', 'dark');
    }
    else if (document.getElementById('switch-style').checked === false){
      window.localStorage.setItem('theme', 'light');
    }

  }

  render() {
    return (

          <input type="checkbox" id="switch-style" onClick={this.handleClick} />

    );
  }
}

export default LightDarkToggle;
```


texts:
Basically, this function returns a list of flights for an airline. But if the airline doesn't exist, I want to throw some custom runtime exception. If that airline does exist, I want to return a list of flights (which could potentially be empty).

Is this is the standard way of doing things in Scala, or is there a better way to write this code?

Coming from a Java background, I'm still trying to get to grips with the Scala way of doing things.

def getFlightsForAirline(id:Long):Try[Option[List[Flight]]] = {
     val maybeAirline:Option[Airline] = Airline.getById(id)

     maybeAirline match {
       case Some(airline) => {
          Success(Flight.getFlightsByAirline(airline))
       }
       case None => Failure(new RecordNotFoundException("Couldnt find airline"))
     }
   }


texts: Computing the largest substring starting with a substring

texts:
Given a string and a non-empty substring sub, compute recursively the largest substring which starts and ends with sub and return its length.

sub_sandwich("catcowcat", "cat") → 9
sub_sandwich("catcowcat", "cow") → 3
sub_sandwich("cccatcowcatxx", "cat") → 9

I'm not very satisfied with my code and I'm not sure how I can improve it.

def subSandwich(word, char, pos, start, end):
    if pos == len(word)-1:
        if end == 0:
            return len(char)
        return end - (start-2)

    if word[pos:pos+len(char)] == char:
        if start != 0:
            end = pos + len(char) - 1
        else:
            start = pos+1

    return subSandwich(word, char, pos + 1, start, end)

def main():
    print subSandwich("catcowcat", "cow",0,0,0)

if __name__ == "__main__":
    main()


texts:
I'm using jQuery to create a (hidden) form that redirects people to another page using JavaScript.

// redirect the user to another url
function redirect(options) {
  // create the form
  $("<form>").attr({
    "hidden": true, "action": options.url, "target": (options.new_tab === true) ? "_blank" : "_self"
  // create the query inputs and append them to the form
  }).append($.map(options.queries || {}, function(name, value) {
    return $("<input>").attr({"name": name, "value": value, "hidden": true})[0];
  // append the form to the body and submit it
  })).appendTo("body").submit();
}

To simplify this question the form looks like this when broken down:

// redirect the user to another url
function redirect(options) {
  // create the form
  var form = $("<form>").attr({
    "hidden": true,
    "action": options.url,
    "target": (options.new_tab === true) ? "_blank" : "_self"
  });

  // create the query inputs and append them to the form
  form.append($.map(options.queries || {}, function(name, value) {
    return $("<input>").attr({
      "name": name,
      "value": value,
      "hidden": true
    })[0];
  }));

  // append the form to the body and submit it
  form.appendTo("body").submit();
}

How can I simplify the second part of this code?

// create the query inputs and append them to the form
form.append($.map(options.queries || {}, function(name, value) {
  return $("<input>").attr({
    "name": name,
    "value": value,
    "hidden": true
  })[0];
}));


texts: Aggregating recent trading data from Bitcoin derivatives exchange

texts:
As a component of some trading software, I wrote function parse_ticks(), as part of an Exchange class that models the Bitcoin derivatives exchange BitMEX.
The purpose of parse_ticks() is to convert the previous minutes stored tick data (a list of individual trades, obtained by calling all_ticks = self.ws.get_ticks()) into a dictionary which aggregates the  OHLCV values from the list of previous minutes ticks. The list of trades is a list of dict's, each dict containing a timestamp, size of trade, if the tick was a buy or sell, etc.
parse_ticks() gets invoked once per instrument when minute elapses. In this scenario, I am watching two instruments, so parse_ticks() gets called twice at the start of each minute.
I timed parse_ticks() run time for 2400 minutes (2400 observations) with as many background processes and programs disabled as possible, and obtained these results (in seconds):
mean run time: 0.0318425
min run time: 0.00458
max run time: 0.07958
std dev: 0.02276709988
Theres a massive range here, with the min and max  substantially different, and the std dev is almost as large as the mean.
How would I lower the std. dev of parse_ticks() run time, and get the mean run time closer the minimum observation of 0.00458?
Is this kind of optimisation within the scope of python?
EDIT: To answer the questions in comments (thank you all for your help):
ws.get_ticks() has no outbound API calls, it looks like this:
def get_ticks(self):
        return self.data['trade']

where data['trade'] is a list containing ticks saved from a websocket stream in realtime. The 'trade' list is trimmed by 30% if it goes above 10000 elements, so that aspect (constantly-increasing amount of data to parse) is constant, once the limit is reached. So the data is already available when parse_ticks() is called.
The amount of ticks DOES vary, so some variance can be explained by that. But surely not the extreme range of 0.075? (min - max).
The run times are seemingly random, there are long and short runs interspersed throughout all the observations.
self.bars = {}
self.symbols = ["XBTUSD", "ETHUSD"]
self.ws = Bitmex_WS()

def parse_ticks(self):
    """Return a 1-min OHLCV dict, given a list of the previous
       minutes tick data."""

    all_ticks = self.ws.get_ticks()
    target_minute = datetime.datetime.utcnow().minute - 1
    ticks_target_minute = []
    tcount = 0

    # search from end of tick list to grab newest ticks first
    for i in reversed(all_ticks):
        try:
            ts = i['timestamp']
            if type(ts) is not datetime.datetime:
                ts = parser.parse(ts)
        except Exception:
            self.logger.debug(traceback.format_exc())

        # scrape prev minutes ticks
        if ts.minute == target_minute:
            ticks_target_minute.append(i)
            ticks_target_minute[tcount]['timestamp'] = ts
            tcount += 1

        # store the previous-to-target-minute bar's last
        # traded price to use as the open price for target bar
        if ts.minute == target_minute - 1:
            ticks_target_minute.append(i)
            ticks_target_minute[tcount]['timestamp'] = ts
            break
    ticks_target_minute.reverse()

    # reset bar dict ready for new bars
    self.bars = {i: [] for i in self.symbols}

    # build 1 min bars for each symbol
    for symbol in self.symbols:
        ticks = [i for i in ticks_target_minute if i['symbol'] == symbol]
        bar = self.build_OHLCV(ticks, symbol)
        self.bars[symbol].append(bar)
        # self.logger.debug(bar)


texts:
Today I built a linspace function in Python's C API:

static PyObject *
linspace(PyObject * self, PyObject * args)
{
    int n, i;
    double start, end;

    if (!PyArg_ParseTuple(args, "ddi:linspace", &start, &end, &n))
        return NULL;

    if (n <= 1)
        return Py_BuildValue("[d]", end);

    double h;
    PyObject *pylist = PyList_New(n);

    h = (end - start) / (n - 1);

    for (i = 0; i < n; i++)
        PyList_SetItem(pylist, i, Py_BuildValue("d", (start + h * i)));

    return Py_BuildValue("O", pylist);
}

It behaves how I would like it to behave, however, when I benchmarked it against NumPy's linspace it was slower by about a factor of 80.

I have a few questions that I think may be affecting performance, but I can't seem to find help online:

Is there a memory leak? Or am I not incrementing or decrementing any references that I should be?
Can I do this with a C double array and then return that as a Python Object? Would this even be faster (I think it may)?
Am I missing something? I am new to the C API and I am not confident in it yet.


texts: First-time F#: A simple Rock Paper Scissors

texts:
This is my first F# program. It's a simple Rock-Paper-Scissors implementation.
I am looking for feedback of all sorts, e.g. the choice of types (e.g. List vs Array), whether there are parts that could be solved more elegantly / idiomatic, formatting, etc.
open System

let allowedActions = [ "r"; "p"; "s" ]

let randomItem list (rng: Random) =
    List.item (rng.Next(List.length list)) list

let computerAction () = randomItem allowedActions (Random())
let rec playerAction () =
    printfn "Write 'r' for Rock, 'p' for Paper, 's' for Scissors. Type 'q' to Quit."

    let input = Console.ReadLine()

    let isInputAllowed = List.contains input allowedActions || input = "q"
    match isInputAllowed with
    | true -> input
    | _ -> printfn "invalid input '%s'" input; playerAction()

let computerWin playerAction computerAction =
    printfn "The computer did win. '%s' beats '%s'." computerAction playerAction
let playerWin playerAction computerAction =
    printfn "The player did win. '%s' beats '%s'." playerAction computerAction
let tie anAction = printfn "It's a tie. '%s'" anAction

let ruling playerAction computerAction =
    match (playerAction, computerAction) with
    | ("r", "p")
    | ("p", "s")
    | ("s", "r") -> computerWin playerAction computerAction
    | ("r", "s")
    | ("p", "r")
    | ("s", "p") -> playerWin playerAction computerAction
    | (_, _) -> tie playerAction

let playGame playerAction computerAction =
    printfn "You've chosen '%s'." playerAction
    printfn "The computer chose '%s'." computerAction
    ruling playerAction computerAction
    ()

let game () =
    let playerAction = playerAction ()
    let computerAction = computerAction ()
    match playerAction with
    | "q" -> false
    | _ ->
        playGame playerAction computerAction
        true

[<EntryPoint>]
let rec main arg =
    printfn "Hello World to Rock Paper Scissors"
    match game () with
    | true -> main arg
    | false -> 0
```


texts: Processing a list of pairs of items using promises and functional programming

texts:
I posted an answer on StackOverflow which I believed to be adherent to the principles of Functional Programming.

However, I was told by the original asker that it was not 'functional' as my function used an internal variable oldData which kept track of results.

I believe that the code still satisfies the paradigms of functional programming as it does not mutate it's arguments, does not use globals and has no side effects (assuming action is not a network call)

Is the function process() violating the principles of functional programming? If so, how would I fix it?

var items = [
    ["item1", "item2"],
    ["item3", "item4"],
    ["item5", "item6"],
    ["item7", "item8"],
    ["item9", "item10"]
]

function action(item) {
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve(item + ":processed");
        }, 100)
    });
}

function process(items) {
  return items.reduce((m, d) => {
    const promises = d.map(i => action(i));
    let oldData;
    return m.then((data) => {
        oldData = data;
        return Promise.all(promises);
      })
      .then(values => {
        //oldData.push(...values);
        oldData.push.apply(oldData, values);
        return Promise.resolve(oldData);
      })
  }, Promise.resolve([]))
}

process(items).then(d => console.log(d))

//Prints:

// ["item1:processed","item2:processed","item3:processed","item4:processed","item5:processed","item6:processed","item7:processed","item8:processed","item9:processed","item10:processed"]

The original asker suggested that I update my code to use concat instead of push to create immutable arrays every time to make this properly functional. Does that make sense?


texts:
This is my Stack implementation in Python.

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return self

    def __next__(self):
        if self.head:
            curr = self.head
        else:
            raise StopIteration()
        self.head = self.head.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

Need comments on primarily 3 aspects -

Is there anything, just plain wrong?
How to improve efficiency of this design?
What more can I add to make it an actually usable data structure beyond the ADT specification?


texts:
I have created this bash script for Compile And Run c++ code, car++.sh.
As I'm new to bash scripting, I'm not sure about good bash programming practices.

Please review it to see if you could find any anomaly.

#!/bin/bash

found=false;
output=;
o_is_set=false;

#retrieve output_filename from arguments as provided by user
for arg in "$@"
do
    if [ "$o_is_set" = true ]
    then
        output="$arg";
        found=true;
        break;
    fi

    if [[ $arg == -o ]]
    then
        o_is_set=true;
    fi
done

#else retrieve from file name of first .cpp or .c++ file specified
if [ "$found" = false ]
then
    for file in "$@"
    do
        ext=$(echo $file | tr '[:upper:]' '[:lower:]');

        if [[ $ext == *.cpp ]]
        then
            output=$(basename "$file" ".cpp");
            found=true;
            break;
        fi

        if [[ $ext == *.c++ ]]
        then
            output=$(basename "$file" ".c++");
            found=true;
            break;
        fi
    done
fi

#else retrieve from first .c file specified
if [ "$found" = false ]
then
    for file in "$@"
    do
        ext=$(echo $file | tr '[:upper:]' '[:lower:]');

        if [[ $ext == *.c ]]
        then
            output=$(basename "$file" ".c");
            found=true;
            break;
        fi
    done
fi

#output file name is not specified by user and there is no C++ or C file,
#lets see what g++ says about it
if [ "$found" = false ]
then
echo;
    g++ -Wall -std=c++11 "$@";
    exit "$?";
fi

run="./$output";

g++ -Wall -o "$output" -std=c++11 "$@" && $run;


texts:
I've implemented an external mergesort to sort a file consisting of Java int primitives, however it is horribly slow (fortunately it does at least work).

Very little happens in the sort method: it just recursively calls merge with blockSize doubling each call and swapping input and output files each time.

How could I be losing so much time here?

//Merge stage of external mergesort
//Read from input file, already sorted into blocks of size blockSize
//Write to output file, sorted into blocks of 2*blockSize
public static void merge(String inputFile, String outputFile, long blockSize)
    throws IOException
{
  //readers for block1/2
  FileInputStream fis1 = new FileInputStream(inputFile);
  DataInputStream dis1 = new DataInputStream(fis1);
  FileInputStream fis2 = new FileInputStream(inputFile);
  DataInputStream dis2 = new DataInputStream(fis2);

  //writer to output file
  FileOutputStream fos = new FileOutputStream(outputFile);
  DataOutputStream dos = new DataOutputStream(fos);

  // merging 2 sub lists
  // go along pairs of blocks in inputFile
  // continue until end of input

  //initialise block2 at right position
  dis2.skipBytes((int) blockSize);

  //while we haven't reached the end of the file
  while (dis1.available() > 0)
    {
      // if block1 is last block, copy block1 to output
      if (dis2.available() <= 0)
        {
          while (dis1.available() > 0)
            dos.writeInt(dis1.readInt());
          break;
        }
      // if block1 not last block, merge block1 and block2
      else
        {
          long block1Pos = 0;
          long block2Pos = 0;
          boolean block1Over = false;
          boolean block2Over = false;

          //data read from each block
          int e1 = dis1.readInt();
          int e2 = dis2.readInt();

          //keep going until fully examined both blocks
          while (!block1Over | !block2Over)
            {
              //copy from block 1 if:
              //  block1 hasnt been fully examined AND
              //  block1 element less than block2s OR block2 has been fully examined
              while ( !block1Over & ((e1 <= e2) | block2Over) )
                {
                  dos.writeInt(e1); block1Pos += 4;
                  if (block1Pos < blockSize & dis1.available() > 0)
                    e1 = dis1.readInt();
                  else
                    block1Over = true;
                }
              //same for block2
              while ( !block2Over & ((e2 < e1) | block1Over) )
                {
                  dos.writeInt(e2); block2Pos += 4;
                  if (block2Pos < blockSize & dis2.available() > 0)
                    e2 = dis2.readInt();
                  else
                    block2Over = true;
                }
            }
        }
      // skip to next blocks
      dis1.skipBytes((int) blockSize);
      dis2.skipBytes((int) blockSize);
    }
  dis1.close();
  dis2.close();
  dos.close();
  fos.close();
}


texts: Authenticating user/password against Active Directory using ASP.NET Identity

texts:
I am trying to learn how to use ASP.NET Identity. My scenario is that I have to authenticate against Active Directory. For that purpose I am trying to use ActiveDirecotoryMembershipProvider.

What I have to do is:

Authenticate user/password against Active Directory
Check whether user is present in my own database

The way I did it is I configured in my web.config to use ActiveDirectoryMembershipProvider as default membership provider. Then I override PasswordSignInAsync method in my ApplicationSignInManager class (which inherits SignInManager) as follows:

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    var adok = Membership.Provider.ValidateUser(userName, password);
    if (adok)
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
            return Task.FromResult<SignInStatus>(SignInStatus.Failure);
        else
        {
            base.SignInAsync(user, isPersistent, shouldLockout);
            return Task.FromResult<SignInStatus>(SignInStatus.Success);
        }
    }
    else
        return Task.FromResult<SignInStatus>(SignInStatus.Failure);
}

This seems to work, but I think it's not the right way to do it. Can anyone suggest any better way of achieving this?


texts: What takes precedence: readability or elimination of side effects?

texts:
I have a method:

  def removeExpiredCookies(jar: CookieJar): CookieJar = {
    val currentDate = System.currentTimeMillis / 1000L
    jar.filter(_._2._2 > currentDate)
  }

You use said method like so.

var cookieJar = new CookieJar
cookieJar = removeExpiredCookies(cookieJar)

That method has no side effects. But it's used inside a class:

class CookieManager {
      type ExpiryDate = Long
      type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

      var cookieJar = new CookieJar

      private def removeExpiredCookies(jar: CookieJar): CookieJar = {
        val currentDate = System.currentTimeMillis / 1000L
        jar.filter(_._2._2 > currentDate)
      }

      def getCookie(domain: String): Set[Cookie] = {
        cookieJar = removeExpiredCookies(cookieJar)
        cookieJar.find(_._1 endsWith (domain))
      }
}

Is it better to write the method such as above or to have a more succinct and readable code but with side-effecting methods? I'm guessing as this is encapsulated inside a class, this is actually "better" for maintainability but it is not as pure functional programming. It's an imperative style. However, the strongest argument against this is that it's more difficult to test as the tests are not as isolated.

class CookieManager {
      type ExpiryDate = Long
      type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

      var cookieJar = new CookieJar

      private def removeExpiredCookies {
        val currentDate = System.currentTimeMillis / 1000L
        cookieJar = cookieJar.filter(_._2._2 > currentDate)
      }

      def getCookie(domain: String): Set[Cookie] = {
        removeExpiredCookies() //bracket to indicate side effect
        cookieJar.find(_._1 endsWith (domain))
      }
}


texts: Kattis challenge to finding the number of different elements in a set

texts:
I have started doing Kattis challenges from their website. For now I am still at the low complexity ones.

The first line of input contains a single positive integer T≤50 indicating the number of test cases. The first line of each test case also contains a single positive integer n indicating the number of elements available for the test case.

Elements only contain lowercase letters, have at least one letter, and do not contain spaces.

The number elements for a test case is at most 100 and each element contains no more than 20 characters.

For each test case, I have to output a single line containing a single integer that is the number of distinct elements found in the specific test case.

To view the challenge follow this link: I've Been Everywhere, Man

Sample input:

2
7
saskatoon
toronto
winnipeg
toronto
vancouver
saskatoon
toronto
3
edmonton
edmonton
edmonton

Sample output:

4
1

Here is the code:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using std::cin;
using std::cout;
using std::vector;
using std::string;

int main()
{
    int testCasesCount = 0, tripsCount = 0;
    vector<string> trips;
    vector<int> testCasesResults;

    cin >> testCasesCount;

    for (int i = 0; i < testCasesCount; i++) {
        cin >> tripsCount;

        string destination;
        int uniqueCount = 0;
        for (int j = 0; j < tripsCount; j++) {
            cin >> destination;

            if (std::find(trips.begin(), trips.end(), destination) == trips.end())
                trips.push_back(destination);
        }

        testCasesResults.push_back(uniqueCount);
    }

    for (unsigned int i = 0; i < testCasesResults.size(); i++)
        cout << testCasesResults.at(i) << "\n";

    return 0;
}

The code is working fine, BUT it's kind of ugly, at least that's how I see it.

My first question is to ask if there is a better way to check if an array/vector contains a certain element?

And the second question - can someone give me some tips as to what I can improve and what will be a good idea to avoid?


texts: Uniformly generate a number from 0 to n-1 that isn't on a blacklist

texts:
The task:

  Given an integer n and a list of integers l, write a function that
  randomly generates a number from 0 to n-1 that isn't in l (uniform).

Solution 1:

const getRandNotInList = (n , list) => {
  const rand = Math.floor(Math.random() * n);
  return list.includes(rand) ? getRandNotInList(n, list) : rand;
};

console.log(getRandNotInList(16, [1,2,3,4]));

Solution 2:

const getRandNotInList2 = (n, list) => {
  let rand;
  do { rand = Math.floor(Math.random() * n); }
  while(list.includes(rand));
  return rand;
};

console.log(getRandNotInList2(13, [2,3,4,5,6]));


texts: Pull data from database to generate XML files

texts:
I have the following script in Perl that does the following:

Prompts user for time in epoch. If user enters '########', the query will look for all reports generated after that date/time. If user does not input time, it will just look for all reports in past day.
Connects to a database, runs a query to receive reports
I create a directory of the current date (i.e. Jun25)
I iterate through every row in the results and I save the contents of the xml file into an actual file and name the file [customer name]-[epoch time].xml

I am trying to clean up my code and have it run more efficiently.

#!/usr/bin/perl

#use strict;
use DBI;
use File::Slurp;
use Encode;
use utf8;
use POSIX qw(strftime);
use File::Slurp;
use XML::XPath;
use XML::XPath::XMLParser;
$| = 1;
print "Please enter epoch time of which to receive reports or leave blank to receive last day of reports: ";
my $epoch = <STDIN>;
chomp($epoch);
if ($epoch =~ /\D/) {$epoch = time() - 86400}
###Start Database
my $dsn = join "", (
    "dbi:ODBC:",
    "Driver={SQL Server};",
    "Server=SERVER;",
    "Database=DATABASE",
);
my $user = q/USERNAME/;
my $password = q/PASSWORD/;

my $db_options = {
    PrintError => 1,
    RaiseError => 1,
    #LongTruncOk => 1,
    LongReadLen => 100000000,
};

print "CONNECTING TO DATABASE...";
# Connect to the data source and get a handle for that connection.
my $dbh = DBI->connect($dsn, $user, $password, $db_options)
    or die "Can't connect to $dsn: $DBI::errstr";
print "CONNECTED\nFETCHING ROWS AND PARSING...\n";

my $sql = "SELECT [receivedTime], [reportXml] from UsageReport WHERE [receivedTime] > " . $epoch . " AND [reportXml] NOT LIKE '%exclude%'";

# Prepare the statement.
my $sth = $dbh->prepare($sql)
     or die "Can't prepare statement: $DBI::errstr";

$sth->execute();
###End Database

#Make Directory of Current Date
$datestring = strftime "%b%d", localtime;
mkdir $datestring;
chdir $datestring;
# Fetch and display the result set value.
my @matrix;
my $count = 0;
while (my @row = $sth->fetchrow_array ) {
    my ($time, $report) = @row; #time, report
    $count++;
    eval {
        my $xp = XML::XPath->new(xml => $report);
        my $customer = $xp->getNodeText('/report/instances/instanceroot/instanceheader/customer');
        if ($customer eq "") {next;}
        our $ext = $customer . "-" . $time . ".xml";
        write_file($ext, $report);
    };
    if ( $@ ) {printf "ERROR ";}
    else {printf "$count ";}
}

# Disconnect the database from the database handle.
$dbh->disconnect;
print "\nCOMPLETED REPORT PARSING\nLatest Report Date: ";


texts: Logger which writes asynchronously to file from multiple threads

texts:
I have written a simple logger, AsyncFile, which asynchronously writes data to a file. Since data is going to be written very often (E.g. 10 writes per 30 milliseconds from different threads, my system has a 30ms sync time), I would like to know if:

1. The design makes sense att all? Am I missing something obvious?
2. If the logger is fairly optimal, e.g. that no unneccessary copying takes place.

Basically, my idea is to write data to a shared buffer(m_queue), then copy that data to a tempBuffer from which I then write to a file.

The method write can be called from multiple threads.

I have tested this logger and it seems to work fine, but like all problems involving shared resources, it is hard to know if it is well-designed until you have tried it for a good amount of time.

AsyncFile.h:

#pragma once

#include <cstdint>
#include <cstddef>
#include <array>
#include <mutex>
#include <condition_variable>

class AsyncFile
{
public:

   AsyncFile();

   void write(std::array<char,40>& buffer);

   void done();

private:

    std::array<char, 160> m_queue;

    std::array<char, 160> tempBuffer;

    std::mutex queue_mutex;

    std::condition_variable cv;

    size_t counter = 0;

    bool readyToCopy = false;

    bool finished = false;

    void logger_thread();

}; // class AsyncFile

AsyncFile.cpp:

#include <thread>
#include <fstream>
#include <string.h>
#include <iostream>
#include <chrono>

void AsyncFile::logger_thread()
{
    FILE* file = fopen("test_file.bin", "wb");

    while(!finished) // Pass "finished" as a parameter by ref? Protect by a mutex?
    {
        std::unique_lock<std::mutex> lk(queue_mutex);
        cv.wait(lk, [&]{return readyToCopy;});

        std::copy(m_queue.begin(), m_queue.end(), tempBuffer.begin());

        readyToCopy = false;
        lk.unlock();

        // Now write to file from the temporary buffer:
        fwrite(&tempBuffer, sizeof(char), sizeof(tempBuffer), file);
    }
    fclose(file);
}

AsyncFile::AsyncFile()
{
      std::thread m_worker(&AsyncFile::logger_thread, this);
      m_worker.detach(); // let the worker thread live on its own.
}

void AsyncFile::done()
{
    finished = true;
}

void AsyncFile::write(std::array<char, 40>& buffer) // 40 should probably be a
                                                    // configurable parameter.
{
   std::lock_guard<std::mutex> guard(queue_mutex);
   std::copy(buffer.begin(), buffer.end(), m_queue.begin() + counter);
   if (counter == 120) // fill the queue, 40 char each time, until we have 160 chars in total. Then
                       // notify the writing thread we are ready.
   {
      counter = 0;
      readyToCopy = true;
      cv.notify_one();
   }
   else
   {
      counter += 40;
   }
}


texts: Toggle menu under specified screen width

texts:
I've created a simple toggle menu in jQuery, which is capable of specifying a breakpoint, but I'm afraid my code is too complicated. How can I make it simpler?

I also have a question about performance of code on window resize. I want to invoke a function only once if the window's width is smaller than a given breakpoint. Should I use some boolean variable, or is there a better solution?

Here's a pen.

$(document).ready(function() {
  var $menuBtn = $('[href="#menu"]'),
      $nav = $('#menu'),
      $window = $(window),
      breakpoint = 800;

  function changeMenuStyle() {
    if ($window.width() < breakpoint) {
      $menuBtn.show();
      $nav.addClass('toggled').hide();
    } else {
      $menuBtn.hide();
      $nav.removeClass('toggled').show();
    }
  }

  changeMenuStyle();

  $window.on('resize',function() {
    changeMenuStyle();
  });

  $menuBtn.on('click',function(e) {
    e.preventDefault();
    $nav.slideToggle();
  });
});
* {
  box-sizing: border-box;
}

body {
  background: #485373;
  font-family: "Lato", sans-serif;
  font-weight: 300;
}

.container {
  max-width: 940px;
  margin: 0 auto;
}

.menu-link {
  display: block;
  color: #fff;
  background: #202332;
  width: 100%;
  padding: 20px;
  text-decoration: none;
}
.menu-link i {
  display: inline-block;
  margin: 0 10px;
}

.menu {
  overflow: hidden;
}
.menu i {
  display: block;
  font-size: 25px;
  padding: 10px 0;
}
.menu ul {
  width: 100%;
}
.menu li {
  width: 20%;
  float: left;
  text-align: center;
}
.menu a {
  display: block;
  padding: 20px;
  width: 100%;
  background: #323A51;
  color: #fff;
  text-decoration: none;
  border-bottom: 2px transparent solid;
}
.menu a:hover {
  background: #202332;
  border-bottom: 2px #fff solid;
}
.menu.toggled i {
  display: inline-block;
  margin-right: 10px;
  padding: 0;
  font-size: 15px;
}
.menu.toggled li {
  width: 100%;
}
.menu.toggled a {
  padding: 10px;
}

main {
  padding: 50px;
  color: #fff;
}
main h1 {
  font-size: 30px;
  font-weight: 400;
  line-height: 40px;
  margin: 10px 0;
}

    Menu

Home

About

Services

Team

Contact

Toggle menu

Vestibulum tempus at ipsum a finibus. Mauris pharetra eleifend odio quis lacinia. Pellentesque ullamcorper, dolor vel congue tincidunt, mi nisl suscipit metus, nec bibendum elit ligula vitae leo. Integer volutpat semper iaculis. Mauris fermentum, enim ac finibus scelerisque, magna nibh volutpat dolor, vitae sodales mi augue molestie augue. Aliquam ultricies eget mi vel viverra. Morbi id tortor purus. Vivamus sed pretium justo. Fusce porttitor eu neque quis volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ultrices metus a aliquet tincidunt. Ut pellentesque dui nec ipsum fringilla ultricies.


texts:
I have the following data structure that's obtained from a third party:

var data = [
    ["Parent1", "Parent1.1", "Parent1.1.1"],
    ["Parent2", "Parent2.1", "Parent2.1.1"],
    ["Parent3", "Parent3.1", "Parent3.1.1"],
    ["Parent1", "Parent1.2", "Parent1.2.1"],
    ["Parent1", "Parent1.2", "Parent1.2.2"]
];

Where child nodes may or may not be present.
I'm turning it into a tree to represent the data logically:

var tree = {
    "Parent1": {
        "Parent1.1": ["Parent1.1.1"],
        "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
    },
    "Parent2": {
        "Parent2.1": ["Parent2.1.1"]
    },
    "Parent3": {
        "Parent3.1": ["Parent3.1.1"]
    }
};

What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:

var tree = data.reduce(function(tree, item) {
    if (!item[0]) return tree;
    tree[item[0]] = tree[item[0]] || {};
    if (!item[1]) return tree;
    tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
    if (!item[2]) return tree;
    tree[item[0]][item[1]].push(item[2]);
    return tree;
}, {}); //Returns as shown above

Is there a better way to approach this problem, what improvements could be made?
The depth of the data is always fixed at three.


texts: Handling dialog closure in a VBA user form

texts:
I already asked a Code Review question about Working with a new form instance every time.

As far as I have decided, that the most important part of the code is to work with the instance of the form and to learn how to handle them properly, I have remade the code (roughly using the code from @Mat's Mug) in a way that I am looking for a type of a boilerplate for forms, that I will probably use later.

Thus, let's start. I have a form, that looks like this:

Buttons are called btnStart, btnExit and lblInfo.

This is the code behind the frmMain:

Option Explicit

Public Event OnRunReport()
Public Event OnExit()

Private Sub btnRun_Click()
    RaiseEvent OnRunReport
End Sub

Private Sub btnExit_Click()
    RaiseEvent OnExit
End Sub

Private Sub UserForm_QueryClose(CloseMode As Integer, Cancel As Integer)

    End

End Sub

This is the code behind the modMain:

Option Explicit

Private objPresenter   As clsSummaryPresenter

Public Sub MainGenerateReport()

    Call objPresenter.ChangeLabelAndCaption("Starting and running...", "Running...")
    GenerateNumbers

End Sub

Public Sub GenerateNumbers()

    Dim lngLong         As Long
    Dim lngLong2        As Long

    tblMain.Cells.Clear

    For lngLong = 1 To 3000
        For lngLong2 = 1 To 10
            tblMain.Cells(lngLong, lngLong2) = lngLong * lngLong2
        Next lngLong2
    Next lngLong

End Sub

Public Sub ShowMainForm() 'CTRL+E

    If (objPresenter Is Nothing) Then Set objPresenter = New clsSummaryPresenter
    objPresenter.Show

End Sub

This is the code behind the clsSummaryPresenter:

   Option Explicit

    Private WithEvents objSummaryForm As frmMain

    Private Sub Class_Initialize()

        Set objSummaryForm = New frmMain

    End Sub

    Private Sub Class_Terminate()

        Set objSummaryForm = Nothing

    End Sub

    Public Sub Show()

        If Not objSummaryForm.Visible Then
            objSummaryForm.Show vbModeless
            objSummaryForm.lblInfo = "Press Run to Start"
            objSummaryForm.Caption = "Starting"
        End If

    End Sub

    Public Sub Hide()

        If objSummaryForm.Visible Then objSummaryForm.Hide

    End Sub

  Public Sub ChangeLabelAndCaption(strLabelInfo As String, strCaption As String)

    objSummaryForm.lblInfo = strLabelInfo
    objSummaryForm.Caption = strCaption
    objSummaryForm.Repaint

  End Sub

  Private Sub objSummaryForm_OnRunReport()

    MainGenerateReport
    Refresh

End Sub

Private Sub objSummaryForm_OnExit()

    Hide

End Sub

Public Sub Refresh()

    With objSummaryForm
        .lblInfo = "Ready"
        .Caption = "Task performed"
    End With

End Sub

What I am not sure (and I did not understand) was how to handle the red X in a way that there is no error after it. Thus, I have decided to use the End, which seems to work fine.

I have put the Excel file on GitHub.  It contains the same VBA code as shown above, I encourage you to first inspect it with macros disabled, as a good security practice with Excel files from the Internet.


texts: Returning elements in a list also found in another list

texts:
I'm trying to write a short function which takes a list (a) and returns another list which only contains the elements (x) such that -x is also in a. I've done that, and it works, but it runs really slowly. I know why it does, and I know the second for loop is unnecessary, but I don't know how to fix it without breaking the function.

def negated(a):
    mark = set()
    add_mark = mark.add
    b = []
    c = []
    for i in a:
        if i not in mark and not add_mark(i):
            b.append(i)
    for i in b:
        if -i in b:
            c.append(i)
    return c


texts:
Pretty simple 2-Dimensional Vector template with operators and two utility functions making use of C++20 concepts. Header-only templates, function inlining and operator overloading, etc. is not exactly my strong foot, so that's why i wrote this hoping to get some feedback.
#pragma once

#include <cmath>
#include <type_traits>

namespace math {

    template<typename T>
    concept Arithmetic = std::is_arithmetic_v<T>;

    template<Arithmetic T>
    struct Vector2D
    {
        T X = 0;
        T Y = 0;

        Vector2D() = default;

        Vector2D(T x, T y);

        Vector2D(const Vector2D<T> &other);

        inline T Magnitude() const;

        inline Vector2D<T> Normal() const;
    };

    template<Arithmetic T>
    inline Vector2D<T>::Vector2D(T x, T y) : X(x), Y(y)
    {}

    template<Arithmetic T>
    inline Vector2D<T>::Vector2D(const Vector2D<T> &other) : X(other.X), Y(other.Y)
    {}

    template<Arithmetic T>
    inline T Vector2D<T>::Magnitude() const
    {
        return std::sqrt(X * X + Y * Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> Vector2D<T>::Normal() const
    {
        auto magnitude = Magnitude();

        return Vector2D<T>(X / magnitude, Y / magnitude);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator-(const Vector2D<T> &vec)
    {
        return Vector2D<T>(-vec.X, -vec.Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator+(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        return Vector2D<T>(first.X + second.X, first.Y + second.Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator-(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        return Vector2D<T>(first.X + second.X, first.Y + second.Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator*(const Vector2D<T> &vec, const T factor)
    {
        return Vector2D<T>(vec.X * factor, vec.Y * factor);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator*(const T factor, const Vector2D<T> &vec)
    {
        return Vector2D<T>(factor * vec.X, factor * vec.Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> operator/(const Vector2D<T> &vec, const T divisor)
    {
        return Vector2D<T>(vec.X / divisor, vec.Y / divisor);
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator+=(Vector2D<T> &first, const Vector2D<T> &second)
    {
        first.X += second.X;
        first.Y += second.Y;

        return first;
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator-=(Vector2D<T> &first, const Vector2D<T> &second)
    {
        first.X -= second.X;
        first.Y -= second.Y;

        return first;
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator*=(Vector2D<T> &vec, const T factor)
    {
        vec.X *= factor;
        vec.Y *= factor;

        return vec;
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator/=(Vector2D<T> &vec, const T factor)
    {
        vec.X /= factor;
        vec.Y /= factor;

        return vec;
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator==(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        return (first.X == second.X) && (second.Y == second.Y);
    }

    template<Arithmetic T>
    inline Vector2D<T> &operator!=(const Vector2D<T> &first, const Vector2D<T> &second)
    {
        return !(first == second);
    }
}


texts: Counting occurrences of each word in a sentence

texts:
I have been doing this test task for C# Developer role at UBS.London recently and have been rejected. No reason stated yet. Was wondering if you can take a look and provide feedback on what I can do to improve solution. The task description is below and solution itself is on GitHub. Also attached code for two main classes I have implemented. Unit tests are in solution. No UI provided as I thought it is not required as Unit tests are self explanatory.

Hope it will be helpful for someone else doing interviews for C# Dev roles.

Exercise description

  Create a .net application that will solve the following problem. There
  are no time constraints and you are free to use any resources at your
  disposal.

  The Problem As an author I want to know the number of times each word
  appears in a sentence So that I can make sure I'm not repeating myself

  Acceptance Criteria Given a sentence When the program is run Then I'm
  returned a distinct list of words in the sentence and the number of
  times they have occurred

  Example Input: "This is a statement, and so is this." Output: this - 2
  is – 2 a – 1 statement – 1 and – 1 so - 1

Solution is on GitHub

I am also using Netfx-Guard library from Nuget

Solutions contains two projects: main project with SentenceParser and StringSplitter classes and unit testing projects.

SentenceParser and StringSplitter classes are below.

using System.Collections.Generic;
using System.Linq;
using UBS.TextParsing.Interfaces;

namespace UBS.TextParsing
{
    public class SentenceParser
    {
        private IStringSplitter _splitter;

        public SentenceParser(IStringSplitter splitter)
        {
            _splitter = splitter;
        }

        public IDictionary<string, int> Parse(string sentence)
        {
            Guard.NotNullOrEmpty(() => sentence, sentence);

            var words = _splitter.SplitIntoWords(sentence);

            var wordsCounts = from word in words
                group word by word.ToLower()
                into g
                select new {Word = g.Key, Count = g.Count()};

            return wordsCounts.ToDictionary(wc => wc.Word, wc => wc.Count);
        }
    }
}

Here is StringSplitter class which splits sentence into words.

using System;
using System.Collections.Generic;
using System.Text;
using UBS.TextParsing.Interfaces;

namespace UBS.TextParsing
{
    public class StringSplitter : IStringSplitter
    {
        public IEnumerable<string> SplitIntoWords(string sentence)
        {
            Guard.NotNull(() => sentence, sentence);

            var stringList = new List<string>();

            var currentWordSb = new StringBuilder();

            foreach (var chr in sentence)
            {
                if (Char.IsPunctuation(chr) || Char.IsSeparator(chr) || Char.IsWhiteSpace(chr))
                {
                    AddToList(currentWordSb, stringList);
                    currentWordSb.Clear();
                }
                else
                {
                    currentWordSb.Append(chr);
                }
            }

            AddToList(currentWordSb, stringList);

            return stringList;
        }

        private void AddToList(StringBuilder stringBuilder, ICollection<string> collection)
        {
            var word = stringBuilder.ToString();
            if(!string.IsNullOrEmpty(word))
                collection.Add(word);
        }
    }
}


texts: Checking if an array of dates are within a date range

texts:
I created a dates_in_range() function which checks if all of the dates passed to it ($dates array) are within $start_date and $end_date. If they aren't, it'll return false.
The code works fine, but I'm wondering if there's a way to refactor it better using something like array_filter? Or does this look fine?
function dates_in_range( $start_date, $end_date, $dates = array() ) {

    foreach ( $dates as $date ) {
        if ( ! ( ( (strtotime( $date ) >= strtotime( $start_date ) ) && ( strtotime( $date ) <= strtotime( $end_date ) ) ) ) ) {
            return false;
        }
    }

    return true;
}

$dates = array(
    '2021-11-19 00:00:00',
    '2020-11-20 00:00:00',
);

$start_date = '2021-10-01 00:00:00';
$end_date   = '2021-12-31 00:00:00';

// Returns true
if ( dates_in_range( $start_date, $end_date, $dates ) ) {
    echo "In range.";
} else {
    echo "Not in range.";
}


texts:
I am quite new to Ruby, coming from a JavaScript background. I wrote this simple Ruby script that finds whether two strings are anagrams or not.

To run it: ruby ruby_anagrams.rb 'script1' 'script2'

I am looking for comments and a code review on my script. Can I do anything better? Is this good Rubyism?

# removing whitespace (in case of multi-word anagrams), converting to lowercase and getting
# array representations:
string_1_arr = ARGV[0].gsub(/\s+/, "").downcase.split("")
string_2_arr = ARGV[1].gsub(/\s+/, "").downcase.split("")

if string_1_arr.size != string_2_arr.size
  puts "Not anagrams"
  exit
end

string_1_arr.each do |c|
  print c, " ",string_2_arr, "\n" # debug statement, but left here 'cuz the output looks cool

  # just delete would delete all occurences of the same letter, e.g. "food" would become
  # "fd" if we delete 'o', which is obviously wrong. Have to use delete_at(index) instead
  if i = string_2_arr.index(c)
    string_2_arr.delete_at i
  else
    puts "Not anagrams"
    exit
  end
end

puts "Anagrams!"


texts: Inserting command output into multiline string

texts:
I'm writing a bash script to that picks up a user password from an environment variable, hashes this, and inserts the results into a postgres database.

What I have works and looks fairly readable to me but I'm no expert on bash.  Are there better conventions I could be following for what I'm doing?

#!/bin/bash
HASHED=$(echo -n $GUAC_PASSWORD | sha256sum | head -c 64)

PGPASSWORD=$POSTGRES_PASSWORD psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
    entity_id,
    decode('${HASHED}', 'hex'),
    null,
    CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF

Edit: I thought up a way to do it without sed feels neater to me.

Update: Thanks @OhMyGoodness and @TobySpeight!  The conversations about passwords being in the clear got me twitchy enough to use docker secrets.  So now I have the passwords in a file, not environment variables. PGPASSWORD isn't actually needed as

  The PostgreSQL image sets up trust authentication locally so you may notice a password is not required when connecting from localhost

The finalized script looks like this now:

#!/bin/bash
hashed=$(tr -d '\n' < /run/secrets/guac_password | sha256sum | tr -dc a-f0-9)

psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
    entity_id,
    decode('${hashed}', 'hex'),
    null,
    CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF


texts:
There is a varint encoding, which I call LEP64 (Little Endian Prefix Max 64-bit).

Basically, the first byte of the encoded value tells us, how many bytes follow (needed bytes encoded in unary coding, then the value encoded simply in binary):

First Byte   following   can encode values
               bytes        between
  xxxxxxx1       -       [ 0; 2^ 7-1 ]  // xxxx contains low bits of value
  xxxxxx10   [1  byte]   [ 0; 2^14-1 ]
  xxxxx100   [2 bytes]   [ 0; 2^21-1 ]
      .
      .
  x1000000   [6 bytes]   [ 0; 2^49-1 ]
  10000000   [7 bytes]   [ 0; 2^56-1 ]
  00000000   [8 bytes]   [ 0; 2^64-1 ]

There is a need for a function, which can write a LEP64 into a buffer. Here's my current version (for gcc, can be ported to any current compiler easily):

int enc(unsigned char *result, unsigned long long int value) {
    int nUsedBits = 64 - __builtin_clzll(value|1);
    int nBytesNeeded = (nUsedBits+6)/7;
    if (nBytesNeeded<9) {
        value = ((value<<1)|1)<<(nBytesNeeded-1);
    } else {
        *result++ = 0;
        nBytesNeeded = 9;
    }
    __builtin_memcpy(result, &value, 8);
    return nBytesNeeded;
}

The question is, is it possible to improve on this function? Algorithm-wise (I don't really like the division by 7, even though it is optimized to a mul), or implementation-wise? Some clever tricks to speed up this routine? Or maybe shorten its asm code, while retaining its speed?

Note: I interested only in x86_64 platform, and it's fine that this routine always writes at least 8 bytes.

Note2: The distribution of values -- as almost always -- skewed towards small numbers (small numbers are more probable than 8-byte numbers)


texts: Finding the longest palindromic substring

texts:
I have the following code that works correctly. I am wondering if there is a simpler way to go about implementing my solution and/or if there is anything that looks non-standard in my code. If anyone wants to offer criticism I'm all ears.

### Question 2 main function and helper functions.
"""Given a string a, find the longest palindromic substring contained in a.
Your function definition should look like question2(a), and return a string."""
# Gives substrings of s in decending order.
def substrings(s):

    # Declare local variable for the length of s.
    l = len(s)

    # Here I chose range over xrange for python version compatibility.
    for end in range(l, 0, -1):
        for i in range(l-end+1):
            yield s[i: i+end]

# Define palindrome.
def palindrome(s):
    return s == s[::-1]

# Main function.
def Question2(a):
    for l in substrings(a):
        if palindrome(l):
            return l

# Simple test case.
print Question2("stresseddesserts")
# stresseddesserts


texts:
I would like to get feedback on this, which are just simple Response/Request classes.

I tried to keep it simple, so I made two interfaces and two classes:

RequestInterface.php
Request.php
ResponseInterface.php
Response.php

The use Foo\Storage\ArrayHandler as access; is just a class to access and set arrays, so I wouldn't have to use functions like array_key_exists all over the place to check for keys, set, and unset arrays.

RequestInterface.php

namespace Foo\Http;
interface RequestInterface
{
    public function get($key, $default = null);
    public function post($key, $default = null);
    public function server($key, $default = null);
    public function getMethod();
}

ResponseInterface.php

namespace Foo\Http;
interface ResponseInterface
{
    public function setStatusCode($statusCode);
    public function addHeader($name, $value);
    public function setContentType($contentType);
    public function redirect($url);
}

Request.php

namespace Foo\Http;
use Foo\Storage\ArrayHandler as access;
class Request implements RequestInterface
{

    protected $get;
    protected $post;
    protected $files;
    protected $server;
    protected $cookies;

  public function __construct(
         access $get,
         access $post,
         access $files,
         access $server,
         access $cookies
    ) {
        $this->get = $get;
        $this->post = $post;
        $this->files = $files;
        $this->server = $server;
        $this->cookies = $cookies;
    }

    public function get($key, $defaultValue = null){
      return $this->get->get($key, $defaultValue);
    }

    public function post($key, $defaultValue = null){
        return $this->post->get($key, $defaultValue);
    }

    public function server($key, $defaultValue = null){
        return $this->server->get($key, $defaultValue);
    }

    public function getMethod(){
        return $this->server->get('REQUEST_METHOD');
    }
}

Response.php

namespace Foo\Http;

class Response implements ResponseInterface
{

    private $statusCode = 'HTTP/1.1 200 OK';
    private $headers = [];

    public function addHeader($name, $value){
        $this->headers[$name][] = $value;
    }

    public function setHeader($name, $value){
        $this->headers[$name] = [
            (string) $value,
        ];
    }

    public function redirect($url){
        $this->setHeader('Location', $url);
    }

}


texts: Generate a find command with pruned directories based on a config file

texts:
The idea is to perform indexing of filetrees while excluding certain directories. I want to give the user a simple conf file instead of having to edit the script itself.
This is what I came up with:
conf.file:
cache
home/files

program:
#!/usr/bin/env bash

function get_opts {
        while read opt
        do
        echo "-path /data/data/com.termux/$opt -prune -o \\" >> fn_temp
        done < conf.file
}

function build_search_fn {
        touch fn_temp
        echo "function do_search {" > fn_temp
        echo "find /data/data/com.termux \\" >> fn_temp
        get_opts
        echo "-print" >> fn_temp
        echo "}" >> fn_temp
}

build_search_fn
source fn_temp
do_search >> output

It does what I want, but I have a strong feeling that it's not the 'proper' way of doing it. Besides the obvious lack of putting the base path into variables and some errorhandling I'm eager to learn about other approaches to do this.


texts: YouTube playlist steganography: hide secret messages inside YouTube playlists

texts:
I have created this repo on GitHub and I have shown how this software works through a video.

If you have time, please visit the repo and read the files. I'll post some relevant snippets below, but if you can quickly skim over the whole thing, that would be great.

I'm new to Python so I'm sure there are some things in the code below that may not be best code practice. If you spot anything off, please let me know.

file yousecret.py:

I don't see many people writing Tkinter .grid() calls in this fashion so I'm thinking there may be some more practical way to do this. Also, the outcome looks like something from 1995, so I also wish I could give it a modern look.

enc_userkeys_label.grid(row=0,column=0)
enc_userkeys.grid(row=0,column=1)
enc_userkeys_clear.grid(row=0,column=2)
enc_sourcetext_label.grid(row=1,column=0)
enc_sourcetext.grid(row=1,column=1)
enc_sourcetext_clear.grid(row=1,column=2)
enc_button.grid(row=2,column=1)

file ysdecode.py:

What follows below feels like C code, I believe there must be a shorter and faster way to write this function in Python.

def getsum(addrlist):
    alladdr = []
    sumlists = []
    for addr in addrlist:
        final = []
        temp = []
        switch = True
        for url in addr:
            if switch:
                temp.append(url[0])
                switch = False
            elif not switch:
                temp.append(url[-1])
                switch = True
                final.append(tuple(temp))
                temp = []
        alladdr.append(tuple(final))
    for addr in alladdr:
        temp = []
        for pair in addr:
            for bitpair in BITARRAY:
                if pair == bitpair:
                    temp.append(BITARRAY.index(bitpair))
                    continue
        sumlists.append(tuple(temp))
    return sumlists

The addrlist parameter is a list of tuples, like this:

addrlist = [ ('wDzN2SQ8dCs', 'NLQf-Q8zlG0'), ('EhFPMTWSsso', 'wf1laG5Jp34') ]

BITARRAY is a global variable that is also a list of tuples.

for i in '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz':
    for j in '048AEIMQUYcgkosw':
        BITARRAY.append((i,j))


texts: How to automatically insert HTML to a form and obtain the inputs?

texts:
For a form I got the markup below, it belongs to an input category and as there can be more than one insertion at it I includded an Añadir button (Add).

I give id="posgrado1" to first div and using Java Script I increment the id's to posgrado2, posgrado3, ... posgrado#n

    Estudios de Posgrado

        <select class="form-control inputPosgradoTipo">
            <option>Especialidad</option>
            <option>Maestría</option>
            <option>Doctorado</option>
        </select>

        <input type="text" class="form-control inputPosgradoTitulo" placeholder="Título">

        <input type="text" class="form-control inputPosgradoCedula" placeholder="Cédula">

        <input type="button" class="form-control btnAñadirPosgrado" value="Añadir">

Each html within a class got a class identifying the type of input.

So far this is how I add more input instances:

numPosgrados = 1

function agregarPosgrado () {

    var markupPosgrado="";
    markupPosgrado += "
";
    markupPosgrado += "                        ";
    markupPosgrado += "                        <\/label>";
    markupPosgrado += "";
    markupPosgrado += "
";
    markupPosgrado += "                            <select class=\"form-control inputPosgradoTipo\">";
    markupPosgrado += "                                <option>Especialidad<\/option>";
    markupPosgrado += "                                <option>Maestría<\/option>";
    markupPosgrado += "                                <option>Doctorado<\/option>";
    markupPosgrado += "                            <\/select>                ";
    markupPosgrado += "                        <\/div>";
    markupPosgrado += "";
    markupPosgrado += "
";
    markupPosgrado += "                            <input type=\"text\" class=\"form-control inputPosgradoTitulo\" placeholder=\"Título\">                        ";
    markupPosgrado += "                        <\/div>";
    markupPosgrado += "";
    markupPosgrado += "
";
    markupPosgrado += "                            <input type=\"text\" class=\"form-control inputPosgradoCedula\" placeholder=\"Cédula\">";
    markupPosgrado += "                        <\/div>";
    markupPosgrado += "";
    markupPosgrado += "                    <\/div>";

    $("#posgrado"+(numPosgrados-1)).after(markupPosgrado)
}

For getting the information I'd like to return a JSON, like:

function obtenerPosgrados () {

    return {EachInstance: {eachInputTypesForEach}}
}

This is an example fiddle.

What's a better implementation of this?  Can I take more advance of jQuery or any other JavaScript library?


texts: Functions taking iterables: peaks, compress, and skipper

texts:
I am just testing out a few small functions for learning purposes:

def peaks(iterable):
    # returns a list of int for those values in the iterable that are bigger
    # than the value preceding and following them.
    itr = iter(iterable)
    peak =[]
    curr = next(itr)
    last = next(itr)
    try:
        while True:
            first = curr
            curr = last
            last = next(itr)
            if curr > first and curr > last:
                peak.append(curr)
    except:
        pass
    return peak

def compress(v_iterable,b_iterable):
    #takes two iterables as parameters: it produces every value from the first iterable that
    # has its equivalent position in the second iterable representing what Python would consider
    # a True value. Terminate the iteration when either iterable terminates
    mega_it = dict(zip(v_iterable, b_iterable))
    for nxt in sorted(mega_it):
        if mega_it[nxt]:
            yield nxt

def skipper(iterable,n=0):
    #akes one iterable and one int (whose default value is 0) as parameters: it produces values from
    # the iterable, starting at the first one, skipping the number of values specified by the int
    #(skipping 0 means producing every value from the iterable)
    itr = iter(iterable)
    yield next(itr)
    while True:
        for i in range(n):
            skipped = next(itr)
        yield next(itr)

I feel like my codes are lengthy for the kind of work it does. Is there a way to make my functions cleaner or smaller?


texts:
I wrote code to creating structure with files on hard disc. I used here Composite pattern. Please make code review to this.

using System.Collections.Generic;
using System.Text;

namespace Common.FileSystem
{
    public abstract class FileSystemItem
    {
        public FileSystemItem(string rootPath, string name)
        {
            if (rootPath == null)
                throw new ArgumentNullException("rootPath");

            if (name == null)
                throw new ArgumentNullException("name");

            RootPath = rootPath;
            Name = name;
        }

        public string Name { get; private set; }

        public string RootPath { get; private set; }

        public string Path
        {
            get { return System.IO.Path.Combine(RootPath, Name); }
        }

        public abstract void Create();

        public abstract Directory AddDirectory(string name);

        public abstract void AddFile(string name, IFileBuilder fileBuilder);

        public abstract void Remove(FileSystemItem item);

        public abstract string Print();

        private string _rootPath;
    }

    public class Directory : FileSystemItem
    {
        public Directory(string rootPath, string name) : base(rootPath, name) { }

        public override void Create()
        {
            System.IO.Directory.CreateDirectory(Path);
            foreach (var item in _items)
                item.Create();
        }

        public override Directory AddDirectory(string name)
        {
            var directory = new Directory(Path, name);
            _items.Add(directory);

            return directory;
        }

        public override void AddFile(string name, IFileBuilder fileBuilder)
        {
            var file = new File(Path, name, fileBuilder);
            _items.Add(file);
        }

        public override void Remove(FileSystemItem item)
        {
            _items.Remove(item);
        }

        public override string Print()
        {
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine(Path);
            foreach (var item in _items)
                stringBuilder.Append(item.Print());

            return stringBuilder.ToString();
        }

        private List<FileSystemItem> _items = new List<FileSystemItem>();
    }

    public class File : FileSystemItem
    {
        public File(string rootPath, string name, IFileBuilder fileBuilder) : base(rootPath, name)
        {
            if (fileBuilder == null)
                throw new ArgumentNullException("fileBuilder");

            _fileBuilder = fileBuilder;
        }

        public override void Create()
        {
            var fileContent = _fileBuilder.Build();

            System.IO.File.WriteAllText(Path, fileContent);
        }

        public override Directory AddDirectory(string name)
        {
            throw new InvalidOperationException("Operation is unavailable for this object");
        }

        public override void AddFile(string name, IFileBuilder fileBuilder)
        {
            throw new InvalidOperationException("Operation is unavailable for this object");
        }

        public override void Remove(FileSystemItem item)
        {
            throw new InvalidOperationException("Operation is unavailable for this object");
        }

        public override string Print()
        {
            return Path + Environment.NewLine;
        }

        private IFileBuilder _fileBuilder;
    }

    public interface IFileBuilder
    {
        string Build();
    }
}


texts:
Validate that the following bracket pairs [], {}, () open and close successfully in a candidate String.

Valid String Example: "[{()}]" should be evaluated as true because no "outer" open bracket is closed before an "inner" open bracket.

Invalid String Example: "[f{o]o}"

I would appreciate feedback on my implementation:

Is there a case I'm missing?
Is there a cleaner way to validate bracket pairs?
Are there any particular performance concerns I'm ignoring?
I have hard-coded my bracket values. What if I want to add, say, ten more bracket values...is there a cleaner way to implement the open/close relationship? Use a Map, perhaps?

public boolean validateBracketPairs(final String string) {
        final Stack<Character> bracketStack = new Stack<>();
        for (final char character : string.toCharArray()) {
            if ('{' == character || '[' == character || '(' == character) {
                bracketStack.push(character);
            }

            else if (!bracketStack.empty() &&
                    (('{' == bracketStack.peek() && '}' == character)
                        || ('[' == bracketStack.peek() && ']' == character)
                        || ('(' == bracketStack.peek() && ')' == character)))  {
                bracketStack.pop();
            }

            else if ('}' == character || ']' == character || ')' == character) {
                return false;
            }
        }

        return bracketStack.empty();
    }


texts:
I'm using PHP Readability to extract contents from news to get title, description and body like so.

<?php
    include "vendor/autoload.php";
    use andreskrey\Readability\Readability;
    use andreskrey\Readability\Configuration;

    $readability = new Readability(new Configuration());

    $client_config = [
        'timeout' => 10.0,
        'cookie' => true,
        'verify' => false,
    ];
    $client = new \GuzzleHttp\Client($client_config);
    $response = $client->request('GET', "https://www.nytimes.com/2018/11/22/world/middleeast/saudi-arabia-nuclear.html")->getBody();

    $html = $response->getContents();

    try {
        $readability->parse($html);
        echo "
" . $readability->getTitle() . "

";
        echo "" . $readability->getExcerpt() . "

";
        echo $readability->getContent() . "

";
    } catch (ParseException $e) {
        echo sprintf('Error processing text: %s', $e->getMessage());
    }

Everything work just fine, but I was wondering, does it has any other better "PHP Reader view" library out there? Or someone can point me a better way to study?

Any idea?


texts: A WinForm application that filters users

texts:
I built a small WinForm application that has checkboxes to filters users with different properties.

Each user has a name, color and number.
With the program you can filter by color or name the users that you will see:

Inside the application there is a static list of users:

// SomeUser(<name>, <color>, <number>);
SomeUser("user1", "red", "one");
SomeUser("user2", "blue", "one");
SomeUser("user3", "red", "two");
SomeUser("user4", "blue", "two");
SomeUser("user4", "yellow", "two");
SomeUser("user4", "blue", "three");

The application works as expected.
If you are not specified any filters, it will show you all.
There is OR inside each groupbox.
There is AND bettwen the groupboxes.
Meaning:
If you checked red and blue, it will search for users that have red color OR blue color.
If you checked red, blue and one, it will search for users that have red OR blue color AND one number.
I hope you understand from these two small examples.

This is the filter function:

void countFinding(CheckBox checkbox, string userField, ref int found)
{
    if (checkbox.Checked)
    {
        if (userField == checkbox.Text)
        {
            found++;
        }
    }
}

private bool isFilter(SomeUser user)
{
    bool isAllowed = false;

    int shouldBeFound = 0;
    int found = 0;
    if(this.checkBoxRed.Checked || this.checkBoxBlue.Checked)
    {
        shouldBeFound++;
        countFinding(this.checkBoxRed, user.color, ref found);
        countFinding(this.checkBoxBlue, user.color, ref found);
    }

    if (this.checkBoxOne.Checked || this.checkBoxTwo.Checked)
    {
        shouldBeFound++;
        countFinding(this.checkBoxOne, user.number, ref found);
        countFinding(this.checkBoxTwo, user.number, ref found);
    }

    if (shouldBeFound == found)
    {
        isAllowed = true;
    }

    return isAllowed;
}

Inside the isFilter() function I am checking twice the same checkbox.
In the first if I am checking:
if(this.checkBoxRed.Checked || this.checkBoxBlue.Checked)
and if one of them is true it goes (twice) to an inner function (countFinding())that also checks if the checkbox is checked.

So, it appear them I am checking at least one checkbox twice to see if it checked.

Is it possible to make it better?  what do you think?


texts:
I want to  split an integer of type unsigned long long to its digits.
Any comments and suggestions are always welcome.
#include <iostream>
#include <string>

#include <vector>

using namespace std;

vector<unsigned short> IntegerDigits(unsigned long long input)
{
    vector<unsigned short> output;
    const unsigned short n = log10(ULLONG_MAX);
    unsigned long long divisor = pow(10, n);
    bool leadingZero = true;

    for (int i = 0; i < n + 1; i++)
    {
        unsigned short digit = input / divisor % 10;
        if (!leadingZero || digit != 0)
        {
            output.push_back(digit);
            leadingZero = false;
        }
        divisor /= 10;
    }

    return output;
}

void main()
{
    vector<unsigned short> output = IntegerDigits(ULLONG_MAX);

    cout << ULLONG_MAX << ": [";
    for (auto y : output)
        cout << y << ", ";
    cout << "\b\b]";

    cout << ""<<endl;

}


texts: Chunking a list into separate lists of 5, and then iterating through each

texts:
I'm writing a service that receives a list of Latitude/Longitude objects, prepares them for transaction, and then calls a web service to write them to the organization's Mainframe.  According to the existing application that I'm replacing, the Mainframe can only accept "chunks" of up to 5 Lat/Long values at a time, however the user is able to enter as many as they want.

After getting the list of Lat/Longs from the UI, if it is more than 5 pairs I break it into separate lists of 5, and then call another developers code to prepare them to transmit.  This preparation includes setting up the transaction with the Case File's relevant information (FileType/FileNumber, Username, password, ect), calling SetCode() or SetMisc() on each individual Latitude and Longitude string, and then calling the web service. I do this for every chunk of 5 Lat/Longs, and if the last chunk is less than 5, I only call SetCode() or SetMisc() for however many there are left. There may also be fewer than 5 records to begin with, and often times will only be 1 Latitude/Longitude.

While my code works, I feel like it could be improved.  Specifically, I don't care for all of the if checks, but I haven't been able to find another way to work it.  I also feel like this is inefficient code, however this specific code only runs once per each case, so efficiency isn't absolutely vital.

public void PostLatLong(string fileType, string fileNumber, List<LatLongDEntry>     latLongList,  DateTime? transactionDate = null, string commentText1 = null, string commentText2 = null, string username = null, string password = null)
{
    string transactionCode = "LATLONGS";
    List<List<LatLongEntry>> splitList = new List<List<LatLongEntry>>();

    try
    {
        while (latLongList.Any())
        {
            splitList.Add(latLongList.Take(5).ToList());
            latLongList = latLongList.Skip(5).ToList();
        }

        foreach (List<LatLongEntry> list in splitList)
        {
            SetupCaseFileUpdateTransaction(transactionCode, fileType, fileNumber, commentText1, commentText2, transactionDate, username, password);
            SetCode(1, list[0].Latitude);
            SetCode(2, list[0].Longitude);
            if (list.Count > 1)
            {
                SetCode(4, list[1].Latitude);
                SetCode(5, list[1].Longitude);
            }
            if (list.Count > 2)
            {
                SetCode(6, list[2].Latitude);
                SetCode(7, list[2].Longitude);
            }
            if (list.Count > 3)
            {
                SetMisc(1, list[3].Latitude);
                SetMisc(2, list[3].Longitude);
            }
            if (list.Count > 4)
            {
                SetMisc(3, list[4].Latitude);
                SetMisc(4, list[4].Longitude);
            }
            CallWebService();
        }
    }
    catch (Exception e)
    {
        LogTransactionException(transactionCode, e);
        throw;
    }
}