texts:
I'm looking for a code review on my Stack Implementation in Java. Specifically I am looking for correctness, style, and efficiency. Thank you!

public class MyStack<T> {
    private int top;
    private T[] stackArray;
    private int size;

    public MyStack(int size) {
        this.size = size;
        this.stackArray = (T[]) new  Object[size];
        this.top = -1;
    }

    public void push(T element) {
        if(isFull()) {
            throw new IndexOutOfBoundsException();
        }
        this.stackArray[++top] = element;
    }

    public T pop() {
        if(isEmpty()) {
            throw new NullPointerException("Stack is empty");
        }
        return this.stackArray[top--];
    }

    public boolean isFull() {
        if(this.top==(size - 1)) {
            return true;
        }
        return false;
    }

    public boolean isEmpty() {
        if(this.top== -1) {
            return true;
        }
        return false;
    }

    public int getTop() {
        return top;
    }

    public T[] getStackArray() {
        return stackArray;
    }

    public void setStackArray(T[] stackArray) {
        this.stackArray = stackArray;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }
}


texts:
I just want some feedback to improve readability and structure for this implementation of Hangman. The goal was to write it in a purely functional way. However, coming from an imperative background, I found it difficult to organize functional code.

function Hangman(word, revealed = word.replace(/\w/g, '_'), errors = 0) {
  const hasLost = errors > 5;
  const hasWon = !hasLost && word === revealed;

  const tryGuess = (letter, character, guess) =>
    new RegExp(letter, "i").test(character) ? character : '_';

  const revealCharacter = (letter, character, guess) => /_/.test(guess) ?
    tryGuess(letter, character, guess) : guess;

  const revealLetters = (letter, [head, ...rest], [guess, ...guessed]) => {
    const character = / /.test(head) ? ' ' : revealCharacter(letter, head, guess);
    return rest.length ?
      character + revealLetters(letter, rest, guessed) : character;
  }

  const getErrorCount = (guess, word, count) =>
    new RegExp(guess, "i").test(word) ? count : count + 1;

  const getResult = () => hasLost ? 'You lose' : 'You win';

  if (!hasWon && !hasLost) {
    this.guess = letter => new Hangman(word,
      revealLetters(letter, word, revealed),
      getErrorCount(letter, word, errors));
    console.log(revealed, errors);
  } else {
    console.log(getResult());
  }
}

const game = new Hangman('Agile Development');
game.guess('e').guess('a').guess('t').guess('z');

UPDATE: Below is the revised edition of the code with the advised changes. The code base looks much cleaner and I decided to try to stick to only using primitives and functions. Having each function accomplish a single task increased the code size, but definitely improved the readability and maintainability of the code.

function Hangman(text, revealed = null, errors = 0) {
  { // constructor
    if (revealed === null) {
      return Hangman(text, revealMatch(/\s/g, text), 0);
    }

    if (isDone()) {
      console.info(getGameStatus());
    } else {
     console.info(arguments);
      return makeGuess;
    }
  }

  function createMatchedCharacterList(matcher) {
    return (revealed, actual, index) => {
      if (matcher.test(actual)) {
        revealed[index] = actual;
      }
      return revealed;
    }
  }

  function revealMatch(matcher, text) {
    return text.split('').reduce(createMatchedCharacterList(matcher), [])
  }

  function revealCharacter(guess) {
    return Object.assign([], revealed, revealMatch(new RegExp(guess, 'i'), text));
  }

  function makeGuess(guess) {
    return (hasCharacter(guess) && !hasGuessed(guess)) ?
      Hangman(text, revealCharacter(guess), errors) :
      Hangman(text, revealed, errors + 1);
  }

  function hasCharacter(character) {
    return text.search(character) > -1;
  }

  function hasGuessed(guess) {
    return revealed.join('').search(guess) > -1;
  }

  function hasLost() {
    return errors > 5;
  }

  function hasWon() {
    return text === revealed.join('');
  }

  function isDone() {
    return hasLost() || hasWon();
  }

  function getGameStatus() {
    return isDone() ? hasLost() ? 'You lose' : 'You win' : 'Incomplete';
  }
}

console.log(Hangman('eatz')('e')('a')('t')('z'));


texts: Small method that runs various processes

texts:
I have a project which runs from a db table - it's purpose is to run processes written in various ways.

Currently it deals with python scripts, vbs scripts and console exe files.

It works but I'm wondering if there any obvious refactors?

private Process aProcess;

public void runProcess(string aPath,string aName,string aFiletype)
{

  aProcess = new Process();
  string stInfoFileName = null;
  string stInfoArgs = null;
  bool blUseShell = false;

  //if it is to call a python script
  if(aFiletype == "py")
  {
    stInfoFileName = @"python.exe";
    stInfoArgs = string.Format("\"{0}{1}{2}\"",aPath,Path.DirectorySeparatorChar,aName);
  }

  //if it is to call console app exe
  if(aFiletype == "exe")
  {
    stInfoFileName = aName;
    stInfoArgs = string.Format("\"{0}{1}{2}\"",aPath,Path.DirectorySeparatorChar,aName);
    blUseShell = true;
  }

  //if it is to run vbs script
  if(aFiletype == "vbs")
  {
    stInfoFileName = "cscript";
    stInfoArgs = string.Format("/B \"{0}{1}\"",@aPath,@aName);
  }

  aProcess.StartInfo.FileName = stInfoFileName;
  aProcess.StartInfo.Arguments = stInfoArgs;

  aProcess.StartInfo.WorkingDirectory = aPath;           //<< does not seem to need the extra quotes

  aProcess.StartInfo.UseShellExecute = blUseShell;
  aProcess.StartInfo.RedirectStandardOutput = false;

  aProcess.Start();

  this.aProcess.WaitForExit();
  this.aProcess.Dispose();

}


texts:
Please, review the code:

#include <iostream>
using namespace std;

template <class T>
struct Node
{
  Node(T data) : data(data), next(NULL), prev(NULL) {}
  T data;
  Node * next;
  Node * prev;
};

template <class T>
class DoublyLinkedList
{
public:
  DoublyLinkedList() : head(NULL), tail(NULL) {}
  DoublyLinkedList(const DoublyLinkedList<T> & dll);
  ~DoublyLinkedList();
  void addNode(T data);
  //void insertNodeBefore(int data, int before);
  //void insertNodeAfter(int data, int after);
  void deleteNode(T data);
  template <class U>
  friend std::ostream & operator<<(std::ostream & os, const DoublyLinkedList<U> & dll);
private:
  Node<T> * head;
  Node<T> * tail;
};

template <class U>
std::ostream & operator<<(std::ostream & os, const DoublyLinkedList<U> & dll)
{
  Node<U> * tmp = dll.head;
  while (tmp)
    {
      os << tmp->data << " ";
      tmp = tmp->next;
    }

  return os;
}

template <class T>
DoublyLinkedList<T>::~DoublyLinkedList()
{
  Node<T> * tmp = NULL;
  while (head)
    {
      tmp = head;
      head = head->next;
      delete tmp;
    }
  head = tail = NULL;
}

template <class T>
void DoublyLinkedList<T>::addNode(T data)
{
  Node<T> * t = new Node<T>(data);

  Node<T> * tmp = head;
  if (tmp == NULL)
    {
      head = tail = t;
    }
  else
    {
      while (tmp->next != NULL)
        {
          tmp = tmp->next;
        }

      tmp->next = t;
      t->prev = tail;

      tail = t;
    }
}

template <class T>
void DoublyLinkedList<T>::deleteNode(T data)
{
  Node<T> * tmp = head;
  while (tmp && tmp->data != data)
    {
      tmp = tmp->next;
    }

  if (tmp)
    {
      if (tmp->prev && tmp->next) // no change to head or tail
        {
          tmp->prev->next = tmp->next;
          tmp->next->prev = tmp->prev;
        }
      else if (tmp->prev) // change to tail
        {
          tmp->prev->next = tmp->next;
          tail = tmp->prev;
        }
      else if (tmp->next) // change to head
        {
          tmp->next->prev = tmp->prev;
          head = tmp->next;
        }

      delete tmp;
    }
}

template <class T>
DoublyLinkedList<T>::DoublyLinkedList(const DoublyLinkedList<T> & dll)
{
  Node<T> * tmp = dll.head;
  while (tmp)
    {
      this->addNode(tmp->data);
      tmp = tmp->next;
    }
}

int main()
{
  DoublyLinkedList<int> dll;

  dll.addNode(1);
  dll.addNode(2);
  dll.addNode(3);
  dll.addNode(4);
  dll.addNode(5);

  cout << dll << endl;
  DoublyLinkedList<int> dll2(dll);
  cout << dll2 << endl;

  dll.deleteNode(3);
  dll.deleteNode(1);
  dll.deleteNode(5);

  cout << dll << endl;
  cout << dll2 << endl;

  return 0;
}


texts:
Recently I had an interview where it was asked:

  Given a list of people with their birth and end years find the year with the most number of people alive.

I implemented in Java and was trying to find the optimal solution. I am sure there might be some data structure which will be optimal to use in this scenario.

static class Person {
    int born;
    int died;

    Person(int born, int died) {
        this.born = born;
        this.died = died;
    }
}

/*
 * (1920, 1939),
 * (1911, 1944),
 * (1920, 1955),
 * (1938, 1939),
 * (1920, 1939),
 * (1911, 1944),
 * (1920, 1955),
 * (1938, 1939),
 * (1937, 1940)
 *
 */

public static void main(String[] args) {
    List<Person> people = new ArrayList<>();
    people.add(new Person(1933, 1989));
    people.add(new Person(1920, 1939));
    people.add(new Person(1911, 1944));
    people.add(new Person(1920, 1955));
    people.add(new Person(1938, 1939));
    people.add(new Person(1920, 1939));
    people.add(new Person(1911, 1944));
    people.add(new Person(1920, 1955));
    people.add(new Person(1938, 1939));
    people.add(new Person(1937, 1940));
    System.out.println(solution1(people));

}

public static int solution1(List<Person> people) {
    HashMap<Integer, Integer> peopleMap = new HashMap<>();
    int maxCount = 0;
    int year = 0;
    for (Person p : people) {
        for (int i = p.born; i <= p.died; i++) {
            Integer value = peopleMap.get(i);
            if (value == null) {
                peopleMap.put(i, 1);
            } else {
                value++;
                if (maxCount < value) {
                    maxCount = value;
                    year = i;
                }
                peopleMap.put(i, value);
            }
        }
    }
    return year;
}


texts: Univariate linear regression from scratch in Python

texts:
I am relatively new to machine learning and I believe one of the best ways for me to get the intuition behind most algorithms is to write them from scratch before using tons of external libraries.

This classifier I wrote seems to be yielding reasonable results based on the dataset I provided. This dataset is based on the number of hours that a student studied for a test (x), and the score this same student got in the test (y).

I tried to exploit OOP as much as I could, instead of using a procedural approach to write the algorithm.

Would you mind giving me your opinions and comments about this code? This is also important because I'll be adding to my portfolio. Are there some missing good practices in the code? What would you recommend keeping and removing in a professional setting or for life as a developer?

Univariate linear regression algorithm:

# Linear equation based on: y = m * x + b, which is the same as h = theta1 * x + theta0
import numpy as np

class LinearRegressionModel():
    """
    Univariate linear regression model classifier.
    """

    def __init__(self, dataset, learning_rate, num_iterations):
        """
        Class constructor.
        """
        self.dataset = np.array(dataset)
        self.b = 0  # Initial guess value for 'b'.
        self.m = 0  # Initial guess value for 'm'.
        self.learning_rate = learning_rate
        self.num_iterations = num_iterations
        self.M = len(self.dataset) # 100.
        self.total_error = 0

    def apply_gradient_descent(self):
        """
        Runs the gradient descent step 'num_iterations' times.
        """
        for i in range(self.num_iterations):
            self.do_gradient_step()

    def do_gradient_step(self):
        """
        Performs each step of gradient descent, tweaking 'b' and 'm'.
        """
        b_summation = 0
        m_summation = 0
        # Doing the summation here.
        for i in range(self.M):
            x_value = self.dataset[i, 0]
            y_value = self.dataset[i, 1]
            b_summation += (((self.m * x_value) + self.b) - y_value) # * 1
            m_summation += (((self.m * x_value) + self.b) - y_value) * x_value

        # Updating parameter values 'b' and 'm'.
        self.b = self.b - (self.learning_rate * (1/self.M) * b_summation)
        self.m = self.m - (self.learning_rate * (1/self.M) * m_summation)
        # At this point. Gradient descent is finished.

    def compute_error(self):
        """
        Computes the total error based on the linear regression cost function.
        """
        for i in range(self.M):
            x_value = self.dataset[i, 0]
            y_value = self.dataset[i, 1]
            self.total_error += ((self.m * x_value) + self.b) - y_value
        return self.total_error

    def __str__(self):
        return "Results: b: {}, m: {}, Final Total error: {}".format(round(self.b, 2), round(self.m, 2), round(self.compute_error(), 2))

    def get_prediction_based_on(self, x):
        return round(float((self.m * x) + self.b), 2) # Type: Numpy float.

def main():

    # Loading dataset.
    school_dataset = np.genfromtxt(DATASET_PATH, delimiter=",")

    # Creating 'LinearRegressionModel' object.
    lr = LinearRegressionModel(school_dataset, 0.0001, 1000)

    # Applying gradient descent.
    lr.apply_gradient_descent()

    # Getting some predictions.
    hours = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    for hour in hours:
        print("Studied {} hours and got {} points.".format(hour, lr.get_prediction_based_on(hour)))

    # Printing the class attribute values.
    print(lr)

if __name__ == "__main__": main()

Dataset snippet:

32.502345269453031,31.70700584656992
53.426804033275019,68.77759598163891
61.530358025636438,62.562382297945803
47.475639634786098,71.546632233567777
59.813207869512318,87.230925133687393
55.142188413943821,78.211518270799232
52.550014442733818,71.300879886850353
45.419730144973755,55.165677145959123


texts:
I wrote a anonymous event creator. I would like to ask if anyone can tell me if I did it the "right" or "best" way, or how I could make it better.

Here is what I did:

Declaration:

  TAnonymousEvents<TTEventPointer,TTEventReference>=class
  public
    class function Create(AEvent:TTEventReference):TTEventPointer;
  end;

Implementation:

class function TAnonymousEvents<TTEventPointer,TTEventReference>.Create(AEvent: TTEventReference): TTEventPointer;
type
  TVtable = array[0..3] of Pointer;
  PVtable = ^TVtable;
  PPVtable = ^PVtable;
begin
  TMethod(result).Code := PPVtable(AEvent)^^[3];
  TMethod(result).Data := Pointer(AEvent);
end;

Usage:

.....

type TNotifyEventReference = reference to procedure (Sender: TObject);

.....

procedure TForm1.FormCreate(Sender: TObject);
begin
  Button1.OnClick := TAnonymousEvents<TNotifyEvent,TNotifyEventReference>.Create(
    procedure (Sender:TObject)
    begin
      ShowMessage('it works!');
    end
  );
end;


texts:
I am using 2 functions written in Python to convert a DLG file to PDB energies:
import glob
import os
import subprocess
import numpy as np
from vmd import vmdnumpy as vnp
from vmd import Molecule
from vmd import atomsel

def dlg_to_multiframepdb(fname):
        inputstrings = subprocess.check_output("grep \"DOCKED:\" %s" % fname, shell=True).decode().split("\n")
        output = ""
        for s in inputstrings:
                if s[8:12] == "ATOM" or s[8:12] == "HETA":
                        output += s[8:] + "\n"
                elif s[8:14] == "ENDMDL":
                        output += "ENDMDL\n"
        return output

def dlg_to_energy(fname):
        inputstrings = subprocess.check_output("grep \"Estimated\" %s | sed 's/=//g' | awk '{print $8}'" % fname, shell=True).decode().split("\n")[:-1]
        energies = np.array(inputstrings).astype(np.float)
        return energies

# simple code: loop over the directory of DLG filles and convert each file to PDB
pwd = os.getcwd()
dlg= 'dlg'
#set directory to analyse
data = os.path.join(pwd,dlg)

dirlist = [os.path.basename(p) for p in glob.glob(data + '/*.dlg')]
os.chdir(data)
for dlg_file in dirlist:
      energies = dlg_to_energy(dlg_file)
      pdb = dlg_to_multiframepdb(dlg_file)

Briefly, the first function takes some part from the initial file using shell utility GREP, skipping some unused strings; and the second function - use GREP + SED to take specific strings from the same file and store it as a numpy array. How can the code be further improved?


texts: Simple parallel foreach loop code correctness

texts:
I have both the regular for each loop and its equivalent paralleled version.  The loop simply iterates through a collection, looking for the rate key in a local db instance and then updating the topic code.

using (var db = new SomeEntities())
{
    foreach (var measure in measures)
    {
        var keytofind= measure.RateKey.ToString(CultureInfo.InvariantCulture);
        var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
        if (firstOrDefault != null)
            measure.TopicCode = firstOrDefault.TopicCode;
    }

    Parallel.ForEach(measures, measure=>
    {
        var keytofind= rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture);

        lock(measure)
        {
            var firstOrDefault = db.RatesMappings.FirstOrDefault(r => r.RateKey == keytofind);
            if (firstOrDefault != null)
                measure.TopicCode = firstOrDefault.TopicCode;
        }
    });
}

Is the paralleled code correct and has the lock been placed correctly?


texts: Type that returns a result based on some logic

texts:
I have a type that returns a result based on some logic. The result contains a message. Should a good unit test check that the message is correct?

A negligible amount has changed as I'm not allowed to post IP:

class MyFilter
{
    private readonly int _state;

    public Result FilterResult { get; private set; }

    public MyFilter(int value)
    {
        _state = value;
    }

    public void Initialise()
    {
        string message;

        if (_state == 0)
        {
            message = "filtered because zero";
            FilterResult = new Result {ShouldFilter = true, Reason = message};
            log(message);
        }
        else if(_state == 1)
        {
            message = "filtered because one";
            FilterResult = new Result {ShouldFilter = true, Reason = message};
            log(message);
        }
        else
        {
            message = "not filtered because...";
            FilterResult = new Result {ShouldFilter = false, Reason = message};
            log(message);
        }
    }

    public bool ShouldFilter()
    {
        return FilterResult.ShouldFilter;
    }

    private void log(string message) { }
}

I want to test this type.  I want to test that it correctly sets the ShouldFilter flag on the result.  But I also want to test why it thinks it should filter or not, so I'm checking the string on the result too:

    [Test]
    public void When_zero()
    {
        MyFilter sut = new MyFilter(0);
        sut.Initialise();
        Assert.AreEqual(true, sut.FilterResult.ShouldFilter);
        Assert.AreEqual("filtered because zero", sut.FilterResult.Reason);
    }

I had some feedback on an internal code review saying that testing strings was a code smell;  if someone changes the string, the test will fail even though the behaviour may still be the same.

I personally think that, in this case, it's OK to test the string: the fact that the type thinks something is filtered is just part of the answer; I want to know why it thinks it should be filtered.

That's the crux of the question. It's not my ideal style of code, so, to give a little context, I'll explain what the code did before I inherited it:

The filter just used to log the reason why it was filtering. FilterResult didn't exist.  The code was just this:

class MyFilter
{
    private readonly int _state;
    private bool _filtered;

    public MyFilter(int value)
    {
        _state = value;
    }

    public void Initialise()
    {
        if (_state == 0)
        {
            _filtered = true;
            log("filtered because zero");
        }
        else if(_state == 1)
        {
            _filtered = true;
            log("filtered because one");
        }
        else
        {
            _filtered = false;
            log("not filtered because...");
        }
    }

    public bool ShouldFilter() => _filtered;

    private void log(string message) { }
}

This type was hard to test. The logic could change for the worse and it would be likely that the tests would still pass as they were just checking the binary ShouldFilter().

What I would've liked to have done, and what I normally do for important 'messages', is inject an INotifySupport interface as a dependency (have used this for years since reading this fine book), and rather than just logging these messages, I would call _notifySupport.OfSomethingFilterRelated(reason). I could then write a test named liked SupportWereNotified.

But I couldn't do that this time, so I exposed the Result property.

Anyway, bit of a convoluted post, so I'd better reiterate the question:

Should a good unit test check that the message is correct?


texts: Reading text from the web and writing to a JSON file

texts:
This code reads text from the web using a WebDriver element and writes data to a JSON file. I had to use if-else (to write only the last line to the JSON file) just because of the asynchronous behaviour of NodeJs, otherwise I was trying to add fs.appendFile(filepath,"}") in the end to close the JSON file.

I just want you to optimize this snippet as I am new to NodeJs.

saveListOfAllCitiesIntoJsonFile () {
    var filePath = './Data/AllCitiesAvailableOnWeb.json';
    var CITY_COUNT = pageElements["CityCount"];
    var AllCity = homePageElements['AllCity'];
    var CityList = homePageElements['CityList'];
    super.findElementByClassName(AllCity).click();
    super.findElementsByClassName(CityList).then(function (element_CityName) {
        fs.truncate(filePath, 0);
        fs.appendFile(filePath, "{" + "\n");
        var jsonData = null;
        var elementData = null;
        for (var i = 0; i < CITY_COUNT; i++) {
            elementData = element_CityName[i].getText();
            if (i === CITY_COUNT - 1) {
                elementData.then(function (text) {
                    jsonData = "\"" + text + "\"" + ": " + "\"/hotels-in-" + text;
                    fs.appendFile(filePath, jsonData + "\"" + "\n" + "}", function (err) {
                        if (err) {
                            console.log(err);
                        }
                    });
                });
            }
            else {
                elementData.then(function (text) {
                    jsonData = "\"" + text + "\"" + ": " + "\"/hotels-in-" + text;
                    fs.appendFile(filePath, jsonData + "\"," + "\n", function (err) {
                        if (err) {
                            console.log(err);
                        }
                    });
                });
            }
        }
    });
}


texts:
I have pieced together some code that works for my project. However, it is pretty long, but self-similar. I am a jQuery beginner and I tried to shorten the code by using variables, but it didn't work so far. I guess I should use some for()-statement. Could you help me to simplify this code?

//apply the class "active" to the menu items whose div is in the viewport and animate
$('#home').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(1)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(1) a').css( {'color': 'white'} );
    $('#nav li:nth-child(1)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(1)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(1) a').css( {'color': 'black'} );
    $('#nav li:nth-child(1)').stop().animate({opacity: 0.2}, 500);
    }
});
$('#referenzen').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(2)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(2) a').css( {'color': 'white'} );
    $('#nav li:nth-child(2)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(2)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(2) a').css( {'color': 'black'} );
    $('#nav li:nth-child(2)').stop().animate({opacity: 0.2}, 500);
    }
});
$('#unternehmen').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(3)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(3) a').css( {'color': 'white'} );
    $('#nav li:nth-child(3)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(3)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(3) a').css( {'color': 'black'} );
    $('#nav li:nth-child(3)').stop().animate({opacity: 0.2}, 500);
    }
});
$('#taetigkeit').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(4)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(4) a').css( {'color': 'white'} );
    $('#nav li:nth-child(4)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(4)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(4) a').css( {'color': 'black'} );
    $('#nav li:nth-child(4)').stop().animate({opacity: 0.2}, 500);
    }
});
$('#kontakt').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(5)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(5) a').css( {'color': 'white'} );
    $('#nav li:nth-child(5)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(5)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(5) a').css( {'color': 'black'} );
    $('#nav li:nth-child(5)').stop().animate({opacity: 0.2}, 500);
    }
});
$('#anfahrt').bind('inview', function (event, visible) {
    if (visible == true) {
    $('#menu li:nth-child(6)').stop().animate(
            {backgroundPosition:"(0 0)"},
            {duration:500});
    $('#menu li:nth-child(6) a').css( {'color': 'white'} );
    $('#nav li:nth-child(6)').stop().animate({opacity: 1}, 500);
    } else {
    $('#menu li:nth-child(6)').stop().animate(
            {backgroundPosition:"(-200px 0)"},
            {duration:500});
    $('#menu li:nth-child(6) a').css( {'color': 'black'} );
    $('#nav li:nth-child(6)').stop().animate({opacity: 0.2}, 500);
    }
});


texts: Get a value from a list in Sharepoint 2010

texts:
I am using SharePoint 2010 and get values from a list using the code below.

It might be called like this: getValueFromList("addresses", "secondName", "city", "manhattan");

It will return the "secondName" of the first entry that has "city = manhattan". Is there a way to make it more efficient?

private string getValueFromList(string theList, string returnColumnName,   string matchColumnName, string valueToMatch)
{
    try
    {
        SPSite siteh2 = SPContext.Current.Site;

        using (SPWeb oWeb = siteh2.OpenWeb())
        {

            //SPWeb oWeb = SPControl.GetContextSite(Context).OpenWeb();
            SPList oList = oWeb.Lists[theList];

            SPQuery oQuery = new SPQuery();
            oQuery.Query = "<Where><Eq><FieldRef Name='" + matchColumnName + "' />" +
                "<Value Type='Text'>" + valueToMatch + "</Value></Eq></Where>";

            //oQuery.Query = "<Query><Where><Eq><FieldRef Name='Username' /><Value Type='Text'>whelanp</Value></Eq></Where></Query>";

            SPListItemCollection results = oList.GetItems(oQuery);

            if (results.Count == 0)
                return "";

            foreach (SPListItem oListItem in results)
            {
                return cleanValue(oListItem[returnColumnName].ToString());
            }
            return "";
        }
    }
    catch (Exception ex)
    {
        return "";
    }
}


texts:
I am trying to increase my understanding of classes, so I tried to implement a simple address book program that holds ten names with that names corresponding address. The program works correctly and I am proud of what I have done so far, but I am looking to see if there is any aspect that can be made better, and or needs to be changed.

Class:

#pragma once
#include <iostream>
#include <string>

class Person
{
    friend std::istream &read(std::istream &is, Person add_book[10]);
    friend std::ostream &print(std::ostream &os, const Person add_book[10]);

public:
    Person& Person::sort_addbook(Person add_book[10]);
    Person();
    ~Person();
private:
    std::string name;
    std::string address;
};

Member functions:

#include "Person.h"

std::istream &read(std::istream &is,Person add_book[10]) {
    for (int count = 0; count < 10; count++) {
        is >> add_book[count].name; // get name
        std::getline(is,add_book[count].address); // get address from input
    }
    return is;
}

std::ostream &print(std::ostream &os, const Person add_book[10]) {
    for (int count = 0; count < 10; count++) {
        os << "Name: " << add_book[count].name << std::endl << "Adress: "
        << add_book[count].address << std::endl << std::endl; //output contents of address book
}
    return os;
}

//use bubble sort to sort address book alphabetically by name
Person& Person::sort_addbook(Person add_book[10]) {
    for (int pass = 0; pass < 10; pass++) {
        for (int i = 0; i < 9; i++) {
            if (add_book[pass].name < add_book[i].name)
                swap(add_book[pass].name, add_book[i].name);
        }
    }
    return *this;
}

Person::Person()
{
}

Person::~Person()
{
}

Main function:

#include <iostream>
#include "Person.h"

/*create address book that stores name + address,
sort that adress into alphabetical order, print address book.*/

int main() {

    Person address_book[10]; //stores name in column 1, address in column 2

    std::cout << "Enter name, and then address: " << std::endl;
    read(std::cin,address_book); //get user input

    address_book[10].sort_addbook(address_book); //sort addressbook
    std::cout << std::endl;

   print(std::cout, address_book); //print contents of addressbook

   system("pause");
}


texts:
On a game I'm working curently I keep on memory a simplified representation of the map which only have solid and non-solid cells. I need to get the outline of the shapes that adjacent cells might create, something like this:

I do not have a 8×8 array of bools on memory but a container of cell1 objects:

struct point { int x{}, y{}; };
struct line { point b{}, e{}; };
struct cell
{
    int x{}, y{};
    std::array<line, 4> lines() const
    {
        return
        {{
            {{x + 0, y + 0}, {x + 0, y + 1}},
            {{x + 0, y + 0}, {x + 1, y + 0}},
            {{x + 0, y + 1}, {x + 1, y + 1}},
            {{x + 1, y + 0}, {x + 1, y + 1}},
        }};
    };
};

Mi goal is to obtain a container with all the otulines, for example the outlines of the square at the top right corner are:

{
    // Vertical line (x6) that starts at position y0 and ends at position y2
    {{6, 0}, {6, 2}},
    // Horizontal line (y0) that starts at position x6 and ends at position x8
    {{6, 0}, {8, 0}},
    // …
    {{6, 2}, {8, 2}},
    // …
    {{8, 0}, {8, 2}}
}

The algorithm I'm using have the following steps:

Transform cells to lines.
Save lines into container, if the line is already on that container: delete it (this Will get rid of lines inside shapes).
Test each line against the others, if two lines are colinear and the end of one is the beggining of the other: merge it.

template <template <typename> typename container_t>
auto vertex_of(const container_t<cell> &cells)
{
    std::set<line> outlines;

    for (const auto &cell : cells)
        // Transform cells to lines
        for (const auto &line : cell.lines())
            // Save lines into temp container
            if (auto [i, b] = outlines.insert(line); !b)
                // If the line is already on the container: delete it
                outlines.erase(i);

    std::vector<line> result;
    // Test each line against the others, if two lines are colinear and the end of one
    // is the beggining of the other: merge it.
    for (const auto &outline : outlines)
    {
        if (std::find_if(result.begin(), result.end(), [&b = outline](line &a)
        {
            bool result{};
            if ((result = (a.e == b.b) && ((a.b.x * (b.b.y - b.e.y)) + (b.b.x * (b.e.y - a.b.y)) + (b.e.x * (a.b.y - b.b.y)) == 0)))
                a.e = b.e;
            return result;

        }) == result.end())
        {
            result.push_back(outline);
        }
    }

    return result;
}

Code Snippet available here, I have the feeling that it have lots of room for improvement.

1cell is more complex, but the additional complexity is out of the scope right now, so I'll keep things simple.


texts:
I am working on my template web api project.

I just wanna hear any suggestion how to improve this code. I heard that repository pattern is anti pattern so I want to make code without it. Any opinion will be great :D

Service

public class TemplateService : ITemplateService
{
    private readonly ContextTemplate context;

    public TemplateService(ContextTemplate context)
    {
        this.context = context;
    }

    public int AddTemplate(TemplateInput input)
    {
        var template = new TemplateModel()
        {
            Name = input.Name,
            CreatedDate = DateTime.UtcNow
        };

        context.TemplateModel.Add(template);
        context.SaveChanges();
        return template.Id;
    }

    public int UpdateTemplate(TemplateInput input)
    {
        var template = GetTemplate(input.Id);
        if (template != null)  {
            template.Name = input.Name;
            template.ModifiedDate = DateTime.UtcNow;
            context.Update(template);
            context.SaveChanges();
        }
        return (int)template?.Id;
    }

    public bool ArchiveTemplate(int templateId)
    {
        var isArchiveSuccessfull = false;
        var template = GetTemplate(templateId);
        if (template != null)
        {
            template.IsArchived = true;
            isArchiveSuccessfull = true;
            context.Update(template);
            context.SaveChanges();
        }
        return isArchiveSuccessfull;
    }

    public IEnumerable<TemplateModelDto> GetTemplates()
    {
        return Mapper.Map<List<TemplateModel>, List<TemplateModelDto>>(this.context.TemplateModel.Where(x=>!x.IsArchived).ToList());
    }

    public TemplateModel GetTemplate(int templateId)
    {
        var template = context.TemplateModel.FirstOrDefault(x => x.Id == templateId);
        return template;
    }

Controller

 [Route("api/[controller]")]
 public class TemplatesController : Controller
 {
    private readonly ITemplateService templateService;
    private readonly ILogger logger;

    public TemplatesController(ITemplateService templateService, ILogger<TemplatesController> logger)
    {
        this.templateService = templateService;
        this.logger = logger;
    }
    // GET api/templates
    [HttpGet]
    public IEnumerable<TemplateModelDto> Get() => templateService.GetTemplates();

    // GET api/templates/5
    [HttpGet("{templateId}")]
    public TemplateModel GetTemplate(int templateId) =>  templateService.GetTemplate(templateId);

    // POST api/templates
    [HttpPost]
    public int Post([FromBody]TemplateInput input) => templateService.AddTemplate(input);

    // PUT api/templates/5
    [HttpPut("{templateId}")]
    public int Put(int templateId, [FromBody]TemplateInput input) => templateService.UpdateTemplate(input);

    // DELETE api/templates/5
    [HttpDelete("{templateId}")]
    public Boolean ArchiveTemplate(int templateId) => templateService.ArchiveTemplate(templateId);
}


texts: Wait for an element to exist in DOM before clicking it

texts:
Here is the problem: some script is injecting some HTML5 elements (actually a button with the #thebutton ID) to the current DOM.

But this is a third party script and I have no control of when this will be injected to the page.
I need to click automatically on this button when the button is injected to the DOM. Here is my solution so far.

It's actually working but I'm not sure on how fine this code is. My first guess is that I may use the clearTimeout() method. Is there anything else I must do?

<script type="text/javascript">
    function waitForElementToDisplay(selector, time) {
        if (document.querySelector(selector) !== null) {
            document.getElementById("thebutton").click();
            return;
        } else {
            setTimeout(function () {
                waitForElementToDisplay(selector, time);
            }, time);
        }
    }
    // onload
    (function () {
        waitForElementToDisplay("#thebutton", 500);
    })();
</script>

Here is a simulated jsFiddle of the whole process: https://jsfiddle.net/qxpcj3wm/


texts: Serving a growing audio file with Django

texts:
I would like to serve a growing audio file (raw PCM audio for now) with the possibility of seeking. I tried to manage it with Apache, but in the end wasn't able to achieve what I wanted.

Now I managed to come up with a solution within Django that seems to work quite nicely. Basically I created a view that delivers a part of the file and then sends a response with status code 206 and Content-Range header.

### DJANGO VIEW

MAX_CHUNK_SIZE = 32000
HEADER_PATH = "/path/to/header.wav"
MAX_WAV_LENGTH = 4294967303
BYTES_PER_SECOND = 32000

def get_audio(request, file_name):

    # get offset
    pos = int(request.GET.get("pos", 0))
    offset = pos * BYTES_PER_SECOND

    # get range
    r = request.META["HTTP_RANGE"]
    start = int(r.replace("bytes=", "").split("-")[0])
    start_o = start + offset

    # in case this is the first request, a wave header is added
    if start == 0:
        with open(HEADER_PATH, "rb") as f:
            data = f.read()
        length = 44
    else:
        data = ""
        length = 0
        start_o -= 44

    file_path = join(settings.STREAMS_DIR, file_name)

    # wait up to 10 seconds if the end of the file is reached
    # (in case it grows more)
    for _ in range(10):
        size = getsize(file_path)
        if size - start_o > 0:
            break
        else:
            sleep(1)

    length += min(MAX_CHUNK_SIZE, size - start_o)

    # if the length is zero (if end of file is reached and there is
    # nothing more to server), set the total length to the actual
    # served length
    if length == 0:
        total = size - offset + 44
    # else, set the total length to the maximum possible wav length
    # so that the browsers know that it has to send subsequent requests
    else:
        total = MAX_WAV_LENGTH

    # get the actual data from the raw audio file
    with open(file_path, "rb") as f:
        f.seek(start_o)
        data += f.read(length)

    # send response with use of Content-Range
    resp = HttpResponse(data, content_type="audio/x-wav", status=206)
    resp["Content-Range"] = "bytes " + str(start) + "-" + str(start + length) + "/" + str(total)
    return resp

In the browser, I can then simply request my audio like in the following way, to make it play from any point:

var fileName = "xyz.wav";
var start = 25; //seconds
audio = new Audio();
audio.src = "/getAudio/" + fileName + "?pos=" + start;
audio.play();

As I said, this all seems to work pretty well. But I would like to know this is a valid approach that I can use in production or if there are some major problems that I am not aware of.


texts: Breaking a chess coordinate string into 2D coordinates

texts:
Given a chess coordinate as a string (e.g. "a1") I'd like to transform it into a 2-D array (so, for "a1" I'd like to get [1,1]).

Here's what I came up with:

def safe_pawns(pawns)
  pawns.inject([]){|res, pwn| res << [pwn.split('')[0].index(/[a-h]/) + 1, pwn.split('')[1].to_i]}
end

Can anyone suggest a refactoring please to make it more idiomatic Ruby?


texts:
I would like the have a second opinion on my code I've written to calculate e

e is an integer that you wherefore the following counts gcd(φ(n),e) = 1 with 1 < e < φ(n)

public int calce()
{
    do
    {
        e = priemgen.newKey(1, euler);
    } while (GCD(euler, e) != 1);

    return e;
}

private int GCD(int value1, int value2)
{
    while (value1 != 0 && value2 != 0)
    {
        if (value1 > value2)
        {
            value1 %= value2;
        }
        else
            value2 %= value1;
    }

    return Math.Max(value1, value2);
}

private int NewPrime(int lowerbound, int upperbound)
{
    return priemgen.newKey(lowerbound, upperbound);
}


texts: Transform this to one line arrow function ES6+

texts:
I am using one line arrow functions a lot, if they are well written I believe they can make code easier to read. I believe that the following code can be easily transformed into one liner but I can't figure out how. Any ideas please? I am asking more just from curiosity.
const getUID = async () => {
  let uid;
  await firebase.auth().onAuthStateChanged(async (user) => {
    if (!user) await firebase.auth().signInAnonymously();
    uid = user.uid;
  });
  return uid;
};


texts:
I'm toggling on/off series in chart and was wondering if I was doing anything crazy.

Is the atom really a good idea here?

;; ================ Graph data ================

(def serie1 {:label "Bar" :data [[11 13] [19 11] [30 -7]]})
(def serie2 {:label "Foo" :data [[10 1] [17 -14] [30 5]]})
(def serie3 {:label "Zon" :data [[8 2] [18 7] [30 15]]})

(def series (for [serie [serie1 serie2 serie3]]
              {:label (:label serie) :action "toggle-serie" :param serie}))

;; ============ Chart state ================

(def !chart
  "Chart state"
  (atom []))

(defn toggle-serie! [serie]
  "Return the series collection minus/plus the given serie"
  (swap! !chart #(if (some #{serie} %)
                   (remove #{serie} %)
                   (conj % serie))))

(defn reset-chart []
  "Reset chart state"
  (reset! !chart []))

;;================ Page population ================

; almost identical to ibdknox overtone example
(defpartial button [{:keys [label action param]}]
  [:a.button {:href "#" :data-action action :data-param param} label])

(defn populate [container buttons]
  (doseq [b buttons]
    (append container (button b))))

(populate ($ :#series) series)

;; ================ Button functions ================

(defn plot
  "Plot the given series and return the chart as an object."
  [placeholder coll-data & options]
  (js/jQuery.plot placeholder (clj->js coll-data) (clj->js options)))

(def chart ($ :#chart))

(defn toggle-serie-and-update-chart!
  "Add or remove a serie form the chart atom and redraw the chart."
  [serie]
  (toggle-serie! serie) ;update the chart atom
  (plot chart @!chart)) ; redraw the chart

(delegate ($ :#series) button :click
          (fn [e]
            (.preventDefault e)
            (this-as me
                     (let [$me ($ me)
                           param (cljs.reader/read-string (data $me :param))]
                       (toggle-serie-and-update-chart! param)))))


texts: Want to know vulnerabilities in below program finding minimum positive number greater than 0 that doesn't occur in array

texts:
Below program find a minimum positive number that is greater than 0, it doesn't occur in the array. My solution actually works fulfil performance-wise. However, Codelity has given 55% only, I m trying to understand what is the potential issues with below code?

For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

#include <stdio.h>

#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])

int solution(int A[], int N) {
    // write your code in C99 (gcc 6.2.0)
    int i=0, j=0, k=0;
    int result = 1, tmp = 0;

    for(i=0; i < N; i++) {
        for(j=i+1; j < N; j++) {
            if(A[j] < A[i]) {
                tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
        }
    }

    for (i = 0; i < N; i++) {
        printf("%d\n", A[i]);
    }

    for ( k = 0; k < N; k++) {
        if (A[k] == result)
            result += 1;
        if (A[k] > result)
            break;
    }

    return result;
}

int main(void) {
    int a[] = {1,3,6,4,1,2};
    int ret = solution(a, ARRAY_SIZE(a));
    printf("Smallest positive integer: %d\n", ret);
    return 0;
}


texts:
Please, correct me with anything that I say in here (The actual question is below the code).

I've been quickly prototyping a project (ASP.NET Core 2.1) and haven't found the need to structure it with Webpack/Parcel/Rollup/Browserify as it's done with simple JavaScript validations per views (I do minify the files with Gulp).

Since I'm not enclosing my files into modules, they're all open to the global scope (bad idea, right?). Therefore, I've decided to "namespace" them by running everything inside a JavaScript variable.

The code that I have looks like this:

const formValidation = {
  submitBtn : null as unknown as HTMLButtonElement,
  errors: null as unknown as string[],
  errorsDiv: null as unknown as HTMLDivElement,
  gradeSections: null as unknown as HTMLDivElement,
  form: null as unknown as HTMLFormElement,
  mapDOM() {
    this.submitBtn = document.getElementById('js-btn-submit') as HTMLButtonElement;
    this.errorsDiv = document.getElementById('js-errors') as HTMLDivElement;
    this.gradeSections = document.getElementById('js-grade-sections')  as HTMLDivElement;
    this.form = document.getElementById('js-submit-form') as HTMLFormElement;
    this.mapEventListenersFormValidation();
  },
  mapEventListenersFormValidation() {
    this.submitBtn.addEventListener('click', this.submit.bind(this));
  },
  submit(evt: Event) {
    console.log(evt);
    evt.preventDefault();
    this.resetForms();
    if (!this.checkIfSubmitIsValid()) {
      this.showErrors();
      return;
    }
    this.form.submit();
  },
  checkIfSubmitIsValid() {
    this.errors = [];
    const subjectSelected = this.isSubjectSelected();
    const sectionsSelected = this.areSectionsSelected();

    if (!subjectSelected) {
      selectSubjectDropdown.classList.add('is-invalid');
      this.errors.push('Debe de seleccionar por lo menos una materia');
    }

    if (!sectionsSelected) {
      this.gradeSections.classList.add('form-error');
      this.errors.push('Debe de seleccionar al menos una sección');
    }

    return subjectSelected && sectionsSelected;
  },
  isSubjectSelected() {
    return selectSubjectDropdown.selectedIndex !== 0;
  },
  areSectionsSelected() {
    return selectedSectionCounter > 0;
  },
  showErrors() {

    if (!this.errorsDiv || !this.errorsDiv.parentElement) {
      return;
    }
    this.errorsDiv.parentElement.removeAttribute('hidden');
    this.errorsDiv.innerHTML = '';
    this.errors.forEach((error) => {
      const li = document.createElement('li');
      li.innerHTML = error;
      this.errorsDiv.appendChild(li);
    });
  },
  resetForms() {
    selectSubjectDropdown.classList.remove('is-invalid');
    this.gradeSections.classList.remove('form-error');
  },

};

DOMReady(formValidation.mapDOM.bind(formValidation));

Check the submitBtn, errors, and errorsDiv properties. AFAIK, JavaScript doesn't have a way to declare an "empty" property. Therefore something sane would be to assign it either undefined or null.

As I want to have it statically defined (through TypeScript), I want to assign a type to those properties. The problem is that I just can't assign a non-nullable type to a null.

As I'm trying to avoid non-implicit any's in the scripts, the compiler suggested me to use unknown.

The question is, whether it's ok for me to use the unknown type from TypeScript to cast a null to an unknown so it can let me cast it to the type that I'm going after.

Edit Ended up adding the whole document into it. I was working with that function, so it's different now.


texts:
Is there a better way to refactor the join and fetch the required attributes or is there any better option here?

 #student.rb
class Student < ActiveRecord::Base
  has_many :subjects
end

 #subject.rb
Class Subject < ActiveRecord::Base
  belongs_to :student

  def self.get_all_subjects_and_student_info
    protocol_sponsor_joined
  end

  def self.get_one_subject_and_student_info(subject_id)
    subject_student_joined.where(id: subject_id).first
  end
  # Description: This method will perform a basic join & return the required
  #results to its calling functions.
  def self.subject_student_joined
    @result ||= Subject.select('subjects.*, students.name AS STUDENT_NAME').joins(:student)
  end

end

 #subjects_controller.rb
Class SubjectsController < ApplicationController
  def show
   #GET a subject and it's associated STUDENT_NAME
   @subject = Subject.get_one_subject_and_student_info(params[:id])
  end

  def index
   # get all subjects info(along with the subjects STUDENT_NAME)
   @subjects = Subject.get_all_subjects_and_student_info
  end
end


texts: Replace ' ' Spaces in a URL with a '%20' - Coding Challenge

texts:
This was a small coding challenge proposed at my school. The problem is:

  Given a string (or URL), replace the white-spaces inside of the string
  with %20, but any spaces on the outside should not be included.

  For example, input " Mr John Smith " would return "Mr%20John%20Smith".

I have completed this challenge successfully using the code below. My question is, is there any way to improve the efficiency? I believe the complexity is currently \$O(2n) = O(n)\$ given the 2 for loops. I do not want to use any libraries or functions like str.replace(). But I'm assuming there is a better way than trimming and then counting the whitespace.

public class URL {

    /**
     * @description URLify ~ A small method that makes a string with spaces URL Friendly!
     * @param str
     * @param length
     * @return String
     */

    public static String URLify(String str) {
        str = str.trim();
        int length = str.length();
        int trueL = length;
        if(str.contains(" ")) {
            for(int i = 0; i < length; i++) {
                if(str.charAt(i) == ' ') {
                    trueL = trueL + 2;
                }
            }
            char[] oldArr = str.toCharArray();
            char[] newArr = new char[trueL];
            int x = 0;
            for(int i = 0; i < length; i++) {
                if(oldArr[i] == ' ') {
                    newArr[x] = '%';
                    newArr[x+1] = '2';
                    newArr[x+2] = '0';
                    x += 3;
                } else {
                    newArr[x] = oldArr[i];
                    x++;
                }
            }
            str = new String(newArr, 0, trueL);
        }
        return str;
    }
    public static void main(String[] args) {
        String str = "     https://google.com/  testing  .pdf    ";
        str = URLify(str);
        System.out.print(str);
    }
}

Note: I am looking for any criticism. I would really like to improve my skills in general.


texts: Coalescing lvalue references to std-optionals

texts:
I want to coalesce (lvalue references to) optionals of the same type, in C++17:

#include <optional>

template <typename... Ts>
constexpr auto coalesce(std::optional<Ts>&... optionals );

template <typename T>
constexpr std::optional<T>& coalesce(std::optional<T>& x, std::optional<T>& y)
{
    return x.has_value() ? x : y;
}

template <typename T>
constexpr std::optional<T> coalesce(std::optional<T>& x)
{
    return x;
}

template <typename T, typename... Ts>
constexpr std::optional<T> coalesce(std::optional<T>& x, std::optional<Ts>&... xs )
{
    return coalesce(x, coalesce(std::forward<std::optional<T>&>(xs)...));
}

This is sub-optimal, as it uses recursive templated function calls, rather than ellipsis-based expansion in a single body. What would you suggest?

Notes:

C++17 and no fancy libraries please.
This can be seen as a specific case of the "return first parameter in a pack satisfying a predicate", with the predicate being [](auto x) { return x.has_value(); }
If possible, let's not copy any T's.


texts: Iterate attributes of property, typecast and store info if found

texts:
Im constructing metadata about a class. With reflection i iterate over the class properties, and those properties have attributes (name, validation etc). When iterating those attributes, i typecast to some specific attribute-types, and if successful store the relevant attribute information. Im looking to do this in a more elegant way since there is much code repetition at this point. In part the typecast checks (attibute as Attributetype), and also the check if Validate is null, and then new-ing it up is repetitive (Validate needs to be null if there are no validation attributes). I expect the number of attribute-types to grow

Ideal would be to define what attribute-types im looking for, and if found execute relevant code.

foreach (Attribute attribute in property.GetCustomAttributes(true))
{

    //Info attribute
    DisplayAttribute display = attribute as DisplayAttribute;
    if (display != null)
    {
        Name =display.Name;
        Group = display.GroupName;
        Description = display.Description;
    }

    //Validation attributes
    MinLengthAttribute min = attribute as MinLengthAttribute;
    if (min != null)
    {
        if (Validate == null) Validate = new MetaValidate();
        Validate.MinLength = min.Length;
    }

    MaxLengthAttribute max = attribute as MaxLengthAttribute;
    if (max != null)
    {
        if (Validate == null) Validate = new MetaValidate();
        Validate.MaxLength = max.Length;
    }

    RegularExpressionAttribute regex = attribute as RegularExpressionAttribute;
    if (regex != null)
    {
        if (Validate == null) Validate = new MetaValidate();
        Validate.Regex = regex.Pattern;
        Validate.RegexError = regex.ErrorMessage;
    }
}


texts: Share data between 2 React components using React Hooks

texts:
In my app I have 3 components:

MovieSearchComponent to "house" the other 2 components
MovieSearch to search an API and retrieve the data
MovieResultList to display the data in the browser

Both components are wrapped in a parent container MovieSearchComponent.
My MovieSearchComponent looks like this:
interface Movie {
  original_title: string;
  id: string;
}

const MovieSearchComponent = () => {
  const [movieList, setMovies] = useState<Movie[]>([]);

  const addMovie = ((movies: Movie[]) => {
    setMovies([...movies]);
  });

  return (
    <React.Fragment>
      <MovieSearch addMovie={addMovie} />
      <MovieResultList movieList={movieList}/>
    </React.Fragment>
  )
}

In here I have a empty MovieList array that uses the setMovies function to fill the MovieList array. There's also a addMovie function that gets called from the MovieSearch component and takes a array as a parameter. Then I pass the MovieList array to the MovieResultList component.
The MovieSearch component:
const Search = styled.input`
  color: green;
`

const MovieSearch = ( {addMovie }) => {
    const apikey = 'api_key=***************dad4';
    const baseurl = 'https://api.themoviedb.org/3/search/movie?'

    const searchTMDBapi = (e) => {
        e.persist()
        setMovieSearchResults(e);
    }

    const setMovieSearchResults = debounce((e) => {
        const query = e.target.value;
        fetch(baseurl + apikey + '&language=en-US&query=' + query + '&page=1&include_adult=false')
          .then(response => response.json())
          .then(data => addMovie(data.results))
  }, 500);

  return <Search placeholder="Search" onChange={searchTMDBapi}/>
}

In this function component I render a input field by using styled components. The input field calls the searchTMDBapi function when something is typed. In that method I call the setMovieSearchResults method which calls the api and sets the api data in the Hook by using .then(data => addMovie(data.results))
The addMovie Hook updates the movieList array in MovieSearchComponent and the <MovieResultList movieList={movieList}/>  syntax passes the movieList array to the MovieResultList which renders it:
const MovieResultList = (props) => {
    return (

                {props.movieList.map(movie => {
                    return (
{movie.original_title}
)
                })}

    )
}

My goal was to create 2 components. 1 to retrieve data from a external API and the other to display that data in a different component. I succeeded in that but I was wondering if there are some aspects on which I could improve this code and my React knowledge.


texts: Working with a new form instance every time

texts:
I have a form that looks like this:

It is initialized with a Shortcut from the keyboard. It is in a module:

Public Sub ShowMainForm()
    With frmMain
        .Show vbModeless
    End With
End Sub

The form has a button:

Private Sub btnRun_Click()
    Call MainGenerateReport
End Sub

The button runs a procedure, called MainGenerateReport in a module.

Public Sub MainGenerateReport()
    ' other code;
    Call frmMain.MakeLabel
    ' other code;
End Sub

frmMain.MakeLabel changes a label in the form with some information:

Public Sub MakeLabel()
    Dim c           As Long
    Dim r           As Long
    Me.lbInfo.Visible = checkNumbers
    Me.lbInfo.Clear

    If checkNumbers Then
        With Me.lbInfo
            .ColumnCount = 2
            .ColumnWidths = CStr(Me.lbInfo.Width / 1.8 & ";" & Me.lbInfo.Width / 4)

            For r = 0 To 7
                .AddItem
                For c = 0 To 1
                    .List(r, c) = tblInfo.Cells(1 + r, 3 + c)
                Next c
            Next r
        End With
    End If
End Sub

At the end, if I want to close the form, I use the Esc key. I have a button on the form, btnExit and its cancel property is set to True:

Private Sub btnExit_Click()
    Unload Me
End Sub

The problem: According to VBA best practices, I should initialize the form like this (and rewrite my MakeLabel and the btnExit_Click accordingly):

Public Sub ShowMainForm()
    With new frmMain
        .Show vbModeless
    End With
End Sub

Is that recommended?


texts:
I created a simple Pomodoro timer using React JS.
In my example:

Timer should count down seconds until it reaches 00:00
Timers should switch between 25 and 5 minutes
Timer should be able to start, stop, and reset

My questions:

how can I improve the switching between the "work" and "relax" modes? Now I use 2 functions for this: toogleWork() and toogleRelax().
my functions for stop, start and reset look very simple and I always think that  there is something missing here...

Thank you for your time and any suggestions you can provide.

class Timer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      time: props.time,
    }
  }

  format(seconds) {
    let m = Math.floor(seconds % 3600 / 60);
    let s = Math.floor(seconds % 3600 % 60);
    let timeFormated = (m < 10 & '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
    return timeFormated
  }

  startTimer = () => this.interval = setInterval(this.countDown, 1000)

  countDown = () => {
    if (this.state.time !== 0) {
      this.setState(prevState => ({time: prevState.time - 1}))
    } else {
      this.stopTimer()
    }
  }

  stopTimer = () => clearInterval(this.interval)

  resetTime = () => {
    this.stopTimer()
    this.setState({time: this.props.time})
  }

  componentWillUnmount() {
    clearInterval(this.interval)
  }

  render() {
    return (

{this.format(this.state.time)}

        <button onClick={this.startTimer}>Start</button>
        <button onClick={this.stopTimer}>Stop</button>
        <button onClick={this.resetTime}>Reset</button>

    );
  }
}

class App extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      work: true,
    }
  }

  toogleWork = () => this.setState({work: true})

  toogleRelax = () => this.setState({work: false})

  render() {
    return (

        <button onClick={this.toogleWork}>Work</button>
        <button onClick={this.toogleRelax}>Relax</button>
        {this.state.work && <Timer time={1500} />}
        {!this.state.work && <Timer time={300} />}

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
.App {
  text-align: center;
}

button {
  margin: 15px 5px;
  padding: 10px;
  border: none;
}

.time {
  font-size: 32px;
}


texts: Maintaining state in a pagination handler

texts:
In my application I wrote a pagination code that retrieves data from the server as the user scrolls down. In this case, I need to mantain the current page, whether a request is being processed, and whether the server has more data to serve. I didn't want to use globals, but still needed to mantain these 3 variables state.

Here's my code:

fetchNextNotificationPage = (function() {

    var currentPage = 0;
    var maxPageHit = false;
    var fetching = false;

    return function () {

        // Prevent firing concurrent or pointless requests.
        if (fetching || maxPageHit) return;

        fetching = true;

       $.getJSON("GetPageUrl", { page: currentPage + 1 }, function (data) {

           if (!data.error) {

               // Finished fetching, so now it is safe
               // to say we are at previous page + 1.
               currentPage += 1;

               updateData(data.page);

               if (data.lastPage) {
                   maxPageHit = true;
               }
           }
           else {

               console.log(data.error);
           }

       }).always(function() {.

           fetching = false;
       });
   };
}());

Is there a better way to solve this other than using closure?


texts:
I did this code for an interview. Can you tell me how it looks? I didn't get the job, so I'm wondering what I could do better in my code.

/**
 * TASK 1: IMPLEMENT: C - binomial coefficient
 *
 * C(n,k) = n! / [ k! (n - k)! ]
 * Where x! is the factorial of x
 *
 * Use a recursive solution. If needed, you can implement helper functions.
 */

function C(n,k) {
    "use strict";

/**
 * ~~OMID~~
 * The code is not linted, or refactored on purpose.
 * Tested with node 0.10.32.
 */

/**
 * factorial() returns the factorial
 * of any none-negative number.
 * @param {integer}
 */
    function factorial(number) {

        var result = 1;

        if(number < 0){
          return;
        } else if (number <= 1) {
          return  result;
        }
        else {
          result = number * factorial(number-1);
        }
        return result;
      }
    // Testing numerality of parameteres, n and k
    if(isNaN(parseFloat(n)) && isFinite(n) && isNaN(parseFloat(n)) && isFinite(n)) {
        return;
    }
    else {
/**
 * Implementing the formula.
 * C(n,k) = n! / [ k! (n - k)! ]
 */
      return  (factorial(n)/factorial(k)*factorial(n-k));
    }
}

/**
 * TASK 2: IMPLEMENT: Tests for function C
 *
 * Write a set of tests, that validate your binomial coefficient function.
 * Write as many test cases as you feel is needed.
 */

(function testBinomialCoefficient() {

    var tests = {

        example: function() {
            var pass = typeof C === "function";
            return {
                success: pass,
                message: (!pass) ? 'Expected C to be a function' : ''
            };
        },
                normalInteger: function() {
                        var pass = C(5, 4) === 5;
                        return {
                                success: pass,
                                message: (!pass) ? 'C(5,4) Should be equal to 5': ' '
                        };

                },
                negativeInput: function() {
                        var pass = isNaN(C(-5, 4));
                        return {
                                success: pass,
                                message: (!pass) ? 'Negative input must result in NaN': ' '
                        };

                },
                smallerSecondParam: function() {
                        var pass = isNaN(C(10, 19));
                        return {
                                success: pass,
                                message: (!pass) ? 'Second parameter should be smaller': ' '
                        };

                },
    };

    //  ---- You shouldn't change the code below this line  ----

    for (var test in tests) {
        var result = tests[test].apply(undefined);
        if (result.success) {
            console.log("Passed: " + test);
        } else {
            console.log("Failed: " + test + ", Message: " + result.message);
        }
    }

    //  ---- You shouldn't change the code over this line  ----

})();


texts:
What follows is a Dockerfile for my Vim settings, so I could use it anywhere.
While it is public, it is not intended for mass usage, and so the face that it creates the password in the build process isn't a problem.
There is no COMMAND at the end because it is intended to be run with mount. The command I run it with docker run -itv /:/tmp/real_root uberhumus/vim-anywhere:latest vi <Filename>
Was I supposed to COPY the .vimrc later? Or use ADD instead? Am I too splurgy with the layers? Is there a smarter way to do the RUN, WORKDIR, RUN situations I ran into?
Thanks!

ENV DEBIAN_FRONTEND=noninteractive
ARG TZ=Asia/Jerusalem
RUN apt-get update; \
    apt-get dist-upgrade -y && \
    apt-get autoremove -y && \
    apt-get autoclean -y && \
    apt-get install -y vim tmux bash-completion shellcheck ssh git pylint flake8 python sudo expect curl cmake build-essential python3-dev golang npm openjdk-11-jre exuberant-ctags && \
    echo vim-anywhere > /etc/hostname

ARG USERNAME=yotam
RUN PASSWORD=$(openssl rand -base64 16 | tr -d "=") && \
    useradd -m -s /bin/bash $USERNAME && \
    usermod -aG sudo $USERNAME && \
    echo "$USERNAME:$PASSWORD" | chpasswd && \
    echo $PASSWORD

WORKDIR /home/$USERNAME
COPY .vimrc .
RUN mkdir -p ./.vim/pack/plugins/start
WORKDIR /home/$USERNAME/.vim/pack/plugins/start
RUN git clone https://github.com/tpope/vim-fugitive.git/ && \
    git clone --depth 1 https://github.com/dense-analysis/ale.git && \
    git clone https://github.com/ycm-core/YouCompleteMe.git
WORKDIR /home/$USERNAME/.vim/pack/plugins/start/YouCompleteMe
RUN git submodule update --init --recursive && \
    python3 install.py --all && \
    chown -R $USERNAME:$USERNAME /home/$USERNAME
USER $USERNAME```


texts: Finding the longest sequence of increasing numbers in an array

texts:
A continuation of  this queston.
The task's description can also be found there.

After reformatting the code and getting rid of the ArrayIndexOutOfBounds check,it now looks like this:

public static List<Integer> findLongestIncreasingSequence(int[] numbersToBeProcessed) {

        if (numbersToBeProcessed.length == 0) {
            return null;
        }

        List<Integer> longestIncreasingSequence = new ArrayList<Integer>();
        List<Integer> currentNumbersSequence = new ArrayList<Integer>();

        // the first number will be added always,no matter what
        currentNumbersSequence.add(numbersToBeProcessed[0]);

        for (int i = 1; i < numbersToBeProcessed.length; i++) {

            int currentNumber = numbersToBeProcessed[i];
            int previousNumber = numbersToBeProcessed[i - 1];

            if (currentNumber > previousNumber) {
                currentNumbersSequence.add(currentNumber);
            } else {
                // checks if the current sequence is bigger
                if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
                    longestIncreasingSequence.clear();
                    longestIncreasingSequence.addAll(currentNumbersSequence);
                }
                // clear the current sequence so it can start all over again
                currentNumbersSequence.clear();
                // after clearing add the current number as the first of the new
                // sequence
                currentNumbersSequence.add(currentNumber);
            }
        }
        // at the end of the loop always compare the two sequences.
        if (currentNumbersSequence.size() > longestIncreasingSequence.size()) {
            longestIncreasingSequence.clear();
            longestIncreasingSequence.addAll(currentNumbersSequence);
        }
        return longestIncreasingSequence;
    }

There are couple of things that bother me about the algorithm above:

We never actually check the n-1 number at the start of the algorithm - instead we directly check if the n number and we process it. This is why I have added the  currentNumbersSequence.add(numbersToBeProcessed[0]); code line before we go in the for loop.
What if the last n number is bigger than n-1? That means that we do not go into the else statement and the current sequence will never be compared against the largest one at this moment.
This is why I had to add an extra check after the for loop. However it leads to a very obvious code repetition.


texts:
I was told to create a 2D array from a txt file that had the "carModel, carColor" followed by a new line. The 2D array is 8x8 and for each time a certain carmore and carcolor appear, their respective [x][y] coordinate that represents their count goes up by 1.

So far, I have read the file, created a 2D array from the file, and have created an output with the 2D array and every slot filled with zero, but the only way I can seem to figure out to update each model,color count is if I manually make 64 if-statements to check if they appear in the list n+ times. Surely there has to be another way?

For example, When my scanner reads through the list, I need it to check if the list repeats the carmodel, carcolor and if so, update the count of that carmake and color.

This is the code I have thus far:

public static void main (String [] args) throws Exception
{
    String [][] cars = new String [8][8];
    ArrayList <String> colors = new ArrayList<>();
    colors.add("BLUE  ");
    colors.add("BLACK ");
    colors.add("BROWN ");
    colors.add("GREEN ");
    colors.add("RED   ");
    colors.add("SILVER");
    colors.add("WHITE ");
    Collections.sort(colors);
    ArrayList <String> models = new ArrayList<>();
    models.add("Escape  ");
    models.add("Explorer");
    models.add("F150    ");
    models.add("F250    ");
    models.add("Flex    ");
    models.add("Mustang ");
    models.add("Taurus  ");
    Collections.sort(models);
    cars [0][0] = "_____  ";
    for (int a = 1; a < cars.length; a++)
    {
        cars[0][a] = (models.get(a-1)) + " ";
    }
    for (int b = 1; b < cars.length; b++)
    {
        cars[b][0] = (colors.get(b-1)) + " ";
    }
    for (int fir = 1; fir < cars.length; fir++)
    {
        for (int sec = 1; sec < cars[1].length; sec++)
        {
            if (cars[fir][sec] == null)
            {
                cars[fir][sec] = "0        ";
            }
        }
    }
    for (int first = 0; first < cars.length; first++)
    {
        for (int second = 0; second < cars[first].length; second++)
        {
            System.out.print(cars[first][second]);
        }
        System.out.println();
    }
    File file = new File ("C:\\Users\\delta\\Documents\\NetBeansProjects\\SchoolWork\\cars.txt");
    Scanner sc = new Scanner(file);
    String ab = sc.nextLine();
        while (ab != null)
        {
            String [] nums = sc.nextLine().split(" ");
            for (int i = 0; i < nums.length;i++)
            {
               System.out.println(nums[i]);
            }
        }
}

The output is supposed to look something like this:


texts: Selecting an email template and BCC address based on the message type

texts:
My code-editor "show hints" says that the method length exceeds 20 lines.  How can I refactor the setEmailTemplateBcc function?

private function setBcc($bcc)
    {
        if ($bcc) {
            $this->bcc = explode(',', $bcc);
        }
    }

    public function setType($type)
    {
        $this->setEmailTemplateBcc($type);
        return $this;
    }

    private function setEmailTemplateBcc($type)
    {
        $template = '';
        $bcc = '';

        switch ($type) {
            case self::EMAIL_NEW_SUBSCRIPTION:
                $template = DataHelper::XML_PATH_SUBSCRIPTION_EMAIL;
                $bcc = DataHelper::XML_PATH_REMINDER_EMAIL_BCC;
                break;
            case self::EMAIL_CARD_ADD:
                $template = DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL;
                $bcc = DataHelper::XML_PATH_NEW_CARD_ADD_EMAIL_BCC;
                break;
            case self::EMAIL_PAYMENT_FAILED:
                $template = DataHelper::XML_PATH_PAYMENT_FAILED_EMAIL;
                $bcc = DataHelper::XML_PATH_PAYMENT_FAILED_EMAIL_BCC;
                break;
            case self::EMAIL_PROFILE_UPADATE:
                $template = DataHelper::XML_PATH_PROFILE_UPDATE_EMAIL;
                $bcc = DataHelper::XML_PATH_PROFILE_UPDATE_EMAIL_BCC;
                break;
            case self::EMAIL_REMINDER:
                $template = DataHelper::XML_PATH_REMINDER_EMAIL;
                $bcc = DataHelper::XML_PATH_REMINDER_EMAIL_BCC;
                break;
            case self::EMAIL_TOPUP_REMINDER:
                $template = DataHelper::XML_PATH_EWALLET_TOPUP_REMINDER_EMAIL;
                $bcc = DataHelper::XML_PATH_EWALLET_TOPUP_REMINDER_EMAIL;
                break;
        }

        $this->setTemplate($template);
        $this->setBcc($bcc);
    }


texts: My attempt at an immutable container view in C++

texts:
I have this very simple template:

#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <vector>

template<class Container>
class ImmutableContainerView {
private:
    Container& my_container;
public:
    ImmutableContainerView(Container& container) :
    my_container {container} {}

    typename Container::const_iterator cbegin() const {
        return my_container.cbegin();
    }

    typename Container::const_iterator cend() const {
        return my_container.cend();
    }

    typename Container::const_reverse_iterator crbegin() const {
        return my_container.crbegin();
    }

    typename Container::const_reverse_iterator crend() const {
        return my_container.crend();
    }

    typename Container::size_type size() const {
        return my_container.size();
    }

    bool empty() const {
        return my_container.empty();
    }
};

int main(int argc, const char * argv[]) {
    std::initializer_list<int> il = { 1, 2, 4, 5, 6 };

    std::list<int>   my_list   = il;
    std::set<int>    my_set    = il;
    std::vector<int> my_vector = il;

    ImmutableContainerView<std::list<int>>   my_immutable_list(my_list);
    ImmutableContainerView<std::set<int>>    my_immutable_set(my_set);
    ImmutableContainerView<std::vector<int>> my_immutable_vector(my_vector);

    // Iterators:
    std::ostream_iterator<int> out_it (std::cout, ", ");
    std::copy(my_immutable_list.cbegin(), my_immutable_list.cend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_set.cbegin(), my_immutable_set.cend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_vector.cbegin(), my_immutable_vector.cend(), out_it);
    std::cout << "\n";

    // Reversed iterators:
    std::copy(my_immutable_list.crbegin(), my_immutable_list.crend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_set.crbegin(), my_immutable_set.crend(), out_it);
    std::cout << "\n";

    std::copy(my_immutable_vector.crbegin(), my_immutable_vector.crend(), out_it);
    std::cout << "\n";

    // Size:
    std::cout << my_immutable_list.size() << "\n";
    std::cout << my_immutable_set.size() << "\n";
    std::cout << my_immutable_vector.size() << "\n";

    // Empty:
    std::cout << std::boolalpha;
    std::cout << my_immutable_list.empty() << "\n";
    std::cout << my_immutable_set.empty() << "\n";
    std::cout << my_immutable_vector.empty() << "\n";

    return 0;
}

I would like to hear comments on how to improve it. In particular, is it possible to do some metaprogramming trickery such that it can adapt to different containers; for example, it could provide operator[size_t] for std::vector, but find for std::set?


texts: Generic toString() for JPA base entity class

texts:
In a Java/JPA project I usually define a base class (on which I put the id). The goal is to implement an generic toString() on this base class (named BaseEntity) from which all other entities inherit. We played around with apache commons ReflectionToStringBuilder, but we ran into problems because of cyclic references and the lack of different handling depending on the type of the fields.

My wish is that, if an Entity is printed/logged I get all field names and their values except for fields of type collection, in this case we just want the IDs of these objects to avoid recursion (PS: We can assume that collections on entities always contain other entities and they have an ID)

The desired output pattern is the following

classname[fieldname1=value1, fieldname2=value2,..., collectionname1=[id1,id2,..], collectionname2=[id1,id2,...],...]

a sample output for an entity "Project" which subclasses BaseEntity may look like this:

Project[nameLong=Testproject, nameShort=tpr, support=false, active=true, priority=0, blockers=[20], responsibilities=[13,14,15]]

We came up with the following implementation using reflection:

@Override
public String toString() {
    // init container for field names
    List<String> fieldToPrintout = new ArrayList<String>(0);

    // get all fields from this object (use declared fields to get private
    // and protected fields)
    Field[] fieldsOnTheObject = this.getClass().getDeclaredFields();

    // set the accessibility for field which are private
    AccessibleObject.setAccessible(fieldsOnTheObject, true);

    for (Field field : fieldsOnTheObject) {
        try {
            // ignore static fields
            if (!Modifier.isStatic(field.getModifiers())) {
                // get the object from the field
                Object fieldValue = field.get(this);
                // check if the field is a collection
                if (Collection.class.isAssignableFrom(field.getType())) {
                    // check if the collection generic type is BaseEntity
                    if (field.getGenericType() instanceof ParameterizedType) {
                        Class<?> genericType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
                        if (BaseEntity.class.isAssignableFrom(genericType)) {
                            // iterate over all BaseEntities and get all id's
                            List<String> ids = ((Collection<BaseEntity>) fieldValue).stream().map(p -> p.getId().toString()).collect(Collectors.toList());
                            fieldToPrintout.add(field.getName() + "=[" + String.join(",", ids) + "]");
                        }
                    }
                } else { // --> no collection
                    // note: Field.get(Object) creates wrapper objects for primitive
                    fieldToPrintout.add(field.getName() + "=" + fieldValue);
                }
            }
        } catch (IllegalAccessException ex) {
            logger.catching(ex);
        }
    }
    return MessageFormat.format("{0}[{1}]", this.getClass().getSimpleName(), String.join(", ", fieldToPrintout));
}

I'm currently not really happy with the code, I'm sure it can be improved/simplified. Any suggestions?


texts:
I have started learning Java recently and was looking into the challenges on sorting on Hackerrank.I solved the following problemHackerrank on Insertion Sort.
The challenge was :

In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array?
Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller.
In this challenge, don't print every time you move an element. Instead, print the array after each iteration of the insertion-sort, i.e., whenever the next element is placed at its correct position.
Since the array composed of just the first element is already "sorted", begin printing from the second element and on.
Input Format
There will be two lines of input:

the size of the array
a list of numbers that makes up the array

Output Format :
On each line, output the entire array at every iteration.

Sample Input:
6
1 4 3 5 6 2

Sample Output:
 1 4 3 5 6 2
 1 3 4 5 6 2
 1 3 4 5 6 2
 1 3 4 5 6 2
 1 2 3 4 5 6

I am trying to get better at writing good code for my solutions..Please give me your suggestions .
import java.util.Scanner;

public class InsertionSortPart2 {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    int size = keyboard.nextInt();

    int[] array = new int[size];

    for (int i = 0; i < array.length; i++) {
        array[i] = keyboard.nextInt();

    }

    array = insertionsort(array);

}

private static int[] insertionsort(int[] a) {

    for (int i = 1; i < a.length; i++) {
        // set key to value at index i
        int key = a[i];
        // set j as i-1 to look for previous element
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }

        a[j + 1] = key;
        for (int f = 0; f < a.length; f++) {
            System.out.print(a[f] + " ");
        }
        System.out.println();
    }

    return a;
  }
}


texts:
I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:

 /**
 * This class converts strings by looping through the characters, gets the
 * decimal code for each, then divides the number by 2 untill the quotient is 0
 *
 * @author Mr Pro Pop
 *
 */
public class Binary {

    /**
     * This function takes a string as a parameter and converts it to binary code
     *
     * @param string The string to be converted to binary code
     * @return The binary code of the input string
     */

    public String getBinaryCode(String string) {

        if (string.length() == 0)
            return null;

        char[] characters = string.toCharArray();
        StringBuilder result = new StringBuilder();
        int number = 0;

        for (int i = 0; i < characters.length; i++) {
            number = getDecimal(characters[i]);
            for (int j = 0; j < 8; j++) {
                if (number % 2 == 0) {
                    result.insert(0, 0);
                } else {
                    result.insert(0, 1);
                }
                number = (int) (number / 2);
            }
            result.append(" ");
        }
        return result.toString();
    }

    /**
     * This function gets the decimal number of a character
     *
     * @param character The character that we want the decimal value of
     * @return The decimal of the character from the ascii table
     */
    public int getDecimal(char character) {
        for (int i = 0; i <= 255; i++) {
            if (character == (char) i) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String string = "a";
        Binary b = new Binary();
        System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));
    }

}

Output:

  Binary code for a is 01100001

Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i]) but tried doing it my way to learn and especially with this method.

Any improvements I could do or anything to pay attention for?


texts:
I am learning PowerShell, and created the following script cmdlet.

It reads one or more specified script files, to discover special functions (UnitTests, or functions with the Verb 'UnitTest' or 'DataTest'.

I designed the parameters to work like Get-Content, as it reads content from files.

I would like general feedback on this cmdlet (design, workings), but i am also intrested in correctness.

<#
.SYNOPSIS
    Gets UnitTests from a UnitTestFile.
.DESCRIPTION
    UnitTests are PowerShell script functions, which are identified with the verb 'UnitTest' or 'DataTest'.
#>
function Get-UnitTest {
    [CmdletBinding(DefaultParameterSetName = "Path")]
    [OutputType([System.Management.Automation.FunctionInfo])]
    Param(
        <# Specifies a path to one or more UnitTestFiles. Wildcards are permitted. #>
        [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = $true)]
        [string[]] $Path,

        <# Specifies a LiteralPath to one or more UnitTestFiles. Wildcards are permitted. #>
        [Parameter(ParameterSetName = "LiteralPath", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias("FullName")]
        [string[]] $LiteralPath,

        <# Specifies the Verb to use to identify UnitTests. The default verbs are 'UnitTest' and 'DataTest'. This means that functions with a name like 'UnitTest-Get-ChildItem' or 'DataTest-Invoke-WebRequest' are found. #>
        [String[]] $Verb = @( "UnitTest", "DataTest" )
    )

    Process {

        foreach($curPath in ($LiteralPath + $Path | Where {$_} | Resolve-Path)) {
            if(Test-Path $curPath -PathType Leaf) {

                Write-Trace "Getting UnitTests from '$curPath'."
                . $curPath

                # find and return all unit tests (from the requested file)
                Get-Command -Verb $Verb `
                    | Where { $_.CommandType -eq "Function" } `
                    | Where { ( $_.ScriptBlock.File ) -eq $curPath }
            }
        }
    }
}

This cmdlet can be called as follows:

Get-UnitTest -Path .\somefile.ps1
Get-UnitTest -Path .\somefile.ps1 -Verb 'OtherTest'
Get-ChildItem -Recurse *.ps1 | Get-UnitTest


texts:
I have implemented Insertion sort in Java.  Please review it.

public class InsertionSort {

public static void main(String[] args) {
        int[] values = new int[args.length];
        for (int i = 0; i < args.length; i++) {
            values[i] = Integer.parseInt(args[i]);
        }

        for (int i = 0; i < values.length; i++) {
            if (i!=0 && values[i] < values[i - 1]) {
                for (int j = i; j >= 1; j--) {
                    System.out.println(" j"+j);
                    if (values[j] < values[j-1]) {
                        int temp = values[j - 1];
                        values[j - 1] = values[j];
                        values[j] = temp;
                    } else {
                        break;
                    }
                }
            }
        }
        System.out.println(" sorted numbers");
        for (int i = 0; i < values.length; i++) {
            System.out.println(" "+values[i]);
        }
    }
}


texts:
This program use random number generator to create sentences. It prints 20 sentences randomly.
Here is the code:

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

#define STR_LEN 80
#define MAX_SEN 20

int main(void) {
    char *article[] = {"the", "a", "one", "some", "any"};
    char *noun[] = {"boy", "girl", "dog", "town", "car"};
    char *verb[] = {"drove", "jumped", "ran", "walked", "skipped"};
    char *preposition[] = {"to", "from", "over", "under", "on"};
    int num;
    char sentence[MAX_SEN][STR_LEN];
    char (*i)[STR_LEN];
    srand((unsigned) time(NULL));
    for(i = sentence; i < sentence + MAX_SEN; i++) {
        num = rand() % (sizeof(article)/sizeof(article[0]));
        strcpy(*i, article[num]);
        num = rand() % (sizeof(noun)/sizeof(noun[0]));
        strcat(strcat(*i, " "), noun[num]);
        num = rand() % (sizeof(preposition)/sizeof(preposition[0]));
        strcat(strcat(*i, " "), preposition[num]);
        printf("%s.\n", *i);

    }

    return 0;
}

Can you make some improvements on the code especially on the sizeof operator. You can use any things functions, arrays, strings, pointers etc.
Also, I don't know how to make first letter capital of each sentence using toupper() function.


texts: Processing a sequence of additions and deletions

texts:
I am working on a program which manages a list, and must be able to insert new items, and delete ranges of items. I want the user to be able to specify the insertions and deletions in terms of the current state of the list, and not have to worry about how later operations will need an offset index in order to work on the correct items.
eg:

  delete: 4-5
  insert: 2,6

will insert an element before index 2, and another element before what was originally element 6, and delete the items originally at 4 and 5.

I want to convert these instructions into a list of deletions followed by insertions, which can be performed consecutively, ie the operations above would become:

  delete 4, delete 4, insert 2, insert 4

as the deletion at 4 shifts the following operations left, so the next deletion also acts at 4. The insertion of 2 shifts the insertion of 6 right, but the previous 2 subtractions shift it left.

I'm looking for a (hopefully readable) formula for converting the indices of these insertions and deletions into the form they will be in in the delete and insert lists.

So far, I have a rather unreadable python function, which would be difficult to maintain, but which seems to output the correct values:

ii = jj = kk = 0 # list indices
plus = minus = 0 # plus / minus offset
while ii < len(dellist) or jj < len(addlist):
    if jj < len(addlist): # in the list
        if addlist[jj] == kk: # at the specified index
            addlist[jj] -= minus # deletions happen first, so shift it back
            addlist[jj] += plus # then additions happen, so shift it forward
            jj += 1 # next addition
            plus += 1 # one more item inserted before the others
    if ii < len(dellist): # in the list
        if dellist[ii] == kk: # at the specified index
            dellist[ii] -= minus # previous deletions, so shift back
            ii += 1 # next deletion
            minus += 1 # one more item removed from before the others
    kk += 1 # next list element

I'm mainly concerned with having readable code, that I can easily modify later; and, ideally, something more modular, although I'm not sure how that would be achieved in this case.


texts: Combination aggregate/greatest-n-per-group SQL query on simplified data set

texts:
I've been reading the top 'greatest-n-per-group' answers on StackOverflow but haven't yet found any answers that fit my specific case.

The following code works, but it seems overly-complicated for what I want to achieve. The nested/self-joined derived tables seem wrong but I don't know how to simplify things without resorting to a correlated sub-query.

Goal: For each article, I want to select the url (as determined by the page with the lowest page_number), page count and word count.

SQL Fiddle

Schema:

-- tables
CREATE TABLE article (
  id int PRIMARY KEY
);
CREATE TABLE page (
  id int PRIMARY KEY,
  url text,
  page_number int,
  word_count int,
  article_id int REFERENCES article
);

-- data
INSERT INTO article (id) VALUES (1), (2), (3);
INSERT INTO page (id, url, page_number, word_count, article_id) VALUES
  (1, '/1/1', 1, 250, 1), (2, '/1/2', 2, 230, 1), (3, '/1/3', 3, 55, 1),
  (4, '/2/1', 1, 300, 2),
  (5, '/3/1', 1, 1000, 3), (6, '/3/2', 2, 1000, 3);

Query:

SELECT
  first_page.url,
  count(*) AS page_count,
  sum(page.word_count) AS word_count,
  page.article_id
FROM
  page
  JOIN (
    SELECT
      page.url,
      page.article_id
    FROM
      page
      JOIN (
        SELECT
          min(page_number) AS page_number,
          article_id
        FROM page
        GROUP BY article_id
      ) AS first_page ON
        first_page.article_id = page.article_id AND
        first_page.page_number = page.page_number
  ) AS first_page ON first_page.article_id = page.article_id
GROUP BY
  page.article_id,
  first_page.url;


texts:
I'm solving the m-coloring problem using java. and I have following code that uses concept of recursion and backtracking.

import java.util.Arrays;

public class GraphColoring {

    static void graphColor(int k, int m, int n, int colors[], int graph[][]) {
        for (int c = 1; c <= m; c++) {
            if (isSafe(k, c, n, colors, graph)) {
                colors[k] = c;
                if (k + 1 < n)
                    graphColor(k + 1, m, n, colors, graph);
            }
        }
    }

    static boolean isSafe(int k, int c, int n, int[] colors, int graph[][]) {
        for (int i = 0; i < n; i++) {
            if (graph[k][i] == 1 && c == colors[i]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {

        int n = 4, m = 3;
        int[] colors = new int[n];
        int graph[][] = { { 1, 1, 0, 1 }, { 1, 1, 1, 1 }, { 0, 1, 1, 1 }, { 1, 1, 1, 1 } };
        graphColor(0, m, n, colors, graph);
        System.out.println(Arrays.toString(colors));

    }
}

  OUTPUT

1 2 1 3

I would like review about its performance, time complexity and improvements. Also If I'm missing any corner cases please let me know as this code is tested on very few examples as I didn't find any online problem that checks its appropriate output.


texts:
I have just started using Python, and I am attempting to make a prime number sequence generator, where it will print the a specified amount prime numbers in terminal.  I have other versions of this also, and versions for the Fibonacci sequence, although, I will post just the version for prime numbers I specified above.

    P = 2
    Count = 1
    X = int(raw_input('choose number: '))

    def Main(P, X):
        while Count <= X:
            isprime = True
            for x in range(2, P - 1):
                if P % x == 0:
                    isprime = False
            if isprime:
                print P
                Count += 1
            P += 1

I am currently trying to optimize this code so that it runs as fast as possible, and then making small edits.  I did this by putting a get daytime now function at the beginning and the end of the sequence generator, and printing the time, then looping it all a specified amount of times.

from datetime import datetime as dt

P = 2
Count = 1
Count2 = 1
X = int(raw_input('choose number: '))

def Main(P, Count, X):
    t1 = dt.now()
    while Count <= X:
        isprime = True
        for x in range(2, P - 1):
            if P % x == 0:
                isprime = False
        if isprime:
            Count += 1
        P += 1
    t2 = dt.now()
    print ((t2-t1).microseconds)

while Count2 <= 20:
    Main(P, Count, X)
    Count2 += 1

As far as my knowledge of Python extends, I have optimized this code so it runs quite efficiently.  However, I want to know if anyone can help make this code any better, however, it needs to stay within one function (two if necessary), and it does the same type of thing.  Also, if it is possible to explain why it does better, that would be appreciated.  However, any comment or feedback would be nice.


texts:
I'm no pro in JavaScript. Please help me review this code. I would appreciate any suggestions!

JavaScript:

var y_offset, /*current position of window*/
    distance_from_current_position, /*different between current position and target*/
    body_height, /*hight of body*/
    window_height, /*height of window*/
    position_of_target, /*target position*/
    max_scroll, /*max position to scroll to*/
    up_or_down, /*scroll up or down*/
    my_classes = document.querySelectorAll('.y');

function scroll_function(target) {

    y_offset = window.pageYOffset;

    distance_from_current_position = target - window.pageYOffset;

    setTimeout(function () {

        if (distance_from_current_position !== 0) {
            if (up_or_down) {
                if (y_offset < target - 5) {
                    window.scroll(0, y_offset + (distance_from_current_position / 3))
                } else {
                    window.scroll(0, y_offset + 1)
                }
                if (y_offset < position_of_target - 1) {
                    scroll_function(target);
                }
            } else {
                if (y_offset > target + 5) {
                    window.scroll(0, y_offset + (distance_from_current_position / 3))
                } else {
                    window.scroll(0, y_offset - 1)
                }
                if (y_offset > position_of_target + 1) {
                    scroll_function(target);
                }
            }
        }

    }, 50)
}

function click_function(i) {
    my_classes[i].onclick = function () {
        body_height = document.body.clientHeight;

        position_of_target = document.getElementById(this.getAttribute('data-y')).offsetTop;

        window_height = window.innerHeight;

        max_scroll = body_height - window_height;

        if (window.pageYOffset < position_of_target) {
            up_or_down = 1
        } else {
            up_or_down = 0
        }

        if (position_of_target > max_scroll) {
            position_of_target = max_scroll;
        }
        $y_1(position_of_target);

    };

}

for (var i = 0; i < my_classes.length; i++) {
    click_function(i);
}

HTML:

<!DOCTYPE html>
<title></title>

Scroll to id1

Scroll to id2

Scroll to id´3


texts: Toggle logical NOT operator based on a boolean value

texts:
I'm trying to think of a better way to write the below Javascript/NodeJS code without having to check the value of the boolean using an if statement. I know this can be accomplished with a ternary, but that would look ugly.

This is of course only an example, I'm sure there's a better way to write this; however I'm specifically wondering about this use-case.

var getNumbers = function(getNumbers) {
    return function(e) {
        if (getNumbers) {
            return !isNaN(e) ? e : null;
        } else {
            return isNaN(e) ? e : null;
        }
    };
};

var data = ['A', 'B', 'C', 'D', '1', '2', '3', '4'];

console.log(data.filter(getNumbers(true)));
console.log(data.filter(getNumbers(false)));

Output:

[ '1', '2', '3', '4' ]
[ 'A', 'B', 'C', 'D' ]