texts: Assemble network packet on stack for iovec

texts:
The recurring problem to assemble a network packet out of payload, sequence number, header, and other misc. information is mostly solved either on the heap (e.g. appending to a std::vector) or by first allocating a (hopefully large enough) buffer and then writing to that buffer. Some of the elements always stay the same or only change minimally (like the header) and therefore the scatter/gather approach offered by writev with iovec, Asio with buffer sequences or other networking interfaces allow to avoid those unnecessary copies.
There is still the problems that different parts of the message are produced in different parts of the code, especially when more than on sub-protocol is to be used. In that case we are again tempted to use dynamic memory allocation to construct the iovec.
I would like to avoid those dynamic memory allocation and potentially oversized buffers for so I came up with the following in-stack stack implementation (I named it stack_stack):
template<class T, size_t length=1>
struct stack_stack {
  using next_type = stack_stack<T, length-1>;
  using prev_type = stack_stack<T, length+1>;
  const T value;
  const next_type * next = nullptr;
  static constexpr size_t ssize = length;

  struct iterator {
    using value_type = T;
    using pointer = const value_type*;
    using reference = const value_type&;
    using iterator_category = std::input_iterator_tag;

    iterator& operator++() {
      ptr = static_cast<const stack_stack*>(ptr)->next;
      return *this;
    }
    bool operator==(iterator other) const {
      return ptr == *other;
    }
    bool operator!=(iterator other) const {
      return ptr != *other;
    }
    pointer operator*() {return static_cast<pointer>(ptr);}

    const void* ptr;
  };
  iterator begin() const {return iterator{this};}
  iterator end() const {return iterator{nullptr};}

  prev_type push_front(T val) const {
    return {val, this};
  }
};

It keeps track of its length using template parameters and could be used like in the following example scenario:

struct ioitem {
  char* data;
  size_t size;
};

template<class stack>
void Send(const stack& b) {
  for (auto a : b) {
    std::cout << a->data << std::endl;
  }
}

template<class stack>
void SendWithHeader(const stack& b) {
  auto header = std::string("HDX1");  // This would normally some kind of constexpr
  Send(b.push_front({header.data(), header.size()}));
}

template<class stack>
void SendWithSeqno(const stack& b) {
  auto seq_no = std::string("5");
  auto b1 = b.push_front({seq_no.data(), seq_no.size()});  // it's ok if one module addds more than one part
  auto b2 = b1.push_front({seq_no.data(), seq_no.size()});
  SendWithHeader(b2);
}

template<class stack>
void SendWithTag(const stack& b) {
  auto tag_name = std::string("my tag");  // I am just making up a protocol here
  SendWithSeqno(b.push_front({tag_name.data(), tag_name.size()}));
}

int main() {
  auto my_data = std::string("Hello World");
  auto my_Buffer = stack_stack<ioitem>{my_data.data(), my_data.size()};
  SendWithTag(my_Buffer);
}

What I would like to improve:

In the Send function I could copy the stack to a statically sized array according to the size of stack::ssize. However I did not get std::copy to work.
I don't like the hacks with the void* in the iterator.

Also: Is this a good way to approach this problem or is there a much better solution (without the heap) that got under my radar? I searched for similar implementations to mine but could not find anything.


texts: Boilerplate singleton / lazy initialiser

texts:
I'm working with an existing code base here and while I don't have the time/budget to re-do the entire thing (ultimate solution), I do get a bit of leeway to enhance the code base, as well as maintaining it.

We're using EntityFramework and the SynchronizedBindingList is essentially just that; it keeps all the data in memory, but also ensures that it's as in-sync as possible with the database. The idea being that memory is cheap and we'd rather use the end-users' (internal staff) memory, than have a few hundred users frequently querying the database. The concept works well and we haven't really had any issues with the setup, I'm just trying to make the code more maintainable.

At present, we have a lot of Manager classes, essentially one for each table, that has the following code:

public class LessonsLeartManager
{
    private static readonly Lazy<LessonsLearntManager> Lazy =
            new Lazy<LessonsLearntManager>(() => new LessonsLearntManager());
    public SynchronizedBindingList<LessonsLearnt, DbContext> LessonsLearntList { get; private set; }

    public static LessonsLearntManager Instance
    {
        get { return Lazy.Value; }
    }

    private LessonsLearntManager()
    {
        LessonsLearntList = new SynchronizedBindingList<LessonsLearnt, DbContext>();
        LessonsLearntList.RefreshSync();
    }

    // Manager specific code goes here.
}

Obviously this is highly repetitive and difficult to maintain if you want to change something as it would have to be changed across multiple files.

I have been fiddling with this idea today and would like to get other opinions on the quality/idea of this code:

public class DatabaseTable<TManager, TTable> where TManager : class, new()
        where TTable : class, IDbPk<TTable>, IAutoIncludeEntity<TTable>, new()
{
    private static readonly Lazy<TManager> Lazy = new Lazy<TManager>(() => new TManager());
    public SynchronizedBindingList<TTable, DbContext> List { get; private set; }

    internal DatabaseTable()
    {
        List = new SynchronizedBindingList<TTable, DbContext>();
        List.RefreshSync();
    }

    public static TManager Instance
    {
        get { return Lazy.Value; }
    }
}

Obviously the previous LessonsLearntManager code then becomes:

public class LessonsLearntManager : DatabaseTable<LessonsLearntManager, LessonsLearnt>{//Manager specific code}

and can be used as such:

MyGridView.DataSource = LessonsLearntManager.Instance.List;

which is a far bit better than previously (the class declaration anyway, the usage doesn't change much).


texts: C# Multi level HTML TagBuilder object - Design pattern Review needed

texts:
I find the TagBuilder written in C# little poor without the ability to "host" inside it sub tags (as objects not as strings).

So I wrote a simple class that inherits TagBuilder and allow to save sub tags.
I can navigate inside it and add things to it while I move across the application.
And when I call the Top Tag Object .ToString, it will render the entire html

public class MultiLevelHtmlTag : TagBuilder
{
    public MultiLevelHtmlTag(string tagName) : base(tagName) { }

    public List<MultiLevelHtmlTag> InnerTags = new List<MultiLevelHtmlTag>();

    public override string ToString()
    {
        if (InnerTags.Count > 0)
        {
            foreach (MultiLevelHtmlTag tag in InnerTags)
            {
                this.InnerHtml += tag.ToString();
            }
        }
        return base.ToString();
    }
}

this is how I use it:

MultiLevelHtmlTag top = new MultiLevelHtmlTag("div");
top.InnerTags.Add(new MultiLevelHtmlTag("span"));
log.Debug(top.ToString());

output:

What do you think about it?
is that a goot pattern?


texts: Selecting control class in a document assembler

texts:
I feel like there is a cleaner/simpler way of doing the following. Is there an existing software pattern that I should be using?

I have an Assembler class that I use to assemble/process content rules MS-Word documents.

There are many different types of Controls that are processed:

ClearCellIf
DeleteColumnIf
DeleteLineIf
DeleteRowIf
RepeatingControl

The controls fall into two categories:

Generic controls (used over and over)
Custom controls (only used in a specific solution)

Each control extends a base PrecedentControl class and has a Test and a Process method:

class DeleteRowIf : PrecedentControl
{
    public DeleteRowIf(Wd.ContentControl control) : base(control) { }

    public static bool Test(Wd.ContentControl control, PrecedentInstruction Instruction)
    {
        return Instruction != null && Instruction.Command == "DeleteRowIf";
    }

    public override void Process<T>(T data, ref bool Cancel)
    {
        var result = PrecedentExpression1.Resolve(control.GetPrecedentInstruction().Expression, data);
        if (result)
            control.DeleteRow();
    }
}

The bit that I hate, and would like to do better, is the logic that determines which type of control is in use:

public static PrecedentControl AsPrecedentControl(this Wd.ContentControl control)
{
    var instruction = control.GetPrecedentInstruction();
    if (FormatVariable.Test(control, instruction))
        return new FormatVariable(control);
    else if (Optional.Test(control, instruction))
        return new Optional(control);
    else if (DeleteControlIf.Test(control, instruction))
        return new DeleteControlIf(control);
    else if (DeleteControlIf_AndPreviousSpace.Test(control, instruction))
        return new DeleteControlIf_AndPreviousSpace(control);
    else if (DeleteControlIf_AndSurroundingPunctuation.Test(control, instruction))
        return new DeleteControlIf_AndSurroundingPunctuation(control);
    else if (DeleteLineIf.Test(control, instruction))
        return new DeleteLineIf(control);
    else if (DeleteLineIf_OrRemoveControl.Test(control, instruction))
        return new DeleteLineIf_OrRemoveControl(control);
    else if (DeleteLineIf_AndRepositionBulletEnding.Test(control, instruction))
        return new DeleteLineIf_AndRepositionBulletEnding(control);
    else if (DeleteRowIf.Test(control, instruction))
        return new DeleteRowIf(control);
    else if (DeleteRowIf_OrRemoveControl.Test(control, instruction))
        return new DeleteRowIf_OrRemoveControl(control);
    else if (DeleteColumnIf.Test(control, instruction))
        return new DeleteColumnIf(control);
    else if (ClearCellIf.Test(control, instruction))
        return new ClearCellIf(control);
    else if (RepeatingControl.Test(control, instruction))
        return new RepeatingControl(control);
    else if (RepeatingControl_RemoveLastAnd.Test(control, instruction))
        return new RepeatingControl_RemoveLastAnd(control);
    else if (RepeatingControl_SecondLastHasAnd.Test(control, instruction))
        return new RepeatingControl_SecondLastHasAnd(control);
    else if (RunMacro.Test(control, instruction))
        return new RunMacro(control);
    else if (ContactDelivery.Test(control, instruction))
        return new ContactDelivery(control);
    else if (ContactDelivery_DeleteControlAndPrecedingComma.Test(control, instruction))
        return new ContactDelivery_DeleteControlAndPrecedingComma(control);
    else if (ContactDelivery_MultilineAddress.Test(control, instruction))
        return new ContactDelivery_MultilineAddress(control);
    else
        return null;
}


texts: Lightweight localization for a Cordova app

texts:
I had been trying to find a suitable solution to implement localization in my Phonegap/Cordova application. My search proved that any localization through seperate .xml or .json files was a nightmare (mostly due to cross-access-origin).

Because of this, I decided to create a (very) simple, lightweight localization solution.

Here is what I've written:

var locale = {
    getString:function(required){
        var language = localStorage.getItem("language");
        if(language === null){
            language = "nl";
        }

        return window['locale']['translation'][language][required];
    },

    translation: {
        en: {
            play:"Play",
            faq:"FAQ",
            highscore:"Highscore",
            gameStart:"Game starting in ",
        },
        nl: {
            play:"Speel",
            faq:"FAQ",
            highscore:"Highscore",
            gameStart:"Spel start in ",
        }
    }
}

I am really interested in any comments you have. Would there be a better solution or any better methods to use in my implementation?


texts:
This is a simple Morse code interpreter with a CLI. It's a naive table-lookup implementation, and uses my-py for type checking. It automatically detects the input (English or Morse) and converts accordingly. It has the simplest possible CLI that I could think of. There is a git repo here.

I don't often write Python; I write Ruby for work and Clojure in my free time, but I do love Python and have a bit of experience with it. I welcome any suggestions on how to write more "Pythonic" code, simpler code or interfaces, or how to make the code more robust. Ideally, I want it to "just work" and be able to take even malformed data. Unfortunately, I think I need to keep the msg argument surrounded by quotes from the command line, otherwise the shell will interpret a single or double dot as the current or parent directory.

I'm considering using the Boyer-Moore algorithm instead of a lookup table, but I'm not sure if that's worth it.

import re
import argparse
from typing import Dict

eng = {
    "a" : ".-",
    "b" : "-...",
    "c" : "-.-.",
    "d" : "-..",
    "e" : ".",
    "f" : "..-.",
    "g" : "--.",
    "h" : "....",
    "i" : "..",
    "j" : ".---",
    "k" : "-.-",
    "l" : ".-..",
    "m" : "--",
    "n" : "-.",
    "o" : "---",
    "p" : ".--.",
    "q" : "--.-",
    "r" : ".-.",
    "s" : "...",
    "t" : "-",
    "u" : "..-",
    "v" : "...-",
    "w" : ".--",
    "x" : "-..-",
    "y" : "-.--",
    "z" : "--..",
    " " : "/",
    "0" : "-----",
    "1" : ".----",
    "2" : "..---",
    "3" : "...--",
    "4" : "....-",
    "5" : ".....",
    "6" : "-....",
    "7" : "--...",
    "8" : "---..",
    "9" : "----.",
    "," : ",",
    "." : ".",
    "!" : "!",
    "?" : "?",
} # type: Dict[str, str]

morse = {v: k for k, v in eng.items()} # type: Dict[str, str]

def morsep(msg: str) -> bool:
    if msg[0][0] in ['.', '-', '/']:
        return True
    else:
        return False

def morse_to_eng(msg: str) -> str:
    out = "" # type: str
    split_msg = re.split(" ", msg) # type: list
    filtered_msg = [e for e in split_msg if e] # type: list
    for char in filtered_msg:
        c = morse[char] # type: str
        out += c
    return("".join(out))

def eng_to_morse(msg: str) -> str:
    out = "" # type: str
    for char in msg:
        c = eng[char] # type: str
        out += "{} ".format(c)
    return("".join(out))

def decode(msg: str) -> str:
    "Main control flow."
    if morsep(msg) == True:
        return(morse_to_eng(msg))
    else:
        return(eng_to_morse(msg))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Translate English to Morse code, and vice versa.')
    parser.add_argument('-v', '--version', help='Show the version.', action='version', version='Morse 0.1')
    parser.add_argument('msg', type=str, nargs=1,
                        help='The message to be decoded. Input type will be automatically detected and converted. \
                        Must be wrapped in quotes.')

    args = parser.parse_args()
    out = decode(args.msg[0]) # type: str
    print("{}".format(out))


texts:
I've written the following algorithm to solve this HackerRank problem using STL algorithms.

Problem statement

  Given an array with n elements, can you sort this array in ascending
  order using only one of the following operations?

  Swap two elements.
  Reverse one sub-segment.

  Input Format

  The first line contains a single integer, n, which indicates the size
  of the array.   The next line contains  integers separated by spaces.

n
d1 d2 ... dn

  Output Format

  If the array is already sorted, output yes on the first line. You do not need to output anything else.
  If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:

  If you can sort the array by swapping d_l and d_r, output "swap l
  r" in the second line. l and r are the indices of the elements to be
  swapped, assuming that the array is indexed from 1 to n.
  Else if it is possible to sort the array by reversing the segment
  d[l...r], output "reverse l r" in the second line. l and r are the
  indices of the first and last elements of the subsequence to be
  reversed, assuming that the array is indexed from 1 to n.

  d[l...r] represents the sub-sequence of the array, beginning at index
  l and ending at index r, both inclusive.

  If an array can be sorted by either swapping or reversing, stick to
  the swap-based method.

  If you cannot sort the array in either of the above ways, output "no" in the first line.

Code

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

int main() {
    int n; std::cin >> n;
    std::vector<int> v;
    v.reserve(n);
    while(n--){
        int x; std::cin >> x;
        v.push_back(x);
    }
    auto v_sorted = v;
    std::sort(v_sorted.begin(),v_sorted.end());

    auto mismatch_1 = std::mismatch(v.begin(),v.end(),
                                    v_sorted.begin());
    auto mismatch_2 = std::mismatch(std::next(mismatch_1.first),v.end(),
                                    std::next(mismatch_1.second));
    auto mismatch_3 = std::mismatch(v.rbegin(),v.rend(),
                                    v_sorted.rbegin());

    if (std::prev(mismatch_3.first.base()) == mismatch_2.first) {
        if (*std::prev(mismatch_2.first)<=*mismatch_1.first) {
           std::cout
               << "yes\n" << "swap "
               << std::distance(v.begin(),mismatch_1.first) + 1
               << " "
               << std::distance(v.begin(),mismatch_2.first) + 1;
        }
    }
    else {
       std::reverse(mismatch_1.first,mismatch_3.first.base());
       if (std::equal(mismatch_1.first,std::prev(mismatch_3.first.base()),mismatch_1.second)) {
           std::cout
               << "yes\n" << "reverse "
               << std::distance(v.begin(),mismatch_1.first) + 1
               << " "
               << std::distance(v.begin(),std::prev(mismatch_3.first.base())) + 1;
       }
       else {
           std::cout << "no";
       }
    }

    return 0;
}

Questions

My main question is about reverse iterators. I feel it's a little bit confusing when I compare them with forward iterators, as I need to do std::prev(reverse_iterator.base()). Do you think this affects readability or is the code fine like it is? Any other suggestion?


texts: Is Lock necessary to make operation thread safe for this scenario

texts:
I have the following method that is responsible for retrieving an Item from the database. There will be multiple threads instantiating this class, so I want to make sure that the operation will be thread-safe. As a result, I have added a lock around it, however since class only contains instance variables (and no static variables), is adding a lock necessary for this scenario?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace My.Library
{
    public class MyDataProvider : IMyDataProvider
    {
        private object sync = new object();
        private string connectionString;

        public MyDataProvider(string connString)
        {
            connectionString = connString;
        }
        public Item GetItem(Guid itemId)
        {
            lock (sync)
            {
                Item item = new Item();
                string sqlQuery = @"SELECT ItemId, ItemName FROM Item WHERE ItemId = @itemId";

                using SqlConnection connection = new SqlConnection(connectionString);
                SqlCommand command = new SqlCommand(sqlQuery, connection);
                command.Parameters.AddWithValue("@itemId", itemId);
                connection.Open();

                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    item.ItemId = reader["ItemId"] == DBNull.Value ? Guid.Empty : (Guid)reader["ItemId"];
                    item.ItemName = reader["ItemName"] == DBNull.Value ? null : reader["ItemName"];
                }

                return item;
            }
        }
    }
}


texts: Cleanest way to close over a counter in CoffeeScript

texts:
I haven't spent too much time with CoffeeScript and am trying to have a simple counter:

casper.on('step.complete', ( ->
        i = 0
        return (step) ->
            i += 1
            @echo "Step#{ i }"
    )())

Which works fine but seems to have a bit too many parenthesis for CoffeeScript.


texts: Counting numbers in an array that are divisible by any 2 numbers

texts:
While solving one question I got stuck with a time limit error. The main objective in question is to count numbers in an array \$A\$ that are either divisible by \$P\$, \$Q\$ or both.

  Input format:

  The first line contains a single integer \$N\$ denoting the size of
  array \$A\$. The next line contains \$N\$ space separated integers,
  where the \$i\$th integer denotes \$A[i]\$.

  The next line contains a single integer \$T\$ denoting the number of
  queries Monk poses to you. Each of the next \$T\$ lines contains 2
  space-separated integers \$P\$ and \$Q\$.

  Example:

6
2 3 5 7 4 9
2
4 5
3 7

  Output:

2
3

The naive approach from my side is this:

a = int(raw_input())                      # Length of an array
b = map(int,raw_input().split())          # Array of size a
c = int(raw_input())                      # Number of query
for _ in xrange(c):
    d,e = map(int,raw_input().split())    # 2 numbers
    count = 0
    for i in b:
        if i%d==0:
            count+=1
        elif i%e==0:
            count+=1
    print count

I guess it is taking linear time \$O(n) + c\$ which can be improved to \$O(log(n))\$ but I am not sure what's the best way to do it or how to implement it.


texts:
I have completed a VHDL 16-bit parity generator and I would like to know if I have programmed it correctly. I have compiled it 10 times and worked out any bugs that it found. I was finally able to compile it successfully. My problem is that I am trying to run a timing simulation to make sure it will work correctly but I am not sure what I should be looking for.

The basic operation is to XOR the A and B inputs to perform an iterative process with an output of '1' as odd and an output of '0' as even. My code is written such that a basic XOR block is then added as a component of the complete parity generator.

I would like a second opinion to make sure I have written it correctly and if it will do what it is designed to do. I thank you all in advance and look forward to any input, good or bad.

Basic XOR gate block VHDL Code

library ieee;
use ieee.std_logic_1164.all;

entity xor_gate is
port(
        a : in std_logic;
        b : in std_logic;
        pari : in std_logic;
        paro : out std_logic);

    end xor_gate;

architecture behavior of xor_gate is
    begin

    paro <= (a xor b) or pari;

end behavior;

16-bit Parity Generator Code

library ieee;
use ieee.std_logic_1164.all;
entity parity_2 is

port(a: in std_logic_vector (0 to 15);
      b: in std_logic_vector (0 to 15);
      paro: out std_logic);

end parity_2;

architecture behavior of parity_2 is
        signal parry: std_logic_vector (0 to 15);

component xor_gate
            port (a,b: in std_logic;
                   pari: in std_logic;
                    paro: out std_logic);

end component;

begin

c1: xor_gate port map (a(0), b(0), '0', parry(0));
c: for i in 1 to 15 generate
c2: xor_gate port map (parry(i-1), a(i), b(i), parry(i));

end generate;

paro <= parry(15);

end behavior;


texts: Implementing a tic tac toe board in python

texts:
This is my attempt at making a class to represent a game board for tic tac toe. I normally hate while loops but I used one because I cant seem to make the for loop look nice for the display.

import numpy as np

class TicTacToeBoard():
    """Class to represent a board for a game of tic tac toe"""

    def __init__(self):
        """Initialize the board data"""
        self.dimension = 3,3
        self.board_data = np.array(range(1,10), dtype=object).reshape(self.dimension)
        self.space_to_coordinate = {}
        self.last_marked_coordinate = None

        for coord in np.ndindex(self.board_data.shape):
            space = self.board_data[coord]
            self.space_to_coordinate[space] = coord

    def display(self):
        """Displays the game board to console

        Example:
                1 | 2 | 3
                ----------
                4 | 5 | 6
                ----------
                7 | 8 | 9
        """
        count = 1
        while count < 10:
            coordinate = self.space_to_coordinate[count]
            space_data = self.board_data[coordinate]
            print(str(space_data)) if not count % 3 else print(str(space_data) + " |", end=' ')
            print('----------') if not count % 3 and count != 9 else None
            count += 1
        print()

    def is_marked(self, space):
        """Checks if space is marked returns false if not marked"""
        coordinate = self.space_to_coordinate[space]
        space_data = self.board_data[coordinate]
        if space_data == "X" or space_data == "O":
            return True
        return False

    def add_mark(self, space, mark):
        """If space is not marked, then add player mark and return true else return false"""
        if not self.is_marked(space):
            coordinate = self.space_to_coordinate[space]
            self.board_data[coordinate] = mark
            self.last_marked_coordinate = coordinate
            return True
        return False

    def is_winner(self, mark):
        """Checks to see if mark has won the board by getting '3 in a row' """
        if self.last_marked_coordinate == None:
            return False

        row_win, column_win, diag1_win, diag2_win = [True] * 4
        fixed_row, fixed_column = self.last_marked_coordinate
        for i in range(3):

            #check row
            if self.board_data[fixed_row, i] != mark:
                row_win = False

            #check column
            if self.board_data[i, fixed_column] != mark:
                column_win = False

            #check diagnol 1
            if self.board_data[i,i] != mark:
                diag1_win = False

            #check diagnol 2
            if self.board_data[i, 2-i] != mark:
                diag2_win = False

        return any([row_win, column_win, diag1_win, diag2_win])

NOTE: just realized I forgot to test for a cats game.


texts: Refactor code to find four co-linear points

texts:
I am relatively new to Java, but have been reading up on how to improve the quality of my code.

I am writing a system where I take in a series of points from a file with x and y co-ordinates and by checking slopes relative to each other, am calculating and drawing a line if there is four or more co-linear points on the line. The code works and is doing what is required, but I would like to tidy up this method by reducing the if statements, but am not sure on how to, or if it is even necessary. The parameters being passed in is an array of doubles, which are slopes relative to an origin.  I am iterating this array to look for 3 or more equal slopes in a row which would give a line and adding the corresponding points and any further equal points to a set.  Once a line has been found, the rest of the slopes in array are checked in similar fashion. Any advice would be appreciated.

I think it's messy, but not sure how to rectify it.

public static void checkForLines(Double[] arrayOfSlopes, Point[] tempArray)
{
    int count = 0; // Keeps track of number of duplicates
    int i = 1;

    while (i < arrayOfSlopes.length - 1)
    {
        Double first = arrayOfSlopes[i];
        Double next = arrayOfSlopes[i + 1];

        if (first.equals(next))
            // Compares two consecutive indexes in array for equality
        {
            count = count + 1; // If match found increase the count

            if (count == 2)
                // At this point a line has been found
            {
                SortedSet<Point> line = new TreeSet<Point>();
                //Create a set to store points from this line
                line.add(tempArray[0]);
                line.add(tempArray[i - 1]);
                line.add(tempArray[i]);
                line.add(tempArray[i + 1]);
                //Store four found points

                int j = i + 1;

                while (j + 1 < arrayOfSlopes.length - 1 && (arrayOfSlopes[j].equals(arrayOfSlopes[j + 1])))
                {
                    line.add(tempArray[j + 1]);
                    //Store any other further duplicates if exist
                    j++;
                }

                if (arrayOfSlopes[j].isInfinite() && arrayOfSlopes[arrayOfSlopes.length - 1].isInfinite() ||
                    arrayOfSlopes[arrayOfSlopes.length - 1].equals(first))
                {
                    line.add(tempArray[tempArray.length - 1]);
                    //Check the last element for equality
                }

                if (lines.isEmpty())
                {
                    lines.add(line);
                }

                else
                {
                    lines.add(0, line);
                    ;
                    weedDuplicates(line);
                }
                i = j + 1; //Continue iteration from this point
            }

            if (count < 2)
            {
                i++;
            }
        }

        else if (first.equals(next) == false)
        {
            count = 0;
            i++;
        }
    }
}


texts: Using foldl to add numbers, while validating that they are nonnegative

texts:
I have a function that will calculate the sum of a list of integer, however if any of the number is negative, it will should an error instead (not throwing exception).

The following is a working Haskell code (Glasgow Haskell Compiler, Version 7.10.3):

addAll :: [Int] -> Either String Int
addAll xs = foldl safeAdd (Right 0) xs
   where
     safeAdd :: Either String Int -> Int -> Either String Int
     safeAdd = (\acc next -> case acc of
                     Left s  -> Left s
                     Right n -> if next < 0
                                 then Left (show next ++ " is not positive")
                                 else Right (n + next))

Examples output of the function:

addAll [1,2,3]  -- Right 6
addAll [-1,2,3] -- Left "-1 is not positive"

Although the code works, but I'm not entirely satisfied with it, because the recursion keeps going until the last element even though errors are encountered early.  Not only that, it feels a little more complicated than it should be.

After reading some SO posts such as this one, I think that the code above can be further simplified using functions like foldM or even applicative <$>.

But, I'm just not sure how to use those functions, so please do show me a way to simplify the code above.


texts: Query column names and then using them in statements

texts:
I currently have a table with over 250 columns, in which ~10-15 columns have column names that have a specific prefix, namely EQP_.

Assume that you do not want to type the names of these columns, but still want only a result set containing those columns.

Some possible solutions I thought of:

Using a common_table_expression
Using a table variable with a function
Using an INNER JOIN with INFORMATION_SCHEMA

All of these seem like overkill to me, so I ended using a temp table and dynamic SQL to get something working. I am not a fan of dynamic SQL, so I was hoping to get some feedback on how to do this better.

Query

SELECT TOP 15 COLUMN_NAME 'name', 0 'selected'
INTO #columns
FROM Production.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'it_master'
AND COLUMN_NAME LIKE 'EQP_%'

DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT TOP 10 ' ;

WHILE EXISTS(SELECT 1 FROM #columns WHERE [selected] = 0 )
BEGIN

    DECLARE @column NVARCHAR(100)

    SELECT TOP 1 @column  = [name] FROM #columns WHERE [selected]= 0

    SET @sql = @sql + @column + ', '

    UPDATE c
    SET [selected] = 1
    FROM #columns c
    WHERE [name] = @column

END

SET @sql = LEFT(@sql, LEN(@sql) - 1) + ' FROM it_master '

EXECUTE sp_executesql @sql

IF OBJECT_ID('tempdb..#columns') IS NOT NULL
    DROP TABLE #columns


texts: Suppress console output from React in Jest testing output but not in browser output

texts:
I have a React app that I am testing with the built-in jest testing tools. In the process of debugging, I sometimes send data to the console (e.g. console.log, console.error, etc.) from my code-under-test. This shows up both in the browser console as well as in the testing output in the terminal which is what I sometimes want.

However, sometimes I want to send such debugging messages to either:

the testing terminal or
the browser,

but not both.

I know how to do #1: just include the console.log in the jest test code rather than in the code-under-test. However, if I want to do #2, I'm not quite sure what to do.

I tried the following in the code-under-test:

if (!jest) {
  console.log('some browser-only output');
}

That does suppress the output in the test, which otherwise behaves normally, i.e. no error is thrown during testing. However, it does not output anything in the browser but instead throws an error: "Uncaught ReferenceError: jest is not defined", i.e. there is no let jest = ... or const jest = ... anywhere in the code.

I did come up with a solution:

try { jest; }
catch(e) {
    console.log('some browser-only output');
}

This gives me the desired results. However, the solution feels very hack-y: It requires throwing an error in order to work, which just "smells" wrong, even for a debugging tool.

So, is there a better way for me to check whether jest exists without throwing an error? Or another way to see if testing is underway, again without throwing an error?


texts: Counting votes for candidates in a category and region

texts:
With the following code, I want to count the Vote objects from a collection, filtering on one of their fields, Candidate.

I have the feeling that I can get this done much more efficiently.

// Get all votes from the database
Collection<Vote> votes = getVotesFromCategoryAndRegion(c, r);

// Filter distinct candidates
Collection<Candidate> candidates = votes
            .stream()
            .map(Vote::getCandidate)
            .distinct()
            .collect(Collectors.toList());

List<VoteResult> results = new ArrayList<>();

// If vote.candidate == candidate, candidates's vote counter ++
for (Candidate currentCandidate : candidates) {
      int currentVoteCount = 0;
      for (Vote v : votes)
          if (v.getCandidate().equals(currentCandidate))
              currentVoteCount++;

      results.add(new VoteResult(currentCandidate, currentVoteCount));
    }

    Collections.sort(results);
    return results;

If you have any suggestions, please tell.


texts: Check if a range in Excel contains DataValidation

texts:
One of the answers to Determine if cell contains data validation
 got me thinking about an edge case I needed to solve. If cell happens to be a multi-cell range what's the best way to answer? The answer below returns False if the range contains both a cell with and without validation.

Function HasValidation(cell As Range) As Boolean
    Dim t: t = Null

    On Error Resume Next
    t = cell.Validation.Type
    On Error GoTo 0

    HasValidation = Not IsNull(t)
End Function

The answer I arrived at allows for non-contiguous ranges. I chose Variant as the return type in the case that there's a mix of validated and non-validated cells. Since it's neither True nor False a Null seemed the best fit.

Public Function HasValidation(ByVal cell As Range) As Variant
    Dim tempVariable As Variant
    If cell.Cells.Count > 1 Then
        On Error Resume Next

        Dim singleCell As Range
        For Each singleCell In cell
            Debug.Print singleCell.Address(True, True)
            tempVariable = Empty
            tempVariable = singleCell.Validation.Type

            If IsEmpty(tempVariable) Then
                Dim cellWithoutValidationFound As Boolean
                cellWithoutValidationFound = True
            Else
                Dim cellWithValidationFound As Boolean
                cellWithValidationFound = True
            End If

            If cellWithValidationFound And cellWithoutValidationFound Then
                On Error GoTo 0
                HasValidation = Null
                Exit Function
            End If
        Next

        HasValidation = cellWithValidationFound
    Else
        tempVariable = Null
        tempVariable = cell.Validation.Type
        HasValidation = IsNull(tempVariable)
    End If
End Function


texts: Exercism assignment word-count in Python

texts:
Can someone review my code which I put on exercism.io for the word-count exercise (found here)?

class Phrase:
    def __init__(self, phrase):
        self.phrase = phrase.strip().lower().split()

    def word_count(self):
        word_dict = {}
        for word in self.phrase:
            word_input = ''.join(e for e in word if e.isalnum()).strip()
            if word_input:
                word_dict[word_input] = word_dict.get(word_input, 0) + 1
        return word_dict


texts:
Similar to this question, here's another implementation. Assume the input is already a set.

 (defn powerset
       [set]
       (reduce
           (fn [xs x] (concat xs (map #(cons x %) xs)))
           [()]
           set))


texts:
I am to implement a stack in C using a linked list. My code is below. My design:

I use stack_ prefix to each function, and each function has a Stack* self pointer. This is similar to object-oriented languages’ bundling of data and methods. I do not know how idiomatic this is in C.
Each function returns a bool indicating success or failure. A more detailed implementation would have error codes and messages. I do not know how idiomatic this is in C.
The stack_init function does not call malloc, so that one could define an instance of Stack locally, as in the test methods below.
I used int as the type of data, but this could be modified for other types. I did not use void* since void* would lose type safety.

stack.h

#ifndef STACK_H_
#define STACK_H_

#include <stdbool.h>

typedef struct Node {
  int data;
  struct Node* next;
} Node;

typedef struct {
    Node* root;
} Stack;

bool stack_init(Stack* self);
bool stack_delete(Stack* self);
bool stack_pop(Stack* self, int* data);
bool stack_push(Stack* self, int data);

#endif  // STACK_H_

stack.c

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

bool stack_init(Stack* self) {
  if (self == NULL) {
    return false;
  }

  self->root = NULL;
  return true;
}

bool stack_delete(Stack* self) {
  Node* next;
  while (self->root != NULL) {
    next = self->root->next;
    free(self->root);
    self->root = next;
  }

  return true;
}

bool stack_push(Stack* self, int data) {
  if (self == NULL) {
    return false;
  }

  Node* node = malloc(sizeof(Node));
  if (node == NULL) {
    return false;
  }

  node->data = data;
  node->next = self->root;
  self->root = node;

  return true;
}

bool stack_pop(Stack* self, int* data){
  Node* root = self->root;
  if (root == NULL) {
    return false;
  }

  *data = root->data;
  self->root = root->next;
  free(root);

  return true;
}

stack_test.c

#include <assert.h>
#include "stack.h"

static void test_null_stack_should_fail_to_init() {
  // arrange
  Stack* stack = NULL;

  // act
  assert(!stack_init(stack));
}

static void test_empty_stack() {
  // arrange
  Stack stack;

  // act
  assert(stack_init(&stack));
  assert(stack_delete(&stack));
}

static void test_push_then_pop() {
  // arrange
  Stack stack;
  stack_init(&stack);
  stack_push(&stack, 1);
  stack_push(&stack, 2);
  stack_push(&stack, 3);
  int data;

  // act
  assert(stack_pop(&stack, &data));
  assert(data == 3);
  assert(stack_pop(&stack, &data));
  assert(data == 2);
  assert(stack_pop(&stack, &data));
  assert(data == 1);
  assert(!stack_pop(&stack, &data));
  assert(stack_delete(&stack));
}

static void test_push() {
  // arrange
  Stack stack;
  stack_init(&stack);
  stack_push(&stack, 1);
  stack_push(&stack, 2);
  stack_push(&stack, 3);

  // act
  assert(stack_delete(&stack));
}

int main() {
  test_null_stack_should_fail_to_init();
  test_empty_stack();
  test_push_then_pop();
  test_push();
}


texts: Split a big file into two and then merge back into the original

texts:
After searching and reading some threads (1, 2, 3, 4 and 5) on how to split a big file into smaller ones and then merge them back into the original one I made the following VB.NET code on an empty project with module Module1 and reference to System.Windows.Forms:

' <Summary>
'
'   3 files: 1; 2; 3
'   1 has data
'   2 and 3 are empty
'
'   How to split file 1 into files 2 and 3:
'     remove 2º comment (leave 1º comment)
'     run program (select file 1 in the 1º file system prompt and file 2 in the 2º file system prompt)
'     add 2º comment back and remove 1º comment
'     run program (select file 1 in the 1º file system prompt and file 3 in the 2º file system prompt)
'
'   How to join/merge files 2 and 3 into file 1:
'     leave both 1º and 2º comments commented
'     run program (select file 3 in the 1º file system prompt and file 2 in the 2º file system prompt)
'     file 2 will be the merge of files 2 and 3 (same as file 1)
'
' </Summary>

Imports System.IO
Module Module1
    Sub Main()
        With New Windows.Forms.OpenFileDialog()
            .ShowDialog()
            Dim inputStream As FileStream = New FileStream(.FileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
            .ShowDialog()
            Dim outputStream As FileStream = New FileStream(.FileName(), FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
            'inputStream.Position = inputStream.Length \ 2 - inputStream.Length \ 2 Mod 10000
            Dim buffer As Byte() = New Byte(9999) {}
            Dim bytesRead As Integer
            bytesRead = inputStream.Read(buffer, 0, buffer.Length)
            While bytesRead > 0 'And inputStream.Position <= inputStream.Length \ 2
                outputStream.Write(buffer, 0, bytesRead)
                bytesRead = inputStream.Read(buffer, 0, buffer.Length)
            End While
            outputStream.Flush()
            inputStream.Close()
            outputStream.Close()
        End With
    End Sub
End Module

I'm looking to know if there's any different way to do this with a noticeable performance improvement. The size of the original file is almost 30 GB, which will be split into 2 files, sent online together with the program and then merged back together.

Being of that size it takes some time so performance is the focus here, there's no checks of the user's input, no exception/error handling, no pretty code with forms, options and methods/functions. It's just some quick and dirty code.


texts:
I have a class ConfigFile that reads some values from a JSON using Boost and stores them in variables. Everything is done in the constructor:

ConfigFile::ConfigFile(const std::string& configFileNamePathIn)
{
    PTree tmpPT;
    std::string path;

    /// reading aws config file ///
    json::read_json(configFileNamePathIn, tmpPT);

    // read a string value
    path = "path1";
    m_param1 = tmpPT.get<std::string>(path, "");
    checkEmptyness(m_param1, "param1", path);

    // read a float value
    path = "path2";
    m_param2 = tmpPT.get< float >(path, -1);
    checkNegativity(m_param2, "param2", path);

    // ... much more lines like these two also for int and double
}

Because the constructor is long, I thought of creating 4 functions that return string, int, float or double and that receive as input parameters the string path and the PTree:

std::string readStringValue(const std::string& pathIn, const PTree& tmpPT)
{
  path = "path1";
  return tmpPT.get<std::string>(path, "");
}

In the constructor, I just call the function and verify the result:

// ...
m_param1 = readStringValue("path1", tmpPT);
checkEmptyness(m_param1, "param1", path);
// ...

Do you think this is a good improvement, or shall I keep the initial constructor?


texts:
This is a calculator I'm working on. The ultimate goal is to calculate multiple payrolls before selecting to end the program, please review current version in that context. PSA: I'm a beginner.

def main():

    hours, rate = inputData()
    normal_hours, overtime_hours, overtime  = computePay (hours,rate)
    regular, total_pay  = preovertime_hours (hours, rate, overtime)
    displayPay  (rate, normal_hours, overtime_hours, regular, overtime, total_pay)

def inputData():

    name = raw_input('Name of employee: ')
    hours = float (input('Now enter the hours worked please:'))
    rate = float (input('Now enter the pay rate:'))

    return hours, rate

def computePay (hours,rate):

    if hours < 40:
        normal_hours = hours
        overtime_hours = 0
    else:
        normal_hours = 40
        overtime_hours = hours - 40

    if hours > 40:
        overtimerate = 1.5 * rate
        overtime = (hours-40) * overtimerate
    else:
        overtime = 0

    return normal_hours, overtime_hours, overtime

def preovertime_hours (hours, rate, overtime):

    regular = hours * rate
    total_pay = regular
    return regular, total_pay

def displayPay (rate, normal_hours, overtime_hours, regular, overtime, total_pay):

    print ("The amount to be paid to in this pay period is $" + format(total_pay, '.2f'))

main()


texts: AngularJS Todo List - too much controller logic?

texts:
I am starting an angular app and I was wondering if I am on the right track with this. I worked on my last angular app when I was just a youngun who didn't understand the important of designing the code properly. I failed so hard at keeping the code clean and maintainable, mostly due to not understanding directives or services.

I am wondering if there is a better structure to my error handling in the below code.  Is that too much logic in the controller functions? All I am doing is allowing the adding of items to a list, but not allowing them to be added or removed if the list length is < 5 or > 1 respectively.  If there are other problems besides the controller logic, please let me know.

var toDo = angular.module('toDo',[]);

toDo.factory('listEdit', function() {
return {
    add: function(list, item) {
        list.push(item);
        return list;
    },
    remove: function(list, index) {
        list.splice(index, 1);
        return list;
    },
    count: function(list) {
        return list.length;
    }
}
});

//Error handling methods

toDo.controller('main', ['$scope', 'listEdit', function($scope, listEdit) {
$scope.list = [];

$scope.addToList = function() {
    list_length = listEdit.count($scope.list);
    if(list_length < 5) {
        $scope.list = listEdit.add($scope.list, $scope.todo);
    } else {
        alert('Too many list items');
    }
}

$scope.remove = function(index) {
    list_length = listEdit.count($scope.list);
    if(list_length > 1) {
    $scope.list = listEdit.remove($scope.list, index);
    } else {
        alert("You can't delete this last item");
    }
}

}]);

HTML

    <input type="text" ng-model="todo">
    <button ng-click="addToList()">Add to List</button>

    {{todo}}


texts: Find the largest decrease in a sequence of numbers

texts:
I have written a function that takes as input a list of 5 numbers, then the program's goal is to return the largest drop in the list. It is important to understand that [5, 3, ...] is a decrease of 2 and that [5, 20, .....] is a decrease of 0. In short, a decrease can only be from left to right and the largest decrease can for example also be the decrease from the 1st number to the 4th number, they do not necessarily have to be next to each other.
def biggest_drop(temperature):
    difference = 0
    new_temperature = temperature.copy()
    a = 0
    for i in temperature:
        del new_temperature[0]
        for j in new_temperature:
            if i <= j:
                   False
            else:
                a = i - j
                if a > difference:
                    difference = a
    return difference

The good news is the code works, the bad news is that because of the double for loop there is already a Big-O notation of O(n2). However, the program must have a Big-O notation of O(n1) and I don't know how to fix this and where the speed of the code is also high enough. For example, here I have made a fairly sloppy alternative, but it is too slow:
def biggest_drop(temperature):
    difference = 0
    a = 0
    b = temperature[1]
    c = temperature[2]
    d = temperature[3]
    e = temperature[4]
    for i in temperature:
        if temperature[0] <= temperature[1] <= temperature[2] <= temperature[3] <= temperature[4]:
            return 0
        elif i > b:
            a = i - b
            if a > difference:
                difference = a
        elif i > c:
            a = i - c
            if a > difference:
                difference = a
        elif i > d:
            a = i - d
            if a > difference:
                difference = a
        elif i > e:
            a = i - e
            if a > difference:
                difference = a
    return difference

Do you have a better idea how my code complies with the big-O notation of O(n1) and is also fast enough for larger n, in other words lists with more than 5 integers?


texts:
It's about two months since I posted this question on CodeReview. I've been working hard to improve the code posted there and came up with the following.

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

typedef unsigned long long ull;

int main(void) {

    ull start=1, stop=100,cnt;
    register int t,len;
    char *str=calloc(33,sizeof(char));
    char *Alpha="abcdefghijklmnopqrstuvwxyz", *p1, *p2;
    int a_len=(int)strlen(Alpha);

    for (;start<=stop;++start) {

        cnt=start;

        /*
            This is used to construct a string from given alphabet.
            The generated string must be reversed
        */
        for (t = 0, len = 0; cnt; cnt = (cnt-1)/a_len, ++str, ++len, ++t)
            *str = Alpha[(cnt-1) % a_len];

        /*
            A bit odd but working (and important!) part of this code.
            As the str pointer was incremented during string generation,
            we need to 'reverse' it.
        */
        while ( t-- ) str--;

        /*
            This is used to reverse a string instead of strrev
        */
        for (p1 = str, p2 = str+len-1; p2>p1; ++p1, --p2) {
            *p1 ^= *p2;
            *p2 ^= *p1;
            *p1 ^= *p2;
        }

        printf("%llu --- %s\n",start,str);
    }

    free(str);

    return 0;
}

As you could have already guessed, this code generates letter combinations. The 'reversing' of a pointer (I'm not quite sure how to call this properly) is necessary because if one doesn't do that, he'll get a SegmentationFault as he'll be trying to access unallocated memory.

Example output

1 --- a
2 --- b
3 --- c
4 --- d
5 --- e
6 --- f
7 --- g
8 --- h
9 --- i
10 --- j

< omitted >

91 --- cm
92 --- cn
93 --- co
94 --- cp
95 --- cq
96 --- cr
97 --- cs
98 --- ct
99 --- cu
100 --- cv

This works quite well but I was wondering if it is possible to do the same thing even faster, if it is possible to omit the 'pointer revering' business.

Note: this code is different from the one I linked this question to because it doesn't use a function, thus, the technique and the algorithm are very different.


texts: Java8: Stream filter, map and joining with an alternative result if the stream is empty

texts:
Given a list of integers, I would like to:

filter odds numbers
produce a list inside brackets: [n1, n2, n3]
if the list is empty it should be a dash -

My current implementation is:

private static String doIt(List<Integer> list) {
    List<String> l = list.stream()
            .filter(i -> (i % 2 == 0))
            .map(Object::toString)
            .collect(Collectors.toList());

    if (l.isEmpty()) {
        return "-";
    }
    return l.stream()
            .collect(Collectors.joining("; ", "[", "]"));
}

I am wondering if it is possible to do it without the intermediate list result l.

There is a problem with following implementation:

private static String doIt(List<Integer> list) {
    return list.stream()
            .filter(i -> (i % 2 == 0))
            .map(Object::toString)
            .collect(Collectors.joining("; ", "[", "]"));
}

The result in case of empty list is [] (expected is -)

Test method:

public static void main(String[] args) {
    System.out.println(doIt(Arrays.asList(1, 2, 3)));
    System.out.println(doIt(Arrays.asList(2, 3, 4)));
    System.out.println(doIt(Arrays.asList(1, 3)));
}

Expected Result:

[2]
[2; 4]
-


texts: Comma Code - Ch. 4 Automate the Boring Stuff

texts:
I am new to programming and currently learning Python using "Automate the Boring" by Al Sweigart. I've just completed the "Comma Code" task in Chapter 4 and would like some feedback on my solution. The task is:

Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']

Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.

I tried to come up with something that mostly sticks to what you learn by this point in the book, but I did use .join() which is from a few chapters later. I also tried to make sure my code works with lists containing strings and/or integers, and for the output to be correct independent of list size (no comma when the list has two items, etc.).
your_list = ['item1', 'item2', 3, 'item4', 'item5', 'item6', 7, 'item8', 9]

def list_concatenator(your_list):
    items = len(your_list)
    if items == 0:
        return 'Your list is empty'

    elif items == 1:
        return "'" + str(your_list[0]) + "'"

    elif items == 2:
        return "'" + str(your_list[0]) + ' and ' + str(your_list[1]) + "'"

    else:
        your_list_split1 = (', '.join((map(str,your_list[:-1]))))
        return "'" + your_list_split1 + ', and ' + str(your_list[-1]) + "'"

list_concatenator(your_list)

I realize these exercises have been answered before, I'm just looking for some feedback on my solution.


texts: Type definitions for simple NPM package that generates OAuth 1.0a authorization header for Twitter API using native https nodejs module

texts:
I added type definitions to a simple npm package. I would love to get some feedback on ways to do better for the type definitions.
The package exports a single function which returns a function that returns a promise:
function request(httpsOptions, body) {
  return new Promise((resolve, reject) => {
    const req = https.request(httpsOptions, (res) => {
      let data = ''
      res.on('data', (_data) => {
        data += _data
      })
      res.on('end', () => {
        resolve(JSON.parse(data))
      })
    })
    req.on('error', (error) => {
      reject(error)
    })
    req.write(body)
    req.end()
  })
}

module.exports = (oAuthOptions) => ({
  subdomain = 'api',
  endpoint,
  requestMethod = 'GET',
  queryParams = {},
  bodyParams = {},
}) => {
  const baseUrl = buildBaseUrl(subdomain, endpoint)
  const body = buildBody(bodyParams)
  const url = buildUrl(baseUrl, queryParams)
  const httpsOptions = buildHttpsOptions(url, {
    requestMethod,
    body,
    baseUrl,
    queryParams,
    bodyParams,
    oAuthOptions,
  })
  return request(httpsOptions, body)
}

This is the type definition file that I created:
export type OAuthOptions = {
  api_key: string
  api_secret_key: string
  access_token: string
  access_token_secret: string
}

export type RequestOptions = {
  subdomain?: string
  endpoint: string
  requestMethod?: string
  queryParams?: Record<string, string>
  bodyParams?: Record<string, string>
}

export default function (
  oAuthOptions: OAuthOptions,
): <T>(requestOptions: RequestOptions) => Promise<T>

Any advise on how to do better with the type definitions is highly appreciated.


texts:
Note: A run is a series of adjacent chars that are the same.

I just want to answer a few questions:

Is this readable?
Does it need commenting or is it self-descriptive enough?
Are there any efficiency tweaks this could have?
Is this a good way to test?
Which is the preferred/conventional syntax?

int maxCheck = 0,
    maxRun = 1,
    currentRun = 1;`

vs.

int maxCheck = 0, maxRun = 1, currentRun = 1;

vs.

int maxCheck = 0;
int maxRun = 1,
int currentRun = 1;

I surmise this probably varies from individual to individual, but for this challenge in particular my instincts were to exclude spaces, but the challenge didn't specify this, and in the last challenge: my intuition, just as the first answer, also wanted me to include digits larger than 9, but that was actually 'wrong' and outside of the specifications of the challenge -- as was evidenced with failed tests (provided by the challenge).

Should I just take 'requirements' literally most of the time to avoid constructing technically 'incorrect' code? I ask since the tests in this case don't include spaces, and it's definitely something I'm wondering in case of larger, more abstract projects.

public class Standford2 {
    public static void main(String[] args) {
        System.out.println("Test 1: " + (1  == maxRun("123")));
        System.out.println("Test 2: " + (2  == maxRun("1223")));
        System.out.println("Test 3: " + (2  == maxRun("112233")));
        System.out.println("Test 4: " + (3  == maxRun("1112233")));
        System.out.println("Test 5: " + (2  == maxRun("hoopla")));
        System.out.println("Test 6: " + (3  == maxRun("hoopllla")));
        System.out.println("Test 7: " + (3  == maxRun("abbcccddbbbxx")));
        System.out.println("Test 8: " + (0  == maxRun("")));
        System.out.println("Test 9: " + (3  == maxRun("hhhooppoo")));
    }

    public static int maxRun(String str) {
        if (str.length() == 0) { return 0; }

        int maxCheck = 0,
            maxRun = 1,
            currentRun = 1;

        if (str.length() == 1) { return maxRun; }

        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == str.charAt(i - 1)) {
                currentRun++;
                if (currentRun > maxRun) { maxRun = currentRun; }
            }
            else { currentRun = 1; }
        }
        return maxRun;
    }
}


texts: Implementation of database access class [PHP]

texts:
I programmed a class for database access for my REST service. According to my understanding it should be implemented as singleton, because there can be a lot of simultaneous requests. Is there everything okay with this approach?

Is there a way to handle the getData... functions better? They basically do all the same thing, expect for the SQL query and the different parameters for the query.

Is it good to store the connection data (username, password..) in a JSON file?

Note that I've modified some lines from the actual code (SQL-queries and function names), because I think they are not relevant for my questions.

class DBManager {
protected static $con;
protected static $_instance = null;
protected function __construct() {
    $data = self::getConnectionData ();
    $host = $data ["host"];
    $name = $data ["name"];
    self::$con = new PDO ( "pgsql:host=$host;dbname=$name", $data ["user"], $data ["password"] );
}
protected function __clone() {}

public static function getInstance() {
    if (null === self::$_instance) {
        self::$_instance = new self ();
    }
    return self::$_instance;
}
protected function getConnectionData() {
    $raw = file_get_contents ( "conf/database.json" );
    $json = json_decode ( $raw, true );
    return $json;
}
public function getData1($year) {
    $query = "...";
    $stmt = self::$con->prepare ( $query );
    $stmt->bindParam ( 1, $year );
    $stmt->execute ();
    $result = $stmt->fetchAll ( PDO::FETCH_ASSOC );
    return $result;
}
public function getData2($year, $month) {
    $query = "...";
    $stmt = self::$con->prepare ( $query );
    $stmt->bindParam ( 1, $year );
    $stmt->bindParam ( 2, $month);
    $stmt->execute ();
    $result = $stmt->fetchAll ( PDO::FETCH_ASSOC );
    return $result;
}

// more getData functions...
}


texts: An installer for shell scripts, written in pure sh

texts:
I wrote a tiny shell script that basically installs a script into your system by copying it to someplace like /usr/local/bin, chmodding it, and adding it to your PATH. It works on both Unix and Windows (via an emulation layer like MSys or Cygwin). Its source code is available on GitHub. Here is the script in its entirety:

#!/bin/sh

set -e

help()
{
    echo 'sinister is a simple installer for shell scripts.'
    echo
    echo 'Usage: sinister -u url [options]'
    echo
    echo 'Options:'
    echo
    echo '-?,-h,--help: Print this help and exit.'
    echo '-c,--chmod: The mode to chmod your script. Defaults are a+x and u+x.'
    echo '-d,--debug: sinister should be run in debug mode.'
    echo '-l,--local: The script should be saved for the current user, instead of the entire machine.'
    echo '-n,--name: The name of the file the script should be saved to. Mandatory if no URL is given.'
    echo '-o,--output: The output directory the script should be saved to.'
    echo 'By default this is ~/bin on Unix systems, and C:\Users\you\AppData\Local\script on Windows.'
    echo '-u,--url: The location of the script online. e.g: https://github.com/you/repo/raw/master/script'
    echo 'If no URL is given the script is read from stdin.'
}

on_windows()
{
    uname | grep -q '[CYGWIN|MINGW|MSYS]'
}

per_user()
{
    test $LOCAL = 'true'
}

run_powershell()
{
    powershell -NoProfile -ExecutionPolicy Bypass "$1"
}

getpath_windows()
{
    run_powershell "[Environment]::GetEnvironmentVariable('PATH', '$1')"
}

setpath_windows()
{
    run_powershell "[Environment]::SetEnvironmentVariable('PATH', '$1', '$2')"
}

pwd_windows()
{
    run_powershell 'Get-Location'
}

CHMOD=
LOCAL='false'
NAME=
OUTPUT=
URL=

test $# -ne 0
while [ $# -gt 0 ]
do
    case "$1" in
        '-?'|-h|--help) help; exit 0 ;;
        -c|--chmod) CHMOD="$2"; shift ;;
        -d|--debug) set -x ;;
        -l|--local) LOCAL='true' ;;
        -n|--name) NAME="$2"; shift ;;
        -o|--output) OUTPUT="$2"; shift ;;
        -u|--url) URL="$2"; shift ;;
        *) help; exit 1 ;;
    esac
    shift
done

if [ -z "$CHMOD" ]; then
    if per_user; then
        CHMOD='u+x' # Executable for the current user
    else
        CHMOD='a+x' # Executable for all users
    fi
fi

if [ -z "$URL" ]; then
    test ! -z "$NAME"
    SCRIPT=$(< /dev/stdin) # read from standard input
else
    NAME=${URL##*/} # Grab everything after the last /
    if which curl > /dev/null 2>&1; then
        SCRIPT=$(curl -sSL "$URL")
    else # Assume wget is installed
        SCRIPT=$(wget -q -O - "$URL")
    fi
fi

if [ -z "$OUTPUT" ]; then
    if per_user; then
        if on_windows; then
            OUTPUT=~/AppData/Local/"$NAME"
        else
            OUTPUT=~/bin
        fi
    else
        if on_windows; then
            OUTPUT='/C/Program Files/$NAME'
        else
            OUTPUT='/usr/local/bin'
        fi
    fi
fi

# Use sudo on Unix
! on_windows && SUDO='sudo'

# Where the magic happens
$SUDO mkdir -p "$OUTPUT"
cd "$OUTPUT"
echo "$SCRIPT" | $SUDO tee "$NAME" > /dev/null
$SUDO chmod $CHMOD "$NAME"

# Add $OUTPUT to PATH if it's not in it
if ! which "$NAME" > /dev/null 2>&1; then
    if on_windows; then
        if per_user; then
            TARGET='User'
        else
            TARGET='Machine'
        fi
        CURRENT_PATH=$(getpath_windows $TARGET)
        CURRENT_DIRECTORY=$(pwd_windows)
        setpath_windows "$CURRENT_PATH;$CURRENT_DIRECTORY" $TARGET
    else # Unix
        CONTENTS="export PATH=\$PATH:$OUTPUT"
        if per_user; then
            echo "$CONTENTS" >> ~/.profile
        else
            sudo echo "$CONTENTS" >> /etc/profile
        fi
    fi
fi

Any feedback would be appreciated; I haven't tested this on Windows yet so some of the PowerShell snippets might be untested.


texts: Cleaning up complex if statements for Chess game

texts:
Shown below is a function I wrote for pawn move generation, I find it difficult to understand what the code does in a glance due to the cumbersome if statements, so any changes I make are done unnecessarily slowly. Is there a way to avoid these complex if statements so that the code is more maintainable?

  if(standardPawn.indexOf(this.board[position.y][position.x]) != -1){
          if(position.x + 1 < 8){
            if(board[position.y][position.x + 1].canEnpas === true && standardPawn.indexOf(board[position.y][position.x + 1]) == -1){
              moves.push({x: position.x + 1, y: position.y - 1});
            }
          }
          if(position.y == 6){
            if(board[position.y - 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y - 1});
            }
            if(board[position.y - 2][position.x] == "vacant" && board[position.y - 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y - 2});
            }
          } else if(position.y - 1 >= 0){
            if(board[position.y - 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y - 1});
            }
          }
          if(position.x + 1 < 8 && position.y - 1 >= 0){
            if(getPieceType({x: position.x + 1, y: position.y - 1}, this.board) != pieceType && board[position.y - 1][position.x + 1] != "vacant"){
              moves.push({x: position.x + 1, y: position.y - 1});
            }
          }
          if(position.x - 1 >= 0 && position.y - 1 >= 0){
            if(getPieceType({x: position.x - 1, y: position.y - 1}, this.board) != pieceType && board[position.y - 1][position.x - 1] != "vacant"){
              moves.push({x: position.x - 1, y: position.y - 1});
            }
          }
        } else {
          if(position.x + 1 < 8){
            if(board[position.y][position.x + 1].canEnpas === true && standardPawn.indexOf(board[position.y][position.x + 1]) != -1){
              moves.push({x: position.x + 1, y: position.y + 1});
            }
          }
          if(position.y == 1){
            if(board[position.y + 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y + 1});
            }
            if(board[position.y + 2][position.x] == "vacant" && board[position.y + 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y + 2});
            }
          } else if(position.y + 1 < 8){
            if(board[position.y + 1][position.x] == "vacant"){
              moves.push({x: position.x, y: position.y + 1});
            }
          }
          if(position.x + 1 < 8 && position.y + 1 < 8){
            if(getPieceType({x: position.x + 1, y: position.y + 1}, this.board) != pieceType && board[position.y + 1][position.x + 1] != "vacant"){
              moves.push({x: position.x + 1, y: position.y + 1});
            }
          }
          if(position.x - 1 >= 0 && position.y + 1 < 8){
            if(getPieceType({x: position.x - 1, y: position.y + 1}, this.board) != pieceType && board[position.y + 1][position.x - 1] != "vacant"){
              moves.push({x: position.x - 1, y: position.y + 1});
            }
          }
        }


texts: Implementation of portscanner for a host

texts:
I have tried to check whether the ports of a host from port 0 to port 1023 is open or not. Could someone please review this code and provide feedback.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netdb.h>
#include<error.h>
#include<errno.h>
char *convert_int_to_string(int num);

char *convert_int_to_string(int num)
{
    int tmp;
    int i = 0;
    int j = 0;
    static char a[5] = {'0'};

    while (num > 0) {
        tmp = num % 10;
        a[i++] = tmp + '0';
        num = num / 10;
    }
    a[i] = '\0';
    for (j = 0; j < i / 2; j++) {
        tmp = a[j];
        a[j] = a[i - j - 1];
        a[i - j - 1] = tmp;
    }
    return a;
}

int main(int argc, char **argv)
{
    int status;
    char *node;
    char *port_no;
    int sock_fd;
    int i = 0;
    struct  addrinfo hints, *serviceinfo;

    if (argc != 2)
        error(1, errno, "Too many or few arguments\n");
    node = argv[1];
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    for (i = 0; i < 1024; i++) {
        port_no = convert_int_to_string(i);
        status = getaddrinfo(node, port_no, &hints, &serviceinfo);
        if (status != 0) {
            error(1, errno, "error in getaddrinfo() function call\n");
        }
        sock_fd = socket(serviceinfo->ai_family, serviceinfo->ai_socktype, serviceinfo->ai_protocol);
        if (sock_fd == -1)
            error(1, errno, "error in socket() function call\n");
        status = connect(sock_fd, serviceinfo->ai_addr, serviceinfo->ai_addrlen);
        if (status != -1)
            printf("Port : %s is open\n", port_no);
        else
            printf("Port : %s is closed\n", port_no);
    }
}


texts: Setting zoom for layer disappearance in Leaflet

texts:
I have got 2 working codes, where one is a bit longer and another a bit shorter. Is it some way to bind all these layers as a one group?

The first one is:

 map.on('zoomend', function() {
if (map.getZoom() <6){
        map.removeLayer(job);
    }else{
    map.addLayer(job);
    }
    if (map.getZoom() <7){
        map.removeLayer(job2);
    }else{
    map.addLayer(job2);
    }
    if (map.getZoom() <8){
        map.removeLayer(job3);
    }else{
    map.addLayer(job3);
    }
  });

and another one

   map.on('zoomend', function() {
     if (map.getZoom() <8){
        map.removeLayer(job);
    }
    if (map.getZoom() <8){
        map.removeLayer(job2);
    }
    if (map.getZoom() <8){
        map.removeLayer(job3);
    }
     else {
        map.addLayer(job);
        map.addLayer(job2);
        map.addLayer(job3);
    }
   });

I would like to avoid this kind of repeats, as I am going to have multitude of layers in the future.


texts:
Background: I have created a program that allows a user to input information about their dog. The output is the bill they will receive commensurate their dog's weight.

The Problem: I believe I am doing this inefficiently. I don't like the way I have structured the current code and would like to improve upon my code. I would like critique from other programmers on how to improve this code

The Code:

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

namespace TheBarkingLotHasslerChasenB
{
    class Program
    {
        static bool isInt = false;
        static bool isDouble = false;

        static void Main(string[] args)
        {
            int id = 0;
            int age = 0;
            double weight = 0.0;

            id = HandleInput("Please enter your Owner ID", id);
            String name = HandleInput("Please enter the name of your dog");
            String breed = HandleInput("Please enter the breed of your dog");
            age = HandleInput("Please enter the age of your dog", age);
            weight = HandleInput("Please enter the weight of your dog", weight);

            DogOwner dogOwner = new DogOwner(id);

            Dog fido = new Dog(age, name, breed, weight);

            DetermineCost(fido.GetDogWeight());

            Console.Read();
        }

        private static int HandleInput(String input, int output)
        {
            do
            {
                Console.WriteLine(input);
                isInt = int.TryParse(Console.ReadLine(), out output);
                if (isInt)
                {
                    Console.WriteLine("");
                    return output;
                }

                Console.WriteLine("Please enter an integer value\n");

            } while (!isInt);

            return 0;

        }

        private static String HandleInput(String input)
        {
            String output;

            Console.WriteLine(input);

            output = Console.ReadLine();

            Console.WriteLine("");

            return output;
        }

        private static double HandleInput(String input, double output)
        {
            do
            {
                Console.WriteLine(input);
                isDouble = double.TryParse(Console.ReadLine(), out output);
                if (!isDouble)
                {
                    Console.WriteLine("Please enter a decimal value\n");
                }
                // If the user didn't enter a decimal, they are asked for input once again
                else
                {
                    Console.WriteLine("");
                    return output;
                }
            } while (!isDouble);

            return 0.0;
        }

        private static void DetermineCost(double weight)
        {
            if (weight < 15.0)
            {
                Console.WriteLine("Your bill for weekly day care is going to be: $55.00");
            }
            else if (weight > 15.0 && weight <= 30.0)
            {
                Console.WriteLine("Your bill for weekly day care is going to be: $75.00");
            }
            else if (weight > 30.0 && weight <= 80.0)
            {
                Console.WriteLine("Your bill for weekly day care is going to be: $105.00");
            }
            else
            {
                Console.WriteLine("Your bill for weekly day care is going to be: $125.00");
            }
        }
    }
}


texts:
Suppose there is a very big matrix and and a small window is moving on the matrix. The small window will move right and down, step by step (means each time move one step right, or move one step down). After each move, set all the values covered by the small window to be the average value of all values covered by the small window.

The major idea of my code is to maintain the current sum, and when moving right, subtract one column sum value, and add the rightmost new column value, and get average then reset matrix values. Similarly, when moving down, subtract one row sum value, and add the bottom most new row value, and get average then reset matrix values.

import random
from collections import defaultdict
class BigMatrix:
    def __init__(self, matrix, window_left_top_row, window_left_top_col, window_width, window_height):
        self.matrix = matrix
        self.window_left_top_row = window_left_top_row
        self.window_left_top_col = window_left_top_col
        self.window_width = window_width
        self.window_height = window_height
        self.init_window_sum()
    def init_window_sum(self):
        result = 0
        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):
            for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):
                result += self.matrix[r][c]
        self.sum_so_far = result
        a = result / (self.window_height * self.window_width)
        self.set_matrix_values(a)
    def set_matrix_values(self, v):
        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):
            for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):
                self.matrix[r][c] = v
    def move_right(self):
        if (self.window_left_top_col + self.window_width) >= len(self.matrix[0]):
            raise Exception('invalid move!')
        self.window_left_top_col += 1
        # update sum so far
        self.sum_so_far -= self.sum_so_far / self.window_width
        for r in range(self.window_left_top_row, self.window_left_top_row+self.window_height):
            self.sum_so_far += self.matrix[r][self.window_left_top_col+self.window_width-1]
        a = self.sum_so_far / (self.window_height * self.window_width)
        self.set_matrix_values(a)
    def move_down(self):
        if (self.window_left_top_row + self.window_height) >= len(self.matrix):
            raise Exception('invalid move!')
        # update sum so far
        self.window_left_top_row += 1
        self.sum_so_far -= self.sum_so_far / self.window_height
        for c in range(self.window_left_top_col, self.window_left_top_col+self.window_width):
            self.sum_so_far += self.matrix[self.window_left_top_row+self.window_height-1][c]
        a = self.sum_so_far / (self.window_height * self.window_width)
        self.set_matrix_values(a)
if __name__ == "__main__":
    row = 10
    col = 10
    matrix = []
    for i in range(row):
        r = []
        for j in range(col):
            r.append(random.randint(0,9))
        matrix.append(r)
    window_row = 0
    window_col = 0
    window_width = 2
    window_height = 2
    for r in matrix:
        print r
    print "======"
    b = BigMatrix(matrix, window_row, window_col, window_width, window_height)
    for r in b.matrix:
        print r
    print "======"
    b.move_right()
    for r in b.matrix:
        print r
    print "======"
    b.move_down()
    for r in b.matrix:
        print r


texts: Namedtuple and list to populate each record of a JSON file

texts:
I had a JSON file in this format:

{
    "cols": [
        "Employee",
        "start_time"
    ],
    "data": [
        [
            "Serena",
            "Sat, 22 Aug 2015 14:06:03 -0700"
        ],
        [
            "Rhonda",
            "Sun, 25 Mar 2012 10:48:52 -0700"
        ],
        [
            "Fleur",
            "Mon, 16 Dec 2013 07:20:26 -0800"
        ],
        [
            "Giselle",
            "Sat, 19 Apr 2008 23:47:21 -0700"
        ],
        [
            "Jeanette",
            "Thu, 06 Nov 2008 23:02:44 -0800"
        ],
        [
            "Iliana",
            "Sun, 13 May 2007 14:22:08 -0700"
        ],
        [
            "Geraldine",
            "Tue, 24 Jul 2012 08:43:58 -0700"
        ],
        [
            "Tatiana",
            "Thu, 08 Oct 2009 07:56:25 -0700"
        ],
        [
            "Jessamine",
            "Wed, 14 Jun 2006 12:03:42 -0700"
        ]
        [
            "Emily",
            "Tue, 06 Jan 2015 04:51:06 -0800"
        ],
        [
            "Sydnee",
            "Mon, 16 Dec 2013 11:28:04 -0800"
        ],
        [
            "Zorita",
            "Wed, 16 Dec 2009 11:22:18 -0800"
        ]

    ]
}

The file has Employee name and start time fields. I wanted to get every employee's name and start time and find the total time they have been  in the company (subtracting start time from current time).

I first loaded a JSON file using json.load() and then read each record in a loop and store it in a namedtuple. After that I added each namedtuple in a list.

import json
import pprint
import dateutil.parser
from collections import namedtuple
from datetime import datetime, timezone

file_name = "d:/a.json"
#Create a named tuple to store all data later,
# Total time is Current time - start_time
EmployeeData = namedtuple('EM', ["name", "start_time", "total_time"])

# Here I will store final list of all employee tuples
final_list = []

# Get string date as input and convert it to datetime object
def format_time(string_time):
    op_time = dateutil.parser.parse(string_time)
    return op_time

with open(file_name, "r") as data:
    json_data = json.load(data)
    for record in json_data["data"]:
        # Time in JSON file also has timezone so i have to use timezone.utc
        today = datetime.now(timezone.utc)
        # create date object from string date
        record[1] = format_time(record[1])
        # Find total number of days,
        tenure = (today - record[1]).days
        # create a tuple
        temp_tuple = EmployeeData(name=record[0], start_time = record[1], total_time = tenure)
        final_list.append(temp_tuple)

pprint.pprint(final_list)

Output:

 EM(name='Whitney', start_time=datetime.datetime(2015, 8, 7, 5, 37, 32, tzinfo=tzoffset(None, -25200)), total_time=1165),
 EM(name='Deirdre', start_time=datetime.datetime(2009, 8, 19, 15, 50, 27, tzinfo=tzoffset(None, -25200)), total_time=3343),
 EM(name='Alexandra', start_time=datetime.datetime(2007, 9, 5, 17, 31, 29, tzinfo=tzoffset(None, -25200)), total_time=4057),
 EM(name='Lila', start_time=datetime.datetime(2011, 8, 27, 8, 8, 47, tzinfo=tzoffset(None, -25200)), total_time=2606),
 EM(name='TaShya', start_time=datetime.datetime(2009, 1, 1, 18, 15, 1, tzinfo=tzoffset(None, -28800)), total_time=3573),
 EM(name='Kerry', start_time=datetime.datetime(2013, 6, 20, 13, 39, 30, tzinfo=tzoffset(None, -25200)), total_time=1942)]

I then sorted the record using:

sorted_time = sorted(final_list, key=lambda y: y.total_time)
print(sorted_time)

I would like to improve my code further since I will be dealing with a larger files soon. Is there any way to make it more efficient?


texts: Linked List: Smart Pointer Implementation

texts:
Linked list using smart pointers, iterative implementation. It amazes me how a std::forward_list does not allow the list to be walked until the last pointer is null.

I would appreciate if you could pay special attention to usage of shared_ptr.

#include <iostream>
#include <string>
#include <memory>
#include <cmath>

const int SIZE=7;

struct Node {
    int val;
    std::shared_ptr<Node> next;
};
std::shared_ptr<Node> newNode(int v) { // Create and return new node
    std::shared_ptr<Node> n(new Node);
    n->val = v;
    n->next = NULL;
    return n;
}
void print(std::shared_ptr<Node> r) { // Print the list
    while (r != NULL) {
        std::cout << r->val << ' ';
        r = r->next;
    }
    std::cout << std::endl;
}
int main() {
    std::shared_ptr<Node> root(new Node), last;
    srand(time(NULL));
    root->val = rand();
    root->next = NULL;
    last = root;
    for (int i=1; i<SIZE; ++i) { // Build the list
        last->next = newNode(rand());
        last = last->next;
    }
    last->next = NULL;
    print(root);
    std::cout << std::endl;
    return 0;
}


texts:
I've started learning JavaScript last week. Today I ran into a JS exercise available at this link
codewars exercise and decided to give it a try. I've used very basic JS because I know only a small number of JS methods. Could you please review and rate my code?

challenge text :

  Your task is to write a function named do_math that receives a single argument. This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it.

    Example : "24z6 1x23 y369 89a 900b"

  As shown above, this alphabet letter can appear anywhere within the number. You have to extract the letters and sort the numbers according to their corresponding letters.

    Example : "24z6 1x23 y369 89a 900b" will become 89 900 123 369 246 (ordered according to the alphabet letter)

  Here comes the difficult part, now you have to do a series of computations on the numbers you have extracted.

  The sequence of computations are + - * /. Basic math rules do NOT apply, you have to do each computation in exactly this order.
  This has to work for any size of numbers sent in (after division, go back to addition, etc).
  In the case of duplicate alphabet letters, you have to arrange them according to the number that appeared first in the input string.
  Remember to also round the final answer to the nearest integer.

    Examples :
        "24z6 1x23 y369 89a 900b" = 89 + 900 - 123 * 369 / 246 = 1299
        "24z6 1z23 y369 89z 900b" = 900 + 369 - 246 * 123 / 89 = 1414
        "10a 90x 14b 78u 45a 7b 34y" = 10 + 45 - 14 * 7 / 78 + 90 - 34 = 60

my code :

var inputStr, inputsArray, numsArray, arrayStrNumber, isAdd, isSub, isMul, isDiv;

numsArray = [];
strArray = [];
arrayStrNumber = [];
inputStr = "10a 90x 14b 78u 45a 7b 34y";

isAdd = true;
isSub = true;
isMul = true;
isDiv = true;

// create array from strings
inputsArray = inputStr.split(" ");

// loop in array

for (var i = 0; i < inputsArray.length; i++) {
  var inputValue = inputsArray[i];

  // seperate numbers from alphabet
  for (x = 0; x < inputValue.length; x++) {

    //   if it's not a number add it to string's array
    if (isNaN(inputValue[x])) {
      strArray[i] = inputValue[x];
    } else {
      isNaN(numsArray[i])
        ? (numsArray[i] = "" + inputValue[x] + "")
        : (numsArray[i] += "" + inputValue[x] + "");
    }
  }

  //create an array with letter on start
  arrayStrNumber[i] = strArray[i] + numsArray[i];
}
// sort array based on first alphabet or first number after alphabet
arrayStrNumber.sort(function (a, b) {
  if (a[0] != b[0]) {
    if (a > b) {
      return 1;
    }
    if (b > a) {
      return -1;
    }
    return 0;
  } else {
    if (arrayStrNumber.indexOf(a) > arrayStrNumber.indexOf(b)) {
      return 1;
    }
    if (arrayStrNumber.indexOf(b) > arrayStrNumber.indexOf(a)) {
      return -1;
    }
    return 0;
  }
});

console.log(arrayStrNumber);
// Do math operation with order +-*/
var finalResult = 0;
for (var i = 0; i < arrayStrNumber.length; i++) {
  arrayStrNumber[i] = parseInt(arrayStrNumber[i].slice(1));
  if (i === 0) {
    finalResult += arrayStrNumber[i];
    continue;
  }
  if (isAdd) {
    finalResult += arrayStrNumber[i];
    isAdd = false;
    continue;
  }
  if (isSub) {
    finalResult -= arrayStrNumber[i];
    isSub = false;
    continue;
  }
  if (isMul) {
    finalResult *= arrayStrNumber[i];
    isMul = false;
    continue;
  }
  if (isDiv) {
    finalResult /= arrayStrNumber[i];
  }
  isAdd = true;
  isSub = true;
  isMul = true;
  isDiv = true;
  finalResult = Math.round(finalResult);
}


texts:
I have to write a Blackjack game for college using the Processing language. It has to be done in a strict object-oriented approach, so I can't make an object of a class in another class unless there is some connection.

We have to use a Player interface:

interface Player {

  // This is the interface you are expected to implement for both
  // the computer controlled 'dealer' and the human player(s)

  // You can change the return types for any of the items in the interface.
  // You can also add arguments two the first two method listed below

  void twist(/* you can add an argument here */);               // This method should allow the player to add acard to their hand

  void updateValueOfHand(/* you can add an argument here */);   // Updates the the value of the cards the player has in their hand

  void stick();        // Called when the player does not want to take another card

  void updateScore();  // Updates the player's overall score (number of games they have won)

  int getValueOfHand(); // Getter method for the value of the cards the player has in their hand

  int getScore();      // Getter method for the player's overall score (number of games they have won)

  void showHand();     // Used to display the player's hand on screen

  void clearHand();    // Used at the end of a round to empty the cards in the player's hand

}

I have done a storyboard for the game:

interface Player
class Card
class Deck extends Card

class Computer implements Player
class Human implements Player

I am planning to have a class called ScoreTable where I can keep and show the scores and a Button class where I can draw the buttons.

What kind of classes should I have? Should I have a ScoreTable class which implements Player, and also a standalone Button class?


texts:
I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:

def my_min(num_list):
    minimum = num_list[0]
    for num in num_list[1:]:
        if num < minimum:
            minimum = num
    return minimum

My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?

My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.


texts:
I've asked a question about pinging a URL before, but I wanted something that was a bit shorter and still just as efficient.  libcurl seemed to be the perfect answer.  Here is my method:

/**
 * @fn int testConnection(void)
 * @brief Pings "https://www.google.com/" to test if there is an internet connection.  Timeout is set to three seconds.
 * @return Success value if connected to the internet.
 */
int testConnection(void)
{
    CURL *curl;
    CURLcode res = 0;
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, "https://www.google.com/");
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return res;
}

Is there anything "wrong" with this pinging method?  Are there any ways that I could make this method more efficient?


texts: Locate a number in an array with ascending even and descending odd entries

texts:
Below are two examples of arrays I have, with some given length:

For some value z, I want to find the column the value is in. MATLAB code I wrote:

if z == 1
   column = ceil(length/2);
elseif logical(mod(z,2))
   column = length - (z-3)/2;
else
   column = z/2;
end

It is correct I think. But ugly and possibly slow. Is there a one-liner in MATLAB that can do this?


texts: What is the best way to conditionally add to an immutable collection in Scala?

texts:
I find myself frequently trying to build up Seq's based on some conditionals, but the code I end up with feels verbose and clunky. An example:

def generateSeq(foo: Option[String]) = {
  Map("bar" -> "baz") ++ ( if (foo.isDefined) {
      Map("foo" -> foo.get)
    } else {
      Nil
    } )
}

If it were Python, I would simply do:

def generateObject(foo):
    obj = {}
    obj["bar"] = "baz"
    if foo: obj["foo"] = foo
    return obj

Is there a cleaner way to write the Scala code (especially as I add more logic and conditionals involved in building the map)?


texts:
I have created a query in which there is a column that calculates a percentage:

SELECT
     u.User_FirstName
    ,l.[Total Leads]
    ,SUM(s.SalesCount) AS [New Clients]
    ,c.Target
    ,CONVERT(VARCHAR, CONVERT(DECIMAL(11,0),ROUND((CONVERT(DECIMAL(11,2), SUM(s.SalesCount)) / l.[Total Leads]) * 100, 0))) + '%'

As you can see, that last column is my percentage column, which uses a lot of CONVERT.  I was wondering if there is a simpler or faster way to get a two-digit percentage in SQL Server 2008.


texts: Advent of Code 2019 Day 6 - Beginner Rust solution

texts:
I am doing Advent of Code 2019 in order to learn Rust (it's been fun, but challenging!).

I am looking for help and feedback from more experiences Rustaceans on my solution to Day 6: Universal Orbit Map in Rust.

Specifically I am looking to see where I am not doing it the idiomatic Rust way, where my Java background shines through or anything that doesn't look or feel right or Rust-ish.

use std::collections::HashMap;
use std::io;
use std::io::Read;

fn main() {
    let mut input = String::new();
    match io::stdin().read_to_string(&mut input) {
        Ok(v) => v,
        Err(_) => panic!("Unable to read input"),
    };
    let mut orbits = HashMap::new();
    input
        .lines()
        .map(|l| l.split(")").collect::<Vec<&str>>())
        .for_each(|o| {
            orbits.insert(o[1].to_string(), o[0].to_string());
        });
    let num_orbits = orbits
        .iter()
        .map(|k| path(k.0, &orbits))
        .map(|p| p.len())
        .sum::<usize>();

    let mut you_path = path("YOU", &orbits);
    let mut san_path = path("SAN", &orbits);

    while you_path.get(you_path.len() - 1) == san_path.get(san_path.len() - 1) {
        you_path.pop();
        san_path.pop();
    }

    println!(
        "Number of orbits: {}, Number of jumps: {}",
        num_orbits,
        (you_path.len() + san_path.len())
    );
}

fn path(from: &str, orbits: &HashMap<String, String>) -> Vec<String> {
    let mut p = Vec::new();
    let mut inner = from;
    loop {
        match orbits.get(inner) {
            Some(v) => {
                p.push(v.to_string());
                inner = v;
            }
            None => break,
        };
    }
    p
}


texts: Decision making inside a for loop and taking certain path based on output from gathered results

texts:
I would love to simplify my code, with better utilisation of for loop indexes. The goal is to change out all UP once for new UP once, which means take down each UP one and bring it up again. There should always be one in UP state while this process takes place, so I need to cover the following scenarios:

  up - up     == delete -> create -> delete -> create

  down - down == delete -> create -> delete -> create

  up - down   == delete -> create -> delete -> create

  down - up   == delete -> create -> delete -> create

  up          == create -> delete -> create

  down        == create -> delete -> create

This is what I have come up with, but I find it a bit cumbersome, and I', sure there is a room for an improvement.
For Instance could I go without using slices for holding the indexes countStateAvailable and countStateDown

fun myFunc() {
    var countStateAvailable []int
    var countStateDown []int
    lags := convertToDirectconnect(lagPair, amz.dcLags)
    vi := newVIFProvider(amz.dcRead, amz.dcWrite, bd, amz.trace, amz.pr)
    for i := 0; i < len(lags); i++ {
        if i == 0 {
            for j := 0; j < 2; j++ {
                vis, err := amz.dcRead.DescribeVirtualInterfaces(&directconnect.DescribeVirtualInterfacesInput{ConnectionId: lags[j].LagId})
                if err != nil {
                    return err
                }

                for k := 0; k < len(vis.VirtualInterfaces); k++ {
                    if *vis.VirtualInterfaces[k].OwnerAccount == cfg.RemoteAccountID {
                        if aws.StringValue(vis.VirtualInterfaces[k].VirtualInterfaceState) == directconnect.VirtualInterfaceStateAvailable {
                            countStateAvailable = append(countStateAvailable, j)
                        } else if aws.StringValue(vis.VirtualInterfaces[k].VirtualInterfaceState) == directconnect.VirtualInterfaceStateDown {
                            countStateDown = append(countStateDown, j)
                        }
                    }
                }
            }
        }

        if len(countStateAvailable) == 0 {
            fmt.Println("contains 1 or more down elements")
            err := amz.Create(cfg, nst)
            if err != nil {
                return err
            }
            return nil
        }

        // check if second or both elements are UP
        if countStateAvailable[0] == 1  || len(countStateAvailable) == 2 {
            fmt.Println("second or both elements are UP")
            err = vi.DeleteSingle(cfg, lags[i], i)
            cfg.Neighbors, err = vi.CreateSingle(cfg, lags[i], i)
            if err != nil {
                return err
            }
            err = vi.RestorePollSingle(cfg, lags[i], i)
            if err != nil {
                return err
            }
        } else if countStateAvailable[0] == 0 { // first element is UP, delete second element first
            fmt.Println("first element is UP, delete second element first")
            err = vi.DeleteSingle(cfg, lags[1], 1)
            cfg.Neighbors, err = vi.CreateSingle(cfg, lags[1], 1)
            if err != nil {
                return err
            }
            err = vi.RestorePollSingle(cfg, lags[1], 1)
            if err != nil {
                return err
            }

            err = vi.DeleteSingle(cfg, lags[0], 0)
            cfg.Neighbors, err = vi.CreateSingle(cfg, lags[0], 0)
            if err != nil {
                return err
            }
            err = vi.RestorePollSingle(cfg, lags[0], 0)
            if err != nil {
                return err
            }
            return nil
        } else {
            fmt.Println("contains 1 or more down elements")
            err := amz.Create(cfg, nst)
            if err != nil {
                return err
            }
            return nil
        }
    }

    fmt.Println("countStateAvailable: ", countStateAvailable)
    fmt.Println("countStateDown: ", countStateDown)

    return nil
}


texts:
My goal is to precisely calculate the current timezone using C++ standard library, represented as the difference (in seconds) between GMT time and local time.

Example: Italy is GMT+1 so my expected output is -3600. This offset represents the difference between GMT time (i.e. 12:00) and italian time (i.e. 13:00), ignoring daylight savings.

My actual code looks like this and it seems to work:

long timezone = 0;

bool _tzset() {
   std::time_t now = std::time(NULL);
   std::time_t local = std::mktime(std::localtime(&now));
   std::time_t gmt = std::mktime(std::gmtime(&now));
   timezone = static_cast<long> (gmt - local);
   return true;
}

From my understanding, what I'm doing here is getting the local time (ignoring DST) and the GMT time (ignoring DST) and just returning the difference.

It looks pretty straightforward but is it correct? Do you see any flaws?

EDIT: I was not clear about my real goal here. I am working on a Win32 framework that has to be ported to the Universal Windows Platform. The problem is that this framework uses a lot of CRT functions that are not supported anymore in the UWP. As you can see, _tzset() is one of them (also it looks like that the timezone variable is defined globally in a Win32 environment). In other words what I'm doing here is giving an alternative implementation to these unsupported functions. I can't change the signature of them.


texts: remove all nodes with same value in a linked list

texts:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

The following is my code:

ListNode *getNextElement(ListNode *head, bool& repeated){
    while ((head->next) != NULL &&
            (head->val == head->next->val)){
        head = head->next;
        repeated = true;
    }

    return head->next;
}

ListNode *deleteDuplicates(ListNode *head) {
    ListNode *result = NULL;
    ListNode *copy_result = result;
    ListNode *next = NULL;

    for (ListNode *cur = head; cur != NULL; cur = next){
        bool cur_repeat = false;
        next = getNextElement(cur, cur_repeat);

        if (cur_repeat == true){
            while(cur!=next){
                ListNode *toFree = cur;
                cur = cur->next;
                delete toFree;
            }
        }
        else{
            if(result == NULL){
                result = cur;
                copy_result = result;
            }
            else{
                result->next = cur;
                result = result->next;
            }
        }
    }

    if(result != NULL)
        result->next = NULL;
    return copy_result;
}