texts: Convert carry-add loop to a map or reduce to one-liner

texts:
I want to perform standard additive carry on a vector. The base is a power of 2, so we can swap modulus for bitwise AND.

def carry(z,direction='left',word_size=8):
        v = z[:]
        mod = (1<<word_size) - 1
        if direction == 'left': v = v[::-1]
        accum = 0
        for i in xrange(len(v)):
                v[i] += accum
                accum = v[i] >> word_size
                v[i] = v[i] & mod
                print accum,v
        if direction == 'left': v = v[::-1]
        return accum,v

Is there any way to make this function even tinier?


texts:
I'm trying to create small PHP framework for my own needs (and likes). However there are questions for which I may need advice of more wise and experienced people before things became too complicated - so I moved it to github from private repo.

Currently I'm curious about organizing imports of modules better. I use the special object, "context" - to hold links to all necessary modules - data access objects, utils etc. I use lazy initialization here, so that when field of this object is required, it is provided by the getter of the same name.

It looks like:

class ProtoContext {

    function __get($name) {
        $methodName = 'get' . ucfirst($name);
        if (!method_exists($this, $methodName)) {
            throw new Exception("No property '$name' in Context!");
        }
        $res = $this->$methodName();
        if (is_object($res)) {
            $res->ctx = $this;
        }
        $this->$name = $res;
        return $res;
    }

    protected function getElems() {
        return Elems::$elems;
    }

    protected function getUtil() {
        module('sys/Util');
        return new Util();
    }

}

main Context class is inherited from this ProtoContext, though it is not significant now. With the grow of application context may look like this:

module('sys/ProtoContext');

class Context extends ProtoContext {

    protected function getAuth() {
        module('MyAuth');
        return new MyAuth();
    }

    protected function getUsersDao() {
        module('dao/MysqlDao');
        return new MysqlDao('users');
    }

    protected function getRolesDao() {
        module('dao/MysqlDao');
        return new MysqlDao('roles');
    }

    /*
     * 5-10 more similar methods 'getSomethingDao'
     * each including MysqlDao via method 'module'
     */

    protected function getLinksCViewDao() {
        module('dao/MysqlDao');
        return new MysqlDao('linksc_view');
    }

}

There is no problem that module method may be called several times, include is performed once only. However it looks annoying that inclusion of MysqlDao is mentioned so many times. On the other hand if I pull it above the class (like import of ProtoContext) it will be imported even if I need it not. For example when addressing $ctx->auth field (which will call getAuth method).

I wonder, whether here is comfortable workaround which will preserve lazy load and lazy initialization - and at the same time will allow to get rid of extra imports?


texts: Split list of integers at certain value efficiently

texts:
I am working on a python puzzle over at codewars ( Largest Rectangle )  My solution is working for small cases but times out for the very large ones.)  I think one major hit to performance is in my subroutine splitz(arr):

The purpose of this subroutine is something like string.split('X') - but for lists of integers.  In my case, I will always be spllitting at the minimum value on the list, so splitz([3,3,5, 1, 5,5,5, 1, 6,5,4]) should return  [[3,3,5], [5,5,5], [6,5,4]]

def splitz(iterable):
    key = (min(iterable),)
    return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in key) if not k]

My code is adapted from a snippet found on Stackoverflow, and I don't understand it well enough to know how efficient it really is (or not.)  It needs to efficiently deal with lists with len ~= 100,000 that could be splitting up into almost that many sublists.

Is there a better way to do this split, or do I need to find a completely different approach to solving the overall problem?

FULL CONTEXT

The overall task is to identify the largest rectangle that can be made in a grid made from stacked rows of length a[i].  So if a is [7,2,6,4,5,1] the grid looks like

0000000
00
000000
0000
00000
0

largest possible rectangle is shown in H's:

0000000
00
HHHH00
HHHH
HHHH0
0

And the routine should return 12 (=3*4)

This is my third approach.  The first one was a lambda one-liner that was quite compact, but could only handle lists up to about 1000.  My current solution works with long lists on my PC,  (150,000 in 1.5 seconds, 1.5 million in 110 seconds) but fails on codewars.  I don't know how long the longest test case is there, but the time limit is 1.2 seconds.

import itertools

def largest_rect(a):
    maxRect = 0  # This will store the result
    if len(a) == 0:
        return 0
    mina = min(a)

    # The area of a rectangle extending
    # all the way across the the current list,
    # with the maximum possible height (which is the minimum in this list)
    maxRect = len(a) * mina
    # split the current lists into sublist, dividing at the
    # value that limited the height of the previous calc
    newarrlist = splitz(a, mina)

    # Now loop through each of the lists returned when split the original
    keepTrying = True
    while keepTrying:
        tmparrlist = []
        keepTrying = False  # This will be set True if we generate a new sublist
        for thisarr in newarrlist:
            # If the enclosing dimensions of this block aren't bigger
            # than the current largest rectangle, don't bother using it.
            lenta = len(thisarr)
            if lenta * max(thisarr) > maxRect:
                minta = min(thisarr)
                maxRect = max(maxRect, minta*lenta)
                lists = splitz(thisarr, minta)
                # If splitz was given a perfect rectangle, that block is now finished.
                # Otherwise add the sublists to a temporary array.
                if len(lists) > 0:
                    tmparrlist = tmparrlist + lists
                    keepTrying = True  # We stored a sublist - we'll have to repeat

        # Once we have gone through the list of lists, reset to our temporary array
        # and try again until keepTrying = False
        newarrlist = tmparrlist
    return maxRect

# This will split a list into sublists at the minimum value on the original
def splitz(iterable, minin):  # Pass in the min value, since we already know it.
    splitters = (minin, )
    return [list(g) for k, g in itertools.groupby(iterable,lambda x:x in splitters) if not k]


texts: How can I use the State monad effectively in Haskell?

texts:
I have written a simple fibonacci function in Haskell that uses the State monad to save solutions to overlapping sub-problems. Now despite the function working I am not really happy with the solution, especially with the last map lookup. How can I improve my solution? Thank you.
module Lib (
    fib
) where

import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe

type DP = Map Int Int

fib :: Int -> State DP Int
fib 0 = return 1
fib 1 = return 1
fib x = do
    solved <- get
    let m = Map.lookup x solved
    case m of
            Nothing -> do
                prev1 <- fib (x - 1)
                prev2 <- fib (x - 2)
                put $ Map.insert x (prev1 + prev2) solved
            Just value -> put $ Map.insert x value solved
    gets (fromMaybe 0 . Map.lookup x)


texts: Extending CGPoint to conform to Hashable

texts:
For Advent of Code Day 1, I found myself needing to use a tuple as a key in a dictionary.  Seeing that I can't extend tuples in Swift, I decided to extend CGPoint to conform to Hashable:

extension CGPoint: Hashable {
    public var hashValue: Int {
        return hash()
    }

    func hash() -> Int {
        var hash = 23
        hash = hash &* 31 &+ Int(self.x)
        return hash &* 31 &+ Int(self.y)
    }
}

This is based off of an implementation found on Stack Overflow.  Another viable option might be self.x.hashValue << sizeof(CGFloat) ^ self.y.hashValue (from here).

This works if the x and y values of the CGPoint are whole numbers, but the Int truncation gives a lossy conversion from CGFloat to Int which could lead to hash collisions.

How can I improve this implementation, and get floating point numbers to play nicely with a hash value that is an Int?

Or, would the best approach not even be to extend CGPoint at all and to just use a custom Swift container struct or an NSObject subclass?


texts:
The assignment is to take a "Magic Square" .txt file (where the horizontal lines, vertical lines and diagonal line all add up to the same number), read it and prove that they are in fact magic squares.

Is anything in this answer bad practice or just bad? I'm using a lot of Lists and for loops.

package magicSquares;

public  MagicSquaresCormac() {
    return;
}

private List<List<Integer>> getNumberList(String file) throws IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);

    String line = null;
    Integer num = null;
    List<String> lineList = new ArrayList<>();
    List<String> charList;
    List<List<String>> listOfNums = new ArrayList<>();
    List<Integer> numlist;
    List<List<Integer>> numListList = new ArrayList<>();

    while ((line = br.readLine()) != null) {
        line.split("\t");
        if (!line.equals("")) {
            lineList.add(line);
        }
    }

    for (String lineFromList : lineList) {
        //    lineFromList.split(" ");
        numlist = new ArrayList<>();
        charList = Arrays.asList(lineFromList.split("\\s"));
        listOfNums.add(charList);
        for (String character : charList) {
            num = Integer.valueOf(character);
            numlist.add(num);
        }
        numListList.add(numlist);
    }

    br.close();
    return numListList;
}

private boolean horizontalLine(String file) throws IOException {
    List<List<Integer>> numListList = getNumberList(file);
    boolean isMagic = true;
    Integer lastSum = -1;
    Integer sum;

    for (List<Integer> listNum : numListList) {
        sum = 0;
        for (Integer i : listNum) {
            sum = sum + i;
        }
        if (lastSum == -1)
            lastSum = sum;

        else if (!lastSum.equals(sum)) {
            isMagic = false;
        }
    }

    return isMagic;
}

private boolean diagonalLine(String file) throws IOException {
    List<List<Integer>> numListList = getNumberList(file);
    boolean isMagic = true;
    Integer sum;
    Integer sumDiagonal = 0;

    for (int j = 0; j < numListList.size(); j++) {
        sumDiagonal = sumDiagonal + numListList.get(j).get(j);
    }

    sum = sumDiagonal;

    if (!sum.equals(260)) {
        isMagic = false;
    }
    return isMagic;
}

private boolean verticalLine(String file) throws IOException {
    List<List<Integer>> numListList = getNumberList(file);
    boolean isMagic = true;
    Integer lastSum = -1;
    Integer sum;
    List<Integer> tempList;
    List<List<Integer>> verticalLists = new ArrayList<>();

    for (int k = 0; k < numListList.size(); k++) {
        tempList = new ArrayList<>();
        for (int i = 0; i < numListList.size(); i++) {
            tempList.add(numListList.get(i).get(k));
        }
        verticalLists.add(tempList);
    }

    for (List<Integer> listNum : verticalLists) {
        sum = 0;
        for (Integer i : listNum) {
            sum = sum + i;
        }
        if (lastSum == -1)
            lastSum = sum;

        else if (!lastSum.equals(sum)) {
           System.out.println((lastSum != sum) + "really?");
            isMagic = false;
        }
    }
    return isMagic;
}

public static void main(String[] args) throws IOException {
   MagicSquaresCormac magicSquaresCormac =  new MagicSquaresCormac();
    String[] files = {"Mercury.txt", "Luna.txt"};
    for (String file : files) {
        System.out.println(file + " (horizontal lines) is magic? " + magicSquaresCormac.horizontalLine(file));
        System.out.println(file + " (vertical lines) is magic? " + magicSquaresCormac.verticalLine(file));
        System.out.println(file + " (diagonal line) is magic? " + magicSquaresCormac.horizontalLine(file));
    }
}
}


texts:
This is an implementation of the Karatsuba algorithm for multiplication:

use std::cmp::max;

/// Multiplies two numbers using the Karatsuba algorithm
fn karatsuba(a: isize, b: isize) -> isize {
    // Single digit multiplication: no need for Karatsuba
    if a < 10 && b < 10 {
        a * b
    } else {
        let nr_of_digits = max(get_nr_of_digits(a), get_nr_of_digits(b));

        let half_nr_of_digits = nr_of_digits / 2;

        let (p, q) = split_at(half_nr_of_digits, a);
        let (r, s) = split_at(half_nr_of_digits, b);

        let u = karatsuba(p, r);
        let w = karatsuba(q, s);
        let v = karatsuba(p + q, r + s);

        // Since we used integer division for half_nr_of_digits,
        // half_nr_of_digits * 2 is not always equal to nr_of_digits.
        // For example when nr_of_digits is 9.
        let raised_u = u * 10_isize.pow(half_nr_of_digits * 2);

        let raised_v_w_u = (v - w - u) * 10_isize.pow(half_nr_of_digits);

        // That's the product of a and b
        raised_u + raised_v_w_u + w
    }
}

/// Gets the number of digits in a number. For example:
/// get_nr_of_digits(12345) == 5
fn get_nr_of_digits(x: isize) -> u32 {
    let mut nr_of_digits = 1;
    let mut copy = x;
    while copy > 9 {
        copy /= 10;
        nr_of_digits += 1;
    }

    nr_of_digits
}

/// Splits a number at a position. For example:
/// split_at(2, 1234) == (12, 34)
fn split_at(pos: u32, x: isize) -> (isize, isize) {

    let power = 10_isize.pow(pos);

    let high = x / power;
    let low = x % power;
    (high, low)
}

#[test]
fn split_at_works() {
    assert_eq!(split_at(2, 1234), (12, 34));
    assert_eq!(split_at(1, 67), (6, 7));
    assert_eq!(split_at(2, 67), (0, 67));
    assert_eq!(split_at(2, 674), (6,74));
    assert_eq!(split_at(2, 67461), (674, 61));
    assert_eq!(split_at(3, 674610), (674, 610));
}

#[test]
fn karatsuba_works() {
    // Positive numbers
    assert_eq!(karatsuba(12, 34), 12 * 34);
    assert_eq!(karatsuba(3, 4), 3 * 4);
    assert_eq!(karatsuba(5678, 4321), 5678 * 4321);
    assert_eq!(karatsuba(678, 4321), 678 * 4321);
    assert_eq!(karatsuba(67, 65432), 67 * 65432);
    assert_eq!(karatsuba(671, 654), 671 * 654);
    assert_eq!(karatsuba(6781001, 6542001), 6781001 * 6542001);
    assert_eq!(karatsuba(671, 654), 671 * 654);
    assert_eq!(karatsuba(67, 654321), 67 * 654321);
    assert_eq!(karatsuba(678032, 432132012), 678032 * 432132012);

    // Negative numbers
    assert_eq!(karatsuba(-678, 432), -678 * 432);
    assert_eq!(karatsuba(678032, -232132012), 678032 * -232132012);
    assert_eq!(karatsuba(571, -654), 571 * -654);
}

#[test]
fn get_nr_of_digits_works() {
    assert_eq!(get_nr_of_digits(0), 1);
    assert_eq!(get_nr_of_digits(10), 2);
    assert_eq!(get_nr_of_digits(12345), 5);
    assert_eq!(get_nr_of_digits(87654321), 8);
}

I'd love to know how to make this faster and rustier.


texts:
I have the following scenario:

The (web-) application is built with Java/Spring. I have several REST-endpoints which deliver data prepared to be consumed by a frontend by datatables.net. Each of this endpoint has a somehow similar signature (sEcho, iDisplayStart, iDisplayLength etc.) which are standardparameters necessary to work with datatables. Some of the controllers need additional Information, which are provided in extra variables.

So I made a DatatablesOptions class for the general usecase and if I need additional fields I extend the DatatablesOptions class.

My question is now about the naming of the extended classes.

There are two approaches:

I have a package for each of the endpoints, where all additional classes for a topic are stored: e.g. "CustomerComplaints". In such a package you would find the derived class which is used for the additional fields exactly for the usecase of "customer complaints". Hence it is in the "CustomerComplaints"-package the name of e.g. "ViewOptions" would be enough to say what it is used for: »This object is used for the options of a view in the context of "CustomerComplaints"«.

So my code in the Controller looks like this:

@Controller
@RequestMapping("/")
public class CustomerComplaints {

[...]
    @RequestMapping(value="/customercomplaints/datatable", method= RequestMethod.GET)
    @ResponseBody
    public AjaxTableModel getCustomerComplaintsForDataTable(@RequestParam (value="sEcho")int echo,
                                            @RequestParam (value="iDisplayStart")int startLine,
                                            @RequestParam (value="iDisplayLength")int linesPerPage,
                                            @RequestParam (value="iSortCol_0")int columnToSort,
                                            @RequestParam (value="sSearch", required = false) String searchString,
                                            @RequestParam (value="statusfilter")FilterOptions filterOptions,
                                            @RequestParam (value="sSortDir_0")String sortingDirection
[...]
ViewOptions o = new ViewOptions()
            .setLinesPerPage(linesPerPage)
            .setStartLine(startLine)
            .setSortColumn(getSortingKeyForColumnNumber(columnToSort))
            .setSortingDirection(sortingDirection)
            .setFilterOptions(filterOptions)
            .setSearchString(searchString);

The job of the ViewOptions-class is in every controller the same and for the understanding of the code neglectable.

So a further specification via the classes name is not necessary. It seems to me like some kind of "Hungarian Notation". The name CustomerComplaintsViewOptions provides not more Information in this context. And the package makes it unambigous enough. Every smart IDE should resolve the definition for that.
The second approach, which is more texteditor-friendly, is to make it easy to find the definition of this class and name it CustomerComplaintsViewOptions. So a coworker sees from the variable name, where to look, when he wants to know more.

What kind of naming is better style?


texts: Determine the length of the largest contiguous segment

texts:
Problem Link- https://www.hackerearth.com/challenges/competitive/october-circuits-19/algorithm/ap-1-f43562f4/

  Problem Statement :

  You are given an integer array  of size A. You are also given  queries Q. In each query, you are given three integers L, R, and D respectively.

  You are required to determine the length of the largest contiguous segment in the indices range [L, R] of A that forms an arithmetic progression with a common difference of D

  Note: The segment whose length is 1 always forms an arithmetic progression of a common difference D

  Input format

  First line: Two space-separated integers N and Q respectively
  Second line: N space-separated integers denoting elements of A
  Next Q lines: Three space-separated integers L, R, and D (1<= L <= R <= N)       respectively

  Output format

  Print Q lines representing the answer such as the ith line denotes the answer for the ith query.

  Constraints

1 <= N <= 200000
1 <= Ai <= 200000
-200000 <= D <= 200000

  Sample Input

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

Sample Output
3
1

  Explanation

  For the first query, [1,2,3] forms an AP with difference 1.

  For the second query, [5] forms an AP.

I was attempting to solve this problem on hacker earth, however for large size N and Q the following code exceeds the time limit. Is there any way I can make this code run faster, other than changing the algorithm?

N, Q = [int(x) for x in input().split()]

A = list(map(int, input().split()))

for testcase in range(Q):
    L, R, D = [int(x) for x in input().split()]

    if L == R:
        print("1")
        continue

    count_length = 0
    count_temp = 0

    for index in range(L, R):
        if A[index] == A[index-1] + D:
            count_temp += 1
            if index == R-1:
                count_temp += 1
                count_length = max(count_length, count_temp)

        else:
            count_temp += 1 # to include the first element of AP
            count_length = max(count_length, count_temp)
            count_temp = 0

    print(count_length)


texts:
I have a function that needs to return the call to another function that have some parameters. Let's say, for example, the following:

def some_func():
   iss = do_something()
   example = do_something_else()

   return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'})

I want to adjust it so it will comply with PEP 8. I tried:

def some_func():
   iss = do_something()
   example = do_something_else()

   return some_long_name('maybe long string', {'this': iss,
                                               'an': example,
                                               'dictionary': 'wich is very long'})

But it still goes way beyond 80 characters. So I did a two step 'line continuation', but don't know if it's how it's done.

def some_func():
   iss = do_something()
   example = do_something_else()

   return some_long_name('maybe long string',
                         {
                             'this': iss,
                             'an': example,
                             'dictionary': 'wich is very long'
                         })

Or should it be something like:

def some_func():
   iss = do_something()
   example = do_something_else()

   return some_long_name('maybe long string',
                         {'this': iss,
                          'an': example,
                          'dictionary': 'wich is very long'})

I would appreciate some insight so I can maintain a better code because PEP8 doesn't explain it very well.


texts:
I made a function which creates Bezier curves of grade n. What do you think?

float interpolate(float n1, float n2, float prec)
{
    return n1 + ((n2-n1) * prec);
}

std::vector<Vector2f> make_bezier(const std::vector<Vector2f>& anchors, double accuracy=10000.0)
{
    if(anchors.size()<=2)
        return anchors;

    std::vector<Vector2f> end;
    end.push_back(anchors[0]);

    for(float i=0.f; i<1.f; i+=1.f/accuracy)
    {
        std::vector<Vector2f> temp;
        for(unsigned int j=1; j<anchors.size(); ++j)
            temp.push_back(Vector2f(interpolate(anchors[j-1].x, anchors[j].x, i),
                                    interpolate(anchors[j-1].y, anchors[j].y, i)));

        while(temp.size()>1)
        {
            std::vector<Vector2f> temp2;

            for(unsigned int j=1; j<temp.size(); ++j)
                temp2.push_back(Vector2f(interpolate(temp[j-1].x, temp[j].x, i),
                                         interpolate(temp[j-1].y, temp[j].y, i)));
            temp = temp2;
        }
        end.push_back(temp[0]);
    }

    return end;
}


texts: Simple stack implementation using linked list

texts:
Please review my Stack using linked list:

template<class T>
struct Node {
    T item;
    Node* next;
    Node(T t = {}, Node* link = nullptr) :item{t}, next{link} { }
    ~Node() { delete next; }
};

template<class T>
class Stack {
public:
    int size() const { return n; }
    bool empty() const { return n == 0; }
    void push(const T&);
    T pop();
    T peek();
private:
    Node<T>* first;
    std::size_t n;
};

template<class T>
void Stack<T>::push(const T& t) {
    Node<T>* old{first};
    first = new Node<T>{t,old};
    ++n;
}

template<class T>
T Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    auto t = first->item;
    first = first->next;
    --n;
    return t;
}

template<class T>
T Stack<T>::peek() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    return first->item;
}

A few notes:

I would like to experiment to try to avoid allocating in the heap, but I really can't because I don't know how to keep the newly created and added node in push() alive.
Is it correct to use std::size_t when tracking the size of the stack?

I thought that since my Stack class acts like a handle to nodes, I thought I should write my own copy and move operations so I can avoid member-wise copying, but something very funny happens when I tested my Stack:

int main() {
    Stack<std::string> x{};
    x.push("str");
    x.push("tring");
    x.push("string");
    Stack<std::string> y = x;
    y.pop();
    std::cout << x.peek() << '\n';
    y.pop();
    std::cout << x.peek() << '\n';
    y.pop();
    std::cout << x.peek() << '\n';
    y.push("nox");
    std::cout << x.peek() << '\n';
    std::cout << x.size() << '\n';
    std::cout << y.size() << '\n';
}

When x.peek() is called the result is always "string", x.size() is 3 and y.size() is 1. It seems the default copy operation works correctly. I thought it shouldn't because first is a pointer so they should refer to the same elements.
So I did not write a copy and move operation because it seems the default operations work correctly but I really don't know why and how. Can anyone explain why?

How can I make this code better?


texts: Vector with move constructor and move assignment operator

texts:
Please verify whether the code for a move constructor and a move assignment operator is correct.

#include <iostream>
using namespace  std;

class MyVector {
    size_t m_Size;
    int* m_pInt;
public:`enter code here`
    ~MyVector()
    {
        delete[] m_pInt;
    }

    MyVector():m_Size(0), m_pInt(nullptr)
    {   }

    MyVector(int x)
    {
        m_Size = x;
        m_pInt = new int[m_Size];
        for (int i = 0; i < m_Size; ++i)
        {
            m_pInt[i] = i;
        }
    }

    void print() const
    {
        for (int i = 0; i < m_Size; ++i)
        {
            cout << m_pInt[i] << endl;
        }

    }

    MyVector(const MyVector& rhs)
    {
        m_Size = rhs.m_Size;
        m_pInt = new int[m_Size];
        for (int i = 0; i < m_Size; ++i)
        {
            m_pInt[i] = rhs.m_pInt[i];
        }
    }

    MyVector(MyVector&& rhs):m_Size(move(rhs.m_Size)), m_pInt(move(rhs.m_pInt))
    {
        rhs.m_Size = 0;
        rhs.m_pInt = nullptr;
    }

    MyVector& operator=(const MyVector& rhs)
    {
        if (this != &rhs)
        {
            if (m_pInt != nullptr)
            {
                delete m_pInt;
            }
            m_Size = rhs.m_Size;
            m_pInt = new int[m_Size];
            for (int i = 0; i < m_Size; ++i)
            {
                m_pInt[i] = rhs.m_pInt[i];
            }
        }
        return *this;
    }

    MyVector& operator=(MyVector&& rhs)
    {
        if (this != &rhs)
        {
            if (m_pInt != nullptr)
            {
                delete m_pInt;
            }
            m_Size = move(rhs.m_Size);
            m_pInt = move(rhs.m_pInt);
            rhs.m_Size = 0;
            rhs.m_pInt = nullptr;
        }
        return *this;
    }
};

int main()
{
    MyVector ob1(10);
    // Copy
    MyVector ob2;
    ob2 = ob1; // Asssignment operator
    MyVector ob3 = ob1; // Copy Ctr

    ob1.print();
    // Move
    MyVector ob4(move(ob1));
    MyVector ob5;
    ob5 = move(ob1);

    ob1.print();

    return 0;

}


texts: Initializing and managing many references in multithreaded control application

texts:
I have a large multi-window GUI program (implemented with MFC) that controls a variety of physics experiment apparatus. When the user starts the main function of the program (the "experiment" run), a large worker thread starts which needs references various singleton objects (generally one per piece of apparatus) to do it's work - in particular programming a variety of machines. These objects are in general managed by the windows which contain the GUI elements relative to those objects, and because they are tied to the GUI windows, they will always exist as long as the program is running. I'm struggling to figure out the best way to handle the references to these objects. What I've done in the past is just use raw pointers to these objects, but this seems like bad style so I'm looking at improvements.

My current scheme is having class structures like this:

#include "RF_Generator.h"
#include "AnalogOutputs.h"

struct MasterThreadInput
{
    MasterThreadInput(RfWindow& rfWin, AnalogOutputWindow& aoWin) :
        objA(winA.getObjA()),
        objB(winB.getObjB())
    {    }
    RfGenerator& rfSys;
    AnalogOutputs& aoSys;
}

class RfWindow : public CDialog
{
public:
    RfGenerator& getRfSys();
private:
    RfGenerator rfSys;
}

class AnalogOutputWindow : public CDialog
{
public:
    AnalogOutputs& getAoSys();
private:
    AnalogOutputs aoSys;
}

This then gets filled and used like this:

void startThread(RfWindow& rfWin, AnalogOutputWindow& aoWin)
{
    MasterThreadInput* input = new MasterThreadInput(rfWin, aoWin);
    // other checks on the input
    _beginthreadex( NULL, NULL, &MainExperimentThreadProcedure, input, NULL, NULL );
}

unsigned int __stdcall MainExperimentThreadProcedure( void* voidInput )
{
    MasterThreadInput* input = (MasterThreadInput*)voidInput;
    try
    {
        // And then do work.
        input->rfSys.programRfGeneration();
        input->aoSys.programAnalogOutputs();
        // etc.
    }
    catch (...)
    {
        // handle errors
    }
    delete input;
    return 0;
}

This example code should be very representative of the real thing, except that in the real thing there are 5 windows, many more objects to fill (about 15 in total), and a much more complicated thread procedure - it's a big worker thread. I thought about using smart pointers instead of references considering the seemingly awkward constructor needed to initialize the references, and since I was using raw pointers before these references. However, considering that I don't actually need the worker thread to manage the memory for these objects (the objects will exist as long as the windows do, and the windows will exist for the entire program), it seems that I should just try to avoid pointers all-together. Does this code follow best practices regarding managing memory and shared access in multitheaded c++ applications? Are there ways to improve on this organization? It's a very important part of the control system, so I'd like to get it right.


texts:
I am new to Angular. Am I following best practices here? I understand controllers should not do too much. My controller seems to have a lot of logic here. Can I do anything to improve it? It is just a basic ToDo App.

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

app.controller('FirstCtrl', function($scope, todos){
    $scope.todos = todos;

    $scope.todos.submit = function(){
        if ($scope.input == "" || $scope.input == undefined){
            return false;
        }
        else{
            $scope.todos.list.push({
                task:$scope.input,
                completed: false
            });
            $scope.input = "";
        }
    }

    $scope.clear = function(){
         $scope.todos.list = $scope.todos.list.filter(function(todo){
            return !todo.completed;
        });
    }

});

app.factory('todos', function(){
    var todos = {};

    todos.list = [];

    return todos;
})

app.directive('todo', function(){
    return {
        restrict: "E",
        templateUrl:'templates/todos.html',
        controller:'FirstCtrl as First'
    }
})


texts: Should my class "data" dependency be a repository, adapter or another pattern?

texts:
I have a class called CheckUserUltraSecretInformation that is kind of a Use Case in "clean architecture terms", this class has a dependency that is responsible for retrieving a couple of information from a cache "provider", such as Redis, this is a crucial business rule for this use case, in order for the user to retrieve its "ultra-secret information" the cached information must exist.
since "retrieving the data from the cache" it's a data layer, my first thought was to use the repository pattern, but that implicates that I also have an Entity or a "Domain Model" for this repository, the thing is: although I can picture a "CachedUserInformation" object and its properties I cannot see the CachedUserInformation as an entity, because it's not a "core" object of my application.
I feel like this is more of a rule of the use case than an entity, but I cannot just return an array of data from this "repository".
should I just call it CachedUserDataAdapter and return the CachedUserInformation object?
what are some good approaches for this scenario?
my code:
interface CachedUserDataRepository {
    function findByDocument(string $document): CachedUserInformation;
}

class CheckUserUltraSecretInformation {

    public function __construct(
        private CachedUserDataRepository $cachedDataRepository
    )
    {
    }

    public function Check(string $document)
    {
        $cachedUserData = $this->cachedDataRepository->findByDocument($document);

        if(empty($cachedUserData)) {
            throw new Exception('User Cached information not found, cannot proceed');
        }
    }
}

class CachedUserInformation {
    private string $id;
    private string $secretInformation;
}


texts: Factory to instantiate and configure Selenium WebDriver

texts:
I, also, need to know whether this is a valid implementation of the factory pattern.

The amount of effort which goes into configuring DriverFactory to simply get a WebDriver instance seems disproportionate to the point where I ask:  "is there not a better way?"

The main class code:

package dur.bounceme.net.SeleniumBase;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;

public class App {

    private static final Logger LOG = Logger.getLogger(App.class.getName());
    private Properties properties = new Properties();

    public static void main(String[] args) throws IOException {
        new App().initSelenium();
    }

    private void initSelenium() throws IOException {
        properties.loadFromXML(App.class.getResourceAsStream("/selenium.xml"));
        WebDriver webDriver = DriverFactory.getWebDriver(properties);  //is this factory and usage correct?
        HomePage homePage = new HomePage(webDriver);
        homePage.populateCatalogue();
    }
}

And my factory:

package dur.bounceme.net.SeleniumBase;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

public class DriverFactory {

    private static final Logger LOG = Logger.getLogger(DriverFactory.class.getName());

    private Properties properties = new Properties();
    private FirefoxBinary firefoxBinary = null;
    private FirefoxOptions firefoxOptions = null;
    private WebDriver webDriver = null;
    private URL url = null;
    private String driver = null;
    private String gecko = null;
    private final List<String> commandLineOptions = new ArrayList<>();

    private DriverFactory() {
    }

    private DriverFactory(Properties properties) throws MalformedURLException {
        this.properties = properties;
        loadProps();
        init();
    }

     static WebDriver getWebDriver(Properties properties) throws MalformedURLException {
        DriverFactory driverFactory = new DriverFactory(properties);
        return driverFactory.webDriver;
    }

    private void loadProps() throws MalformedURLException {
        LOG.fine(properties.toString());
        url = new URL(properties.getProperty("url"));
        driver = properties.getProperty("driver");
        gecko = properties.getProperty("gecko");
        String commandLineOption = properties.getProperty("option01");
        commandLineOptions.add(commandLineOption);
    }

    private void init() throws MalformedURLException {
        firefoxBinary = new FirefoxBinary();
        commandLineOptions.forEach((commandLineOption) -> {
            LOG.fine(commandLineOption.toString());
            firefoxBinary.addCommandLineOptions(commandLineOption);
        });
        System.setProperty(driver, gecko);
        firefoxOptions = new FirefoxOptions();
        firefoxOptions.setBinary(firefoxBinary);
        webDriver = new FirefoxDriver(firefoxOptions);
        webDriver.get(url.toString());
        LOG.fine(webDriver.getTitle());
        LOG.fine(webDriver.getCurrentUrl().toLowerCase());
    }

    void close() {
        webDriver.close();
    }

}

There seems no nice way to get around loading configuration from a file, which is then loaded.  But, it strikes me that I'm re-inventing the wheel of loading a props file for the purpose of configuring a Selenium WebDriver when I expect there's a tried-and-true approach.

Or, at least, more re-usable.

Although, what possible use there would be for multiple WebDriver instances is beyond me.  It would seem Selenium Grid would handle that question quite differently.


texts: How to optimize the for loop for finding a matching 2 string using fuzzywuzzy

texts:
I am getting the probability of a string being similar to another string in Python using fuzzywuzzy lib.

Currently, I am doing this using a for loop and the search is time consuming.

Below is working code :

from fuzzywuzzy import fuzz

with open('all_nut_data.csv', newline='') as csvfile:
   spamwriter = csv.DictReader(csvfile)
   mostsimilarcs = 0
   mostsimilarns = 0
   for rowdata in spamwriter:
       mostsimilarns = fuzz.ratio(rowdata["Food Item"].lower(), name.lower())
       if mostsimilarns > mostsimilarcs:
           mostsimilarcs = mostsimilarns
           row1 = rowdata

How I can optimize this code without for loop?

Note* CSV file contain 600,000 rows and 17 column


texts: perform fuzzy matching on a large set of dictionary keys

texts:
Any suggestions on improving the speed of below code. My dictionary is rather large in fold of * 100000 and expected to grow larger every day.
I am open to completely new ideas or approaches to do the below operation.
from pyxdameraulevenshtein import damerau_levenshtein_distance, normalized_damerau_levenshtein_distance
name = 'john doe'

word_dict = {
              'john' : ['ID1','ID2', 'AB2' ,'AS1']
             ,'doe' : ['ID1','ID4', 'AB2' ,'AS6']
             ,'jahn' : ['ID3','ID2', 'AB2' ,'AS5']
             }
# perform iteration on dictionary keys . compute and filter if damerau edit distance is less than 2
all_matches = []
for nWord in set(name.split()):
    match = []
    match += [(word,list(word_dict[word]), int((1-normalized_damerau_levenshtein_distance(nWord,word))* 100))\
    for word in word_dict if damerau_levenshtein_distance(nWord,word) in [0,1,2]]
    all_matches.append(match)


texts:
I am hiding and fading in different content on the same page using jQuery to hide() and fadeIn() the content depending on which link is clicked.

It works how I want it to, but the way I've written the jQuery looks like it could be simplified.

$("#navItem1").on('click', function(){
    $('#content-wrap1').hide();
    $('#content-wrap2').hide();
    $('#content-wrap3').hide();
    $('#content-wrap4').hide();
    $('#content-wrap5').hide();
    $('#content-wrap1').fadeIn(1000);
});
$("#navItem2").on('click', function(){
    $('#content-wrap1').hide();
    $('#content-wrap2').hide();
    $('#content-wrap3').hide();
    $('#content-wrap4').hide();
    $('#content-wrap5').hide();
    $('#content-wrap2').fadeIn(1000);
});
$("#navItem3").on('click', function(){
    $('#content-wrap1').hide();
    $('#content-wrap2').hide();
    $('#content-wrap3').hide();
    $('#content-wrap4').hide();
    $('#content-wrap5').hide();
    $('#content-wrap3').fadeIn(1000);
});
$("#navItem4").on('click', function(){
    $('#content-wrap1').hide();
    $('#content-wrap2').hide();
    $('#content-wrap3').hide();
    $('#content-wrap4').hide();
    $('#content-wrap5').hide();
    $('#content-wrap4').fadeIn(1000);
});
$("#navItem5").on('click', function(){
    $('#content-wrap1').hide();
    $('#content-wrap2').hide();
    $('#content-wrap3').hide();
    $('#content-wrap4').hide();
    $('#content-wrap5').hide();
    $('#content-wrap5').fadeIn(1000);
});

function fadeInFirstContent(){
    $('#content-wrap1').fadeIn(1000);

}
fadeInFirstContent();

Here's a jfiddle

How can I rewrite the jQuery so it does exactly the same thing but in much less code?


texts:
I'm fairly new to Javascript and am writing a piece of code to create a filtering system for a portfolio grid (a grid of work examples that filter by category when a button is selected).

While the code works just fine, I feel like the way I'm writing it is overly clunky. Can someone please let me know if there's a way I can streamline/improve this code block?

Any help would be much appreciated - thanks! :D

var gridItem = document.querySelectorAll('.grid div');
var featuredItem = document.querySelector('.featured');
var filterBtn = document.querySelectorAll('.filter-btn');

function getAttributes(event) {
  event.preventDefault();

  var thisValue = event.target.getAttribute('data-filter');

  // Get grid item filter attributes
  for (let a = 0; a < gridItem.length; a++) {
    const gridFilterAttr = gridItem[a].getAttribute('data-filterType');
    if (thisValue == gridFilterAttr) {
      gridItem[a].classList.add('active')
      gridItem[a].classList.remove('not-active')
    } else if (thisValue == 'all') {
      gridItem[a].className = 'active';
      featuredItem.className = 'featured active'

    } else {
      gridItem[a].classList.remove('active')
      gridItem[a].classList.add('not-active')
    }
  }
}

for (let b = 0; b < filterBtn.length; b++) {
  filterBtn[b].addEventListener('click', getAttributes);

}

HTML:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Js Projects</title>
  <link rel="stylesheet" href="/assets/css/app.css">

    <button data-filter="all" class="filter-btn">All</button>
    <button data-filter="web" class="filter-btn">Web Project</button>
    <button data-filter="app" class="filter-btn">App</button>
    <button data-filter="ux" class="filter-btn">UX/UI</button>

Featured Item

Web item

App item

UX item

Web item

UX item

App item


texts: SICP - exercise 1.7 better end test for square root approximation

texts:
Here is exercise 1.7 from SICP:

  Exercise 1.7

  The good-enough? test used in computing square roots will not be very
  effective for finding the square roots of very small numbers. Also, in
  real computers, arithmetic operations are almost always performed with
  limited precision. This makes our test inadequate for very large
  numbers. Explain these statements, with examples showing how the test
  fails for small and large numbers. An alternative strategy for
  implementing good-enough? is to watch how guess changes from one
  iteration to the next and to stop when the change is a very small
  fraction of the guess. Design a square-root procedure that uses this
  kind of end test. Does this work better for small and large numbers?

I believe "a very small fraction of the guess" means guess*a-very-small-number. I think it is working correctly. I haven't found any values that could fail the good-enough? test. Is there something wrong here I haven't discovered? Please review my code. How can I improve it?

(define (sqrt x)
  (sqrt-iter 1.0 x))

(define (sqrt-iter guess x)
  (if (good-enough? guess (improve guess x))
      guess
      (sqrt-iter (improve guess x) x)))

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

(define (good-enough? guess next-guess)
  (< (abs (- guess next-guess)) (* guess 0.000000000000000000000000000001)))

(define (square x)
  (* x x))


texts:
I have a working C# code of a TCP server that runs inside a windows service. It accepts incoming connections and starts sending/receiving data based on some complex rules.

The top-level class for this server looks as follows:

public async void StartListen()
{
    var endpoint = new IPEndPoint(IPAddress.Parse(_host), _port);
    _serverSocket = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    _serverSocket.Bind(endpoint);
    _serverSocket.Listen((int)SocketOptionName.MaxConnections);

    while (!_shutdown)
    {
        var socket = await AcceptClient();
        ProcessTransaction(socket);
    }
}

private async Task<Socket> AcceptClient()
{
    var socket = await Task<Socket>.Factory.FromAsync(_serverSocket.BeginAccept, _serverSocket.EndAccept, null);
    return socket;
}

private void ProcessTransaction(Socket socket)
{
    Task.Factory.StartNew(() => ProcessTransactionAsync(socket));
}

private void ProcessTransactionAsync(Socket socket)
{
    // complex logic involving socket.Send, socket.Receive, serialization, etc...
}

The server is started by calling StartListen, and then it should run indefinitely (as long as the Windows service it is hosted in is up and running).

This code works, but I have certain doubts about it. I don't have much experience with TPL, but, for example, I know that async void method is an anti-pattern (as stated in many TPL tutorials). What problems can it cause? Are there any other flaws in this code? This server is supposed to handle high load somewhere in the future, so its speed and efficiency is also a concern.


texts: QuickSort in Java with Lomuto Partition or Hoare Partition

texts:
I have developed a quick sort in java, that can work with both Lomuto Partition Strategy, or Hoare Partition Strategy.

Both of them sort the array correctly.

I would like to have it code reviewed to ensure I was able to correctly implement each one of those partitioning strategies.

Is there any reason to use one vs the other?

Here it is:

public class QuickSort {

    public static void main(String... args) {
        int array[] = {2, 3, 4, 1, 11, 5, 7, 0, 10, -1, 99, 23};
        quickSort(array);
        System.out.println(Arrays.toString(array));
    }

    public static void quickSort(int array[]) {
        quickSort(array, 0, array.length - 1);
    }

    private static void quickSort(int array[], int l, int r) {
        if (l >= r) {
            return;
        }
        int p = lomutoPartition(array, l, r);//hoarePartition(array, l, r);//lomutoPartition(array, l, r);
        quickSort(array, l, p - 1);
        quickSort(array, p + 1, r);
    }

    private static int lomutoPartition(int array[], int l, int r) {
        //pivot chosen
        int pivot = array[r];
        int i = l - 1;
        for (int j = l; j < r; j++) {
            if (array[j] < pivot) {
                i++;
                swap(array, i, j);
            }
        }
        swap(array, i + 1, r);
        return i + 1;
    }

    private static int hoarePartition(int array[], int l, int r) {
        int pivot = array[r];
        int left = l;
        int right = r;
        while (true) {
            while (array[left] < pivot) {
                left++;
            }
            while (array[right] > pivot) {
                right--;
            }
            if (left >= right) {
                return left;
            }
            swap(array, left, right);
        }
    }

    private static void swap(int array[], int a, int b) {
        int temp = array[a];
        array[a] = array[b];
        array[b] = temp;
    }

}


texts:
I have a complex strings like the following:

$company=>Company(code->MyCompany)
$brand=>Brand(code->Brand_1, company->$company)

and then I prepare objects out of them as follows:

Macro [key=$company, type=Company, map={code=MyCompany}]
Macro [key=$brand, type=Brand, map={ company=$company, code=Brand_1}]

using the following code for parsing. Is there a better way?

public class Macro {

    private String key;

    private String type;

    private Map<String, String> map;
}

public static Macro getMacro(String str) {
    final Macro macro = new Macro();
    final Map<String, String> map = new HashMap<String, String>();
    final Matcher matcher = Pattern.compile("\\(([^)]+)\\)").matcher(str);
    while (matcher.find()) {
        final List<String> list = Arrays.asList(matcher.group(1).split(",")).stream()
                .collect(Collectors.toList());
        list.stream().forEach(a ->
        {
            final String[] ar = a.split("->");
            map.put(ar[0], ar[1]);
        });
    }
    str = str.replaceAll("\\(.*\\)", "");
    final String[] s = str.split("=>");
    macro.setMap(map);
    macro.setKey(s[0]);
    macro.setType(s[1]);
    return macro;
}


texts:
I'm implementing some mathematical functions right now for future use in more exciting things and wanted to know if I'm on the right track in my approach, as I don't have much C++ experience.

Here I'm offering my softmax function implementation.

#include <cmath>
#include <iterator>
#include <functional>
#include <numeric>
#include <type_traits>

template <typename It>
void softmax (It beg, It end)
{
  using VType = typename std::iterator_traits<It>::value_type;

  static_assert(std::is_floating_point<VType>::value,
                "Softmax function only applicable for floating types");

  auto max_ele { *std::max_element(beg, end) };

  std::transform(
      beg,
      end,
      beg,
      [&](VType x){ return std::exp(x - max_ele); });

  VType exptot = std::accumulate(beg, end, 0.0);

  std::transform(
      beg,
      end,
      beg,
      std::bind2nd(std::divides<VType>(), exptot));
}

Info on softmax

The softmax function is defined as

$$\text{softmax}(\mathbf{x})_{i} = \frac{\exp(x_{i})}{\sum_{j=1}^{n} \exp(x_{j})}$$

As mentioned in a comment, my reasoning for evaluating the softmax after subtracting the maximum of my vector is numerical stability. Consider the case where each element of my iterator is equal to some constant \$\alpha\$. If \$\alpha\$ is large and positive we might overflow or if large and negative we might underflow. Subtracting \$\max _{i} x_{i}\$, we ensure that the largest argument taken by \$\exp\$ is \$0\$ (so no overflow) and that at least one denominator term protects us from underflow leading to division by zero.

Thoughts while writing this

Is the static_assert a reasonable thing to check? The other thought I had was to use SFINAE which I don't know too much about. Like

template <typename Condition>
using EnableIf =
    std::enable_if_t<Condition::value>;

template <
  typename It,
  EnableIf<std::is_floating_point<
             typename std::iterator_traits<It>::value_type
             >
           >...
  >
void softmax(...)

What I liked about this approach that if I try to pass an iterator with a non-floating point type somewhere I get a nice immediate error recognition in my Emacs session for no function overload.. but I thought the static_assert might be better because there really is no other overload I have in mind for softmax - passing a non-floating iterator is really just an error.
Is there any possible issues / considerations when using the value type of the iterator like I am doing here?


texts:
Edit: added clarification for why I want this, and updated the code since I don't have any answers yet
I have a C++11 array-like class which (can be) a wrapper around a random-access iterator.  Index-based access and .begin()/.end() can just pass through to the iterator, but there's a bit of complication when the object is const:
    template<class Size, typename DataIterator>
    class Storage : public Size {
        DataIterator iterator;
    public:
        Storage(const DataIterator &iterator, const Size &size) : Size(size), iterator(iterator) {}

        auto operator[](index_t i)
                -> decltype(iterator[i]) {
            return iterator[i];
        }
        auto operator[](index_t i) const
                -> MakeConst<decltype(iterator[i])> {
            return iterator[i];
        }

        DataIterator begin() {return iterator;}
        ConstWrapper<DataIterator> begin() const {return iterator;}
        DataIterator end() {return iterator + this->size();}
        ConstWrapper<DataIterator> end() const {return iterator + this->size();}
    };

If we simply returned DataIterator from the const version of .begin() and .end(), then people holding a Storage const & would (incorrectly!) be able to modify the array through that iterator.
Containers like std::vector have two separate iterators (::iterator and ::const_iterator), but our Storage class only has the read-write one, so we synthesise one using ConstWrapper:
    template <typename Iterator>
    class ConstWrapper {
        Iterator iterator;

        using traits = std::iterator_traits<Iterator>;
    public:
        using difference_type = typename traits::difference_type;
        using value_type = typename traits::value_type;
        using pointer = ConstWrapper;
        using reference = MakeConst<typename traits::reference>;
        using iterator_category = typename traits::iterator_category;

        ConstWrapper() {}
        ConstWrapper(const Iterator &iterator) : iterator(iterator) {}

        // The problematic cases:
        auto operator[](index_t i) const
                -> MakeConst<decltype(iterator[i])> {
            return iterator[i];
        }
        auto operator*() const
                -> MakeConst<decltype(*iterator)> {
            return *iterator;
        }

        bool operator!= (const ConstWrapper& other) const {
            return iterator != other.iterator;
        }
        /** All the other random-access iterator methods **/
    };

    // Specialisation to prevent infinite loops
    template <typename Iterator>
    class ConstWrapper<ConstWrapper<Iterator>> : ConstWrapper<Iterator> {
    public:
        using ConstWrapper<Iterator>::ConstWrapper;
    };

The implementation forwards all the relevant methods, and has a specialisation for ConstWrapper<ConstWrapper<...>> so that it can't wrap itself.
A key part is MakeConst, which turns types into the correct const variant (unlike simply adding const, which has no effect on references):
    // Converts (T & -> T const &), and (T -> const T)
    using MakeConst = typename std::conditional<
        std::is_reference<T>::value,
        typename std::remove_reference<T>::type const &,
        const T
    >::type;

Does this make sense, and is it OK?  Is there something else I could be doing which is more readable/efficient/etc.?
Thanks!


texts:
Project Euler #3 asks:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

I've written a general solution for any number:
module Main where

isDiv :: Integer -> Integer -> Bool
n `isDiv` k = n `mod` k == 0

fullyDiv :: Integer -> Integer -> Integer
fullyDiv n k
    | n `isDiv` k = fullyDiv (n `div` k) k
    | otherwise = n

intSqrt :: Integer -> Integer
intSqrt = floor . sqrt . fromIntegral

maxPrimeFact :: Integer -> Integer
maxPrimeFact n = go n (1, wheel)
    where
        wheel = 2 : [3,5..intSqrt n]
        go n (x, []) = if n == 1 then x else n
        go n (x, (y:ys))
            | n `isDiv` y =
                let o = fullyDiv n y
                in go o (y, takeWhile (<= intSqrt o) ys)
            | otherwise = go n (x, ys)

problem3 :: Integer -> Integer
problem3 = maxPrimeFact

main :: IO ()
main = do
    _ <- getLine
    contents <- getContents
    let cases = map read $ lines contents
    let results = map problem3 cases
    mapM_ print results

An explanation of this algorithm can be found at my answer.
I'd appreciate any comments on rewriting maxPrimeFact as it seems unwieldy to me.


texts: Unit Test to verify number of times lazy initialization logic is executed for a data member

texts:
I'll write a small simulation of my actual class first to request insights on unit testing one of the behaviors of this class. Here is my class A:

public class A {
    private final String a;
    private final String b;
    private String c;

    public A(final String a, final String b) {
       this.a = a;
       this.b = b;
       this.c = null;
    }

    public getC() {
       if (this.c==null) {
          // Logic to compute value of this.c using this.a and this.b
          // set this.c
       }

       return this.c;
    }
}

In the above class I'm doing lazy initialization of a data member c. Responsibility of class A is to  compute this.c from this.a and this.b and cache it so that there is no need to compute it again on future invocation of getC. Class A has only this responsibility.

I want to write a unit test to verify that on Multiple invocations of getC() method on the same instance of class A, logic for computing this.c should be executed only once. Could anyone please help in figuring out, how can I write this unit test ? One way I can see is delegating the logic of computing this.c to another class B and then making class A dependent on class B so that a mock of class B can be injected during testing. After injection of mock of B, Mockito's feature to verify number of times method invocation happens on a mock can be used. But Class A has only one responsibility of computing this.c and delegating that responsibility to another object is looking like an overkill to me.


texts: Shuffle array elements by rearranging the key value associations

texts:
PHP's shuffle() function destroys the array keys, so I decided to write a shuffle function that doesn't do that and instead rearranges key-value associations. As I would be using the function in place of shuffle() most of the time, I'd like it to be as fast and memory efficient (if a time-space tradeoff is needed, I think I would prioritise time) as possible:

<?
    function swap(&$a, &$b)
    {
        $tmp = $a;
        $a = $b;
        $b = $tmp;
    }

    function shuffleX(&$arr)    #Shuffles the key-value associations in an array.
    {
        $keys = array_keys($arr);   #extract the keys from the array.
        $length = count($keys);
        $i = 0; #Index.
        while ($i < $length-1)
        {
            $target = rand(($i+1), $length-1);  #This ensures that no value ends up mapped to the same key.
            swap($arr[$keys[$i]], $arr[$keys[$target]]);    #Swap each element of the array with another.
            $i++;
        }
    }
?>


texts: Get file absolute path from file URL in PHP

texts:
Reading several questions regarding the topic, I made my function to return file's absolute path from the file URL. As I'm using this in an WordPress environment, hence I availed untrailingslashit() in it.

/**
 * Get file absolute path from URL.
 *
 * @author  carlosveucv
 * @link    https://stackoverflow.com/a/17744219/1743124
 *
 * @param   string $file_url File URL.
 * @return  string           File path.
 * --------------------------------------------------------------------------
 */
function wp20171021_get_file_path_from_url( $file_url ) {
    $file_path = parse_url( $file_url, PHP_URL_PATH );
    return wp_normalize_path( $_SERVER['DOCUMENT_ROOT'] . $file_path );
}

How bulletproof is this?
What kind of caveats this might have in real world?
I tested this in Windows, so is it 'cross platform-friendly?


texts:
public static GeneratePassword(minPassLength) {
    let small = "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".split(' ');
    let big = "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".split(' ');
    let numbers = "0 1 2 3 4 5 6 7 8 9".split(' ');
    let special = "! \" # $ % & ( ) * + - . : ; < = > ? @ [ \ ] _ { | }".split(' ');

    var pass = "";
    for (let i = 0; i < minPassLength; i++) {
      pass += small[this.randomIntFromInterval(0, small.length - 1)];
    }
    for (let i = 0; i < minPassLength / 4; i++) {
      pass += big[this.randomIntFromInterval(0, big.length - 1)];
    }
    for (let i = 0; i < minPassLength / 4; i++) {
      pass += numbers[this.randomIntFromInterval(0, numbers.length - 1)];
    }
    for (let i = 0; i < minPassLength / 4; i++) {
      pass += special[this.randomIntFromInterval(0, special.length - 1)];
    }
    pass = pass.split('').sort(function () { return 0.5 - Math.random() }).join('');
    return pass;
 }

  private static randomIntFromInterval(min, max) // min and max included
  {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

A simple function to generate a new password with at least X (this is function parameter) chars including 1 special, 1 number and 1 uppercase.

Please a code review :-)


texts: Getting multiple inputs from single EditText

texts:
This is an Android app and there is a EditText box, and I need to accept multiple types of inputs one after another in order. This order is predefined. On USER_INP_NAME object newUser is created. After this multiple properties are set with this object. Finally on USER_INP_STATE the object is added to a list. This cycle repeats.

I am a "C" programmer, so this is coded in procedure-oriented manner. The switch case is looking ugly for now.  Is there a better solution to do this ?

userInputs.setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                int val = (Integer) userInputs.getTag();
                switch (val) {
                case USER_INP_NAME:
                    newUser = new Users();
                    newUser.setUsersName(userInputs.getText()
                            .toString());
                    userInputs.setTag(USER_INP_NUMBER);
                    userInputs.setText("");
                    userInputs.setHint("User Name");
                    break;
                case USER_INP_NUMBER:
                    newUser.setUnitWeight(Integer
                            .parseInt(userInputs.getText().toString()));
                    userInputs.setTag(USER_INP_STATE);
                    userInputs.setText("");
                    userInputs.setHint("User Number");
                    break;
                case USER_INP_STATE:
                    newUser.setShelfLife(Integer
                            .parseInt(userInputs.getText().toString()));
                    userInputs.setTag(USER_INP_NAME);
                    userInputs.setText("");
                    userInputs.setHint("User State");
                    uList.add(newUser);
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
                }

            default:
                break;
            }
        }
        return false;
    }
});


texts: Basic API wrapper around a Restful service

texts:
I'm writing a basic wrapper around a restful service that returns a list of Stores. I'm using RestSharp which I'm injecting into the class.

Naturally, I want to make it completely testable (that's a major requirement!).

I'm also thinking that it could be more generic i.e. GetStores but I'm struggling how to do as I need to specify things like the RootElement.

public class TopManClient : ITopManClient
{
    private readonly IRestClient _restClient;
    private const string BaseUrl = "https://TopmanStores.Api.com/";
    private const string AcceptTenant = "uk";
    private const string AcceptLanguage = "en-GB";

    public TopManClient(IRestClient restClient)
    {
        _restClient = restClient;

        _restClient.BaseUrl = new Uri(BaseUrl);
        _restClient.AddDefaultHeader("Accept-Tenant", AcceptTenant);
        _restClient.AddDefaultHeader("Accept-Language", AcceptLanguage);
    }

    public IRestRequest GetRequest(string url)
    {
        return new RestRequest(url, Method.GET);
    }

    public List<Store> GetStores(string postCode)
    {
        var request = GetRequest("stores");
        request.RootElement = "Stores";
        request.AddQueryParameter("q", postCode);

        var response = _restClient.Execute<List<Store>>(request);

        if (response.ErrorException != null)
        {
            const string message = "Error retrieving response. Check inner details for more info.";
            throw new ApplicationException(message, response.ErrorException);
        }

        return response.Data;
    }
}


texts: Simpler version of capitalizing each word in a string

texts:
I have this code which does the job, however it seems to me that the same could be done with less code. And why if I put 'var newString = stored.join(' ');' below 'var stored=[];' the code doesn't work?

function titleCase(str) {

var lower = str.toLowerCase();

var arr = lower.split(' ');

var stored = [];

//takes a string from arr
for(var i = 0; i<arr.length; i++) {

 //splits and stores the string to letters
   var word = arr[i].split(''); // ['l','i','t'...]

    // takes the first letter from the array and makes it uppercase
   for(var k=0; k<1; k++){
   var upper = word[k].toUpperCase();
   word.shift();
   word.unshift(upper);
   var joined = word.join('');
   stored.push(joined);
}

}
 var newString = stored.join(' ');

 return newString;

}

 titleCase("I'm a little tea pot");


texts:
I have two database tables UsersDownload, Non-UsersDownload. There is also two model object and two service that take in the object and insert the data into the correct table. Is this the best architecture for this? or is there a better way to handle this? Would it be better to use an interface?

public class UserLog
{
    public string CustomerId { get; set; }
    public bool? IsMobile { get; set; }
    public int? DeviceId { get; set; }
}
public class NonUserLog
{
    public string DeviceId { get; set; }
    public bool? IsMobile { get; set; }
    public string AppType { get; set; }
}

insert using Store Procedure

 internal ResultStatus UsersDownload(UserLog userLog)
        {
            queryName = "usp_Insert_UserLog";
            SQLHelper sql = new SQLHelper(conn);
            ResultStatus rs = new ResultStatus();
            SqlParameter[] parms = new SqlParameter[] {
                            new SqlParameter("@CustomerID", SqlDbType.NVarChar, 50),
                            new SqlParameter("@IsMobile", SqlDbType.Bit),
                        new SqlParameter("@DeviceId", SqlDbType.Int)
            };

            parms[0].Value = guidelineLog.CustomerId;
            parms[1].Value = guidelineLog.IsMobile;
            parms[2].Value = guidelineLog.DeviceId;

            using (SqlDataReader dataReader = sql.ExecuteReaderStoreProcedure(queryName, parms))
            {
                rs.ResultCode = 1;
                rs.ResultMessage = "Success";
                dataReader.Close();
            }

            return rs;
        }
 internal ResultStatus NonUsersDownload(NonUserLog nonUserLog)
        {
            queryName = "usp_Insert_NonUserLog";
            SQLHelper sql = new SQLHelper(conn);
            ResultStatus rs = new ResultStatus();
            SqlParameter[] parms = new SqlParameter[] {
                            new SqlParameter("@DeviceId", SqlDbType.NVarChar, 50),
                            new SqlParameter("@IsMobile", SqlDbType.Bit),
                        new SqlParameter("@AppType", SqlDbType.NVarChar)
            };

            parms[0].Value = guidelineLog.DeviceId;
            parms[1].Value = guidelineLog.IsMobile;
            parms[2].Value = guidelineLog.AppType;

            using (SqlDataReader dataReader = sql.ExecuteReaderStoreProcedure(queryName, parms))
            {
                rs.ResultCode = 1;
                rs.ResultMessage = "Success";
                dataReader.Close();
            }

            return rs;
        }

service

public ResultStatus InsertUsersDownload(UserLog userLog)
        {
            return glDb.UsersDownload(userLog);
        }

        public ResultStatus InsertNonUsersDownload(NonUserLog nonUserLog)
        {
            return glDb.NonUsersDownload(nonUserLog);
        }


texts:
I writing some specific poker equity calculator. Basically, equity calculator tells how much one hand is more profitable than other. I have written such calculator and it works, works fast, but there is a one not optimal place where a lot of time is spent and it definitely can be optimized. I am asking you about the advice how to optimize it.

Below is the simplified structure of poker equity calculator. For sample purpose, I have made it for the game when both Players hands contain one from 52 cards, 4 cards are on board(turn), one(river) board card left. Let say that player who's sum of the board and hand card is higher - wins.

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <ctime>
#include <string>

using namespace std;

static const int card_count = 52;

// Checks that board contains the card. A lot of time spent here. Need to be optimized.
bool Contains(const std::vector<int>& board, int card)
{
    for (int boardCard : board)
    {
        if (boardCard == card)
        {
            return true;
        }
    }

    return false;
}

// Fake function that evaluates hand strength. This is just for example real evaluator is different. So no need to optimize this.
size_t GetHandStrength(const std::vector<int>& board, int card, int b)
{
    size_t stren = 0;

    for (int boardCard : board)
    {
        stren += boardCard;
    }

    return stren + card + b;
}

// Returns equity for the board
float GetEquity(const std::vector<int>& board)
{
    float equity = 0;

    for (int c1 = 0; c1 < card_count; c1++) // Player1 card
    {
        if (Contains(board, c1))
        {
            continue;
        }

        for (int c2 = 0; c2 < card_count; c2++)  // Player2 card
        {
            if (c1 == c2 || Contains(board, c2))
            {
                continue;
            }

            size_t usedBoards = 0; // number of boards are possible for this players and board cards
            float currentEquity = 0;

            for (int b = 0; b < card_count; b++) // Iterating river board cards
            {
                if (Contains(board, b))
                {
                    continue;
                }

                if (b == c1 || b == c2) // Check that there are no conflict with players cards
                {
                    continue;
                }

                size_t p1stren = GetHandStrength(board, c1, b);
                size_t p2stren = GetHandStrength(board, c2, b);

                if (p1stren > p2stren)
                {
                    currentEquity += 1.0;
                }
                else if (p1stren < p2stren)
                {
                    currentEquity -= 1.0;
                }

                usedBoards++;
            }

            currentEquity /= usedBoards;
            equity += currentEquity;
        }
    }

    return equity;
}

int main()
{
    clock_t begin = clock();
    std::vector<int> board = { 0, 1, 2, 21 }; // Some turn random board (4 cards)
    float equity = GetEquity(board);;
    cout << "equity: " << equity <<  endl;
    return 0;
}

When iterating over the hand and board cards I need to check that board doesn't already contains the card, so I need to iterate over the board cards again and again. This is done by the bool Contains(const std::vector<int>& board, int card) also checks like if (b == c1 || b == c2) What can you suggest to optimize this part?


texts:
I know that there are several ways to develop the MVC pattern. To improve consistently my knowledge, I would like to get some advice and feedback. How could I enhance my code? I knew that there are several lines of code, but it would be great if you help me improve my skills.

The Model store the object Person and notify the view if there are any changes. The view implements the interface IModelPersonObserver to receive the notification. The view notify the controller about any changes. The controller starts a new task for long calculations. The result is passed to the model.

To pass different events I am able to use multiple events, like ModelHandler and ViewHandler based on the real action or just one event and extend the EventArgs class.

IModelPerson

public delegate void ModelHandler<IModelPerson>(IModelPerson sender, ModelEventArgs e);

public class ModelEventArgs : EventArgs
{
    public Person person;
    public ModelEventArgs(Person p) { person = p; }
}

public interface IModelPersonObserver
{
    void Add(IModelPerson model, ModelEventArgs e);
}

public interface IModelPerson : IModel
{
    void Add(Person person);

    void Remove(Person person);

    void Observe(IModelPersonObserver obsever);
}

ModelPerson

public class ModelPerson : IModelPerson
{
    private readonly ArrayList persons = new ArrayList();

    public event ModelHandler<ModelPerson> change;

    public void Add(Person person)
    {
        this.persons.Add(person);
        this.change.Invoke(this, new ModelEventArgs(person));
    }

    public void Remove(Person person)
    {
        this.persons.Remove(person);
    }

    public void Observe(IModelPersonObserver obsever)
    {
        this.change += obsever.Add;
    }
}

IView

public interface IView
{
    Controller Controller { set; }
}

IViewPerson

public delegate void ViewHandler<IViewPerson>(IViewPerson sender, ViewEventArgs e);

public class ViewEventArgs: EventArgs
{
    public Person person;
    public ViewEventArgs(Person p) { person = p; }
}

public interface IViewPerson : IView
{
    event ViewHandler<IViewPerson> change;
}

ViewPerson

public partial class ViewPerson : Form, IViewPerson, IModelPersonObserver
{
    private Controller controller;

    public event ViewHandler<IViewPerson> change;

    public ViewPerson()
    {
        InitializeComponent();
    }

    public Controller Controller
    {
        set { this.controller = value; }
    }

    private void button1_MouseClick(object sender, MouseEventArgs e)
    {
        var person = new Person();
        person.Name = "Name";
        person.Surname = "Surname";

        this.change.Invoke(this, new ViewEventArgs(person));
    }

    public void Add(IModelPerson model, ModelEventArgs e)
    {
        MessageBox.Show("e");
    }
}

Controller

public abstract class Controller
{
    protected readonly IModel model;

    protected readonly IView view;

    protected Controller(IModel model, IView view)
    {
        this.model = model;
        this.view = view;

        this.view.Controller = this;
    }
}

ControllerPerson

public class ControllerPerson : Controller
{
    private static ModelPerson modelPerson;

    public ControllerPerson(ModelPerson model, ViewPerson view) : base(model, view)
    {
        ControllerPerson.modelPerson = model;
        ControllerPerson.modelPerson.Observe(view);

        view.change += ViewOnChange;
    }

    private static void ViewOnChange(IViewPerson sender, ViewEventArgs viewEventArgs)
    {
        Task.Factory.StartNew(() => Add(viewEventArgs.person));
    }

    private static void Add(Person state)
    {
        Thread.Sleep(5000);
        ControllerPerson.modelPerson.Add(state);
    }
}

What do you think?


texts:
I've written the following function to produce n realizations of a CIR process for a given set of parameters:
def cir_simulations(alpha, mu, sigma, delta_t, n, num_sims):

    x = np.reshape(np.array([mu] * num_sims), (-1, 1))

    for i in range(0, n):
        x = np.concatenate((x, np.reshape(x[:, -1], (-1, 1)) + alpha * (
                    mu - np.reshape(x[:, -1], (-1, 1))) * delta_t + sigma * np.sqrt(
            np.reshape(x[:, -1], (-1, 1))) * np.sqrt(delta_t) * np.random.normal(0, 1, size=(num_sims, 1))), axis=1)

    return x

This code works, but I am now wondering whether it would be possible to remove the loop and fully vectorize it. I've struggled to find a way of doing this, as the operation being performed in the loop is recursive (the values in the next column of the matrix are non-linearly dependent on the previous columns values).
Additionally, could this code be simplified? In particular, I feel like there may be needless complexity in the way that I am accessing the last column of the array using
np.reshape(x[:, -1], (-1, 1))


texts: Call WebAPI then parse part of json result

texts:
this is a basic web api call using HttpClient and parse some part of the result, this was working as expected, but the part inside the if (response.IsSuccessStatusCode) doesnt seems right. It feels like it can be simplified, but I don't know how.

static async Task<List<Hero>> GetHero(string url, string urlParameters)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    using (var response = client.GetAsync(urlParameters).Result)
    {
        if (response.IsSuccessStatusCode)
        {
            var heroes = new List<Hero>();
            var jsonResult = await response.Content.ReadAsStringAsync();
            var deserializedjsonResult = JObject.Parse(jsonResult);
            var resultHeroes = deserializedjsonResult["result"]["heroes"].ToList();

            resultHeroes.ForEach(x => heroes.Add(x.ToObject<Hero>()));

            return heroes;
        }
    }

    return null;
}

the api that I was calling will return something in this format

{
  "result": {
    "heroes": [
      {
        ...
      },
      {
        ...
      }
    ],
    "villains": [
      {
        ...
      },
      {
        ...
      }
    ],
    "extras": [
      {
        ...
      },
      {
        ...
      }
    ],
  }
}


texts:
Looking for tips on how to improve my code and areas that I can better follow Object Orientated principles. Is this class structure ok? How is the code overall?

The problem: There are two IBAN standards: IBAN-10 and IBAN-13. IBAN-10 is made up of 9 digits plus a check digit. IBAN-13 is made up of 12 digits plus a check digit. Spaces and hyphens may be included in a code but are not significant.

The check for IBAN-10 is calculated by multiplying each digit by its position, summing these products together and taking the modulus 11 of the result. Substituting X if the result is 10.

The check digit for IBAN-13 is calculated by multiplying each digit alternately by 1 or 3, summing these products together and taking the modulus 10 of the result and subtracting this value from 10. Then with this result take the modulus of ten so as to reduct the number to a single digit.

Return true if it is a valid IBAN-10/IBAN-13

class IBAN

  def initialize(number)
    puts "number: #{number}"

    @number = number
    @number.gsub!(/[^0-9]/i, '')
    return @number
  end

  def number
    @number
  end

  # # check IBAN length and if valid proceed to process IBAN type
  def check_number_format
    iban_length = self.number.length

    unless iban_length == 10 || iban_length == 13
      puts "Not a valid IBAN - incorrect length"
      return false
    else
      self.validate_iban_type
    end
  end

  def validate_iban_type
    case self.number.length
    when 10
      @iban_ten = IBANTEN.new(self.number)
      @iban_ten.process_ten_digit_iban
    when 13
      @iban_thirteen = IBANTHIRTEEN.new(self.number)
      @iban_thirteen.process_thirteen_digit_iban
    else
      return false
    end
  end
end

class IBANTEN

  def initialize(iban_number)
    @iban_number = iban_number
  end

  def iban_number
    @iban_number
  end

  def process_ten_digit_iban
    number_split = self.iban_number.split('')
    final_digit = number_split[-1]
    running_total = 0

    number_split[0, (number_split.length - 1)].each_with_index do |num, index|
      # multiply each digit by its position
      sum = num.to_i * (index.to_i + 1)
      running_total += sum.to_i
    end
    # get the modulus of the running total if it exuals 10 replace it with X otherwise return the result
    digit_sum_total = running_total % 11
    calculated_result = digit_sum_total == 10 ? "X" : digit_sum_total

    if calculated_result == final_digit.to_i
      puts "Valid IBAN-10 Number"
      return true
    else
      puts "Invalid IBAN-10 Number"
      return false
    end
  end

end

class IBANTHIRTEEN

  def initialize(iban_number)
    @iban_number = iban_number
  end

  def iban_number
    @iban_number
  end

  def process_thirteen_digit_iban
    number_split = self.iban_number.split('')
    final_digit = number_split[-1]
    running_total = 0

    number_split[0, (number_split.length - 1)].each_with_index do |num, index|
      # if the remainder equals zero multiply by 1 otherwise multiplu by 3
      sum = (index % 2 == 0 ) ? num.to_i * 1 : num.to_i * 3
      running_total += sum.to_i
    end
    # modulo 10 of the result and subtracting this value from 10, and then taking the modulo 10 of the result again to produce a single digit
    calculated_result = ( (10 - (running_total % 10) ) % 10)

    if calculated_result == final_digit.to_i
      puts "Valid IBAN-13 Number"
      return true
    else
      puts "Invalid IBAN-13 Number"
      return false
    end
  end
end

@iban_v13_valid = IBAN.new("978 0 471 48648 0")
@iban_v13_valid.check_number_format

@iban_v13_invalid = IBAN.new("9780470059021")
@iban_v13_valid.check_number_format

@iban_v10_valid = IBAN.new("0 471 60695 2")
@iban_v10_valid.check_number_format

@iban_v10_invalid = IBAN.new("0-470-84525-6")
@iban_v10_invalid.check_number_format

@iban_invalid_length = IBAN.new("0-470-84525-618423")
@iban_invalid_length.check_number_format


texts: Name Mashup Program Improvement in Python

texts:
I am learning python and trying to solve different problems i came across this program which is name mashup which is in Get Programming:Learn to code with Python.

problem statement: Write a program that automatically combines two names given by
the user. That’s an open-ended problem statement, so let’s add a few more details and restrictions:

Tell the user to give you two names in the format FIRST LAST. Show the user two possible new -names in the format FIRST LAST.
The new first name is a combination of the first names given by the user, and the new last name is a combination of the last names given by the user.

For example, if the user gives you Alice Cat and Bob Dog, a possible mashup is Bolice Dot.

I'd like to know is there any way to improve this program like using functions to make this program better.

    print('Welcome to the Name Mashup Game')

name1 = input('Enter one full name(FIRST LAST): ')
name2 = input('Enter second full name(FIRST LAST): ')

space = name1.find(" ")
name1_first = name1[0:space]
name1_last = name1[space+1:len(name1)]
space = name2.find(" ")
name2_first = name2[0:space]
name2_last = name2[space+1:len(name2)]
# find combinations
name1_first_1sthalf = name1_first[0:int(len(name1_first)/2)]
name1_first_2ndhalf = name1_first[int(len(name1_first)/2):len(name1_first)]
name1_last_1sthalf = name1_last[0:int(len(name1_last)/2)]
name1_last_2ndhalf = name1_last[int(len(name1_last)/2):len(name1_last)]

name2_first_1sthalf = name2_first[0:int(len(name2_first)/2)]
name2_first_2ndhalf = name2_first[int(len(name2_first)/2):len(name2_first)]
name2_last_1sthalf = name2_last[0:int(len(name2_last)/2)]
name2_last_2ndhalf = name2_last[int(len(name2_last)/2):len(name2_last)]

new_name1_first = name1_first_1sthalf + name2_first_2ndhalf
new_name1_last = name1_last_1sthalf + name2_last_2ndhalf
new_name2_first = name2_first_1sthalf + name1_first_2ndhalf
new_name2_last = name2_last_1sthalf + name1_last_2ndhalf

# print results
print(new_name1_first, new_name1_last)
print(new_name2_first, new_name2_last)


texts:
I was practicing for the upcoming zco in CodeChef, where I came across this problem:

  Given some number \$K\$ and a list of \$N\$ numbers, count the number of pairs (\$i\$, \$j\$) such that \$1 \le i \lt j \le N\$ and \$|a_i − a_j | \ge K\$.

  \$1 \le N \le 65000\$
  \$1 \le K \le 10^8\$
  \$0 \le a_i \le 10^8\$

I got the algorithm correct for \$N \le 4000\$, but for \$N \le 65000\$, it failed to compute in the given time limit.

#include <iostream>
#include <vector>
#include <sstream>
#include <cmath>
#include <cstdio>

using namespace std;

vector<int>split(string s){
    stringstream ss(s);
    string item;
    vector<int> elems;
    while(getline(ss,item,' ')){
        elems.push_back(stoi(item));
    }
    return elems;
}

int main(){
    string one,two;
    getline(cin,one);
    getline(cin,two);

    vector<int> testCases = split(one);
    vector<int> nums = split(two);

    int args = testCases[0];
    int k = testCases[1];
    int cases = 0;

    for(int i=0;i<args-1;i++){
        for(int j=1;j<nums.size();j++){
            int temp = abs(nums[0]-nums[j]);
            if(temp >= k){
                cases++;
            }
        }
        nums.erase(nums.begin());
    }

    printf("%i\n",cases);
    return 0;
}

I tried to use the printf instead of std::cout, because I read somewhere that it is much faster than the latter, but the result was same. How can I overcome the TLE? I also tried some few more tricks but they somehow altered the algorithm as a result they were giving wrong outputs.


texts:
I've a function to generate random characters from a set of alphabets. This function would be called multiple times and thus I'm trying to make it use same set of variables, i.e. have same seed so that strings don't repeat as long as possible.

#include <iostream>
#include <random>
#include <string>

std::string generateRandomChar(const unsigned int _len)
    {
        std::string result;
        result.reserve(_len);

        static constexpr char alphanum[] = "0123456789"
                                           "abcdefghijklmnopqrstuvwxyz"
                                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, 61);

        for (int i = 0; i < _len;
            result += (alphanum[dis(gen)]);
        }
        return result;
    }

int main(){
    for(int i = 0; i < 10; ++i){
        std::cout << generateRandomChar(10) << std::endl;
    }
}

Unfortunately I don't have any expertise with C++11 <random> functions and I was only using srand and friends earlier, so I might be making lots of mistakes here. Currently it works and generates tons of strings without repeating, but I'm sure I could make either of:

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 61);

static variable too, so that it isn't calculated each time the function is called because that would be waste right?

So which one should be static here? Are there any mistakes/improvements that you see here?

Ideone


texts:
I have this JavaScript to make a sidebar widget stick to a fixed position once the page is scrolled down, once you scroll to the bottom of the page where the footer div is I then un-sticky it so that the stickied div does not overlap the footer.

It works great but I am not very good with JavaScript, so I am hoping to clean it up because it looks sloppy.

JavaScript

$(window).load(function () {
/*-----------------------*/
 * Fixed Widget on Scroll
 *-----------------------*/

    // set some Div vars
    var stickyID = $("#sticky-scroll-wrapper"),
        footerID = $('#footer'),
        stickyDivHeight = stickyID.outerHeight(),
        stickyIDMargin = 70;

    $(window).scroll(function () {
        var currentPosition = $(document).scrollTop() + stickyIDMargin;
        var stickyIDPosition = stickyID.offset().top;

        // cut off point/un sticky when we reach this far down the page
        var limit = footerID.offset().top - stickyDivHeight;

        //determines whether sidebar should stick and applies appropriate settings to make it stick
        if (currentPosition >= stickyIDPosition && currentPosition < limit) {
            $('#sticky-elements').css({
                'position': 'fixed',
                'top': '70px'
            });
        } else {
            $('#sticky-elements').css({
                'position': 'static',
            });
        }
        // Un-stick once we reach the #fotter section of the page to prevent overlapping
        if (limit < currentPosition) {
            var diff = limit - currentPosition;
            $('#sticky-elements').css({
                'top': diff + stickyIDMargin,
                'position': 'fixed',
            });
        }

    });

});

HTML

sidebar content


texts: Counting the elements of one array that are less than or equal to some other numbers

texts:
I have a method which compares two array О(n2), maxes with each element in nums against <= condition then it prints out the new array with total count for each case, but it's too slow for large arrays, what's the most efficient way to solve this problem?

def counts(nums, maxes)
  total = 0
  total_array = []

  maxes.each do |m|
    nums.each do |n|
      if n <= m
        total += 1
      end
    end

    total_array.push(total)

    total = 0
  end

  total_array
end

nums = [2,10,5,4,8]
maxes = [3,1,7,8]

print counts(nums, maxes) => # [1,0,3,4]

# Explanation:

# 1. maxes[0] >= nums[0]
# 2. maxes[1] >= 0
# 3. maxes[2] >= nums[0], nums[2], nums[3]
# 4. maxes[3] >= nums[0], nums[2], nums[3], nums[4]


texts: Count number of ways to construct binary search tree with n elements

texts:
I had this question asked in an interview:

  In how many ways, we can construct binary search tree from \$n\$ elements?

I have written this code, but got a feedback that it could be improved. How to do it?

def count_ways(n):
    c = [0] * (n+1)
    c[0] = 1
    c[1] = 1
    for i in xrange(2, n+1):
        sum_w = 0
        for j in xrange(0, i):
            sum_w += c[j] * c[i-j-1]
        c[i] = sum_w
    return c[n]

print count_ways(4)


texts:
I am trying to create a web app (CMS) as part of my research project, and I use the code below to load modules into a page.  Please review this code.

public function LoadModule($module,$position){

    if(file_exists('modules/'.$module.'.tpl'))
    {
        //todo: might have to get a better thing for this !
        $mod = 'modules/'.$module.'.tpl';
        ob_start();
        include($mod);
        $mod = ob_get_clean();

        $this->html = str_replace('__{'.$position.'}__', $mod ,$this->html);
    }
    else{
        if(function_exists('LOGIT')){

            LOGIT('$module - module not found.');
        }
        else {
            $this->html = str_replace('__{'.$position.'}__', "$module Modlule not found" ,$this->html);
        }
    }
}


texts:
I'm wondering if there's a more Pythonic way to keep paginating an API endpoint until there's no next key in the response. The thing that bothers me the most is the for item in json_resp.get("data") (I know this can be extracted as a function).

# some code is omitted, some obfuscated
# attachment of token in API calls omitted for code brevity
def get_object_list_for_user(user_service_token):
    endpoint = f"{HOSTNAME}/me/library/objects/"
    params = {"limit": 100}

    response = _call_service_api(endpoint, params=params)
    json_resp = response.json()

    lists_of_objects_to_append = []

    # get first batch
    for item in json_resp.get("data"):
        object_dict = {"library_id": item["id"], "name": item["attributes"]["name"]}
        lists_of_objects_to_append.append(object_dict)

    offset = 0
    while json_resp.get("next"):
        offset += 100
        params.update({"offset": offset})
        response = _call_service_api(endpoint, params=params)
        json_resp = response.json()

        for item in json_resp.get("data"):
            object_dict = {"library_id": item["id"], "name": item["attributes"]["name"]}
            lists_of_objects_to_append.append(object_dict)

    return lists_of_objects_to_append


texts:
I can't use std::to_string and std::to_wstring function, so I have written a converter:

///@struct ParseInt
///Contains function that parses integer.
template<typename Char_T> struct ParseInt{
    static std::basic_string<Char_T> toString(int x);
};

///Converts integer to std::string
///@param x the integer to convert
///@return std::string from the integer
template<> inline std::string ParseInt<char>::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    char* buf = 0;
    do{
        delete[] buf;
        buf = new char[++length + 1];
    }while(sprintf(buf, "%d", x) < 0);
    std::string str(buf);
    delete[] buf;
    return str;
}

///Converts integer to std::wstring
///@param x the integer to convert
///@return std::wstring from the integer
template<> inline std::wstring ParseInt<wchar_t>::toString(int x){
    int length = 2; //most ints coming here are 2 digits long.
    wchar_t* buf = 0;
    do{
        delete[] buf;
        buf = new wchar_t[++length + 1];
    }while(swprintf(buf, length + 1, L"%d", x) < 0);
    std::wstring str(buf);
    delete[] buf;
    return str;
}

I am not sure how efficient it is. Is there any solution that is more efficient?


texts:
Problem: JavaScript does not provide a random BigInt so there is a need to generate a random BigInt within a given range that is evenly distributed.

Solution
I have tried many algorithms with a emphasis on speed. The best solution builds an array of random Int32 converted to string and padded with zeros which are then joined converted to a BigInt with the return being BitInt % range

function randBigInt2(range) { // returns BigInt 0 to (range non inclusive)
    var rand = [], digits = range.toString().length / 9 + 2 | 0;
    while (digits--) {
        rand.push(("" + (Math.random() * 1000000000 | 0)).padStart(9, "0"));
    }
    return BigInt(rand.join("")) % range;  // Leading zeros are ignored
}

As Math.log can not be used to get the number of digits in range I am forced to use a hack of converting range to a string and using the string length to get log10

The generated array of digits is at least 9 digits longer than the required range to counter the problem of bias to numbers that end in digits less than the least significant digit. Though the bias still exists, it is so small that I am unable to detect it in any tests.

If the range is a multiple of 10 there is no bias

The alternative function that uses BigInt in the calculation is about 2-4% slower.

function randBigInt(range) {
    var rand = 0n, digits = range.toString().length / 9 + 2 | 0;
    while(digits--) {
        rand *= 1000000000n;
        rand += BigInt(Math.random() * 1000000000 | 0);
    }
    return rand % range;
}

Are there any flaws in my logic?


texts: Handling missing elements on login form in Selenium

texts:
I try to improve my code so that I don't have to program a try - catch block all the time.

e.g. at the moment I have to write many codeblocks like this:

try {
    $login_feld = $SeleniumObj->driver->findElement(WebDriverBy::id("login_feld"));
} catch(NoSuchElementException $exception) {
    $SeleniumObj->setErrorMessage("1 ID login_feld does not exist.", $exception,  true, "login_field");
    break;
}
try {
    $password_field = $SeleniumObj->driver->findElement(WebDriverBy::id("password_field"));
} catch(NoSuchElementException $exception) {
    $SeleniumObj->setErrorMessage("1 ID password_field does not exist.", $exception,  true, "login_field");
    break;
}
try {
    $field3 = $SeleniumObj->driver->findElement(WebDriverBy::id("field3"));
} catch(NoSuchElementException $exception) {
    $SeleniumObj->setErrorMessage("1 ID field3 does not exist.", $exception,  true, "login_field");
    break;
}

My goal is to reduce this to one line.

Therefore I outsourced the whole driver->findElement(WebDriverBy::id("xy")); to a new function from the class Selenium called ById

/**
 *
 * @param id $id
 * @param bool $takeScreenshot
 * @return void
 */
public function ById($id, $takeScreenshot=false)
{
    try {
        return $this->driver->findElement(WebDriverBy::id($id));

    } catch(NoSuchElementException $exception) {

        $this->setErrorMessage("ID '$id' does not exist.", $exception,  $takeScreenshot, $id);
        //break;  <- does not work in this context
    }
}

Now theoretically I can code the whole block like this:

$login_feld = $SeleniumObj->ById('login_feld', true);
$password_field = $SeleniumObj->ById('password_field', true);
$field3 = $SeleniumObj->ById('field3', true);

However, one problem still persist. I can't call break in the exception block in the function ById, otherwise I get

  break' not in the 'loop' or 'switch' context

Now to solve this I could instead return a status, e.g. false if the code reached in the exception block and then check this before proceeding

/**
 *
 * @param id $id
 * @param bool $takeScreenshot
 * @return void
 */
public function ById($id, $takeScreenshot=false)
{
    try {
        return $this->driver->findElement(WebDriverBy::id($id));

    } catch(NoSuchElementException $exception) {

        $this->setErrorMessage("ID '$id' does not exist.", $exception,  $takeScreenshot, $id);
        return false;
    }
}

-

$login_field = $SeleniumObj->ById('login_field', true);
if ($login_field == false) { break; }
$pw_field = $SeleniumObj->ById('pw_field', true);
if ($pw_field == false) { break; }
$field3 = $SeleniumObj->ById('field3', true);
if ($field3 == false) { break; }

But now I need two lines per block instead of one.
Is it possible to improve this even further?