texts:
I have an implementation of depth first search, which I want to test using the pytest framework.
I would be making test cases for other graph algorithms, and would like to know if this approach is good enough to be replicated on similar programs.
Here is what it looks like currently:
(This may not be a very exhaustive set of test cases, but my goal is to separate simple checks that are done in the actual implementation)
import pytest
from dfs import dfs_recursive, dfs_iterative

def test_data():
    test_graph = {
        'A' : ['B','S'],
        'B' : ['A'],
        'C' : ['D','E','F','S'],
        'D' : ['C'],
        'E' : ['C','H'],
        'F' : ['C','G'],
        'G' : ['F','S'],
        'H' : ['E','G'],
        'S' : ['A','C','G']
    }

    assert dfs_iterative(test_graph, 'A') is not None
    assert len(dfs_iterative(test_graph, 'A')) == len(list(test_graph.keys()))
    assert dfs_recursive(test_graph, 'A') is not None
    assert len(dfs_recursive(test_graph, 'A')) == len(list(test_graph.keys()))

def test_graph():
    test_graph = {
        1: [2, 3]
    }

    if len(test_graph.keys()) < 2:
        print("\nA graph has to have atleast 2 vertices")

def all_unique(x):
    """
    Check if all elements in a list are unique; if not exit erly
    """
    seen = set()
    return not any(i in seen or seen.add(i) for i in x)

def test_unique():
    test_graph = {
        'A': ['B', 'C'],
        'B': ['A', 'D', 'E'],
        'C': ['A', 'F'],
        'D': ['B'],
        'E': ['B', 'F'],
        'F': ['C', 'E']
    }

    assert all_unique(dfs_iterative(test_graph, 'A')) is True
    assert all_unique(dfs_recursive(test_graph, 'A')) is True

def test_vertex1():
    test_graph = {
        'A': ['B', 'C'],
        'B': ['A', 'D', 'E'],
        'C': ['A', 'F'],
        'D': ['B'],
        'E': ['B', 'F'],
        'F': ['C', 'E']
    }

    with pytest.raises(KeyError) as excinfo:
        dfs_iterative(test_graph, 'Z')

    assert 'Z' in str(excinfo.value)
    assert 'KeyError' in str(excinfo.type)
    print('\nVertex does not exist')

def test_vertex2():
    test_graph = {
        1: [2, 3],
        2: [2, 3, 4],
        3: [],
        4: [],
    }

    for key, value in test_graph.items():
        if key in value:
            pytest.fail("A vertex cannot point to itself")    # explicitly fails this test

Please suggest any changes, additions or improvements.


texts: React component to list TV shows from a JSON result

texts:
I'm trying to rewrite my old project in Reactjs. As I am a beginner and this is my first app, I need some assistance in understanding what is the best way to do this in the React way and how I can improve myself and this demo project.

Here is a working demo of it.

ListManager.js

import React, { Component } from 'react'
import List from './List'

export class ListManager extends Component {
    constructor(props, context) {
       super(props, context)
       this.state = { finaldata :[]}
}

APIres(ids){
    Promise.all(ids.map(id =>
        fetch('http://api.tvmaze.com/shows/'+id).then(resp => resp.json().then(data => data.name))
        )).then(data => {
            data.sort()
            this.setState({finaldata:data})
        })
}

componentWillMount(){
    const id = [1,2,3,4,5]
    this.APIres(id)

}

render() {

    return (

{this.props.title}

            <List data={this.state.finaldata} />

    )
  }
}

List.js

'use strict'
import React, { Component } from 'react'

const ListItem = (props) =>
{ props.text }

const List = (props) => {
    const listNodes = props.data.map((
    value,index) => {
        return(
            <ListItem text={value} key={index}></ListItem>
        )
    })

    return (
{listNodes}

    )
}

export default List

Some note: id array will come with a URL query like example.com/#/?id=1,2,3,4. I will be using react-router for this.


texts:
This is GildedRose refactoring kata. Can this code be written to be more readable, and maintainable?
class GildedRose:

    def __init__(self, items):
        self.items = items

can I improve this part of code?
    @staticmethod
    def update_min_max_quality(item):
        """Updates min and max values of items"""
        if item.quality >= 50:
            item.quality = 50
        if item.quality < 0:
            item.quality = 0
        return item.quality

    def decrease_quality(self, item):
        """Decreases item value by 1"""
        self.update_min_max_quality(item)
        item.quality -= 1
        return item.quality

    @staticmethod
    def decrease_sell_in(item):
        """Decreases item sell in by 1"""
        item.sell_in -= 1
        return item.sell_in

    @staticmethod
    def update_aged_brie(item):
        """Updates Aged Brie sell in and quality"""
        if item.sell_in < 0:
            item.quality += 2
        return item.quality

How about this function?
    @staticmethod
    def update_backstage(item):
        """Updates Backstage quality"""
        if item.sell_in <= 0:
            item.quality = 0
            return item.quality
        elif item.sell_in < 6:
            item.quality += 3
            return item.quality
        elif item.sell_in < 11:
            item.quality += 2
            return item.quality
        else:
            return item.quality

    @staticmethod
    def update_conjured(item):
        """Updates conjured items sell in and quality"""
        item.quality -= 2
        item.sell_in -= 1
        return item.quality, item.sell_in

    @staticmethod
    def update_sulfuras(item):
        """Update sulfuras sell in"""
        item.sell_in -= 1
        return item.sell_in

No switches in python, how to shorten this section?
    def update_quality(self):
        """Updates quality and sell in of provided item"""
        for item in self.items:
            if item.name == 'Aged Brie':
                self.update_aged_brie(item)
            if item.name == 'Backstage passes to a TAFKAL80ETC concert':
                self.update_backstage(item)
            if item.name == "Conjured Mana Cake":
                self.update_conjured(item)
            if item.name == "Sulfuras, Hand of Ragnaros":
                self.update_sulfuras(item)
            if item.name in ['+5 Dexterity Vest', "Elixir of the Mongoose"]:
                self.decrease_sell_in(item)
                self.decrease_quality(item)
            if (item.sell_in < 1 or item.quality == 50) and item.name != "Sulfuras, Hand of Ragnaros":
                self.update_min_max_quality(item)

class Item:
    def __init__(self, name, sell_in, quality):
        self.name = name
        self.sell_in = sell_in
        self.quality = quality

    def __repr__(self):
        return "%s, %s, %s" % (self.name, self.sell_in, self.quality)


texts: Helper utilities for easier benchmarking in C

texts:
I have this tiny library for measuring the execution time in milliseconds and returning the duration plus the result:

execres.h

/******************
* File: execres.h *
******************/

#ifndef EXECRES_H
#define EXECRES_H

#include <sys/time.h>

typedef struct {
    unsigned long long  millis;
    void*               result;
} ExecResult, *PExecResult;

PExecResult execTime(void* (*code)(void*), void* param);

#endif  /* EXECRES_H */

execres.c

/******************
* File: execres.c *
******************/

#include "execres.h"
#include <stdlib.h>

PExecResult execTime(void* (*code)(void*), void* param)
{
    PExecResult result;
    struct timeval tva;
    struct timeval tvb;

    if (!code)
    {
        return NULL;
    }

    result = malloc(sizeof(ExecResult));

    if (!result)
    {
        return NULL;
    }

    gettimeofday(&tva, NULL);
    result->result = code(param);
    gettimeofday(&tvb, NULL);

    result->millis = (unsigned long long)
                     (tvb.tv_sec * 1000 + tvb.tv_usec / 1000 -
                      tva.tv_sec * 1000 - tva.tv_usec / 1000);
    return result;
}

main.c

/***************
* File: main.c *
***************/

#include <stdint.h>
#include <stdio.h>
#include "execres.h"

static uint64_t Fibonacci(uint64_t n)
{
    switch (n)
    {
        case 0:
            return 0;

        case 1:
            return 1;

        default:
            return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
}

int main()
{
    PExecResult result;

    puts("Begin computation.");

    result = execTime((void* (*)(void*)) Fibonacci, (void*) 40);

    printf("Fibonacci took %u milliseconds and returned %llu.\n",
           (unsigned) result->millis,
           (uint64_t) result->result);

    return 0;
}


texts: Codility voracious fish are moving along a river

texts:
I am trying to solve the codility problem:

  N voracious fish are moving along a river. Calculate how many fish are alive.

Codility Problem

My code get only 50 percent of 100. Could you tell me what is wrong with my code?

  You are given two non-empty zero-indexed arrays A and B consisting of
  N integers. Arrays A and B represent N voracious fish in a river,
  ordered downstream along the flow of the river.

  The fish are numbered from 0 to N − 1. If P and Q are two fish and P <
  Q, then fish P is initially upstream of fish Q. Initially, each fish
  has a unique position.

  Fish number P is represented by A[P] and B[P]. Array A contains the
  sizes of the fish. All its elements are unique. Array B contains the
  directions of the fish. It contains only 0s and/or 1s, where:

  0 represents a fish flowing upstream, 1 represents a fish flowing
  downstream. If two fish move in opposite directions and there are no
  other (living) fish between them, they will eventually meet each
  other. Then only one fish can stay alive − the larger fish eats the
  smaller one. More precisely, we say that two fish P and Q meet each
  other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish
  between them. After they meet:

  If A[P] > A[Q] then P eats Q, and P will still be flowing downstream.
  If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We
  assume that all the fish are flowing at the same speed. That is, fish
  moving in the same direction never meet. The goal is to calculate the
  number of fish that will stay alive.

  For example, consider arrays A and B such that:

A[0] = 4    B[0] = 0
A[1] = 3    B[1] = 1
A[2] = 2    B[2] = 0
A[3] = 1    B[3] = 0
A[4] = 5    B[4] = 0

  Initially all the fish are alive and all except fish number 1 are
  moving upstream. Fish number 1 meets fish number 2 and eats it, then
  it meets fish number 3 and eats it too. Finally, it meets fish number
  4 and is eaten by it. The remaining two fish, number 0 and 4, never
  meet and therefore stay alive.

  Write a function:

class Solution { public int solution(int[] A, int[] B); }

  that, given two non-empty zero-indexed arrays A and B consisting of N
  integers, returns the number of fish that will stay alive.

  For example, given the arrays shown above, the function should return
  2, as explained above.

  Assume that:

  N is an integer within the range [1..100,000]; each element of array A
  is an integer within the range [0..1,000,000,000]; each element of
  array B is an integer that can have one of the following values: 0, 1;
  the elements of A are all distinct.

  Complexity:

  Expected worst-case time complexity is O(N); expected worst-case space
  complexity is O(N), beyond input storage (not counting the storage
  required for input arguments).

This is my algorithm:

public static int solution(int[] size, int[] direction)
{
    var stack = new Stack<int>();
    const int UPSTREAM = 0;
    const int DOWNSTREAM = 1;
    var updateStack = false;

    for (int i = 0; i < size.Length; i++)
    {
        if (stack.Count <= 0) //initial data
            stack.Push(i);
        else
        {
            var lastFish = stack.Peek();

            if (direction[i] == direction[lastFish] || direction[lastFish] == UPSTREAM && direction[i] == DOWNSTREAM)
            {
                stack.Push(i);
            }
            else
            {
                while (stack.Count > 0 && size[lastFish] < size[i] && direction[lastFish] == DOWNSTREAM && direction[i] == UPSTREAM)
                {
                    updateStack = true;
                    stack.Pop();
                    if (stack.Count > 0)
                        lastFish = stack.Peek();
                }
                if (updateStack)
                {
                    stack.Push(i);
                    updateStack = false;
                }
            }
        }

    }
    return stack.Count;
}


texts:
I just finished creating a fancy checkbox and am hoping for some tips to help improve my code, as I am still learning.

$(document).ready(function(){
  function checkbox(){
    var y = $("#yon");
    var n = $("#non");
    var cx = $("#chex")
    var cbx = $("#checkbox");
    var chval = false;
    $(".cspan").click(function(){
      $(n).toggleClass("no");
      $(y).toggleClass("yes");
      if(chval){
        $(cx).text("\u2716");
        $(cbx).prop('checked', false);
        chval = false;
      }
      else{
        $(cx).text("\u2714");
  $(cbx).prop('checked', true);
        chval = true;
      }
    });
  }
  checkbox();
});
#checkcon p{

}
input[type="checkbox"] {
    display:none;
}
input[type="checkbox"] + label span {
    display:inline-block;
 width: 160px;
 height: 60px;
 border-radius: 25px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background-color: #ff3a31;
    cursor:pointer;
 transition: background-color 100ms linear;
 position:absolute;
}
input[type="checkbox"]:checked + label span {
    background-color: #00cc66;
    transition: background-color 100ms linear;

}
input[type="checkbox"] {

}
.checkemb{
 position:relative;
 display:inline-block;
 margin-right:10px;
 margin-left:10px;
 font-family:"Arial Black", Gadget, sans-serif;
 color:#ffffff;
}
#chex{
 margin-right:25px;
 margin-left:25px;

}
p.yes{
 color:#990800;
 transition: color 100ms linear;
}
p.no{
 color:#008040;
 transition: color 100ms linear;
}

    <input id="checkbx" type="checkbox"/>

Yes

&#10006

No


texts:
I have this legacy code and I don't really think this is easy to read/maintain it. Can you suggest a way to make this more readable while still saving the performance?

template<typename T>
    void static ConvertBayerToRgbImageDemosaic(T* BayerChannel, T* RgbChannel, int Width, int Height, ColorSpace ColorSpace)
    {
        //Translates index offset in Bayer image to channel offset in RGB image
        int offsets[4];
        std::vector<int> colorOffsets[4];
        //calculate offsets according to color space
        switch (ColorSpace)
        {
        case ColorSpace::BGGR:
            offsets[0] = 2;
            offsets[1] = 1;
            offsets[2] = 1;
            offsets[3] = 0;
            colorOffsets[0].push_back(0);
            colorOffsets[0].push_back(1);
            colorOffsets[0].push_back(Width);
            colorOffsets[0].push_back(Width + 1);
            colorOffsets[1].push_back(-1);
            colorOffsets[1].push_back(0);
            colorOffsets[2].push_back(0);
            colorOffsets[2].push_back(1);
            colorOffsets[3].push_back(-Width - 1);
            colorOffsets[3].push_back(-Width);
            colorOffsets[3].push_back(-1);
            colorOffsets[3].push_back(0);
            break;
        case ColorSpace::RGGB:
            offsets[0] = 0;
            offsets[1] = 1;
            offsets[2] = 1;
            offsets[3] = 2;
            colorOffsets[0].push_back(0);
            colorOffsets[0].push_back(1);
            colorOffsets[0].push_back(Width);
            colorOffsets[0].push_back(Width + 1);
            colorOffsets[1].push_back(-1);
            colorOffsets[1].push_back(0);
            colorOffsets[2].push_back(0);
            colorOffsets[2].push_back(1);
            colorOffsets[3].push_back(-Width - 1);
            colorOffsets[3].push_back(-Width);
            colorOffsets[3].push_back(-1);
            colorOffsets[3].push_back(0);
            break;
        case ColorSpace::GBRG:
            offsets[0] = 1;
            offsets[1] = 2;
            offsets[2] = 0;
            offsets[3] = 1;
            colorOffsets[0].push_back(0);
            colorOffsets[0].push_back(1);
            colorOffsets[1].push_back(-1);
            colorOffsets[1].push_back(0);
            colorOffsets[1].push_back(Width - 1);
            colorOffsets[1].push_back(Width);
            colorOffsets[2].push_back(-Width);
            colorOffsets[2].push_back(-Width + 1);
            colorOffsets[2].push_back(0);
            colorOffsets[2].push_back(1);
            colorOffsets[3].push_back(-1);
            colorOffsets[3].push_back(0);
            break;
        case ColorSpace::GRBG:
            offsets[0] = 1;
            offsets[1] = 0;
            offsets[2] = 2;
            offsets[3] = 1;
            colorOffsets[0].push_back(0);
            colorOffsets[0].push_back(1);
            colorOffsets[1].push_back(-1);
            colorOffsets[1].push_back(0);
            colorOffsets[1].push_back(Width - 1);
            colorOffsets[1].push_back(Width);
            colorOffsets[2].push_back(-Width);
            colorOffsets[2].push_back(-Width + 1);
            colorOffsets[2].push_back(0);
            colorOffsets[2].push_back(1);
            colorOffsets[3].push_back(-1);
            colorOffsets[3].push_back(0);
            break;
        default:
            throw "Unsupported colorSpace. Only bayer supported.";
        }

        #pragma omp parallel for
        for (auto row = 0; row < Height; row++)
        {
            for (auto col = 0, bayerIndex = row * Width; col < Width; col++, bayerIndex++)
            {
                auto offset = (row % 2)*2 + (col % 2); //0...3
                std::for_each(colorOffsets[offset].begin(), colorOffsets[offset].end(),
                    [&](int colorOffset)
                {
                    auto rgbIndex = (bayerIndex + colorOffset) * 3 + offsets[offset];
                    RgbChannel[rgbIndex] = BayerChannel[bayerIndex];
                });
            }
        }
    }


texts: Rotate a matrix, using transposition and reflection

texts:
I want to compare two solutions to the following question from Cracking The Coding Interview by Gayle Laakman McDowell :

  1.7 Rotate Matrix - Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image
  by 90 degrees. Can you do this in place?

We will be assuming we have a square matrix to rotate by 90 degrees clockwise like so:

input:
1 2 3
4 5 6
7 8 9
result:
7 4 1
8 5 2
9 6 3

The book suggests an unusual "layer" method that works its way from the outer edge of the matrix towards the inside

Video explanation by McDowell
McDowell solution code on
Github

A much more intuitive way to solve this seems to be a matrix transpose, followed by a mirror about the vertical axis. This solution is more intuitive because it uses known mathematical matrix operations - the transposition and the reflection. Aside from this being more obvious and easier to read for who have dealt with matrices in the past, it is also more useful because these individual mathematical operations could be saved for other purposes.

Is there any issue with the following code ? More specifically, what are the pros and cons versus the original McDowell solution ?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef vector<vector<int>> matrixT;
class Solution {
    public:
    bool static rotateMatrix(matrixT &mtx){
        if (mtx.size() != mtx[0].size() || mtx.size() == 0) return false;
        int N = mtx.size();

        //transpose matrix
        for (int n = 0 ; n<= N-2; n++)
            for(int m= n+1 ; m<= N-1; m++)
                swap(mtx[n][m], mtx[m][n]);

        //vertical mirror
        for (int n = 0; n < N; n ++)
            for (int m=0; m<N/2 ;m++)
                swap(mtx[n][m], mtx[n][N-1-m]);

        return true;
    }

    void static printMatrix(matrixT mtx){
        for(int m = 0; m < mtx.size(); m++) {
            for(int n = 0; n < mtx.size(); n++)
                cout << mtx[m][n] << " ";
            cout << endl;
        }
    }
};

int main() {
    cout << "input: " << endl;
    matrixT mtx = {{1,2,3},
                   {4,5,6},
                   {7,8,9}};

    Solution::printMatrix (mtx);
    Solution::rotateMatrix (mtx);
    cout << "result: " << endl;
    Solution::printMatrix (mtx);
    return 0;
}


texts:
I'm writing an AD Termination script for work. I'm new to PowerShell and was wondering if multiple commands within PowerShell switch statement is okay to do:

# Switch statement to start here
$switchTitle = "Terminate User"
$confirmMessage = "Are you sure that " + $fullName + " is the user that you want to terminate?"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",
"Starts the termination process for the selected user"

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",
"Cancels the termination process and, eventually, will prompt for another user selection"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($switchTitle, $confirmMessage, $options, 0)

switch ($result)
   {
      0 {"You have selected Yes. The Termination Script will now start."
           Copy-Item -Path "Microsoft.PowerShell.Core\FileSystem::\\Path\To\UserFolder" `
           -Destination "Microsoft.PowerShell.Core\FileSystem::\\path\To\TermFolder" -Recurse -Force
        # TODO: Put delete command here for old profile
        # TODO: Put Disable AD Object command here
        }
      1 {"You have selected No. Please choose another user."}
   }

I'm also concerned with PowerShell styling/conventions so if I'm doing anything wrong, please let me know.


texts: Can this promise be chained more cleanly?

texts:
The below code uses Promises/A+ (specifically rsvp.js) to generate a token.  It does so by either taking an existing token or downloading and parsing a token from a web page.  Is it possible to chain this to LoadURIPromise more cleanly? Usually one can chain together promises without causing as much indentation drift.

new RSVP.Promise(function (resolve) {
    if (TokenData) {
        resolve(TokenData);
    } else {
        LoadURIPromise(TokenURL).then(function (xmlDoc) {
            TokenData = xmlDoc.evaluate(
                '/root/theToken',
                xmlDoc.documentElement,
                null,
                XPathResult.FIRST_ORDERED_NODE_TYPE,
                null
            ).singleNodeValue.textContent;
            resolve(TokenData);
        });
    }
}).then(function (token) {
    //Use Token here
}


texts: Find the thousandth integer without the digits 3, 4, and 7

texts:
I have to find the thousandth number (excluding numbers 3, 4, 7) but it's taking a long time, about 9 seconds. I'd like to find out how to improve performance.

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

public class FirstChallange {

    private static int removedNumbers;
    private static int numberQuantity;
    private static int lastNumberFound;
    private static int cont;
    private static int pos3;
    private static int pos4;
    private static int pos7;

    public static void main(String[] args)
    {

        long inicio = System.currentTimeMillis();

        removedNumbers = 0;
        numberQuantity = 10000000;

        for (cont = 1; removedNumbers <= numberQuantity; cont++) {
            String str = new String();
            str = String.valueOf(cont);

            pos3 = str.indexOf("3");
            pos4 = str.indexOf("4");
            pos7 = str.indexOf("7");

            if((pos3 == -1) && (pos4 == -1) && (pos7 == -1)) {
                removedNumbers++;
                if(removedNumbers == numberQuantity){ // can not find numbers (3, 4, 7)
                    lastNumberFound = cont;
                }
            }
        }

        DecimalFormat dfmt = new DecimalFormat("0");

        System.out.println(dfmt.format(lastNumberFound));

        long fim  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(fim - inicio)));

    }
}

Is converting numbers into string and removing them with indexOf the best mode? or is there anything better than indexOf like RabinKarp?

Expected result: 180999565 in 5/4 seconds


texts:
I would like to improve the naive matrix transpose algorithm by using a cache friendly algorithm.

So far there are 4 variants.

Iterate over the source matrix:

  MatrixXd transposeSrc() const
  {
    MatrixXd At(m_cols, m_rows);

    for (int i = 0; i < m_rows; i++) {
      for (int j = 0; j < m_cols; j++) {
        At(j, i) = (*this)(i, j);
      }
    }
    return At;
  }

Iterate over the destination matrix:

  MatrixXd transposeDst() const
  {
    MatrixXd At(m_cols, m_rows);

    for (int i = 0; i < m_cols; i++) {
      for (int j = 0; j < m_rows; j++) {
        At(i, j) = (*this)(j, i);
      }
    }
    return At;
  }

A "tiling" version found on StackOverflow:

  MatrixXd transposeTilingSO(int tileSize = 16) const
  {
    MatrixXd out(m_cols, m_rows);

    for (int i = 0; i < m_rows; i += tileSize) {
      for (int j = 0; j < m_cols; ++j) {
        for (int b = 0; b < tileSize && i + b < m_rows; ++b) {
          out.m_data[j*m_rows + i + b] = (*this).m_data[(i + b)*m_cols + j];
        }
      }
    }

    return out;
  }

A block tiling version:

  MatrixXd transposeTiling(int tileSize = 16) const
  {
    MatrixXd At(m_cols, m_rows);

    for (int i = 0; i < m_rows;) {
      for (; i <= m_rows - tileSize; i += tileSize) {
        int j = 0;
        for (; j <= m_cols - tileSize; j += tileSize) {
          for (int k = i; k < i + tileSize; k++) {
            for (int l = j; l < j + tileSize; l++) {
              At(l, k) = (*this)(k, l);
            }
          }
        }

        for (int k = i; k < i + tileSize; k++) {
          for (int l = j; l < m_cols; l++) {
            At(l, k) = (*this)(k, l);
          }
        }
      }

      for (; i < m_rows; i++) {
        for (int j = 0; j < m_cols; j++) {
          At(j, i) = (*this)(i, j);
        }
      }
    }

    return At;
  }

Experimentally, I thought I have found how to choose which variant is preferable depending on the input matrix size:

  MatrixXd transposeOptim(int tileSize = 16) const
  {
    if (m_rows > 2 * m_cols && m_cols <= 64) {
      return transposeSrc();
    } else if (m_cols > 2 * m_rows && m_rows <= 64) {
      return transposeDst();
    } else if (m_rows % tileSize == 0) {
      return transposeTilingSO();
    } else {
      return transposeTiling();
    }
  }

And the essential information about the MatrixXd class (full source code):

class MatrixXd {
public:
  MatrixXd() :
    m_data(), m_rows(0), m_cols(0) {}

  MatrixXd(int row, int col) :
    m_data(row*col), m_rows(row), m_cols(col) {}

  double& operator() (int row, int col)
  {
    return m_data[row*m_cols + col];
  }

  double operator() (int row, int col) const
  {
    return m_data[row*m_cols + col];
  }

  std::vector<double> m_data;
  int m_rows;
  int m_cols;
};

On one computer, I have found that:

for Nx6 it was preferable to iterate over the source matrix
for 6xN the opposite
when the first dimension was divisible by 16 (the tile size), the SO tiling variant was better
otherwise the block tiling was better

It is interesting for me to optimize Nx6 size that corresponds to problem that involves N samples and 6 variables.

On another computer, the results are a little bit different that makes me think I have probably overengineered the problem (block tiling seems to be the best overall).

Moreover, on quick-bench, I don't have the same conclusion (block tiling performs the worst).

Any idea how to have a fast matrix transpose that performs well on any matrix size and specifically for matrices of Nx6 size?

How to choose the optimal tile size? I have used 16 experimentally.

I target classical architecture that has 32 kB of L1-cache, 8-way associative and 64 bytes of cache line size.

Full source code and log are here. I use Catch2 for micro-benchmarking.


texts:
I am testing various sorting algorithms. Right now I am testing shell sort, insertion sort and selection sort. I ran all three algorithms on a randomly-generated list of 1000 integers. The selection sort took 41 seconds, insertion sort took 34 seconds and shell sort sort took over 3 minutes. What can I do to improve my implementation?

  public class SortAlgorithm
{
    public void InsertionSort<T>(T[] a) where T : IComparable
    {
        for (int i = 0; i < a.Length; i++)
        { // Exchange a[i] with smallest entry in a[i+1...N).
            int min = i;  // index of minimal entr.
            for (int j = i + 1; j < a.Length; j++)
            {
                if (Less(a[j], a[min]))
                {
                    min = j;
                }
                else if (a.Length < j + 1)
                {

                    a[j + 1] = a[j];
                    a[j] = a[min];
                }
            }
            Show(a);
            Exch(a, i, min);
        }
    }

    public void ShellSort<T>(T[] a) where T : IComparable
    { // Sort a[] into increasing order.
        int N = a.Length;
        int h = 1;
        while (h < N / 3)
        {
            h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ..
        }
        while (h >= 1)
        { // h-sort the array.
            for (int i = h; i < N; i++)
            { // Insert a[i] among a[i-h], a[i-2*h], a[i-3*h]... .
                for (int j = i; j >= h && Less(a[j], a[j - h]); j -= h)
                    Exch(a, j, j - h);
                Show(a);
            }

            h = h / 3;
        }
    }

    public void SelectionSort<T>(T[] a) where T : IComparable
    { // Sort a[] into increasing order.
        int n = a.Length;  // array length
        for (int i = 0; i < n; i++)
        { // Exchange a[i] with smallest entry in a[i+1...N).
            int min = i;  // index of minimal entr.
            for (int j = i + 1; j < n; j++)
                if (Less(a[j], a[min])) min = j;
            Exch(a, i, min);
            Show(a);
        }
    }

    private static void Exch<T>(T[] a, int i, int j) where T : IComparable
    {
        T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    public void Show<T>(T[] a) where T : IComparable
    {            // Print the array, on a single line.
        foreach (T t in a)
        {
            Console.Write(t + " ");
        }
        Console.WriteLine();
    }

    private static bool Less(IComparable v, IComparable w)
    {
        return v.CompareTo(w) < 0;
    }

    public bool IsSorted(IComparable[] a)
    { // Test whether the array entries are in order.
        for (int i = 1; i < a.Length; i++)
            if (Less(a[i], a[i - 1])) return false;
        return true;
    }
}


texts: Better way to code download speed calcuation

texts:
I'm writing a program that downloads stuff from the internet. While the program is working fine, I want to get one critical part reviewed. I use System.Diagnostics.StopWatch object to measure the time taken for the ns (NetworkStream) object to read the bytes in buffer. I then divide the number of elapsed seconds in stopwatch by number of bytes received to calculate the speed of my download in KBPS.

However, this method is giving me some extraordinarily large speeds (in excess of 8000KBPS), whereas I know that my internet bandwidth is not that fast. Is there anything wrong with this method? If not, then what is the correct way of getting the download speed? Here is my code:

while(true) //(bytesToRead>0)
{

    sw.Start();
    int n = ns.Read(buffer, 0, buffer.Length);
    sw.Stop();
    Speed = (float)n / sw.Elapsed.TotalSeconds;

    if (n==0)
        break;

    fs.Write(buffer,0,n);

    BytesRead+=n; //TODO: Persist the bytesRead object somewhere, so that it can be taken back for resumes
    bytesToRead -= n;
    OnProgress(this,new System.EventArgs());
    if (Status == DownloadStatusEnum.Paused) break;
}


texts: String Similarity using fuzzywuzzy on big data

texts:
I have a file in which I was to check the string similarity within the names in a particular column. I use fuzzywuzzy token sort ratio algorithm as it is required for my use case. here is the code, is there a way to speed it up? It is taking a lot of time for 30000 records.

import csv
import itertools
import pandas as pd
from fuzzywuzzy import fuzz

data = pd.read_csv('D:\\Sim_Input.csv')

Dishes = data['Product_Name']

threshold_ratio = 85

with open('D:\\Sim_Score.csv', 'w') as f1:
    writer = csv.writer(f1, delimiter='\t', lineterminator='\n', )
    writer.writerow(['tag4'])
    for str_1, str_2 in itertools.permutations(Dishes, 2):
        list = []
        ratio = (fuzz.token_sort_ratio(str_1, str_2))
        if ratio > threshold_ratio:
            row = (str_1, str_2, ratio)
            list.append(row)
            print(list)
            writer.writerow(list)

I need the output in a csv file with the names of ItemA, ItemB and similarity score, where the similarity should be above 85.


texts:
I implemented the following (what I believe to be) safe Reverse Polish Calculator.

Now I'm using foldM to take advantage of the power of Monads. Previously, I was not.

Can you please critique my code?

import Data.Maybe
import Text.Regex
import Control.Monad
import Network.CGI.Protocol

data Operator = Add | Subtract | Multiply

-- safe Reverse Polish Notation calculator
rpn :: String -> Maybe Double
rpn xs = maybeStringToMaybeDouble result :: Maybe Double
      where result = safeHead $ foldM foldingOp [] $ words xs

--foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a

maybeStringToMaybeDouble :: Maybe String -> Maybe Double
maybeStringToMaybeDouble x = do
      y <- x
      maybeRead y

-- extract maybeHead of Maybe [a]
safeHead :: Maybe [a] -> Maybe a
safeHead m = do
    x <- m -- x has type [a]
    listToMaybe x

foldingOp :: [String] -> String -> Maybe [String]
foldingOp acc s
   | isNumber s        = Just (s : acc)
   | isPlusRegex s     = performOp Add acc
   | isMinusRegex s    = performOp Subtract acc
   | isMultiplyRegex s = performOp Multiply acc
   | otherwise         = Nothing

performOp :: Operator -> [String] -> Maybe [String]
performOp o (x:y:zs) = Just $ (doOp o x y) : zs
performOp _ _        = Nothing

doOp :: Operator -> String -> String -> String
doOp Add a b       = show $ (read b :: Double) + (read a :: Double)
doOp Subtract a b  = show $ (read b :: Double) - (read a :: Double)
doOp Multiply a b  = show $ (read b :: Double) * (read a :: Double)

isNumber :: String -> Bool
isNumber = matches' mkNumberRegex

mkNumberRegex :: Regex
mkNumberRegex = mkRegex "^[0-9]+[.]?[0-9]*$"

isPlusRegex :: String -> Bool
isPlusRegex = matches' mkPlusRegex

isMinusRegex :: String -> Bool
isMinusRegex = matches' mkMinusRegex

isMultiplyRegex :: String -> Bool
isMultiplyRegex = matches' mkMultiplyRegex

mkPlusRegex :: Regex
mkPlusRegex = mkRegex "^[+]$"

mkMinusRegex :: Regex
mkMinusRegex = mkRegex "^[-]$"

mkMultiplyRegex :: Regex
mkMultiplyRegex = mkRegex "^[*]$"

matches' :: Regex -> String -> Bool
matches' r x
   | matchRegex r x == Nothing = False
   | otherwise                 = True


texts:
I did this spider that checks the stock of references list (around 3500 references).

Now the spider takes around 37 seconds to scrap 400 references. The CPU is around 5%, the network card (1Gbps) around 18%. My internet connection is 300Mbps simetric and it's only connected to this computer.

Any idea to improve performance?  Is this a good performance? Maybe ISP router is a bottleneck?

import scrapy
from scrapy.crawler import CrawlerProcess

class Spider(scrapy.Spider):
    name = "Spider"

    start_urls = ['URLS']

    def __init__(self, references=None, *args, **kwargs):
        super(ktmSpider, self).__init__(*args, **kwargs)

    def parse(self, response):
        return scrapy.FormRequest.from_response(
            response,
            formdata={'UserName': 'username', 'Password': 'password'},
            callback=self.after_login
        )

    def after_login(self, response):
        ref = references.pop()
        yield scrapy.Request(url="url" + ref, callback=self.parse_stock)

    def parse_stock(self, response):
        self.f.write(response.selector.xpath('//*[@id="priceDetails"]/form/div[2]/text()').extract_first() + ',')
        self.f.write(response.selector.xpath('//*[@id="priceDetails"]/form/div[8]/div[1]/span/span[2]/text()').extract_first() + ',')
        self.f.write(response.selector.xpath('//*[@id="priceDetails"]/form/div[8]/div[1]/span/span[1]/i/@style').extract_first() + '\n')

        while len(references) > 0:
            ref = references.pop()
            yield scrapy.Request(url="url" + ref, callback=self.parse_stock)

f = open("references.txt")
references = f.read().splitlines()

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
    'LOG_LEVEL': 'INFO',
    'AUTOTHROTTLE_ENABLED': 'True',
    'AUTOTHROTTLE_START_DELAY': '0.1',
    'AUTOTHROTTLE_TARGET_CONCURRENCY': '100'
})

process.crawl(ktmSpider, references=references, stockFile="file.txt")
process.start()


texts:
From the Project Euler challenge series:

  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

The brute force method runs in 1.8s per loop on my machine:

def getGen(n):
    return range(n,-1,-1)

def bruteForce():
    gen = getGen(999)
    sc = maxpalin = 0
    for i in gen:
        for j in gen:
            sc += 1
            prod = i * j
            s = str(prod)
            if s==s[::-1] and prod > maxpalin:
                maxpalin = prod
    print(sc)
    return maxpalin

%timeit bruteForce()

When I initially approached the problem, I tried to use the properties of multiplying 2 different 3-digit numbers to find the solution. This approach, however, takes approximately 16.7s per loop, even though the sc for the bruteForce is 1 million and the sc for Palindrome.main() (see below) is considerably lower at 4536. Why does the Palindrome class run so much slower?

$$(a.b.c) * (x.y.z) = (l.m.n.n.m.l)$$
$$(100a + 10b + c) * (100x + 10y + z) = (100001l + 10010m + 110n)$$
$$(10000ax + 1000ay + 100az) + (1000bx + 100by + 10bz) + (100cx + 10cy + cz) = (100001l + 10010m + 110n)$$
$$10000ax + 1000(ay + bx) + 100(az + by + cx) + 10(bz + cy) + cz = (100001l + 10010m + 1100n)$$
$$10(1000ax + 100(ay + bx) + 10(az + by + cx) + (bz + cy)) + cz = 100001l + 10(1001m + 110n)$$

firstPass
$$10(1000ax + 100(ay + bx) + 10(az + by + cx) + (bz + cy) - 1001m - 110n) = 100001l - cz = 10p \implies 10 \mid 10p$$

secondPass
$$p = 10(100ax + 10(ay + bx) + (az + by + cx - 11n)) + (bz + cy) - 1001m \implies 10 \mid p + 1001m - (bz + cy) = 10q$$

thirdPass
$$q = 10(10ax + (ay + bx)) + (az + by + cx - 11n) \implies 10 \mid q + 11n - (az + by + cx) = 10r$$

main
$$r = 10ax + (ay + bx) \implies 10 \mid r - (ay + bx) = 10s$$

class Palindrome(object):
    def __init__(self):
        self.a = 0
        self.b = 0
        self.c = 0
        self.l = 0
        self.m = 0
        self.n = 0
        self.x = 0
        self.y = 0
        self.z = 0

    def firstPass(self):
        gen = getGen(9)
        for l in gen:
            for c in gen:
                for z in gen:
                    p = 100001 * l - (c * z)
                    if (p % 10):
                        continue
                    self.l = l
                    self.c = c
                    self.z = z
                    yield p / 10

    def secondPass(self, p):
        gen = getGen(9)
        for m in gen:
            for b in gen:
                for y in gen:
                    q = p + (1001 * m) - ((b * self.z) + (self.c * y))
                    if (q % 10):
                        continue
                    self.m = m
                    self.b = b
                    self.y = y
                    yield q / 10

    def thirdPass(self, q):
        gen = getGen(9)
        by = self.b * self.y
        for a in gen:
            for x in gen:
                for n in gen:
                    r = q + (11 * n) - (a * self.z + by + self.c * x)
                    if (r % 10):
                        continue
                    self.a = a
                    self.x = x
                    self.n = n
                    yield r / 10

    def main(self):
        sc = 0
        for p in self.firstPass():
            for q in self.secondPass(p):
                for r in self.thirdPass(q):
                    a = self.a
                    b = self.b
                    x = self.x
                    y = self.y

                    s = r - (a * y + b * x)
                    if s == 10 * a * x:
                        sc += 1
                        m = 100 * a + 10 * b + self.c
                        n = 100 * x + 10 * y + self.z

                        yield m * n
        print(sc)

i = Palindrome()
%timeit (max(i.main()))


texts: Speed up performance of nested for loops to get all related format of all Authors' Books

texts:
This works but is very slow.  I have an Author table that foreign keys to all books by that author.  Each book has a variety of formats it can appear in (html, pdf, etc), which its linked to by its own foreign key.

As the code shows, what I'm doing now is getting all the authors, then looping through to get each book by the author, and looping through those to get all the format types of each book.  If the book does not have all four types, it's appended to a list of dictionaries to be displayed in the template.

Note that checking simply the count of each format would be insufficient, as it's possible a book might have multiple versions of one type; I need to make sure each type appears at least once.

We have tens of thousands of authors, each of which can have up to about 20 books, each of which can have up to about 5-8 formats max.

def missing_book_format_report(request):

    authors = Author.objects.all()
    data = []
    for author in authors:
        books = author.book_set.all()
        for book in books:
            book_info = {
                "book_num": book.num,
                "type": book.short_name,
                "xml": False,
                "pdf": False,
                "html": False,
                "gen_html": False
            }
            book_formats = book.format_set.all()
            for book_format in book_formats:
                format_type = book_format.format_type_cd_id.lower()  # e.g. xml
                book_info[format_type] = True
            if not all([book_info["xml"], book_info["pdf"], book_info["html"], book_info["gen_html"]]):
                data.append(book_info)
    context = {
        'data': data,
        'books': books
    }

    return render(request, 'book-report.html', context)


texts:
I'm going to implement something like the Unity3D component model for my C++ game engine. Please, review my draft of the Component base class:

class Component
{
public:
    template<class T>
    static T* create(void)
    {
        if (Type<T>::id == 0)
            Type<T>::id = ++_idCounter;

        T* component = new T();
        component->_id = Type<T>::id;
        return component;
    }

    template<class T>
    inline bool is(void) const
    {
        return Type<T>::id == _id;
    }

protected:
    Component(void) {}

private:
    static unsigned int _idCounter;
    unsigned int _id;

    template<class T> struct Type { static unsigned int id; };
};

unsigned int Component::_idCounter = 0;
template<class T> unsigned int Component::Type<T>::id = 0;

It has some RTTI-like functionality, and I can use it this way:

class ComponentA: public Component {};
class ComponentB: public Component {};

...

ComponentA* a = Component::create<ComponentA>();
ComponentB* b = Component::create<ComponentB>();

std::cout << a->is<ComponentA>() << std::endl; // 1
std::cout << b->is<ComponentB>() << std::endl; // 1
std::cout << b->is<ComponentA>() << std::endl; // 0
std::cout << a->is<ComponentB>() << std::endl; // 0

And I have a question. How can I prevent any construction of any descendant of Component outside of Component::create?


texts: Communicating with other fragments or to activity

texts:
Android documentation says:

  Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

My question is: Why should Fragments never communicate directly? Because it can cause problems or simply because of "good" code (clean code, maintenance...)?

Fragments communicate directly in my apps and I have not encountered any problem yet. Here an example of how I pass data from an "Event" fragment to a "Event Details" fragment:

public class UpcomingEventsFragment extends Fragment {

    private UpcomingEventsAdapter mAdapter;
    private ListView listview;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_upcomingevents, container, false);
        listview = (ListView) rootView.findViewById(R.id.upcomingevents);
        mAdapter = new UpcomingEventsAdapter(getActivity());
        listview.setAdapter(mAdapter);

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Event event = mAdapter.getItem(position);
                Bundle args = new Bundle();
                args.putString("id", event.getId());

                EventDetailsFragment fragment = new EventDetailsFragment();
                fragment.setArguments(args);
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        return rootView;
    }
}


texts: Ensuring a valid JavaScript string in security-critical application

texts:
I'm writing an application where users can write custom expressions which are then converted to JavaScript functions and executed. The expressions are used for filtering and sorting data from a database and to improve performance I want to be able to run the expressions on my server without worrying about getting hijacked. So the main concern is to ensure that the user cannot do code injection to execute an arbitrary script.

This part of the application makes sure that any string literal present in the user's expression will get converted into a valid JavaScript string literal without any chance of containing malicious code.

In the user's expression, string literal should always match this regex: /"(?:\\"|\\\\|[^"\\])*"/ (or its equivalent with single-quotes). However since the regex pattern isn't evaluated directly by JavaScript, I don't want to rely on it working exactly as I expect, so I double-check it.

function buildString(quote, literal)
{
    quote = String(quote)[0]; // for example `"`
    literal = String(literal); // the user's string literal
    let built = ''; // parsed string

    if (literal[0] !== quote || literal[literal.length-1] !== quote)
        throw new Error(`Unexpected internal error: String literal doesn't begin/end with the right quotation mark.`);

    for (let i = 1; i < literal.length - 1; i++)
    {
        if (literal[i] === "\\")
        {
            i++;
            if (i >= literal.length - 1) throw new Error(`Unexpected internal error: Unescaped backslash at the end of string literal.`);

            if (literal[i] === "\\") built += '\\';
            else if (literal[i] === quote) built += quote;
            else throw new Error(`Unexpected internal error: Invalid escaped character in string literal: ${literal[i]}`);
        }
        else if (literal[i] === quote)
        {
            throw new Error(`Unexpected internal error: String literal contains unescaped quotation mark.`);
        }
        else
        {
            built += literal[i];
        }
    }

    return JSON.stringify(built); // valid JavaScript string literal
}

.

Here are some test cases:

expect( () => buildString(`'`, `'''`  ) ).throws();
expect( () => buildString(`'`, `'\\'` ) ).throws();
expect( () => buildString(`'`, `'\\"'`) ).throws();
expect( () => buildString(`'`, `'\\n'`) ).throws();

expect( () => buildString(`"`, `"""`  ) ).throws();
expect( () => buildString(`"`, `"\\"` ) ).throws();
expect( () => buildString(`"`, `"\\'"`) ).throws();
expect( () => buildString(`"`, `"\\n"`) ).throws();

// null byte
expect(eval( buildString(`'`, `'\n \\\\ \\' " \u0000'`) )).equals(`\n \\ ' " \u0000`);

// unpaired surrogate
expect(eval( buildString(`"`, `"\uD800"`) )).equals(`\uD800`);


texts:
I have a little experience working with .hl7 data (format for transmitting health data), so I decided to try and write an .hl7 parser using fparsec.

A standard .hl7 segment is a single line with:

First 3 chars are the header
Next 5 chars are the separators (typically |^~\&)
Fields / repetitions delimited by pipes

A segment has fields or repetitions (repeating fields).  A field can have components.   A component can have sub-components.

Sample .hl7 message header:

MSH|^~\\&|Location|SendingApp|DateTimeOfMessage

I am looking for feedback on data design (the types) and the functions.

type Subcomponent = {value:string; position:int}
type Component = {subcomponents: Subcomponent list; position:int}
type SingleField = {components: Component list; position:int}
type Field = Repetitions of SingleField list | SingleField of SingleField
type Segment = { name:string; fields:Field list; }
type Hl7Message = { segments:Segment list }

let hl7Seps = "|^~\\&"

let normalChar = noneOf hl7Seps

let unescape c = match c with
                    | 'F' -> '|'
                    | 'R' -> '~'
                    | 'S' -> '^'
                    | 'T' -> '&'
                    | 'E' -> '\\'
                    | c -> c

let escapedChar = attempt (pchar '\\' >>. anyChar |>> unescape .>> skipChar '\\') <|> pchar '\\'

let pHl7Element = manyChars (normalChar <|> escapedChar)

let pcomp = sepBy pHl7Element (pchar '&') |>> (fun vals -> List.mapi (fun i s -> {value = s; position = i}) vals)

let pfield = sepBy pcomp (pchar '^') |>> (fun comps -> List.mapi (fun i c -> {subcomponents = c; position = i}) comps)

let pRepsOrField = sepBy pfield (pchar '~') |>> (fun fields -> match fields.Length with
                                                                | 0 | 1 -> SingleField {components = fields.Item 0; position = 0}
                                                                | _ -> Repetitions (List.mapi (fun i c -> {components = c; position = i}) fields))

let pheader = anyString 3 |>> (fun name -> name)

let pSegment = pipe2 pheader (sepBy pRepsOrField (pchar '|')) (fun name repsOrFields -> {name = name; fields = repsOrFields})

test pSegment "EVN|A&1^B^C|123~456~789"


texts: Javascript Object of Arrays manipulation

texts:
I am writing a function to decode data from a run length encoded format like:

{
  dataGroup: {
    count: [4, 4, 2, 1],
      dataOne: [1, 3, 2, 1],
      dataTwo: [7, -1, 9, 0],
      dataThree: [3, 8, 1, 2]
  }
}

to

{
  groupName: {
    dataOne:   [1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 1],
    dataTwo:   [7, 7, 7, 7,-1,-1,-1,-1, 9, 9, 0],
    dataThree: [3, 3, 3, 3, 8, 8, 8, 8, 1, 1, 2]
  }
}

I have written two solutions to date but feel like there may yet be a better way.

function decode(obj) {

    const arrayLengthN = (N, data=null) => [...Array(N)].map(_ => data);

    const [ group ] = Object.keys(obj);
    const { count, ...data } = obj[group];
    const dataKeys = Object.keys(data);

    // method one

    // output object to be written upon iteration over count and data
    const output = {};

    // populate output with empty arrays to push to
    dataKeys.map(key => output[key] = []);

    // do the decoding
    count
        .map((n, i) => {
            dataKeys
                .map(key => {
                    output[key].push(...arrayLengthN(n, data[key][i]));
                });
        });

    // method two

    const otherMethod = {
        [group]: Object.assign(
            {},
            ...dataKeys.map((key) => {
                return {
                    [key] : count
                        .map((n, i) => dataKeys
                            .map(key => arrayLengthN(n, data[key][i]))
                        )
                        .flat(2)
                };
            })
        )};

    return {[group]: output}
    // or return otherMethod
}

Is there anything wrong with the first method? It feels clunky to create an object, add empty arrays to it, and then mutate that object from within a .map call. That being said, to me it seems far more readable.

Any help or comments much appreciated.

Cheers,

P


texts:
This is an implementation of a practice problem from cprogramming.com:  Temperature Converter Challenge

The problem:

  In this challenge, write a program that takes in three arguments, a start temperature (in Celsius), an end temperature (in Celsius) and a step size. Print out a table that goes from the start temperature to the end temperature, in steps of the step size; you do not actually need to print the final end temperature if the step size does not exactly match. You should perform input validation: do not accept start temperatures less than a lower limit (which your code should specify as a constant) or higher than an upper limit (which your code should also specify). You should not allow a step size greater than the difference in temperatures. (This exercise was based on a problem from C Programming Language).

The code:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

const double LowestLimit = 0;
const double HighestLimit = 50000;
const string LowerLimitMessage = "Please enter a lower limit, limit >= 0: ";

struct UserInputs
{
public:
    double LowerLimit = -1;
    double UpperLimit = -1;
    double StepAmount = -1;
};

stringstream GetSingleInput(const string message)
{
    stringstream returnStream;
    string input;
    cout << message;
    cin >> input;
    returnStream << input;
    return returnStream;
}

UserInputs GetUserInputs()
{
    UserInputs parsedInputs;
    auto LowerLimitStream = GetSingleInput(LowerLimitMessage);

    while (!(LowerLimitStream >> parsedInputs.LowerLimit) || parsedInputs.LowerLimit < LowestLimit)
    {
        cout << "Invalid Lower Limit!\n";
        LowerLimitStream = GetSingleInput(LowerLimitMessage);;
    }

    stringstream UpperLimitMessage;
    UpperLimitMessage << "Please enter an upper limit, limit > "
        << parsedInputs.LowerLimit
        << ", limit <= "
        << HighestLimit
        << ": ";

    auto UpperLimitStream = GetSingleInput(UpperLimitMessage.str());

    while (!(UpperLimitStream >> parsedInputs.UpperLimit)
        || parsedInputs.UpperLimit > HighestLimit
        || parsedInputs.UpperLimit <= parsedInputs.LowerLimit)
    {
        cout << "Invalid Upper Limit!\n";
        UpperLimitStream = GetSingleInput(UpperLimitMessage.str());
    }

    stringstream stepMessage;
    stepMessage << "Please enter a step amount , step > "
        << LowestLimit
        << ", step <= "
        << (parsedInputs.UpperLimit - parsedInputs.LowerLimit)
        << ": ";

    auto stepStream = GetSingleInput(stepMessage.str());
    while (!(stepStream >> parsedInputs.StepAmount)
        || parsedInputs.StepAmount <= 0
        || parsedInputs.StepAmount > parsedInputs.UpperLimit - parsedInputs.LowerLimit)
    {
        cout << "Invalid Step Amount!\n";
        stepStream = GetSingleInput(stepMessage.str());
    }

    return parsedInputs;
}

double CelsiusToFarenheit(const double celsius)
{
    return celsius * 33.8;
}

int main()
{
    auto inputs = GetUserInputs();

    cout << "Celsius" << "\t\t\t" << "Farenheit" << "\n";
    cout << "----------" << "\t\t" << "----------" << "\n";
    cout.precision(9);
    while (inputs.LowerLimit <= inputs.UpperLimit)
    {
        cout << fixed << inputs.LowerLimit << "\t\t" << CelsiusToFarenheit(inputs.LowerLimit) << "\n";
        inputs.LowerLimit += inputs.StepAmount;
    }

    return 0;
}

I'm a C# developer who has been self learning C++. As a result I am likely making simple mistakes on structural design which don't feel odd in C#.

Any commentary would be appreciated, especially as to whether or not my method of checking the input is inefficient.


texts:
I have created mini-opengl program that draw simple chess board on screen by using SFML windows model only. The program runs fine. The main purpose of this program is to keep it as simple as possible and it is not rely on any of OpenGL helper functions like glOrtho or gluOrtho2D for converting coodinates. Also, it is not using any external library for loading textures.

I would like to know how can I improve it?

#include <SFML/OpenGL.hpp>
#include <SFML/Window.hpp>
#include <vector>

int main()
{
    sf::Window window(sf::VideoMode(800, 600), "OpenGL");

    // Set Orthographic
    auto width = static_cast<float>(window.getSize().x);
    auto height = static_cast<float>(window.getSize().y);
    auto a = 2.f / width;
    auto b = 2.f / height;
    std::vector<float> matrix =
    {
         a , 0, 0, 0,
         0, -b, 0, 0,
         0,  0, 1, 0,
        -1,  1, 0, 1
    };

    // Set the projection matrix
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(matrix.data());

    // Initialize vertices:
    std::vector<float> vertices =
    {
        0,     0,
        0,     height,
        width, height,
        width, 0
    };

    // Initialize colors
    std::vector<float> colors =
    {
        1, 0, 0,
        0, 1, 0,
        0, 0, 1,
        0, 1, 1
    };

    // Initialize texture virtice
    std::vector<float> texCoord =
    {
        0, 0,
        0, 1,
        1, 1,
        1, 0
    };

    // Create texture: simple chess board 8x8
    auto numRows = 8u;
    auto numCols = 8u;
    auto character = 172u;
    auto remain = 255u - character;
    std::vector<unsigned char> texture(numCols * numRows);
    for (auto i = 0u; i < texture.size(); ++i)
        texture[i] = ((i + (i / numCols)) % 2) * remain + character;

    // Upload to GPU texture
    unsigned textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, numCols, numRows, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, texture.data());

    // Initialize clear colors
    glClearColor(0.f, 0.f, 0.f, 1.f);

    // Activate necessary states
    glEnable(GL_TEXTURE_2D);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, vertices.data());
    glColorPointer(3, GL_FLOAT, 0, colors.data());
    glTexCoordPointer(2, GL_FLOAT, 0, texCoord.data());

    while (window.isOpen())
    {
        sf::Event windowEvent;
        while (window.pollEvent(windowEvent))
        {
            if (windowEvent.type == sf::Event::Closed)
                window.close();
        }

        // render
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_QUADS, 0, 4);

        window.display();
    }
}


texts: How do I dynamically create Python unit tests in a readable way?

texts:
I have Django unit tests that are pretty much the following format:

class Tests(unittest.TestCase):
    def check(self, i, j):
        self.assertNotEquals(0, i-j)

for i in xrange(1, 4):
    for j in xrange(2, 6):
        def ch(i, j):
            return lambda self: self.check(i, j)
        setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))

A function that returns a lambda that is bound as a method via setattr, which is an eyesore and as unreadable as you can get in Python without really trying to obfuscate.

How can I achieve the same functionality in a more readable way, preferably without lambda?

For reference, see the original SO question about the subject.


texts:
I'm writing a function that takes between one and three arguments (function callback [, number limit] [, regexp pattern]). Since the second two are both optional, I need to determine which argument is being passed when the function is supplied with only two. Below is my solution, but it seems overly verbose. Is there a cleaner way to do this?

  var get_queued_pages = function() {
    if(arguments>0){
        var callback = arguments[0];
        if(arguments.length == 3){ //all arguments are being passed
        var limit    = arguments[1];
        var pattern  = arguments[2];
        }
        else if(arguments.length == 2){ //only 2 arguments passed
        if(typeof(arguments[1]) == "number"){ //check if the second one is limit or pattern
            var limit = arguments[1];//no pattern defined; second argument is limit
        }
        }
        else{
        var limit = 1;
        }
    }
    //do stuff

}


texts: Median of two sorted arrays (optimal runtime)

texts:
I've written a solution to the leetcode problem Median of Two Sorted arrays. The solution I anticipated coming up with initially was going to features some kind of binary search on both arrays based on the range of numbers (given that the question calls for a runtime of O(log (m+n))).

Along the way, I thought of another, simpler solution that featured averaging the largest number of both arrays (the last element of one of the arrays) and the smallest number of the two arrays (index 0 of one of the arrays). I also include a number of if statements to handle the possible different array lengths that could be passed in. I'm particularly interested in the approach of this solution since it would have a faster runtime than what was suggested.

This solution surprisingly passes 2056 / 2084 of the test cases. It fails, however, on the input arrays of [3],[-2,-1], which leads me to believe that the code will fail only when there exist negative numbers in either array.  Is this the case, or is it just that the test cases used for the question aren't wide-ranging enough?

class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        if len(nums1) == 0 and len(nums2) == 0:
            return None
        if len(nums1) == 0 and len(nums2) > 0:
            if len(nums2) == 1:
                return nums2[0]
            elif len(nums2) > 1 and len(nums2) % 2 == 1:
                lo,hi = 0,len(nums2)-1
                mid = (hi+lo)//2
                return nums2[mid]
            elif len(nums2) > 1 and len(nums2) % 2 == 0:
                lo,hi = 0,len(nums2)-1
                mid = (hi+lo)//2
                return (nums2[mid] + nums2[mid+1])/2

        if len(nums1) > 0 and len(nums2) == 0:
            if len(nums1) == 1:
                return nums1[0]
            elif len(nums1) > 1 and len(nums1) % 2 == 1:
                lo,hi = 0,len(nums1)-1
                mid = (hi+lo)//2
                return nums1[mid]
            elif len(nums1) > 1 and len(nums1) % 2 == 0:
                lo,hi = 0,len(nums1)-1
                mid = (hi+lo)//2
                return (nums1[mid] + nums1[mid+1])/2

        l1A,l2A,l1B,l2B = 0,0,len(nums1)-1,len(nums2)-1
        arrBeg = nums1[l1A] if nums1[l1A] <nums2[l2A] else nums2[l2A]
        arrEnd = nums1[l1B] if nums1[l1B] > nums2[l2B] else nums2[l2B]
        target = (arrEnd+arrBeg)/2
        return target


texts:
My Problem

I have a library containing business logic which is being used from 3 different projects:

Website
Local WPF Application
WCF Service

The library uses Entity Framework and a connection string which is read out of config on first use and saved in a static variable. (The config file for all 3 consumer projects have the same keys)

Now I've changed the WCF Service, so that one service can serve different users, meaning different databases. Of course now the static connection string only holds one connection string so I need a concept of changing the used connection string depending on who called the service. Along with the connection string I have some more user-specific data which I stored in a static global class.

My Solution

On the WCF Service I use a custom authorization policy which changes the threads principal user to my own custom identity. On each call the service authenticates the caller, and changes the threads identity to the specific object which now contains the connection string and all the specific data previously stored in static global. If there is no thread principal set (or at least not from the type I expected), I assume the caller is not the service but the website or local application. Then I store the Identity in static variable like I did before.

My Code

/// <summary>
/// Represents the settings for the current context (user database).
/// Usually for web and app this is always the database defined in config-file and therefor stored in static
/// For WCF service the context can vary depending on the caller if the current principal is set
/// </summary>
public class ContextIdentity : IIdentity
{
    public static ContextIdentity LocalIdentity;
    public static ContextIdentity Current
    {
        get
        {
            if (Thread.CurrentPrincipal.Identity is ContextIdentity)
            {
                // Return the threads Context
                return Thread.CurrentPrincipal.Identity as ContextIdentity;
            }
            else
            {
                // Return the Local context
                if (LocalIdentity == null)
                {
                    LocalIdentity = new ContextIdentity();
                }
                return LocalIdentity;
            }
        }
    }

    public ContextIdentity()
    {
        // Load from File
        _name = "Default";
        Server = ConfigurationManager.AppSettings["DatabaseServer"];
        Database = ConfigurationManager.AppSettings["DatabaseName"];
        User = ConfigurationManager.AppSettings["DatabaseUser"];
        Password = ConfigurationManager.AppSettings["DatabasePass"];
        IntegratedSecurity = "True".Equals(ConfigurationManager.AppSettings["DatabaseIntegratedSecurity"]);
    }

    public ContextIdentity(string contextName, string server, string database, string user, string password, bool integratedSecurity)
    {
        // Load from File
        _name = contextName;
        this.Server = server;
        this.Database = database;
        this.User = user;
        this.Password = password;
        this.IntegratedSecurity = integratedSecurity;
    }

    #region Context Data Connection

    public string Server { get; set; }

    public string Database { get; set; }

    public string User { get; set; }

    public string Password { get; set; }

    public bool IntegratedSecurity { get; set; }

    // Other stuff needed...

}


texts:
I'm trying to create a custom "mongodb perl wrapper".
I created the following perl module, which local on my machine runs.
My questions to the community are:

Would you create the module different?
Do you have improvements or adaptations to create the module better?

Code:

package MyMongo;

use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
use MongoDB;

$VERSION     = 1.00;
@ISA         = qw(Exporter);
@EXPORT      = qw();
@EXPORT_OK   = qw();
%EXPORT_TAGS = ( DEFAULT => [qw()],
                 Both    => [qw()]);

sub new {
    my ($class, $args) = @_;
    my $self = {
        host     => $args->{host} || 'localhost',
        port     => $args->{port} || '27017',
        database => $args->{database} || '',
        connection => $class->_set_connection(),
    };
    return bless $self, $class;
}

sub _set_connection {
    my $self = shift;
    my $client = MongoDB->connect('mongodb://localhost');
    return $client;
}

sub get_database_names {
    # Lists all databases on the mongo server
    my $self = shift;
    return  $self->{connection}->database_names;
}

sub get_database {
    # Returns a MongoDB::Database instance for database with the given $name
    my ($self, $dbname) = @_;
    return $self->{connection}->get_database($dbname);
}

sub authenticate {
    my ($self, $args) = @_;
    $self = {
        dbname => $args->{dbname},
        user => $args->{user},
        password => $args->{password}
    };
    $self->{connection}->authenticate($self->{dbname}, $self->{user}, $self->{password});
}
1;


texts: Reordering a list from the ends towards the middle

texts:
let  shuffley (numbers:int list) =
    let rec loop numbers acc =
        match numbers with
        | head::tail -> loop (List.rev(tail)) (head::acc)
        | [] -> List.rev(acc)
    loop numbers []
shuffley [1;2;3;4;5;6;7;8]

I am trying to practice some F# and I was wondering if could be a good example of tail recursion or this is just some nonsense.


texts: Refactor highlight matched word in string

texts:
I have following method which highlight matched word in text:

# Hightlight matched term
#
# Ex(for term: some):
#   "Some CEO Event"
#
def highlight_matched(matched_word, text)
  regex = matched_word.gsub(/\*|\"|\'/, "")
                       .split(" ")
                       .map { |s| "\\b#{s}" }.join('|')

  text.gsub(/(#{regex})/i, '\1')
end

Is there a better solution for that?

I am using it here:

"%s %s" %[highlight_matched(title[0..70]), content_tag(:span, caption, class: 'search-type')]


texts:
Could you please critisize the logger class below? Can it be used in a multi threaded web environment? If not how can I improve it? Is there anything wrong with locking in WriteToLog method or multithreading in FlushLog method?

public class Logger
{
    private static Logger instance;
    private static Queue<LogData> logQueue;
    private static string logDir = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["LogDirectory"]);
    private static string logFile = "log.txt";
    private static int maxLogAge = Int32.Parse(ConfigurationManager.AppSettings["LogMaxAge"]);
    private static int queueSize = Int32.Parse(ConfigurationManager.AppSettings["LogQueueSize"]);
    private static DateTime LastFlushed = DateTime.Now;

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Logger();
                logQueue = new Queue<LogData>();
            }
            return instance;
        }
    }

    public void WriteToLog(string message)
    {
        lock (logQueue)
        {
            LogData logEntry = new LogData(message);
            logQueue.Enqueue(logEntry);

            if (logQueue.Count >= queueSize || DoPeriodicFlush())
            {
                FlushLog();
            }
        }
    }

    private bool DoPeriodicFlush()
    {
        TimeSpan logAge = DateTime.Now - LastFlushed;
        if (logAge.TotalSeconds >= maxLogAge)
        {
            LastFlushed = DateTime.Now;
            return true;
        }
        else
        {
            return false;
        }
    }

    private void FlushLog()
    {
        System.Threading.ThreadPool.QueueUserWorkItem(q => {
            while (logQueue.Count > 0)
            {
                LogData entry = logQueue.Dequeue();
                string logPath = logDir + entry.LogDate + "_" + logFile;

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true, System.Text.Encoding.UTF8))
                {
                    file.WriteLine(string.Format("{0}\t{1}", entry.LogTime, entry.Message));
                }
            }
        });
    }

    ~Logger()
    {
        FlushLog();
    }
}

public class LogData
{
    public string Message { get; set; }
    public string LogTime { get; set; }
    public string LogDate { get; set; }

    public LogData(string message)
    {
        Message = message;
        LogDate = DateTime.Now.ToString("yyyy-MM-dd");
        LogTime = DateTime.Now.ToString("HH:mm:ss.fff tt");
    }
}

Thanks in advance,


texts:
hi guys this script recursively searches for files with a certain extension and possibly in a directory passed by the terminal ....(In case no directory has been passed, search from the current one) I believe it works correctly but I wanted to ask you if you noticed any flaws and report them to me or just tell me that everything is ok ...thanksss

 #include<stdio.h>
 #include<sys/stat.h>
 #include<errno.h>
 #include<stdlib.h>
 #include<dirent.h>
 #include<stdarg.h>
 #include<limits.h>
 #include<string.h>
 #include<time.h>

 char * scrivi(const char * a, char * B) {

 char *targetdir = malloc(2048);
 strcpy(targetdir,a);
 strcat(targetdir,"/");
 strcat(targetdir,B);
 return targetdir;
 }

 void ricor1(const char estensione[],const char nomedirectory[]){

 struct stat attr;
 char dbuf[PATH_MAX+1];
 DIR * fh ;
 struct dirent *fdata;
 struct stat buf;

 if((fh=opendir(nomedirectory))==NULL){
 perror("ERRORE 1");
 exit(errno);
 }

 while((fdata = readdir (fh))!=NULL){
 if(strcmp(fdata->d_name,".")==0){
 continue;
 }

 if(strcmp(fdata->d_name,"..")==0){
 continue;
  }

 char *percorso;
 percorso = scrivi(nomedirectory,fdata->d_name);
 if (fdata->d_type==DT_DIR){

 ricor1(estensione,percorso);
  }
 if (fdata->d_type == DT_REG && strstr(fdata->d_name, estensione)) {

realpath(percorso, dbuf);
printf("[%s]", dbuf);

stat(percorso, &attr);

printf("%s\n", ctime(&attr.st_mtime));

 }

free(percorso);
 }
closedir(fh);
 }

int main(int argc, char *argv[]) {

if(argc==3){

printf("Checking existence directory.. \n");

DIR* dir=opendir(argv[2]);

if(dir){
closedir(dir);
ricor1(argv[1],argv[2]);

 }

else if (ENOENT==errno){

printf("Directory doesn't exist\n");
  }

else{

printf("error");

     }
 }

else if(argc==2){

ricor1(argv[1],"./");

  }
 }


texts: Binary search using recursion, iteration, shifted array

texts:
Interview  question some engineer, asked me to write binary search in 2 ways,
Also asked me to write binary search on a shifted array (10 20 1 2 3 4).
Wrote that and then asked me to find the offset of the array in log n.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class BinarySearch
    {
        public BinarySearch()
        {
            int[] array = new int[10] { 5, 6, 7, 8, 9, 10, 12, 15, 20, 30 };
            int numberToFind = 10;
            int index = FindIndexRecursive(numberToFind, array, 0, array.Length - 1);
            Console.WriteLine("the number " + numberToFind + "is located at index: " + index);
            index = FindIndexIterative(numberToFind, array, 0, array.Length - 1);
            Console.WriteLine("the number " + numberToFind + "is located at index: " + index);
            int[] shiftedArray = new int[6]{10, 20, 1, 2, 3 ,4};

            index = FindShiftedArray(numberToFind, shiftedArray, 0, array.Length - 1);
        }

        private int FindShiftedArray(int numberToFind, int[] shiftedArray, int indexMin, int indexMax)
        {
            //we find the pivot and from there do a binary search
            int pivot = FindPivot(shiftedArray, 0, shiftedArray.Length - 1);
            //the pivot acts like the first slicing of the arrays
            if (shiftedArray[pivot] == numberToFind)
                return pivot;
            if (shiftedArray[0] <= numberToFind)
            {
                return FindIndexRecursive(numberToFind,shiftedArray, 0, pivot - 1 );
            }
            else
            {
                return FindIndexRecursive(numberToFind,shiftedArray, pivot + 1, shiftedArray.Length - 1 );
            }
        }

        private int FindPivot(int[] array, int indexMin, int indexMax)
        {

            if (indexMax < indexMin)
            {
                return -1;
            }
            if (indexMax == indexMin)
            {
                return indexMin;
            }
            int mid = (indexMin + indexMax)/2;   /*low + (high - low)/2;*/
            if (mid < indexMax && array[mid] > array[mid + 1])
            {
                return mid;
            }
            if (mid > indexMin && array[mid] < array[mid - 1])
            {
                return (mid-1);
            }
            if (array[indexMin] >= array[mid])
            {
                return FindPivot(array, indexMin, mid-1);
            }
            else
            {
                return FindPivot(array, mid + 1, indexMax);
            }
}

        public int FindIndexRecursive(int numberToFind, int[] array, int indexMin, int indexMax)
        {
            if (indexMin > indexMax)
            {
                return -1;
            }

            int mid = ((indexMax - indexMin) / 2 ) + indexMin;

            if (array[mid] < numberToFind)
            {
               return FindIndexRecursive(numberToFind, array, mid, indexMax);
            }
            else if (numberToFind < array[mid])
            {
                return FindIndexRecursive(numberToFind, array, indexMin, mid);
            }
            else
            {
                return mid;
            }
        }

        public int FindIndexIterative(int numberToFind, int[] array, int indexMin, int indexMax)
        {
            while (indexMin < indexMax)
            {
                int mid = ((indexMax - indexMin) / 2) + indexMin;
                if (array[mid] < numberToFind)
                {
                    indexMin = mid;
                }
                else if (numberToFind < array[mid])
                {
                    indexMax = mid;
                }
                else
                {
                    return mid;
                }
            }
            return -1;
        }
    }
}


texts: purrr::partial() but keeping function signature

texts:
I quite like purrr::partial(), which allows us to easily create partial functions. However, the partial function loses its remaining arguments from its signature (replaced with ...):

f <- function(x, y) {
  print(x)
  print(y)
  return(invisible())
}

ff <- purrr::partial(f, y = 1)

ff(2)
#> [1] 2
#> [1] 1

ff
#> <partialised>
#> function (...)
#> f(y = 1, ...)

So when developing and trying to remember the positions or names of the remaining arguments for the partial function, we're forced to check the original function instead. So I decided to create my own version which keeps the arguments:

partialize <- function(.f, ...)
{
  dots <- c(...)
  dotsNames <- names(dots)
  symbols <- rlang::syms(dotsNames)

  new.f <- .f

  args <- rlang::fn_fmls(new.f)
  args[names(dots)] <- NULL
  rlang::fn_fmls(new.f) <- args

  rlang::fn_body(new.f) <- rlang::expr({
    !!!mapply(rlang::call2, symbols, dots, MoreArgs = list(.fn = "<-"))
    !!rlang::fn_body(new.f)
  })

  return(new.f)
}

This function performs basically like purrr::partial, but keeps argument names.

f <- function(a, b, d) {
  print(paste(a, b, d))
}

x <- partialize(f, a = 1, d = 3)

x
#> function (b)
#> {
#>     a <- 1
#>     d <- 3
#>     {
#>         print(paste(a, b, d))
#>     }
#> }

x(2)
#> [1] "1 2 3"

Note how inspecting x shows its remaining argument b.

This method is different from purrr::partial in that arguments are eagerly evaluated. It also doesn't have a bug found in how purrr::partial handles invisible returns (though I'm sure you all will find plenty of others!).

z <- 1
purrrf <- purrr::partial(f, d = z)
myf <- partialize(f, d = z)

purrrf(1, 2)
#> [1] "1 2 1"
#> [1] "1 2 1"
myf(1, 2)
#> [1] "1 2 1"

z <- 2
purrrf(1, 2)
#> [1] "1 2 2"
#> [1] "1 2 2"
myf(1, 2)
#> [1] "1 2 1"  # kept z = 1

purrrf
#> <partialised>
#> function (...)
#> f(d = z, ...)

myf
#> function (a, b)
#> {
#>     d <- 1
#>     {
#>         print(paste(a, b, d))
#>     }
#> }
#> <bytecode: 0x000000000806f8d8>

A big drawback I've found with partialize is that it doesn't work with generic functions (i.e. those whose body is merely UseMethod(...)) with default values for their arguments. Since it sets the arguments as variables in its own environment instead of calling the original function with the arguments as actual arguments, the UseMethod(...) call doesn't catch the arguments.

partialize(mean, na.rm = TRUE)
function (x, ...)
{
    na.rm <- TRUE
    {
        UseMethod("mean")
    }
}

As always, happy for any and all comments on the code, and if anyone can figure out how to allow for lazy evaluation (so as to keep in line with purrr::partial), that'd be great.

To be clear: partialize is a function to be included in an in-house utility package, and is therefore somewhat generic. The function f above is merely a placeholder demonstrating partialize's functionality, but the question here is essentially about how partialize itself has been written, whether it can be improved (by adding lazy evaluation or any other way you see fit) and if it has any drawbacks I haven't realized versus purrr::partial.


texts: Initializing complex constant in Constants interface

texts:
I'm being forced to use the common anti-pattern of a public interface Constants which many classes in this project implement.  Long story short, I need to have a List constant which is pre-populated with values.  Normally I would do this like so:

public static final List<String> MY_CONSTANT = new ArrayList<String>();
static {
    MY_CONSTANT.add("foo");
    MY_CONSTANT.add("bar");
    // ...
}

Unfortunately, I can't use static initializers in an interface.  So after much frustration, I finally have my implementation as follows:

public static final List<String> MY_CONSTANT = new ArrayList<String>() {
    private static final long serialVersionUID = 1898990046107150596L;
    {
        add("foo");
        add("bar");
        // ...
    }
}

I hate the fact that I've made an anonymous extension like this and it makes me cringe.  Are there any better techniques I can use to accomplish this?  Changing the Constants file to a class instead of an interface isn't an option.  As I said, I'm just retouching a large, pre-existing code base.


texts: Faster solution for data grouping to determine highest frequency than iteration with for loops

texts:
The code below allows me to determine what the most common main dish and the most common method of preparation for the most common main dish, for each US Region. It uses data obtained from 'thanksgiving-2015-poll-data.csv' which can be found on (GitHub).

I believe that a pivot_table might offer a more efficient method of getting the same information, but I can not figure out how to do so. Can anyone offer any insight? Here's the code I used to get this information which works but I feel is not the best (fastest) method for doing so.

import pandas as pd

data = pd.read_csv('thanksgiving-2015-poll-data.csv', encoding="Latin-1")
regions = data['US Region'].value_counts().keys()
main_dish = data['What is typically the main dish at your Thanksgiving dinner?']
main_dish_prep = data['How is the main dish typically cooked?']
regional_entire_meal_data_rows = []

for region in regions:
    is_in_region = data['US Region'] == region
    most_common_regional_dish = main_dish[is_in_region].value_counts().keys().tolist()[0]
    is_region_and_most_common_dish = (is_in_region) & (main_dish == most_common_regional_dish)
    most_common_regional_dish_prep_type = main_dish_prep[is_region_and_most_common_dish].value_counts().keys().tolist()[0]
    regional_entire_meal_data_rows.append((region, most_common_regional_dish, most_common_regional_dish_prep_type))

labels = ['US Region', 'Most Common Main Dish', 'Most Common Prep Type for Main Dish']
regional_main_dish_data = pd.DataFrame(regional_entire_meal_data_rows, columns=labels)

full_meal_message = '''\n\nThe table below shows a breakdown of the most common
full Thanksgiving meal broken down by region.\n'''
print(full_meal_message)
print(regional_main_dish_data)


texts:
This is my first try with Python. I wanted to parse some Log4J so I thought it a good opportunity to write my first Python program.

The format of the logs I deal with are simply like [INFO BLA 08:00:00] Blabla. Most of the time there are single lines  like the above; but sometimes, there is a stack trace logged, so a logical "line" is longer than a physical line. Each "logical" line starts with the character [.

So I came up with

#!/usr/bin/env python

import sys
from collections import namedtuple

Logline = namedtuple("Logline", "level timestamp message")

def apply_filter(current_log_line, filtered_lines):
    parsed_line = parse_line(current_log_line)
    if filter(parsed_line):
        filtered_lines.append(parsed_line)

def get_filtered_lines(source):
    filtered_lines = []
    line_buffer = ""
    for line in source:
        if line.startswith('[') and line_buffer:
            apply_filter(line_buffer, filtered_lines)
            line_buffer = ""
        line_buffer += line
    apply_filter(line_buffer, filtered_lines)
    return filtered_lines

def parse_line(log_line):
    prefix, message = log_line.split("]", 1)
    level, timestamp = parse_prefix(prefix)
    return Logline(level, timestamp, message)

def parse_prefix(prefix):
    prefix = prefix.strip("[]")
    tokens = prefix.split(" ")
    level = tokens[0]
    timestamp = tokens[-1]
    return level, timestamp

def filter(log_line):
    return log_line.level == "ERROR" and log_line.timestamp > "07:00:00"

def console_out(lines):
    for line in lines:
        print("{}{}".format(line.timestamp, line.message.rstrip("\n")))

def main():
    if len(sys.argv) != 2:
        print("Usage: {0} $logfile".format(sys.argv[0]))
    else:
        file_name = sys.argv[1]
        with open(file_name) as file:
            console_out(get_filtered_lines(file))

if __name__ == '__main__':
    main()

Feel free to comment.

One thing, what bugs me is the apply_filter function, which does too many things at once. But I have have no solution for that.


texts: Reading in data from a file and then assigning vals and then creating object

texts:
So I have some code which I created from the top of my head. But in all honesty I know it can't be the most efficient way of doing it.

I have some data in a file all positioned 5 values per line separated by commas (one line will be a specific object) dependent on the name of the item.

I know this can't be the best way of doing it as I have done the exact same code in java with less than half the lines.

PS: I started learning C++ this week, so don't be too hard on me!

Here is my code:

ifstream inFile;
inFile.open("inventory.txt");

// check for error
if(inFile.fail()){
    cerr << "Error opening file" << endl;
    exit(1);
}

InventoryLinkedList list;
string line;
int counter =0;
while(getline(inFile, line)){
    stringstream linestream(line);
    string value;
    int i = 0;
    string type;
    string code;
    int count;
    int price;
    string other;
    while(getline(linestream,value,',')){
        if(i==0){
            cout<< "Type " << value << endl;
            type = value;
        }
        else if(i==1){
            cout<< "Code " << value << endl;
            code = value;
        }
        else if (i==2){
            cout << "Count " << value << endl;
            count = atoi(value.c_str());
        }
        else if (i ==3){
            cout << "Price " << value << endl;
            price = atoi(value.c_str());
        }
        else if(i ==4){
            cout << "Other " << value << "\n"<< endl;
            other = value;
        }
        i++;
        if(i ==5){
            StockItem *t;
            if(type == "transistor"){
                t = new Transistor(code,count,price,other);
            }else if (type == "IC"){
                t = new IC(code,count,price,other);
            }else if (type == "resistor"){
                t = new Resistor(code,count,price,other);
            }else if (type == "capacitor"){
                t = new Capacitor(code,count,price,other);
            }else{
                t = new Diode(code,count,price,other);
            }
            list.tailAppend(t);
            //counter++;

        }
    }
}


texts: Creating custom objects with custom properties using generics

texts:
I have two base classes: City and Building:

public class City
{
    public string Name { get; set; }
    public double Area { get; set; }
}

public class Building
{
    public string Name { get; set; }
    public double Area { get; set; }
    public int Stories { get; set; }
}

With two classes that inherit from Building, with their own Id property:

public class MyBuilding : Building
{
    public int MyId { get; set; }
}

public class HisBuilding : Building
{
    public int HisId { get; set; }
}

And two classes that inherit from City, with their own Id and IEnumerable<Building> properties:

public class MyCity : City
{
    public int MyId { get; set; }
    public IEnumerable<MyBuilding> Buildings { get; set; }
}

public class HisCity : City
{
    public int HisId { get; set; }
    public IEnumerable<HisBuilding> Buildings { get; set; }
}

Below is a method I've created that returns a KeyValuePair<City, Building> using generics:

public static KeyValuePair<TCity, IEnumerable<TBuilding>> GetData<TCity, TBuilding>()
    where TCity : City, new()
    where TBuilding : Building, new()
{
    TCity city = new TCity();
    IEnumerable<TBuilding> buildings = new List<TBuilding>();
    return new KeyValuePair<TCity, IEnumerable<TBuilding>>(city, buildings);
}

And in my Main method I've logic that instantiates a specific City object based on a user's input.

int input = -1;
string strInput = Console.ReadLine();
int.TryParse(strInput, out input);
string json = string.Empty;
switch (input)
{
    case 1:
        KeyValuePair<MyCity, IEnumerable<MyBuilding>> myCity
            = GetData<MyCity, MyBuilding>();
        MyCity my = myCity.Key;
        my.MyId = 1;
        my.Buildings = myCity.Value;
        json = JsonConvert.SerializeObject(my, Formatting.Indented);
        break;

    default:
        KeyValuePair<HisCity, IEnumerable<HisBuilding>> hisCity
            = GetData<HisCity, HisBuilding>();
        HisCity his = hisCity.Key;
        his.HisId = 2;
        his.Buildings = hisCity.Value;
        json = JsonConvert.SerializeObject(his, Formatting.Indented);
        break;
}
Console.WriteLine(json);
Console.ReadLine();

The above generic method is just something I cobbled together in the last half hour, but I'm wondering if there is a more efficient way of creating these custom objects of mine, especially when each City has its own, different IEnumerable<Building> property.

EDIT

Here is the code I have for building the IEnumerable inside my GetData method:

public static IEnumerable<TBuilding> GetBuildingData<TBuilding>()
    where TBuilding : Building, new()
{
    DataTable table;
    string myConnectionString = @"Data Source=(LocalDb)\MSSQLLocalDb;Initial Catalog=Test;Integrated Security=True;";
    List<TBuilding> buildings = new List<TBuilding>();
    using (SqlConnection connection = new SqlConnection(myConnectionString))
    {
        using (SqlCommand command = new SqlCommand("[dbo].[GetListData]", connection) { CommandType = CommandType.StoredProcedure })
        {
            connection.Open();
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {
                table = new DataTable();
                adapter.Fill(table);
            }
            connection.Close();
        }
    }
    foreach (DataRow row in table.Rows)
    {
        TBuilding building = new TBuilding();
        building.Area = Convert.ToDouble(row["Area"]);
        building.Name = row["Name"].ToString();
        building.Stories = Convert.ToInt32(row["Stories"]);
        buildings.Add(building);
    }
    return buildings;
}


texts: Getting and checking value from a mixed object array HTTP endpoint

texts:
I try to get location data by a external HTTP call. For this API, any part in the data can be missing. Initially I wrote the following code to check whether data.res.accounts[0].contacts[0].location exists:
const getLocation = async () => {
  const data = await fetchLocation();
  if (
    data == null
    data.res == null ||
    data.res.accounts == null ||
    data.res.accounts[0] == null ||
    data.res.accounts[0].contacts == null ||
    data.res.accounts[0].contacts[0] == null ||
    data.res.accounts[0].contacts[0].location == null
  ) {
    return null;
  }
  return data.res.accounts[0].contacts[0].location;
}

I have tried to simplify the mixed object and array code.
One way of doing this is using JavaScript's new conditional operator ?..
For example if they are all objects then I can use something like:
if (data?.res?.account?.contact?.location == null) {
  return null;
}

However my data is mixed with arrays and objects. This is the best I've come up with:
if (
  data?.res?.accounts == null ||
  data.res.accounts[0]?.contacts == null ||
  data.res.accounts[0].contacts[0]?.location == null
) {
  return null;
}

Can I simplify it further?


texts: Computing the difference of the cross-totals of the diagonals of a matrix

texts:
I have solved a seemingly easy problem:

  Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix  is shown below:
$$\begin{bmatrix} 1\, 1\, 1 \\ 2 \, 3\, 3 \\ 0\,1\,0\end{bmatrix}$$

The left-to-right diagonal = \$0+3+1=4\$. The right to left diagonal \$1+3+0=4\$. Their absolute difference is \$0\$.

However, I am a beginner in C and had some troubles. It took me way too long :D. Also, I tried to abstract the problem on a higher level - which does not mean it is high. However, I am not sure how far I should abstract the problem in such challenges.

How well/bad is this code written?
Is the code abstract enough?
How can you solve such challenges more quickly?

int addDiagonal(int from_X,int to_X,int from_Y, int to_Y, int** arr){
    int sum = 0;
    int dirX = to_X - from_X;

    if(dirX < 0) dirX = -1;
    else if(dirX > 0) dirX = 1;

    int dirY= to_Y - from_Y;
    if(dirY < 0) dirY = -1;
    else if(dirY > 0) dirY = 1;

    while(from_X != to_X){
        sum+=arr[from_X][from_Y];
        from_X += dirX;
        from_Y += dirY;
    }
    sum+=arr[from_X][from_Y];
    return sum;
}

int diagonalDifference(int arr_rows, int arr_columns, int** arr) {
    int left_to_right = addDiagonal(0,arr_columns-1,0,arr_rows-1,arr);
    int right_to_left = addDiagonal(0, arr_columns-1,arr_rows-1,0,arr);
    if(left_to_right - right_to_left > 0) return left_to_right - right_to_left;
    return right_to_left - left_to_right;
}


texts:
I've implemented the Equals() support for my class as follows:

public override bool Equals(object obj)
{
  return Equals(obj as TwoDPoint);
}

public bool Equals(TwoDPoint p)
{
  return ((object)p != null) && (x == p.x) && (y == p.y);
}

This obviously doesn't match the reference implementation on MSDN, here, as they add explicit checking for null before and after converting to a TwoDPoint, and they implement the actual equality test in each method (i.e. no call from one to the other).

I like my implementation as it's much more succinct. But I'm wondering - what have I missed? Am I losing (significant) performance with my version? Is there actually a bug in this approach?


texts:
The condition for refactoring is:

Define 2 new rules with respect to rental charges that are applicable and with the ability to add new categories of movies.
Ex: Rental amount for children's movie for more than 2 days should be 100 from 3rd day onwards.

I have 3 classes (Children, Movie and Rental). I need suggestions on code smell and refactoring it.
Customer.java
import java.util.ArrayList;
import java.util.Iterator;

public class Customer {

    private String name;
    private ArrayList rentals = new ArrayList();

    public Customer(String name) {
        this.name = name;
    }

    public void addRental(Rental arg) {
        rentals.add(arg);
    }

    public String getName() {
        return name;
    }

     public String statement() {

        double totalAmount = 0;
        int frequentRenterPoints = 0;

        String returnVal = "Rental record for : " + this.getName() + ".....\n";

        Iterator iter = rentals.iterator();

        while(iter.hasNext()) {
            double thisAmount = 0;
            Rental each = (Rental) iter.next();
            //determine amounts for each line
            switch (each.getMovie().getPriceCode()) {
                case Movie.REGULAR: thisAmount += 100;
                if (each.getDaysRented() > 2)
                    thisAmount += (each.getDaysRented() - 2) * 75;
                break;

                case Movie.NEW_RELEASE:
                thisAmount += each.getDaysRented() * 150;
                break;

                case Movie.CHILDREN:
                thisAmount += 75;
                if (each.getDaysRented() > 3)
                thisAmount += (each.getDaysRented() - 3) * 75;
                break;
            }

            // add frequent renter points
            frequentRenterPoints ++;
            // add bonus for a two day new release rental
            if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1)
                frequentRenterPoints ++;

            //show figures for this rental
            returnVal += "\t" + each.getMovie().getTitle() + ": " + thisAmount + "\n";
            totalAmount += thisAmount;

        }

        //print footer
        returnVal += "Amount owed is: " + totalAmount + "\n";
        returnVal += "You have earned " + frequentRenterPoints + " frequent renter points";

        return returnVal;
    }
}

Movie.java
public class Movie {

    public static final int CHILDREN = 2;
    public static final int REGULAR = 0;
    public static final int NEW_RELEASE = 1;

    private String title;
    private int priceCode;

    public Movie(String title, int priceCode) {
        this.title = title;
        this.priceCode = priceCode;
    }

    public int getPriceCode() {
        return priceCode;
    }

    public void setPriceCode(int arg) {
        priceCode = arg;
    }

    public String getTitle() {
        return title;
    }
}

Rental.java
class Rental {

    private Movie movie;
    private int daysRented;

    public Rental(Movie movie, int daysRented) {
        this.movie = movie;
        this.daysRented = daysRented;
    }

    public int getDaysRented() {
        return daysRented;
    }

    public Movie getMovie() {
        return movie;
    }
}