texts:
The assignment is to mask (or rather unmask) certain indexes from a string. Both the input string and the demasker are strings. An example shows how it's supposed to work.

  Input: "abcdefgh"
  Mask: "2-4,6"
  Output: "bcdf"

The index is one-based and we need not to worry about malicious users' entries. The entries are always separated by a comma and the limits (if not atomary) by a dash.

My current solution is this.

string input = "abcdefghijklmnopqrstuvwxyz";
string mask = "3-5,8,9-12,13,14,18-26";

Dictionary<int, int> intervals = mask.Split(',').ToDictionary(
  element => Convert.ToInt32(element.Split('-').First()),
  element => Convert.ToInt32(element.Split('-').Last()));
string substring = "";
foreach (KeyValuePair<int, int> entry in intervals)
  substring += input.Substring(entry.Key - 1, entry.Value - entry.Key + 1);

I'm unhappy with the way it looks right now, because I'd like it to be demasking using other method than foreach. Given that the strings are relatively short, there's no option of deploying a third party library.

Can the above be made smoother? All creative critique is welcome.


texts: Splitting C string without modifying input

texts:
I wrote this after using strtok_r and needing something similar that can copy the input string and handle multiple characters in the delimiter. Its functionally similar to Python's str.split(), as it keeps empty spaces without trimming.

tokens.h

#ifndef TOKENS_H
#define TOKENS_H

#include <string.h>

struct Tokens {
    char **array;
    size_t count;
};

extern struct Tokens *string_split(const char *input,
                                   const char *delim,
                                   const int count);

extern void tokens_free(struct Tokens *tokens);

#endif

tokens.c

#include "tokens.h"

#include <stdbool.h>
#include <stdlib.h>

static bool tokens_add(struct Tokens *tokens, const char *token){
    tokens->array = realloc(tokens->array,
                            ++tokens->count * sizeof(char *));

    if (!tokens->array){
        tokens->count--;

        return false;
    }

    char *dupstr = strdup(token);

    if (!dupstr){
        tokens->count--;

        return false;
    }

    tokens->array[tokens->count - 1] = dupstr;

    return true;
}

struct Tokens *string_split(const char *input,
                            const char *delim,
                            const int count){

    struct Tokens *tokens = malloc(sizeof(struct Tokens));

    if (!tokens){
        return NULL;
    }

    tokens->count = 0;
    tokens->array = NULL;

    const size_t inputlen = strlen(input);
    const size_t delimlen = strlen(delim);

    if (count == 0 || delimlen == 0){
        tokens_add(tokens, input);

        return tokens;
    }

    int delimcount = 0;
    size_t inputpos = 0;
    const char *start = NULL;

    while ((start = strstr(&input[inputpos], delim))){
        const int delimpos = (start - &input[inputpos]);
        char token[delimpos + 1];

        memcpy(token, &input[inputpos], delimpos);
        token[delimpos] = '\0';

        if (!tokens_add(tokens, token)){
            return NULL;
        }

        inputpos += (delimpos + delimlen);

        if (delimcount++ == count){
            break;
        }
    }

    if (inputpos <= inputlen){
        const int charcount = (inputlen - inputpos);
        char token[charcount + 1];

        memcpy(token, &input[inputpos], charcount);
        token[charcount] = '\0';

        if (!tokens_add(tokens, token)){
            return NULL;
        }
    }

    return tokens;
}

void tokens_free(struct Tokens *tokens){
    if (!tokens){
        return;
    }

    for (size_t index = 0; index < tokens->count; index++){
        free(tokens->array[index]);
    }

    free(tokens);
}

test.c

#include <stdio.h>

#include "tokens.h"

int main(void){
    // <0 = split indefinitely
    struct Tokens *tokens = string_split("Hello;world;!;", ";", -1);

    if (tokens){
        for (size_t index = 0; index < tokens->count; index++){
            printf("%s\n", tokens->array[index]);
        }

        tokens_free(tokens);
    }
}


texts:
For my project, I need to convert dollar to cents, so I wrote the following function to safely do the conversion. The input dollar is float and the output should be int.

def safe_dollar_to_cent(dollar):
    parts = str(dollar).split('.')

    msg = 'success'
    status = 0
    if len(parts) == 1:
        return status, int(parts[0])*100, msg

    decimal_part = parts[1]
    if len(decimal_part) > 2:
        decimal_part = decimal_part[0:2]
        msg = 'dollar has been truncated: {} -> {}'.\
              format(parts[1], decimal_part)
        status = 1

    ret = int(parts[0]) * 100
    multiplier = 10
    for i, s in enumerate(decimal_part):
        ret += int(s) * multiplier
        multiplier /= 10

    return status, ret, msg

I am posting here for seeking other some pythonic way of doing this job.

Update:

my input is expected to be float, the return value should be int.
The reason of this implementation is that I found the following incorrect computation.

18.90 * 100 = 1889.9999999999998


texts:
Logic based of this site which had a VB example I used as a base.

function Get-LevenshteinDistance{
    [cmdletbinding()]
    param(
        [string]$CompareString,
        [string]$DifferenceString
    )

    # Collect the string lengths
    $compareStringLength = $CompareString.Length
    $differenceStringLength = $DifferenceString.Length
    Write-Verbose "Comparision String: '$CompareString' with length '$compareStringLength'"
    Write-Verbose "Difference String: '$DifferenceString' with length '$differenceStringLength'"

    # If either of the strings are empty the LD is known and we can stop
    if($compareStringLength -eq 0){return $differenceStringLength}
    if($differenceStringLength -eq 0){return $compareStringLength}

    # Build the comparison matrix and populate the first column and first row.
    $comparisonMatrix = New-Object 'object[,]'  ($differenceStringLength+1),($compareStringLength+1)

    # Populate the first row
    for($index=0; $index -le $compareStringLength; $index++){
        $comparisonMatrix[0,$index]=$index
    }

    # Populate the first column
    for($index=0; $index -le $differenceStringLength; $index++){
        $comparisonMatrix[$index,0]=$index
    }

    # Calculate the Levenshtein distance by working through each position in the matrix.
    # Working the columns
    for($columnIndex=1; $columnIndex -le $compareStringLength; $columnIndex++){
        # Cycle each character in the list
        $compareCharacter = $compareString[$columnIndex-1]

        # Working the rows
        for($rowIndex=1; $rowIndex -le $differenceStringLength; $rowIndex++){
            # Cycle each character in the list
            $differenceCharacter = $differenceString[$rowIndex-1]

            Write-Verbose "Matrix location: [$rowIndex, $columnIndex]"
            Write-Verbose "Compare character: $compareCharacter - Difference character: $differenceCharacter"
            # Calculate the cost
            $cost=if($compareCharacter -eq $differenceCharacter){0}else{1}
            Write-Verbose "Cost: $cost"

            # The cell immediately above plus 1
            $cellAbove = $comparisonMatrix[($rowIndex-1), $columnIndex] + 1
            Write-Verbose "Cell Above: [$($rowIndex-1), $columnIndex] + 1 = $cellAbove"

            # The cell immediately to the left plus 1
            $cellLeft =  $comparisonMatrix[$rowIndex,($columnIndex-1)] + 1
            Write-Verbose "Cell Left: [$rowIndex,$($columnIndex-1)] + 1 = $cellLeft"

            # The cell diagonally above and to the left plus the cost
            $cellUpperLeft = $comparisonMatrix[($rowIndex-1),($columnIndex-1)] + $cost
            Write-Verbose "Cell Upper Left: [$($rowIndex-1),$($columnIndex-1)] + cost($cost) = $cellUpperLeft"

            # Select minumum of the of the last 3 cells calculations and assign it to the current matrix position.
            $comparisonMatrix[$rowIndex,$columnIndex] = $cellAbove,$cellLeft,$cellUpperLeft | Measure-Object -Minimum | select -ExpandProperty Minimum
        }
    }
    # The cacluated LD will now be in the bottom right of the matrix.
    return $comparisonMatrix[$differenceStringLength,$compareStringLength]
}

Was working on a PPCG question where I had to roll my own LD calculator. Since I saw future value in this I made a more professional looking version. Since it is iterating over every character in a string for every other character in the other string it really starts to show its performance issues when they start to get over 50 chars in size.

The model it uses supports deletions, insertions and substitutions. If I wanted to change the weight of substitutions I suppose I would need to edit this line and support a parameter for it?

$cost=if($compareCharacter -eq $differenceCharacter){0}else{1}

Never really played with multidimensional arrays before and I am not sure how I could improve on this. I know there are a few things I could do to make the code more brief and still functional however I opted for this solution as I liked the improved readability.


texts: Reading large text file from network (SMB)

texts:
I am facing performance issues while reading a large text file from the network. The same file is read locally without any performance problems:

int file_no_lines(char *file_path)
{
    FILE *fp = NULL;
    char line_read[200];
    int linecount = 0;
    fp = fopen(file_path, "r");
    while(1)
    {
     if (fgets(line_read, 160 ,fp) == NULL)
     {
        if(feof(fp))
        {
           fclose(fp);
           return linecount;
        }
        else
        {
            printf("Bad File Termination");
            fclose(fp);
            return -1 ;
        }
     }
     else
     {
        linecount++;
     }
    }
    fclose(fp);
    return linecount;
}
int file_read_lines(char *file_path)
{
    FILE *fp = NULL;
    char line_read[200];
    fp = fopen(file_path, "r");
    while(1)
    {
     if (fgets(line_read, 160 ,fp) == NULL)
     {
        if(feof(fp))
        {
           fclose(fp);
           return -1;
        }
        else
        {
            printf("Bad File Termination");
            fclose(fp);
            return -1 ;
        }
     }
     else
     {
        //update structure
     }
    }
    fclose(fp);
    return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{

    int no_lines = file_no_lines("C:/sample.txt"); //count no. of lines
    //allocate structure for no. of lines
    file_read_lines("C:/sample.txt"); // fill allocated array
    return 0;
}

Steps:

Count the no. of valid lines using file_no_lines
Allocate for no. of lines
Update structure, file_read_lines


texts: Generating longest palindrome by switching only k digits

texts:
//This program generates a maximum possible palindrome from of a string num 's', of length 'n', by switching only 'k' digits.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n=scan.nextInt();
        int k=scan.nextInt();
        String s=scan.nextLine();
        s=scan.nextLine();

        int ar[]=new int[n];
        int i=0;
        for(i=0;i<n;i++) //Forming an array to store the numbers.
            ar[i]=s.charAt(i)-48;

        int k2=count(ar,n); //counts the numbers to be switched.

        if(k2>k) //if numbers to be switched are more than 'k', then palindrome will not form.
            System.out.print(-1);

        else {
            int x=0,y=n-1;

            while(k>k2 && (x<y)) { //if the given limit 'k' is more than normal exchanges, then swap adjacent numbers by 9, to get maximum palindrome
                if(ar[x]!=ar[y]) {
                    ar[x]=9;
                    ar[y]=9;
                    x++;
                    y--;
                    k-=2; //since two changes have been made.
                }
            }

            while(k>0 && (x<y)) { //now just changing one number with the adjacent, by the greater of the two.
                if(ar[x]!=ar[y]) {
                    ar[x]=Math.max(ar[x], ar[y]);
                    ar[y]=ar[x];
                    k--;
                }
                x++;
                y--;
            }

            if(k>0 && n%2!=0) //Now if all possible switches are done, and still allowed 'k' is left, then change the middle digit by 9, to get maximum number.
                ar[x]=9;

            for(i=0;i<ar.length;i++) //printing the number.
                System.out.print(ar[i]);
        }
        scan.close();
    }

    static int count(int x[],int n) { //calculates the count of necessary switches.
        int t1=0,t2=n-1,c=0;
        while(t1<t2) {
            if(x[t1]!=x[t2])
                c++;
            t1++;
            t2--;
        }
        return c;
    }
}

Whenever an Online judge checks it, 20/32 I get Terminated due to Timeout. I have tried every possible thing I know. I guess its time to learn something new...


texts:
I put together this little memory pool class to help avoid the costs associated with heap allocation and deallocation of objects that are frequently created & destroyed. It creates C++ standard shared_ptrs with custom deleters that return the pointed-to object to the memory pool where it can be recycled. Right now it uses the moodycamel queue to manage the pool, but it could be rewritten to use a simple vector or stack instead.

I'd appreciate any comments on design / implementation.

#ifndef SHAREDPTRMEMORYPOOL_H
#define SHAREDPTRMEMORYPOOL_H

#include <memory>
#include <3rdParty/spsc_queue/readerwriterqueue.h>

// Objects to be managed must have a default constructor
// and a reconstruct(...) function which serves to initialize
// their state (like a constructor)
//
// Use like:
// auto obj = make_shared_ptr_from_pool(my_memory_pool, my_reconstruct_args, ...);

template<class TPointedToClass>
class SharedPtrMemoryPool {
 public:
  explicit SharedPtrMemoryPool(unsigned int num_to_prealloc);
  ~SharedPtrMemoryPool();

  std::shared_ptr<TPointedToClass> get_shared_ptr();
  void release_shared_ptr(TPointedToClass* to_release);

 private:
  moodycamel::ReaderWriterQueue<TPointedToClass*> _pointer_queue;
};

template<class TPointedToClass>
SharedPtrMemoryPool<TPointedToClass>::SharedPtrMemoryPool(unsigned int num_to_prealloc) {
  for(unsigned int i = 0; i < num_to_prealloc; ++i) {
    auto prealloc_item = new TPointedToClass();
    _pointer_queue.enqueue(prealloc_item);
  }
}

template<class TPointedToClass>
SharedPtrMemoryPool<TPointedToClass>::~SharedPtrMemoryPool() {
  TPointedToClass* raw_ptr;
  while(_pointer_queue.try_dequeue(raw_ptr)) {
    delete raw_ptr;
  }
}

template<class TPointedToClass>
std::shared_ptr<TPointedToClass> SharedPtrMemoryPool<TPointedToClass>::get_shared_ptr() {
  TPointedToClass* raw_retval;
  bool recycle_success = _pointer_queue.try_dequeue(raw_retval);
  if(!recycle_success) {
    raw_retval = new TPointedToClass();
  }

  return std::shared_ptr<TPointedToClass>(raw_retval, [this](TPointedToClass* to_release) {
    this->release_shared_ptr(to_release);
  });
}

template<class TPointedToClass>
void SharedPtrMemoryPool<TPointedToClass>::release_shared_ptr(TPointedToClass* to_release) {
  _pointer_queue.enqueue(to_release);
}

template<class TPointedToClass, class... Args>
std::shared_ptr<TPointedToClass> make_shared_ptr_from_pool(SharedPtrMemoryPool<TPointedToClass>& pool, Args&&... args) {
  std::shared_ptr<TPointedToClass> retval = pool.get_shared_ptr();
  retval->reconstruct(std::forward<Args>(args)...);
  return retval;
}

#endif


texts: Form every unique combination of the items of a list of lists

texts:
I've tried looking some stuff up. I thought it was transposition first, but looking at this, that's not exactly it.

I hacked this code together in about 3 hours, stopping frequently due to frustration and I'm pretty sure there's some bad practices in there, I'm just too glad right now I actually got it to work. If anyone could point out a better way of doing this, or a part of it, that would be appreciated.

The idea is you have a variable amount of lists with each a variable amount of items. For instance, lists of String, which I used in my code, which can look like this:

List1["a","b","c"]
List2["d"]
List3["e","f"]

And the result would be:

List1["a","d","e"]
List2["a","d","f"]
List3["b","d","e"]
List4["b","d","f"]
List5["c","d","e"]
List6["c","d","f"]

I left in the sysout statements in case somebody wants to execute it and follow what's happening.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.common.collect.Lists;

public class Main {

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a");
        list1.add("b");
        list1.add("c");

        List<String> list2 = new ArrayList<String>();
        list2.add("d");

        List<String> list3 = new ArrayList<String>();
        list3.add("e");
        list3.add("f");

        List<List<String>> group = Lists.newArrayList(list1,list2,list3);
        System.out.println(Arrays.toString(group.toArray()));

        List<List<String>> end = makeList(group);

        System.out.println(Arrays.toString(end.toArray()));
    }

    /**
     * Take the original list and output all unique combinations.
     * This method is called recursively.
     */
    private static List<List<String>> makeList(List<List<String>> group) {
        if (group.size() == 1) {
            return splitToSingleItemsLists(group.get(0));
        } else {
            List<List<String>> subList = makeList(group.subList(1, group.size()));
            System.out.println(Arrays.toString(subList.toArray()));
            System.out.println(Arrays.toString(group.toArray()));
            System.out.println("=====");
            List<List<String>> tmpList = Lists.newArrayList();

            List<List<String>> splitToSingleItemsLists = splitToSingleItemsLists(group.get(0));
            System.out.println(Arrays.toString(splitToSingleItemsLists.toArray()));
            System.out.println("----");

            List<String> result = new ArrayList<String>();
            for (List<String> string : subList) {
                result = new ArrayList<String>();
                result.addAll(string);
                for (List<String> tmp : splitToSingleItemsLists) {
                    List<String> result2 = new ArrayList<>();
                    result2.addAll(result);
                    for (String tmp2 : tmp) {
                        result2.add(tmp2);

                        tmpList.add(result2);
                    }
                }
            }

            return tmpList;
        }
    }

    /**
     * Split a list of strings to a list of lists with 1 item of the original list each time.
     */
    private static List<List<String>> splitToSingleItemsLists(List<String> list) {
        List<List<String>> result = Lists.newArrayList();

        for (String str : list) {
            List<String> tmp = new ArrayList<String>();
            tmp.add(str);
            result.add(tmp);
        }

        return result;
    }
}


texts: Read through a log file to find serial numbers based upon prior information found

texts:
This class takes a log file name(which must be of a specific format/order) and returns a list of serial numbers of those drives which contain particular type of error. It uses regular expressions to process the file line by line and all but one of the regular expressions searches using patterns shaped by previous matches.

I have little experience in object orientated programming and would like to better understand how I might structure code to achieve the below task. In particular, I'm unsure about my methods calling each other in sequence as they do.

import re

class SerialNumberFinder:
    """Finds serial numbers of drives with a corrupt filesytem (XFS ERROR)"""

    def __init__(self, filename):
        self.serial_numbers = []
        self.result = None
        self.match = None
        try:
            with open(filename) as f:
                # reverse order of lines otherwise serial number information
                # for a drive is processed before error type is identified
                self.lines = reversed(f.readlines())
        except FileNotFoundError:
            print("Cannot find file {}".format(self.filename))

    def get_next_line(self):
        """Return next line from self.lines if lines, otherwise return None"""
        try:
            line = next(self.lines)
        except StopIteration:
            return None
        else:
            return line

    def get_serial_numbers(self):
        """Return a list of serial numbers"""
        self.find_error()
        return self.serial_numbers

    def find_error(self):
        """Use a regex to find mention of a specific type of error in a line"""
        while not self.match:
            line = self.get_next_line()
            if not line:
                return
            self.match = re.match("XFS ERROR (\[sd[a-z]\])", line)
        self.result = self.match.groups()[0]
        self.match = None
        self.find_bus()

    def find_bus(self):
        """Find mention of bus using identifier from find_error"""
        while not self.match:
            line = self.get_next_line()
            if not line:
                return
            self.match = re.match("(sd \S+) {}.*".format(re.escape
                                                         (self.result)), line)
        self.result = self.match.groups()[0]
        self.match = None
        self.find_serial()

    def find_serial(self):
        """Find a serial number using identifier from find_bus"""
        while not self.match:
            line = self.get_next_line()
            if not line:
                return
            self.match = re.match("{} \(SERIAL=([^)]*)\)".format(self.result),
                                  line)
        self.serial_numbers.append(self.match.groups()[0])
        self.match = None
        self.find_error()

if __name__ == "__main__":
    s = SerialNumberFinder("EXAMPLE_LOG.log")
    nums = s.get_serial_numbers()
    print(nums)

Output:

['WW11111', 'ZZ12345']

Example log file:

unrelated log messages
sd 0:0:0:0 Attached Disk Drive
unrelated log messages
sd 0:0:0:0 (SERIAL=ZZ12345)
unrelated log messages
sd 0:0:0:0 [sda] Options
unrelated log messages
XFS ERROR [sda]
unrelated log messages
sd 2:0:0:1 Attached Disk Drive
unrelated log messages
sd 2:0:0:1 (SERIAL=ZZ67890)
unrelated log messages
sd 2:0:0:1 [sdb] Options
unrelated log messages
sd 3:0:1:8 Attached Disk Drive
unrelated log messages
sd 3:0:1:8 (SERIAL=WW11111)
unrelated log messages
sd 3:0:1:8 [sdc] Options
unrelated log messages
XFS ERROR [sdc]
unrelated log messages


texts: SVG class with boilerplate prologue and epilogue from files

texts:
I noticed this old class of mine:

class SvgDrawing:

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

        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_start.txt'), mode='r') as f:
            self.svg_start = f.read()

        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_end.txt'), mode='r') as f:
            self.svg_end = f.read()

And I thought I would refactor it like this to avoid re-reading the same file every time an instance is created.

class SvgDrawing:

    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_start.txt'), mode='r') as f:
        svg_start = f.read()

    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_end.txt'), mode='r') as f:
        svg_end = f.read()

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

The new code works and improves the performance, but... something is telling me that there should be a better way.

Is it correct to put code that does something more complex than just assigning constant values in the class definition?


texts: Calculate elapsed time from input times without using conditional statements

texts:
I have just started programming and we are being taught C++. After our 2nd lecture we were given an assignment to make a program that would take two values of time from the user (0 <= hr <= 12 and 0 <= min <= 60)  and return the value of elapsed time.

Since conditionals statements are not introduced yet, I am trying to make the program without one.

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main(void)
{
    clrscr();
    int ih,im,fh,fm,e,a,b;
    cout<<"Enter initial hour:";
    cin>>ih;
    cout<<"Enter initial min:";
    cin>>im;
    cout<<"Enter final hours:";
    cin>>fh;
    cout<<"Enter final min:";
    cin>>fm;
    a=ih*60+im;
    b=fh*60+fm;
    e=abs(((780+a)/(781+b))*720-abs(a-b));
    cout<<"the elasped time is "<<e/60<<":"<<e%60;
    getch();
}

I see several problems with my code. For one my code doesn't look nice and I would like to include hours and time in hr:min format. Furthermore, I think there are exceptions for which my code won't work. How can I sort these problems?


texts:
I'm learning C++, and move semantics and exception safety seem to be a top priority when using the language. I implemented the simplest data structure I could think of.

#ifndef STACK_CPP11_HPP
#define STACK_CPP11_HPP

#include <vector>

namespace stack {

template <typename T>
class Stack {
private:
  std::vector<T> storage;

public:
  Stack() : storage() {}

  Stack(const Stack<T> &other) {
    *this = other;
  }

  Stack(Stack<T> &&other) {
    *this = other;
  }

  ~Stack() {
  }

  Stack<T> &operator=(const Stack<T> &rhs) {
    if (this != &rhs)
      storage = rhs.storage;

    return *this;
  }

  Stack<T> &operator=(Stack<T> &&rhs) {
    if (this != &rhs)
      storage = rhs.storage;

    return *this;
  }

  bool top(T &ret) const noexcept {
    if (storage.empty())
      return false;

    ret = storage.back();
    return true;
  }

  void push(T item) noexcept {
    storage.push_back(std::move(item));
  }

  bool pop() noexcept {
    if (storage.empty())
      return false;

    storage.pop_back();
    return true;
  }
};

} // namespace stack

#endif // STACK_CPP11_HPP

I tested the code, and it uses the move constructor wherever possible.
Here are the tests:

#include <cassert>
#include <string>

#include "stack.hpp"

using namespace stack;

struct Box {
  std::string label;

  Box(std::string l) : label(l) {}

  friend void swap(Box &lhs, Box &rhs) {
    using std::swap;
    swap(lhs.label, rhs.label);
  }

  Box(const Box &other) {
    label = other.label;
  }

  Box(Box &&other) {
    swap(*this, other);
  }

  ~Box() {
  }

  Box &operator=(Box rhs) {
    swap(*this, rhs);
    return *this;
  }
};

int main(void) {
  Stack<int> stack1;

  int ret;
  assert(!stack1.top(ret));

  stack1.push(100);
  assert(stack1.top(ret));
  assert(stack1.pop());
  assert(ret == 100);

  auto stack2 = Stack<Box>();

  Box box("bar");
  assert(!stack2.top(box));

  stack2.push(std::move(Box{"foo"}));
  assert(stack2.top(box));
  assert(stack2.pop());
  assert(box.label == "foo");

  return 0;
}

Is there a way to improve the code with regards to move semantics and having an overall noexcept behavior? Also, since I'm fairly new to C++, is there anything I could improve in general?


texts: Rewriting SQL IN statement with long list of parameters

texts:
These IDs seem like they should be a table as, there are several queries that use the same list of IDs.  The following needs to be refactored.

SELECT SUM(CASE WHEN s.TypeID IN(1,2,3,4,7,8,10) THEN 1 ELSE 0 END) FROM Sales s

The problem is a subquery can't be used in an aggregate function.  I'd like to write it as follows, but it causes an error:

SELECT SUM(CASE WHEN s.TypeID IN(SELECT ID FROM SaleTypes WHERE SaleType.Desc = 'US') THEN 1 ELSE 0 END) FROM Sales s


texts: Find index where left sum equals to right sum

texts:
Given an array, find if there is an index where left sum equals to right sum.

My idea is calculate sum, and scan again to see if there is an index for which left_sum equals to total_value - left_sum. My code needs to scan the array twice. I'm wondering if there are any solutions which only need to scan the array once.

import random
def find_index(nums):
    total_value = sum(nums)
    left_sum = 0
    for i,v in enumerate(nums):
        left_sum += v
        if total_value - left_sum == left_sum:
            return i
    return -1

if __name__ == "__main__":
    nums = []
    for i in range(10):
        nums.append(random.randint(0,5))
    print nums
    print find_index(nums)


texts: Loading images in the background for a table view

texts:
I have fetchData method which fills my imagesArray:

func fetchData(){

    let imageQuery = PFUser.query()
    imageQuery?.whereKey("username", containedIn: namesArray)

    imageQuery!.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            for object in objects! {
                print("\(object["username"] as! String)")

                self.imagesArray.append(object["image"] as! PFFile)
                if self.imagesArray.count == self.namesArray.count {
                    self.tableView.reloadData()
                    print("Names Order: \(self.namesArray)")
                }
            }
        } else {
            print("error: \(error?.localizedDescription)")
        }
    }
}

And I have tableView:cellForRowAtIndexPath method which uses this array to fill the UIImageView instance:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ChatsCell
    cell.nameLabel.text = namesArray[indexPath.row]

    if imagesArray.count == namesArray.count && self.imagesLoaded == false{
        imagesArray[indexPath.row].getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
            if error == nil {
                let image = UIImage(data: imageData!)
                cell.imageView?.image = image
                self.tableView.reloadData()
                self.imagesLoaded = true
            }
        }
    }

    return cell
}

Actually I use if condition for waiting my array imagesArray to be filled by query of another method and I use variable imagesLoaded to prevent infinite call of reloadData method. How can I write this method without if statement?


texts:
So after I finished my fractal generator, I decided that text is ugly, at least compared to pictures, so I made a text-to-picture converter:

require 'chunky_png'
require 'etc'
require 'pathname'

class Array
  def chunk(chunk_size)
    self.each_with_index.with_object(Array.new(size / chunk_size) { [] }) do |(elt, ind), result|
      result[ind / chunk_size] << elt
    end
  end
end

raise ArgumentError, 'Wrong argument number. Run with -h to see usage.' unless ARGV.length % 2 == 1

filename = ARGV.pop

colors = Hash[
    ARGV.chunk(2).map do |(char, color)|
      color = ChunkyPNG::Color.from_hex(color)
      [char, color]
    end
]

text = []
text << $_.chomp.chars until $stdin.gets.nil?
row_length = text[0].length
raise ArgumentError, 'Input cannot be jagged' unless text.all? { |row| row.length == row_length }

image = ChunkyPNG::Image.new(row_length, text.length, ChunkyPNG::Color::WHITE)
text.each.with_index do |row, y|
  row.each_with_index do |char, x|
    raise ArgumentError, "No valid color provided for `#{char}`" if colors[char].nil?
    image[x, y] = colors[char]
  end
end

image.save(filename)

puts "Image saved to #{File.join(Dir.getwd, filename)}"

Note that it uses the ChunkyPNG gem, which I wholeheartedly recommend for any of your pixel-by-pixel image generation needs.

Since this script takes the input data via standard input, it's meant to be used in a command like this:

ruby build_fractal.rb <fractal options> | ruby to_image.rb "X" 000 " " FFF fractal.png

which makes pretties like these.

I'm looking for advice specifically on:

Efficiency: I want to spend as little time as possible drawing the image, so I can spend more time on generating the fractal.

That's it. Since this is purely a utility script that, as far as I can tell, is complete, there's no reason to worry about maintainability or code prettiness. I'm willing to sacrifice everything else to get every last bit of speed out of this.


texts: Vue 3 composition API typescript using ref in Object

texts:
Hi I using Vue 3 with Typescript. In my code I have variable:
const editItem = ref<{
  id: number
  title: string
  author: string
}>({
  id: 0,
  title: '',
  author: '',
})

This variable I update using this method:
const updateItem = (data: {
  id: number
  title: string
  author: string
}) => {
  const { title, author } = data

  getBooks.value = getBooks.value.map(book => ({
    ...book,
    title: editItem.value.id === book.id ? title : book.title,
    author: editItem.value.id === book.id ? author : book.author,
  }))
}

Did this code is correctly by typescript? I readed that I should using reactive instead of ref to object, but reactive value can not be empty


texts: Counting users by the type in their profile

texts:
I'm creating a django web application and I would like to know how to shorten this code.

I have a model where every user has a typeOfPerson (Student, Teacher, Guest ...) and I want to count these types.

@register.simple_tag()
def get_stats_type(choice):
    items = []
    for vote in choice.vote_set.all():
        if vote.user not in items:
            items.append(vote.user)

    types = {}
    for user in items:
        if user.userprofile.typeOfPerson not in types:
            types[user.userprofile.typeOfPerson] = Vote.objects.filter(Choice=choice).count()

    percent = 0
    for type, value in types.items():
        percent += value
    if percent == 0:
        percent = 1

    values = {}
    for type, value in types.items():
        if type not in values:
            values[type] = value / percent * 100

    return values


texts:
I am working on scanned documents (ID card, Driver licenses, ...). The problem I faced while I apply some preprocessing on them is that the documents occupy just a small area of the image, all the rest area is whether white/blank space or noised space. For that reason I wanted to develop a Python code that automatically trims the unwanted area and keeps only the zone where the document is located (without I predefine the resolution). That's possible with using findContours() from OpenCV. However, not all the documents (especially the old ones) have  clear contour and not all the blank space is white, so this will not work.
The idea that came to me is:

Read the image and convert it to gray-scale.

Apply the bitwise_not() function from OpenCV to separate the background from the foreground.

Apply adaptive mean threshold to remove as much possible of noise (and eventually to whiten the background).
At this level, I have the background almost white and the document is in black but containing some white gaps.

I applied erosion to fill the gaps.

Read each row of the image and if 20% of it contains black, then keep it, if it is white, delete it. And do the same with each column of the image.

Crop the image according to the min and max of the index of the black lines and columns.

Here is my code with some comments:
import cv2
import numpy as np

def crop(filename):
    #Read the image
    img = cv2.imread(filename)
    #Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Separate the background from the foreground
    bit = cv2.bitwise_not(gray)
    #Apply adaptive mean thresholding
    amtImage = cv2.adaptiveThreshold(bit, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 35, 15)
    #Apply erosion to fill the gaps
    kernel = np.ones((15,15),np.uint8)
    erosion = cv2.erode(amtImage,kernel,iterations = 2)
    #Take the height and width of the image
    (height, width) = img.shape[0:2]
    #Ignore the limits/extremities of the document (sometimes are black, so they distract the algorithm)
    image = erosion[50:height - 50, 50: width - 50]
    (nheight, nwidth) = image.shape[0:2]
    #Create a list to save the indexes of lines containing more than 20% of black.
    index = []
    for x in range (0, nheight):
        line = []

        for y in range(0, nwidth):
            line2 = []
            if (image[x, y] < 150):
                line.append(image[x, y])
        if (len(line) / nwidth > 0.2):
            index.append(x)
    #Create a list to save the indexes of columns containing more than 15% of black.
    index2 = []
    for a in range(0, nwidth):
        line2 = []
        for b in range(0, nheight):
            if image[b, a] < 150:
                line2.append(image[b, a])
        if (len(line2) / nheight > 0.15):
            index2.append(a)

    #Crop the original image according to the max and min of black lines and columns.
    img = img[min(index):max(index) + min(250, (height - max(index))* 10 // 11) , max(0, min(index2)): max(index2) + min(250, (width - max(index2)) * 10 // 11)]
    #Save the image
    cv2.imwrite('res_' + filename, img)

Here is an example. I used an image from the internet to avoid any confidentiality problem. It is to notice here that the image quality is much better (the white space does not contain noise) than the examples I work on.
Input: 1920x1080

Output: 801x623

I tested this code with different documents, and it works well. The problem is that it takes a lot of time to process a single document (because of the loops and reading each pixel of the image twice: once with lines and the second with columns). I am sure that it is possible to do some modifications to optimize the code and reduce the processing time. But I am very beginner with Python and code optimization.
Maybe using numpy to process the matrix calculations or optimizing the loops would improve the code quality.


texts: How to increase efficiency of matrix operation in C?

texts:
I have a N*N upper triangular matrix with property such that, all its diagonal elements are a1,a2,a3,...,aN. I want that a[i][j] (for all j>i) should be

(a[i][j-1] + a[i+1][j]) / 2.

I have many test cases, and I have to apply this property every time to calculate the answer. What is the most optimal way to do this, so that for all test cases the overall running time is less? Test cases: Inputs are N and a1,a2,...,aN.

To calculate the answer, I need to do:

a[0][0] + a[0][2] + ... + a[0][n-1] + a[2][n-1] + a[4][n-1] + ... + a[n-1][n-1].

My solution (which keeps getting timed out):

#include<stdio.h>
double a[2000][2000];
int main(){
int test;
scanf("%d",&test);
//int arr[2000];
while(test--){
    int n,i,j;
    //scanf("%d",&n);
    scanf("%d",&n);
    for(i=0;i<n;i++){
         int num;
         scanf("%d",&num);
         if(n!=1)
            a[i][i] = num*0.5;
         else
            a[i][i] = num;
     }
    for(j=1;j<n;j++){
         int k=j;
         for(i=0;i<n-j;i++,k++){
             if(i==0 && k==n-1)
                 a[i][k] = (a[i+1][k]+a[i][k-1]);
             else
                 a[i][k] = (a[i+1][k]+a[i][k-1])*0.5;
         }
     }
     float sum=0.0;
     for(i=0;i<n;i+=2){
         if( i != n-1 )
         sum+=a[0][i]+a[n-1-i][n-1];
         else
         sum+=a[0][i];
     }
    printf("%.3f\n",sum);
}
getch();
}

Please provide some hints how to optimize the above code.


texts:
Recently I have written an SslStream class asynchronously authenticate clients and receive message from them. I still would like anyone to suggest improvements for my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IO;

public class Wrapper
{
    public byte[] buffer;
    public SslStream sslStream;
    public object connector;
}

public class Sock
{
    private Dictionary<string, byte> Connections;
    public event Action<Wrapper> AnnounceNewConnection;
    public event Action<Wrapper> AnnounceDisconnection;
    public event Action<byte[], Wrapper> AnnounceReceive;
    private Socket _sock;

    private X509Certificate certificate = X509Certificate.CreateFromCertFile("exportedcertificate.cer");

    public Sock(int port)
    {
        try
        {
            Connections = new Dictionary<string, byte>();
            _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _sock.Bind(new IPEndPoint(IPAddress.Any, port));
            _sock.Listen(500);
            _sock.BeginAccept(AcceptConnections, new Wrapper());
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    private void AcceptConnections(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            wr.sslStream = new SslStream(new NetworkStream(_sock.EndAccept(result), true));
            wr.sslStream.BeginAuthenticateAsServer(certificate, EndAuthenticate, wr);

            _sock.BeginAccept(AcceptConnections, new Wrapper());
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }

    private void EndAuthenticate(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            try { wr.sslStream.EndAuthenticateAsServer(result); }
            catch { }

            if (wr.sslStream.IsAuthenticated)
            {
                AnnounceNewConnection.Invoke(wr);
                if (wr.sslStream.CanRead)
                {
                    wr.buffer = new byte[5];
                    wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
                }
            }
            else
            {
                AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose();
            }
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }

    private void ReceiveData(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            AnnounceReceive.Invoke(wr.buffer, wr);

            SocketError error = SocketError.Disconnecting;
            int size = wr.sslStream.EndRead(result);
            if (error == SocketError.Success && size != 0)
            {
                wr.buffer = new byte[size];
                wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
            }
            else
            {
                wr.sslStream.Close();
                wr.sslStream.Dispose();
                AnnounceDisconnection.Invoke(wr);
            }
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }
}

Also, how can I verify server authentication?


texts: Possible combinations of bills that sum to the given amount

texts:
Question:

  You are given an array that represents bills in certain currency
  (for example 1, 2, 5, 10) and an amount, for example 17. You should output
  the number of possible combinations of bills that sum to the given amount.

Answer:

  {2, 5, 10}

Can I optimize/improve below code? Current complexity is: O(2(n-1)), where n is the bill list length.

//Returns possible Bills List
public static List<Set<Integer>> possibleBills(Integer amount, int[] bills){
    List<Set<Integer>> result = new ArrayList<Set<Integer>>();

    if(amount < 0){
        return null;
    }

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

    if(amount-bills[0] == 0){
        Set<Integer> set = new TreeSet<Integer>();
        set.add(bills[0]);
        result.add(set);
        return result;
    }

    //Include 0'th bill and generate possible bills
    List<Set<Integer>> result1 = possibleBills(amount - bills[0], Arrays.copyOfRange(bills, 1, bills.length));
    if(result1 != null){
        Iterator<Set<Integer>> result1Itr = result1.iterator();
        while(result1Itr.hasNext()){
            Set<Integer> set = result1Itr.next();
            set.add(bills[0]);
        }
        result.addAll(result1);
    }

    //exclude 0'th bill and generate possible bills
    List<Set<Integer>> result2 = possibleBills(amount, Arrays.copyOfRange(bills, 1, bills.length));
    if(result2 != null){
        result.addAll(result2);
    }

    if(result.size() == 0){
        return null;
    }
    return result;
}


texts: implementing simple stream processor with sockets

texts:
I'm trying to implement simple data streamer in Python with sockets. Consider one server and one or more clients. I just want to read data from server, process it and send it to the client. Here's how I do it now:

        outputsocket = socket.socket()
        outputsocket.bind((self.outputaddress, self.outputport))
        outputsocket.listen(2)
        inputsocket = socket.socket()
        rsocks, wsocks = [], []
        rsocks.append(outputsocket)
        rsocks.append(inputsocket)
        recv_data = []

        try:
            inputsocket.connect((self.inputaddress, self.inputport))
            while True:
                try:
                    reads, writes, errs = select.select(rsocks, [], [])
                except:
                    return
                for sock in reads:
                    if sock == outputsocket:
                        client, address = sock.accept()
                        wsocks.append(client)
                    elif sock == inputsocket:
                        data_from_socket = sock.recv(8192)

                if data_from_socket:
                    outdata = process_data(data_from_socket)
                    if wsocks:
                       reads, writes, errs = select.select([], wsocks, [], 0)
                       for sock in writes:
                           sock.send(outdata)
        except KeyboardInterrupt:
            inputsocket.close()
            outputsocket.close()
            # etc

Obviously, it's stripped down example, but I think you got the idea.
Does anyone have better ideas?


texts: Breadth-first search in Java: competitive style

texts:
Here my attempt was to write a graph algorithm the way a competitive programmer would write under time pressure. The problem to solve was to find a shortest path in a directed, unweighted graph using breadth-first search algorithm (BFS, for short).

Basically, I would like to hear comments on my style. Is it effective, for example?

import java.util.Arrays;

class BFS {

    static int[] bfs(int[][] graph, int sourceNode, int targetNode) {
        int[] queue = new int[graph.length];
        int[] distance = new int[graph.length];
        int[] parents = new int[graph.length];

        for (int i = 0; i < parents.length; i++) {
            parents[i] = -1;
        }

        int queueStartIndex = 0;
        int queueEndIndex = 1;

        queue[0] = sourceNode;
        distance[sourceNode] = 0;

        while (queueStartIndex < queueEndIndex) {
            int currentNode = queue[queueStartIndex++];

            if (currentNode == targetNode) {
                return buildPath(targetNode,
                                 distance[targetNode] + 1,
                                 parents);
            }

            for (int childNode : graph[currentNode]) {
                if (parents[childNode] == -1) {
                    parents[childNode] = currentNode;
                    distance[childNode] = distance[currentNode] + 1;
                    queue[queueEndIndex++] = childNode;
                }
            }
        }

        return null;
    }

    private static int[] buildPath(int targetNode,
                                   int pathLength,
                                   int[] parents) {
        int[] path = new int[pathLength];
        int pathIndex = path.length - 1;
        int currentNode = targetNode;

        while (currentNode != -1) {
            path[pathIndex--] = currentNode;
            currentNode = parents[currentNode];
        }

        return path;
    }

    /*    B ----+
         /      |
        A       E
         \      /
          C - D
    */

    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        int c = 2;
        int d = 3;
        int e = 4;

        int[][] graph = new int[5][];
        graph[a] = new int[]{ c, b };
        graph[b] = new int[]{ e };
        graph[c] = new int[]{ d };
        graph[d] = new int[]{ c, e };
        graph[e] = new int[]{ b, d };

        // A -> B -> E
        int[] path = bfs(graph, a, e);
        System.out.println(Arrays.toString(path));

        // A <- B <- E does not exist:
        System.out.println(Arrays.toString(bfs(graph, e, a)));
    }
}

(See the next iteration.)


texts: Printing out a binary tree level by level

texts:
Below is my implementation for an interview question of printing a binary tree level by level. I've also included some methods for creating a binary tree from a vector in my solution.  Please review my solution.

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <type_traits>

template <typename T>
struct Node
{
  T data;
  Node<T>* left;
  Node<T>* right;

  Node (T d, Node<T>* l = nullptr, Node<T>* r = nullptr) : data(d), left(l), right(r) {}
};

template<typename T>
void deleteTree ( Node<T>* n)
{
  if ( !n )
    return;
  deleteTree(n->left);
  deleteTree(n->right);
  delete n;
}

template <typename T>
void printBinaryTree (Node<T>* n )
{
  std::unordered_map<int, std::vector<Node<T>*> > m;
  printBinaryTree (n, m, 0);
  for ( auto& i : m )
  {
    std::cout << " Level " << i.first << ": ";
    for ( auto& j : i.second )
      std::cout << j->data << "  ";
  }
  std::cout << std::endl;
}

// print a binary tree level by level
template <typename T>
void printBinaryTree (Node<T>* n, std::unordered_map<int, std::vector<Node<T>*> >& m, int level )
{
  if (n)
  {
    ++level;
    printBinaryTree ( n->left ,m,level);
    printBinaryTree ( n->right,m,level);

    m[level].push_back(n);
  }
}

template <typename ItType>
auto buildBinaryTree (ItType start, ItType end) -> Node<typename std::iterator_traits<ItType>::value_type>*
{
  using T =typename std::iterator_traits<ItType>::value_type;
  auto first = start;
  auto last = std::prev(end);

  if ( first > last ) // error case
    return nullptr;
  else if ( first < last )
  {
    auto mid = first +  ( last - first ) / 2; // avoid overflow
    Node<T>* n = new Node<T>(*mid);
    n->left = buildBinaryTree ( first, mid);
    n->right = buildBinaryTree ( mid+1, end);
    return n;
  }

  // equal
  return new Node<T>(*first);
}

template <typename T>
Node<T>* buildBinaryTree (std::vector<T>& v)
{
  if  ( v.empty() )
   return nullptr;

  std::sort(v.begin(), v.end());
  return buildBinaryTree (v.begin(), v.end());
}

int main()
{
  std::vector<int> v { 1,2,3,4,5,6,7,8,9,10 };
  Node<int>* root = buildBinaryTree ( v );
  printBinaryTree (root);
  deleteTree(root);
}


texts:
What is Spellathon?

The rules of Spellathon are as follows:

Create words that have 4 to 7 letters.
Include the center letter in every word.
Form at least one 7-letter word.
Plurals are acceptable.
The dictionary used is in English.

Here is a similar implementation.

The dictionary (word list) I'm using is this.

public class Spellathon {

    private static final Set<String> permutations = new HashSet<>();

    private static void permutation(String str) {
        permutation(str.charAt(0), "", str);
    }

    private static void permutation(char idx, String prefix, String str) {
        int n = str.length();

        if (n != 0) {
            for (int i = 0; i < n; i++) {
                permutation(idx, prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
            }
        }

        if(prefix.length() > 3 && prefix.indexOf(idx) >= 0) {
            permutations.add(prefix);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String letters;

        System.out.print("Input: ");
        letters = sc.nextLine();

        permutation(letters);

        try {
            for(String x: permutations) {
                Scanner scFile = new Scanner(new File("words.txt"));

                while(scFile.hasNextLine()) {
                    String cur = scFile.nextLine();
                    if(cur.equalsIgnoreCase(x)) {
                        System.out.println("Found: " + cur);
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Word list file Not Found.");
        }
    }
}

Input: Pass the given letters as a String with the central letter as the first letter. The other letters can be in any order.

Output:

Input: elolh
Found: Hell
Found: hell
Found: Lole
Found: hello
Found: Holle
Found: Hole
Found: hole

I don't mind the redundant occurrences. My issue is that the code takes a lot of time to execute (that is why, I used 5 letters as an example).

Any comments/answers that can help reduce the execution time will be appreciated. Also, if anyone review the overall correctness of the program, it will be helpful.


texts: Refactor/Review JS function which moves a banner on window resize

texts:
Okay, so I wrote this function yesterday for one of our websites here at the office, the site is responsive, but one of the banners wasn't behaving at a certain screen size (was getting chopped off when screen size was less than 1067px). Basically, this script checks for window size of 1067px (higher than 1068px, banner is fine) to 980px (lower than 981, banner is hidden)

function updateReadyGoBG(){
    var vpWidth, difference, position = 0;
    vpWidth = jQuery(this).width();

    if(vpWidth > 980 && vpWidth < 1067){
        position = jQuery(".ready_go_bg").css("left").replace("px", "")
        difference = (position - (600 - (vpWidth - position) ) ) + 100;
        jQuery(".ready_go_bg").css("left", difference + "px")
    }
}

Any ideas on how to improve this to improve performance or reduce calls? Any review, refactoring or just general thoughts would be highly appreciated. What did I do wrong? What would you change?

Thanks all!

EDIT: adding rudimentary html snipped this acts on

        Ready. Go.


texts: Does Java need an Observable object with generics?

texts:
This is the follow-up question from here.

This is an Observable class similar to java.util.Observable. The difference is that it uses generics to avoid casts.

There are two questions:

Is it really worth the effort? or it's just making things more complex than needed?
Should this class be declared final, or is it ok to be subclassed? java.util.Observable is not final.

package cc.koosha.silkroad.lang;
import java.util.ArrayList;
import java.util.Collection;

/**
 * like java.util.Observable, But uses generics to avoid need for a cast.
 * For any un-documented variable, parameter or method, see java.util.Observable
 */
public class Observable<T> {
    public interface Observer<T> {
        public void update(Observable observable, T args);
    }

    /**
     * Holds registered observers.
     * @TODO if class is not final can we make this protected? (should we?).
     */
    private final Collection<Observer<? super T>> registry;
    private boolean changed = false;

    /**
     * @TODO should this be private and the class final?.
     */
    protected Observable(final Collection<Observer<? super T>> registry) {
        this.registry = registry;
    }

    /**
     * Static constructor.
     */
    public static <F> Observable<F> getInstance() {
        ArrayList<Observer<? super F>> container = new ArrayList<Observer<? super F>>();
        return new Observable<F>(container);
    }

    // @TODO Should o be checked for null?
    public void addObserver(final Observer<? super T> o) {
        synchronized (this.registry) {
            if (!this.registry.contains(o))
                this.registry.add(o);
        }
    }

    protected void update(final T args) {
        ArrayList<Observer<? super T>> toNotify;

        synchronized (this.registry) {
            if (!changed)
                return;

            toNotify = new ArrayList<Observer<? super T>>(this.registry);
            this.changed = false;
        }
        // Look at OpenJDK to see why a new Collection is used.
        for (Observer<? super T> o : toNotify)
            o.update(this, args);
    }

    public void notifyObservers(final T args) {
        this.update(args);
    }

Methods deleteObserver, deleteObservers, setChanged, clearChanged, hasChanged, countObservers, notifyObservers are removed for brevity.

The rest of the code is at GitHub.


texts:
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

Here's my implementation in Python:
def number_to_word(n):
    """Assumes is an integer from 1 - 1000.
    Returns number in words ex: 122 --> one hundred and twenty-two."""
    # num_to_alpha contains the unique values for numbers that will be returned according to repetitive patterns
    num_to_alpha =\
        {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
         11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen',
         18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty',
         70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'one hundred', 1000: 'one thousand'}
    # Numbers below 21 , 100, 1000 are unique words (cannot be formed using a repetitive rule)
    if 0 < n < 21 or n == 100 or n == 1000:
        return num_to_alpha[n]
    mod = n % 10
    # Numbers in range (21 - 99) have a single rule except the multiples of 10 (formed by a single word)
    if 20 < n < 100:
        if n % 10 != 0:
            return f'{num_to_alpha[n // 10 * 10]}-{num_to_alpha[mod]}'
        return num_to_alpha[n]
    # Numbers above 100 have a single rule except the following:
    if 100 < n < 1000:
        # a) multiples of 100
        if n % 100 == 0:
            return f'{num_to_alpha[n // 100]} hundred'
        # b) numbers whose last 2 digits are above 20 and are also multiples of 10
        if not n % 100 == 0 and n % 100 > 20 and n % 10 == 0:
            return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[n % 100]}'
        # c) numbers whose last 2 digits are below 20 and not multiples of 10
        if n % 100 < 21:
            second_part = num_to_alpha[n % 100]
            return f'{num_to_alpha[n // 100]} hundred and {second_part}'
        # d) numbers whose last 2 digits are above 20 and not multiples of 10
        if n % 100 > 20:
            return f'{num_to_alpha[n // 100]} hundred and {num_to_alpha[((n % 100) // 10) * 10]}-' \
                f'{num_to_alpha[(n % 100) % 10]}'
    # To prevent counting False values
    if n <= 0 or n > 1000:
        return ''

def count():
    """Cleans numbers from spaces and hyphens and returns count."""
    all_numbers = [number_to_word(x) for x in range(1, 1001)]
    numbers_without_spaces = [number.replace(' ', '') for number in all_numbers]
    clean_numbers = [number.replace('-', '') for number in numbers_without_spaces]
    total = 0
    for clean_number in clean_numbers:
        total += len(clean_number)
    return total

if __name__ == '__main__':
    print(count())


texts: Calculate arithmetic expression represented by a string, in Java

texts:
I saw that interview question online and gave it a try:
Implement a function that gets a string which represents an arithmethic expression: contains only numbers or the the operators: '+', '-', '*', '/'.
The function returns the calculation result of the arithmethic expression which appears in the string.
This need to be done in O(n) run-time (n is the length of the string) and O(1) extra space.

Example:

"1+2*3" -> 7

I succeed in implementing this (based mainly on some code I found online), but I just have one problem: logic is too complicated. So when reviewing the code, please tell me how can I simplify the logic here.

Here is the code:

class ArithmethicalStatments {

  private static int applyOperator(char operand, int firstNum, int secondNum){
      switch (operand) {
        case '*':
            firstNum *= secondNum;
            break;
        case '/':
            firstNum /= secondNum;
            break;
        case '+':
            firstNum = secondNum;
            break;
        case '-':
            firstNum = -secondNum;
            break;
      }

      return firstNum;
  }

  public static int calc(String str){
    int sum = 0;
    int lastApplyOpRes = 0;
    int lastNum = 0;
    int len = str.length();
    char prevOperator = '+';

    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);

        if (c >= '0' && c <= '9') {
            lastNum = lastNum * 10 + c - '0';
            continue;
        }

        lastApplyOpRes = applyOperator(prevOperator, lastApplyOpRes , lastNum);
        lastNum = 0;

        switch (c) {
            case '+':
            case '-':
                sum += lastApplyOpRes;
                lastApplyOpRes = 0;
                break;
        }

        prevOperator = c;
    }

    lastApplyOpRes = applyOperator(prevOperator, lastApplyOpRes , lastNum);

    return sum + lastApplyOpRes;
  }
}

In case you want to modify the code- some Junit tests I wrote for your convenience:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class ArithmethicalStatmentsTest {

    @Test
    void testEmpty() {
        assertEquals(0, ArithmethicalStatments.calc(""));
    }

    @Test
    void testOneNum() {
        assertEquals(5, ArithmethicalStatments.calc("5"));
    }

    @Test
    void testPlus() {
        assertEquals(8, ArithmethicalStatments.calc("5+3"));
    }

    @Test
    void testMul() {
        assertEquals(15, ArithmethicalStatments.calc("5*3"));
    }

    @Test
    void testMulPlus() {
        assertEquals(8, ArithmethicalStatments.calc("2*3+2"));
    }

    @Test
    void testPlusMul() {
        assertEquals(11, ArithmethicalStatments.calc("2+3*3"));
    }

    @Test
    void testPlusMulPlus() {
        assertEquals(16, ArithmethicalStatments.calc("2+3+3*3+2"));
    }

    @Test
    void testMinus() {
        assertEquals(2, ArithmethicalStatments.calc("5-3"));
    }

    @Test
    void testDivision() {
        assertEquals(2, ArithmethicalStatments.calc("6/3"));
    }

    @Test
    void testMinusPlus() {
        assertEquals(1, ArithmethicalStatments.calc("2-3+2"));
    }

    @Test
    void testPlusDivide() {
        assertEquals(5, ArithmethicalStatments.calc("3+4/2"));
    }

    @Test
    void testAll() {
        assertEquals(6, ArithmethicalStatments.calc("2-3+3/3+2*3"));
    }

}


texts: Create file path and filename in JSON and send it to Discord

texts:
I have been working on a function which I call report. What it does is that whenever I call the report function. I can give it a payload of my dict with some data and as well as reason where I can have custom message or the exception errors of whatever can happened.
For now I have created something simple where I create names for file_path and filename. I check if there is a path for that name already and if not then we create. We create a JSON file with the report data to my local PC and then I send it to discord. Both the JSON file and a small text that describes that there has been and error and to check it out ASAP.
My question here is pretty simple to see if there is anything I can actually improve my code somehow. Make it less code or a better report, I take whatever possible!
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import os
import time
from datetime import datetime
from typing import List

from discord_webhook import DiscordEmbed, DiscordWebhook

# payload example payload = {"store": "burger-king"}
# reason = Custom message or exception err

def report(payload=None, reason=None):

    webhook = DiscordWebhook(
        url="https://discord....."
    )

    embed = DiscordEmbed(title="An error has occurred", color=16711680)

    # -------------------------------------------------------------------------
    # Create file path and filename
    # -------------------------------------------------------------------------

    file_path = f'./error/{payload["store"] if payload else "Other"}'
    filename = f'{datetime.strftime(datetime.now(), "%Y-%m-%d_%H-%M-%S-%f")}.json'

    # Check if the path already exists
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    # Write to a JSON file
    with open(f"{file_path}/{filename}", "w", encoding="utf-8") as f:
        f.write(json.dumps(
            {
                "payload": payload if payload else None,
                "reason": str(reason)
            },
            indent=4,
            ensure_ascii=False
        ))

    # -------------------------------------------------------------------------
    # Filename embed
    # -------------------------------------------------------------------------
    embed.add_embed_field(name="Filename", value=filename, inline=False)

    # -------------------------------------------------------------------------
    # Send files to discord
    # -------------------------------------------------------------------------
    with open(f"{file_path}/{filename}", "rb") as f:
        webhook.add_file(file=f.read(), filename=f"{filename}")

    # -------------------------------------------------------------------------
    # Footer timestamp
    # -------------------------------------------------------------------------
    embed.set_footer(text=f'AutoSnkr | {datetime.now().strftime("%Y-%m-%d [%H:%M:%S.%f")[:-3]}]')

    webhook.add_embed(embed)

    # -------------------------------------------------------------------------
    # Send to discord with exceptions
    # -------------------------------------------------------------------------
    while True:

        response = webhook.execute()

        # Workaround bug from discord_webhook pypi
        if isinstance(response, List):
            assert (len(response) == 1)
            response = response[0]

        # Successful requests
        if response.ok:
            return

        # Rate limit. Wait until the limitation is gone
        elif response.status_code == 429:
            sleep_time = int(response.headers["retry-after"]) / 1000
            time.sleep(sleep_time)

        else:
            print("Big error here! This text needs to be replaced later on")
            return


texts: Find all possible interpretations of an array of digits

texts:
Consider a coding system for alphabets to integers where 'a' is
  represented as 1, 'b' as 2, .. 'z' as 26. Given an array of digits (1
  to 9) as input, write a function that prints all valid interpretations
  of input array.

    Input: {1, 1} Output: ("aa", 'k")  [2 interpretations: aa(1, 1), k(11)]

    Input: {1, 2, 1} Output: ("aba", "au", "la")  [3 interpretations: aba(1,2,1), au(1,21), la(12,1)]

    Input: {9, 1, 8} Output: {"iah", "ir"}  [2 interpretations: iah(9,1,8), ir(9,18)]

I'm looking for code-review, optimizations and best practices.  I'm also verifying space complexity to be \$O(2^n)\$, where \$n\$ is the number of alphabets is the length of input array.

public final class FormulateAlphabets {

    private static final String[] data = {
        "", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
        "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
    };

    private FormulateAlphabets() { }

    public static List<String> getAllStrings(int[] arr) {

        List<String> strList = new ArrayList<>();
        formulate(arr, 0,  false, strList, new StringBuffer());
        formulate(arr, 0,  true,  strList, new StringBuffer());

        return strList;
    }

    private static void formulate(int[] arr, int currPosition, boolean includeNextPosition, List<String> strlist, StringBuffer sb) {

        int nextPosition = 0;

        if (!includeNextPosition) {
            sb.append(data[arr[currPosition]]);
            nextPosition = currPosition + 1;
        } else {

            if ((currPosition + 1) == arr.length) return;

            int result = arr[currPosition] * 10 + arr[currPosition + 1];
            if (result <= 26) {
                sb.append(data[result]);
            } else {
                return;
            }

            nextPosition = currPosition + 2;
        }

        if (nextPosition == arr.length) {
            if (sb.length() > 0) {
                strlist.add(sb.toString());
                sb.deleteCharAt(sb.length()-1);
            }
            return;
        }

        formulate(arr, nextPosition, false, strlist, sb);
        formulate(arr, nextPosition, true, strlist, sb);

        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length()-1);
        }
    }

}

public class FormulateAlphabetTests {

    @Test
    public void test1() {
        int[] a1 = {1, 2, 3, 4};
        assertEquals(Arrays.asList("abcd", "awd", "lcd"), FormulateAlphabets.getAllStrings(a1));
    }

    @Test
    public void test2() {
        int[] a2 = {1, 2, 2, 1};
        assertEquals(Arrays.asList("abba", "abu", "ava", "lba", "lu"), FormulateAlphabets.getAllStrings(a2));
    }

    @Test
    public void test3() {
        int[] a3 = {1, 2, 3};
        assertEquals(Arrays.asList("abc", "aw", "lc"), FormulateAlphabets.getAllStrings(a3));
    }

    @Test
    public void test4() {
        int[] a4 = {12, 23, 2};
        assertEquals(Arrays.asList("lwb"), FormulateAlphabets.getAllStrings(a4));
    }
}


texts:
I live in a country where an electricity blackout happens after every hour, which corrupts the Minecraft save files, so I came up with this auto backup utility which backs up the %appData%.minecraft\saves folder constantly after a specified time.

It works fine but I'm still not satisfied with it.  Tell me what more I can do to improve/enhance it.

import time
import os
import sys

#class for parsing settings.ini
class parseIni(object):
    def __init__(self, fileStream):
        self.lines = fileStream.readlines()
    self.options = []
        for line in self.lines:
            if "=" not in line:
                continue
            else:
                self.options.append(tuple(line.replace("\n", "").split("=")))
    def getValueOf(self, option):
        for op, value in self.options:
                if op==option:
                    return value

#Tries to open the settings file, if unsuccessful then exit program
settingsFileStream = None
try:
    settingsFileStream = open("settings.ini")
except IOError:
    print("ERROR: SETTINGS FILE NOT FOUND.", file=sys.stderr)
    raw_input("Press <ENTER> to exit....")
    sys.exit(0)

#Initialize parser
settings = parseIni(settingsFileStream)

#Precondition: settings file was opened successfully
#Assigning values to required variables
timeDelayInMins = eval(settings.getValueOf("timeDelay")) #For user information
timeDelay = timeDelayInMins * 60 #Converting to seconds, for time.sleep() method
sourcePath = settings.getValueOf("sourcePath")
destinationPath = settings.getValueOf("destinationPath")

#Runs the game
os.system("Minecraft.exe")

#Prints out Welcome message
print()
print("|--------------------------------------------------------|")
print("|WELCOME TO MINECRAFT AUTO BACKUP UTILITY!               |")
print("|--------------------------------------------------------|")
print("|REFER TO THE settings.ini FILE TO EDIT SETTINGS FOR THIS|")
print("|PROGRAM. e.g. TIME DELAY FOR AUTO BACKUP, PATHS etc     |")
print("|--------------------------------------------------------|")
print("|TIME DELAY FOR AUTO BACKUP IS {:0.2f} MIN(S)        |".format(timeDelayInMins))
print("|--------------------------------------------------------|")
print()

#Variable to keep tract of backups done per session
backupsDone = 0

#mainLoop runs forever, backups "saves" folder every after ever timeDelay mins
while True:
    time.sleep(timeDelay)
    os.system('robocopy "{}" "{}" /e'.format(sourcePath, destinationPath))
    backupsDone += 1
    print
    print
    print("|---------------------------------|")
    print("|{} BACKUP(S) DONE THIS SESSION.  |".format(backupsDone))
    print("|---------------------------------|")

And the settings.ini file with the program is:

[TIME]
timeDelay=1
[PATHS]
sourcePath=%appData%\.minecraft\saves
destinationPath=%appData%\.minecraft\SavesBackup


texts:
This question is related to another one that I have asked here.

I need to find ways to improve the runtime performance of the following piece of C-code.

I want to increase RANGE to around 1G, and still complete the execution within a reasonable time.

Auxiliary data structures:

#define RANGE 16000000

uint08 sieve[RANGE]    = {0};
uint32 prime[RANGE/16] = {0}; // only around RANGE/log(RANGE) are primes
uint32 numOfPrimes     =  0 ;

Initialize the auxiliary data structures:

void CalcAuxiliaryData()
{
    uint32 i,j;

    uint32 root = (uint32)sqrt((double)RANGE);

    for (i=2; i<=root; i++)
    {
        if (sieve[i] == 0)
            for (j=i+i; j<RANGE; j+=i)
                sieve[j] = 1;
    }

    for (i=2; i<RANGE; i++)
    {
        if (sieve[i] == 0)
            prime[numOfPrimes++] = i;
    }
}

Calculate the square root of the sum of the squares of the prime factors of an input number:

uint32 CalcDiagonalLen(uint32 n)
{
    uint32 i;

    uint64 square;
    uint32 length;

    if (sieve[n] == 0) // quickly resolve the case of a prime number
        return n;

    square = 0;
    for (i=0; i<numOfPrimes && n>1; i++)
    {
        uint32 p = prime[i];
        uint64 pp = (uint64)p*p;
        while (n%p == 0)
        {
            n /= p;
            square += pp;
        }
    }

    length = (uint32)sqrt((double)square);
    if ((uint64)length*length == square)
        return length;

    return 0; // indicate that the result is not integer
}

Calculate the square root of the sum of the squares of the prime factors of each number:

int main()
{
    uint32 i;

    uint32 diagonal_len;

    CalcAuxiliaryData();

    for (i=2; i<RANGE; i++)
    {
        diagonal_len = CalcDiagonalLen(i);
        if (diagonal_len != 0)
            printf("%u %u\n",i,diagonal_len);
    }

    return 0;
}

Function CalcDiagonalLen holds the bottleneck, but any suggestions will be greatly appreciated.


texts: A multi-threaded Producer Consumer with C++11

texts:
I am trying to learn concurrent programming in C++11. I tried to write code for a classic producer consumer concurrency problem. Would you please review and make any comments about it?

#include <iostream>
#include <thread>
#include <deque>
#include <mutex>
#include <chrono>
#include <condition_variable>

using std::deque;
std::mutex mu,cout_mu;
std::condition_variable cond;

class Buffer
{
public:
    void add(int num) {
        while (true) {
            std::unique_lock<std::mutex> locker(mu);
            cond.wait(locker, [this](){return buffer_.size() < size_;});
            buffer_.push_back(num);
            locker.unlock();
            cond.notify_all();
            return;
        }
    }
    int remove() {
        while (true)
        {
            std::unique_lock<std::mutex> locker(mu);
            cond.wait(locker, [this](){return buffer_.size() > 0;});
            int back = buffer_.back();
            buffer_.pop_back();
            locker.unlock();
            cond.notify_all();
            return back;
        }
    }
    Buffer() {}
private:
    deque<int> buffer_;
    const unsigned int size_ = 10;
};

class Producer
{
public:
    Producer(Buffer* buffer)
    {
        this->buffer_ = buffer;
    }
    void run() {
        while (true) {
            int num = std::rand() % 100;
            buffer_->add(num);
            cout_mu.lock();
            std::cout << "Produced: " << num << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            cout_mu.unlock();
        }
    }
private:
    Buffer *buffer_;
};

class Consumer
{
public:
    Consumer(Buffer* buffer)
    {
        this->buffer_ = buffer;
    }
    void run() {
        while (true) {
            int num = buffer_->remove();
            cout_mu.lock();
            std::cout << "Consumed: " << num << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
            cout_mu.unlock();
        }
    }
private:
    Buffer *buffer_;
};

int main() {
    Buffer b;
    Producer p(&b);
    Consumer c(&b);

    std::thread producer_thread(&Producer::run, &p);
    std::thread consumer_thread(&Consumer::run, &c);

    producer_thread.join();
    consumer_thread.join();
    getchar();
    return 0;
}


texts: Taking action on a webpage(select checkbox or enter textbox or select from a list)

texts:
I currently have the following code. This function works successfully, however, i would like some feedback because I think it is very messy.

Currently, this function checks if the field is checkbox or textbox or Select. Once it verifies the field it performs an action based on that. For example if it is SELECT it will select the value.

If it cannot find any of the above it throws an error that it cannot find the textbox.

I have defined two variables enterValue and checkboxUncheck=False. enterValue is what user wants to enter. checkboxUncheck variable is used so the user can perform two actions, uncheck the checkbox or check it. By default it checks it. However this can be changed if it is set to checkboxUncheck=True.

Here is the function.:

def take_action(self, enterValue, checkboxUncheck=False):
        try:
            child = [
            self.text.find_element_by_xpath(PageCommonLocatars.FINDCHECKBOXONE),
            self.text.find_element_by_xpath(PageCommonLocatars.FINDCHECKBOXTWO)
            ]

            var = self.text.find_element_by_xpath(PageCommonLocatars.ENTERCHECKBOXVAL % enterValue)
            #var = self.text.find_element_by_xpath('./..//..//div/input[@value="%s"]' % enterValue)
            if checkboxUncheck == True:
                if var.is_selected() == True:
                    self.driver.execute_script("arguments[0].click();", var)
            else:
                if var.is_selected() == False:
                    self.driver.execute_script("arguments[0].click();", var)

        except:
            try:
                Select(self.text.find_element_by_xpath(PageCommonLocatars.FINDSELECT_TYPE)).select_by_visible_text(enterValue)
            except:
                self.text.find_element_by_xpath(PageCommonLocatars.FINDTEXTBOX)
                elemtwo = self.text.find_element_by_xpath(PageCommonLocatars.ENTERTEXTBOXVAL)
                actions = webdriver.ActionChains(self.driver)
                actions.move_to_element(elemtwo)
                elemtwo.clear()
                actions.send_keys(enterValue)
                actions.perform()

        # saves it after making changes
        self.click(10, *PageCommonLocatars.SAVEBUTTON)

Here in a separate locators.py. I have defined my locators

class PageCommonLocatars(object):
  # Login function locators
  ROWPARENT           = '//tr/th//*[text()="%s"]'
  FINDCHECKBOXONE     = './..//..//input[@type="checkbox"]'
  FINDCHECKBOXTWO     = './..//..//input[@type="CheckBox"]'
  ENTERCHECKBOXVAL    = './../../td/input[@value="%s"]'
  FINDSELECT_TYPE     = './..//..//./td/select'
  FINDTEXTBOX         = './../../td/input[@type="text"]'
  ENTERTEXTBOXVAL     = './../..//./td/input'
  SAVEBUTTON          = (By.XPATH, '//button[contains(text(),"Save")]')

  GETSELECTVAL     = './../../../td/select'
  GETTEXTBOXVAL    = './../../td/input[@value="%s"]'
  GETCHECKBOXVAL   = './../../td/input[@value="%s"]'


texts: Check if email address contains one of many domains from a table, ignoring the subdomain

texts:
I'm trying to validate email addresses as being from certain universities. I have a table, University, which is full of university domains. University email addresses often have different subdomains, and I want to be able to tolerate any subdomain under the domains in my table.

I think the following works, but is poorly written.  Can anyone suggest ways of refactoring this, with explanations?

domain = self.email.split("@")[1]

domain_test = false

University.all.each do |d|
  if domain.include?(d.domain)
    domain_test = true
    break
  end
end

if domain_test = false
  errors.add(:email, "Sorry, no match found")
end


texts: Bubble sort with counting swaps and comparsions

texts:
I have bubble sort code below, which has to count swaps and comparisons of elements. How can it be made more elegant and clear, if it is possible? I think using lots of tuples is not the best way to do this.

bsort' x = bsort (x,0,0)

bsort :: (Ord a) => ([a], Int,Int) -> ([a], Int, Int) -- (table, nswaps, ncompares)
bsort ([],i,j) = ([], i, j)
bsort (lst, inswp, incmp)
    | hasNoSwaps = (lst, swaps, cmps)
    | otherwise = ((next ++ [last bubbled]), subswaps, subcounts)
    where
        (next, subswaps, subcounts) = bsort ((init bubbled), swaps, cmps)
        (bubbled, hasNoSwaps, swaps, cmps) = bubble (lst, inswp ,incmp)

        bubble :: (Ord a) => ([a], Int, Int) -> ([a], Bool, Int, Int)
        bubble ([x], i, j) = ([x], True, i, j)
        bubble ((x:y:xs), swaps, cmps)
            | x > y = (y : bubbled_x, False, newswaps_x+1, newcmps_x+1)
            | otherwise = (x : bubbled_y, swaps_y, newswaps, newcmps+1)
            where
                (bubbled_y, swaps_y, newswaps, newcmps) = bubble ((y:xs), swaps, cmps)
                (bubbled_x, swaps_x, newswaps_x, newcmps_x) = bubble ((x:xs), swaps, cmps)


texts: Throw exception in Spring when loading a file

texts:
I have this following piece of code:

@Component
public class ManifestReader {

    private final ServletContext servletContext;
    private Properties p;

    @Autowired
    public ManifestReader(final ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public Properties getManifest() throws IOException {
        if (p == null) {
            p = new Properties();
            p.load(servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"));
        }
        return p;
    }
}

What I want to do it is just, to load the file, and once it is loaded, it can be injected to all the classes that need that properties file. Like here:

@RestController
@RequestMapping(value = "/info")
public class InfoEndPoint {

    private final ManifestReader manifestReader;

    @Autowired
    public InfoEndPoint(final ManifestReader manifestReader) {
        this.manifestReader = manifestReader;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Info get(final HttpServletRequest httpServletRequest) throws IOException {
        final App app = fillApp(httpServletRequest, manifestReader.getManifest());
        final Info info = new Info();
        info.setApp(app);
        return info;
    }
    ....
}

As you can see, everytime I have to call to getManifest I throw an IOException. I don't really want that since I just need to load it once, and then it can be reused without throwing any exception. So, my idea is that you could call to the getManifest method without having to check for any exception.

My first idea was to load the file in the constructor of the class, but I do not know if that is a good practice for Spring. Any clue?


texts: Finding the longest string and its length using Java streams

texts:
Java 8 streams are my new golden hammer that I try to use as often as possible with often enormous gains in brevity and readability. Getting multiple return values, such as a maximum value and its associated element, is a bit cumbersome though (and requires an additional "pair" class).

Should I go back to "normal Java" for this task or is this syntax preferable? Is there a more concise way?

List<String> names = Arrays.asList("John","Paul","Ringo");
Pair<String,Integer> longestName = names.stream()
 .map(n->new Pair<>(n,n.length())) // pretend n.length() to be a lengthy operation
 .max(Comparator.comparing(Pair::getB)).get();
System.out.println(longestName.getA()+" "+longestName.getB());

P.S.: With "lengthy operation" I mean long running, as in I don't want to calculate it twice.


texts: Resository Pattern and Unit of Work with ADO.net

texts:
I am trying to implement the Repository Pattern with a Unit of work but I don't know if I am on the right direction. This is my Model:

public class Resource
{
    public string RessourceUID { get; set; }
    public string RessourceName { get; set; }
    public List<Team> Teams { get; set; }
    public string Loginname { get; set; }
}

This is my Repository:

public class ResourceRepository
{
    public static Resource GetResourceByLoginname(string loginname)
    {
        return RunWithElevatedPrivileges(() => GetResourceByLoginnameInternal(loginname));
    }

    private static Resource GetResourceByLoginnameInternal(string loginname)
    {
        return ExecuteSql(cmd =>
        {
            Resource resource;

            cmd.CommandText = @"SELECT convert(nvarchar(36), ResourceUID) AS ResourceUID, UserClaimsAccount, ResourceName FROM MSP_EpmResource_UserView WHERE UserClaimsAccount = @userclaimsaccount";
            cmd.Parameters.AddWithValue("@userclaimsaccount", SqlDbType.NVarChar).Value = loginname;

            using (var dr = cmd.ExecuteReader())
            {
                if (!dr.HasRows)
                    return null;

                resource = new Resource();

                while (dr.Read())
                {
                    MapResourceData(resource, dr);
                    resource.Teams = RunWithElevatedPrivileges(() => GetResourceTeams(resource));
                }
            }

            return resource;
        });

    }

     private static void MapResourceData(Resource resource, SqlDataReader dr)
    {
        resource.RessourceUID = SqlReaderHelper.GetValue<string>(dr, "ResourceUID");
        resource.RessourceName = SqlReaderHelper.GetValue<string>(dr, "ResourceName");
        resource.Loginname = SqlReaderHelper.GetValue<string>(dr, "UserClaimsAccount");
    }

    private static T RunWithElevatedPrivileges<T>(Func<T> action)
    {
        var result = default(T);

        Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(() => result = action());

        return result;
    }

    private static void ExecuteSql(Action<SqlCommand> action)
    {
        string connectionString = Connectivity.GetConnectionString();

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            var cmd = conn.CreateCommand();

            action(cmd);
            cmd.ExecuteNonQuery();
        }
    }

    private static T ExecuteSql<T>(Func<SqlCommand, T> action)
    {
        T result;

        string connectionString = Connectivity.GetConnectionString();

        using (var conn = new SqlConnection(connectionString))
        {
            conn.Open();
            var cmd = conn.CreateCommand();

            result = action(cmd);
            cmd.ExecuteNonQuery();
        }

        return result;
    }
}

Is this a good design?
Is this the Repository Pattern?
What could I optimize?
I absolutely don't know how to implement the Unit of work. How could I do this?
Should I move the ExecuteSql methods out of the Repository?
Should I also move the MapXXXData methods out of this Repository?


texts: Extracts marks of all students in class from website

texts:
This code extracts marks of all students in class and stores the result in a file results.txt, using BeautifulSoup. I'm looking for code review and suggestions.

from bs4 import BeautifulSoup
import requests

file = open("results.txt","w")

for roll in range(1,60):
    if roll in range(1,10):
            rollstr = '0'+str(roll)
    else:
            rollstr = str(roll)
    url = 'http://www.*.org/'
    r = requests.get(url)

    data = r.text
    soup = BeautifulSoup(data)

    file.write('roll: ' +rollstr + ' ')

    for i in soup.find_all('strong'):
            sgpa = i.get_text()
            if sgpa.find('SGPA') == 0:
                    file.write(sgpa)
                    break
    file.write('\n')


texts: Simplifying casting in my C/C++ qsort char** comparator function

texts:
I have a comparator function I use with qsort to sort an array of char* (i.e., char**), which compiles with current versions of Clang and GCC without giving errors or warnings:

static int
comparator(const void* a, const void* b)
{
#ifdef __cplusplus
    auto a_recast = const_cast<void *>(a);
    auto b_recast = const_cast<void *>(b);
    auto a_rerecast = reinterpret_cast<char **>(a_recast);
    auto b_rerecast = reinterpret_cast<char **>(b_recast);
    auto a_rererecast = const_cast<const char **>(a_rerecast);
    auto b_rererecast = const_cast<const char **>(b_rerecast);
    return std::strcmp(*a_rererecast, *b_rererecast);
#else
    return strcmp(*(const char**) a, *(const char**) b);
#endif
}

It compiles conditionally, that is, depending on whether a C or C++ compiler is used, one or the other block of code is compiled.

I offer both blocks, because this is part of a program that can be compiled alone in C, or in a larger suite of tools compiled with a C++ toolkit.

My question is about the work I had to do to in the C++ block, where I strip const, recast to char **, and reapply const.

Is there a simpler or cleaner way to do this C++-style casting, which generates the correct end results and does not result in warnings about C-style casting?

Clang, in particular, is chatty with warnings about old C-style casts, and I like my build logs to be clean, where fixes are realistic.

I also like the code to be clear and easy to and maintain. I'd also like to inline this code, which would probably be easier for the compiler if the comparator function is smaller.

If I'm doing the correct work, that's fine, but if there are better ways, I'd be interested to learn them. Thanks for your advice.


texts:
Now that I've got this working, any improvements that I can make to better my code review would be helpful.

import random
import math
import console

console.set_font('Arial-BoldMT',15)

print'Welcome to the guessing game!\nA number will be randomly chosen from 0 to 1000.\nThe player will make a guess, and then the computer will guess. Who ever is closest wins that round!\nFirst to 5 wins!'

rounds = 0
run_again = 'y'
player_wins = 0
computer_wins = 0
draws = 0

while run_again == 'y':
    number = random.randint(0,1000)
    player_number = input('\nPlayer: ')
    computer_number = random.randint(0,1000)

    print 'Computer:', computer_number
    print 'Number:', number

    player_score = math.fabs(player_number - number)
    computer_score = math.fabs(computer_number - number)

    if player_score>=computer_score:
        computer_wins+=1
        console.set_color(1.00, 0.00, 0.00)
        print 'You lost that round'
        console.set_color(0.00, 0.00, 0.00)

    if player_score<=computer_score:
        player_wins+=1
        console.set_color(0.00, 0.00, 1.00)
        print 'You won that round'
        console.set_color(0.00, 0.00, 0.00)

    if player_score==computer_score:
        draws+=1
        console.set_color(0.00, 1.00, 0.00)
        print 'That round was a tie'
        console.set_color(0.00, 0.00, 0.00)

    rounds +=1

    if rounds == 5:
        if player_wins > computer_wins:
                console.set_color(0.00, 0.00, 1.00)
                print '\nYOU WON THE GAME'
                console.set_color(0.00, 0.00, 0.00)
                break
        elif computer_wins > player_wins:
                console.set_color(1.00, 0.00, 0.00)
                print '\nYOU LOST THE GAME'
                console.set_color(0.00, 0.00, 0.00)
                break
        else:
                print "Wrong counts"


texts: Doing a qsort function to compare strings, case insensitive

texts:
How does the following C program look to compare to strings and return a case-insensitive sort? The following is what I have so far:
int main(void)
{
    char* strings[4] = {"Onus", "deacon", "Alex", "zebra"};
    for (int i=0; i<4; i++) printf("%d. %s\n", i+1, strings[i]);
    qsort(strings, 4, 8, scmp);
}

int scmp(const void *p1, const void *p2)
{

    // being a string (pointer-to-char)
    const char* s1 = *(char**) p1;
    const char* s2 = *(char**) p2
    size_t len_s1 = strlen(s1);
    size_t len_s2 = strlen(s2);

    // lower-case first string buffer
    char s1_lower[len_s1+1];  // cannot initialize with {[len_s1]=0} in VLA ?
    s1_lower[len_s1] = 0;
    for (int i=0; s1[i] != 0; i++)
        s1_lower[i] = tolower(s1[i]);

    // lower-case second string buffer
    char s2_lower[len_s2+1];
    s2_lower[len_s2] = 0;
    for (int i=0; s2[i] != 0; i++)
        s2_lower[i] = tolower(s2[i]);

    // built-in string compare (strcmp) will return the sort value
    return strcmp(s1_lower, s2_lower);
    /* printf("%s -- %s\n", s1_lower, s2_lower); */

}

Another version extracting out the str_lower function would be:
void lower_string(char buffer[], const char* str, size_t len)
{
    char str_lower[len+1];
    str_lower[len] = 0;
    for (int i=0; str[i] != 0; i++)
        str_lower[i] = tolower(str[i]);
}
int scmp(const void *p1, const void *p2)
{
    const char* s1 = *(char**) p1;
    const char* s2 = *(char**) p2;

    char s1_lower[strlen(s1)+1];
    lower_string(s1_lower, s1, strlen(s1));

    char s2_lower[strlen(s2)+1];
    lower_string(s2_lower, s2, strlen(s2));

    return strcmp(s1_lower, s2_lower);
}


texts:
For example, given a 2D array (a matrix):

{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}}

What are the solutions to find a number, such as 6?

Here's the code I tried using binary search method:

int main(){
    int sample[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    int target = 6;
    int lowX, highX, lowY, highY, midX, midY;

    //Note: some values are hardcoded, should not matter.
    lowX = 0;
    highX = 2;
    lowY = 0;
    highY = 3;

    if(target <= sample[0][0] || target >= sample[3 - 1][4 - 1]){
        std::cout<<"Nope";
    }

    while(lowX <= highX && lowY <= highY){
        midX = (lowX + highX)/2;
        midY = (lowY + highY)/2;

        if(target < sample[midX][midY]){
            highX = midX - 1;
            highY = midY - 1;
        }
        else if(target > sample[midX][midY]){
            lowX = highX + 1;
            lowY = highY + 1;
        }
        else {
            lowX = highX + 1;
            lowY = highY + 1;
        }
    }

    if(target == sample[midX][midY]){
        std::cout<<"Found";
    }
    else{
        std::cout<<"Nope";
    }

    return 0;
}

Is this method optimal?
What are the other possible solutions?


texts: Dynamic way to use string/array as index of object in javascript

texts:
I've got a structure of files and folders in a directory structured like the "example_object" I describe below. I also have paths of each of the files as strings.

So my solution is to split the path into an array, and then use the array to index the object as described in the function below. The length of the array will vary as I don't know how many levels of folders there will be.

Whilst what I've written below works, and I guess is only 4 lines, I see a lot of users get anxious about using "eval". It also seems an indirect method to get the job done. Any improvements/alternate ways to do this?

function change_object_using_path_string(this_object,this_path,new_value){
  var array_as_index = this_path.split("/");
  array_as_index = "['"+array_as_index.join("']['")+"']";
  var code_to_eval = this_object+array_as_index+"='"+new_value+"'";
  eval(code_to_eval);
}

The above function is what I'm actually using in my script. The below code reflects the structure of the inputs I would put into the above function:

// NOTE: I'm only inputting "example_object" into 'change_object_using_path_string' as a string to facilitate the eval solution I'm using. I would prefer a solution which directly inputs example_object into the function.

example_object = {
  folder_1_name:{
    folder_2_name:{
      folder_3_name:{
        'file.txt':'this file content'
      }
    }
  }
}
example_path = "folder_1_name/folder_2_name/folder_3_name/file.txt";

change_object_using_path_string("example_object",example_path,"new content instead");


texts: Correct way to cover dependencies in unit tests

texts:
My approach to unit testing feels very wrong. I feel like I am missing something very basic, and I'm looking for some insight please.

Let's assume that I am testing a method (I'm using NUnit) that returns an object. It might look like this:

public void TestConnection()
{
     DBConnector dbConn = new DBConnector(connString);
     Assert.IsInstanceOf(typeof(DBConnector), dbConn);
}

Let's assume too that the test passes.

Later in my test class, I create another test on an object that has a dependency on MyObject. That test method might look like this:

public void IsCallInstanceNull()
{
     DBConnector dbConn = new DBConnector(connString);
     dbConn.EstablishConnection();
     CallInstance ci = new CallInstance(dbConn);
     Assert.IsNotNull(ci);
}

I am first marking TestConnection() "public void", ensuring a basic pass, then changing the method to private so that I can use a typed object in the second method, instead of duplicating code. So my example test class becomes:

private DBConnector CreateDBConnector()
{
     var dbConn = new DBConnector(connString);
     dbConn.EstablishConnection();
     return dbConn;
}

public void IsCallInstanceNull()
{

     CallInstance ci = new CallInstance(CreateDBConnector());
     Assert.IsNotNull(ci);
}

But this feels completely wrong. No one will ever know that the constructor for DBConnector was ever tested (since not only did I change its visibility, I renamed the method!) so  how can this be refactored so that I ensure test coverage for the private method without having to leave 2 almost identical methods in the test class?