texts:
I'm ruby developer, and I faced some issue in my app, I thought that is more generic issue so I wrote my first gem. I know that probably there are dozens of things which I can made better. So could you look at my code https://github.com/rwegrzyniak/redis_locker. I have doubts with mainly metaprogramming which is done here:
# frozen_string_literal: true
#
require "zeitwerk"

module RedisLocker
  STRATEGIES = %i[exception retry silently_die].freeze
  DEFAULT_RETRY_COUNT = 3
  DEFAULT_RETRY_INTERVAL = 1
  MODEL_LOCK_STRING = "model_lock"
  DEFAULT_STRATEGY = :exception
  DEFAULT_EXCLUDED_METHODS = %i[id initialize].freeze
  class << self
    def configuration
      @configuration ||= Configuration.new
    end

    def configure
      yield(configuration)
    end

    def release_locks!
      configuration.redis_connection.del(configuration.redis_connection.keys("LOCKER:*"))
    end

  end

  def self.included(base_klass)
    base_klass.extend(ClassMethods)
    base_klass.include(InstanceMethods)
    interceptor = base_klass.const_set("#{base_klass.name.split('::').last}Interceptor", Module.new)
    base_klass.prepend interceptor
  end

  module ClassMethods
    def lock_every_method_call(strategy: DEFAULT_STRATEGY, retry_count: DEFAULT_RETRY_COUNT, retry_interval: DEFAULT_RETRY_INTERVAL,
                               exclude: DEFAULT_EXCLUDED_METHODS)
      interceptor = self.const_get("#{name.split('::').last}Interceptor")
      self.define_singleton_method(:method_added) do |method|
        return super(method) if exclude.include? method

        interceptor.define_method(method) do |*args, **opts, &block|
          returned_value = nil
          method_locker(method).with_redis_lock strategy: strategy, retry_count: retry_count, retry_interval: retry_interval do
            returned_value = super(*args, **opts, &block)
          end
          returned_value
        end
      end
    end

    def lock_method(method, strategy: DEFAULT_STRATEGY, retry_count: DEFAULT_RETRY_COUNT, retry_interval: DEFAULT_RETRY_INTERVAL)
      interceptor = self.const_get("#{name.split('::').last}Interceptor")
      interceptor.define_method(method) do |*args, **opts, &block|
        returned_value = nil
        method_locker(method).with_redis_lock strategy: strategy, retry_count: retry_count, retry_interval: retry_interval do
          returned_value = super(*args, **opts, &block)
        end
        returned_value
      end
    end
  end

  module InstanceMethods
    def method_locker(method)
      method_lockers[method] ||= RedisLocker::MethodLocker.new(model_locker, method)
    end

    def lock
      model_locker.lock
    end

    def lock!
      model_locker.lock!
    end

    def unlock
      model_locker.unlock
    end

    def with_redis_lock(strategy: RedisLocker::DEFAULT_STRATEGY, retry_count: RedisLocker::DEFAULT_RETRY_COUNT,
                        retry_interval: RedisLocker::DEFAULT_RETRY_INTERVAL, &block)
      model_locker.with_redis_lock(strategy: strategy, retry_count: retry_count, retry_interval: retry_interval, &block)
    end

    private

    def method_lockers
      @method_lockers ||= {}
    end

    def model_locker
      @model_locker ||= RedisLocker::ModelLocker.new(self)
    end
  end

end

I suppose that it could be overkill and many thing probably could be written in simpler and cleaner way.


texts: Find all pairs in an array that sum to a given number

texts:
Assume you have an array of random integers and a sum value. Find all
  pairs of numbers from the array that sum up to the given sum in O(n)
  time. Find all distinct pairs. (1,2) and (2,1) are not distinct.

import java.util.HashSet;

public class PairsSummingToElement {

  public static void main(String[] args) {
    PairsSummingToElement e = new PairsSummingToElement();
    int[] input = new int[] { 2, 5, 3, 7, 9, 8 };
    int sum = 11;
    HashSet<Pair> result = e.findAllPairs(input, sum);
    for (Pair p : result) {
      System.out.println("(" + p.getElement1() + "," + p.getElement2() + ")");
    }

  }

  public HashSet<Pair> findAllPairs(int[] inputList, int sum) {
    HashSet<Integer> allElements = new HashSet<Integer>();
    HashSet<Integer> substracted = new HashSet<Integer>();
    HashSet<Pair> result = new HashSet<Pair>();

    for (int i : inputList) {
      allElements.add(i);
      substracted.add(i - sum);
    }

    for (int i : substracted) {
      if (allElements.contains(-1 * i)) {
        addToSet(result, new Pair(-i, i + sum));
      }
    }

    return result;

  }

  public void addToSet(HashSet<Pair> original, Pair toAdd) {
    if (!original.contains(toAdd) && !original.contains(reversePair(toAdd))) {
      original.add(toAdd);
    }
  }

  public Pair reversePair(Pair original) {
    return new Pair(original.getElement2(), original.getElement1());
  }

}

class Pair {
  private int element1;

  private int element2;

  public Pair(int e1, int e2) {
    element1 = e1;
    element2 = e2;
  }

  public int getElement1() {
    return element1;
  }

  public int getElement2() {
    return element2;
  }

  public int hashCode() {
    return (element1 + element2) * element2 + element1;
  }

  public boolean equals(Object other) {
    if (other instanceof Pair) {
      Pair otherPair = (Pair) other;
      return ((this.element1 == otherPair.element1) && (this.element2 == otherPair.element2));
    }
    return false;
  }

}


texts:
I am new to learning code, and would love some feedback on how this little game could be improved and/or tidied up.

import random

num = random.randint(1, 100)

def user_guess():
    guess = input("Guess a number between 1 and 100: ")
    print("Your guess is", guess)
    guess = int(guess)

    while guess != num:
        if guess < num:
            guess = input("Your guess was too low: guess again!")
            print("Your guess is", guess)
            guess = int(guess)
        if guess > num:
            guess = input("Your guess was too high: guess again!")
            print("Your guess is", guess)
            guess = int(guess)
        if guess == num:
            print("Correct! Well done!")
            again = input("Would you like to play again? (Y or N): ")
            if again == "y":
                user_guess()
            break


texts:
How do I decrease time, especially in sorting?

  Given a list of numbers, you are to sort them in non-decreasing order.

  Input

  t – the number of numbers in list, then t lines follow [\$t \le 10^6\$].

  Each line contains one integer: N [\$0 \le N \le 10^6\$]

  Output

  Given numbers in non-decreasing order.

  Example

  Input:

5
5
3
6
7
1

  Output:

1
3
5
6
7

struct sort_list{
int num;
struct sort_list *next;
};
typedef struct sort_list node;
void enter();
void sort();
void print();
int main()
{

        node *head;
        int tot_num;
        scanf("%d",&tot_num);  //asking for entering total numbers
        head=(node*)malloc(sizeof(node));
        enter(head,tot_num);
        sort(head,tot_num);
        print(head);
    return 0;
    }
    void enter(node *list,int tot_num)
    {
        int i=0;
        while(i!=tot_num)
        {
            scanf("%d",&list->num);
            if(i==tot_num-1)
            {
                list->next=0;
                //break;
            }
            else
            {
                list->next=(node*)malloc(sizeof(node));
                list=list->next;
            }
            i++;
        }
    }
    void print(node *list)
    {
        int i=0;
        while(list->next!=0)
        {
            printf("%d\n",list->num);
            list=list->next;
            i++;
        }
        if(list->next==0)
        {
            printf("%d\n",list->num);
        }
    }
    void sort(node *list,int tot_num)
    {
        node *new=list;
        int i,j,t;
        for(i=0;i<tot_num;i++)
        {
            for(j=i+1;j<tot_num;j++)
            {
                if(list->num > list->next->num)
                {
                    t=list->num;
                    list->num=list->next->num;
                    list->next->num=t;
                }
                list=list->next;
            }
            list=new;
        }
    }


texts: Calculate the statistical mean of different files and save it into a CSV file

texts:
In this code I calculate the statistical functions of values from different files and save them into CSV files (one filer for each statistical function).

def mean(data):
    pass

def standard_deviation(data):
    pass

def afd(data):
    pass

def norma_afd(data):
    pass

def asd(data):
    pass

def norma_asd(data):
    pass

def calculation(file):
    """
    Get the DataFrame and calculate for ever column the different statistical mean
    :param file: DataFrame 56x7681
    :return: 6 different 56x1 lists for (mean, std, afd, norm_afd, asd, norm_asd)
    """
    m, sd, afd_l, nafd, asd_l, nasd = ([] for _ in range(6))
    for column in file:
        data = file[column].to_numpy()
        m.append(mean(data))
        sd.append(standard_deviation(data))
        afd_l.append(afd(data))
        nafd.append(norma_afd(data))
        asd_l.append(asd(data))
        nasd.append(norma_asd(data))
    return m, sd, afd_l, nafd, asd_l, nasd

def run(load_path, save_path):
    """
    Get (yield) all the different DataFrame from a folder
    and calculate for each file the statistical mean and save it in a csv file

    :param load_path: the folder path to load all the different files
    :param save_path: the folder save path
    :return: none
    """
    m, sd, afd_l, nafd, asd_l, nasd = ([] for _ in range(6))
    for current_path, file in yield_data(load_path, data_type="data"):
        a, b, c, d, e, f = calculation(file)
        m.append(a)
        sd.append(b)
        afd_l.append(c)
        nafd.append(d)
        asd_l.append(e)
        nasd.append(f)

    if not os.path.exists(save_path):
        os.makedirs(save_path)

    pd.DataFrame(m).to_csv(save_path + os.path.sep + "mean.csv", index=False, header=False)
    pd.DataFrame(sd).to_csv(save_path + os.path.sep + "std.csv", index=False, header=False)
    pd.DataFrame(afd_l).to_csv(save_path + os.path.sep + "afd.csv", index=False, header=False)
    pd.DataFrame(nafd).to_csv(save_path + os.path.sep + "norm_afd.csv", index=False, header=False)
    pd.DataFrame(asd_l).to_csv(save_path + os.path.sep + "asd.csv", index=False, header=False)
    pd.DataFrame(nasd).to_csv(save_path + os.path.sep + "norm_asd.csv", index=False, header=False)

Is there a better and more efficient way to write this code? This may be a stupid question, but I would be really interested to know if there is a better way.


texts:
I have scripts to display commit statistics and merge statistics of my repos, and they work. I wrote them for my personal usage, and because I was interested in finding trends in my git repos.

This script reports statistics about commits (number, average length in words, etc.). Relevant commits can be selected using git-rev-list options.

Features and times

count: report number of commits (not a performance issue)
len: report length in words of commit message and commit hash (~20s for 1561 commits)
len min, len max, and len avg: report minimum, maximum, or average commit message length in words and commit hash (~10-15s for the same)

  Benchmarks run with bash's time on my dotfiles repo

A previous implementation using for-loops had similar performance.

Obviously, the algorithms are O(n). They are still too slow for every-day usage.

#! /usr/bin/env bash

set -euo pipefail

USAGE='[-h] (count | len [min|max|avg]) [rev-list options]

Display commit statistics
Filter commits based on [rev-list options]'
SUBDIRECTORY_OK=true

# source git-sh-setup for some helpers
set +u
source "$(git --exec-path)"/git-sh-setup
set -u

SIZER=(
  wc
  # count words
  -w
)

size() {
  local commit="$1"
  git log "$commit" -1 --format=%B | "${SIZER[@]}" | tr -d ' '
}

commits_list() {
  command=(
    git
    rev-list
    # start somewhere
    --all
  )
  if (($# > 0)) ; then
    command+=("$@")
  fi
  "${command[@]}" 2>/dev/null
}

commit_count() {
  commits_list "$@" | wc -l | tr -d ' '
}

commit_len() {
  commits_list "$@" |
    while read c ; do
      size "$c" | tr -d '[:space:]'
      printf ' %s\n' "$c"
    done
}

commit_len_min() {
  commit_len "$@" |
    sort -n |
    head -n 1
}

commit_len_max() {
  commit_len "$@" |
    sort -rn |
    head -n 1
}

commit_len_avg() {
  local num=0
  {
    printf '%s\n' '5k'
    while read c ; do
      ((++num))
      size "$c"
      ((num >= 2)) && printf '%s\n' '+'
    done < <(commits_list "$@")
    printf '%s\n' "$num" '/p'
  } | dc
}

main() {
  (($# >= 1)) || usage
  case "$1" in
    count) commit_count "${@:2}" ;;
    len)
      if (($# >= 2)); then
        case "$2" in
          max|min|avg) commit_len_"$2" "${@:3}" ;;
          *) commit_len "${@:2}" ;;
        esac
      else
        commit_len "${@:2}"
      fi
      ;;
    *) usage ;;
  esac
}

main "$@"

Shell scripts being hard to profile, I've been unable to identify the bottleneck (though commit_len seems like a good place to start).

I run shellcheck regularly.


texts: Determine if someone has won a game of Tic-Tac-Toe on a board of any size

texts:
I was asked this question in interview yesterday:

  Write the code for winning condition in an NxN matrix for tick tack toe.For example A function named "input_event(player_info, x_position,
  y_position)" will be triggered when the player inputs O or X, how will
  you check if the player has won inside this function ? Given: NxN
  matrix N>=3 and <=100

I managed to answer this by checking by loops horizontal, vertical and diagonal elements depending upon the current position. But the interviewer was not pleased and wanted me to achieve this without using so many repeated loops.

I searched on the internet on how to achieve this optimally and found this. I have posted the my implementation below:

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

class TicTacToe {
  vector<vector<char> > board;
  vector<int> winArr;
  int N;
public:
  TicTacToe(int sz) : N(sz) {
    board.resize(N);
    winArr.resize(2*N+2, 0);
    for(int i = 0; i < N; i++)
      board[i].resize(N, '.');
  }
  void playMove(char player, int nRow, int nCol) {
    cout << player << " Marks board[" << nRow << "]["<<nCol << "].\n";
    board[nRow][nCol] = player;
    updateWinArr(player, nRow, nCol);
    checkWinCondition();
  }
  void updateWinArr(char player, int nRow, int nCol) {
    int nVal = (player == 'X' ? 1 : -1);
    winArr[nRow] += nVal;
    winArr[N + nCol] += nVal;
    // check diagonals :
    if(nRow == nCol) // left diagonal
      winArr[2*N] += nVal;
    else if(nRow+nCol == N-1) // right diagonal
      winArr[2*N+1] += nVal;
  }
  void checkWinCondition() {
    bool bWin = false;
    char winner = '\0';
    for(int i = 0; i < winArr.size(); i++) {
      if(winArr[i] == -N) {
        bWin = true;
        winner = 'O';
        break;
      }
      else if(winArr[i] == N) {
        bWin = true;
        winner = 'X';
        break;
      }
    }
    if(bWin == true)
      cout << "Congrats!, " << winner << " has won the game\n";
  }
};

int main() {
  TicTacToe tt(3);
  tt.playMove('X', 0, 0);
  tt.playMove('O', 0, 2);
  tt.playMove('X', 1, 1);
  tt.playMove('O', 0, 1);
  tt.playMove('X', 2, 2);
  return 0;
}

I welcome any suggestions since I'm a beginner in C++.


texts: Replacing simple jQuery methods for better use

texts:
There are a few common jQuery call I find my self calling when creating my app. I need some help and maybe a better way to do all this or rewrite it.
1) Singleton Selector
If I want to select only one class I would do it like this:
$("#tempo").on("click", ".entity", function(e){
    $(".selected").removeClass("selected");
    $(this).addClass('selected');
    // ....

2) Resource Selector
I have a div with all the resource elements (divs,ul) with formated code added class and even children). This is the code I write a lot to select it, clone it and append it.
// $R = $('div.resources'); - Create only once.
$R.find(".folder").clone()
    .addClass(id++)
    .appendTo("#folders");

3) Prevent Double Actions
I have quite a lot of ajax request to the server once a button gets clicked and have to disable the button from being double clicked each time.
$("button#new_game").on("click",function(e){
    if( $(this).hasClass("clicked") == false ){
        var $pre = $(this);
            $pre.addClass("clicked");

        createAjaxCall(function(result){
           $pre.removeClass("clicked");
        }
    }
});

Adding the clicked class can allow me to customize the button a bit I should mention, So I can't really use .data()
These are the three main jQuery repetitive/non optimized problems I run into.


texts:
I am currently attempting to implement Matrix Math for another project I am working on.

However, I am not sure whether this implementation will work. Can someone please tell me if there are any errors with my implementation?

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

typedef vector<vector<double> > Matrix;

Matrix add(Matrix a, Matrix b)
{
  assert(a.size() == b.size() && a[0].size() == b[0].size());

  int numRow = a.size(), numCol = a[0].size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = a[i][j] + b[i][j];
    }
  }

  return output;
}

Matrix subtract(Matrix a, Matrix b)
{
  assert(a.size() == b.size() && a[0].size() == b[0].size());

  int numRow = a.size(), numCol = a[0].size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = a[i][j] - b[i][j];
    }
  }

  return output;
}

Matrix multiply(Matrix a, double b)
{
  int numRow = a.size(), numCol = a[0].size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = a[i][j] * b;
    }
  }

  return output;
}

Matrix multiply(Matrix a, Matrix b)
{
  assert(a.size() == b.size() && a[0].size() == b[0].size());

  int numRow = a.size(), numCol = a[0].size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = a[i][j] * b[i][j];
    }
  }

  return output;
}

Matrix dotProduct(Matrix a, Matrix b)
{
  assert(a[0].size() == b.size());

  int numRow = a.size(), numCol = b[0].size();
  Matrix output(numRow, vector<double>(numCol, 0));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      for(unsigned int k = 0; k < a[0].size(); k++)
      {
        output[i][j] += a[i][k] * b[k][j];
      }
    }
  }

  return output;
}

Matrix transpose(Matrix a)
{
  int numRow = a[0].size(), numCol = a.size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = a[j][i];
    }
  }

  return output;
}

Matrix applyFunc(Matrix a, double (*f)(double))
{
  int numRow = a.size(), numCol = a[0].size();
  Matrix output(numRow, vector<double>(numCol));

  for(int i = 0; i < numRow; i++)
  {
    for(int j = 0; j < numCol; j++)
    {
      output[i][j] = (*f)(a[i][j]);
    }
  }

  return output;
}

int main()
{

}


texts:
I am creating a class project which involves two classes: Library and Book. I would like a general review on the code.

public class Book
{
    private String title;
    private String author;
    private String summary;

    public Book() {
        title = "";
        author = "";
        summary = "";
    }

    public Book(String title, String author, String summary) {
        this.title = title;
        this.author = author;
        this.summary = summary;
    }

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public String getSummary() {
        return summary;
    }
}

import java.util.*;

Next is my Library class.

import java.util.Scanner;

public class Library
    {
        private String location;
        private String openingHours;
        private Book book;
        private Map<Book,Integer> bookList = new HashMap<Book,Integer>();

        public Library(String location, String openingHours) {
            this.location = location;
            this.openingHours = openingHours;
        }

        public void addBook(Book book) {
            //If the book doesn't exist add it: otherwise increase the quantity of the book
            if (bookList.containsKey(book))
                bookList.put(book, bookList.get(book) + 1);
            else
                bookList.put(book, 1);
        }

        public String printOpeningHours() {
            return openingHours;
        }

        public String printAddress() {
            return location;
        }

        public void borrowBook(Book book) {
            bookList.put(book, bookList.get(book) - 1);
        }

        public void returnBook() {
            bookList.put(book, bookList.get(book) + 1);
        }

        public String printAvailableBooks() {
            ArrayList <String> available = new ArrayList();

            for (Book books: bookList.keySet())
                available.add(books.toString());

            return available.toString();
        }

        public boolean isBorrowed() {
            int value = 0;

            for (Book bq: bookList.keySet()) {
                value = bookList.get(bq);
                if (value > 0)
                    return true;
            }
            return false;
        }

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            Library l1 = new Library("111 Your Street", "9am");
            l1.addBook(new Book("Test", "Author", "Test summary"));
            l1.addBook(new Book("Test2", "Author2", "Test summary2"));
            l1.addBook(new Book("Test3", "Author3", "Test summary3"));
            System.out.println(l1.printAvailableBooks());
            System.out.print("Choose book: ");
            Book book = (Book) input.next();
            borrowBook(book);
        }
    }


texts: Script to download sequentially named files, rename them, and delete smaller files

texts:
I've written a little script to download sequentially named files, rename them, and delete files smaller than an certain number of kilobytes. I came up with this but I'm not too happy.  Any advice for me?

#!/bin/sh
echo
echo -n "Start file #:"
read start
echo
echo -n "End file #:"
read end
echo

wget --progress=bar:force http://www.mybox.com/pictures/show_pic.asp?src_id={$start..$end} 2>&1 | progressfilt

sleep 1

for file in *.asp
do
    mv "$file" "${file%.asp}.jpg"
done

find * -maxdepth 1 -name "*.jpg" -size -300k -delete

echo "tasks completed...exiting"
exit


texts: split string into container on char; efficiently?

texts:
Here is my single parse code for splitting a std::string on a char into a std::vector<std::string>:

#include <iostream>
#include <vector>

std::vector<std::string> split_uri(std::string, unsigned chr='/');

int main() {
    std::vector<std::string> uri_v = split_uri(uri, '/');

    for (auto elem: uri_v)
         std::cout << elem << std::endl;
}

std::vector<std::string> split_uri(std::string uri, unsigned chr) {
    bool start=true;
    std::string part;
    std::vector<std::string> vec;
    vec.reserve(uri.length()/2);

    for(char c: uri) {
        switch(c) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case 'a':
            case 'b':
            case 'c':
            case 'd':
            case 'e':
            case 'f':
            case 'g':
            case 'h':
            case 'i':
            case 'j':
            case 'k':
            case 'l':
            case 'm':
            case 'n':
            case 'o':
            case 'p':
            case 'q':
            case 'r':
            case 's':
            case 't':
            case 'u':
            case 'v':
            case 'w':
            case 'x':
            case 'y':
            case 'z':
                part += c;
                break;
            default:
                if (c == chr) {
                    if (!start)
                        vec.push_back(part);
                    else start = false;
                    part.clear();
                    part += c;
                }
                else {
                    std::cerr << "Invalid URI; from: \'" << c << "\' (hex: " << std::hex << "0x" << (unsigned int)c << ")\n";
                    vec.clear();
                    return vec;
                }
        }
    }

    return vec;
}

What can I do to improve its efficiency?


texts: Calculating the sum, of the mod Q, position multiplied, sort sequence, of Fibonacci numbers

texts:
I need to write a program that uses the Fibonacci Sequence to calculate a sum.

The calculation requirement

1: Take the first n Fibonacci numbers (excluding F0)
    S1 = {F1, F2, F3 ..... , Fn}
2: Modulo each Fibonacci number by a positive value Q
    S2 = {A1, A2, A3 ..... , An}  Where Ax = Fx % Q
3: Sort the number in S2 (small to large)
    S3 = {C1, C2, C3 ..... , Cn}
4: Calculated the weighted sum:
    S = 1.C1 + 2.C2 + 3.C3 ......... + n.Cn

I tried to use recursion to find out the Fibonacci number and the professor gave hints to me: "use radix sort to sort the sequence".

I tried it but the result is the program run not fast enough. When the program needs to calculate first 5000000 numbers, it will run a very very long time.

Do there exist any algorithms that can make the program the fastest?

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

int maxbit(int data[], int n)
{
    int maxData = data[0];

    for (int i = 1; i < n; ++i)
    {
        if (maxData < data[i])
            maxData = data[i];
    }
    int d = 1;
    int p = 10;
    while (maxData >= p)
    {

        maxData /= 10;
        ++d;
    }
    return d;

}
void radixsort(int data[], int n)
{
    int d = maxbit(data, n);
    int *tmp = new int[n];
    int *count = new int[10];
    int i, j, k;
    int radix = 1;
    for (i = 1; i <= d; i++)
    {
        for (j = 0; j < 10; j++)
            count[j] = 0;
        for (j = 0; j < n; j++)
        {
            k = (data[j] / radix) % 10;
            count[k]++;
        }
        for (j = 1; j < 10; j++)
            count[j] = count[j - 1] + count[j];
        for (j = n - 1; j >= 0; j--)
        {
            k = (data[j] / radix) % 10;
            tmp[count[k] - 1] = data[j];
            count[k]--;
        }
        for (j = 0; j < n; j++)
            data[j] = tmp[j];
        radix = radix * 10;
    }
    delete[]tmp;
    delete[]count;
}

int fib(int n) {

    if (n == 0)
        return 0;

    if (n == 1)
        return 1;

    return (fib(n - 1) + fib(n - 2));

}

int main() {
    int T,n,Q;
    cin >> T;
    while (T--) {
        cin >> n >> Q;
        int* S1 = new int[n];
        int* A = new int[n];
        for (int i = 0; i < n; i++)
            S1[i] = fib(i+1);
        for (int i = 0; i < n; i++)
            A[i] = S1[i] % Q;

        radixsort(A,n);
        for (int i = 0; i < n; i++)
            A[i] = A[i] * (i + 1);
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += A[i];

        cout << sum%Q << endl;
        delete[] A;
        delete[] S1;
    }
    system("pause");
    return 0;
}


texts: Trying to convert an extended Array.prototype to a function

texts:
I got a random image rotator working by using the following script (demo). But I was told that it is a bad practice to extend Array.prototype. And it does. It conflicts with the chained select box unless I modify the selected box script. So I guess it's better to not use Array.prototype.shuffle ,isn't it?

Here's The script:

                Array.prototype.shuffle = function() {
                var s = [];
                while (this.length) s.push(this.splice(Math.random() * this.length, 1));
                while (s.length) this.push(s.pop());
                return this;
            }

            var picData = [
                ['img1','url_1'],
                ['img2','url_2'],
                ['img3','url_3'],

            picO = new Array();
            randIndex = new Array();
            for(i=0; i < picData.length; i++){
                picO[i] = new Image();
                picO[i].src = picData[i][0];
                picO[i].alt = picData[i][1];
                randIndex.push(i);
            }
            randIndex.shuffle();
            window.onload=function(){
                var mainImgs = document.getElementById('carouselh').getElementsByTagName('img');

                for(i=0; i < mainImgs.length; i++){
                    mainImgs[i].src = picO[randIndex[i]].src;
                    mainImgs[i].parentNode.href = picData[randIndex[i]][1];
                    mainImgs[i].alt = picData[randIndex[i]][1];
                }

            }

I'm not sure where to start. I'm reading this article, should I do something like

    Array.shuffle = function() {for(var
a=[];this.length;)a.push(array.splice(Math.random()*array.length,1));
for(;a.length;)this.push(a.pop());return this};

Would anyone please point me in some directions to rewrite that part?


texts:
I have a long-running task that processes an input file and then uploads it to a web server. The processing part can be interrupted (with cleanup) but the upload shouldn't be interruptable so that we know whether the server received the file correctly.

My thread looks like this (I'm using PyQt but I imagine this problem occurs in other threading modules too):

class ImportThread(QtCore.QThread):
    def __init__(self, path):
        super(ImportThread, self).__init__()

        self.path = path
        self.stopped = False

    @property
    def stopped(self):
        return self._stopped

    @stopped.setter
    def stopped(self, stopped):
        self._stopped = stopped

    def run(self):
        self.emit(QtCore.SIGNAL("processing()"))

        # Do the processing task unless the thread has already been stopped
        if not self.stopped:
            do_processing_task()

            # Don't move on to the next step if the thread has been stopped
            if not self.stopped:
                self.emit(QtCore.SIGNAL("uploading()"))
            else:
                cleanup_processed_file()
                return   # Exit thread

        do_upload_task()
        self.emit(QtCore.SIGNAL("completed()"))

I don't think the nested ifs are very readable and am looking for a way to clean this up. Any suggestions?

Usage looks a little like this:

# triggering thread
self.thread = ImportThread(path)
# ... connects() to thread signals that update the progress dialog ...
self.thread.start()

# Create a progress dialog to monitor the thread
self.progress = QtGui.QProgressDialog("Starting...", "Cancel", 0, 2, self)
self.progress.setValue(0)
self.progress.show()

# Connect cancellation signal from progress dialog to method to stop the thread
self.connect(self.progress, QtCore.SIGNAL("canceled()"), self.notify_cancelled)

def notify_cancelled(self):
    self.progress.setLabelText("Cancelling...")
    self.thread.stopped = True
    self.thread.exit()    # Not sure this is correct?
    self.progress.close()


texts:
import requests
import json
import time

f = open('ok.txt', 'r')
c = f.read()
r = []
start = time.perf_counter()

def steamCheck(name):
    return requests.get("https://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=removed&vanityurl=%s" % (name)).json()

for word in c.split():
    p = steamCheck(word)
    if p['response']['success'] == 42:
        with open('www.txt', 'a') as save:
            save.write(word + '\n')
            print('%s is available' % (word))
            r.append(word)
    else:
        print('%s is taken' % (word))

finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')

Hi this is a script I made to check if each word from a list exists as a vanityurl on steam or not.
I removed the api key so if you wanted to test yourself you would have to get one here :
https://steamcommunity.com/dev/apikey

I am a beginner in python and would like to know how you would change my script to make it better (faster, cleaner, etc..).
So far it works as intended however it is fairly slow and believe I may be doing something inefficiently.
Thanks for any advice you may have.

Example response from api if url is not taken:

{'response': {'success': 42, 'message': 'No match'}}

Example if the url IS taken:

{"response": {"steamid": "76561198868XXXXXX", "success": 1}}


texts:
I have developed this simple TCP Server/Client communication program, and am looking for ways of lowering the code footprint where possible.Side note, Both Classes are Main as they run independently, though interact.

TCPClient

package socketUse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;

class TCPClient
{
    public static void main(String[] args) throws Exception
    {
        try
        {
        String input;
        String modedInput;
        System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        @SuppressWarnings("resource")
        Socket client = new Socket("localhost", 22003);
        client.setSoTimeout(3000);
        while(true)
        {
            DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
            input = inFromUser.readLine();
            outToServer.writeBytes(input + '\n');
            modedInput = inFromServer.readLine();
            System.out.println("You Sent: " + modedInput);
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }
        }
        }
        catch(SocketTimeoutException e)
        {
            System.out.println("Timed Out Waiting for a Response from the Server");
        }

    }
}

TCPServer

package socketUse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class TCPServer
{
    public static void main(String[] args) throws Exception
    {
        try
        {
            String TCPclientMess;
            String returnMess;
            @SuppressWarnings("resource")
            ServerSocket input = new ServerSocket(22003);

            while(true)
            {
                Socket connectionSocket = input.accept();
                BufferedReader iptFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream optToClient = new DataOutputStream(connectionSocket.getOutputStream());
                TCPclientMess = iptFromClient.readLine();
                System.out.println("You Sent: " + TCPclientMess);
                returnMess = TCPclientMess;
                optToClient.writeBytes(returnMess);
            }
        }

        catch(Exception e)
        {
            e.getStackTrace();
        }
    }
}


texts: Find overlaps between lists of axis-aligned rectangles using line sweep

texts:
Triggered by Finding overlaps between two lists of axis-aligned rectangles, I tried to code "rectilinear" intersection using line sweep - in python.
I'm not keen on discussing (2D) line sweep in general here (which is why this isn't tagged algorithm).
The code looks small enough to stay a single module.
I didn't take the time to digest PEP 8 & Co.

"""
intersection/overlap between iso-oriented(axis-aligned)
 rectangles from separate collections
relies on left < right with every rectangle
"""
from collections import namedtuple
from intervaltree import IntervalTree#, Interval
from heapq import heapify, heappop, heapreplace

Rectangle = namedtuple('Rectangle', 'xLow yLow, xHigh yHigh')
Event = namedtuple('LineSweepEvent', 'x y, r, category')

# from karu's
# "Finding overlaps between two lists of axis-aligned rectangles"
# (https://codereview.stackexchange.com/q/147177/93149)
rect  = Rectangle(10, 12,  56, 15)
rect2 = Rectangle( 0,  0,   1, 15)
rect3 = Rectangle(10, 12,  56, 15)

listA = (rect, rect2, Rectangle(1, 5, 16, 17))
listB = (rect3,       Rectangle(0, 1,  2, 13))

# event queue processing relies on indexing the next three alike
lists = (listA, listB)
labels = ('listA', "listB")
intervals = tuple(IntervalTree() for l in lists)
nCategories = len(lists)

# find overlaps by line sweep:
# "put left edges in event queue"
events = [Event(r.xLow, r.yLow, r, category)
              for category, items in enumerate(lists)
                  for r in items]
heapify(events)

# process event queue
while (events):
    e = events[0]
    c = e.category
#    print(e)
    if e.x == e.r.xLow:  # left edge
        intervals[c].addi(e.y, e.r.yHigh, e.r)
#         e.x = e.r.xHigh  # replace left edge event by right
        heapreplace(events, e._replace(x=e.r.xHigh))
        headerShown = False
        for o in range(nCategories):
            if o != c:
                found = intervals[o].search(e.y, e.r.yHigh)
                if found:
                    if not headerShown:
                        print(labels[c], e.r, " overlaps")
                        headerShown = True
                    print("\t" + labels[o],
                          [iv.data for iv in found])
    else:  # right edge
        intervals[c].removei(e.y, e.r.yHigh, e.r)
        heappop(events)

(I had no luck using "the []-interface" to IntervalTree.)
I have an idea what made me refrain from creating a class to (temporarily) keep a rectangle list, its label and its intervals "on the sweep-line" together - would a "named tuple" be/look more lightweight?
Is ("avoidably") creating a new object using _replace() too costly?
Suggestions (/edits) to make this code more readable or pythonesque (pythonic? "less irritating to those well versed in python") welcome.


texts:
I am writing a small class that has one method: get_state. It is parameterless and returns a dictionary of all the names in self (look in its dict) that are not bound to function objects (test functions by using inspect.isfunction on the objects). When a class inherits from Dumpable, its instances can call get_state() to get a dictionary of all the names in its namespace (that are not functions) and their values.

For example, if we first defined class Modular_Counter(Dumpable) and then mc = Modular_Counter(0,3) and then print(mc.get_state()), it would print the following dictionary: {'_value': 0, '_modulus': 3}.

Here is my current working code for the class:

class Dumpable:
    def get_state(self):
        no_funs = self.__dict__
        no_fun_list = [no_fun_key for no_fun_key in no_funs.keys() if inspect.isfunction(no_funs[no_fun_key])]
        for fun in no_fun_list:
            del no_funs[fun]
        return no_funs

Is there a cleaner way to get the same results? I still need to use the one function in the class. Any help would be appreciated.


texts:
I'm visiting some code that I wrote for one of my finals projects and wanted to know whether there were a more optimal, more elegant way to do this so it does not look so "hard-coded".

The problem was that I needed to calculate the Determinant of a matrix, and, at the time (some of it was rushed) I did not know of a better way, using loops or re-usable code that could make the code a little better. Here is the code:

namespace Determinant {

    template<int X>
    float determinant(std::vector<Vector> &data)
    {

        float deter = 0.0;
        if(X == 2)
        {
            float a = data[0][0];
            float b = data[1][0];
            float c = data[1][1];

            deter = (a + c) * (a + c) -4 * (a*c-b*b);
        }else if(X == 3)
        {

            float determinant1 = (data[1][1] * data[2][2]) - (data[2][1] * data[1][2]);
            float determinant2 = (data[1][0] * data[2][2]) - (data[2][0] * data[1][2]);
            float determinant3 = (data[1][0] * data[2][1]) - (data[2][0] * data[1][1]);

            deter = (data[0][0] * determinant1) - (data[0][1] * determinant2) + (data[0][2] * determinant3);
        }
        return deter;
    }
}

As you can see the Determinant is very hard-coded which is probably not the right way -- But are there any other alternatives that isn't hard-coded? I want to start to use a design pattern, as I feel one would be useful here but can't seem to figure out which one.


texts: Queue that permits at most X simultaneous operations

texts:
I ran into this once (permits=N) and then again today (permits =1) where I only want 1 to N operations running simultaneously.  One example comes from firing into a state machine (the permit=1 example) where I don't want more than 1 person firing in and I want the rest to queue up the request and return the thread to do more work.  The other example is the http2 spec says if remote end gives you max_concurrent=N, you must obey.  I wrote a generic wrapper around some function, CompleteableFuture<RESP> someFunction.

Here is my entire implementation where I try to avoid the synchronized keyword.  I would have also preferred to just re-use client threads only and not have an executor but I could not figure out a way without letting a client thread get stuck processing which could be really bad.

public class PermitQueue<RESP> {

private static final Logger log = LoggerFactory.getLogger(PermitQueue.class);
private final ConcurrentLinkedQueue<QueuedRequest<RESP>> queue = new ConcurrentLinkedQueue<>();
private final Semaphore permits;
private Executor executor;

public PermitQueue(Executor executor, int numPermits) {
    this.executor = executor;
    permits = new Semaphore(numPermits);
}

public CompletableFuture<RESP> runRequest(Supplier<CompletableFuture<RESP>> processor) {
    CompletableFuture<RESP> future = new CompletableFuture<RESP>();
    queue.add(new QueuedRequest<>(future, processor));

    processItemFromQueue();

    return future;
}

private void processItemFromQueue() {
    boolean acquired = permits.tryAcquire();
    if(!acquired)
        return;

    QueuedRequest<RESP> req = queue.poll();
    if(req == null) {
        permits.release(); //ended up not using it
        return;
    }

    CompletableFuture<RESP> future = req.getFuture();

    try {
        CompletableFuture<RESP> resp = req.getProcessor().get();
        resp.handle((r, t) -> handle(r, t, future));
    } catch(Throwable e) {
        log.warn("Exception", e);
        handle(null, e, future);
    }
}

private Void handle(RESP resp, Throwable t, CompletableFuture<RESP> future) {
    if(t != null)
        future.completeExceptionally(new RuntimeException(t));
    else
        future.complete(resp);

    permits.release();

    executor.execute(() -> processItemFromQueue());

    return null;
}

}


texts:
I wrote a code which prints the following pattern :

5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5

The code is as follows :

#include <stdio.h>

void main(){
   int n,i,k,b,a;
   printf("ENTER OUTER NUMBER:");
   scanf("%d",&n);
   for(i=0;i<2*n-1;i++){
     printf("%d",n);
   }
   printf("\n");
   int p=n;
   for(i=0;i<n-1;i++){
     int a=0;
     for(k=0;k<=i;k++){
        printf("%d",n-a);
        a++;
     }
     for(b=0;b>i;b++){
        printf(" ");
     }
     for(k=1;k<=2*p-3;k++){
        printf("%d",n-i-1);
     }
     p--;
     for(k=i;k>=0;k--){
        printf("%d",n-k);
     }
     printf("\n");
   }
    int q=1;
    for(i=0;i<n-2;i++){
     for(k=n;k>i+1;k--){
        printf("%d",k);
     }
     for(k=1;k<=2*q-1;k++){
        printf("%d",q+1);
     }
     q++;
     for(k=2+i;k<=n;k++){
        printf("%d",k);
     }
     printf("\n");
   }
   for(i=0;i<2*n-1;i++){
     printf("%d",n);
   }
   getchar();
}

I printed the first and last line independently.Then,I divided the pattern into two halves and considered some common triangular patterns as follows:

5                 5    2 3 4 5
5 4             4 5      3 4 5
5 4 3         3 4 5        4 5
5 4 3 2     2 3 4 5          5

The code ran well in the CODE BLOCKS IDE.But, I think it's too long and I complicated the coding.My query is:

Can I shorten the code with the similar logic of breaking the pattern into parts or mine is ok ?
Is there any alternative to this ?


texts:
You have two lists with meetings scheduling (start time, end time). Meetings in single list don't intersect. Find all intersecting meetings across the two lists.

Is my complexity \$O(N M)\$? If I use binary search I might get \$O(N \log M)\$. Can you think of a better algorithm?

For simplicity, I didn't use DateTime. I just assumed meetings are in round hours.

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

namespace ConsoleApplication2
{

    public class IntersectingMeetings
    {
        public IntersectingMeetings()
        {
            MeetingList meetingList1 = new MeetingList();
            MeetingList meetingList2 = new MeetingList();
            meetingList1.AddMeeting(2,3);
            meetingList1.AddMeeting(1,2);

            meetingList1.AddMeeting(4,6);

            meetingList2.AddMeeting(2,3);
            meetingList2.AddMeeting(3,4);
            meetingList2.AddMeeting(5,6);
            List<Meeting> intersectionsList = FindInterSections(meetingList1, meetingList2);
        }

        private List<Meeting> FindInterSections(MeetingList meetingList1,MeetingList meetingList2)
        {
            meetingList1.list.Sort();
            meetingList2.list.Sort();
            List<Meeting> intersectingList = new List<Meeting>();
            foreach (var item in meetingList1.list)
            {
                foreach (var other in meetingList2.list)
                {
                    if ((item.StartTime >= other.StartTime && item.EndTime <= other.EndTime) ||
                        (other.StartTime >=item.StartTime && other.EndTime <=item.EndTime))
                    {
                        intersectingList.Add(item);
                        intersectingList.Add(other);
                    }
                }
            }
            return intersectingList;
        }
    }

    public class MeetingList
    {
        public List<Meeting> list;
        public MeetingList()
        {
            list = new List<Meeting>();
        }
        public void AddMeeting(int start, int end)
        {
            list.Add(new Meeting(start,end));
        }
    }

    public class Meeting : IComparable<Meeting>
    {
        public int StartTime { set; get; }
        public int EndTime { set; get; }

        public Meeting(int start, int end)
        {
            StartTime = start;
            EndTime = end;
        }

        public int CompareTo(Meeting other)
        {
            if (StartTime > other.StartTime)
            {
                return 1;
            }
            else if (StartTime < other.StartTime)
            {
                return -1;
            }
            return 0;
        }
    }
}

This is one solution of the problem I have found.

An efficient approach is to first sort the intervals according to starting time. Once we have the sorted intervals, we can combine all intervals in a linear traversal. The idea is, in sorted array of intervals, if interval[i] doesn't overlap with interval[i-1], then interval[i+1] cannot overlap with interval[i-1] because starting time of interval[i+1] must be greater than or equal to interval[i]. Following is the detailed step-by-step algorithm.


texts: Overlay a YouTube video iFrame Over an Image

texts:
This is my code and the main thing I wanted to accomplish when creating this was to: overlay an iFrame over an image and also to see if I could embed a YouTube video iFrame with the video ID entered through a form. This is what I came up with.

function changeChannel() {
    var out = document.getElementById("vid");
    var inp = document.getElementById("form");
    var base = "https://www.youtube.com/embed/";
    var params = "?autoplay=1&loop=1&controls=0&showinfo=0&rel=0&disablekb=1";
    if (inp.value.length > 11) {
        alert("Nice HTML Attribute editing! But honestly, why even try?");
        out.src = base + "kffacxfA7G4" + params;
    }
    else {
        out.src = base + inp.value + params;
    }
}
#bg {
    background-image: url(https://i.imgur.com/CexLZOK.jpg);
    width: 900px;
    height: 412px;
}

#vid {
    border: 0;
    position: relative;
    left: 233px;
    top: 56px;
    width: 81px;
    height: 66px;
    pointer-events: none;
}
<!DOCTYPE HTML>

<title>What's Osama Bin Watchin'?</title>
<meta charset="utf-8">

What's Osama Bin Watchin'?

<input type="text" maxlength="11" placeholder="Put A YouTube Video ID Here" id="form">
<input type="submit" onclick="changeChannel()">

Some commercial or sponsored videos might not work, or it might not work if the video id you entered is invalid...

I came here to see if anyone has any ideas of something(s) I should change, or could change; after all it is Code Review. I was also wondering why the YouTube Player iFrame does not loop.

UPDATE:
Here is a live link.Ok, so for anyone else that sees this please DO NOT take this seriously! It was a satirical joke, and honestly, I went here to see if my code was any good at completing the task of displaying an image overlaid on an iFrame. Not to be downvoted because people were too offended to actually take a look at the code and give me some pointers.


texts: mIRC scripting like string token manipulation in Lua

texts:
I'm trying to reproduce in Lua the  mIRC scripting manipulating tokens function:

local function tokenize(C, text)
    local char = string.format("%c", C)
    local t = {}
    for w in string.gmatch(tostring(text), "[^"..char.."]+") do
    w = tonumber(w) or tostring(w)
    table.insert(t,w)
    end
    return t
end

local function gettok(strng, position, separator, range)
  local char = string.format("%c", separator)
  local tokens = tokenize(separator, strng)
  local result, n, r, start, stop
  if (position ~= 0) then
    if (position > 0) then n = position else n = #tokens + position + 1 end
    if (range) and (position ~= range) then
      if (range > 0) then r = range

      elseif (range == 0) or ((n + range) > #tokens) then r = #tokens
      else r = n + (range + 1)
      end
      if (n == r) then
        result = tokens[i]
      else
        start = (r >= n) and n or r
        stop = (r <= n) and n or r
        for i = start, stop do
          result = (not result) and tokens[i] or tostring(result..char..tokens[i])
        end
      end
    else
      for i = 1, #tokens do
        if (i == n) then result = tokens[i] end
      end
    end
  else result = strng
  end
  return result
end

And this is the way it should work:

gettok(strng, position, separator, range)

Where

strng = string to manipulate
position = position of the token inside the string. If lesser than 0, it will be considered the position from the last token to the first. If equal to 0, returns the whole string.
separator = ASCII code of the token separator
range = optional: if specified, returns the token from position to range. If equal to 0, return all tokens from position to the end of the string.

local text = "apple.banana.cherry.grape.orange"

  apple

gettok(text,1,46)

  grape

gettok(text,-2,46)

  banana.cherry.grape

gettok(text,2,46,4)

  cherry.grape.orange

gettok(text,-1,46,-3)

Could you give me some advice on improving the code?


texts: Implement Java hasNext() and next() in C++

texts:
Recently came upon this question asked in interview with major tech company.

  Implement Java's next and hasNext function in your favorite
  programming language.

Here is the solution I came up with. I am not sure whether next() is implemented correctly. Here is the iterator documentation.

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

template <class T>
class iterator {
public:
    iterator() {}
    iterator(std::vector<T> vec) {
        container = vec;
    }
    bool hasNext() {
        if (curr_pos == container.size()) {
            return false;
        } else {
            if (curr_pos < container.size()) {
                return true;
            }
        }
        return false;
    }
    T next(){
        if (hasNext()) {
            curr_pos += 1;
            return container.at(curr_pos-1);
        }
    }
private:
    std::vector<T> container;
    int curr_pos = 0;
};

int main() {
    std::vector<int> int_vec {1,2,3,4};
    iterator<int> int_it(int_vec);
    while (int_it.hasNext()) {
        std::cout << int_it.next() << " ";
    }

    std::cout << std::endl;

    std::vector<std::string> str_vec {"a", "b", "c","d"};
    iterator<std::string> str_it(str_vec);
    while(str_it.hasNext()) {
        std::cout << str_it.next() << " ";
    }
    std::cout << std::endl;
    std::vector<int> empty_vec;
    iterator<int> empty_it(empty_vec);
    while(empty_it.hasNext()) {
        std::cout << empty_it.next() << " ";
    }
    return 0;
}

Here is the working version of the above code.


texts: Ruby implementation of Soundex algorithm

texts:
I'm new to Ruby. I normally sling code in C#. What could I do to make this simple Soundex class more Rubyesque?

class Surname
  attr_accessor :value

  def initialize(input)
    @value = input
  end

  def soundex
    result = ''
    @value.chars.drop(1).each do |s|
      number = soundex_value(s).to_s
      result &lt;&lt; number unless result[-1,1] == number
    end
    @value.chars.first &lt;&lt; result.ljust(3,'0')
  end

  def soundex_value(s)
    case s
    when /[bfpv]/
      1
    when /[cgjkqsxz]/
      2
    when /[dt]/
      3
    when /l/
      4
    when /[mn]/
      5
    when /r/
      6
    else ''
    end
  end
end

def print_name(input)
  surname = Surname.new(input)
  puts(surname.value + ' => ' + surname.soundex)
end

['Smith', 'Johnson', 'Williams', 'Jones', 'Brown'].each do |s|
  print_name s
end

The output is:

Smith => S530
Johnson => J525
Williams => W452
Jones => J520
Brown => B650


texts: Computing the sum of squared differences

texts:
About Data: 3D data (100x100x20).

Computation/Formula and Method: I am trying to compute the sum of squared differences along rows, columns and angles for various time differences.

%% Grid and time paramters

%# Grid parameters
nRows=100;
nCol=100;
InitLag_Row=0;
InitLag_Col=0;
InitLag_Ang=0;
LessLags=20;
nLags_Row=nRows-LessLags;
nLags_Col=nCol-LessLags;
nLags_Ang=min(nRows,nCol)-LessLags;

%# Time parameters
T=1:1:20;
nT=numel(T);

%# Load concentrations data file with 100x100x20 dimensions
load('c.mat')

%% Shift values along rows for all columns and all time steps
for hRow=InitLag_Row:nLags_Row
    c_ShiftedRow(:,:,:,hRow+1)=circshift(c(:,:,:),[-hRow 0]);
end

%% Shift values along columns for all rows and all time steps
for hCol=InitLag_Col:nLags_Col
    c_ShiftedCol(:,:,:,hCol+1)=circshift(c(:,:,:),[0 -hCol]);
end

%% Shift values along NW-SE and NE-SW directions for all time steps
for hAng=InitLag_Ang:nLags_Ang
    c_ShiftedNWSE(:,:,:,hAng+1)=circshift(c(:,:,:),[-hAng -hAng]);
    c_ShiftedNESW(:,:,:,hAng+1)=circshift(c(:,:,:),[-hAng hAng]);
end

idel_t=1; % initialize index for zero time lag
for del_t=0:nT-1 % time lag
    for nLags_t=1:nT-del_t; % number of time lags formed with del_t lag value
        for hRow=InitLag_Row:nLags_Row
            variogramTemp_hRow3D=(cumsum(((c(1:end-hRow,:,nLags_t)-...
                c_ShiftedRow(1:end-hRow,:,nLags_t+del_t,hRow+1)).^2),1))./...
                (2*size(c(1:end-hRow,:,nLags_t),1));

            variogram_hRow3D(hRow+1,:,nLags_t,idel_t)=variogramTemp_hRow3D(end,:)./...
                mean(var(c(1:end-hRow,:,[nLags_t,nLags_t+del_t]),0,1),3);
        end
        %% Variogram along columns for all images
        for hCol=InitLag_Col:nLags_Col
            variogramTemp_hCol3D=(cumsum(((c(:,1:end-hCol,nLags_t)-...
                c_ShiftedCol(:,1:end-hCol,nLags_t+del_t,hCol+1)).^2),2))./...
                (2*size(c(:,1:end-hCol,nLags_t),2));

            %# normalized variogram values at all times for different lags at all 'nRows'
            variogram_hCol3D(:,hCol+1,nLags_t,idel_t)=variogramTemp_hCol3D(:,end)./...
                mean(var(c(:,1:end-hCol,[nLags_t,nLags_t+del_t]),0,2),3);
        end
        %% Variogram along NW-SE and NE-SW directions for all images
        for hAng=InitLag_Ang:nLags_Ang
            variogramTemp_h3DNWSE=(cumsum(((c(1:end-hAng,1:end-hAng,nLags_t)-...
                c_ShiftedNWSE(1:end-hAng,1:end-hAng,nLags_t+del_t,hAng+1)).^2),1))./...
                (2*size(c(1:end-hAng,1:end-hAng,nLags_t),1));
            variogramTemp_h3DNESW=(cumsum(((c(1:end-hAng,end:-1:1+hAng,nLags_t)-...
                c_ShiftedNESW(1:end-hAng,end:-1:1+hAng,nLags_t+del_t,hAng+1)).^2),1))./...
                (2*size(c(1:end-hAng,end:-1:1+hAng,nLags_t),1));

            %# normalized variogram values/cumulative sum at all times for different lags along NW-SE and NE-SW directions
            variogram_h3DNWSE(hAng+1,1:nCol-hAng,nLags_t,idel_t)=variogramTemp_h3DNWSE(end,:)./...
                mean(var(c(1:end-hAng,1:end-hAng,[nLags_t,nLags_t+del_t]),0,1),3);
            variogram_h3DNESW(hAng+1,1:nCol-hAng,nLags_t,idel_t)=variogramTemp_h3DNESW(end,:)./...
                mean(var(c(1:end-hAng,end:-1:1+hAng,[nLags_t,nLags_t+del_t]),0,1),3);
        end
    end
    %# Change the zero matrices after nT-del_t to NaN
    variogram_hRow3D(:,:,nT-del_t+1:end,idel_t)=nan;
    variogram_hCol3D(:,:,nT-del_t+1:end,idel_t)=nan;
    variogram_h3DNWSE(:,:,nT-del_t+1:end,idel_t)=nan;
    variogram_h3DNESW(:,:,nT-del_t+1:end,idel_t)=nan;

    %# change to next time lag index
    idel_t=idel_t+1;
end

I would appreciate any help on ways to make this code faster and more efficient.


texts: Trim NA values from left and right of Rcpp::NumericVector

texts:
I receive data with NA values. I would like to trim off the leading and trailing NA values, but to leave the interior NA values in place.

I've written the below in Rcpp, but it is very much a hand rolled solution -- and i'm alive to the fact that i'm going to make mistakes doing things this way.

What is the idiomatic cpp / Rcpp (sugar?) way of doing  something like this?

#include<Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector trimNA(Rcpp::NumericVector X) {

    // find first and last non-NA value

    double * F = X.begin();
    double * pBegin = X.begin();
    double * pEnd = X.end();
    double * L = X.end() - 1; // note you must decrement by one as .end() is AFTER

    // look for the values
    while( F < pEnd && NumericVector::is_na(*F)) F++;
    while( L > pBegin && NumericVector::is_na(*L)) L--;

    // create trimmed X vector
    Rcpp::NumericVector Xtrim(L - F + 1);

    for( int i = 0; i < Xtrim.size(); i++) {
        Xtrim[i] = *(F + i);
    }

    return Xtrim;
}

/*** R

x <- c(NA, NA, NA, 1:4, NA, 6:8, NA, 10, NA, NA, NA)
trimNA(x)
*/


texts: Settings dialog, using information from its parent window

texts:
My MainWindow popups a SettingsDialog. The setting dialog need to hide certain fields if the connected device is certain type.

void MainWindow::on_actionSettings_triggered()
{
    SettingsDialog * settings = new SettingsDialog(this);

    settings->exec();
}

Now in SettingsDialog:

SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    QSettings settings;

    MainWindow * mainWindow = (MainWindow *) parent;

    if ( mainWindow->deviceType == DEVICE_TYPE_B )
    {
        ui->comboBoxIP->setVisible( false );
    }
}

It works fine but is it a good way to access the info which is present in the parent window? or should the parent window pass in the device type in the constructor so it only knows the device type and work with it?


texts: Using Specs when testing the process of assigning offers to a customer 2

texts:
Following on from this question: Using Specs when testing the process of assigning offers to a customer.  I received some useful suggestions from t3chb0t and
paparazzo.  Therefore I have decided to revisit the code (without the specs).  Here is a new version of the code:

public class Concor : IProduct
    {
        private const decimal _expenditure = 100;
        public bool IsEligible(Customer customer)
        {
            return (customer.Expenditure < _expenditure);
        }
    }

    public class Chestnut : IProduct
    {
        private const decimal _expenditure = 100;

        public bool IsEligible(Customer customer)
        {
            return (customer.Expenditure >= _expenditure);
        }
    }

    public interface IProduct
    {
        bool IsEligible(Customer customer);
    }

    public class Customer
    {
        private readonly Guid _id;
        private readonly decimal _expenditure;
        private readonly IList<IProduct> _eligibleProducts = new List<IProduct>();
        public IEnumerable<IProduct> EligibleProducts
        {
            get { foreach (var product in _eligibleProducts) yield return product; }
        }

        public Guid Id
        {
            get
            {
                return _id;
            }
        }

        public Decimal Expenditure
        {
            get
            {
                return _expenditure;
            }
        }

        public Customer(Guid id, decimal expenditure)
        {
            _id = id;
            _expenditure = expenditure;
        }

        public void AddProduct(IProduct eligibleProduct)
        {
            _eligibleProducts.Add(eligibleProduct);
        }

        public IEnumerable<IProduct> DetermineEligibility(IList<IProduct> availableProducts)
        {
            return availableProducts.Where(x => x.IsEligible(this));
        }
    }

As it stands the client application will do something like this:

var eligibleProducts= customer.DetermineEligibility(availableProducts).ToList<IProduct>();
eligibleProducts.ToList().ForEach(c => customer.AddProduct(c));

Here are some points:

1) Customer now implements the IEnumerable method.  I understand the reasoning for removing EligibilityCalculator, however I am wandering if Customer now has too many responsibilities.

2) I have corrected the issues with the _assignedProducts list from the last question:
   a) The private variable (_eligibleProducts) has an underscore.
   b) The public variable (EligibleProducts) does not have an underscore.

3) Renamed AddOffer to AddProduct.

4) Reduced the number of lines of code in: IsEligible to 1.

5) Removed the Gender constant.

6) Reduced the number of lines in DetermineEligibility (was CalculateEligibility) to 1.

7) Made private read only fields after introducing public getters.

I would be grateful for comments about the quality of the code and specifically the naming.  Customers are pre approved for products, so I wander if eligible is the correct word.

My specific question surrounds the use of the DetermineEligibility method.  Alternatively, I could change AddProduct to this (and remove DetermineEligibhility):

public void AddProducts(IList<IProduct> availableProducts)
        {
            var eligibleProducts = availableProducts.Where(x => x.IsEligible(this));
            eligibleProducts.ToList().ForEach(c => _eligibleProducts.Add(c));
        }


texts: Converting duplicate JS code into a higher order function

texts:
I have a block of code that is re-used and I want to use functional programming to remove this duplication.
My code takes an array of items, splits the items into batches of 500 and then does some kind of work on them.
In the first function it deletes items from a database:
Delete function:
const deleteDocuments = async (documentReferences) => {
   const batchesOf500 = Math.ceil(documentReferences.length / 500);

   for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
      const batch = getBatchWriter();
      const startingIndex = batchNumber * 500;
      const maxIndex = startingIndex + 500;

      for(let index = startingIndex; index < maxIndex; index += 1) {
         if(index < documentReferences.length) {
            const documentPath = documentReferences[index];
            batch.delete(documentPath);
         }
      }

      await batch.commit();
   }
}

The second function is almost identical but instead of deleting from a database, it writes to the database:
Add function:
const writeToCollection = async (dataArray, collectionRef) => {
   const batchesOf500 = Math.ceil(dataArray.length / 500);

   for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
      const batch = getBatchWriter();
      const startingIndex = batchNumber * 500;
      const maxIndex = startingIndex + 500;

      for(let index = startingIndex; index < maxIndex; index += 1) {
            if(index < dataArray.length) {
               const [key, value] = dataArray[index];
               const doc = getDocFromPath(key);
               batch.set(doc, value);
            }
         }
      }

      await batch.commit();
   }
}

These functions are almost identical, so I have write a higher order function to do most of the leg-work.
Higher order function:
const runFunctionInBatchesOf500 = (func, dataArray) => {
   const batchesOf500 = Math.ceil(dataArray.length / 500);

   for(let batchNumber = 0; batchNumber < batchesOf500; batchNumber += 1) {
      const batch = this.firestore.batch();
      const startingIndex = batchNumber * 500;
      const maxIndex = startingIndex + 500;

      for(let index = startingIndex; index < maxIndex; index += 1) {
         const document = dataArray[index];
         func(document, batch);
      }
   }

   await batch.commit();
}

And to it you can create your own functionality to apply to each document and use it like this:
const write = (document, batch) => {
   const doc = getDocFromPath(key);
   batch.set(doc, value);
};

await runFunctionInBatchesOf500(write, dataArray);

This all works but I think I am missing something. Is this an efficient use of higher order functions? What would a more elegant, FP-style solution be?


texts:
I have been writing a compiler. While profiling the compiler, one method takes 5 seconds to compile 2k lines of code, my profiler tells me that this is the bottleneck.

   def toLLVMHelp(self, tree= None, isGlobal= True):
    if tree == None:
        tree = self.tree #tree is the Ast

    for i in tree: #iterate through the top node
        g = not type(i) is Tree.FuncStart and not type(i) is Tree.FuncBraceOpen and not type(i) is Tree.FuncBody and isGlobal
        #for code that is not inside a function, it must be put somewhere else, g is a boolean for checking if outside a function
        if g:
            if i.isEnd(): #is the end node
                self.main += i.compile(self)
            else:
                self.toLLVMHelp(i, g) #recurse for further nodes
                self.main += i.compile(self) #compile turns the node into 'llvm-ir'
        else:
            if i.isEnd():
                self.out += i.compile(self)
            else:
                self.toLLVMHelp(i, g)
                self.out += i.compile(self)

I am guessing, that it is slow because of object dispatch. Any suggestion, would be greatly appreciated.


texts: Calculating sum of manhattan distances in a sliding puzzle

texts:
I would like some feed back on a method which calculates the sum of Manhattan distances for each tile in a sliding puzzle to its goal position in the goal puzzle.

Here is the code:

public static int calcManhattanDistance(int[] ps, int[] goal) {
    int rowSz = calculatePuzzleRowSize(ps);
    int manhattanDistanceSum = 0;
    for (int i = 0; i < ps.length; i++) {
        for (int j = 0; j < ps.length; j++) {
            if (ps[i] == goal[j])
                manhattanDistanceSum += (Math.abs(i/rowSz - j/rowSz) + Math.abs(i%rowSz - j%rowSz));
        }
    }
    return manhattanDistanceSum;
}

Please tell me if you think something should be changed or what I can do to increase efficiency.

Here is the calculatePuzzleRowSize(ps) method:

public static int calculatePuzzleRowSize(int[] ps) {
    int sz = ps.length;
    int rowSz = (int) Math.sqrt(sz);
    return rowSz;
}

Here is the newly implemented calculateManhattanDistanceSum

public static int calculateManhattanDistanceSum(int[] ps, int[] goal) {
    int rowSize = (int) Math.sqrt(ps.length);
    int manhattanDistanceSum = 0;
    Map<Integer, Integer> psMap = new HashMap<Integer, Integer>();
    for (int i : ps)
        psMap.put(ps[i], i);
    for (int j : goal)
        manhattanDistanceSum += Math.abs(psMap.get(j)/rowSize - j/rowSize) + Math.abs(psMap.get(j)%rowSize - j%rowSize);
    return manhattanDistanceSum;
}


texts:
if params[:package]
  city_ids = []

  city = params[:package].delete 'city'
  city_ids << city  if city.to_i > 0

  cities = params[:package].delete 'cities'
  city_ids += cities  if cities.class == Array && cities.length > 0

  params[:package][:cities] = city_ids.map{ |c| City.get(c) }.compact
end


texts: Join / leave source-specific multicast group and connect / disconnect corresponding socket

texts:
I need to join source-specific multicast group and receive data.  When I don't need to receive data anymore, I need to leave the group and disconnect the socket.

Am I doing everything right? In particular, is this order of actions in Disconnect correct and complete?

Leave the group
Call shutdown for socket
Call closesocket for socket

int join_ssm_group(int s, UINT32 group, UINT32 source, UINT32 inter) {
    struct ip_mreq_source imr;
    imr.imr_multiaddr.s_addr  = group;
    imr.imr_sourceaddr.s_addr = source;
    imr.imr_interface.s_addr  = inter;
    return setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *) &imr, sizeof(imr));
}

int leave_ssm_group(int s, UINT32 group, UINT32 source, UINT32 inter) {
    struct ip_mreq_source imr;
    imr.imr_multiaddr.s_addr  = group;
    imr.imr_sourceaddr.s_addr = source;
    imr.imr_interface.s_addr  = inter;
    return setsockopt(s, IPPROTO_IP, IP_DROP_SOURCE_MEMBERSHIP, (char *) &imr, sizeof(imr));
}

void Receiver::ConnectSocket() {
    //  Make socket
    socketId = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);

    sockaddr_in Sender;
    int SenderAddrSize = sizeof(Sender);

    struct sockaddr_in binda;

    //  Bind it to listen appropriate UDP port
    binda.sin_family = AF_INET;
    binda.sin_port = htons(port);
    binda.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(socketId,(struct sockaddr*)&binda, sizeof(binda));

    // Join to group
    join_ssm_group(socketId, group, source, INADDR_ANY);
}

void Receiver::DisconnectSocket() {
    leave_ssm_group(socketId, group, source, INADDR_ANY);

    int iResult = shutdown(socketId, SD_BOTH);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
    }
    closesocket(socketId);
}


texts: Converting file from Markdown-like markup into HTML using repeated substitutions

texts:
The following code reads a file, splits its data, replaces some characters in the data, and then joins the data again (I added more details in the comments):

// read plain text file and make content available in data
fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  // turn the data into an array
  data = data.split('\n\n')

  // make a clone of the array to be used in the if statements.
  var tree = data.slice()

  for (var i = 0; i < tree.length; ++i) {
    // turn #s into heading tags if #s are present
    if (tree[i].match(/^#/g)) {
      data[i] = data[i]
        .replace(/^#### (.*)/gm, '
$1
')
        .replace(/^### (.*)/gm, '
$1
')
        .replace(/^## (.*)/gm, '
$1
')
        .replace(/^# (.*)/gm, '
$1
')
    }

    // smarten " or ' if present
    if (tree[i].match(/"|'/g)) {
      data[i] = data[i]
        .replace(/"(?=\b|\*|')/g, '“')
        .replace(/"(?!\b|\*|')/g, '”')
        .replace(/'(?!\b|\*)|(?=\b)'(?=\b)/g, '’')
        .replace(/'(?=\b|\*)/g, '‘')
    }

    // turn -- into — if present
    if (tree[i].match(/--/g)) {
      data[i] = data[i]
        .replace(/\b--(\b)*/g, '—')
    }

    // turn * or ** into italics and bold if present
    if (tree[i].match(/\*\*|\*/g)) {
      data[i] = data[i]
        .replace(/\*\*([^\*|\s]+)\*\*/g, '$1')
        .replace(/\*([^\*|\s]+)\*/g, '$1')
    }

    // surround every element with p tags if the
    // element doesn't start with an #. Also if the previous element of
    // the element is # or * * * add the p tag with the class ni
    if (tree[i].match(/^[^#]/g)) {
      if (tree[i - 1] && (tree[i - 1].match(/^#/g) || tree[i - 1] === "* * *")) {
        data[i] = '
' + data[i] + '
'
      } else {
        data[i] = '
' + data[i] + '
'
      }
    }
  }

  // lastly, put the array together again to the saved as HTML
  data = data.join('\n\n')

  saveHtml(data)
})

Example input:

# Title

'Single quotes'

"Double Quotes"

* * *

Paragraphs

Output:

Title

‘Single quotes’

“Double Quotes”

* * *

Paragraphs

Is there a cleaner way to write those if statements? Or at least create a function so that there is less code in that fs.readFile block?


texts: Increase view counter with each page view

texts:
My question is similar to before, but now the code has changed completely. I would like to understand if this code is vulnerable to mysql injection.

    <?php

// Define our querystring variables
$option = (array_key_exists('option', $_POST) ? $_POST['option'] : false);
$view   = (array_key_exists('view', $_POST) ?  $_POST['view'] : false);
$id     = (array_key_exists('id', $_POST) ?  intval($_POST['id']) : false);

// Check wheter our variables are correct in order to proceed
if ($option == 'com_content' && $view == 'video' && $id > 0) {

    // Connect to the database
    include_once("../configuration.php");
    $cg = new JConfig;
    $con = mysqli_connect($cg->host,$cg->user,$cg->password,$cg->db);
    if (mysqli_connect_errno()) {
        die('n/a');
    }

    // Add new hit: Update the `times_viewed` field corresponding to specific video id
    $query = "UPDATE " . $cg->dbprefix . "hdflv_upload
                        SET `times_viewed` = `times_viewed` + 1
                        WHERE `id` LIKE " . $id . ";";

    if (mysqli_query($con, $query) === true) {

    // Get the updated `times_viewed` of video id
        $query  = "SELECT `times_viewed`
                             FROM " . $cg->dbprefix . "hdflv_upload
                             WHERE `id` LIKE " . $id . ";";
        $result = mysqli_fetch_assoc(mysqli_query($con, $query));
    }

    // close the connection to the database
    mysqli_close($con);
    $addone = $result['times_viewed'];
    echo $addone;
}
?>


texts:
I have this GenericDataAccess class to interact with database from my school. I want to ask for some suggestions and advice in how to to improve it and add new methods to it for future use and reference

public static class GenericDataAccess
{
    static GenericDataAccess()
    {

    }

    /// <summary>
    /// creates and prepares a new DbCommand object on a new connection
    /// </summary>
    /// <param name="command"></param>
    /// <returns></returns>
    public static DataTable ExecuteSelectCommand(DbCommand command)
    {
        // The DataTable to be returned
        DataTable table;

        try
        {
            //open connection
            command.Connection.Open();
            //execute command & save the result in DataTable
            DbDataReader reader = command.ExecuteReader();
            table = new DataTable();
            table.Load(reader);
        }
        catch (Exception ex)
        {
           Utilities.LogError(ex);
            throw;
        }
        finally
        {
            command.Connection.Close();
        }

        return table;
    }

    /// <summary>
    /// creates and prepares a new DbCommand object on a new connection
    /// </summary>
    /// <returns></returns>
    public static DbCommand CreateCommand()
    {

        //obtaine the database provider name
        string dataProviderName = CompuData_ProjectManagerConfiguration.DbProviderName;
        //Obtain database connection string
        string connectionString = CompuData_ProjectManagerConfiguration.DbconnctionString;
        //Create new Data Provider Factory
        DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
        //obtain a database specific connection object
        DbConnection conn = factory.CreateConnection();
        //set the connection string
        conn.ConnectionString = connectionString;
        //create a database specific command object
        DbCommand comn = conn.CreateCommand();
        //set the command type to store proc
        comn.CommandType = CommandType.StoredProcedure;

        //return the initialized command object
        return comn;
    }

    /// <summary>
    /// execute an update, delete, or insert command and return the number of affected rows
    /// </summary>
    /// <param name="command"></param>
    public static int ExecuteNonQuery(DbCommand command)
    {
        //the number of affected rows
        int affectedRows = -1;
        // Execute the command making sure the connection gets closed in the end
        try
        {
            //open connction
            command.Connection.Open();
            affectedRows = command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Utilities.LogError(ex);
            throw;
        }
        finally
        {
            command.Connection.Close();
        }

        return affectedRows;
    }

    // execute a select command and return a single result as a string
    public static string ExecuteScaler(DbCommand command)
    {
        // the value to be retuned
        string value = "";

        // Execute the command making sure the connection gets closed in the end
        try
        {
            //open the connection of command
            command.Connection.Open();
            //execute the command and get the number of affected rows

            value = command.ExecuteScalar().ToString();
        }
        catch (Exception ex)
        {
           Utilities.LogError(ex);
            throw;
        }
        finally
        {
            command.Connection.Close();
        }
        return value;
    }
}


texts:
I have a subroutine which re-formats cells after a heading is inserted into the document.

Most cells are 12.75 points high, whereas the headings are 15 points high.

When a heading (single line) is inserted, it pushes all of the other cells down, however the formatting does not move with them, so any headings below the inserted heading become 12.75 points high, while the cells above those headings become 15 points high.

Sub formatcell()
Dim sht1 As Worksheet
Set sht1 = ActiveSheet

Dim startRow As Integer
Dim endRow As Integer
Dim counter As Integer
Dim DoCell As Range
Dim start As Variant
Dim Finish As Variant

startRow = 16
endRow = FindLastRow(sht1)

'THIS BIT BELOW NEEDS TO BE SPED UP'
start = Timer                 'Start Timer'
counter = startRow
Do While counter < endRow + 1
    Set DoCell = sht1.Cells(counter, 1)
    Debug.Print "DoCell = " & DoCell.Address
    If DoCell.MergeArea.Count > 2 Then
        DoCell.RowHeight = 15
    Else
        DoCell.RowHeight = 12.75
    End If
    counter = counter + 1
Loop
Finish = Timer                            'End timer'
MsgBox = "Time Taken = " & Finish - start

End Sub

This uses the Range.MergeArea.Count method (which identifies the headings as they are 26 cells wide), however I need to move through all of the cells below Row 15 to the end of the sheet and format them all. The problem is that it takes roughly 0.06 seconds per row. This sheet can easily have over 100 rows which need formatting, which is then 6sec I need to wait, which is frustrating.

Is there any other method to do this? Could I give the heading cell a range name (i.e. Heading) when I insert it, and then lookup all cells with that range name?


texts: Abstracted email sender with content providers

texts:
I've created an email sender with providers for the email content, that will be changed based on the email type. I need some help to enhance it.
These two models are used to send
public class EmailAddress
{
    public string Name { get; set; }
    public string Address { get; set; }
}

public class EmailMessage
{
    public EmailMessage()
    {
        ToAddresses = new List<EmailAddress>();
        CcAddresses = new List<EmailAddress>();
    }

    public List<EmailAddress> ToAddresses { get; set; }
    public List<EmailAddress> CcAddresses { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}

The content provider provides all the email information(subject, body, To and Cc)
public interface IEmailContentProvider
{
    EmailMessage Message { get; }
}

Then we have the abstracted email sender IEmailSender that has a single method Send which uses IEmailContentProvider parameter to get the email information
interface IEmailSender
    {
        Task Send(IEmailContentProvider provider);
    }

I have an example for the content provider WelcomEmailProvider
public class WelcomEmailProvider : IEmailProvider
{
        public EmailMessage Message { get; }

        public WelcomEmailProvider(string address, string name)
        {
            Message = new EmailMessage
        {
            Subject = $"Welcome {name}",
            Content = $"This is welcome email provider!",
            ToAddresses = new List<EmailAddress> { new EmailAddress { Address = address, Name = name} }
        };
    }
}

The IEmailSender implementation:
public class EmailSender : IEmailSender
{
    private readonly SmtpOptions _options;

    public EmailSender(IOptions<SmtpOptions> options)
    {
        _options = options.Value;
    }

    public async Task Send(IEmailContentProvider provider)
    {
        var emailMessage = provider.Message;
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(_options.Sender.Name, _options.Sender.Address));
        message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
        message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));

        message.Subject = emailMessage.Subject;
        message.Body = new TextPart(TextFormat.Html) { Text = emailMessage.Content };

        using var emailClient = new SmtpClient();
        await emailClient.ConnectAsync(_options.Server, _options.Port, _options.EnableSsl);
        await AuthenticatedData(emailClient);

        await emailClient.SendAsync(message);
        await emailClient.DisconnectAsync(true);

    }

    private async Task AuthenticatedData(SmtpClient smtpClient)
    {
        if (string.IsNullOrWhiteSpace(_options.Username) || string.IsNullOrWhiteSpace(_options.Password))
            return;

        emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
        await emailClient.AuthenticateAsync(_options.Username, _options.Password);
    }
}

And here is, how to use it and send an email:
class Sample
{
    private readonly IEmailSender _emailSender;
    public Samole(IEmailSender emailSender)
    {
        _emailSender = emailSender;
    }

    public async Task DoSomethingThenSendEmail()
    {
        await _emailSender.Send(new WelcomEmailProvider("someone@example.com", "Someone"));
    }
}


texts: Saving a sales order - too many repositories?

texts:
I am wondering if I have overdone it with repositories in the following code, which is to save a sales order.

I understand that the purpose of a repository is to decouple the domain layer from the persistence layer, but this code seems to be replicating what EF does anyway.

public SalesOrder FindSalesOrder(int id)
{
    using (var uow = new UnitOfWork<LogContext>())
    {
        using (var repository = new SalesOrderRepository(uow))
        {
            var SalesOrder = repository.Find(s => s.Id == id, s => s.Site, s => s.User);
            if (SalesOrder != null)
            {
                using (var repository2 = new OrderLineRepository(uow))
                {
                    var OrderLines = repository2.GetList(o => o.SalesOrderId == id);
                    foreach (var OrderLine in OrderLines)
                    {
                        OrderLine.SalesOrder = SalesOrder;
                        SalesOrder.OrderLines.Add(OrderLine);

                        using (var repository3 = new LineDetailRepository(uow))
                        {
                            var LineDetails = repository3.GetList(v => v.OrderLineId == OrderLine.Id, v => v.PropertyName);
                            foreach(var LineDetail in LineDetails)
                            {
                                LineDetail.OrderLine = OrderLine;
                                OrderLine.LineDetails.Add(LineDetail);
                            }
                        }
                    }
                }
            }

            return SalesOrder;
        }
    }
}

[Update]
I had a chat to my co-developer and think that perhaps the code is OK.

Our reasoning is that EF itself is rather complicated so we want to have a wrapper around what we allow the UI layer to use.

We did realize that we don't need the lineDetail repository as there are no instances where we need to access the lineDetails separate from the orderLines. That means we could make the orderLines return containing the lineDetails pre-populated.

However that would then mean some of our repository's Find methods return entities with children and some don't.  Thus I am thinking maybe we need a FindGraph method in our repositories which will return the full graph.

However now I wonder whether the FindSalesOrder method should be in the SalesOrder repository itself instead of the UI layer?


texts: Abstract factory pattern for implementing AdNetworks on multiple platforms

texts:
Here's the link to the github project.

I want to implement abstract factory instead of adding platform-dependent compilation flags in just one file and make it ugly, hence decoupled code. Moreover, I have to implement different AdNetworks on different platforms.

This is the interface:

public interface IAds
{
    void ShowVideoAd();
    void PreLoadVideoAd();
    bool IsAdAvailable();

}

And all the PlatformAdController (Android, IOS, Amazon, Windows) will implement this interface:

    public class AmazonAdsController : IAds
    {
// Code Goes here
    }

Then in someFactoryClass I'll do:

public IAds GetObject()
{
    #if UNITY_Android
    if(platform == Amazon)
    return new AmazonAdsController
    else
    return new AndroidAdsController
    #elif UNITY_IOS
    return new IOSAdsController
    #elif UNITY_WP10
    return new WindowsAdsController
}

This method will be called from AdManager a singleton MonoBehaviour. My current AdManager state is:

namespace MS.Ads
{
    [RequireComponent(typeof(KeyGenerator))]
    public class AdManager : MonoBehaviour
    {
        #region Fields & Properties
        [SerializeField]
        private KeysSource _keysSource;
        [SerializeField]
        [HideInInspector]
        private string _fileName;
        [SerializeField]
        [HideInInspector]
        private string _url;

        // Source from where to get keys
        public KeysSource Source
        {
            get { return _keysSource; }
            set { _keysSource = value; }
        }

        // Web URL from where to get AdKeys
        public string URL
        {
            get { return _url; }
            set { _url = value; }
        }

        // FileName from where to get Adkeys e.g adc.json
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }

        // To be replaced by a FactoryObject.
        private FyberController _fyberController;
        #endregion

        #region Message Methods
        void Start()
        {
            GetComponent<KeyGenerator>().GenerateKeys(Source, URL, FileName);
            _fyberController = new FyberController();
            _fyberController.RequestVideoAd();
        }
        #endregion

        #region Methods
        public void ShowAd()
        {
            if (_fyberController.IsVideoAdAvailable)
                _fyberController.ShowVideoAd();
        }

        public bool IsVideoAdAvailable()
        {
            return _fyberController.IsVideoAdAvailable ? true : false;
        }
        #endregion
    }
}

What I would like to know:

Is factory pattern the right choice here?
If yes, should I go with an interface or an abstract base class or a base class with virtual methods?


texts: Refactoring a LINQ query that (sometimes) returns null

texts:
I have the following LINQ query that should return a result for each Request. I'd prefer to have the query translated to SQL by EntityFramework.

private static Expression<Func<Request, RequestResultModel>> requestResultExpression = request =>
    request.Applicant
            .ApplicantAddresses
            .OrderBy(address => address.IsPreferred)
            .Select(address => new RequestResultModel
            {
                Id = request.Id,
                ApplicantName = request.Applicant.FullName,
                ReviewerName = request.Reviewer.FullName,
                RefferrerName = request.Refferrer.Name,
                City = address.Address.City,
                Province = address.Address.Province.Code,
                DisciplineCode = request.Discipline.Code,
                Event = request.Event,
                StatusName = request.Status.Name,
                Submitted = request.Submitted
            })
            .FirstOrDefault();

The problem is that when the Applicant has no ApplicantAddresses, then the expression returns null for that specific Request. The correct behavior should be that a RequestResultModel should still be returned but with empty address information.

Unfortunately, I can only think of doing this in two steps like this:

private static Expression<Func<Request, RequestResultModel>> requestResultExpression = request =>
{
    var address = request.Applicant
                         .ApplicantAddresses
                         .OrderBy(address => address.IsPreferred)
                         .FirstOrDefault();

    return new RequestResultModel
            {
                Id = request.Id,
                ApplicantName = request.Applicant.FullName,
                ReviewerName = request.Reviewer.FullName,
                RefferrerName = request.Refferrer.Name,
                City = address == null ? null : address.Address.City,
                Province = address == null ? null : address.Address.Province.Code,
                DisciplineCode = request.Discipline.Code,
                Event = request.Event,
                StatusName = request.Status.Name,
                Submitted = request.Submitted
            };
});

Which has he following drawbacks:

It will not be translated to SQL by EntityFramework
It will be executed as multiple queries to the database

Any ideas how I can achieve the desired result?

All assistance will be greatly appreciated.

EDIT: Here is the Request class

public class Request
{
    [Key]
    public int Id { get; set; }

    public virtual Applicant Applicant { get; set; }

    public virtual Reviewer Reviewer { get; set; }

    public virtual Refferrer Refferrer { get; set; }

    [Required]
    public virtual Department Department { get; set; }

    [Required]
    public virtual Discipline Discipline {get; set; }

    [Required]
    public string Event { get; set; }

    public virtual Status Status { get; set; }

    public DateTime Submitted { get; set; }
}


texts:
How do you guys think I can improve the code for collision detection on my website asteroidfield.eu5.org? The current code is

var dx = Math.abs(c1.getcx() - c2.getcx());
var dy = Math.abs(c1.getcy() - c2.getcy());
var dist = Math.sqrt((dx * dx) + (dy * dy));
if (dist - (c1.getR() + c2.getR()) <= 0) {
  if (done === false && invinc !== true) {
    game_over = true;
    done = true;
  }
}

C1 refers to the player sprite, and C2 is the enemy sprite. Getcx is essentially collecting the X location of the edge of what is essentially a collision detection circle, and gety does the same, but collects the Y location. GetR returns the radius of the collision detection circle.


texts: IEnumerable extension method that ingests SqlCommand and returns query results

texts:
The following ingests a preexisting SqlCommand and returns the values.

A couple caveats right now.

1 ) Type properties must be named identical to the SQL column

2) properties must be given a custom [SQLColumn] attribute.

The attribute contains a string which I plan to use later for variation in property names while keeping column designation.

    public static IEnumerable<T> FromCommand<T>(this IEnumerable<T> b, SqlCommand command)
    {

        using (command.Connection)
        {

            command.Connection.Open();

            using (var reader = command.ExecuteReader())
            {

                var readerColumns = new HashSet<string>(Enumerable.Range(0, reader.FieldCount).Select(reader.GetName));
                var properties = typeof(T).GetProperties().Where(o => o.IsDefined(typeof(SQLColumn)) && readerColumns.Contains(o.Name)).ToList();

                while (reader.Read())
                {

                    object OUTPUT = Activator.CreateInstance(typeof(T));

                    foreach (var item in properties)
                    {
                        item.SetValue(OUTPUT, reader[item.Name] is DBNull ? null : reader[item.Name]);
                    }

                    yield return (T)Convert.ChangeType(OUTPUT, typeof(T));
                }
            }
        }
    }

As requested, here is an example of the class utilizing the extension method.

public class MyType
{

    #region Properties Block

    [SQLColumn]
    public Guid GuidColumn { get; set; }

    [SQLColumn]
    public int IntColumn { get; set; }

    [SQLColumn]
    public bool BitColumn { get; set; }

    #endregion Properties Block

    #region Select Block

    [Description("Selects and returns all rows.")]
    public static IEnumerable<MyType> SelectAll()
    {

        SqlCommand command = new SqlCommand(QueryRepository.SELECT_MyType_ALL, Conn.ConnectionString) { CommandTimeout = 0 };

        return new List<MyType>().FromCommand(command);

    }

    [Description("Selects and returns rows filtered by GuidColumn.")]
    public static IEnumerable<MyType> SelectFiltered(Guid GuidColumn)
    {

        SqlCommand command = new SqlCommand(QueryRepository.SELECT_MyType_GuidColumn, Conn.ConnectionString) { CommandTimeout = 0 };

        command.Parameters.Add("@GuidColumn", SqlDbType.UniqueIdentifier).Value = GuidColumn;

        return new List<MyType>().FromCommand(command);

    }

    #endregion Select Block

}


texts:
I used the following to split sequence into batches:

source
    .Select((item, index) => new {Item = item, Index = index})
    .ToLookup(x => x.Index / batchSize, x => x.Item);

but it requires full materialization of the sequence - memory complexity could be high.

Are there anything ready to be used? I think there is nothing in MoreLinq for that.

Here is a custom solution I am trying now:

public static class Batch
{
    public static IEnumerable<T[]> Split<T>(this IEnumerable<T> source, int batchSize)
    {
        var it = source.GetEnumerator();
        for (var b = split(); b.Length > 0; b = split())
            yield return b;

        T[] split() => Enumerable
            .Range(0, batchSize)
            .TakeWhile(i => it.MoveNext())
            .Select(i => it.Current)
            .ToArray();
    }
}


texts:
Any suggestions on how to shorten this would be greatly appreciated. This code takes three parameters through the URL and displays a page with targeted ads. I especially need help on how to cut down the three sections where I replace %20 with spaces. Also, here is the URL with sample parameters - http://timtechsoftware.com/ad.html?file_url=URL?file_name=FILE?keyword=KEY

This is the code of ad.html:

<!DOCTYPE html>

<title>Download File</title>


texts: Between dates : from highest -> current -> lowest

texts:
For example I have 2 dates (year and month) like :

2013-03

2013-01 <-- Jan. current month.

2012-10

So my code is :

// Get current month and year
$m = date('m');
$y = date('Y');

// So I do something to get highest date so result is..
$highest = "2013-03";

// Current month and year
$current = $y."-".$m;

// So I do something to get lowest date so result is..
$lowest = "2012-10";

// My idea is get lower month from variables

function do_lower($date){
    $date = explode("-",$date);
    $y = $date[0];
    $m = $date[1];

    if($m != "01") {
        $m = $m-1;
        $m = sprintf('%02d',$m);
        return $y."-".$m;
    } else {
       return ($y-1)."-12";
    }

}

// This is my simple function to get result between high and low

function different($h,$l) {
    global $data;
    $h = do_lower($h);
    if($h!=$l){
        $data[] = $h;
        different($h,$l);
    }
}

Then .. to do all functions like.. (JSON)

$data[] = $highest;
different($highest,$current);
$data[] = $current;
different($current,$lowest);
$data[] = $lowest;

So my result is correct

["2013-03","2013-02","2013-01","2012-12","2012-11","2012-10"]

Anyone can review my code ?

Thanks so much


texts: Improving performance while sorting a JavaScript Object

texts:
I am sorting an array (filtered) containing JS-Objects by their attribute sortdist:

filtered.sort(function (a, b) {
  if (!a.sortdist) { return 1;}
  else if (!b.sortdist) { return -1;}
  else if (a.sortdist > b.sortdist) { return 1;}
  else { return -1; }
});

However, I am sorting 9000 datasets, which takes a really long time. Is there any way to improve the performance of my sorting algorithm?