texts: Inserting data in the database through POST

texts:
My code here is completely working, but I feel like I destroyed or didn't follow the DRY rule, what suggestions can you give to me for this code??

<?php require_once("./includes/Utilities.php") ;?>
<?php require_once("./includes/Db_Resources/db_connection.php");?>
<?php require_once("./includes/Db/DatabaseUtilities.php"); ?>
<?php
    if(isset($_POST['submit'])){
        require_once("./includes/process_form.inc.php");
        require_once('./includes/Db/CheckPassword.php');
        require_once('./includes/Db/CheckUsername.php');
        $check_pwd = new Db_CheckPassword($password);
        $check_user = new Db_CheckUsername($username,$conn);
        $passwordOK = $check_pwd->check();//Checks if Password is valid
        $userOK = $check_user->check();//Checks if Username is valid
        //Checks if Password is the same with the retyped password
        $password_match = Db_CheckPassword::confirmPassword($password,$conf_pass);

        //if everything is okay! we'll finally add the muthafucking users account
        if($userOK && $passwordOK && $password_match){

            if(Db_DatabaseUtilities::registerAccount($conn,$username,$password,$email)){
                header("Location: login.php");
                exit;
            }

        }else{
            $pass_error =  $check_pwd -> getErrors();
            $user_error  = $check_user->getErrors();
        }
    }
?>


texts:
I've been using random UUIDs—from Rust, e.g. Uuid::new_v4()—for my primary keys in a MySQL database. I recently happened across this, which suggests that UUIDs with an appropriately positioned time component offer some performance improvements.

I created a naive UUID generator like:

fn uuid_new() -> ::uuid::Uuid {

    use ::rand::Rng;

    let now = ::std::time::SystemTime::now()
        .duration_since(::std::time::UNIX_EPOCH)
        .unwrap();

    let (secs, nans): (u64, u32) = (now.as_secs(), now.subsec_nanos());

    let rbts: [u8; 6] = ::rand::thread_rng().gen();

    let bytes = [
        // (secs >> 56) as u8,
        // (secs >> 48) as u8,
        (secs >> 40) as u8,
        (secs >> 32) as u8,
        (secs >> 24) as u8,
        (secs >> 16) as u8,
        (secs >>  8) as u8,
        (secs >>  0) as u8,
        (nans >> 24) as u8,
        (nans >> 16) as u8,
        (nans >>  8) as u8,
        (nans >>  0) as u8,
        rbts[0], rbts[1], rbts[2], rbts[3], rbts[4], rbts[5]
    ];

    ::uuid::Uuid::from_bytes(&bytes).unwrap()

}

I have no requirements for my UUIDs except speed and uniqueness. I'm truncating the first two octets of the secs u64, since they don't seem necessary for the near future.

Am I committing any faux pas here? I don't really know anything about the theory or practice of UUIDs. I'm a little bit worried since the value of get_version_num is gibberish for my UUIDs (though I am not using version number in any way).

Or are there any alternate (Rust) implementations for UUIDs with a time component?


texts: Extracting maximum values from each of the subsets of an array

texts:
Problem description:

I have a numpy array cps from which I want to extract the maximum value in each of the
subsets of the array (a subset is defined as non-zero values which fall between zeros). The input and how the output should look like are illustrated in the following figure.

Note: cps only contains positive values and zeros.

for the moment, I am doing this as below:

## cps is a numpy array which contains values as observed in the figure

idx = np.nonzero(cps)
subsets = np.array_split(idx[0],np.where(np.diff(idx[0])!=1)[0]+1)
lst = np.full(len(cps), 0)

for subset in subsets:
    min = subset[0]   ## index of the start of subset (the smallest index number)
    max = subset[-1]  ## index of the end of subset (the largest index number)

    index_of_change_point_with_max_value = min + np.argmax(cps[min:max+1])

    lst[index_of_change_point_with_max_value] = cps[index_of_change_point_with_max_value]

However, I was wondering if there is anyway to do this in a vectorized manner and getting
rid of the for loop?


texts:
I am working on the MAXSPPROD problem on interviewBit

  You are given an array A containing N integers. The special product of
  each ith integer in this array is defined as the product of the
  following:

  LeftSpecialValue: For an index i, it is defined as the index j such
  that A[j]>A[i] (i>j). If multiple A[j]’s are present in multiple
  positions, the LeftSpecialValue is the maximum value of j.

  RightSpecialValue: For an index i, it is defined as the index j such
  that A[j]>A[i] (j>i). If multiple A[j]s are present in multiple
  positions, the RightSpecialValue is the minimum value of j.

  Write a program to find the maximum special product of any integer in
  the array.

  Input: You will receive array of integers as argument to function.

  Return: Maximum special product of any integer in the array modulo
  1000000007.

  Note: If j does not exist, the LeftSpecialValue and RightSpecialValue
  are considered to be 0.

  Constraints 1 <= N <= 10^5 1 <= A[i] <= 10^9

Basically if you see the vector as a chart LeftSpecialValue and RightSpecialValue are values around local minima.

Here is the algorithm I came up with

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

int mult_mod(int i, int j) {
    return ((i%1000000007) * (j%1000000007)) % 1000000007;
}

int next_bigger(std::vector<int>& v, std::stack<int>& stack, int i){
    while(!stack.empty()){
        int j = stack.top();
        if (v[j] <= v[i]){
            stack.pop();
        }
        else{
            stack.push(i);
            return j;
        }
    }
    stack.push(i);
    return 0;
}

void right( std::vector<int>& v, std::vector<int>& r ){
    std::stack<int> stack;

    for(int i = v.size() - 1; i >= 0; --i){
        r[i] = next_bigger(v, stack, i);
        stack.push(i);
    }
}

int maxProd( std::vector<int>&& v){
    std::vector<int> r(v.size());
    right(v, r);

    int mp = 0;
    std::stack<int> stack;
    for(int i = 0; i < v.size(); ++i){
        int j = next_bigger(v, stack, i );

        int mp_i = mult_mod(j, r[i]);
        if (mp < mp_i){
            mp = mp_i;
        }
    }
    return mp;
}

int main(){
    std::cout << maxProd({3,2,1,2,3}) << std::endl;
    std::cout << maxProd({1,2,3, 2, 1}) << std::endl;
    std::cout << maxProd({1,2,3, 4, 5}) << std::endl;
    std::cout << maxProd({0, 5, 1, 1, 1, 5}) << std::endl;
    std::cout << maxProd({5, 9, 6, 8, 6, 4, 6, 9, 5, 4, 9}) << std::endl;
        std::cout << maxProd({6, 7, 9, 5, 5, 8 }) << std::endl;
        std::cout << maxProd({1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1}) << std::endl; //20

    }

This code is intended to be O(n) in time and space.
The algorithm passes all test but

  might be failing for larger test-cases

I believe it is because I am using an additional vector for RightSpecialValue, which means in worst case twice the size of the input memory.

Can it be improved to use less space?


texts: Implementation of concurrent blocking queue for producer-consumer

texts:
I've implemented concurrent_blocking_queue  for multiple-producers and single consumer.

I intend it to block the producers as well, when the queue is full, which is why I set the capacity of the queue in the constructor. I've provided my own implementation of critical_section, scoped_lock and condition_variable, using msdn primitives.

Please review it. I want to know if there is any potential deadlocks.

template<typename T>
class concurrent_blocking_queue : public noncopyable
{
    std::queue<T> m_internal_queue;
    mutable critical_section m_critical_section;
    condition_variable m_queue_full;
    condition_variable m_queue_empty;
    const size_t m_capacity;
public:
    concurrent_blocking_queue(size_t capacity)
        : m_capacity(capacity), m_critical_section()
    {
    }
    void put(T const & input)
    {
        framework::scoped_lock lock(m_critical_section); //lock
        m_queue_full.wait(lock, [&]{ return !full(); });
        m_internal_queue.push(input);
        m_queue_empty.notify_all();
    }
    T take()
    {
        framework::scoped_lock lock(m_critical_section); //lock
        m_queue_empty.wait(lock, [&]{ return !empty(); });
        T output = m_internal_queue.front();
        m_internal_queue.pop();
        m_queue_full.notify_all();
        return output;
    }
    bool full() const
    {
        framework::scoped_lock lock(m_critical_section);
        if ( m_internal_queue.size() > m_capacity )
        {
            throw std::logic_error("size of concurrent_blocking_queue cannot be greater than the capacity.");
        }
        return m_internal_queue.size() == m_capacity;
    }
    bool empty() const
    {
        framework::scoped_lock lock(m_critical_section);
        return m_internal_queue.empty();
    }
    //..
};

And the remaining classes are posted below. Note that I've implemented them in .h and .cpp files, but here I've merged them to make the post short and simple, and have removed the namespace for brevity, otherwise all classes are defined in framework namespace.

critical_section derives publicly from CRITICAL_SECTION.

class critical_section : public CRITICAL_SECTION, public noncopyable
{
 public:
    critical_section(void) { ::InitializeCriticalSection(this); }
    ~critical_section(void) { ::DeleteCriticalSection(this); }
    void lock() { ::EnterCriticalSection(this); }
    void unlock() { ::LeaveCriticalSection(this); }
};

condition_variable derives privately from CONDITION_VARIABLE.

class condition_variable : private CONDITION_VARIABLE, public noncopyable
{
 public:
    condition_variable() { ::InitializeConditionVariable(this); }
    ~condition_variable(void) {}
    void wait(scoped_lock & lock)
    {
       if (!::SleepConditionVariableCS (this, &lock.m_cs, INFINITE))
       {
          DWORD error = ::GetLastError();
          std::string msg = format("SleepConditionVariableCS() failed with error code = 0x%X.", error);
          throw std::runtime_error(msg);
       }
    }
    void wait(scoped_lock & lock, std::function<bool()> predicate)
    {
       while( !predicate() )  {  wait(lock);  }
    }
    void notify_one() { ::WakeConditionVariable(this); }
    void notify_all() { ::WakeAllConditionVariable(this); }
};

scoped_lock

class scoped_lock : public noncopyable
{
   friend class condition_variable;
   critical_section & m_cs;
 public:
   scoped_lock(critical_section & cs) : m_cs(cs) { m_cs.lock(); }
   ~scoped_lock(void) { m_cs.unlock(); }
};


texts: Emulator for representing hardware and operating systems

texts:
This is an emulator I am currently re-writing for my Operating Systems course. It is a simple emulator that is supposed to represent hardware, OS, etc. It is strictly for learning purposes and I want to propose my solution to the teacher as a method of modern C++ (since his solution is more "C with classes").

However, before I do that, I would like to make sure I don't embarrass myself with bad code.

Right now I'm debating on my association between hardware and OS. They are currently written like so:

// Hardware.h
class OS;
class Hardware : boost::noncopyable
{
    friend class OS;

private:
    Hardware(OS *os);

    void load_job(boost::shared_ptr<Job> job);
    void run_job();

private:
    void execute_instruction(Instruction const& instruction);
    void handle_interrupt(Instruction const& trap);

private:
    enum { NumberOfRegisters     = 32 };
    enum { InstructionMemorySize = 1024 };
    enum { DataMemorySize        = 1024 };

    OS                            *m_pOS;

    std::vector<int>               m_Registers;
    boost::ptr_vector<Instruction> m_InstructionMemory;
    std::vector<int>               m_DataMemory;

    boost::optional<int>           m_Counter;
};

// OS.h
class Hardware;
class OS : boost::noncopyable
{
    friend class Hardware;

public:
    OS();

    // Load jobs
    void boot();
    // Execute jobs
    void run();

private:
    // "Interrupts"
    void trap_halt(int status);
    void trap_getw(int& receiver);
    void trap_putw(int value);
    void trap_dump();

    void time_elapsed();

private:
    void get_next_job();

private:
    boost::scoped_ptr<Hardware> m_pHardware;
    boost::scoped_ptr<Parser>   m_pParser;

    boost::ptr_deque<Job>       m_Jobs;
    boost::ptr_deque<Job>       m_JobsInProgress;
};

The question is:  I don't want the Hardware to be accessible by any other class other than OS. Declaring Hardware private and friending OS is a step in the right direction, but it bothers me that OS now has access to all functions. Is there a way I can restrict OS?

Also, I did some researching on callbacks, but the C++ FAQ suggests that you shouldn't make callbacks to member functions of a class. Are there other solutions such that my Hardware class does not need a pointer to OS in order to call its functions?

Secondly, I'm wondering, at what point does the pImpl idiom become a viable solution? I mean, how large does a class have to be, or how many includes must it have, to seriously consider moving the class into a struct?


texts: C# Class of client methods for interacting with web servers

texts:
I'm in QA Automation, and C# isn't my first language. I've written a small class of methods for GETting and POSTing to web URLs. I use these when I want to test certain things that really fall outside the jurisdiction of Selenium, but are still roughly "black box" type testing. Link scanning, and culling data from POSTBIN, are a few examples.

I was wondering if you C# gurus might like to look the code over, and let me know if there are better ways to do what I've done, or if there's any potential gotcha's I haven't thought of:

public class RawHttp
{
    public static string Url = null;

    public RawHttp(string url)
    {
        Url = url;
    }

    public HttpStatusCode GetStatusCode(string url = null)
    {
        HttpStatusCode result = default(HttpStatusCode);
        string activeUrl = url ?? Url;

        var request = WebRequest.Create(activeUrl);
        request.Method = "HEAD";
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            if (response != null)
            {
                result = response.StatusCode;
                //var headers = response.Headers;
                response.Close();
            }
        }
        return result;
    }

    public string GetBody(string url = null)
    {
        string activeUrl = url ?? Url;

        var request = (HttpWebRequest)WebRequest.Create(activeUrl);
        request.Method = "GET";
        // Set some reasonable limits on resources used by this request
        request.MaximumAutomaticRedirections = 4;
        request.MaximumResponseHeadersLength = 4;
        // Set credentials to use for this request.
        request.Credentials = CredentialCache.DefaultCredentials;
        var response = (HttpWebResponse)request.GetResponse();

        //Console.WriteLine("Content length is {0}", response.ContentLength);
        //Console.WriteLine("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream();
        // Pipes the stream to a higher level stream reader with the required encoding format.
        var readStream = new StreamReader(receiveStream, Encoding.UTF8);
        var body = readStream.ReadToEnd();
        response.Close();
        readStream.Close();
        return body;
    }

    public string Post(string url = null, string parameters = "")
    {
        string activeUrl = url ?? Url;

        var req = WebRequest.Create(activeUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(parameters);
        req.ContentLength = bytes.Length;
        Stream os = req.GetRequestStream();
        os.Write(bytes, 0, bytes.Length); //Push it out there
        os.Close();
        var resp = req.GetResponse();
        //if (resp == null) {return null;}
        var sr = new System.IO.StreamReader(resp.GetResponseStream());
        return sr.ReadToEnd().Trim();
    }
}

Thanks!


texts:
I have made an implementation of the Euclidean algorithm in Java, following the pseudocode shown below.

As far as my knowledge goes, I can't find a way of making this more efficient.

I have looked into other peoples implementations of this algorithm and there are a few which are slightly shorter, and some that use recursion.

The pseudocode:

function gcd(a, b)
    while b ≠ 0
       t := b
       b := a mod b
       a := t
    return a

My implementation:

import java.util.Scanner;
public class EuclideanAlgorithm {
    public static void main (String [] args) {
        int a, b;
        try(Scanner sc = new Scanner(System.in);) {
            System.out.print("Enter integer a: ");
            a = sc.nextInt();
            System.out.print("Enter integer b: ");
            b = sc.nextInt();
        }
        long start = System.nanoTime();
        int answer = EuclideanAlgorithm(a, b);
        long stop = System.nanoTime();
        System.out.println("gcd = " + answer);
        System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");

    }

    public EuclideanAlgorithm() {}; //Suppress default constructor

    private static int EuclideanAlgorithm(int a, int b) {
        int t;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }
}

Is there a way to make this implementation more efficient, and would it have been more efficient to use recursion?


texts:
I have written a Java program to calculate magic squares with recursion and backtracking. A 3*3 Magic square is calculated in about 1 sec, but a 4*4 needs about 50 minutes on my laptop with Intel i5. How i can improve the performance?

import java.util.Scanner;

public class MagicSquare {

private byte[][] square;
private byte magicNumber;
private long tmp = 0;

public MagicSquare() {

    Scanner sc = new Scanner(System.in);
    byte size = sc.nextByte();
    square = new byte[size][size];
    sc.close();
    magicNumber = (byte) ((size * size * size + size) / 2);

    long start = System.currentTimeMillis();
    solve(0, 0);
    printSquare();
    long duration = System.currentTimeMillis() - start;
    System.out.println(tmp);
    System.out.println(duration);
}

private boolean solve(int x, int y) {
    tmp++;
    if (x == square.length && y == square.length - 1 && isMagic()) {
        return true;
    }

    if (x == square.length) {
        y++;
        x = 0;
    }

    for (byte i = 1; i <= square.length * square.length; i++) {

        if (containsNumber(i) == false) {

            if (isValidRow(x) && isValidCol(y)) {

                square[x][y] = i;

                if (solve(x + 1, y) == true) {
                    return true;
                }
            }

        }
    }

    if (x < square.length && y < square.length) {
        square[x][y] = 0;
    }

    return false;
}

private boolean isMagic() {

    int diagonal1 = 0;
    int diagonal2 = 0;
    int col = 0;
    int row = 0;

    for (int i = 0; i < square.length; i++) {

        for (int j = 0; j < square[0].length; j++) {

            col = col + square[j][i];
            row = row + square[i][j];

            if (i == 0) {
                diagonal1 = diagonal1 + square[j][j];
                diagonal2 = diagonal2 + square[j][square.length - j - 1];
            }

        }

        if (col != magicNumber || row != magicNumber || diagonal1 != magicNumber || diagonal2 != magicNumber) {
            return false;
        }

        row = 0;
        col = 0;
    }

    return true;
}

private boolean isValidRow(int row) {

    int sum = 0;

    for (byte i = 0; i < square.length; i++) {
        sum = sum + square[row][i];
    }

    if (sum <= magicNumber)
        return true;

    return false;
}

private boolean isValidCol(int col) {

    int sum = 0;

    for (byte i = 0; i < square.length; i++) {
        sum = sum + square[i][col];
    }

    if (sum <= magicNumber)
        return true;

    return false;
}

public boolean containsNumber(byte value) {

    for (int i = 0; i < square.length; i++) {
        for (int j = 0; j < square[0].length; j++) {

            if (square[i][j] == value) {
                return true;
            }

        }
    }
    return false;
}

private void printSquare() {

    for (int i = 0; i < square.length; i++) {
        for (int j = 0; j < square[0].length; j++) {

            System.out.print(square[i][j] + " ");

        }
        System.out.println();
    }
}

public static void main(String[] args) {

     MagicSquare m = new MagicSquare();

   }
}

Any help is really appreciated.


texts:
I'm pretty new with programming in general.  I'm using Python 2 right now as it seems most of the courses are teaching Python 2 and not 3.  I built this area calculator that will calculate square, rectangle, triangle, circle or trapezoid.  I'm a little concerned about how I used the functions as well as my else statement when an "invalid" input is given.

import math

##formulas for each geometric figure

def calc_square(a_side):
    square_area = a_side ** 2
    return square_area

def calc_rectangle(w_side, l_side):
    rect_area = l_side * w_side
    return rect_area

def calc_triangle(base, height):
    triangle_area = (base * height) / 2
    return triangle_area

def calc_circle(radius):
    circle_area = math.pi * radius ** 2
    return circle_area

def calc_trapezoid(short_base, long_base, height):
    trapezoid_area = ((short_base + long_base) / 2 ) * height
    return trapezoid_area

##function determining which formula to calculate

def area_calc_logic(user_calc):
    if user_calc == "square":
        a_side = float(raw_input("Give length of side: "))
        print calc_square(a_side)
    elif user_calc == "rectangle":
        l_side = float(raw_input("Give the length: "))
        w_side = float(raw_input("Give the width: "))
        print calc_rectangle(w_side, l_side)
    elif user_calc == "triangle":
        base = float(raw_input("Give the length of base: "))
        height = float(raw_input("Give the height: "))
        print calc_triangle(base, height)
    elif user_calc == "circle":
        radius = float(raw_input("Give the radius: "))
        print calc_circle(radius)
    elif user_calc == "trapezoid":
        short_base = float(raw_input("Give the length of the short base: "))
        long_base = float(raw_input("Give the length of the long base: "))
        height = float(raw_input("Give the height: "))
        print calc_trapezoid(short_base, long_base, height)
    else:
        area_calc_logic(raw_input("Error, Re-enter input: "))

print "This program will calculate/narea of some geometric shapes for you"
print "Shapes available are squares, triangles, circles, and trapezoid"
print "Enter square, rectangle, triangle, circle, or trapezoid"
area_calc_logic(raw_input("What area would you like to calculate? "))


texts:
I have written a class to generate a unique username from the full name. The full name is the name of a company usually containing 4 to 5 words. The username generated will be of format {preffix}{username}{suffix}. The user name should not be derived from stop words. stops words are generated analysing the most common words in the list of companies name.

To generate name I am taking the first letter from each word of name and taking remaining from the last word. For eg. if the length of the username is 5 then ABC Company Limited will be converted to ACLIM.

kindly review the code.

class UniqueNameGenerator:

    def __init__(self, stop_words, suffix, prefix):

        self.stop_words = stop_words
        self.suffix = suffix
        self.prefix = prefix

    def split_full_name_and_filter_stop_word(self, full_name, size):

        name_words = " ".join(full_name.split(" ")).split()

        if len(name_words) > size:
            name_words = name_words[:size]
        words_considered = []
        for word in name_words:
            ignore_word = False
            if word.lower() in self.stop_words:
                ignore_word = True
            if not ignore_word:
                words_considered.append(word)
        return words_considered

    @staticmethod
    def get_name_from_list_of_words(size, list_of_words):

        size_counter = 1
        len_words_considered = len(list_of_words)
        letters_left = size
        username = ""
        while size_counter <= len_words_considered:
            current_word = list_of_words[size_counter - 1]
            if size_counter == len_words_considered:
                if len(current_word) >= letters_left:
                    username += current_word[:letters_left]
                else:
                    username += current_word
            else:
                username += current_word[0]
                letters_left -= 1
            size_counter += 1
        return username

    def check_and_update_username_to_unique(self, username, unique_name_list):

        while True:
            s = len(username)
            if username in unique_name_list:
                char_list = list(username)
                char_list[random.randint(0, s)] = random.choices(
                    string.ascii_uppercase + string.digits
                )[0]
                username = "".join(char_list)
            else:
                return username

    def generate_username(self, full_name, size, unique_name_list=None):

        if not unique_name_list:
            unique_name_list = []

        full_name = re.sub("[^\sa-zA-Z]+", "", full_name)
        words_considered = self.split_full_name_and_filter_stop_word(full_name, size)
        username = self.get_name_from_list_of_words(size, words_considered)
        if self.suffix:
            username = username + self.suffix
        if self.prefix:
            username = self.prefix + username
        username = self.check_and_update_username_to_unique(username, unique_name_list)
        return username


texts: Check fragment for exclude show same fragment again

texts:
I use this code to check a fragment before showing it. What can you say about it?

int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0){
    String newFragmentTag = fragment.getClass().getSimpleName()+"|"+fragment.getArguments();
    String nowShowFragmentTag = getFragmentManager().findFragmentById(R.id.main_activity_fragment_container).getTag();
    if (!newFragmentTag.equals(nowShowFragmentTag)) {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())
                .addToBackStack(fragment.toString())
                .commit();
    }
}


texts: Search a unique list and search a larger list to set dictionary with keys of binary values

texts:
I would like to search a list of unique values and create a dictionary with those unique values as keys, and a binary list for whether those values occur.

I have successfully solved this, but would like a more efficient solution. This solution performs a high amount of operations for a search list of size 1000, 10000, and 1000000.

This code is fully reproducible.

import numpy as np

# Create random array, len(10), of integers 1-5

array_to_search = np.array(np.random.randint(0,5,(1,10)))
array_to_search = array_to_search.flatten()

#array_to_search = [0 3 0 0 0 2 1 3 3 0]

# Extract each unique value from array_to_search

array_of_unique_values = np.unique(array_to_search)

# array_of_unique_values = [0 1 2 3]

# Create a dictionary of unique values
output = dict.fromkeys(array_of_unique_values)

# Declare lists as values to the dictionary

output = { k : [] for k in array_of_unique_values}

# For each value in unique values, search the larger list and set the dictionary
# value to a 1 if found, 0 if not found.

for i in array_of_unique_values:
    for j in array_to_search:
        if i == j:
            output[i].append(1)
        else:
            output[i].append(0)

output = {0: [1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
          1: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
          2: [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
          3: [0, 1, 0, 0, 0, 0, 0, 1, 1, 0]}


texts: Speeding up the generation all bit strings with Hamming distance one

texts:
I'm playing around with hypercubes. For this, I need to create its edge set. Specifically, the edge set is the set of all bit strings with Hamming distance 1. An important property is that I want to generate every such pair exactly once. I do this with the following piece of code (I'm also providing a small benchmark for testing its performance):

#include <iostream>
#include <vector>
#include <chrono>
#include <cmath>

int main()
{
    // With 2^15, takes about 0.8 seconds on my machine.
    const int n = std::pow(2, 15);

    // Storing edges not strictly necessary, but let's do it so that the compiler
    // doesn't optimize something away.
    std::vector<int> edges;
    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < i; ++j)
        {
            const int u = i ^ j;

            // https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
            int k = u - 1;
            k |= k >> 1;
            k |= k >> 2;
            k |= k >> 4;
            k |= k >> 8;
            k |= k >> 16;

            if (k + 1 == u)
            {
                edges.emplace_back(j);
                edges.emplace_back(i);
            }
        }
    }

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start);
    std::cout << (duration.count() / 1000.0) << "\n";

    // 2^(n-1)*n
    std::cout << (edges.size() / 2) << "\n";
}

This works fine, but can we make the above even more efficient?


texts: Centralized static factory methods with dependency injection

texts:
I am trying to make a small e-commerce backend in php. I centralized all the static factory methods in a class called EntityFactory. The main reason for that was to centralize the dependency on dependency injector and to make it easy for the client to initialize an entity.

class EntityFactory
{
    private static $employeeRepository;
    private static $productRepository;

    public static function employee($name, $designation, $salary, $contactNo)
    {
        if (!self::$employeeRepository)
            self::$employeeRepository = resolve(EmployeeRepository::class);

        return new Employee(self::$employeeRepository, $name, $designation, $salary, $contactNo);
    }

    public static function product($itemCode, $name, Brand $brand, Category $category, $costPrice, $salePrice)
    {
        if (!self::$productRepository)
            self::$productRepository = resolve(ProductRepository::class);

        return new Product($itemCode, $name, $brand, $category, $costPrice, $salePrice, self::$productRepository);
    }

    public static function brand($name, $id = null)
    {
        $brand = new Brand($name);
        if ($id) $brand->setId($id);
        return $brand;
    }

    public static function category($name, $id = null)
    {
        $category = new Category($name);
        if ($id) $category->setId($id);
        return $category;
    }

    public static function purchaseOrder($customer, $user)
    {
        return new PurchaseOrder($customer, $user);
    }

    public static function orderItem($item, $qty)
    {
        return new PurchaseOrderItem($item, $qty);
    }
}

The main problem I feel here is that this breaks SOLID, especially SRP, ISP and OCP. I may also face problems regarding unit testing in the future(though I've not yet faced one). The code for product purchasing:

//controller: create a new purchase order
public function store(Request $request)
    {
        $this->validateRequest($request);

    $user = $this->productRepository->findById(Auth::id());
    $customer = $this->supplierRepository->findById($request->input('id'));
    $products = $request->input('products');
    $purchaseOrder = EntityFactory::purchaseOrder($customer, $user);

    foreach ($products as $product) {
        $item = $this->productRepository->findById($product['id']);
        $purchaseOrder->addItem(EntityFactory::orderItem($item, $product['qty']));
    }

    $this->purchaseOrderRepository->beginTransaction();
    $this->purchaseOrderRepository->save($purchaseOrder);
    $purchaseOrder->finalize();
    $this->purchaseOrderRepository->endTransaction();
}

Here I can easily stub out the repositories in the controller

// class PurchaseOrder

public function addItem(PurchaseOrderItem $item)
{
    $this->items[] = $item;
}

public function finalize()
{
    foreach ($this->items as $item) {
        $product = $item->getProduct();
        $product->purchase($item->getQuantity());
    }
}

//class Product
public function purchase($qty)
{
    if ($this->stock - $qty < 0) {
        throw new \RuntimeException("Product not available");
    } else {
        $this->stock += $qty;
        $this->productRepository->update($this);
    }
}

Here also the ProductOrderItem and Product can be stubbed.

I didn't want the factory to need instantiation. Otherwise I would have a dependency graph like factory -> repository -> mapper -> factory where mapper maps data from ORM classes to entity classes.

What are your thoughts?


texts:
I have a word-wrap algorithm that basically generates lines of text that fit the width of the text. Unfortunately, it gets slow when I add too much text.

I was wondering if I oversaw any major optimizations that could be made. Also, if anyone has a design that would still allow strings of lines or string pointers of lines that is better I'd be open to rewriting the algorithm.

Thanks

void AguiTextBox::makeLinesFromWordWrap()
{
    textRows.clear();
    textRows.push_back("");
    std::string curStr;
    std::string curWord;

    int curWordWidth = 0;
    int curLetterWidth = 0;
    int curLineWidth = 0;

    bool isVscroll = isVScrollNeeded();
    int voffset = 0;
    if(isVscroll)
    {
        voffset = pChildVScroll->getWidth();
    }
    int AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
    int len = getTextLength();
    int bytesSkipped = 0;
    int letterLength = 0;
    size_t ind = 0;

    for(int i = 0; i < len; ++i)
    {

        //get the unicode character
        letterLength = _unicodeFunctions.bringToNextUnichar(ind,getText());
        curStr = getText().substr(bytesSkipped,letterLength);

        bytesSkipped += letterLength;

        curLetterWidth = getFont().getTextWidth(curStr);

        //push a new line
        if(curStr[0] == '\n')
        {
            textRows.back() += curWord;
            curWord = "";
            curLetterWidth = 0;
            curWordWidth = 0;
            curLineWidth = 0;
            textRows.push_back("");
            continue;
        }

            //ensure word is not longer than the width
            if(curWordWidth + curLetterWidth >= AdjWidthMinusVoffset &&
                curWord.length() >= 1)
            {
                textRows.back() += curWord;

                textRows.push_back("");
                curWord = "";
                curWordWidth = 0;
                curLineWidth = 0;
            }

            //add letter to word
            curWord += curStr;
            curWordWidth += curLetterWidth;

        //if we need a Vscroll bar start over
        if(!isVscroll && isVScrollNeeded())
        {
            isVscroll = true;
            voffset = pChildVScroll->getWidth();
            AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
            i = -1;
            curWord = "";
            curStr = "";
            textRows.clear();
            textRows.push_back("");
            ind = 0;

            curWordWidth = 0;
            curLetterWidth = 0;
            curLineWidth = 0;

            bytesSkipped = 0;
            continue;
        }

        if(curLineWidth + curWordWidth >=
            AdjWidthMinusVoffset && textRows.back().length() >= 1)
        {
            textRows.push_back("");
            curLineWidth = 0;
        }

        if(curStr[0] == ' ' || curStr[0] == '-')
        {
            textRows.back() += curWord;
            curLineWidth += curWordWidth;
            curWord = "";
            curWordWidth = 0;
        }
    }

    if(curWord != "")
    {
        textRows.back() += curWord;
    }

    updateWidestLine();
}


texts: Custom MySQL duplicate_key update queries

texts:
The goal is to create an activity or update its counter if it's already present. And to be super accurate, the code avoids race conditions with a custom insert_on_duplicate_key_update MySQL query.

All user activities are already preloaded, so in case the service knows that there was an existing activity it will just do an update counter+1 query. Additionally, the code has to check whether the given activity_name is valid, which it does by specifying validators on the Activity ActiveRecord class.

How can these be cleaner?

B (code I am currently using)

class ActivitiesService
  def store_activity(activity_name)
    (activities[activity_name] || Activity.new(user_id: id, name: activity_name)).complete
  end
end

class Activity < Active::Record
  def complete
    return self.class.increment_counter(:count, id) if persited?

    insert_on_duplicate_key_update if valid?
    @new_record = false
  end
end

A (alternative rewritten code)

class ActivtiesService
  def store_activity(activity_name)
    if has_activity?(activity_name)
      Activity.increment_counter(:count, user_id)
    else
      Activity.complete(user_id: user_id, name:  activity_name)
    end
  end
end

clas Acttivity < Active::Record
  def self.complete(args)
    insert_on_duplicate_key_update if new(args).valid?
  end
end


texts: Program for converting an array of bytes to hexadecimal

texts:
I have written a program that outputs the hexadecimal representation of an array of bytes. The program works just fine, and I am confident (thanks to valgrind) that I don't have any memory leaks. However, I am not so confident I am doing this the simplest, nor most readable way. It seems to me I have written a lot of code for a small task.

I am looking for general feedback, including code style, types, variable naming, usage of malloc, and simpler ways of appending a char array to a string, possibly avoiding sprintf.

The program was written to exercise storing a hexadecimal representation of a byte array in a string, not printing it out directly using printf().

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

int main() {
    const unsigned char bytearr[] = { 0x0b, 0x34, 0x33, 0x32 };
    const int hexlen = 2; // outputting hex value with leading zero
    const int outstrlen = sizeof(bytearr) * sizeof(char) * sizeof(bytearr[0]) * hexlen;

    char *outstr;
    if ((outstr = malloc(outstrlen + 1)) == NULL) {
        printf("Failed to allocate memory");
        exit(1);
    }
    bzero(outstr, outstrlen + 1);

    int i;
    char tmp[hexlen + 1];
    for (i = 0; i < (sizeof(bytearr) / sizeof(bytearr[0])); i++) {
        sprintf(tmp, "%.2x", bytearr[i]);
        strcat(outstr, tmp);
    }

    printf("Hexadecimal string:\n%s\n", outstr);

    free(outstr);

    return 0;
}

For what it's worth, after this review, my program ended up like this.


texts:
I've written a little function that iterates over two iterables. The first one returns an object which is used to convert an object of the second iterable. I've got a working implementation, but would like to get some feedback.

A simple use case would look like this:

list(serialize([String(), String()], [1, 2]))    # should work
list(serialize([String(), String()], range(3)))  # should fail, too many values
list(serialize([String(), String()], range(1)))  # should fail, too few values

But sometimes the number of values is not known but the type is the same. Therefore infinite iterators should be allowed as types argument:

list(serialize(it.repeat(String()), range(3)))   # should work

Of course finite iterators are allowed as well:

list(serialize(it.repeat(String(), times=3), range(3))) # should work
list(serialize(it.repeat(String(), times=4), range(5))) # should fail
# should fail, but probably not that easy to do.
list(serialize(it.repeat(String(), times=4), range(3)))

My working implementation (except for the last case) looks like this:

class String(object):
    def dump(self, value):
        return str(value)

def serialize(types, values):
    class Stop(object):
        """Since None can be valid value we use it as fillvalue."""

    if isinstance(types, collections.Sized):
        # Since None is a valid value, use a different fillvalue.
        tv_pairs = it.izip_longest(types, values, fillvalue=Stop)
    else:
        tv_pairs = it.izip(it.chain(types, (Stop,)), values)

    for type, value in tv_pairs:
        if type is Stop:
            raise ValueError('Too many values.')
        if value is Stop:
            raise ValueError('Too few values.')
        yield type.dump(value)


texts:
Are the conditions which I have included for insertion and deletion from front and rear sufficient and necessary? Have I missed some condition check? Or have I included some redundant condition?

import java.io.*;
class Dequeue
{
int arr[];
int lim;
int front;
int rear;
public Dequeue(int l)
{
    lim=l;
    front=rear=0;
    arr=new int[(l+1)];
}
void addrear(int val)
{
   if(front==0 && rear ==0)
   {
    front=1;
    rear=1;
    arr[1]=val;
   }
   else if(rear==lim)
   {
   System.out.println("Overflow");
   }
   else
   {
   arr[++rear]=val;
   }
}
void addfront(int val)
{
    if(front==0 && rear ==0)
    {
    front=1;
    rear=1;
    arr[1]=val;
    }
    else if(front==1)
    {
        System.out.println("Overflow");
    }
    else
    {
    arr[--front]=val;
    }
}
void poprear()
{
    if(front==rear)
    {
        System.out.println(arr[front]);
        front=0;
        rear=0;

    }
    else if(front==0 && rear==0)
    {
       System.out.println("Underflow");
    }
    else
    {
        System.out.println(arr[rear]);
        rear--;

    }

}
void popfront()
{
    if(front==rear)
    {
        System.out.println(arr[front]);
        front=0;
        rear=0;

    }
    else if(front==0 && rear==0)
    {
       System.out.println("Underflow");
    }
    else
    {
        System.out.println(arr[front]);
        front++;

         }
      }
void display()
{
if(front!=0 || rear!=0)
{
    for(int i=front;i<=rear;i++)
   {
        System.out.print(arr[i]);
   }
   System.out.println();
}

else
System.out.println("Empty");
}
public static void main(String args[])throws IOException
{
int flag=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter size of array");
Dequeue obj=new Dequeue(Integer.parseInt(br.readLine()));
while(flag==0)
{
System.out.println("1 for addrear");
System.out.println("2 for addfront");
System.out.println("3 for poprear");
System.out.println("4 for popfront");
System.out.println("5 for exit");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
    case 1:
           System.out.println("Enter element");
           obj.addrear(Integer.parseInt(br.readLine()));
           obj.display();
           break;
    case 2:System.out.println("Enter element");
           obj.addfront(Integer.parseInt(br.readLine()));
           obj.display();
           break;
    case 3:obj.poprear();
           obj.display();
           break;
    case 4:obj.popfront();
           obj.display();
           break;
    case 5:flag=1;
           break;

}
}

}
}


texts: snapping code: from separate checks to 1 formula

texts:
I'm working on a 3D-project with three.js and webGl. I've written a function to check for 2 objects to be near each other and thus "snap" to each other.

The objects don't move on the Y-axis, so I only have to check the 4 sides of each object against the side of all other objects in the scene. At the moment I'm doing that with this code:

for (var i = 0; i < elements.length; i++) {

            var newBox = updateBoundingBox(elements[i]);

            var snapped = null;

            if (newBox.min.x - box.max.x < 5 && newBox.min.x - box.max.x > -box.size().x / 2//5
                && box.max.z > newBox.min.z && box.min.z < newBox.max.z) {

                activeElement.position.x = newBox.min.x - ((box.max.x - box.min.x) / 2) - 0.5;
                box = updateBoundingBox(activeElement);
                snapped = [elements[i], "X"];
            }

            if (newBox.min.z - box.max.z < 5 && newBox.min.z - box.max.z > -box.size().z / 2//5
                && box.max.x > newBox.min.x && box.min.x < newBox.max.x) {

                activeElement.position.z = newBox.min.z - ((box.max.z - box.min.z) / 2) - 0.5;
                box = updateBoundingBox(activeElement);
                snapped = [elements[i], "Z"];

            }

            if (box.min.x - newBox.max.x < 5 && box.min.x - newBox.max.x > -box.size().x / 2
                && box.max.z > newBox.min.z && box.min.z < newBox.max.z) {

                activeElement.position.x = newBox.max.x + ((box.max.x - box.min.x) / 2) + 0.6;
                box = updateBoundingBox(activeElement);
                snapped = [elements[i], "X"];

            }

            if (box.min.z - newBox.max.z < 5 && box.min.z - newBox.max.z > -box.size().z / 2
                && box.max.x > newBox.min.x && box.min.x < newBox.max.x) {

                activeElement.position.z = newBox.max.z + ((box.max.z - box.min.z) / 2) + 0.5;
                box = updateBoundingBox(activeElement);
                snapped = [elements[i], "Z"];

            }

            if (snapped != null) {

                activeElement.snapped.push(snapped);
                debug.snapped = true;
            }

}

But, it is very obvious that the 4 if-statements are almost identical, so I was wondering if it was possible to write them in a better/shorter way so I can just loop over them?


texts:
Context

I'm looking into design patterns.  My first try is using the Decorator Pattern.

Question:

Is there another (maybe standard) approach to applying modifications in a decorator other than explicitly overwriting in the constructor?
 -

Car Interface

<?php

interface CarInterface
{
    public function drive();
}

Care Base Class

<?php

class CarBaseClass implements CarInterface
{
    public $model = 'Base Model';
    public $top_speed = null;
    public $features = ['AC', 'Radio'];

    public function __construct($top_speed)
    {
        $this->top_speed = $top_speed;
    }

    public function drive(): void
    {
        echo $this->model . " speed: " . $this->top_speed;
    }

}

Tesla

<?php

class Tesla extends CarBaseClass
{
    public $model = 'Tesla';
}

Engine Feature Decorator

<?php

class V20Engine extends CarBaseClass
{
    public $SPEED_BOOST = 1.5;
    public $new_features = ['V20 Engine'];

    public function __construct(CarBaseClass $car)
    {
        $this->model = 'V20 ' . $car->model;
        $this->top_speed = $car->top_speed * $this->SPEED_BOOST;;
        $this->features = array_merge($car->features, $this->new_features);
    }
}

Turbo Decorator

<?php

class TurboEnabled extends CarBaseClass
{
    public $TURBO_BOOST = 1.75;
    public $new_features = ['Turbo Enabled', 'Snoop Dog GPS'];

    public function __construct(CarBaseClass $car)
    {
        $this->model = 'Turbo Enabled ' . $car->model;
        $this->top_speed = $car->top_speed;
        $this->features = array_merge($car->features, $this->new_features);
    }

    public function activateTurbo() {
        $this->top_speed = $this->top_speed * $this->TURBO_BOOST;

        return $this;
    }
}

index.php

<?php

require 'classes/Car/CarInterface.php';
require 'classes/Car/CarBaseClass.php';
require 'classes/Car/Tesla.php';
require 'classes/Car/Feature/TurboEnabled.php';
require 'classes/Car/Feature/V20Engine.php';

echo "
";

$tesla = new Tesla(100);
$tesla->drive();

echo "
";

$turbo_tesla = new TurboEnabled($tesla);
$turbo_tesla->activateTurbo()->drive();

echo "
";

$v20_tesla = new V20Engine($tesla);
$v20_tesla->drive();

echo "
";

$v20_turbo_tesla = new V20Engine($turbo_tesla);
$v20_turbo_tesla->drive();

echo "
";

$car = new V20Engine( new TurboEnabled( new CarBaseClass(100) ) );
print_r( $car->features );


texts: EF entity, extended with partial classes for actions

texts:
Me colleague and I recently had a discussion on good practices in EF. So I showed one of mine.

He said it is a little bit muddler.

My practice consists of modifying the autogenerated class in a specific way. This is my starting model:

namespace PCServer.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Post: IEntity
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime Date { get; set; }

        public virtual Post ParentPost { get; set; }
        public virtual AspNetUser Author { get; set; }
    }
}

I like to extend it in this way:

public partial class Post
    {
        //This class "do" something, like adding a post or deleting a post
        public static class Do
        {
            public static void AddPost(ref ApplicationDbContext context, string postMessage)
            {
                //Create a post
                Post p = new Post();
                p.Title = "This is an example!";
                p.message = postMessage;
                p.Date = DateTime.UtcNow;

                //Adding to context
                BaseService.Add(post, out context);
            }

            public static void DeletePost(ref ApplicationDbContext context, int postId)
            {
                PostRepository postRepo = new PostRepository(context);

                postRepo.GetById(postId);

                //Removing from context
                BaseService.Remove(post, out context);
            }
        }

        //This class "Get" something, like all posts
        public static class Get
        {
            public static void GetPosts()
            {
                using(ApplicationDbContext context = new ApplicationDbContext())
                {
                    PostRepository postRepo = new PostRepository(context);
                    return postRepo.GetAllPosts();
                }
            }
        }

        //This class "Set" something, like title of the post or the post itself maybe
        public static class Set
        {
            public static void Title(ref ApplicationDbContext context, int postId, string title)
            {
                PostRepository postRepo = new PostRepository(context);
                Post post = postRepo.GetById(postId);
                post.Title = title;

                BaseService.Update(post, out context);
            }

            public static void ChangePost(ref ApplicationDbContext context, int postId, Post post)
            {
                PostRepository postRepo = new PostRepository(context);
                Post dbPost = postRepo.GetById(postId);
                dbPost = post;

                BaseService.Update(dbPost, out context);
            }
        }
    }

So, when I must do something with an Entity, I can (for example only):

ApplicationDbContext c = new ApplicationDbContext();

Post.Do.AddPost(ref c,"Hi!");
IEnumerable<Post> posts = Post.Get.GetPosts();

Post.Set.Title(ref c,100,"Changing title!");

And after all:

await BaseService.CommitAsync<Post>(c);

What do you think? Would you use it? Why?

Here is my original post of this on SO.


texts:
I am creating an application just for practicing c# as well as new programming ways. So i came across the idea that i create an application that stores information about "soldiers" ex. Names, ranks, titles, etc... but the trick here is that i want the soldier title to be automatically upgraded when it's rank increases.

I have created a small application to demonstrate the idea.

Soldier Class

public class Soldier
{
    public string Name { get; private set; }
    public int Rank { get; private set; }
    public string Title { get; private set; }

    public Soldier(string name)
    {
        Name = name;
        RefreshTitle();
    }

    public void Rankup(int rank = -1)
    {
        if (-1 != rank)
            Rank = rank;
        else
            Rank++;

        RefreshTitle();
    }

    public void RefreshTitle()
    {
        Title = SoldierRankLibrary.GetSoldierTitle(Rank);
    }
}

Soldier Rank Library

public class SoldierRankLibrary
{
    private static readonly Dictionary<int, string> RankDictionary = new Dictionary<int, string>
                                                          {
                                                              {0, "Novice"},
                                                              {1, "Second Lieutenant"},
                                                              {2, "First Lieutenant"},
                                                              {3, "Captain"},
                                                              {4, "Major"},
                                                              {5, "Lieutenant Colonel"},
                                                              {6, "Colonel"}
                                                              //etc...
                                                          };

    public static string GetSoldierTitle(int requiredRank)
    {
        return RankDictionary.FirstOrDefault(rank => rank.Key == requiredRank).Value;
    }
}

Using the code

static void Main()
{
    //Create new soldier...
    var soldier = new Soldier("Daniel");

    //Print soldier info...
    PrintSoldierInfo(soldier);

    //Upgrade soldier...
    soldier.Rankup();

    //Print soldier info...
    PrintSoldierInfo(soldier);

    Console.Read();
}

static void PrintSoldierInfo(Soldier soldier)
{
    Console.WriteLine("****************************************");
    Console.WriteLine("Name: {0}", soldier.Name);
    Console.Write("Rank: ");
    switch (soldier.Rank)
    {
        case 0:
            Console.WriteLine("novice");
            break;
        case 1:
            Console.WriteLine("*");
            break;
        case 2:
            Console.WriteLine("**");
            break;
        case 3:
            Console.WriteLine("***");
            break;
        case 4:
            Console.WriteLine("****");
            break;
        case 5:
            Console.WriteLine("*****");
            break;
        case 6:
            Console.WriteLine("******");
            break;
        case 7:
            Console.WriteLine("*******");
            break;
    }
    Console.WriteLine("Title: {0}", soldier.Title);
    Console.WriteLine("****************************************");
    Console.WriteLine();
}

Conclusion

I am really waiting for your answers and i hope you give me detailed information about what i miss, what i can do better, how could i improve this code.


texts:
A plugin I'm writing that will have essentially be a tabbed popup. However, I feel like the method I use to remove tabs is completely unwieldy.

    (function($) {
        var methods = {
            init: function(option) {
       this.data("tabs", {});
       this.data("currentTab", {});
       methods.setupPopup(this);
       return this;
      }
      setupPopup: function (popup) {
         tabs = popup.find(".popupTabs .tab");
         tabs.each(function(i, tab){
        $name = $(tab).data("tabTarget");
        popup.data("tabs")[$name] = {
         tabSelector : $(tab).get(0),
         tab : $(popup).find("[data-tab-name='" + $(tab).data("tabTarget") + "']").get(0)
        }
        $(tab).zIndex( tabs.length - i)
       })
       popup.data("currentTab", popup.data("tabs")[Object.keys(popup.data("tabs"))[0]])
          popup.on( 'click',".tab", function(){
         targetTab = popup.data("tabs")[$(this).data("tabTarget")]
         $(popup.data("currentTab").tab).removeClass('active');
         $(popup.data("currentTab").tabSelector).removeClass('active');
       $(targetTab.tabSelector).addClass("active");
         $(targetTab.tab).addClass("active");
            popup.data("currentTab", targetTab)
          })
       methods.setupTabs(popup, popup.find(".popupTab"))
      },
      setupTabs : function (popup, tabs){
       tabs.each(function(i, tab) {
        btns = $(tab).find('.popupBtn');
        btns.each(function(i, btn) {
         $(btn).on("click", function(){
          methods.removeTab(popup, tab);
         });
        });
       });

      },
      removeTab : function (popup, tab){
       $(popup.data("currentTab").tab).remove();
       $(popup.data("currentTab").tabSelector).remove();
       delete popup.data("tabs")[Object.keys(popup.data("tabs"))[0]]
       popup.data("currentTab", popup.data("tabs")[Object.keys(popup.data("tabs"))[0]])
       $(popup.data("currentTab").tab).addClass("active");
       $(popup.data("currentTab").tabSelector).addClass("active");
      }
        }
        $.fn.PopupTabs = function(method) {
          if (methods[method]) {
               return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
           } else if (typeof method === 'object' || !method) {
               return methods.init.apply(this, arguments);
           } else {
                $.error('Method ' + method + ' does not exist on jQuery.Test');
            }
        };
    })(jQuery);

This is my content for my first tab

Click to close

this is my content for my second tab

Click to close

As you can see, I added the tabs to an object structure so I could call them by name and get both the tab as well as the associated tabBody to act on (i.e. make active, remove, etc.) yet this structure is somewhat hard to work with, especially when I want to remove a tab and automatically call on the next one to make it active.


texts: Binary HeapSort and Ternary HeapSort implementation

texts:
This is my take on binary and ternary heapsort implementation for a university assignment. The code works but I wonder if there are any mistakes or things to improve.

class HeapSorter {

    static int[] array;
    static int heapSize;

    //=============================BINARY HEAPSORT=============================//

    static void maxHeapify(int i){

        int leftChild = left(i);
        int rightChild = right(i);
        int largest;

        largest = leftChild <= heapSize && array[leftChild] > array[i] ? leftChild : i ;

        if(rightChild <= heapSize && array[rightChild] > array[largest])
            largest = rightChild;

        if(largest != i){
            swap(i, largest);

            //Recursively heapify the subtree
            maxHeapify(largest);
        }

    }

    static void binaryHeapSort(int[] toSort){
        array = toSort;
        buildMaxHeap();

        //testing i >= 0 will be executed for i= array.length - 1, array.length - 2,......0,-1. So array.length + 1 times (n + 1)
        //i-- will be executed array.length times (n)
        for(int i = array.length - 1; i >= 0; i--){

            //swap executed n times (n)
            swap(0,i);

            // heapSize - 1 executed n times (n)
            // assignment executed n times (n)
            heapSize = heapSize - 1;

            //maxHeapify executed n times (n)
            maxHeapify(0);
        }

    }

    static void buildMaxHeap(){
        heapSize = array.length - 1;
        for(int i = (array.length - 1) / 2; i >= 0; i--)
            maxHeapify(i);

    }

    static int left(int i){
        return i << 1;
    }

    static int right(int i){
        return (i << 1) + 1;
    }

    //==========================================================================//

    //=============================TERNARY HEAPSORT=============================//

    static void buildMaxHeapT(){
        heapSize = array.length - 1 ;
        for(int i =array.length - 1  / 3; i >= 0; i--)
            maxHeapifyT(i);

    }

    static void maxHeapifyT(int i){

        int leftChild = leftT(i);
        int rightChild = rightT(i);
        int middleChild = middleT(i);
        int largest;

        largest = leftChild <= heapSize && array[leftChild] > array[i] ? leftChild : i;

        if(rightChild <= heapSize && array[rightChild] > array[largest])
            largest = rightChild;

        if(middleChild <= heapSize && array[middleChild] > array[largest])
            largest = middleChild;

        if(largest != i){
            swap(i, largest);
            maxHeapifyT(largest);
        }
    }

    static void ternaryHeapSort(int[] toSort){
        array = toSort;
        buildMaxHeapT();

        for(int i = array.length - 1; i >= 0; i--){
            swap(0,i); //add last element on array, i.e heap root

            heapSize = heapSize - 1; //shrink heap by 1
            maxHeapifyT(0);
        }

    }

    static int leftT(int i){
        return 3 * i + 1;
    }

    static int middleT(int i){
        return 3 * i + 2;
    }

    static int rightT(int i){
        return 3 * i + 3;
    }

    //==========================================================================//

    static void swap(int i, int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    static int[] start (int[] toSort, boolean binaryHeap) {
        if (binaryHeap) {
            binaryHeapSort(toSort);
        } else {
            ternaryHeapSort(toSort);
        }

        return toSort;
    }
}

Also, should I use bit shifting like this:

static int leftT(int i){
    return (i << 1) + i + 1;
 }

instead of

static int leftT(int i){
    return 3 * i + 1;
}


texts:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
int l=0;
bool isprime;
vector<int>primes;
primes.push_back(2);
for (int nur = 3;true;nur+=2)
{

     isprime=true;
     double ilimit= sqrt(nur);
    for (int primecount=0 ;primes[primecount]<=ilimit;primecount++)
    {
        if (nur % primes[primecount] == 0)
        {
            isprime = false;
            break;
        }

    }

     if (isprime)
     {
             cout<<nur<<endl;
          primes.push_back(nur);
             // l++;
     }

     if (nur<0)
     break;

}
cout<<"Finished"<<endl;
//cout<<primes[l];

  return 0;
 }

Is there anyway i can optimize this further without using a sieve?


texts: Lookup class to get descriptions of values

texts:
Following yesterday's advice on my Customer class, I have now created a new class which is for looking up descriptions from a MySQL database. I have a Lookup table which contains type, name, value, and descriptions.

Here's a basic example of type = customer and name = state

Customer States

New Customer
Pending Approval
Approved / Active
Deleted

In this example if I pass in the parameters "customer", "state", and 2, the method will return "Pending Approval".

pdo.inc.php

<?php

// Version 0.1
// Last updated 08 Jun 2016

define('DB_CONFIG_HOST', 'localhost');
define('DB_CONFIG_DB', 'dev');
define('DB_CONFIG_USER', 'dev');
define('DB_CONFIG_PW', 'dev');
$dsn = 'mysql:host=' . DB_CONFIG_HOST . ';dbname=' . DB_CONFIG_DB . ';';
define('DB_CONFIG_DSN', $dsn);

try
{
    $pdo = new PDO(DB_CONFIG_DSN, DB_CONFIG_USER, DB_CONFIG_PW);
}
catch (PDOException $ex)
{
    error_log('Connection failed: ' . $ex->getMessage());
    die();
}

?>

lookup.class.php

<?php

// Version 0.1
// Last updated 09 Jun 2016

class Lookup
{

    function __construct($pdo)
    {
        $this->pdo = $pdo;
    }

    function getLookup($lookup_type, $lookup_name, $lookup_value)
    {

        $valid_types = array("customer");
        $valid_names = array("state");

        if (!in_array($lookup_type, $valid_types))
        {
            throw new InvalidArgumentException('Lookup type is not a valid');
        }

        if (!in_array($lookup_name, $valid_names))
        {
            throw new InvalidArgumentException('Lookup name is not a valid');
        }

        if (empty($lookup_value) || !is_int($lookup_value) || $lookup_value < 0)
        {
            throw new InvalidArgumentException('Lookup value is not a valid integer');
        }

        $query = "SELECT lookup_description FROM Lookup WHERE lookup_type = :lookup_type AND lookup_name = :lookup_name AND lookup_value = :lookup_value LIMIT 1";
        try
        {
            $stmt = $this->pdo->prepare($query);
            $stmt->bindParam(':lookup_type', $lookup_type);
            $stmt->bindParam(':lookup_name', $lookup_name);
            $stmt->bindParam(':lookup_value', $lookup_value);
            $stmt->execute();
            if ($stmt->rowCount() === 0)
            {
                return false;
            }
            else
            {
                return $stmt->fetchColumn();
            }
        }
        catch (PDOException $ex)
        {
            error_log('Something went wrong in getLookup ' . $ex->getMessage());
            return null;
        }
    }

}

?>

test.php

<?php

// Version 0.1
// Last updated 09 Jun 2016

include_once('pdo.inc.php');
include_once('lookup.class.php');

try
{
    $l = new Lookup($pdo);
}
catch (Exception $ex)
{
    echo $ex->getMessage();
    die();
}

try
{
    echo $l->getLookup("customer", "state", 1); // Returns "New Customer"
    echo $l->getLookup("customer", "state", 2); // Returns "Pending Approval"
}
catch (Exception $ex)
{
    echo $ex->getMessage();
    error_log('Customer name lookup failed with: ' . $ex->getMessage());
}

?>

I'm not sure I like the idea of having fixed arrays for looking up valid parameter values. I was thinking of getting a distinct list from MySQL, but as to do that I might as well just pass the query without validation and let it return null. Any thoughts?


texts: LC medium, matrix set zeros, accepted answer but not top

texts:
I've solved LC medium problem, set zeros. Below code is accepted and all test cases were passing. But my code came in the last 10% of accepted answers wrt performance. Can someone help me identify optimization opportunities? This is in C# and memory footprint is fine.
public class Solution {
    public void SetZeroes(int[][] matrix) {

            bool zeroRow = false;
            bool zeroCol = false;

            for (int i = 0;i<matrix.Length;++i)
            {
                for (int j = 0; j < matrix[0].Length; ++j)
                {
                    if (matrix[i][j] == 0)
                    {
                        if (i == 0)
                            zeroRow = true;
                        if (j == 0)
                            zeroCol = true;

                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }

                }

            }

            for (int i = 1; i < matrix.Length; ++i)
            {
                for (int j = 1; j < matrix[0].Length; ++j)
                {
                    if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    {
                        matrix[i][j] = 0;
                    }

                }

            }

            Console.Write('[');
            for (int i = 0; i < matrix.Length; i++)
            {
                if (zeroCol) { matrix[i][0] = 0; }
                Console.Write('[');
                for (int j = 0; j < matrix[0].Length; j++)
                {
                    if (zeroRow) { matrix[0][j] = 0; }
                    Console.Write(matrix[i][j]);
                    if(j!=matrix[0].Length-1)
                    Console.Write(',');
                }
                Console.Write("]");
                if (i != matrix.Length-1)
                    Console.Write(',');
            }
            Console.Write(']');
    }
}


texts: Python Script to look for DNS expiration

texts:
I just wrote a Python script that will take a list of urls and find which ones are about to expire.

The program queries a database, gets the websites, sanitizes the list, then loops through the list and prints the expiration dates to the file. Any websites that expire within 30 days are printed to a text file as well as to the terminal.

The program has two main deficiencies:

The DNS lookup doesn't always work. Sometimes it returns correct information and sometimes it doesn't.
The program is not written in either object-oriented or functional style.
The program is written with a poor implementation of Python modules and is probably not Pythonic.

I would love to get some input on how to make this code better. Everything feels super clunky to me. For example, the sanitization process feels over-complicated, as I feel like I'm jumping through too many hoops to convert the SQL results to a string. The Popen processes feel over-complicated as well.

Would love to get some help making this better.

import database
import re
import time
import datetime
import subprocess
from subprocess import PIPE, Popen
import sys
from termcolor import colored, cprint
import pymysql.cursors

###
# FUNCTIONS
###

# Writes expiration data to the file
def write_to_file(filename, url, days_to_expiration, expiration_date):
    f = open(filename, "a+")
    f.write(url + ' expires in ' + str(days_to_expiration) + ' days on ' + expiration_date + '\n')
    f.close()

###
# END FUNCTIONS
###

###
# MAIN
###

###REMOVED QUERY INFORMATION###

results = cursor.fetchall()

# Sanitize results
results_no_blanks = list(filter(lambda x: x[0] != '', results)) # Remove Blank results
results_no_protocol = list(map(lambda x: re.sub(r'^(https?:)?(\/\/)?(www.)?', '', ''.join(x)), results_no_blanks)) # Remove protocols
final_results = list(map(lambda x: re.sub(r'\/', '', ''.join(x)), results_no_protocol)) # Remove trailing slashses

# Prepare text file
a = open("danger.txt","a+")
a.write('DNS Expirations checked on: ' + datetime.datetime.today().strftime("%m/%d/%Y"))
a.write('\n')
a.close()

# Get WHOIS data for each URL
for result in final_results:
    url = ''.join(result)

    # Use command line to get WHOIS data
    p1 = Popen(['whois', url], stdout=PIPE)
    p2 = Popen(["grep", "Expiration\|Expiry"], stdin=p1.stdout, stdout=PIPE)
    p3 = subprocess.Popen(["awk", "{print $5}"], stdin=p2.stdout, stdout=PIPE)
    p4 = subprocess.Popen(['head', '-c', '14'], stdin=p3.stdout, stdout=PIPE)

    # Turn result into a string
    bytes_result = p4.communicate()
    result = bytes_result[0][1:-3]
    resulter = result.decode('utf-8')

    # Workaround: Sometimes whois returns a string with missing date data.
    try:
        if resulter != '':
            resulter_date = datetime.datetime.strptime(resulter, '%Y-%m-%d')
    except ValueError:
        print('Oops, something failed. Invalid String Format for URL {}, which returned {}.'.format( url, resulter))

    # Get the days until DNS expiration
    difference = resulter_date - datetime.datetime.today()
    days_until_expiration = difference.days

    # Print results to command line and print soon-to-expire URLs to text file.
    if days_until_expiration < 30:
        cprint('DANGER!!!', 'red', 'on_green')
        cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'red', 'on_green')
        cprint('DANGER!!!', 'red', 'on_green')
        write_to_file('danger.txt', url, days_until_expiration, resulter)
    elif days_until_expiration > 31 and days_until_expiration < 91:
        cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'yellow', 'on_blue')
    else:
        cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'green')

```


texts: Linear Equation in Two Variables Solver using Python

texts:
I made this simple program that can solve every set of linear equations in two variables.

You just need to enter two linear equations of the form ax+by=c (without any unnecessary spaces) where 'a' is a positive integer (i.e. x should not have a negative coefficient) and b and c are just integers.

The program can also show outputs like "The two equations have no solution" or "the two equations have infinite solutions" if it is so...

I only used the knowledge of 9th and 10th grade Python along with the concept of functions to make this program and I will update it on the basis of the suggestions that I got from some great people in my last question. I will try to make it shorter, more readable and definitely more efficient soon, will post that too when done.

Here's the Python code :

def getindex(a,b):
    size = len(b)
    status = 0
    for i in range(0,size,1):
        element = b[i]
        if (element == a):
            index = i
            status = 1
            break
    if (status == 1):
        return index
    else:
        return "not found"

def getstring(a,b,c):
    string = c[a]
    for i in range(a+1,b,1):
        element = c[i]
        string = string + element
    return string

def lcm(a,b):
    found = False
    if (a>b):
        larger = a
    else:
        larger = b
    i = larger
    while found == False:
        if (i%a == 0) and (i%b == 0):
            found = True
            break
        else:
            i += larger
    return i

print ()
print ("Please enter two equations of the form ax+by=c where a is a positive integer and b and c are integers...")
print ()
a = str(input("Please enter the first equation : "))
b = str(input("Please enter the second equation : "))
a = list(a)
b = list(b)
sizea = len(a)
sizeb = len(b)

# Getting a, b and c of equation one

symbolindexone = getindex('+',a)
equalindexone = getindex('=',a)
symbolstatusone = "positive"
if (symbolindexone == "not found"):
    symbolindexone = getindex('-',a)
    symbolstatusone = "negative"
xindexone = getindex('x',a)
yindexone = getindex('y',a)
a1 = getstring(0,xindexone,a)
if (a1 == 'x'):
    a1 = 1
else:
    a1 = int(a1)
b1 = getstring(symbolindexone+1,yindexone,a)
if (b1 == 'y'):
    if (symbolstatusone == 'positive'):
        b1 = 1
    else:
        b1 = -1
else:
    b1 = int(b1)
    if (symbolstatusone == "negative"):
        b1 = -b1
c1 = getstring(equalindexone+1,sizea,a)
c1 = int(c1)

# getting a, b and c of equation two

symbolindextwo = getindex('+',b)
equalindextwo = getindex('=',b)
symbolstatustwo = 'positive'
if (symbolindextwo == 'not found'):
    symbolindextwo = getindex('-',b)
    symbolstatustwo = 'negative'
xindextwo = getindex('x',b)
yindextwo = getindex('y',b)
a2 = getstring(0,xindextwo,b)
if (a2 == 'x'):
    a2 = 1
else:
    a2 = int(a2)
b2 = getstring(symbolindextwo+1,yindextwo,b)
if (b2 == 'y'):
    if (symbolstatustwo == 'positive'):
        b2 = 1
    else:
        b2 = -1
else:
    b2 = int(b2)
    if (symbolstatustwo == 'negative'):
        b2 = -b2
c2 = getstring(equalindextwo+1,sizeb,b)
c2 = int(c2)

# LCM and the final phase

lcma = lcm(a1,a2)
tmbone = lcma/a1
tmbtwo = lcma/a2
a1 *= tmbone
b1 *= tmbone
c1 *= tmbone
a2 *= tmbtwo
b2 *= tmbtwo
c2 *= tmbtwo
ratioa = a1/a2
ratiob = b1/b2
ratioc = c1/c2
print ()
if (ratioa == ratiob == ratioc):
    print ("The equations that you entered have infinite solutions...")
elif ((ratioa == ratiob) and (ratioa != ratioc)):
    print ("The equations that you entered have no solution...")
else:
    ysolution = (c1-c2)/(b1-b2)
    xsolution = ((c1)-(b1*ysolution))/(a1)
    print ("The value of x is : ",xsolution)
    print ("The value of y is : ",ysolution)

Let me know what you think

Thanks :)


texts: Calculate Twitter Follower Changes Over Time

texts:
I have a code that grabs quickly the twitter followers for 12 different users. After appending to a Pandas DataFrame, the data is compared to the same file pulled the day before.

It allows me to see which users have gained, lost, and returned followers.

The code works fine. However, the for loop to compare changes between days is slow. Any ideas how to help me out with the for loop section?

TRANSFORMATION FUNCTIONS

# Transformation Functions

# Gained Users

def gained_users(account, new, old):

    gained_followers = []

    old_user_ids = old.Follower_ID[old.Handles == account].unique().tolist()
    new_user_ids = new.Follower_ID[new.Handles == account].unique().tolist()

    gained = list(set(new_user_ids) - set(old_user_ids))

    gained_followers.extend(map(str, gained))

    return gained_followers

# Lost Users

def lost_users(account, new, old):

    old_user_ids = old.Follower_ID[old.Handles == account].unique().tolist()
    new_user_ids = new.Follower_ID[new.Handles == account].unique().tolist()

    lost = list(set(old_user_ids) - set(new_user_ids))

    return lost

# Returned Users

def returned_users(account, new, old):

    returned_followers = []

    new_user_ids = new.Follower_ID[new.Handles == account].unique().tolist()
    returned_user_ids = old.Follower_ID[(old.Handles == account) & (old.End_Date.notnull() == True)].unique().tolist()

    returned =  list(set(returned_user_ids).intersection(new_user_ids))

    returned_followers.extend(map(str, returned))

    return returned_followers

FOR LOOP SECTION

# Add Returned Users

for username in lookup_users:

    returned_ids = returned_users(username, new_followers_df, historical_followers_df)

    if returned_ids:

        historical_followers_df.loc[(historical_followers_df["Handles"] == username) & (historical_followers_df["Follower_ID"] == ids), "Start_Date"] = today
        historical_followers_df.loc[(historical_followers_df["Handles"] == username) & (historical_followers_df["Follower_ID"] == ids), "Returned_After_Days"] = pd.to_datetime(historical_followers_df.Start_Date) - pd.to_datetime(historical_followers_df.End_Date)
        historical_followers_df.loc[(historical_followers_df["Handles"] == username) & (historical_followers_df["Follower_ID"] == ids), "End_Date"] = np.NaN

# Add Lost Users

for username in lookup_users:

    lost_ids = lost_users(username, new_followers_df, historical_followers_df)

    if lost_ids:

        for ids in lost_ids:

            historical_followers_df.loc[(historical_followers_df["Handles"] == username) & (historical_followers_df["Follower_ID"] == ids), "End_Date"] = today

# Add Gained Users

for username in lookup_users:

    new_ids = gained_users(username, new_followers_df, historical_followers_df)

    if new_ids:

            gained_users_list = pd.DataFrame({
            "Handles": username,
            "Follower_ID": new_ids,
            "Start_Date": today})

            historical_followers_df = gained_users_list.append(historical_followers_df, ignore_index=True)

EDIT:

Hi @Graipher thanks for your help. The reasoning makes sense and the structure is much neater! Hopefully if you don't mind, can you please answer these three questions:

1. Could you explain the old_account = old.Handles == account passage, as I have never seen it before!

2. If I run the code as it is it says that old_followers = user_followers & (historical_followers_df["Follower_ID"] == ids) is this because ids in the filter is not specified?

If so, Is it correct to say that:

a. I have to amend the categorize_users function above. Adding:  old = map(str, old_user_ids)  and   return old, gained, lost, returned
b. In the for loop where I call a function I add a new variable ids so that it looks like: ids, new_ids, lost_ids, returned_ids = categorize_users(username, new_followers_df, historical_followers_df)

3. Finally, I think that there's a problem with new_ids as it says that TypeError: object of type 'map' has no len()

a. Is this a code problem? I can't really figure that part out.


texts:
I've made a templated math vector struct with a templated type and templated dimension count.

I want my vectors to be convertible so I can easily make, for example, a vec<int, 3> from a vec<float, 3>

I want to do it in a safe way, or at least I'd like to know the ways it's unsafe.

I've never used static_cast or dynamic_cast and I've never used the operator user-defined conversion.

Here is what I came up with (only the relevant parts of the struct):

template<class t, size_t dimensions> struct vec{
    typedef t coord_type;
    static constexpr size_t dimension_count = dimensions;

    std::array<coord_type, dimension_count> coords;

    template<class new_coord_type> operator vec<new_coord_type, dimension_count>() const{
        std::array<new_coord_type, dimension_count> casted_coords;
        std::transform(
            coords.begin(),
            coords.end(),
            casted_coords.begin(),
            [](coord_type coord){return static_cast<new_coord_type>(coord);}
        );
        return {casted_coords};
    }
};

It seems to work how I want it to. For example, this compiles and gives me the correct results:

vec<float, 3> v1{1.1f, 2.5f, 3.9f};
vec<int, 3> v2 = v1; // converted correctly to {1, 2, 3}

The only way I could figure out how to cast the contents of an array is to use std::transform. I'm not sure if there's a better way.

Final questions: Is this unsafe or incorrect? How can this be improved?


texts: A Ruby implementation of derangement (secret santa) algorithm

texts:
A secret santa gift exchange is a game where each player is randomly assigned a person to whom they anonymously give a gift. The algorithm is referred to as Derangement.

For example, given the following players:

  Mohamad, Carolina, Sami, Tania, Ikram, José

A game may be:

  Mohamad gets Sami
  Carolina gets José
  Sami gets Tania
  Tania gets Mohamad
  Ikram gets Carolina
  José gets Ikram

The important rules are:

A person can not be assigned to themselves.
A person can only be assigned to another person once.
Assignment must be random.

Implementation

This is my object oriented implementation. I do not like my random_player_for implementation. It seems procedural and the use of temporary flags seems like a code smell.

How would you improve this implementation?

class Derangement
  attr_reader :game

  # for convenience
  # PLAYERS = %w[Mohamad Carolina Sami Tania Jose Ikram Rabii Ahmad Kazem]

  def initialize(players)
    @players = players
    @santas = players.dup
    @game = {}
  end

  def solve
    @santas.each do |santa|
      @game[santa] = random_player_for(santa)
    end
  end

private

  def random_player_for(santa)
    found = false
    until found do
      player = @players.sample
      unless player == santa
        found = true
        @players.delete(player)
      end
    end
    player
  end
end


texts:
I'm just getting started with Python and was hoping for some feedback on a simple Tic-Tac-Toe game I wrote. Specifically, is there a simpler way to check the win conditions for the game, and to break the loops at the end without repeating the code twice, and just generally how to shorten this to achieve a similar effect?

print("Player 1 is 'X' and Player 2 is 'O'.\nEnter a number (0-8) to choose a \
space on the board.\nTake turns entering values until someone wins.\n\n[0, 1, 2] \
\n[3, 4, 5]\n[6, 7, 8]")

class Player:
    def __init__(self,num,XO):
        self.num = num
        self.XO = XO

p1 = Player(1,'X') #odd
p2 = Player(2,'O') #even

plist = [p1,p2]

b = [['0','1','2'], ['3','4','5'], ['6','7','8']]
i = 0

while True:
    for plyr in plist:
        while True:
            try:
                p = int(input(f'Player {plyr.num}, enter a number: '))
                row = int(p/3)
                cel = p%3
                if b[row][cel] is not 'X' and b[row][cel] is not 'O':
                    b[row][cel] = plyr.XO
                    break
                else:
                    print(f"Space already taken by {b[row][cel]}")
            except ValueError:
                print("That's not a valid number. Try again and choose 0-8.")

        bf = f"{b[0]}\n{b[1]}\n{b[2]}"
        print(bf)

        i+=1
        def CheckWin(b):
            if b[0][0]==b[0][1]==b[0][2]==plyr.XO or b[0][0]==b[1][0]==b[2][0]==plyr.XO or \
            b[0][0]==b[1][1]==b[2][2]==plyr.XO or b[0][1]==b[1][1]==b[2][1]==plyr.XO or \
            b[1][0]==b[1][1]==b[1][2]==plyr.XO or b[2][0]==b[2][1]==b[2][2]==plyr.XO or \
            b[0][2]==b[1][2]==b[2][2]==plyr.XO:
                print(f"Player {plyr.num} ('{plyr.XO}') wins!")
                return 1
            else:
                pass

        win = CheckWin(b)
        if not win and i<9:
            pass
        elif not win and i==9:
            print('The match is a tie.')
            break
        else:
            break
    if not win and i<9:
        pass
    elif not win and i==9:
        break
    else:
        break


texts: JavaScript sound manager (singleton / static object using observer pattern)

texts:
I have some JavaScript code i would like your feedback on please.

My goals:

SoundManager should be a singleton/static class that has one instance.
SoundManager should have an observer pattern so that other objects can subscribe to "progress" and "complete" events

So far this is working great, but I'm wondering if I could be doing anything better.

define(['Howler'], function(Debug, Howler) {
  var instance = undefined;
  var SoundManager = function() {
    var listeners = {},
        sounds = {},
        manifest = {},
        numLoaded = 0,
        totalSounds = 0;

    instance = {
      events: {
        complete: 'soundmanager.events.complete',
        progress: 'soundmanager.events.progress'
      },
      on: function(eventName, callback) {
        if (!listeners[eventName]) {
          listeners[eventName] = [];
          listeners[eventName].push(callback);
        }
      },
      dispatch: function(eventName, payload) {
        if (listeners[eventName]) {
          for (var i = 0; i < listeners[eventName].length; i++) {
            listeners[eventName][i](payload);
          }
        }
      },
      play: function(id) {
        sounds[id].play();
      },
      createSound: function(item) {
        var sound = new Howl({
          id: item.id,
          src: item.src,
          autoplay: item.autoplay || false,
          loop: item.loop || false,
          volume: item.volume || 0.5,
          onload: this.onSoundLoaded(item)
        });
        sounds[item.id] = sound;
      },

      onSoundLoaded: function(item) {
        numLoaded++;
        this.dispatch(this.events.progress, numLoaded / totalSounds * 100);
        if (numLoaded == totalSounds)
          this.dispatch(this.events.complete);
      },

      loadManifest: function(items) {
        manifest = items;
        totalSounds = items.length;
        for (var i = 0; i < totalSounds; i++)
          this.createSound(manifest[i]);
      },
    }
    return instance;
  }

  if (instance === undefined)
    instance = new SoundManager();

  return instance;
});

Example usage

// index.html will need
<script src="js/require.js" data-main="js/main"></script>

// this would be in your js/main.js file

requirejs.config({
  baseUrl: 'js',
  paths: {
    'Howler': 'js/howler.min'
  }
});

// assumes "js/soundmanager.js"
requirejs(['soundmanager'], function(SoundManager){
  SoundManager.loadManifest([
    {"id": "sound1", "src": ["path/to/sound.mp3"]},
    {"id": "sound2", "src": ["path/to/sound2.mp3"]}
  ]);
  SoundManager.on(SoundManager.events.complete, function() {
    console.log('finished loading sounds');
  });
  SoundManager.on(SoundManager.events.progress, function(progress) {
    console.log('progress: '+ progress);
  });
})


texts: Writing unit tests for exception should be thrown case

texts:
Can anyone here comment on the quality of this test case? I am here testing for the exception should be thrown scenario. I mean it works but is it the correct way to unit test for the scenarios where the expectation is that exception should be thrown?

it('should throw exception if config.env.json is malformed', async () => {
  // Arrange: beforeEach
  const fakeFsStub = sinon.stub(File, 'readFileAsyc');
  fakeFsStub.withArgs('./src/configuration/config.json').returns(mockConfig);
  fakeFsStub.withArgs('./src/configuration/config.test.json').returns(FakePromise.resolve(`{"key"}`));

  try {
    // Act
    await Configuration.getConfiguration('test');
    chai.assert.fail('test case failed: [should throw exception if config.env.json is malformed]');
  } catch (e) {
    // Assert
    chai.assert.equal('SyntaxError: Unexpected token } in JSON at position 6', e + '');
  }
});


texts:
I have a calendar table with a record for every date I need to care about (i.e. 365 records per year), with various meta-information about each date, including the weekday, the fiscal calendar week, month, quarter and year it's under, whether there's a Holiday on that date, etc.

The table has the following keys / indexes:

,constraint PK_FiscalCalendars primary key clustered (_Id)
,constraint NK_FiscalCalendars unique (CalendarDate)

and:

create nonclustered index IX_FiscalCalendars_HolidayFiscalDayOfWeek
    on dwd.FiscalCalendars (Holiday, CalendarDate, FiscalDayOfWeek);

That's nice, but now I need to use this calendar table in various queries, and one of my requirements is to be able to determine the number of workdays between two dates, taking into account the contents of the Holiday column, which contains a non-null nvarchar(50) value (the name of the Holiday / reason for closing) whenever a weekday/date shouldn't be considered a workday; the column contains a NULL value otherwise.

So I've implemented this little function that intakes two dates and returns the number of workdays between them (inclusively):

create function dbo.WorkWeekDateDiff(@fromDate date, @toDate date)
returns int
as
begin

    /* returns the number of workdays (non-holiday week days) between two dates. */
    declare @result int;

    with calendar as (
        select CalendarDate
        from dwd.FiscalCalendars
        where
            CalendarDate between @fromDate and @toDate
        and Holiday is null -- exclude holidays
        and FiscalDayOfWeek not in (1,7) -- exclude Sunday and Saturday
    )

    select @result = (select count(*) from calendar);
    return @result;

end

Execution plan is showing 73% of the cost going on seeking the non-clustered index, and 27% performing that Count(*). It gets the job done, but since this is a scalar-valued function I'd like it as efficient as possible. Is there anything to improve?


texts: Loading more items for an activity feed that uses a global page counter

texts:
I have this script which is for a news feed. A button click will grab more data from the server if there is any and then add it to the box. It doesn't allow any more than 10 pages of results currently and how to properly store that page counter is what this question is about.  loadMoreFeedItems() is the function attached to the onclick event of the aforementioned button.

<script type="text/javascript">

    window.page = 0;

    function loadMoreFeedItems() {
        var options = {};
        options.page = window.page;
        $.ajax({
            url: "home/feed",
            data: options,
            dataType: "html",
            success: function (data) {
                // Code to append the data received into the feed element
                window.page++;
                // Code to hide "load more" button if window.page exceeds 10
            }
        });
    }

    (function () {
        loadMoreFeedItems();
    })();

</script>

So I did a little reading about global variables in JavaScript[1][2][3]  and while this works, I got the vibe that this could be problematic, so I'm wondering if there is a better way. One alternative I thought of was to create some kind of hidden  that stores the value in page rather than the browser, and then I'd modify/retrieve it using a jQuery selector, but that seems even dirtier.


texts:
I have a service class called ClientService, the service class is called using an interface IClientService. The service class simply does CRUD methods for the DbSet<Client> in my context class.  In my service class constructor I have:

private MyContext context;
public ClientService()
{
    context = new MyContext();
}

I then have a void in the ClientService class that can be called from the IClientService interface called Save() that does this:

public void Save()
{
    context.SaveChanges();
    context.Dispose();
    context = new MyContext();
}

Is this safe or even necessary or am I good simply saying context.SaveChanges(); in the Save() void?


texts: Data Structures for Counting Duplicates and using std::vector::erase

texts:
Problem
Dupe detection for a vector of ints. I simply want a count of the unique input characters that occurred at least twice. The goal is to count a dupe only once and ignore that input character if another dupe of it is seen in the future. A test input could look something like this vector<int> test = { 4,5,9,6,9,9,6,3,4 };
Looking for Feedback on
Looking for basic feedback on the data structures I'm using and the possibility of using the vector erase method to iterate and take advantage of the space allocated to my numbers vector instead of using a map to not count dups more than once. Any C++ 11 or 17 features I can take advantage of here too?
int countDuplicates(vector<int> numbers) {
    int dups = 0;
    set<int> s;
    map<int, int> m;
    for (int n : numbers) {
      if (s.insert(n).second == false && m.find(n) == m.end()) {
          dups++;
          m.insert(pair<int, int>(n,0));
          // better to remove from vector than increase space with the map?
          // numbers.erase(remove(numbers.begin(), numbers.end(), n), numbers.end());
        } else {
          s.insert(n);
        }
    }

    return dups;
}


texts:
I have written a function buildGroupRequests() to build an array of multiple groups.

It checks the size of the request group. If a request group is greater than MAXSIZE = 50 then it will create another group in an array.

The logic seems to be complicated, is there a way to rewrite this to be more readable and maintainable in future?

console.log(
  buildGroupRequests([
    { put: "/firstName=Danny" },
    { put: "/lastName=Williams" },
    { put: "/email=danny.w@domain.com" }
  ])
);

function buildGroupRequests(lists) {
  const MAXSIZE = 50;

  return lists.reduce((group, insert) => {
    const LASTINDEX = group.length - 1;

    if (!group.length) {
      group.push({ put: "PUT " + insert.put });
      return group;
    }

    const putGroup = group[LASTINDEX];
    const tempPutSet = putGroup.put + " + " + insert.put;

    if (tempPutSet.length > MAXSIZE) {
      group.push({ put: "PUT " + insert.put });

      return group;
    }

    group[LASTINDEX].put = tempPutSet;
    return group;
  }, []);
}


texts: Improve performance of math function applied to arrays

texts:
This block of code is already somewhat optimized thanks to some answers given over at Stack Overflow. In the last question I made (Improve performance of function without parallelization) the code was marginally improved but I later had to re-write a little bit of it and the changes proposed didn't apply anymore.

I'm looking at optimizing this block of code without resorting to parallelization, other than that I'm pretty much open to using any package out there.

I think this is perhaps the correct site to post this since it's really more of a question about how can I improve my code rather than something not working with it.

Here's the MWE (minimum working example):

import numpy as np
import timeit

def random_data(N):
    # Generate some random data.
    return np.random.uniform(0., 10., N)

# Data lists.
array1 = np.array([random_data(4) for _ in range(1000)])
array2 = np.array([random_data(4) for _ in range(2000)])

def func():
    lst = []

    for elem in array1:

        # Define factors.
        a_01, a_11 = max(elem[1], 1e-10), max(elem[3], 1e-10)
        a_02, a_12 = array2[:,1], array2[:,3]
        # Combine the factors defined above.
        a_0 = a_01**2 + a_02**2
        a_1 = a_11**2 + a_12**2
        Bs, Cs = -0.5/a_0, -0.5/a_1

        # Perform operations.
        A = 1./(np.sqrt(a_0*a_1))
        B = Bs*(elem[0]-array2[:,0])**2
        C = Cs*(elem[2]-array2[:,2])**2
        ABC = A*np.exp(B+C)

        lst.append(max(ABC.sum(), 1e-10))

    return lst

# Time function.
func_time = timeit.timeit(func, number=10000)
print func_time