texts: Groovy Map>> data manipulation method optimization

texts:
Am trying to update the Map<String,List<Map<String,String>>> invoices with the invoiceErrors as below

InvoiceError // is an entity with below attributes
{ String errorMessage,
  String invoiceNumber
}
ErrorMessage                                          invoiceNumber
-------------                                       -------------------
File Error : The file is in an unsupported format   INV-Error_Test1
Line : 1 Invoice does not foot Reported             INV-Error_Test1
Line : 2 MATH ERROR                                 INV-Error_Test1
Line : 3 MATH ERROR                                 INV-Error_Test2
Line : 3 Invoice does not foot Reported             INV-Error_Test2

Am trying to achieve below map
    If the error message doesnt have a line number it need to be appended at the top level as invLineItems.put('error',['INV-Error_Test1' :File Error : The file is in an unsupported format])
   Otherwise errormessage should be appended to the  matching INVOICE and linenumber as below

invLineItems = [INV-Error_Test1:[[LINE:1, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:22, error : `Line : 1 Invoice does not foot Reported`],
                                [LINE:2, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:24, error : `Line : 2 MATH ERROR`],
                INV-Error_Test2:[[LINE:3, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:26, , error : `Line : 3 MATH ERROR | Line : 3 Invoice does not foot Reported`],
                                [LINE:4, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:28,]],
                error : [[INV-Error_Test1:`File Error : The file is in an unsupported format`]]

I wrote the below method to achieve the above

def regex = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+";
for (e in invLineItems ){
  def errors =  lipErrors.findAll{it.invoiceNumber==e.key} // finding the error messages with the invoice number
  errors.each{  // fetching the line numbre from error message and finding the matching record the invoice number and line number in invLineItems
     int lineNumber
     if (it.errorMessage.matches(regex)) {
            Pattern p = Pattern.compile("\\d+");
            Matcher m = p.matcher(it.errorMessage);
            if (m.find()) {
                 lineNumber = Integer.parseInt(m.group());
            }
          println "lineNumber = "+lineNumber
        }

    if(e.value['LINE_ITEM_NUMBER'].find{it==lineNumber.toString()}) {
      def data = lipErrors.findAll{it.invoiceNumber==e.key && it.errorMessage.matches("^Line\\s+"+lineNumber+"?\\:\\s+"+lineNumber+"?.+")}
      e.getValue().each{it.put("error", data.errorMessage.join("|"))}

     }

  }
}

The code doesnt look like Groovy and using traditional java code mostly, am wondering whether the code can be simplified with Groovy approach


texts:
The exercise was to take a file such as this:

You say yes
I say no
You say stop
And I say go go go
CHORUS:
Oh no
You say Goodbye
And I say hello
Hello hello
I don't know why
You say Goodbye
I say hello
#repeat 9 12
Why
#repeat 11 13
I say high
You say low
You say why
And I say I don't know
#repeat 5 19

And parse the repeats so they actually repeat the lines. Nested repeats have to work and I had to use my own stack class.

main.cpp

#include "Stack.h"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

void parseLines(const std::vector<std::string> text, const int begin, const int end);
void parseRepeat(const std::string repeatLine, int &begin, int &end);

int main() {
    int fileLines = 0;

    std::string in;
    std::string fileName = "lyrics";
    std::ifstream inFile(fileName.c_str());
    std::vector<std::string> text;

    while(!inFile.eof()) {
        getline(inFile, in);
        text.push_back(in);
        fileLines++;
    }

    parseLines(text, 0, fileLines);
}

void parseLines(const std::vector<std::string> text, const int begin, const int end) {
    Stack<int> lyricStack;

    int fromLine = begin;
    int toLine = end;

    while(fromLine <= toLine && (unsigned int)fromLine < text.size()) {
        if(text.at(fromLine).substr(0, 7) == "#repeat") {
            lyricStack.push(fromLine);
            lyricStack.push(toLine);

            parseRepeat(text.at(fromLine), fromLine, toLine);
        } else {
            std::cout << text.at(fromLine) << std::endl;
            fromLine++;
        }

    }

    while(!lyricStack.isEmpty()) {
        toLine = lyricStack.pop();
        fromLine = lyricStack.pop();

        fromLine++;

        parseLines(text, fromLine, toLine);
    }
}

void parseRepeat(const std::string repeatLine, int &begin, int &end) {
    std::string numbers = repeatLine.substr(repeatLine.find(" ") + 1);
    begin = atoi((numbers.substr(0, numbers.find(" "))).c_str()) - 1;
    end = atoi((numbers.substr(numbers.find(" "))).c_str()) - 1;
}

Stack.h

#ifndef STACK_H_
#define STACK_H_

#include <string>

template <class A>
struct NODE {
    A data;
    NODE* next;
};

template <class B>
class Stack {
private:
    NODE<B>* head;

public:
    Stack();
    virtual ~Stack();

    void push(const B item);
    B pop();
    bool isEmpty();
};

#endif /* STACK_H_ */

Stack.cpp

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

template <class B>
Stack<B>::Stack() {
    head = NULL;
}

template <class B>
Stack<B>::~Stack() {
    NODE<B>* current = head;
    NODE<B>* previous;

    while(current) {
        previous = current;
        current = current->next;
        delete previous;
    }
}

template <class B>
void Stack<B>::push(const B item) {
    NODE<B>* newNode = new NODE<B>;
    newNode->data = item;

    if(!head) {
        newNode->next = NULL;
        head = newNode;
    } else {
        newNode->next = head;
        head = newNode;
    }
}

template <class B>
B Stack<B>::pop() {
    NODE<B>* next = head->next;

    B data = head->data;

    delete head;

    head = next;

    return data;
}

template <class B>
bool Stack<B>::isEmpty() {
    if(!head) {
        return true;
    }

    return false;
}


texts: Checking a Model's function's return value and setting values to a View member

texts:
I have a WinForms project that uses the Passive View MVP pattern. In the Presenter of one of my Views I have a function that gets questions and from its Model. But I want to make sure these collections are not empty so that I can inform the user when they are. Right now my code seems very ugly and I wonder if anyone has any tips to make it shorter/better. Thank you.

public void InitializeInterview(object sender, EventArgs e)
    {
        List<List<string>> questionList = new List<List<string>>();
        List<List<string>> maturityAnswerList = new List<List<string>>();
        List<List<string>> complianceAnswerList = new List<List<string>>();

        questionList = _model.GetQuestions();
        maturityAnswerList = _model.GetMaturityAnswers();
        complianceAnswerList = _model.GetComplianceAnswers();

        if (questionList != null && questionList.Any())
        {
            _view.Questions = questionList;
        }
        else
        {
            _view.Message("No questions have been found, please add a new question standard");
            _view.CloseView();
        }
        if (maturityAnswerList != null && maturityAnswerList.Any())
        {
            _view.MaturityAnswers = maturityAnswerList;
        }
        else
        {
            _view.Message("No maturity answers have been found, please add a new maturity standard");
            _view.CloseView();
        }
        if (complianceAnswerList != null && complianceAnswerList.Any())
        {
            _view.ComplianceAnswers = complianceAnswerList;
        }
        else
        {
            _view.Message("No compliance answers have been found, please add a new compliance standard");
            _view.CloseView();
        }

    }


texts: File-exclusion based on an array of prefixes

texts:
I am trying to remove files based on an array of prefixes, from files present in sourceDirectory. I am using prefixFileFilter to get the list of files with the prefixes. After that I am removing these from the original list.

Is there any better approach?

package sriram;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.filefilter.PrefixFileFilter;

public class FileFilterExample {
public static void main(String[] args) {
excludeFiles();
}

private static List<String> excludeFiles() {
String[] filesToBeExcluded = { "sri", "agnew" };
File sourceDirectory = new File(
        "C:\\Users\\sriram\\workspace1\\sample\\src");
String[] fileNames = sourceDirectory.list(new PrefixFileFilter(
        filesToBeExcluded));
List<String> listOfFiles = Arrays.asList(fileNames);
List<String> totalFiles = Arrays.asList(sourceDirectory.list());
totalFiles.removeAll(listOfFiles);
return totalFiles;
}
}


texts: Calculating the connectance of a matrix iteratively

texts:
I have a performance issue in R. I have a function that iterates over a dataframe for different levels of "site" and "method". The function samples 1:1000 interactions (rows), converts these to matrices and calculates a value of connectance for each matrix. This is repeated n times. The function runs exactly as I want it, returning a dataframe with connectance values for 1 to 1000 interactions when repeated a small number of times. The problem is when I increase the number of repetitions (say to 100) the function runs progressively slower.

df <- read.table(text = "bird_sp plant_sp value site method
                    1  species_a  plant_a     1    a      m
                    2  species_a  plant_a     1    a      m
                    3  species_b  plant_b     1    a      m
                    4  species_b  plant_b     1    a      m
                    5  species_c  plant_c     1    a      m
                    6  species_a  plant_a     1    b      m
                    7  species_a  plant_a     1    b      m
                    8  species_b  plant_b     1    b      m
                    9  species_b  plant_b     1    b      m
                    10 species_c  plant_c     1    b      m
                    11 species_a  plant_a     1    a      f
                    12 species_a  plant_a     1    a      f
                    13 species_b  plant_b     1    a      f
                    14 species_b  plant_b     1    a      f
                    15 species_c  plant_c     1    a      f
                    16 species_a  plant_a     1    b      f
                    17 species_a  plant_a     1    b      f
                    18 species_b  plant_b     1    b      f
                    19 species_b  plant_b     1    b      f
                    20 species_c  plant_c     1    b      f", header = TRUE)

xDegrees <-function(df, size, numRep){

  #Loading required library
  require(bipartite)

  #Creating vector of unique combinations
  df <- within(df, {SiteMethod <- paste(site, method, sep = ":")})

  #Creating empty dataframe
  connectMatrix <- as.data.frame(matrix(rep(0,4), ncol = 4))
  colnames(connectMatrix) <- c("Site","Method","Size","connectance")

  #Beginning of matrix
  k <- 1

  #Beginning subsetting loop
  for(i in 1:length(unique(df$SiteMethod))){

  #subsetting dataset
  dfSub <- subset(df, SiteMethod == unique(df$SiteMethod)[i])

  #Storing site for matrix
  site <- as.character(dfSub[1,]$site)

  #Storing method for matrix
  method <- as.character(dfSub[1,]$method)

  for(l in 1:numRep){
    #Beginning calculation loop
    for(j in 1:length(size)){

    #show progress
    print(paste("S:M", i,j , "completed", sep = " "))

    #The size being calculated
    subSize <- size[j]

    #generate random samples and convert to matrices
    rows <- sample(1:nrow(dfSub), subSize, replace=T)
    intlist <- dfSub[rows,]
    mat <- with(intlist, tapply(value, list(plant_sp, bird_sp), sum))
    mat[is.na(mat)] <- 0

    #network level function to calculate connectance
    con <- networklevel(mat,  index = c("connectance"))

    #Stitch matrix together
    connectMatrix[k,] <- c(site, method, subSize, con)

    #Update row
    k <- k + 1
      }
    }
  }

#Return complete matrix
return(connectMatrix)

}

#run the function. 1:1000 interactions, 100 reps
stuff <- xDegrees(df, size = 1:1000, numRep = 100)

Any ideas on how to speed this up?


texts:
I have an action on four buttons. I need to make a down (checked) button if it's pressed and other buttons up (unchecked). My button is TToolButton and the property Style is set to tbsCheck.

Could you please suggest improvements?

LButtonName := (Sender as TAction).ActionComponent.Name;
   if LButtonName.Equals('btnVorigeWeek') then
      begin
        LSelectionType := 2;
        btnHuidigeWeek.Down := False;
        btnVorigeWeek.Down := True;
        btnHuidigeMaand.Down := False;
        btnVorigeMaand.Down := False;
      end
      else if LButtonName.Equals('btnHuidigeMaand') then
      begin
        LSelectionType := 3;
        btnHuidigeWeek.Down := False;
        btnVorigeWeek.Down := False;
        btnHuidigeMaand.Down := True;
        btnVorigeMaand.Down := False;
      end
      else if LButtonName.Equals('btnVorigeMaand') then
      begin
        LSelectionType := 4;
        btnHuidigeWeek.Down := False;
        btnVorigeWeek.Down := False;
        btnHuidigeMaand.Down := False;
        btnVorigeMaand.Down := True;
      end
      else
      begin
        LSelectionType := 1;
        btnHuidigeWeek.Down := True;
        btnVorigeWeek.Down := False;
        btnHuidigeMaand.Down := False;
        btnVorigeMaand.Down := False;
      end;


texts: React virtualized list dynamic width/height

texts:
I'm using react-window to virtualize a list. My list is supposed to fill in the container's completely and the container's width and height are 30vh and 100vh. Since the dimensions are dynamic and react-window requires me to provide constant dimensions, I'm hooking into the onresize event and updating the state of the component to pass the dimensions to the FixedSizeList component.

I was wondering if there was a better way to do this.

import React, { useEffect, useRef, useState } from 'react'
import { FixedSizeList } from 'react-window'
import InfiniteLoader from 'react-window-infinite-loader'

const MyList = () => {
  const { items, hasOlder, loadOlder } = mobxStore
  const divRef = useRef<HTMLDivElement>(null)
  const [height, setHeight] = useState(divRef.current?.clientHeight || 800)
  const [width, setWidth] = useState(divRef.current?.clientWidth || 400)
  useEffect(() => {
    const handler = () => {
      const h = divRef.current.clientHeight
      const w = divRef.current.clientWidth
      if (height !== h) setHeight(h)
      if (width !== w) setWidth(w)
    }
    window.addEventListener('resize', handler)
    return () => window.removeEventListener('resize', handler)
  }, [])
  const itemCount = items.length + (hasOlder ? 1 : 0)
  return (

      <InfiniteLoader
        isItemLoaded={index => index < items.length}
        itemCount={itemCount}
        loadMoreItems={loadOlder}
      >
        {({ onItemsRendered, ref }) => (
          <FixedSizeList
            onItemsRendered={onItemsRendered}
            ref={ref}
            itemCount={itemCount}
            itemSize={60}
            height={divRef.current?.clientHeight || height}
            width={divRef.current?.clientWidth || width}
            overscanCount={10}
          >
            {({ index, style }) => {
              const item = items[index]
              if (!item) return
Loading...

              return
{renderItem(item)}

            }}
          </FixedSizeList>
        )}
      </InfiniteLoader>

  )
}

export default MyList

EDIT: Found out the library author recommends using react-virtualized-auto-sizer instead


texts: Extracting key and array value from javascript object?

texts:
My data looks like this:

const sleepStages = [
  {deep: Array(40)},
  {light: Array(40)},
  {rem: Array(40)},
  {awake: Array(40)},
]

I'm using the key and values separately and am using TypeScript.

sleepStages.flatMap((sleepStage) => {
  const stageName = Object.keys(sleepStage)[0];
  const stageValues = Object.values(sleepStage)[0];
  console.log(stageName, stageValues);
});

Does this approach make sense? Whenever I type [0] it smells.


texts: Manager for image and JSON assets of a game

texts:
I would like to know what you think of this assets manager for a game. If it can be optimized or simplified? It allows you to download sprites, tiles, json files, and other images.

const images = {};
images.tiles = {};

exports.images = images;
/**
* Download an image and store it in the cache
* @param {string} url - Address of the image
* @param {string} name - Name of the image
* @param {function} onImageLoaded -Execute this function when all images are loaded
*/

const loadImage = (url, name, onImageLoaded) => {

    if (images[name]) return onImageLoaded(images[name]);

    const image = new Image();

    image.onload = () => {
        if (image.complete) {
            images[name] = image;
            return onImageLoaded(image);
        }
    };

    image.src = url;
};

/*
* Download all images
* @param {object} images -
* @param {function} onImagesLoaded -
*/

const loadImages = (images, onImagesLoaded) => {
    var imagesLoaded = 0;

    const onImageLoaded = () => {
        imageLoaded++;

        if (images.length != imagesLoaded) return ;
        onImagesLoaded();
    }

    for (const image of images)
        loadImage(image.url, image.name, onImageLoaded)
};

/*
* Download all tiles
* @param {object} tiles - Tiles to download
* @param {function} onTilesLoaded - Function that is executed when the tiles are downloaded
*/

const downloadTiles = (tiles, onTilesLoaded) => {

    const images = tiles.map(tile => {
        const image = {};

        image.name = 'tile_' + tile.id;
        image.url =  'assets/tiles/' + image.name + '.png';

        return image;
    });

    loadImages(images, onTilesLoaded);
};

exports.downloadTiles = downloadTiles;

/*
* Download all the images and store them in cache
* @param {object} sprites - Sprites to download
* @param {function} onSpritesLoaded - Function that is executed when the sprites are downloaded
*/

const downloadSprites = (sprites, onSpritesLoaded) => {
    const images = sprites.map(sprite => {
        const image = {};

        image.name = 'sprite_' + sprite.id;
        image.url = 'assets/sprites/' + image.name + '.png';

        return image;
    })

    loadImages(images, onSpritesLoaded);
}

const toJSON = response => response.json();

/*
* @param {string} url -
* @param {string} name -
*/

const loadJSON = (url, name) =>
    fetch(url, { method: 'GET' })
        .then(toJSON);

exports.loadJSON = loadJSON;

exports.loadImage = loadImage;
exports.loadImages = loadImages;

const getTileCoordinates = (image, index, width, height) => {
    var row = 0;
    var x = width * index, y;

    while(true){
        if (x < image.width) break ;
        x-=image.width;
        row++;
    };
    y = height * row;

    return {x, y};
};
exports.getTileCoordinates = getTileCoordinates;


texts: Identical jQuery autocomplete handlers for two form fields

texts:
I do need to use jquery autocomplete for two inputs. But I have use same processing script for these two elements.

At this stage I am doing it like this.

    $("#suburb").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: "includes/state_au_ajax.php",
            dataType: "json",
            method: "post",
            data: {
                term : request.term,
                state : $("#state").val()
            },
                        success: function( data ) {
                             response( $.map( data, function( item ) {
                                var code = item.split("|");
                                return {
                                    label: code[0],
                                    value: code[0],
                                    data : item
                                }
                            }));
                        }
        });
    },
    autoFocus: true,
    minLength: 2,
      select: function( event, ui ) {
            var output = ui.item.data.split("|");
            $('#zip_code').val(output[1]);
        },
    delay: 300
  });

    // --- Populate ZIP code according to the value of "Suburb"
    $("#p_suburb").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: "includes/state_au_ajax.php",
            dataType: "json",
            method: "post",
            data: {
                term : request.term,
                state : $("#p_state").val()
            },
                        success: function( data ) {
                             response( $.map( data, function( item ) {
                                var code = item.split("|");
                                return {
                                    label: code[0],
                                    value: code[0],
                                    data : item
                                }
                            }));
                        }
        });
    },
    autoFocus: true,
    minLength: 2,
      select: function( event, ui ) {
            var output = ui.item.data.split("|");
            $('#p_zip_code').val(output[1]);
        },
    delay: 300
  });

My question is, Can I write this without any code duplication?


texts:
I have been working on a project for several days. It is a command line program for viewing files in hexadecimal. It is usually very fast, but is there any way I could make it more efficient?

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

int main(int argc, char *argv[]){
    if(argc == 2){
        FILE *in = fopen(argv[1], "rb");
        if(in == NULL){
            printf("Could not open %s\n", argv[1]);
        }else{
            int i = 0, j, br, ln[8];
            char l[16];
            while((br = fread(&l, 1, 16, in)) > 0){
                printf("%08x ", i);
                i += br;
                for(j = 0; j < br; j++){
                    if(l[j] > 0){
                        printf("%02x ", l[j]);
                    }else{
                        printf("?? ");
                    }
                }
                for(j = 0; j < 16 - br; j++){
                    printf("   ");
                }
                for(j = 0; j < br; j++){
                    if(l[j] > 31 && l[j] < 127){
                        printf("%c", l[j]);
                    }else{
                        printf(".");
                    }
                }
                printf("\n");
            }
            fclose(in);
        }
    }else{
        printf("Please use the syntax 'hex [file]'\n");
    }
    return 0;
}


texts:
There is backend which connects with IdentityServer using WsFederation. The backend is .NET Core project where there is a derived class from AuthenticationHandler.

The issue is when the time of user's token is expired, the user should be signed out. I've implemented this in the following way:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    var ticket = await EnsureCookieTicket();
    if (ticket == null)
        return AuthenticateResult.Fail("No ticket.");

    //...

    return AuthenticateResult.Success(new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme));
}

private Task<AuthenticationTicket> EnsureCookieTicket()
{
    var cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName);
    if (String.IsNullOrEmpty(cookie))
        return null;

    var ticket = Options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
    if (ticket == null)
        return null;

    var currentUtc = Options.SystemClock.UtcNow;
    var issuedUtc = ticket.Properties.IssuedUtc;
    var expiresUtc = ticket.Properties.ExpiresUtc;

    if (expiresUtc != null && expiresUtc.Value < currentUtc)
    {
        //...

        Context.Items.Add("IsExpired", true);
        return null;
    }
}

protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{
    if (Context.Items.ContainsKey("IsExpired")
        && Context.Items["IsExpired"].Equals(true))
    {
        // 1 case
        if (!Request.Path.HasValue ||
            !Request.Path.Value.Equals("/index.html", StringComparison.OrdinalIgnoreCase))
        {
            Context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            var content = Context.Response;

            using (var responseWriter = new StreamWriter(content.Body, Encoding.UTF8))
            {
                responseWriter.Write("The context has expired and can no longer be used");
            }
        }
        // 2 case
        else
        {
            var signoutContext = new SignOutContext(Options.AuthenticationScheme, context.Properties);
            await SignOutAsync(signoutContext);
        }

        return true;
    }

    // generate return url

    // work with singin, if it is signin message
    // or work with cleanup signout, if it is cleanup signout context
    // or await Options.Events.RedirectToLogin(redirectContext);
}

There are two cases this code serves (// 1 case and // 2 case):

When the user works with the site, suddenly the time is ended and then the backend returns 403. JavaScript on the client machine handles this error and calls Signout as if the user clicks the button Signout himself.
Another case is when the user closes the site tab, the time of the user's token is expired, then the user opens the site again and the signout flow happens.

It works, but I count it as the workaround and not so elegant. What do you think?


texts:
Any better ways to implement 'inverseIndices'? Please give me feedback regarding good coding conventions.

fun main(arg: Array<String>) {
    //− 19 + 7 x − 4 x 2 + 6 x 3
    val coefficients = arrayListOf<Int>(-19, 7, -4, 6)
    val x = 3
    var result: Int = 0
    for (i in coefficients.inverseIndices) {
        result = (result*x) + coefficients[i]
    }
    println(result)
}

val ArrayList<Int>.inverseIndices: IntProgression
    get() = (size -1).downTo(0)


texts:
I have just begun to learn the C language and wanted to start off small with a temperature conversion calculator. The program works, and I'm looking for feedback on do's and don'ts as I am sure there are at least a few errors in technique that can be improved. (I just realized Fahrenheit is spelled incorrectly).

/*Calculates user provided temperature in Farenheight or Celsius depending on option chosen.*/

#include "stdafx.h" //don't actually know what this is for however will not compile without it.
#include <stdio.h>
#include <stdBool.h>
#include <conio.h>

/*Calculator options*/
#define option_1 1
#define option_2 2
#define option_3 3
#define option_4 4

void welcome();
void calculator();
void get_input(_Bool*, int*, float*);
void display_result(int, float);
float F_to_C(float);
float C_to_F(float);

int main(void)
{
    welcome();
    calculator();
    _getch();
}

void welcome() /*Welcome message + instruction*/
{
    printf("Welcome to the Temperaure Conversion Calculator\n\n");
    printf("Please select an option:\n\n");
    printf("Options:\t1)F to C\t2)C to F\t3)OFF\n\n");
}

void calculator() /*Conversion Calclator*/
{
    int option = 0;
    float input_temp = 0.0f;
    _Bool calc_off = 0;

    while (!calc_off)

    {
        get_input(&calc_off, &option, &input_temp);

        if (option == option_1) /*F to C*/
        {
            display_result(option_1, input_temp);
        }
        else if (option == option_2) /*C to F*/
        {
            display_result(option_2, input_temp);
        }
    }

}

void get_input(_Bool *calc_off, int *option, float *input_temp) /*Retrieve user input*/
{
    int trash = 0;
    int data_check;
    printf("Select option: "); scanf_s("%d", option); /*Obtains option*/
    scanf_s("%c", &trash); /*obtains newline character that will cause infinite loop*/

    while (*option != 1 && *option != 2 && *option != 3) /*incorrect option selection*/
    {
        display_result(option_4, option_4);
        scanf_s("%d", option);
        scanf_s("%c", &trash); /*Collects garbage newline character (Prevents infinite loop)*/

    }

    if (*option == option_3) /*Calculator off*/
    {
        *calc_off = 1;
        display_result(option_3, option_3);
        return;
    }

    printf("Temperature: "); scanf_s("%f", input_temp); /*Obtains temperature*/

    return;
}

void display_result(int option, float input_temp) /*Display results*/
{
    if (option == option_1)
        printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));

    else if (option == option_2)
        printf("Celsius to Farenheight of %.1f F is: %.1f F\n", input_temp, C_to_F(input_temp));

    else if (option == option_3)
        printf("Calculator OFF\n");

    else if (option == option_4)
        printf("Invalid option choice, please try again...\nOption: ");
}

float F_to_C(float input_temp) /*Convert Farenheight to Celsius*/
{
    return (5.0 / 9.0)*(input_temp - 32);
}

float C_to_F(float input_temp) /*Convert Celsius to Farenheight*/
{
    return (9.0 / 5.0)*(input_temp)+32;
}


texts:
I have been reading about ZF2 EventManager for some time now and I wonder what you'd think about this approach.

class Model_Member extends App_Model_Model
{
    protected $_data = array(
        'ID' => null,
        'UserName' => null,
        'Password' => null,
        'EmailAddress' => null,
        'CreatedOn' => null,
        'Status' => 0,
        'PasswordResetHash' => null,
        'Role' => 'member'
    );
    const EVENT_SAVE = 'save';
    const EVENT_POSTSAVE = 'post.save';
    public function init()
    {
        $this->events()->attach(self::EVENT_SAVE, array('Service_Member', 'save'));
    }
    public function save()
    {
        $id = $this->events()->trigger(self::EVENT_SAVE, $this)->last();
        $this->ID = $id;
        $this->events()->trigger(self::EVENT_POSTSAVE, $this);
    }
}

And of course there is Service_Member

public function save($event)
{
    // Get the member from the event
    $member = $event->getTarget();
    // If there is no id, save, otherwise update
    if (!$member->ID) {
        $id = $this->doSave($member);
        $event->setParam('id', $id);
        return $id;
    } else {
        return $this->doUpdate($member);
    }
}
public function doSave(Model_Member $member)
{
    // Check if username is taken
    if ($this->checkIfExists('UserName', $member->UserName)) {
        throw new App_Exception_UserNameExists('This username is already taken.');
    }

    // Check if email address already registered
    if ($this->checkIfExists('EmailAddress', $member->EmailAddress)) {
        throw new App_Exception_EmailAddressExists('This email is already registered.');
    }

    // Set default values
    $member->CreatedOn = date('Y-m-d H:i:s');

    // Encrypt password
    $member->Password = sha1($member->Password);

    // Get the data and save. Return the member with new ID
    $data = $member->_toArray();
    unset($data['ID']);
    $this->getWriteDb()->insert('members', $data);
    $id = $this->getWriteDb()->lastInsertId();
    return $id;
}

Do you think this is an acceptable approach?


texts: Searching a dictionary of words using difflib

texts:
I am trying to write a spellchecker and I wanted to use difflib to implement it. Basically I have a list of technical terms that I added to the standard Unix dictionary (/usr/share/dict/words) that I'm storing in a file I call dictionaryFile.py.

I have another script just called stringSim.py where I import the dictionary and test sample strings against it:

import os, sys
import difflib
import time
from dictionaryFile import wordList

inputString = "dictiunary"
print "Search query: "+inputString
startTime = time.time()

inputStringSplit = inputString.split()
for term in inputStringSplit:
    termL = term.lower()
    print "Search term: "+term
    closeMatches = difflib.get_close_matches(termL,wordList)
    if closeMatches[0] == termL:
        print "Perfect Match"
    else:
        print "Possible Matches"
        print "\n".join(closeMatches)

print time.time() - startTime, "seconds"

It returns the following:

$ python stringSim.py
Search query: dictiunary
Search term: dictiunary
Possible Matches
dictionary
dictionary's
discretionary
0.492614984512 seconds

I'm wondering if there are better strategies I could be using for looking up similar matches (assuming a word is misspelled). This is for a web application so I am trying to optimize this part of the code to be a little snappier. Is there a better way I could structure the wordList variable (right now it is just a list of words)?


texts: 'Tag' packages and make them discoverable

texts:
We have another team who is going to expose class packages for use to scan and pickup details from. If they should add some new packages or rename old ones I don't want to have to recode a thing. I am trying to get some input on the best way to accomplish that

For the sake of maintainability we only want the code for processing and scanning this dependency done once. When the version from app1 bumps, app2 can bump and if there are new files or even new or renamed packages to scan then app2 simply discovers this and no one has to do any work. Can the packages be published to a properties file I can wire in?

app1 wants to "expose"

com.company.model.abc
com.company.model.def

but in a newer version a new package is added and the previous 2 are moved:

com.company.org1.model.abc
com.company.org2.mode.def
com.company.model.ghi

Ideally, app2 should only have to do this integration once.

I had imagined an alias that gets set in a filtered maven property file. Something like

model.packages =     com.company.org1.model.abc, com.company.org2.mode.def, com.company.model.ghi

Such that, in app2 code we can simply do:

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
public class EntityService {

    @Value("${model.packages}")
    private String[] packages;

    @Cacheable
    public Set<Class<?>> getEntityClasses() {
        Reflections reflections = new Reflections(packages, new SubTypesScanner(false));

        Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class);
        return subTypesOf;
    }
}

I was thinking that basically having a

  package-info.java

in each to-be-exposed package might work.

Thoughts?


texts: Is it a good practice to have static final field DUMMY in interfaces used as listeners?

texts:
Often I have to write classes implementing listener interfaces with empty methods bodies.

For example:

MyOnClickListener .java

public interface MyOnClickListener {
    void onClick();
}

and

MyDummyOnClickListener .java

public class MyDummyOnClickListener implements MyOnClickListener {
    public void onClick() {
        // skip
    }
}

Maybe it would be better to have a static final field DUMMY in each such an interface?

MyOnClickListener .java

public interface MyOnClickListener {
    void onClick();

    public static final MyOnClickListener DUMMY = new MyOnClickListener() {
        public void onClick() {
            // skip
        }
    }
}

So I need only 1 .java class, and each time when I change interface I don't have to find and open another .java class with "dummy" implementation.

What do you think? What are the disadvantages of such a solution?


texts: Resource that use two different services and query with pagination when resolved

texts:
I'm learning Angular and I don't like my current approach. The current controller uses first Geolocation service and when getLocation() is resolved, then the Pagination service is invoked with the location param. Is it any better solution to provide one service that query server with location? Can I integrate the Pagination service to call it through the Post factory with a resolved location?

angular.module('app').controller('MainCtrl',['$scope','Post','Pagination','Geolocation'
  ($scope, Post, Pagination, Geolocation) ->
    $scope.posts = []
    Geolocation.getLocation().then (location) ->
      Pagination.paginate $scope, Post, 10, (postsRes) ->
        $scope.posts.push posts for posts in postsRes
      , params: {location: location}
])

angular.module('app').factory 'Post', ($resource) ->
  $resource '/posts/:id.json', { id: '@id' }

angular.module('app').service "Geolocation", ['$q', '$window', ($q, $window) ->
  @getLocation = ->
    deferred = $q.defer()
    return deferred.resolve @loc if @loc
    if $window.navigator and $window.navigator.geolocation
      $window.navigator.geolocation.getCurrentPosition (position) ->
        @loc = position.coords
        deferred.resolve position.coords

    deferred.promise
]
angular.module('app').service 'Pagination', ->
  @paginate = ($scope, @resource, @maxElemPerPage=10, @onNewPage, @query={}) ->
    @page = 1
    @canLoadNextPage = true
    $scope.loadPage = (promise) =>
      return promise.resolve() unless @canLoadNextPage
      @load promise

    @load = (promise) =>
      @canLoadNextPage = false
      q = angular.extend @query, page: @page
      @resource.query q, (resources) =>
        @canLoadNextPage = true if resources.length is @maxElemPerPage
        @page++
        @onNewPage resources if @onNewPage
        promise.resolve() if promise

    @load()
  @


texts:
I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.

def findsum(a, n):
  ''' Find whether a consecutive array slice sums up to n '''
  for i in range(len(a)):
    j = i + 1
    while j <= len(a):
      if sum(a[i:j]) == n:
        return True
      j += 1
  return False


texts:
The Needleman–Wunsch algorithm is an algorithm used in bioinformatics to align protein or nucleotide sequences.

Here is an implementation in Scala:

package vu.co.kaiyin.akkconcurrent

import vu.co.kaiyin.akkconcurrent.NeedlemanWunsch.{ResultEntry, Score, SimilarityFunc}

/**
  * Created by IDEA on 2/26/16.
  */
case class NeedlemanWunsch(private var s1: String, private var s2: String, gapPenalty: Int, sm: SimilarityFunc) {
  val borderDirection = (-9, -9)
  val verticalDirection = (-1, 0)
  val horizontalDirection = (0, -1)
  val matchDirection = (-1, -1)
  s1 = " " + s1
  s2 = " " + s2
  private val alignMat = new Array[Array[ResultEntry]](s1.length)
  private var alignResult: (String, String) = ("", "")

  // init alignment matrix
  def initAlignmentMatrix = {
    for (i <- (0 until s1.length)) {
      alignMat(i) = new Array[ResultEntry](s2.length)
      if (i == 0) {
        for (j <- 0 until s2.length) {
          alignMat(i)(j) = (j * gapPenalty, borderDirection)
        }
      } else {
        alignMat(i)(0) = (i * gapPenalty, borderDirection)
      }
    }
  }

  def fillAlignmentMatrix: Unit = {
    def getScore(i: Int, j: Int): Score = {
      if (alignMat(i)(j) != null) {
        alignMat(i)(j)._1
      } else {
        val tryMatch = getScore(i - 1, j - 1) + sm(s1(i), s2(j))
        val horizontalGap = getScore(i, j - 1) + gapPenalty
        val verticalGap = getScore(i - 1, j) + gapPenalty
        val m = Set(tryMatch, horizontalGap, verticalGap).max
        if (m == tryMatch) {
          alignMat(i)(j) = (m, matchDirection)
        } else if (m == horizontalGap) {
          alignMat(i)(j) = (m, horizontalDirection)
        } else {
          alignMat(i)(j) = (m, verticalDirection)
        }
        m
      }
    }
    for (i <- 1 until s1.length) {
      for (j <- 1 until s2.length) {
        val _ = getScore(i, j)
      }
    }
  }

  def align: NeedlemanWunsch = {
    initAlignmentMatrix
    fillAlignmentMatrix
    val alignBuffer1 = new StringBuffer()
    val alignBuffer2 = new StringBuffer()
    var rowNumber = s1.length - 1
    var colNumber = s2.length - 1
    var node = alignMat(rowNumber)(colNumber)
    while (node._2 != borderDirection) {
      val direction = node._2
      if(direction == matchDirection) {
        alignBuffer1.insert(0, s1(rowNumber))
        alignBuffer2.insert(0, s2(colNumber))
        rowNumber -= 1
        colNumber -= 1
      } else if(direction == verticalDirection) {
        alignBuffer1.insert(0, s1(rowNumber))
        alignBuffer2.insert(0, " ")
        rowNumber -= 1
      } else {
        alignBuffer1.insert(0, " ")
        alignBuffer2.insert(0, s2(colNumber))
        colNumber -= 1
      }
      node = alignMat(rowNumber)(colNumber)
    }
    alignResult = (alignBuffer1.toString, alignBuffer2.toString)
    this
  }

  override def toString = {
    s"\n${alignResult._1}\n${alignResult._2}\n"
  }
}

object NeedlemanWunsch {
  type Direction = (Int, Int)
  type Score = Int
  type ResultEntry = (Score, Direction)
  type SimilarityFunc = (Char, Char) => Int
}

object TestNeedlemanWunsch extends App {
  def sm(c1: Char, c2: Char) = if (c1 == c2) 1 else -1
  println(NeedlemanWunsch("GATTACA", "GCATGCU", -1, sm).align.toString)
}

Any suggestions for improvement are welcome.


texts: Print distinct car names with count in descending order

texts:
After reading this question, it jumped to me that many said that the solution to the problem is over-engineered / overkill.

Here I solve the same problem in Python in a more compact way. I think that this solution is compact enough. If you still think that this is overkill for the problem, please tell me. Any kind of other code review is welcome too.

"""
Item list analyzer

Given a file with an element in each line,
for each item this programme will print the number of times
it appears in the text file. It will also sort the items
from the most frequent to the least frequent.

Example:
    example.txt:
        spam \n spam \n eggs \n spam \n foo \n baz \n eggs
        # "\n" should be actual newlines not the "\n" string

    Ouput:
        ('spam', 3)
        ('eggs', 2)
        ('baz', 1)
        ('foo', 1)

"""
import operator

FILENAME = "cars.txt"

def return_frequncy_dict(lst):
    """
    Given a list as input returns a
    dict containg the items as keys and
    the number of occurencies of each item as
    values.

    >>> return_frequncy_dict(["a","b","c","b","b","a"])
    {'a': 2, 'c': 1, 'b': 3}
    """
    return {i:lst.count(i) for i in lst}

def sort_by_value(dict_):
    """
    As the frequency is the value, to sort by frequency we
    must sort by value. Standard sorting goes from the smallest
    to the biggest, we want the reverse of it.

    Credit for this function goes to
    http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
    """
    return reversed(sorted(dict_.items(), key=operator.itemgetter(1)))

if __name__ == "__main__":
    with open(FILENAME,"r") as f:
        data = f.read()

    item_list = data.splitlines()
    item_list = [item.lower() for item in item_list]
    item_list = [item.strip() for item in item_list]

    for j in sort_by_value(return_frequncy_dict(item_list)):
        print(j)


texts:
I am using an Xbox controller to send data to my computer, and am using the SendInput method to handle keys. I was wondering if there was any other, better way to do this.

INPUT Input = { 26 };
Input.type = INPUT_KEYBOARD;
Input.ki.dwFlags = VK_UP;
SendInput(1, &Input, sizeof(INPUT));
std::cout << "Up";


texts: combinations of an integer list with product limit

texts:
In python the itertools module is a good tool to generate combinations of elements. In this case I want to generate all combinations (without repetition) having a subsets of specified length but also with a product limit. For example, given a list of integer numbers I want all subsets of length 4 which product is bellow a given numerical limit, like bellow:
import functools, operator
LST = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 ]
prod = lambda A : functools.reduce(operator.mul, A )

def combinations_with_limit( LST, length,lim ) :
''':Description: LST - array of integers,
    length = number of elements in each subset ,
    lim = product limit of each subset '''

    H = list(range(length))         # H - represents the index array
    B = [ LST[ii] for ii in H ]     # B - the main array with elements
    while H[0] <= len(LST)-length  :
        for i in range( H[-1], len(LST)) :
            H = H[:-1] + [i]
            B = [ LST[ii] for ii in H ]
            if prod(B) > lim :      ###  LIMIT THE OUTCOME PART . It skips the rest of the iteration
                H[-1] = len(LST) - 1
            elif prod(B) <= lim :
                yield B
            if H[-1] == len(LST) - 1 :    # We reset the index array here
                j = len(H)-1
                while H[j] == len(LST)-length+j :
                    j -=1
                H[j] +=1
                for l in range(j+1, len(H)) :
                    H[l] = H[l-1] +1

for i in combinations_with_limit(LST, 4 , 1000 ) :
    print(i ,end='  ' )

The output will look as follows:
[2, 3, 5, 7]  [2, 3, 5, 11]  [2, 3, 5, 13]  [2, 3, 5, 17]  [2, 3, 5, 19]
[2, 3, 5, 23]  [2, 3, 5, 29]  [2, 3, 5, 31]  [2, 3, 7, 11]  [2, 3, 7, 13]
[2, 3, 7, 17]  [2, 3, 7, 19]  [2, 3, 7, 23]  [2, 5, 7, 11]  [2, 5, 7, 13]

And this is correct. All the products subsets are bellow the requested limit. However, I think that the above code is non-elegant and has some major loop inefficiency as I tested it for larger lists with > thousands of elements.
Do you have any ideas on how to improve it?


texts: Filtering from a file to show information

texts:
I want to get my code cleanner and more efficient. This code gets variables form a PHP file and filters it to show the selected user name, all available usergroups on a list box and the groups he is currently into in another.
<script>

    function saveGroup(type,id){
      $('#useridgr').attr('placeholder', '').val('');
      $("#usernamegr").attr('placeholder', 'Nome').val('');
      $('#list_box').html('');
      $('#list_box_ini').html('');

      if (type == 1){

      } else {
        loadatagroup(id);
      }

    }
    var loadatagroup = (uid) => {

      $.ajax({
        type: 'GET',
        url: 'usergrupo/' + uid,
        data: {'_token': $("input[name='_token']").val()},
        success: function(data){

          console.log("success");

          var o = data[0];

          $('#useridgr').attr('placeholder',o.id).val(o.id);
          $("#usernamegr").attr('placeholder',o.name).val(o.name);

          console.log('areaa');

          var size = Object.size(data);

          console.log(size);

          for (var i=0; i<size; i++){
            var o = data[i];
            $("#list_box").append("<option value='"+o.idgrupo+"'>"+o.nome+"</option>");
          }

        }

      })

    }

    Object.size = function(obj) {
      var size = 0, key;
      for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
      }
      return size;
    };

    </script>


texts: How do I remove nested if else conditions?

texts:
I'm playing around with the concept of functional programming.
I have flattened the nested if statements and made by code more verbose.
The refactored code looks overly complicated.
What could be a simpler approach?
Nested Ifs
public static int Main(string[] args)
{
    int computer = 1;
    string brand = "PC";

    if (computer < 2)
    {
        if (brand != "Apple")
        {
            // perform complex calculation 1
            Console.WriteLine("you don't own a Mac");
            return 0;
        }
        else
        {
            // perform complex calculation 2
            Console.WriteLine("you own less than 2 Macs");
            return 1;
        }
    }
    else
    {
        // perform complex calculation 3
        Console.WriteLine("you own two or pcs");
        return 2;
    }
}

Flattened Main
public static int Main(string[] args)
{
    int computer = 1;
    string brand = "PC";

    return CalculatedResult = DetermineComputer(computer, brand);
}

Extension Methods
public static class extensions
{
    public static int ComplexCalc1(this bool val)
    {
        Console.WriteLine("you don't own a Mac");
        return 0;
    }
    public static int ComplexCalc2(this bool val)
    {
        Console.WriteLine("you own less than 2 Macs");
        return 1;
    }
    public static int ComplexCalc3(this bool val)
    {
        Console.WriteLine("you own greater than two pcs");
        return 2;
    }
    public static int ComplexCalc4(this bool val)
    {
        Console.WriteLine("Condition not accounted for");
        return -1;
    }

    public static bool IsLessThanTwo(int computer) => computer < 2;

    public static bool IsApple(string brand) => brand == "Apple";

    public static (Func<bool, int> func, bool result) IsLessThanTwoAndNotApple(this int computer, string brand)
        => (ComplexCalc1, IsLessThanTwo(computer) && (IsApple(brand) == false));

    public static (Func<bool, int> func, bool result) IsLessThanTwoAndIsApple(this int computer, string brand)
        => (ComplexCalc2, IsLessThanTwo(computer) && IsApple(brand));

    public static (Func<bool, int> func, bool result) Unaccountedfor(this int computer, string brand)
        => (ComplexCalc4, true);

    public static (Func<bool, int> func, bool result) IsGreaterThanTwoAndIsNotApple(this int computer, string brand)
        => (ComplexCalc3, (IsLessThanTwo(computer) == false) && (IsApple(brand) == false));
}

Calculation
public static int DetermineComputer(int computer, string brand)
{
    var methodlist = new List<(Func<bool, int>, bool)>
    {
        computer.IsLessThanTwoAndNotApple(brand),
        computer.IsLessThanTwoAndIsApple(brand),
        computer.IsGreaterThanTwoAndIsNotApple(brand),
        computer.Unaccountedfor(brand)
    };

    var tupleResult = methodlist.Where(x => x.Item2 == true).Select(x =>
        new {
            functor = x.Item1,
            result = x.Item2
        }).First();

    return tupleResult.functor(tupleResult.result);
}

Unit Tests
[DataRow(3, "Apple", -1)]
[DataRow(2, "Apple", -1)]
[DataRow(1, "Apple", 1)]
[DataRow(0, "Apple", 1)]
[DataRow(3, "PC", 2)]
[DataRow(2, "PC", 2)]
[DataRow(1, "PC", 0)]
[DataRow(0, "PC", 0)]
[DataTestMethod]
public void NestedIfs_Demo(int first, string second, int expected)
{
    int computer = first;
    string brand = second;

    var CalculatedResult = DetermineComputer(computer, brand);

    Assert.AreEqual(expected, CalculatedResult);
}


texts: Select array element by its weight/probability

texts:
I coded a function that takes an array with numbers and randomly chooses one of these numbers (Returns the index of the chosen one).
The value of each number works as an weight which determines the probability to that number be chosen.

E.G.: A possible input for the function could be [1.5, 3.5, 2.0, 1.3] and the respective probabilities would be 18.07%, 42.16%, 24.09%, 15.66%. In other words, the probability to choose a number is proportional to that number.

The function:

function chooseIndex(weights){

    let weightSum = 0;
    weights.forEach(weight => {
        weightSum += weight;
    });

    let choice = Math.random()*weightSum; // [0 ~ weightSum[
    let retIndex;
    weights.some((weight, index) => {
        choice -= weight;
        if(choice < 0){
            retIndex = index;
            return true;
        }
    });
    return retIndex;
}

I don't know why, but I feel it could be better about performance.
Any suggestions will be very welcome ;D


texts:
I wrote this to make the "callback hell" more manageable on the part of the coder when using Socket IO, so that there wasn't really any callback hell to go with, just a simple await.

This should work with any socket implementation, so long as it has socket.on, socket.emit, and socket.removeListener.

function emit_and_wait(socket, emit, data, wait_key, max_wait = 1000, error_on_timeout = true) {
    return new Promise(function(resolve, reject) {
        let responded = false,
             callback,
             removed = false;
        if(!socket) {
            reject("Socket supplied is not valid.")
        } else if(socket.disconnected) {
            reject("Socket is disconnected");
        }
        let timeout = setTimeout(function() {
            if(!responded) {
                if(error_on_timeout) {
                    reject("Socket timeout");
                } else {
                    resolve(null);
                }
                responded = true;
                if(!removed) {
                    socket.removeListener(wait_key, callback);
                    removed = true;
                }
            }
        }, max_wait)
        callback = function(data) {
            if(!removed) {
                socket.removeListener(wait_key, callback);
            }
            if(!responded) {
                resolve(data);
                clearTimeout(timeout);
            }
        }
        socket.on(wait_key, callback);
        socket.emit(emit, data)
    })
}


texts:
I am trying to write a simple version of the unix tail utility in haskell to improve my understanding of monads. Here is what I have now. I am pretty sure that this is not quite "Haskell enough" yet. Can you please help me improve my code?

import System.Environment
import System.Exit
import Control.Monad

main = getArgs >>= (parse' (10, [])) >>= \ (n_lines, ss) ->
        putStr $ concatMap (tailFile n_lines) ss

tailFile :: Int -> (FilePath, String) -> String
tailFile n_lines (f, c) =
    "==> " ++ f ++ " <==\n" ++
    (unlines.reverse.(take n_lines).reverse.lines) c

parse' :: (Int, [(FilePath, String)])
            -> [String]
            -> IO (Int, [(FilePath, String)])
parse' _ ("-h":_) = putStrLn "usage: " >> exit
parse' _ ("-v":_) = putStrLn "version: 0.1" >> exit
parse' (_, ss) ("-n":num:f) = parse' (read num, ss) f
parse' (n, ss) (f:fs) = do
                            contents <- readFile f
                            parse' (n, ss ++ [(f,contents)]) fs
parse' (x, ss) [] = return (x, ss)

exit = exitWith ExitSuccess
die = exitWith (ExitFailure 1)


texts: Another DataGrid (ObservableCollection) Filtering Method

texts:
I have re-written my DataGrid filtering method to try to improve performance and I feel that although this is the fastest yet, there is still room for improvement on some of the slower machines my program runs on.

The DataGrid is bound to an ObservableCollection, as the user enters text into my searchBox each CompanyModel that matches the filter is added into a filter ListBox. The ListBox is limited to the first 25 CompanyModels so as to enhance performance. Here is the method that is called as the user types;

private void FilterCompanies()
{
    FilteredCompanies = new ObservableCollection<CompanyModel>();
    FilteredCompanies.Clear();

    string searchText = CleanseText(searchBox.Text.ToLower());

    foreach (CompanyModel company in AllCompanies)
    {
        if (!string.IsNullOrEmpty(searchText))
        {
            if (FilteredCompanies.Count <= 25)
            {
                if (CompanyMatchesFilters(company))
                {
                    if (CleanseText(company.Name.ToLower()).Contains(searchText) ||
                        CleanseText(company.Town.ToLower()).Contains(searchText) ||
                        CleanseText(company.Postcode.ToLower()).Contains(searchText))
                    {
                        FilteredCompanies.Add(company);
                    }
                }
            }
        }
    }

    if (FilteredCompanies.Count > 0)
    {
        companiesListBox.ItemsSource = FilteredCompanies;
        companiesListBox.Visibility = Visibility.Visible;
    }
    else
    {
        companiesListBox.ItemsSource = null;
        companiesListBox.Visibility = Visibility.Collapsed;
    }
}

From the code you can see there are two more methods involved in the filtering;

CompanyMatchesFilters

private bool CompanyMatchesFilters(CompanyModel company)
{
    foreach (FilterItem item in firstListBoxItems)
    {
        if (item.ID == 1 && company.CurrentStatus != 1)
        {
            return false;
        }
        if (item.ID == 2 && company.Subcontractor != 1)
        {
            return false;
        }
        if (item.ID == 3 && company.Supplier != 1)
        {
            return false;
        }
        if (item.ID == 4 && company.Planthire != 1)
        {
            return false;
        }
        if (item.ID == 5 && company.Architect != 1)
        {
            return false;
        }
        if (item.ID == 6 && company.QS != 1)
        {
            return false;
        }
        if (item.ID == 7 && company.ProjectManager != 1)
        {
            return false;
        }
        if (item.ID == 8 && company.StructEng != 1)
        {
            return false;
        }
        if (item.ID == 9 && company.ServiceEng != 1)
        {
            return false;
        }
    }
    return true;
}

CleanseText

private static Regex badChars = new Regex("[^A-Za-z0-9']");

private string CleanseText(string text)
{
    return badChars.Replace(text, "");
}

I would be very grateful if I could have some advice on;

A: How to improve my code in general
B(maybe more importantly): How    to further improve the performance
of my methods if at all possible


texts: Inefficient Python script eating up memory (I believe)

texts:
I created a simple Python script to log track listens in iTunes and it seems that it's pretty inefficient. I'm primarily a front-end developer, so this is clearly not my area of expertise. I know loops can cause problems in any language, so I assume that's the issue here.

If I run this script for a while (say, a couple of hours or more) the fan on my computer starts working overtime and won't stop until I kill the script.

Any idea what might be making this happen? Suggestions on how to optimize? Appreciate any help I can get.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx, sqlite3, datetime, threading
from appscript import *
it = app('iTunes')
from AppKit import *

# Create the DB
Tapedeck = sqlite3.connect('Tapedeck.db', check_same_thread = False)
TapedeckQuery = Tapedeck.cursor()
Tapedeck.execute('''CREATE TABLE IF NOT EXISTS plays (id INTEGER PRIMARY KEY, track_id TEXT, track TEXT, artist TEXT, album TEXT, genres TEXT, play_count INTEGER, rating INTEGER, skip_count INTEGER, year_released INTEGER, date_played DATE)''')
Tapedeck.commit()

def getSec(s):
    l = s.split(':')
    return int(l[0]) * 60 + int(l[1])

def addTrack(track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating):
    #print '        --\n        Position: {}\n      Length: {}'.format(it.player_position(),getSec(it.current_track.time()))
    TapedeckQuery.execute('''INSERT INTO plays (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating) VALUES (?,?,?,?,?,?,?,?,?,?)''',
    (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating))
    Tapedeck.commit()

loop_int = 1.0
last_track = '0'

def listen():

    global loop_int, last_track
    threading.Timer(loop_int, listen).start()
    if it.player_state() == k.playing:
        # check to see if track was restarted
        if it.player_position() < getSec(it.current_track.time())/2 and last_track == it.current_track.persistent_ID():
            self.last_track = '0'
        # has the track played beyond the halfway mark?
        if it.player_position() >= getSec(it.current_track.time())/2 and last_track != it.current_track.persistent_ID():
            today = datetime.datetime.today()
            now = '{}-{}-{} {}:{}:{}'.format(today.year, '%02d' % today.month, '%02d' % today.day, '%02d' % today.hour, '%02d' % today.minute, '%02d' % today.second)
            print '\nArtist:        {}\nTrack:      {}\nAlbum:      {}\nGenres:     {}\nDatetime:   {}'.format(it.current_track.artist().encode('ascii','ignore'), it.current_track.name().encode('ascii','ignore'), it.current_track.album().encode('ascii','ignore'), it.current_track.genre().encode('ascii','ignore'), now)
            last_track = it.current_track.persistent_ID()
            addTrack(it.current_track.persistent_ID(), it.current_track.name(), it.current_track.artist(), it.current_track.album(), it.current_track.genre(), it.current_track.played_count(), it.current_track.skipped_count(), it.current_track.year(), now, it.current_track.rating())

listen()


texts:
I've recently learnt about the Model-View-Presenter architectural pattern and I wanted to give it a go with a simple VBA project.

The aim is to retrieve a person's name from a UserForm.

The userform looks like this:

A user should select a team, which updates the name field > Select a name belonging to that team > Hit OK.

The control names are:

TeamSelect
NameSelect
OkButton
CloseButton

  I'm particularly interested in feedback on my implementation of MVP
  (or lack of!)

... So here is the code:

GetName Sub - Standard Module: Macros

Public Sub GetName()
    With New NamePresenter
        .Present
    End With
End Sub

Model - Class Module: NameModel

Private Type TNameView
    Team As String
    Name As String
End Type
Private this As TNameView

Public Property Get Team() As String
    Team = this.Team
End Property

Public Property Let Team(ByVal value As String)
    this.Team = value
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get IsValid() As Boolean
    IsValid = (this.Name <> vbNullString) And (this.Team <> vbNullString)
End Property

View - UserForm Module: NameView

Public Event UpdateNames(ByVal Team As String)

Private Type TNameView
    Model As NameModel
    Data As NameData
    IsCancelled As Boolean
End Type
Private this As TNameView

Public Property Set Model(ByVal Model As NameModel)
    Set this.Model = Model
End Property

Public Property Set Data(ByVal Data As NameData)
    Set this.Data = Data
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property

Private Sub TeamSelect_Change()
    this.Model.Team = TeamSelect.value
    RaiseEvent UpdateNames(TeamSelect.value)
End Sub

Private Sub NameSelect_Change()
    this.Model.Name = NameSelect.value
End Sub

Private Sub OkButton_Click()
    If this.Model.IsValid Then
        Me.Hide
    Else
        MsgBox "Something is missing!"
    End If
End Sub

Private Sub CloseButton_Click()
    this.IsCancelled = True
    Me.Hide
End Sub

Private Sub UserForm_Activate()
    PositionForm
    TeamSelect.List = this.Data.Teams
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Cancel = True
    CloseButton_Click
End Sub

Private Sub PositionForm()
    With Me
        .StartUpPosition = 0
        .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
        .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
    End With
End Sub

Presenter - Class Module: NamePresenter

Private WithEvents View As NameView

Private Model As NameModel
Private Data As NameData

Public Sub Present()
    Set View = New NameView
    Set Model = New NameModel
    Set Data = New NameData

    With View
        Set .Model = Model
        Set .Data = Data
        .Show vbModal
        If .IsCancelled Then Exit Sub
        MsgBox Model.Team & " / " & Model.Name
    End With
End Sub

Private Sub View_UpdateNames(ByVal Team As String)
    View.NameSelect.List = Data.Names(Team)
End Sub

Data - Class Module: NameData

Public Property Get Teams() As Variant
    Teams = Array("Team1", "Team2", "Team3")
End Property

Public Function Names(ByVal Team As String) As Variant
    Select Case Team
        Case "Team1"
            Names = Array("Name1", "Name2", "Name3")
        Case "Team2"
            Names = Array("Name4", "Name5", "Name6")
        Case "Team3"
            Names = Array("Name7", "Name8", "Name9")
    End Select
End Function

Note: I've ommitted Option Explicit only in this post to keep the code-section as short as possible


texts: Thread safety of this queue backed by ConcurrentHashMap

texts:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DedupingQueue<E> implements QueueWrapper<E> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DedupingQueue.class);

private final Map<E, Future<E>> itemsBeingWorkedOn = new ConcurrentHashMap<>();
private final AsyncWorker<E> asyncWorker;

public DedupingQueue(AsyncWorker<E> asyncWorker) {
    this.asyncWorker = asyncWorker;
}

@Override
public Future<E> submit(E e) {
    if (!itemsBeingWorkedOn.containsKey(e)) {
        itemsBeingWorkedOn.put(e, asyncWorker.executeWorkAsync(e, this));
    } else {
        LOGGER.debug("Rejected [{}] as it's already being worked on", e);
    }
    return itemsBeingWorkedOn.get(e);
}

@Override
public void complete(E e) {
    LOGGER.debug("Completed [{}]", e);
    itemsBeingWorkedOn.remove(e);
}

@Override
public void rejectAndRetry(E e) {
    itemsBeingWorkedOn.putIfAbsent(e, asyncWorker.executeWorkAsync(e, this));
}

}

I am having some difficulty reasoning the thread safeness of the above code.

I reckon complete and rejectAndretry are completely thread-safe as the map is thread safe. But what about submit? Also, how can I make it thread safe in the most efficient way?


texts:
from application import app, mail
from threading import Thread
from flask.ext.mail import Message

__all__ = ['send_email', 'send_bulk_email', 'create_email']

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_bulk_async_email(app, emails):
    with app.app_context():
        with mail.connect() as conn:
            for email in emails:
                conn.send(email)

def create_email(subject, recipients, text_body, html_body, sender=('My Company', 'info@mycompany.com.au')):
    email = Message(subject, sender=sender, recipients=recipients)
    email.body = text_body
    email.html = html_body

    return email

def send_email(email):
    thr = Thread(target=send_async_email, args=[app, email])
    thr.start()

def send_bulk_email(emails):
    thr = Thread(target=send_bulk_async_email, args=[app, emails])
    thr.start()

The first two functions are used internally as the threaded function calls. The create_email function is used to generate Message objects, which are then passed back to the send_email or send_bulk_email function dependent on whether there is a singular or multiple emails, respectively.

I currently think merging the singular and multiple send functions would be overkill, and remove some of the readability, however I am also open to feedback on that opinion.


texts: Matching a current user's "liked / followed" items with results from a search query

texts:
This is pretty ugly now.  My main objective is to perform a search query, which I do via mongoosastic / elastic search (the search paginates 12 items at time). Then, I want to match those results with a separate "Following" collection.

I find documents from the "Following" collection by the current user's Id, then I use the for loop to match those documents with the returned array of objects provided by the search query -- to mark them as already followed if they match.

I'm looking for a more elegant node solution, but my main concern is: what is the most scalable / performant way to do this?

If the Following collection greatly increases in size (as there is no limit to how many follows a user can have), would that result in atrocious response times for the current function?

exports.topSearch = function(req, res) {
      Product.search({
          query_string: {
            query: req.body.search
          }
        }, {
          from: req.body.fromNum,
          size: req.body.size,
          hydrate: req.body.hydrate
        },
        function(err, results) {
          if (err) console.log('ERR', err);
          if (results) {
            var data = results.hits.hits;

            Following.find({
              userId: req.user._id
            }, function(err, docs) {
              if (!err) {
                for (var i = 0; i < docs.length; i++) {
                  for (var j = 0; j < data.length; j++) {
                    if (data[j]._id == docs[i]['productId']) {
                      data[j]['followed'] = true;
                    }
                    console.log('data', data[j]);
                  }
                }
                res.send(data);
              }
            });

          } else {
            res.send({
              errmsg: 'results not defined'
            })
          }
        });
    };


texts: Ensuring HttpClient can be used safely as a singleton

texts:
There has been talk recently of how we should be handling the lifetime of the System.Net.Http.HttpClient.

This article http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html says that we should use it as a singleton, but we need to be careful about ensuring the connections are properly closed otherwise DNS changes won't be honoured.

I came up with the following message handler which can be injected in to an HttpClient to take care of setting the connection lease for each distinct scheme + host combination.

public class ServicePointManagingMessageHandler : HttpClientHandler
{
    private readonly ConcurrentDictionary<Uri, ServicePoint> _uriCache = new ConcurrentDictionary<Uri, ServicePoint>();
    private readonly int _oneMinuteInSeconds = (int)TimeSpan.FromMinutes(1).TotalSeconds;

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.RequestUri.IsAbsoluteUri)
        {
            var baseUri = new Uri($"{request.RequestUri.Scheme}://{request.RequestUri.Host}");

            _uriCache.AddOrUpdate(baseUri, uri =>
            {
                var sp = ServicePointManager.FindServicePoint(uri);
                sp.ConnectionLeaseTimeout = _oneMinuteInSeconds;

                return sp;
            }, (uri, point) => point);
        }

        return base.SendAsync(request, cancellationToken);
    }
}

Usage:

var client = new HttpClient(new ServicePointManagingMessageHandler());

I am wondering if the concept of intercepting the URI's as they come in to the HttpClient will allow the HttpClient to safely be used as a singleton without any of the issues listed in that article.

This gets around needing to know all hostnames that you might connect to at startup by intercepting calls - if people agree with this approach then it seems like it should become the accepted way to use the HttpClient for standard cases.


texts:
So I'm learning bits and pieces of python.  Here's some code that just doesn't seem pythonic, and I'd like to improve it.  I'm doing stochastic simulations with a Gillespie style approach, but if that doesn't mean anything to you, no worries.  I'm trying to avoid some iterations and replace them with something like a list comprehension.  The code will work, only I'm looking for a better way to do the same thing.

First I calculate a stopping time (maxTime).  Then I calculate the time of an event (and store it if it's less than maxTime).  Then the time of the next event (and store again).  I repeat until I finally get an event happening after maxTime.

import random
maxTime = random.expovariate(1)

L = []
eventTime = random.expovariate(10)

while eventTime<maxTime:
    L.append(eventTime)
    eventTime += random.expovariate(10)

Any cleaner way to write this code?


texts:
This code determines the maximum number of boxes (one size) that can fit into the back of a truck, checking all possible orientations to ensure maximum Bin Packing excitement.  This is (hopefully) the final version of this code. Please share any modifications that you would make to this code below.

<!DOCTYPE html>
<html>
<script>

// This program determines the maximum number of boxes that can fit into the back of a truck

// Declaring box size in centimetres, and converting it into metres
var boxHeight = prompt("What is the height of your box in centimetres?") / 100;
var boxWidth = prompt("What is the width of your box in centimetres?") / 100;
var boxLength = prompt("What is the length of your box in centimetres?") / 100;

// Declaring truck size in metres
var truckHeight = prompt("What is the height of your truck in metres?");
var truckWidth = prompt("What is the width of your truck in metres?");
var truckLength = prompt("What is the length of your truck in metres?");

// Declaring variables used in equation
var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthA = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthA = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightB = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthB = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthB = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var heightC = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthC = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthC = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightD = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthD = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthD = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightE = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthE = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthE = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightF = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthF = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthF = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var multiplesA = heightA * widthA * lengthA;
var multiplesB = heightB * widthB * lengthB;
var multiplesC = heightC * widthC * lengthC;
var multiplesD = heightD * widthD * lengthD;
var multiplesE = heightE * widthE * lengthE;
var multiplesF = heightF * widthF * lengthF;

var arrayA = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayB = [multiplesA, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayC = [multiplesB, multiplesA, multiplesD, multiplesE, multiplesF];
var arrayD = [multiplesB, multiplesC, multiplesA, multiplesE, multiplesF];
var arrayE = [multiplesB, multiplesC, multiplesD, multiplesA, multiplesF];
var arrayF = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesA];

// Calculating the most efficient orientation of the boxes
var boxCount;

if (multiplesA > arrayA)
{
boxCount = multiplesA;
}

else if (multiplesB > arrayB)
{
boxCount = multiplesB;
}

else if (multiplesC > arrayC)
{
boxCount = multiplesC;
}

else if (multiplesD > arrayD)
{
boxCount = multiplesD;
}

else if (multiplesE > arrayE)
{
boxCount = multiplesE;
}

else
{
boxCount = multiplesF;
}

// Output answer
alert("You can fit up to " + boxCount + (1 == boxCount ? " box" : " boxes") + " into the truck");

</script>
</html>


texts: Review of helper method that adds some divs

texts:
The following code ended up to be ugly and I can't find a way to make it better. Any comments will be very appreciated.

The expected HTML output is this (it is working, the output is just for guidance):

        <input type="file" name="name[]" id="name_">

Choose a file

  New attachment

Code:

module AttachmentsHelper
  def multiple_attachments(name)
    content_tag :div, :class => "attachments-face" do
      (content_tag :div, :class => "files" do
        file_field_tag("#{name}[]")
      end)+
      link_to("New attachment", "#", :data => { 'new-attachment' => true })
    end
  end
end


texts: Calling a Haskell MD5 hashing function from C, and returning the result back to C land

texts:
I'm starting to learn how to meld the worlds of C and Haskell. Looking for any feedback on this first function.

The function takes in a pointer to an array of unsigned chars and returns a pointer to 32 unsigned shorts. Or at least I would like it too :).

I am unsure about when the memory used to return the result is cleaned up. Is it possible that it will be garbage collected before I can use it on the C side?

Anyway here's the code.

{-# LANGUAGE ForeignFunctionInterface #-}
module JSFLPlugin where
import Foreign.C.Types (CInt(..))
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.Ptr (Ptr)
import Data.Serialize (encode)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import Data.Digest.Pure.MD5 (md5)
import Data.ByteString (unpack)
import Data.ByteString.Internal (toForeignPtr, fromForeignPtr)
import Data.ByteString.Lazy.Internal (chunk)
import Data.ByteString.Lazy (empty)
import Data.Word (Word8, Word16)
import Data.Text.Format (hex)
import Control.Applicative ((<$>))
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy (toStrict)
import Data.Text.Foreign (asForeignPtr)
import Data.Monoid ((<>), mempty)

-- | Hash pointer to array of unsigned chars
hash :: CInt -> Ptr Word8 -> IO (Ptr Word16)
hash count addr =  do
    -- cast to ForeignPtr
    fptr <- newForeignPtr_ addr
    -- Make a strict ByteString
    let sbyte    = fromForeignPtr fptr 0 (fromIntegral count)
        -- Make a lazy ByteString from the strict one
        lbyte    = chunk sbyte empty
        -- Hash with md5 and encode as a strict ByteString
        digest   = encode . md5 $ lbyte
        -- Convert the each digest byte to a UTF-16 encoded hexdecimal character
        hexBytes = toLazyText . foldr (\x y -> y <> hex x) mempty . unpack $ digest
    -- Convert to a strict Text and get the pointer to chars
    fmap (unsafeForeignPtrToPtr . fst) . asForeignPtr . toStrict $ hexBytes

foreign export ccall hash :: CInt -> Ptr Word8 -> IO (Ptr Word16)

EDIT: New version per Joey's suggestions (compiled but not tested).

{-# LANGUAGE ForeignFunctionInterface #-}
module JSFLPlugin where
import Foreign.C.Types (CInt(..))
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.Ptr (Ptr)
import qualified Data.Serialize as Serialize
import Data.Digest.Pure.MD5 (MD5Digest)
import Data.ByteString (ByteString)
import Data.ByteString.Internal (fromForeignPtr)
import Data.Word (Word8, Word16)
import Data.Text (Text)
import Data.Text.Foreign (unsafeCopyToPtr)
import qualified Data.ByteString.Base16 as Base16
import Data.Text.Encoding (decodeUtf8)
import Crypto.Classes (hash')

pureHash :: ByteString -> Text
pureHash = decodeUtf8 . Base16.encode . Serialize.encode . md5 where
    md5 s = hash' s :: MD5Digest

hash :: CInt -> Ptr Word8 -> Ptr Word16 -> IO ()
hash count input output =  do
    fptr <- newForeignPtr_ input
    let sbyte = fromForeignPtr fptr 0 $ fromIntegral count
    unsafeCopyToPtr (pureHash sbyte) output

foreign export ccall hash :: CInt -> Ptr Word8 -> Ptr Word16 -> IO ()


texts: A program which adds 2 integers in the range of 0 to 10^100

texts:
I wrote this program to help myself learn C. It is the result of a few days of hacking things together until it worked.

This program takes 2 integers as inputs in the range of 0 to 10100 and outputs the sum of the inputs.

The code used to generate the final result doesn't really feel that elegant so it would be great to see what could have been done better.

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

int main()
{
    char input[2][100];

    // Reset arrays to 0
    for (int i = 0; i < 100; i++)
    {
        input[0][i] = 0;
        input[1][i] = 0;
    }

    int length[2];

    scanf ("%s%n", &input[0][0], &length[0]);
    scanf (" "); // Catch the newline
    scanf ("%s%n", &input[1][0], &length[1]);

    // Format user input
    for (int i = 0; i < 2; i++)
    {
        // Convert chars to ints
        for (int b = 0; b < length[i]; b++)
        {
            input[i][b] = input[i][b] - '0';
        }
        // Shift input to end of array and fill start with 0
        for (int a = length[i]; a > 0; a--)
        {
            input[i][(99 - length[i]) + a] = input[i][a - 1];
            input[i][a-1] = 0;
        }
    }

    int longest = length[0] > length[1] ? length[0] : length[1];
    char* output = (char*)malloc(sizeof(char) * longest + 1);

    int carry = 0;
    for (int i = 99; i >= (100 - longest); i--)
    {
        int result = input[0][i] + input[1][i] + carry;
        int remainder = result % 10;
        carry = result / 10;
        output[longest - (99 - i)] = remainder;
    }
    output[0] = carry;

    // Don't output a 0 at the start of output
    int output_offset = 0;
    if (output[0] == 0)
        output_offset = 1;

    for (int i = output_offset; i < longest + 1; i++)
        printf("%d",output[i]);

    printf("\n");
    return 0;
}


texts: Writing data to an Excel sheet using openpyxl

texts:
I am currently writing a program to update and copy data from one spreadsheet to another. The code I have written works fine, but it takes way too long for it to be practical. In total, it takes about an hour to perform this task. The spreadsheets are also very large I might add, one is 20,000 rows by 30 columns, and the other is 3,000 rows by 30 columns. The code updates specific rows in the larger spreadsheet and then copies the data from the smaller spreadsheet onto the larger spreadsheet if that data doesn't already exist there. After analyzing what the problem could be, I found that copying and writing the data to the larger spreadsheet took a majority of the time (~ 55min). The write_only option in openpyxl does not support writing to existing files as I need, so I am stuck as to how to speed up this writing process.

# iterate through ticket column of first sheet
for roww in range (2, sheet.max_row+1):
    sheet1_ticket_number = sheet.cell(row=roww, column = 3).value
    # iterate through ticket column of second sheet
    # Ticket number x from sheet 1 compared to all ticket numbers in sheet 2
    for row2 in range(starting_row, (sheet2.max_row+1+sheet.max_row)):
        sheet2_ticket_number = sheet.cell(row = row2, column = 3).value

        # If ticket number matches, check to see if columns match, if not, update
        if (sheet.cell(row=roww, column = 3).value == sheet2.cell(row = row2, column = 3).value):
            check = 'true'
            for i in range(1, sheet.max_column+1):
                if sheet2.cell(row=row2, column = 3+i).value != sheet.cell(row=roww, column =3+i).value and (3+i != 15) and (3+i != 38) and (3+i != 14):
                    sheet2.cell(row=row2, column = 3+i).value = sheet.cell(row=roww, column =3+i).value
                    #print('updated row# ', row2, 'Column#', 3+i, 'ticket#', sheet2.cell(row=row2, column = 3).value,  'to:', sheet2.cell(row=row2, column = 3+i).value)

                if sheet2.cell(row=row2, column = 1).value is None:
                    sheet2.cell(row=row2, column = 1).value = sheet.cell(row=roww, column =1).value
                if sheet2.cell(row=row2, column = 2).value is None:
                    sheet2.cell(row=row2, column = 1).value = sheet.cell(row=roww, column =1).value
            break

        # if ticket number is not in second file/ empty row, add new ticket row w column entries.
        if (sheet2.cell(row = row2, column = 3).value is None) and (sheet2.cell(row = row2+1, column = 3).value is None):
            sheet2.cell(row=row2, column =3).value = sheet1_ticket_number
            #print('printed new ticket row# ', sheet2.cell(row=row2, column =3).value)
            for j in range(1, sheet.max_column+1):
                if sheet2.cell(row=row2, column = 3+j).value != sheet.cell(row=roww, column =3+j).value:
                    sheet2.cell(row=row2, column = 2).value = sheet.cell(row=roww, column =2).value
                    sheet2.cell(row=row2, column = 1).value = sheet.cell(row=roww, column =1).value
                    sheet2.cell(row=row2, column = 3+j).value = sheet.cell(row=roww, column =3+j).value
            break


texts:
What are the issues/better ways to do this? I was just trying to implement this for practice and learn C++. Can anyone suggest efficient implementations of other functions such as count, size, all, none, etc?

#define NO_OF_BITS (8 * sizeof(unsigned int))

#include <iostream>
#include <assert.h>

template<ssize_t n>
class BitArray {
  private:
    int array[n];

  public:
    BitArray();
    void set(unsigned int);
    void reset(unsigned int);
    void flip(unsigned int);
    int test(unsigned int);
};

template<ssize_t n>
BitArray<n>::BitArray() {
  memset(array, 0, sizeof(array));
}

template<ssize_t n>
void BitArray<n>::set(unsigned int k) {
  array[k/NO_OF_BITS] |= (1U << (k%NO_OF_BITS));
}

template<ssize_t n>
void BitArray<n>::reset(unsigned int k) {
  array[k/NO_OF_BITS] &= ~(1U << (k%NO_OF_BITS));
}

template<ssize_t n>
int BitArray<n>::test(unsigned int k) {
  return ( (array[k/NO_OF_BITS] & (1U<<(k%NO_OF_BITS))) != 0 );
}

template<ssize_t n>
void BitArray<n>::flip(unsigned int k) {
  array[k/NO_OF_BITS] ^= (1U <<(k%NO_OF_BITS));
}

int main() {
  BitArray<10>* bs = new BitArray<10>();
  bs->set(100);
  assert(bs->test(100)>=1);
  bs->reset(100);
  assert(bs->test(100)==0);
  bs->flip(100);
  assert(bs->test(100)>=1);
}


texts: Log the diff of a Apache httpd config file and reload the service with Python and systemd

texts:
Using systemd's .path unit to run a Python script whenever a httpd config file is changed. The Python script creates a backup of the config and logs the differences of the newly modified and backup file. After that it checks the syntax of the httpd config and gracefully reloads the web server service.

The Python script:

#!/path/to/python

import difflib
import logging
import shutil
import subprocess
import sys
from pathlib import Path
import yaml

logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO)

class HttpdMonitor:

    def __init__(self, config_file):
        self.config_file = config_file
        self.config = self.load_config()
        self.httpd_conf = self.config['httpd-conf']
        self.backup_file = self.config['httpd-conf'] + '.bak'
        self.syntax_check_cmd = self.config['syntax-check-cmd'].split()
        self.reload_cmd = self.config['reload-cmd'].split()

    def load_config(self):
        with open(self.config_file, 'r') as stream:
            return yaml.safe_load(stream)

    def make_backup(self):
        try:
            shutil.copy2(self.httpd_conf, self.backup_file)
        except IOError as e:
            logging.exception("Making backup failed: %s", e)

    def find_diff(self):
        with open(self.httpd_conf, 'r') as f, open(self.backup_file, 'r') as bak:
            diffs = list(
                difflib.unified_diff(f.readlines(), bak.readlines(), fromfile=self.httpd_conf, tofile=self.backup_file))
            return diffs

    def log_diff(self):
        try:
            diffs = self.find_diff()
            logging.info('Differences found: \n%s', ''.join(diffs))
        except IOError as e:
            logging.exception('Finding diff failed: %s', e)

    def call_httpd_commands(self):
        subprocess.run(self.syntax_check_cmd, check=True)
        subprocess.run(self.reload_cmd, check=True)

    def reload_httpd(self):
        try:
            self.call_httpd_commands()
        except subprocess.CalledProcessError as e:
            logging.exception("Reloading failed: %s", e)

    def run(self):
        if not Path(self.backup_file).is_file():
            self.make_backup()
            return
        self.log_diff()
        self.make_backup()
        self.reload_httpd()

if __name__ == '__main__':
    httpd_monitor = HttpdMonitor(sys.argv[1])
    httpd_monitor.run()

This uses a YAML file to specify the httpd config file and also the commands to run, sort of like this:

---
httpd-conf: /path/to/file
syntax-check-cmd: httpd -t
reload-cmd: httpd -k graceful

Using systemd's .path unit the script get fired whenever there's something changed in the httpd config file. For example httpd-monitor.path:

[Unit]
Description=Monitor the httpd conf for changes

[Path]
PathChanged=/path/to/file
Unit=httpd-monitor.service

[Install]
WantedBy=multi-user.target

And httpd-monitor.service:

[Unit]
Description=Do backup, diff changes and reload httpd

[Service]
Restart=no
Type=simple
ExecStart=/path/to/httpd_monitor.py /path/to/httpd-monitor.yaml

[Install]
WantedBy=multi-user.target

So I'd first run systemd start httpd-monitor.service just to create the initial backup (the if condition within the run() method should take care of it) and then just systemd enable --now httpd-monitor.path to enable the .path unit.
Probably not the simplest of solutions so I'm very open to any feedback!


texts: Generating the maximum number possible from an array

texts:
I have the following code in Scala as a solution to the problem:

Find the maximum number possible from the given Seq of Integers while keeping the individual numbers intact

e.g.

Seq(2,5,9,4) should result in 9542
Seq(4, 98, 10, 110, 91) should result in 9891411010

Note that in case of numbers with more than one digit, the entire number should remain together.
Solution in Scala:
import scala.util.Sorting
object MatheMagic {
  def getLargestPossibleNumber(numArray: Seq[Int]) = {
    numArray.sorted[Int](IntOrdering).mkString.toLong
  }
  object IntOrdering extends Ordering[Int] {
    def compare(x: Int, y: Int) = {
      -(x.toString.concat(y.toString).toInt compare y.toString.concat(x.toString).toInt)
    }
  }
}

Sample invocation:
MatheMagic.getLargestPossibleNumber(Seq(4, 98, 10, 110, 91))


texts: Iteratively Build a Summary Dataset in an Effective Way

texts:
This is a problem I find a lot!! Can I achieve this goal without consuming so much time?

My code below achieves what I want it to achieve. However, I believe it could be a lot more efficient and Pythonic.

PROBLEM:
I want to extract summary data from a larger dataset and I only know how to do so utilizing nested For loops. For example, I have a large dataset containing golf data, and I would like to extract summary statistics for the individual golf holes.

This code creates a scoring distribution and mean score for each Season-Hole-Round-Score vs. Par combination (48 rows in total).

import numpy as np
import pandas as pd
import itertools

seasons = [2001,2001,2001,2001,2002,2002,2002,2002]
holes = [1,1,2,2,1,1,2,2]
rounds = [3,4,3,4,3,4,3,4]
scores = [1,-1,0,0,0,1,-1,1] # actual scores vs. par

df = pd.DataFrame({'season' : seasons, 'hole': holes, 'round':rounds, 'score': scores})

all_seasons = set(seasons); all_holes = set(holes);  all_scores = [-1,0,1]
all_rounds = ["R3","R4","Weekend"] #some averages combine rounds
round_iter = np.arange(0,4) #position of rounds list
round_ids = [[3],[4],[3,4]] # weekend incldues rounds 3 and 4

hold_list = [] #blank list

for season,round,hole in itertools.product(all_seasons,round_iter,all_holes):

    hold_data = df[((df['season'] == season) & (df['hole'] == hole))
    & (df['round'].isin(round_ids[round-1]))]

    mean_score = hold_data['score'].mean()
    vspar_distro = hold_data['score'].value_counts().to_dict()
    for score in all_scores:
        count_score = 0
        if score in vspar_distro:
            count_score = vspar_distro[score]
        hold_list.append([season,all_rounds[round-1]
                        ,hole,mean_score,score,count_score])

historical_df = pd.DataFrame(hold_list,columns
            = ['season','round','hole','mean_score','vspar_score','count'])

This produces the df that I desire (here are the first 5 rows), but applying this to a file with 100k+ records takes a long time and I believe there is a more efficient way. Thanks!

   season    round  hole  mean_score  vspar_score  count
0    2001  Weekend     1         0.0           -1      1
1    2001  Weekend     1         0.0            0      0
2    2001  Weekend     1         0.0            1      1
3    2001  Weekend     2         0.0           -1      0
4    2001  Weekend     2         0.0            0      2


texts: A function to remove characters from a string

texts:
I wanted to write a function to remove a set of characters from a string in JavaScript.

I came up with this.

How can it be improved in terms of time/space complexity?

function remove(str, chars) {
    var set = new Set(chars); // looking up presence of char is O(1)
    var arr = [...str]; // operate on an arrray rather than a string to avoid unneccessary string copying
    // What follows is O(N) I think...
    return arr.reduce((p,c) => {
        if(set.has(c)) {
            return p;
        }
        p.push(c);
        return p;
    }, []).join('');
}

remove('hello world', 'el') === 'ho word';


texts:
I was wondering if my code will produce a true singleton.  I am creating an Android app, and all activities should access my API through one instance of the SyncApi class.

public class Api {

    private static SyncApi api = null;

    static {
        synchronized (api) {
            if (api == null) {
                api = new ApiFActory().getSyncApi();
            }
        }
    }

    public static SyncApi getInstance() {
        return api;
    }
}

Use of the class would look like:

SyncApi api = Api.getInstance();
api.logOn("jjnguy", "pa55w0rd");


texts: Nested dictionary creation with setdefault

texts:
Is there a better way of creating a nested dictionary than what I'm doing below? The result for the setdefault is because I don't know whether that particular key exists yet or not.
def record_execution_log_action(
        execution_log, region, service, resource, resource_id, resource_action
    ):
        execution_log["AWS"].setdefault(region, {}).setdefault(service, {}).setdefault(
            resource, []
        ).append(
            {
                "id": resource_id,
                "action": resource_action,
                "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )


texts: Is this good design for custom email template?

texts:
I read effective Java by Joshua Bloch. And it said use enums over int constant. So I was thinking instead of using hard coded strings I could also use enums. The forgotpassword.txt and confirmation.txt are plain text resource files.

When the class is loaded, I get the contents of the text file and store it inside of a map, since enums are only loaded once.

When I want to create an email template I pass key value map to the EmailTemplate.[TemplateName].create () method and it produces an email text. Anytime I want to create a new template I just have to go to one place and add it.

The only down-side I could think of is if you have hundreds of different email templates. Do you think this is a good design?

public enum EmailTemplate
{
    FORGOT_PASSWORD("forgotpassword.txt"),
    CONFIRM_EMAIL("confirmation.txt");

    private final String mFile;

    public String getFile()
    {
        return mFile;
    }

    EmailTemplate(String file)
    {
        mFile = file;
    }

    public String create(Map<String, String> valuesMap)
    {
        //lazy load file content into template
        if (!lookup.containsKey(this))
        {
            lookup.put(this, FileUtil.getFileContents((this.getFile())));
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        return sub.replace(lookup.get(this));
    }

    private static final Map<EmailTemplate, String> lookup = new HashMap<EmailTemplate, String>();
}

public class EmailGenerator
{
    public static void sendConfirmationEmail(String emailAddress,
            String confirmCode)
    {
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("link", confirmCode);

        String text = EmailTemplate.CONFIRM_EMAIL.create(valuesMap);
        System.out.println(text);
    }

    public static void sendContactUs(String subject, String email, String message, String name)
    {
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("name", name);
        valuesMap.put("text", message);
        valuesMap.put("email", email);

        String text = EmailTemplate.CONTACT_US.create(valuesMap);
        System.out.println(text);
    }
}