texts:
Here is piece of code with few if ... else, I appreciate if anyone can clean it.

def process_link(post_script_link_list,read_str):
    links_list1 = ['Wq','Ws','Wi','Wd']
    bad_list = ['How long','how long','How much','how much']
    links_list2 = ['Qd']
    result = ''
    for item in bad_list:
        if item in read_str:
            return
    sent_split = read_str.split()
    for linking in post_script_link_list:
        sub_link = re.search('\((.*?)\)',linking).group(1)
        if sub_link in links_list1:
            if ('Who').lower() in sent_split or 'Who' in sent_split:
                result = 'person'
                break
            elif (('Where').lower() in sent_split or 'Where' in sent_split) and 'What' not in read_str and 'what' not in read_str:
                result = 'location'
                break
            elif ('Why').lower() in sent_split or 'Why' in sent_split:
                result = 'reason'
                break
            elif ('How many').lower() in read_str or 'How many' in read_str:
                result = 'count'
                break
            elif (('When').lower() in sent_split or 'When' in sent_split) and 'What' not in read_str and 'what' not in read_str:
                result = 'time'
                break
            elif (('How').lower() in sent_split or 'How' in sent_split) and ('How long').lower() not in read_str and 'How long' not in read_str and ('How much').lower() not in read_str and 'How much' not in read_str:
                result = 'manner'
                break
        elif sub_link in links_list2:
            check_yn = verify_yesno(post_script_link_list)
            if check_yn == 1:
                result = 'Yes/No'
                break
            elif check_yn == 0:
                result = 'noresult'
                break
            break
        else:
            result = 'noresult'
    return result


texts: Proxy using socket, doubts on multithreading and connection closing

texts:
I'm trying to make a simple proxy server in Python using the socket library, mostly to understand how it works.  I'm a noob both at programming and networking, so please be nice if my questions are totally dumb.

At the moment I've set up a proxy server which intercepts requests from the browser, prints them and sends back an "Hello" sample response. It seems to work, so next I'm going to complete it by adding a client which forwards the request to the web server, receives the response and sends it back to the browser.

However, I have two doubts about this first (seemingly working) part of the code:

import socket, threading
serv_port = 50007
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', serv_port))
server.listen(5)
while True:
    #get conn to client
    conn, addr = server.accept()
    #span thread
     conn_thread = threading.Thread(target=cthread, args=(conn,))
    conn_thread.start()

 def cthread(conn):
    #set timeout
    conn.settimeout(1)
    #receive data until null data is received or socket times out
    req = b''
    while True:
        try:
              req_pack = conn.recv(4096)
            if not req_pack:
                break
            else:
                req += req_pack
        except socket.timeout:
                      break

   print req #print request to stdout

   #send a sample response
   conn.send(b'HTTP/1.1 200 OK\n\n
Hello</h1') #QUESTION 1

   conn.close() #QUESTION 2

My first question is about threading. Should I leave everything as it is, or should I, after receiving a request, span a different thread to deal with the response part?

Sample code of what I mean:

#in function cthread
print req
#span thread
resp_thread = threading.Thread(target=respthread, args=(conn, req))
resp_thread.start()

def respthread(conn, req):
    #do everything that's to be done to get response, send it to browser
    conn.send(b'HTTP/1.1 200 OK\n\n
Hello</h1') #sample response
    conn.close()

Another question: is it correct to close the connection to the browser (conn) after each response has been sent, or does it slow connections too much and it's possible to do without?


texts:
In PHP/Laravel  I have the following function. Can you please review my approach?

private function array_swap_assoc($key1, $key2, $array)
    {
        $newArray = array();
        foreach ($array as $key => $value) {
            if ($key == $key1) {
                $newArray[$key2] = $array[$key2];
            } elseif ($key == $key2) {
                $newArray[$key1] = $array[$key1];
            } else {
                $newArray[$key] = $value;
            }
        }
        return $newArray;
    }


texts:
This code inserts data into the database successfully. I was concerned about whether it is a considered good practise to go about inserting data into the database in this way. Is there something I am not considering?

function insertTest(){

    global $db;

    $field_names    = array("id", "first_name", "last_name", "email");
    $alias          = array(":id", ":fn", ":ln", ":em");
    $assignment     = array(":id" => "2k39dk38dk2k39dk38dk2k39dk38dk2k39dk38dk",
                            ":fn" => "Chris",
                            ":ln" => "Moore",
                            ":em" => "test@gmail.com");

    $array = array();
    $array['table'] = 'users';
    $array['field_names'] = $field_names;
    $array['alias'] = $alias;
    $array['assignment'] = $assignment;

    $q = "INSERT INTO `%s` (%s) VALUES (%s)";
    $q = sprintf($q, $array['table'], implode(", ",$array['field_names']), implode(", ",$array['alias']));
    $q = $db->prepare($q);
    $r = $q->execute($assignment);

    print_r($r);

    return $r;

}


texts:
I am learning about polymorphism in C++ and decided to implement an example. Is there anything I need to fix in my code? This compiles and runs.

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

class Employee
{
public:
    Employee():salary(1000){}
    virtual ~Employee(){}
    virtual void Talk() const {cout << "Employee says: ";}

protected:
    int salary;
};

class Programmer : public Employee
{
public:
    void Talk() const {cout << "I am a Programmer.\n";}
    void Compiling() const {cout << "My code is compiling...\n";}
};

class SalesPerson : public Employee
{
public:
    void Talk() const {cout << "I am a SalesRep.\n";}
    void Selling() const {};
};

int main()
{
    const int numEmployees = 3;
    Employee* Company[numEmployees];
    Employee* pEmployee;

    int choice,i;

    for(i=0; i<numEmployees; i++)
    {
        std::cout << "(1) Programmer (2) SalesRep: ";
        cin >> choice;
        if(choice == 1)
            pEmployee = new Programmer;
        else
            pEmployee = new SalesPerson;

        Company[i] = pEmployee;
    }

    cout << endl;

    for(i = 0; i<numEmployees;i++)
    {
        Company[i]->Talk();

        Programmer *pCoder = dynamic_cast<Programmer *> (Company[i]);

        if(pCoder)
            pCoder->Compiling();

        cout << endl;
    }

    return 0;
}


texts:
I have a basic swing application that I am trying to develop using MVC structure.

The principal class in the model connects to a derby database and retrieves values from columns and stores them in arrays.

My methods in the model (Connect(), Retrieve()) are public void. In runApp(), which is a SwingUtilities runnable, I am calling my model methods like this:

public static void runApp() {
    Model model = new Model();
    model.Connect(); //Connects to database
    model.Retrieve(); //Retrieves database column values from tables, creates arrays
    View view = new View(model);
    Controller controller = new Controller(view, model);
    view.setCalculateListener(controller);
}

I am trying to write this program so that everything is as less tightly coupled as possible.  This code currently works as is, but I would like to do this better.

My question: How can I do this in a less coupled manner? Rather than having the methods being called here, is there a better way to do this?


texts:
I've built a simple Book list app. It allows users to enter the name, author and isbn of a book into a form. Then when this is submitted successfully, the details get added to a new row in the table.

I've tried to make the code as optimal as possible. Any feedback would be greatly appreciated.

const bookList = document.getElementById('book-list');

class Book {
  constructor(title, author, isbn){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }

  addBook(){
    const bookList = document.getElementById('book-list');
    const bookItem = document.createElement('tr');

    bookItem.innerHTML =`
      ${this.title}
      ${this.author}
      ${this.isbn}
      <button type="submit" class="delete">X</button>	`;

    return bookList.appendChild(bookItem);
  }

  static deleteBook(target){
    target.originalTarget.parentElement.parentElement.remove();
  }
}

// Event Listener: Form Submit
form.addEventListener('submit', function(e){
  const bookFields = getFields();

  if(!validateForm(bookFields)) {
    showNotification('Error', 'error');
    e.preventDefault();
    return false;
  }

  const book = new Book(
    bookFields.title,
    bookFields.author,
    bookFields.isbn
  );

  book.addBook(book);

  showNotification('Success', 'success');
  this.reset(); // Reset Form

  e.preventDefault();
});

// Event Listener: Delete Book
bookList.addEventListener('click', function(e){
  Book.deleteBook(e);
  showNotification('Deleted Item', 'success');
});

function getFields(){
  return fields = {
    'title': document.getElementById('title').value,
    'author': document.getElementById('author').value,
    'isbn': document.getElementById('isbn').value
  };
}

function validateForm(fields){
  for(let [key, value] of Object.entries(fields)){
    if(value === '') return false;
  }
  return true;
}

// Notification
function showNotification(message, type){
  const container = document.querySelector('.container');
  const alert = document.createElement('div');

  alert.classList = `${type}`;
  alert.appendChild(document.createTextNode(message));

  container.insertBefore(alert, form);

  setTimeout(function(){
    alert.remove();
  }, 1500);
}```


texts:
The following tail-recursion example is taken verbatim from Chris Smith's Programming F# 3.0. If this is not the appropriate forum for this post, I will gladly move the post to the appropriate place. I did not post this in SO, because I do not have a problem to solve.

let printListRev list =
    let rec printListRevTR list cont =
        match list with
        // For an empy list, execute the continuation
        | [] -> cont()
        // For other lists, add printing the current
        // node as part of the continuation.
        | hd :: tl ->
            printListRevTR tl (fun () -> printf "%d " hd
                                         cont())

    printListRevTR list (fun () -> printfn "Done!");;

What exactly is cont() continuing. I believe I understand the concept that cont() is encapsulating the remaining work to be done, but I am still a little confused about what is going on.
This SO post contains use of the keyword loop in @Juliet 's answer. I am confused as to why loop is used in that answer and not used in the example above.


texts:
Algorithm: Determine if an array of arrays of characters can be
  concatenated in order, into a substring of haystack.

  Example:

[['a','A','@'], ['b','B','8'], ['c','(','[']]

  This list can be combined by selecting from each of the subarrays in
  order, such as:

  abc, ab(, ab[, Abc, Ab( etc.

  Are any of these combinations substrings of the search string?

"123 easy as Ab(" # True
"123 easy as Abb" # False
"123 easy as @b(" # True
"123 easy as Abc" # False

Python 3

combos = [['a','A','@'], ['b','B','8'], ['c','(','[']]
search = "123 easy as Ab(" # True

def find_mutated_string(offset, combos, search):
    for i, char in enumerate(search):
        for mutant in combos[offset]:
            if mutant == char:
                if len(combos) == (offset+1):
                    # Last letter combo found
                    return True
                else:
                    return find_mutated_string(offset+1, combos, search[i+1:])
    # Didn't find mutant char in search string
    return False

print(find_mutated_string(0, combos, search))


texts: Displaying categories and subcategories in php having different tables

texts:
Just wanted to ask if there is an other way of PHP coding for displaying my subcategories and subsubcategries than mine.

My tables:

Categories
-------------------------
cat_ID | cat_name
------------------
4      | Baby & Kids
5      | Bicycles
6      | Boats
7      | Books & Comics
....
13     | Clothes & Accessories
....
35     | Sport & Fitness
36     | Study
....
38     | Toys & Games
....

Subcategories
-------------------------
subcat_ID | cat_ID | extra_cat_ID | subcat_name
------------------------------------------------
....
15        | 4      | 13           | Baby clothes
16        | 4      | 0            | Baby products
17        | 4      | 13           | Kids clothes
18        | 4      | 38           | Toys
19        | 5      | 0            | Bycicles
20        | 5      | 0            | Bycicle gear & Accessories
21        | 6      | 0            | Boat parts
22        | 6      | 0            | Other Boats
23        | 6      | 0            | Power Boats
24        | 6      | 0            | Sailboats
25        | 6      | 35           | Windsurf & Surfing
26        | 7      | 0            | Antiquarian
27        | 7      | 0            | Books
28        | 7      | 38           | Childrens books
29        | 7      | 0            | Comics
30        | 7      | 0            | Magazines & Newspapers
31        | 7      | 36           | Study & Training

Subsubcategories
-------------------------
subsubcat_ID | subcat_ID | subsubcat_name
-----------------------------------------
...
470          | 15        | Baptism outfits
471          | 15        | Bibs
472          | 15        | Body warmers
473          | 15        | Bodysuits
....
496          | 16        | Baby bath
497          | 16        | Baby books
498          | 16        | Baby inserts
499          | 16        | Baby monitors
....
548          | 17        | Belts
549          | 17        | Blouses & Shirts
550          | 17        | Body warmer
551          | 17        | Boots
....
....
740          | 26        | Music
741          | 26        | Navy
742          | 26        | Novel
743          | 26        | Photography
....
....
867          | 30        | Animals
868          | 30        | Arts and Culture
869          | 30        | Branch
870          | 30        | Cars
870          | 30        | Computers
....
....
etc.

I know it's just super basic HTML, but what I want to do is this:

subcat_name 1

subsubcatname 1
subsubcatname 2
subsubcatname 3
subsubcatname 4
subsubcatname 5
subsubcatname 6
subsubcatname 7

subcat_name 2

subsubcatname 8
subsubcatname 9
subsubcatname 10
subsubcatname 11
subsubcatname 12

subcat_name 3

subsubcatname 13
subsubcatname 14
subsubcatname 15
subsubcatname 16
subsubcatname 17
subsubcatname 18

etc ...

My code I use right now:

$result=mysqli_query($connect,"SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = $cat_ID OR subcategories.extra_cat_ID = $cat_ID ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC");
$lastcat = 0;
while ($row = mysqli_fetch_array($result)){
    if($lastcat != $row['subcat_ID']){
        $lastcat = $row['subcat_ID'];
        echo "
";
        echo $row['subcat_name'];
        echo "
";
        echo "
";
        }
    echo $row['subsubcat_name'];
    echo "
";
    }

My code is working fine but what I want to know is if there is a better or safer way of handling it in PHP? Or am I doing it the right way?


texts:
Problem: Arithmetic expressions

  Given a list of 2..10,000 integer numbers in a range of 1..100 place operators +, - or/and * between them, so that the whole expression results in a number divisible by 101. Output the resulting expression.
  Note, the operators have no precedence and are left-associative: expression a+b*c-d*e shall be interpreted as (((a+b)*c)-d)*e.

Link

import java.io.*;
import java.util.*;

public class Solution {

    static int array[];

    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       int n = s.nextInt();
       array = new int[n];
       for (int i = 0; i < n; i++)
           array[i] = s.nextInt();
       System.out.println(array[0] + recursive(array[0], 1));
    }

    public static String recursive(int total, int index) {
       total %= 101;
       if (index == array.length){
           return total == 0 ? "" : null;
       }
       String result =recursive(total-array[index],index +1);
       if (result != null){
          return "-" + array[index] + result;
       }
          result = recursive(total + array[index], index + 1);
       if (result != null){
          return "+" + array[index] + result;
       }
       result = recursive(total * array[index], index + 1);
       if (result != null){
          return "*" + array[index] + result;
       }
       return null;
    }
}

I have tried multiple submissions with alternating the sequence of '+','-','*' and also tried same solution in C but always get the "Terminated due to timeout" message. I am the end of my thinking capacity and would appreciate any help possible.

Note: Changing the sequence of '+','-','*' in recursive function check helped me with few test cases during each sequence , but didn't pass all the test cases for any sequence.


texts:
This question is a follow-up. The original question was itself a follow-up to an older question by @LokiAstari.

  The idea is to provide a compile-time integer range.

This version incorporates almost everything from the answers and comments to the previous iteration of the review (except the handling of corner cases such as INT_MAX, which is kind of hard). Along with the fixes comes a new feature: the possibility to specify the « step » of the range. Here is the new implementation:

#include <cstddef>
#include <utility>

namespace detail
{
    template<
        typename Integer,
        typename SequenceBase,
        Integer Begin,
        Integer Step,
        bool IsIncreasing
    >
    struct integer_range_impl;

    template<
        typename Integer,
        Integer... N,
        Integer Begin,
        Integer Step
    >
    struct integer_range_impl<Integer, std::integer_sequence<Integer, N...>, Begin, Step, true>
    {
        using type = std::integer_sequence<Integer, (N * Step + Begin)...>;
    };

    template<
        typename Integer,
        Integer... N,
        Integer Begin,
        Integer Step
    >
    struct integer_range_impl<Integer, std::integer_sequence<Integer, N...>, Begin, Step, false>
    {
        using type = std::integer_sequence<Integer, (Begin - N * Step)...>;
    };
}

template<
    typename Integer,
    Integer Begin,
    Integer End,
    Integer Step
>
using make_integer_range = typename detail::integer_range_impl<
    Integer,
    std::make_integer_sequence<
        Integer,
        ((Begin < End ? End - Begin : Begin - End) - 1) / Step + 1
    >,
    Begin,
    Step,
    (Begin < End)
>::type;

template<std::size_t Begin, std::size_t End, std::size_t Step>
using make_index_range = make_integer_range<std::size_t, Begin, End, Step>;

Here is an example of how this template integer range can be used:

#include <array>
#include <iostream>
#include <iterator>
#include <numeric>

template<typename T, std::size_t N, std::size_t... Ind>
auto print(const std::array<T, N>& arr, std::index_sequence<Ind...>)
    -> void
{
    int dummy[] = {
        (std::cout << std::get<Ind>(arr) << ' ', 0)...
    };
    (void) dummy;
}

int main()
{
    std::array<int, 20u> arr;
    std::iota(std::begin(arr), std::end(arr), 0);

    // prints 15 12 9 6 3
    print(arr, make_index_range<15u, 0u, 3u>{});
}

I accept any kind of review, be it about style, correctness or possible improvements to the utility in general :)


texts: Speed up looping through slicers and .selected true if slicer item name matches input words

texts:
Sub SearchSlicer()
Dim oSc As SlicerCache
Dim oSi As SlicerItem
Dim searchword As Variant
searchword = InputBox("Enter a searchword")

Set oSc = ThisWorkbook.SlicerCaches("Slicer_SEARCH_WORDS")

For Each oSi In oSc.SlicerItems
      If oSi.Name Like "*" & UCase(searchword) & "*" Then
          oSi.Selected = True
      Else: oSi.Selected = False
      End If
Next

End Sub

So I have a pivot table with two columns - a column for a verb and a column for search words containing synonyms/similar phrases. For example, if a word in the first column is 'broke', the second column will contain the list 'fell apart, broken, split'.

Running the above code asks the user for a search word which will be used to loop through the search word column and filter the search word pivot table and slicers.

This search word slicer is linked to first column slicer as the search word slicer is not visible on the input sheet.

The reason for using slicers is because I have another code for when the user clicks on a slicer choice, it automatically pastes it into the active cell.

I have a table with 350 rows and this code is already taking very long to run. How can I make this more optimal?


texts:
So my web app requires JWT authentication and I decided to make a mockup wrapper class for php-jwt before implementing it into my web app:

class JWTWrapper{
    public function newToken($issuedAt, $notBefore, $expire, $server, $sessionData){
        $tokenId = base64_encode(mcrypt_create_iv(32));
        $notBefore = $notBefore + $issuedAt;
        $expire = $expire + $notBefore;
        $data = [
            'iat' => $issuedAt,
            'jti' => $tokenId,
            'iss' => $server,
            'nbf' => $notBefore,
            'exp' => $expire,
            'data' => $sessionData
        ];

        $jwt = JWT::encode($data, PRIVATE_KEY, "HS512");

        return $jwt;
    }

    public function getToken($jwt){
        if($jwt){
            try{
                $token = JWT::decode($jwt, PRIVATE_KEY, ["HS512"]);
                return $token;
            } catch(Exception $e){
                return false;
            }
        } else{
            return false;
        }
    }

    public function getTokenData($jwt){
        if($jwt){
            try{
                $token = JWT::decode($jwt, PRIVATE_KEY, ["HS512"]);
                return $token->data;
            } catch(Exception $e){
                return false;
            }
        } else{
            return false;
        }
    }
}

I've been reading over articles about JWT vulnerabilities such as so im really paranoid I might have made some sort of catastrophic mistake like this (even though its not apparent that I have...)


texts:
I am writing a recursive function based on the Travelling Salesman Problem.

Is this a correct way of doing things, or am I creating memory leaks?

Prerequisites are:

a two dimensional matrix distance_matrix[][] to store the distances between the cities
a global int called current_minimum_cost which will be MAX_INT for starters (or any high 'impossible' number), it keeps track of the cost of the current 'optimal' path
remaining_cities: a QList of ints which at starting point contains all the cities to visit (except the HOME_CITY) (every city is represented by an integer, the same integer is used to look up the distance between two cities by using distance_matrix[cityA][cityB].
path: a QList of ints which stores the current path followed (so 0 , 7, 2, 5) means the salesman goes from his HOME_CITY to city #7 to city #2 to city #5 . At starting point it only contains the HOME_CITY (which is 0)
after doing his tour, the salesman has to return to his HOME_CITY (0)

void tsp(QList<int>* path, int total_cost, QList<int>* remaining_cities)
{
    int last_visited_city = path->last();

    if(total_cost > current_minimum_cost)
    {
        //cost higher than current_minimum_cost => ABORT
        return;
    }

    if(remaining_cities->empty())
    {
       //all cities visited

       //only add the distance back to the home city (salesman returns home)
       //path += HOME_CITY en total_cost += terug naar HOME_CITY";
       path->push_back(HOME_CITY);

       total_cost += distance_matrix[last_visited_city][HOME_CITY];

       if (total_cost <= current_minimum_cost)
       {
           // we have a new winner!
           current_minimum_cost = total_cost;

           // forget about the previous 'winner' and save the visited path
           tsp_solution->clear();
           foreach(int element , *path)
               tsp_solution->push_back(element);
       }
       // if not, than it means that "returning home" makes the trip more costly than the previous 'winner' (we always 'return home', so this is also taken into account with the previous 'winner')
       return;
    }

    // calculate the new possibilities to travel to from the current city:
    foreach(int next_city_to_visit , *remaining_cities)
    {
      QList<int>*newPATH = new QList<int>();
      newPATH->append(*path);
      newPATH->push_back(next_city_to_visit);

      int total_cost_for_this_new_path = total_cost + distance_matrix[last_visited_city][next_city_to_visit];

      // make a list of 'remaining cities' to visti:
      QList<int>* newREMAINING_CITIES = new QList<int>();
      newREMAINING_CITIES->append(*remaining_cities);

      // of course we do not have to visit 'next_city_to_visit' twice
      newREMAINING_CITIES->removeOne(next_city_to_visit);

      // recursion:
      tsp ( newPATH , total_cost_for_this_new_path , newREMAINING_CITIES );
      delete newPATH;
      delete newREMAINING_CITIES;
    }
}

My questions:

Does this function make sense? It seems to work for all my test cases.
Once I go up to 20 cities, it takes a long while to calculate, over an hour.
On memory management: is issuing delete newPATH enough to clear the memory? Or should I issue a delete for all members of the list newPATH? (I guess not as the members are all ints)


texts:
I want to do some Monte Carlo simulations on a system based on a pool of dice. For each trial, a number of dies are rolled, and the winner is the highest value, getting as many points as dice are over the second, including ties.

Examples:

[1, 2], [5, 1]  One point for the second (5 is the only value over 2).
[20, 12, 20, 14], [17, 15, 19, 18] Two points for the first one (two 20 over 19).
[20, 12, 20, 14], [17, 15, 20, 18] Two points for the first one (one tie at 20, one die over 18).

Here is my algorithm. Can you think of a better way?

from collections import Counter
import numpy as np

def check_rolls(one, other):
    one_c = Counter(one)
    other_c = Counter(other)
    ties = Counter()

    # Remove ties:
    for tie_val in set(one_c.keys()).intersection(other_c.keys()):
        toremove = min(one_c[tie_val], other_c[tie_val])
        one_c[tie_val] -= toremove
        other_c[tie_val] -= toremove
        ties[tie_val] = toremove

        # Clear if 0
        if one_c[tie_val] == 0:
            del one_c[tie_val]
        if other_c[tie_val] == 0:
            del other_c[tie_val]

    max_one = max(one_c.keys()) if one_c else 0
    max_other = max(other_c.keys()) if other_c else 0

    winner = max_one > max_other
    threshold = min(max_one, max_other)

    if winner:
        # One wins
        result = sum(val for key, val in one_c.iteritems()
                   if key > threshold) + \
                   sum(val for key, val in ties.iteritems()
                       if key >= threshold)
    else:
        result = -(sum(val for key, val in other_c.iteritems()
                    if key > threshold) +
                    sum(val for key, val in ties.iteritems()
                        if key >= threshold))
    return result

def roll(d_player, d_gm):
    return check_rolls(np.random.randint(1, 21, size=d_player),
                       np.random.randint(1, 21, size=d_gm))

def test():
    assert check_rolls([1, 1, 2], [1, 1]) == 3
    assert check_rolls([1, 2, 4, 5], [3, 4]) == 2
    assert check_rolls([1, 2, 4, 5], [3, 5]) == 2
    assert check_rolls([1, 2, 4, 5], [3, 6]) == -1
    assert check_rolls([20, 12, 20, 14], [17, 15, 20, 5, 18, 2]) == 2
    assert check_rolls([20, 10, 2, 4], [ 5, 20, 6, 4, 19, 3]) == -2

I am just using it for a quick and dirty script plotting histograms for different configurations. Performance improvements are welcomed, but they are not critical. Style and integration are of low priority.


texts: DRY code for sending email with SendGrid

texts:
I have this code inside a post route:

The first one is to alert me when a user registers on my site:

sendgrid.send({
        to:         "my@email.com",
        from:       "myother@email.com",
        subject:    "[ALERT] " + req.body.eventDate,
        html:       "SOME HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        }
        else {
            next();
        }
});

The next one is a confirmation email sent to the newly-registered member:

sendgrid.send({
        to:         req.body.email,
        from:       "my@email.com",
        subject:    "[CONFIRM] register" + req.body.eventDate,
        html:       "SOME HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        }
        else {
            next();
        }
});

It's working 100%, but this is not a good practice as there is so much duplicatation. Can I DRY this? If so, how?


texts: Area of the triangle generated by the hands of a clock

texts:
Problem explanation:

Let’s suppose we have a clock that has an hour hand 3 units long, a minute hand 4 units long, and a second hand 5 units long. The hour hand moves once every hour, the minute hand moves once every minute, and the second hand moves once every second.
Therefore, exactly every second, the triangle defined by the ends of the hands changes its area.

Which is the maximum area between two given times?

Input: A sequence of hours in sets of 2 in the format hh:mm:ss.

Output: The maximum area defined by the ends of the hands in square units.

For a more comprehensive explanation: https://jutge.org/problems/P17681_en/statement

My code:

I have written a function that takes as arguments the position of the hands in radians and returns its area (trigonometrically intensive).

double area(double secRad, double minRad, double houRad){
    double alfaSM = atan( (5-4*cos(abs(secRad-minRad)))/(4*sin(abs(secRad-minRad))) );
    double alfaSH = atan( (5-3*cos(abs(secRad-houRad)))/(3*sin(abs(secRad-houRad))) );
    double alfaMH = atan( (4-3*cos(abs(minRad-houRad)))/(3*sin(abs(minRad-houRad))) );

    double distSM = abs(5*sin(alfaSM)+4*sin(abs(secRad-minRad)-alfaSM));
    double distSH = abs(5*sin(alfaSH)+3*sin(abs(secRad-houRad)-alfaSH));
    double distMH = abs(4*sin(alfaMH)+3*sin(abs(minRad-houRad)-alfaMH));

    double s = (distSM+distSH+distMH)/2;

    return s*(s-distSM)*(s-distSH)*(s-distMH);
}

My main function reads the input from the user and calculates the area for each second in the range of time the user has entered, stores the maximum area and finally prints it.

int main(){
    char z;
    double hI,mI,sI, hF,mF,sF;
    while(cin >> hI >> z >> mI >> z >> sI >> hF >> z >> mF >> z >> sF){
        double maxArea = 0;
        for(int i = 3600*hI+60*mI+sI; i <= 3600*hF+60*mF+sF; i++){
            double cacheArea = area( 2*pi*((double)(i%60)/60) , 2*pi*(double)((i%3600)/60)/60, 2*pi*(double)((i%43200)/3600)/12);
            if(cacheArea > maxArea) maxArea = cacheArea;
        }
        cout << fixed << setprecision(3) << sqrt(maxArea) << endl;
    }
}

Write this at the beginning so you can test the program:

#include <iostream>
#include <cmath>
#include <iomanip>
#define pi 3.14159265358979323846
using namespace std;

Where am I now and what is left?

The algorithm of the code above works as intended, but it isn't efficient enough. The online judge throws a time limit exceeded error.

I have managed to reduce the number of calculations of area needed by supposing that if the range of time is more than an hour, we just need to check all the combinations for the first hour, since the maximum area will be there and will be appearing again every hour(the relative positions repeat).

I have also implemented a variable that checks if the separation between hands of the clock in the time its checking is smaller than the separation of the hands in the maximum area found until that moment. If it is, the program skips the area calculation.

These changes seem to improve performance considerably (from 43,200 area calculations to ~1,500 in the complete spin of 12 hours), but the judge still doesn't admit it.

I seem to need a cleaner solution, a mathematically prettier one, but I'm struggling to find one.


texts: Keep parsing JSON response until a field becomes false using GSON

texts:
I have JSON which is coming by executing a URL. I want to store all the value of id field in a List<String> by parsing through GSON. Also, if the next field is true, then that means there is another URL at the bottom of the JSON which I need to use to get the second page which will also look like this JSON response which will have ids again, so I will add those ids into the same list again.

Here is the flow:

Execute the URL and get JSON response. After, that check if the next field is true or false in that JSON response.
If it is false, then there is only one page so add all those ids into my List<String> and return.
If it is true, then there will be another URL at the bottom. Use that URL and add prefix to it and then execute it to get another JSON response and repeat the same thing until next is false and keep adding all ids into the same list.

JSON response:

{
    "status": {
        "number": "100",
        "value": "ok"
    },
    "next": true,
    "result": [{
        "type": "Process",
        "id": "1.2.3.4.5.6",
        "device": "hello"
    }, {
        "type": "Process",
        "id": "9.55.1.2.3.2",
        "device": "world"
    }, {
        "type": "Process",
        "id": "5.4.3.2.1.2",
        "device": "proc"
    }, {
        "type": "Process",
        "id": "99.11.11.2.3.4",
        "device": "oreon"
    }],
    "pagination": {
        "cursor": ["", "57d9e9d4e4b073aa2f401542", ""],
        "limit": [10000, 1000, 1000],
        "hint": 0,
        "maxFetch": 0,
        "skipEmptyPage": false
    },
    "next": {
        "method": "GET",
        "url": "/tries/next_set"
    }
}

Working code:

  public List<String> getIds() {
    List<String> ids = new ArrayList<>();
    try {
      String url = generateUrl();
      boolean hasMore = true;
      while (hasMore) {
        Optional<String> response = executeUrl(url);
        if (!response.isPresent()) {
          JsonElement jelement = new JsonParser().parse(response.get());
          JsonObject jobject = jelement.getAsJsonObject();
          hasMore = jobject.get("next").getAsBoolean();
          if (hasMore) {
            url = PREFIX + jobject.getAsJsonObject("next").get("url").getAsString();
          }
          JsonArray jarray = jobject.getAsJsonArray("result");
          for (JsonElement type : jarray) {
            ids.add(type.getAsJsonObject().get("id").getAsString());
          }
        } else {
          hasMore = false; // to avoid infinite loop if response is not present
        }
      }
    } catch (Exception ex) {
      // log error
    }
    return ids;
  }

Below is how my execute method looks like:

  private Optional<String> execute(final String url) {
    Optional<String> abcResponse = Optional.absent();
    try (AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient()) {
      Future<Response> future = asyncHttpClient.prepareGet(url).execute();
      Response response = future.get();
      abcResponse = Optional.of(response.getResponseBody(StandardCharsets.UTF_8.displayName()));
      System.out.println(response.getResponseBody());
    } catch (IOException | InterruptedException | ExecutionException ex) {
      // logging error
    }
    return abcResponse;
  }

The first URL is always generated by calling the generateUrl() method which is different than the subsequent URL which are there in the bottom of the JSON response. I want to see if there is any better way to do the same thing.


texts: SwiftUI custom ScrollView with snap interval

texts:
Due that fact that SwiftUI has poor ScrollView customization and doesn't support snap interval from the box I decided to implement my custom component to support such behaviour.
Example

I know, there are many hard coded values that should be replaced with dynamically calculated values. But for my debug purposes is enough.
I would like to ask if it possible to simplify my code? Or is there any better approach of creating such component.
The thing that confuses me the most is lastTimePoint. The variable which stores the last shift of content. It needs to prevent content jumps on scroll. I will leave more comments in a code to help you understand what's going on.
struct CustomScrollView<Content: View>: View {
  var height: CGFloat
  var content: () -> Content

  @State private var offset = CGFloat.zero
  @State private var lastTimePoint = CGFloat.zero // lastTimePoint the same as offset. I use it to populate value.translation.height and value.predictedEndTranslation.height to prevent content jumps. I want to remove it if it possible.

  var body: some View {
      VStack(alignment: .leading, spacing: 0) {
        content()
          .offset(y: offset) // Scrolls content depending on the this value
          .contentShape(Rectangle())
          .gesture(
            DragGesture(minimumDistance: 0)
              .onChanged(handleDragGestureChange)
              .onEnded(handleDragGestureEnded)
          )
      }
      .frame(height: height, alignment: .top) // clip the content to make content scrollable. height is equal to 250
      .clipped()
  }

  private func handleDragGestureChange(value: DragGesture.Value) { // Updates offset value
    offset = value.translation.height + lastTimePoint // If I remove lastTimePoint content will jump to the top of the list (if user started to scroll from any other place)
  }

  private func handleDragGestureEnded(value: DragGesture.Value) { // I use this function to calculate closest row where offset should stop.
    let predictedY = value.predictedEndTranslation.height + lastTimePoint // Again add lastTimePoint to prevent content jump

    withAnimation(.spring()) { // Animates list scrolling after user stops interacting
      if predictedY > 0 { // If list is going beyond his boundaries stop at the most top visible point (first element)
        offset = 0
      } else if predictedY < -1750 { // 1750 is the size of the content inside (red rectangles). I calculated it by 40 items * 50 item height = 2000 - 250 = 1750 where 1750 total height of all items within 250 height clipped scrollable component
        offset = -1750
      } else { // In this block I calculate the closest row where scrollable view should stop.

        // My rows heights
        // 0
        // -50
        // -100
        // -150
        // -200
        // ...
        // -1750
        //
        // If offset position is 120 (which is closer to 100 than to 150) I calculate it like this
        // -120 % 50 = remainder -20
        // remainder -20 is less then -25 go to the bottom, otherwise to to the top

        let remainder = predictedY.truncatingRemainder(dividingBy:  50)

        if remainder < -25 {
          offset = predictedY - (50 + remainder)
        } else {
          offset = predictedY - remainder
        }
      }
    }

    lastTimePoint = offset
  }
}

struct CustomScrollView_Previews: PreviewProvider {
    static var previews: some View {
        CustomScrollView(
          height: 250
        ) {
          Text("View")
        }
    }
}


texts: Custom exception for string that is too long

texts:
This is my first time working with Java exceptions. I have made a program that works to specifications, but I am wondering if there is anything I've done which is unconventional or not recommended. The application program does specify that there be line breaks between each message.

My driver is:

import java.util.Scanner;
public class ReadStrings {

    public static void main(String[] args) throws StringTooLongException{
        String str1;
        final int MAX_STRING_LENGTH = 20;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter strings, enter DONE when finished:\n");
        str1 = input.nextLine();
        if(str1.equalsIgnoreCase("done"))
            System.exit(0); //exit on first prompt
        do{
            try
            {
                if(str1.length()>MAX_STRING_LENGTH)
                    throw new StringTooLongException();
                System.out.println("\nEnter a string, enter DONE when finished:\n");
                str1 = input.nextLine();
            }
                catch(StringTooLongException e)
            {
                    System.out.println(e.getMessage());
                    str1 = input.nextLine();
            }
        }while(!str1.equalsIgnoreCase("done"));
        input.close();
    }
}

And my custom exception class is:

public class StringTooLongException extends Exception {
    public StringTooLongException()
    {
        super("\nString has too many characters\n\nPlease try again:\n");
    }
}

Thanks for taking a look. Any advice is appreciated.


texts: My grade calculator with special weighting

texts:
My school has a special 65% formal 35% informal weighting, so I made something to find what your grade would be if you added or changed a grade.
http://retep-mathwizard.github.io/gradecalc/gradecalc.html

HTML:

<!DOCTYPE html>

    <title> Grade Calculator</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="gradecalc.css">

Grade Calculator

    <input id="ing" placeholder="Informal grades, seperate by commas.">

    <input id="fog" placeholder="Formal grades, seperate by commas.">

    <input type="radio" name='type' onclick="changeoldgradedisplay()" id='radio_new_grade' >New

    <input type="radio" name='type' onclick="changeoldgradedisplay()" id='radio_old_grade' checked>Change

    <input id="old_grade_input" display='none' placeholder="old grade">
    <input id="new_grade_input" placeholder="new grade">

    <input type="radio" name='gradetype' id='informal_radio'>Informal

    <input type="radio" name='gradetype' id='formal_radio' checked>Formal

    <button onclick="add_grades()" > Go </button>

CSS:

#fog, #ing {

  width: 300px;
}

JS:

function changeoldgradedisplay() {
    if (document.getElementById('radio_old_grade').checked) {
        document.getElementById('old_grade_input').style.display = 'block';
    } else {
        document.getElementById('old_grade_input').style.display = 'none';
    }
}
function get_average(items) {
    var sum = 0;
    var len = items.length;
    for (var i = 0; i < len; i++) {
        sum += parseFloat(items[i]);
    }
    return sum/len;
}

function add_grades() {
    var formal_grades = document.getElementById('fog').value.split(',');
    var informal_grades = document.getElementById('ing').value.split(',');
    var previous_grade = (get_average(formal_grades) * .65) + (get_average(informal_grades) * .35);

    document.getElementById('previous_grade').innerHTML = 'Estimate of previous grade - ' + previous_grade.toFixed(2);

    var is_formal = document.getElementById('formal_radio').checked;
    var gradelist = null;

    if (is_formal) {
        new_grade = document.getElementById("new_grade_input").value;
        if (document.getElementById('radio_old_grade').checked) {
            old_grade = document.getElementById("old_grade_input").value;
            formal_grades[formal_grades.indexOf(old_grade)] = new_grade
        } else {
            formal_grades.push(new_grade);
        }
    } else {
        new_grade = document.getElementById("new_grade_input").value;
        if (document.getElementById('radio_old_grade').checked) {
            old_grade = document.getElementById("old_grade_input").value;
            informal_grades[informal_grades.indexOf(old_grade)] = new_grade
        } else {
            informal_grades.push(new_grade);
        }
    }

    var new_grade = (get_average(formal_grades) * .65) + (get_average(informal_grades) * .35);
    document.getElementById('new_grade').innerHTML = 'Estimate of new grade - ' + new_grade.toFixed(2);
}


texts: Very Simple Spell (Number to Words) 001 to 999 in VBA

texts:
I have come across many spell number functions and have reviewed many VBA code available on the net.

The core function that gets called repeatedly is the function that converts numbers from 001 to 999 as it is the core function for conversion under the English numeral system.
I have seen that this core function is sometime unnecessarily split over sub-functions for converting one, tens, and 20s to 90s.

I have developed the following simple VBA function that takes an input as number in a string format from "001" to "999" and returns the output as a string.
The function uses the dash "-" for numbers e.g. Forty-Two.

The function is easily convertible to other programming languages.

With your assistance, I am looking to further improve or simplifying the function, if possible.

You may test the function like this:

Debug.Print Do999("123")
Debug.Print Do999("001")
Debug.Print Do999("099")

Thanks in advance for your contribution.

Function Do999(ThreeDigits As String)
'-----------------------------------------
'Converts number string from 001 to 999 to Words
'Uses dash for in-between numbers from 21 to 99 for UK/US English
'Mohsen Alyafei 17 Oct 2018
'On Entry: NumIn MUST be a 3 Chars digit string "001" to "999"
'On Exit : String of number in English words
'-----------------------------------------
Dim Ones(), Tens(), dash As String, h As String, t As String, N1 As Integer, N2 As Integer

Ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", " Hundred")

'Next line is optional for English speaking words (UK, US)
If Right(ThreeDigits, 1) <> "0" Then dash = "-"  'dash as per English spelling

'------------Code starts here------------
'Get the hundreds (N1) and tens (N2)

N1 = Left(ThreeDigits, 1): N2 = Right(ThreeDigits, 2)
If N2 > 19 Then t = Tens(Val(Mid(ThreeDigits, 2, 1))) & dash & Ones(Val(Right(ThreeDigits, 1))) Else t = Ones(N2)
Do999 = Trim(IIf(N1 > 0, Ones(N1) & Tens(10), "") & " " & t)

End Function


texts: Finding number of days until a certain date

texts:
I'm using Node.js and Moment in order to retrieve the days until the next 8th:

const getDaysTillSalary = (day) => {
    const today = moment();
    const currentDay = moment().format('D');
    let currentMonth = moment().format('M');
    let currentYear = moment().format('Y');
    const isCurrentDayGreater = parseInt(currentDay) > day;

    currentYear = isCurrentDayGreater && parseInt(currentMonth) === 12 ? moment().add(1, 'year').format('Y') : currentYear;
    currentMonth = isCurrentDayGreater ? moment().add(1, 'months').format('M') : currentMonth;

    const salaryDate = moment(`${day}-${currentMonth}-${currentYear}`, 'DD-MM-YYYY');

    return salaryDate.diff(today, 'days');
}

getDaysTillSalary(8);

I'm sure there is a cleaner and maybe efficient way to solve this problem, and will be glad to get some feedback.


texts: C++ tuple implementation with get as a member

texts:
If you're familiar with std::tuple, you're aware that accessing its elements is slightly unusual. Instead of using a member function, we're provided with the function std::get instead. I was curious as to why this is, so I conducted a brief search. The few websites that I saw all gave the same reason: the code used to called the method is ugly.

We would expect:

my_tuple.get<0>()

but apparently we would have to write:

my_tuple.template get<0>()

(a source, see footnote 5).

This seemed like a bad case of "I heard that she heard that he heard...", because I was unable to find an implementation of a tuple that exposed this ugliness by including get as a member. I heard that Boost's tuple had get as a member, but after inspecting the source I discovered that it also only accepted 10 elements max. It was time for me to implement it myself!

template <typename... Ts>
class Tuple
{

};

template <std::size_t Index, typename... Rs>
struct TypeHolder;

template <std::size_t Index, typename R, typename... Rs>
struct TypeHolder<Index, Tuple<R, Rs...>>
{
    typedef typename TypeHolder<Index - 1, Tuple<Rs...>>::type type;
};

template <typename R, typename... Rs>
struct TypeHolder<0, Tuple<R, Rs...>>
{
    typedef R type;
};

template <typename T, typename... Ts>
class Tuple<T, Ts...> : public Tuple<Ts...>
{
public:
    Tuple(T obj, Ts... objs)
        : Tuple<Ts...>{ std::forward<Ts>(objs)... }
        , obj{obj}
    {

    }

    template <std::size_t Index>
    typename std::enable_if<
        Index == 0,
        typename TypeHolder<Index, Tuple<T, Ts...>>::type&
    >::type get()
    {
        return obj;
    }

    template <std::size_t Index>
    typename std::enable_if<
        Index != 0,
        typename TypeHolder<Index, Tuple<T, Ts...>>::type&
    >::type get()
    {
        return static_cast<Tuple<Ts...>*>(this)->get<Index - 1>();
    }

protected:
    T obj;
};

This functions as expected, and after some brief testing I found that there were no issues with storing pointers or references. But there was no need to write "template" for every call to get! (My compiler is GCC, by the way.)

Is there a reason why std::tuple was not implemented in this way? I would like to know about any glaring flaws with this code before I move forward with it.


texts: Handling combinations of optional parameters for an Angular filter pipe

texts:
This is a simple implementation of an ng2 filter pipe, which can currently take 2 optional facets: <string>status and <string>description. A "filter pipe" is an angular2 view decorator.

The filter receives a list of objects (values) which I want to filter by some criteria specific to the type of data object passed to it. The types of criteria are known in advance for each type of object.

Currently, I have implemented only one object type, a "maintenance event", which can be filtered by:

a status field, which is a fixed enum of strings, and
a free-text description

The filter is implemented in the view like so:

<div *ngFor="let event of maintenanceEvents | filter:'MAINTENANCE_EVENT':statusFilter:wordFilter">

where statusFilter and wordFilter are populated by a form.

The rest parameter (...filters) was used to allow any future arbitrary number of filters to be passed to the common filter module. So, in future, I could implement a filter like this:

<div *ngFor="let person of people | filter:'PEOPLE':title:permissions:locations:reports">

This is my complete pipe module:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {

    transform(values: any, type: string, ...filters: Object[]): any {

        switch (type) {
            case 'MAINTENANCE_EVENT':

                const ALL = "Show all";
                const BLANK = "";
                const DESCRIPTION_FILTER = new RegExp(<string>filters[1], 'gi');

                if (filters.length !== 2) {
                    throw new SyntaxError('MAINTENANCE_EVENT requires exactly 2 filter parameters: <string>status and <string>description')
                }

                if (filters[0] === ALL && filters[1] === BLANK) {
                    return values;
                }
                else {
                    return values.filter(value => {
                        if (value.hasOwnProperty('status') && value.hasOwnProperty('part') && value.part.hasOwnProperty('description')) {
                            if (filters[0] === ALL && filters[1] !== BLANK) {
                                return DESCRIPTION_FILTER.test(value['part']['description']);
                            }
                            else if (filters[0] !== ALL && filters[1] === BLANK) {
                                return value.status === filters[0];
                            }
                            else if (filters[0] !== ALL && filters[1] !== BLANK) {
                                return value.status === filters[0] && DESCRIPTION_FILTER.test(value['part']['description']);
                            }
                        }
                        else {
                            console.error("Attempting to filter by properties not present in available <MaintenanceEvent>s");
                        }
                    });
                }

            default:
                // Return everything
                return values;
        }
    }
}

Particularly, I'm interested in an alternative to the if, else if, else if ... else if N chain, since this will become wholly unmaintainable for filters with more complex facets (we plan for as many as 9 in future).


texts:
I am working on improving the runtime of code that undistorts every pixel point in an image.  Currently each point is undistorted via a call to cv::undistortPoints() as shown below:

cv::Mat src(1, 1, CV_32FC2);        // Create src and dst cv::Mat objects for cv::undistortPoints
cv::Mat dst(1, 1, CV_32FC2);

float* ptr;
ptr = src.ptr<float>(0);            // Fill src with correct pixel x and y values
ptr[0] = (float)x;
ptr[1] = (float)y;

cv::undistortPoints(src, dst, cam_intrinsic, distCoeffs);   //Undistort points

I've identified this particular function as the source of most of the performance issues, since it is called several million times for a single image, and wrote an alternative function in the hopes it would be faster.  My function,   while it works, runs much slower than cv::undistortPoints.  I am not really sure why, since it basically mirrors cv::undistortPoints, minus all the extraneous functionality-- shouldn't it be at least as fast as cv:undistortPoints?  What might be causing my code to run so slowly?

void fast_undistortPoints(const CvMat* src, CvMat* dst, CvMat* K,   CvMat* D)
{
    double A[3][3], RR[3][3], k[8] = { 0, 0, 0, 0, 0 }, fx, fy, ifx, ify, cx, cy;
    CvMat matA = cvMat(3, 3, CV_64F, A), _Dk;
    const CvPoint2D64f* srcd;
    CvPoint2D64f* dstd;
    int stype, dtype;
    int j, iters = 1;

    cvConvert(K, &matA);
    _Dk = cvMat(D->rows, D->cols,
        CV_MAKETYPE(CV_64F, CV_MAT_CN(D->type)), k);

    cvConvert(D, &_Dk);

    fx = A[0][0];
    fy = A[1][1];
    ifx = 1. / fx;
    ify = 1. / fy;
    cx = A[0][2];
    cy = A[1][2];
    srcd = (const CvPoint2D64f*)src->data.ptr;
    dstd = (CvPoint2D64f*)dst->data.ptr;
    stype = CV_MAT_TYPE(src->type);
    dtype = CV_MAT_TYPE(dst->type);

    iters = 5;

    double x, y, x0, y0;
    x = srcd[0].x;
    y = srcd[0].y;

    x0 = x = (x - cx)*ifx;
    y0 = y = (y - cy)*ify;

    // compensate distortion iteratively
    for (j = 0; j < iters; j++)
    {
        double r2 = x*x + y*y;
        double icdist = 1 / (1 + ((k[4] * r2 + k[1])*r2 + k[0])*r2);
        double deltaX = 2 * k[2] * x*y + k[3] * (r2 + 2 * x*x);
        double deltaY = k[2] * (r2 + 2 * y*y) + 2 * k[3] * x*y;
        x = (x0 - deltaX)*icdist;
        y = (y0 - deltaY)*icdist;
    }

    dstd[0].x = x;
    dstd[0].y = y;

}


texts:
I am using a match formula inside of a for loop, but it is taking too much time. Is there any way to optimize this code to make it go faster?

 Lastrow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
For i = 3 To Lastrow

       Sheets("sample").Range("AM1000000").End(xlUp).Offset(1, 0).Select
        Selection.FormulaArray = _
        "=IF(ISNUMBER(MATCH(1," & Chr(10) & "  (order!R2C15:R1000000C15=RC[-24])*" & Chr(10) & "  (order!R2C7:R1000000C7=RC[-32])*" & Chr(10) & "  (order!R2C24:R1000000C24=RC[-15])," & Chr(10) & "  0)), ""pass"",""review"")"

    Next i
      Columns("AM:AM").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False


texts:
I am making an app that shows some pictures and you can like each picture. I am sending a POST request from the Android device. In my backend I have a Python script that takes parameters category and URL of the picture, opens a JSON file, and modifies the "likes" value.

This is the Python script:

#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb, json

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
category= form.getvalue('category')
url= form.getvalue('url')

#Gets the file path,depending on the category
filepath='/home2/public_html/app/%s/%s.json' % (category,category)

# Open a file
with open(filepath) as data_file:
data = json.load(data_file)

# Finds the picture with the specific url and updates the likes value.
for picture in data:
    if picture ["url"] == url:
        likes = int(picture["likes"])
        picture["likes"]=str(likes+1)
        break

# Writes the json file with the new value.
with open(filepath, 'w') as data_file:
    data_file.write(json.dumps(data))

My JSON looks like this:

{"url": "http://pictures.com/app/Funny/picture.jpg", "category": "Funny", "likes": "0"}

What can go wrong with this script? Are there any potential drawbacks? I am new to backend programming, so I don't know what can go wrong here.


texts: Adding two values in a map, if they exist

texts:
My code looks like imperative style code. I want to make my code more functional. How I can rewrite my program so it become functional style code?

    val _map = getMap();
    if(_map.contains(x) && _map.contains(y)) Right(_map(x) + _map(y))
    else if(_map.contains(x + y)) Right(_map(x + y))
    else if(!_map.contains(x)) Left("%d or %d not found".format(x, x + y))
    else if(!_map.contains(y)) Left("%d or %d not found".format(y, x + y))
    else Left("What is it?")


texts: Extract code and convert special characters to HTML entities

texts:
I want users to enter their code into my blog and keep original styling tags intact. So I had to develop a function that extracts user's code (between two tags) and convert special characters to HTML entities, then remove unwanted tags using purifyHTML.

I want to know if it is safe to use it like that, and if there are any bad issues with this function.

public function extracter($string, $start, $end){
    function get_string_between($string, $start, $end){
        $delimiters = array();
        $ini = strpos($string,$start);
        if ($ini == 0) return FALSE;
        $delimiters['start'] = substr($string, 0, $ini);
        $ini += strlen($start);
        $last = strpos($string,$end,$ini);
        $len =  $last - $ini;
        $delimiters['inside'] = substr($string,$ini,$len);
        $delimiters['end'] = substr($string, $last+strlen($end));
        return $delimiters;
    }
    function reconstruct($strings = array(), $filter){
        if( count($strings) == 0 || !$strings )
            return false;
        $count = count($strings);
        $i = 0;
        $str = '';
        $code = array();
        $uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using
        foreach ($strings as $key => $val) {
            $i++;
            foreach ($val as $k => $v) {
                if( $k == 'start' )
                    $str .= $v;
                if( $k == 'inside' ){
                    $str .= '['.$uniq.$i.']'; //creat a token in the string
                    $code[$i] = htmlspecialchars($v);
                }
                if( $i == $count )
                    if( $k == 'end' )
                        $str .= $v;
            }
        }
        $purify = $filter->purifyHtml($str);//i'm using purifyhtml to remove undesirable tags and leave TinyMce tags
        for ($j=1; $j <= $i; $j++) {
            $purify = str_replace('['.$uniq.$j.']', $code[$j], $purify); //replace the token with the escaped code
        }
        return $purify;
    }
    /* main */
    $string = " ".$string;
    $components = array();
    $exists = TRUE;
    while ( $exists ) {
        $st = get_string_between($string, $start, $end);//decompose if token found
        if( !$st )
            return $string;// return the original string if nothing found
        $string = $st['end'];
        $components[] = $st;
        $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string
    }

    return reconstruct($components, $this->InputFilter);
}


texts: Showing a menu with buttons with dropdown submenus

texts:
I have to display a menu where some buttons have dropdown submenus and show if the current button is active or not and put a CSS class to it for each of the two situations (or in both).

<?php

$menus_array = array(
    array('item1', false),
    array('item2', true),
    array('item3', false)
);

$active_item = 'item2';

foreach ($menus_array as $menu_item) {
    if ($menu_item == $active_item && $menu_item[1] != true) {
        $css_class = ' class="active"';
    } else if ($menu_item != $active_item && $menu_item[1] == true) {
        $css_class = ' class="dropdown"';
    } else if ($menu_item == $active_item && $menu_item[1] == true) {
        $css_class = ' class="active dropdown"';
    } else {
        $css_class = '';
    }
}

?>

I've written the code as above, but I don't really like it. Is there a way to write it better? I'm talking about the foreach loop.


texts: Excel VBA - in a list, if cell equals specific value then

texts:
I started working on some code, and it works, but I feel like it could be done more effiently. Below is a portion of it to show what I'm doing. To simplify the idea, I've made it here so if the cell in column M is A, B, or C, it puts a 1 in column L. If column M is a D, E, or F, it puts a 2 in column L. And if column M is a G, H, or I, it puts a 3 in column L.

Is there an easier way to do this than how I'm doing it? I'm going to be dealing with a couple hundred possible values. Alex P suggested I build a reference table. I've never done that before, so I'm not sure if that's my best bet or not.

Sub ChangeTest()
    Dim LastRow As Long
    Dim i As Long
    LastRow = Range("M" & Rows.Count).End(xlUp).Row
    For i = 2 To LastRow
        If Range("M" & i).Value = "A" Or Range("M" & i).Value = "B" Or Range("M" & i).Value = "C" Then
        Range("L" & i).Value = "1"
        End If
        If Range("M" & i).Value = "D" Or Range("M" & i).Value = "E" Or Range("M" & i).Value = "F" Then
        Range("L" & i).Value = "2"
        End If
        If Range("M" & i).Value = "G" Or Range("M" & i).Value = "H" Or Range("M" & i).Value = "I" Then
        Range("L" & i).Value = "3"
        End If
    Next i
End Sub


texts: HackerRank - Binary tree to compute the Nth power of natural numbers that sum up to X

texts:
I'm trying to solve this challenge on HackerRank.
In short, given x and n, I have to determine how many ways I can pick numbers from the nth powers of the  natural numbers such that their sum is x.
So my first reasoning was to compute the list of the nth powers that I need as a first step. This list is
list = takeWhile (<= x)  [i^n | i <- [1..]]`

Now list is the bucket from which I have to pick numbers to add up to n.
I first thought about list comprehensions, because that's how I would pick a given number of numbers from the list; for instance this is how I would generate the sumList of the sums of any different triplets from list:
sumList = [x + y + z | x <- list, y <- dropWhile (<= x) list, z <- dropWhile (<= y) list]

Then I would just need to length $ filter (== x) sumList.
However, after some thinking, I concluded that list comprehensions are not the way to go, since I don't know in advance how many numbers I have to pick from list when attempting to sum them up to x.
So I thought that any possible sum corresponds to a combination of pick or not-pick while traversing the list.  This made me think of binary trees, and I eventually came up with this solution, which fails the Test Case 3 for timeout:
main :: IO()
main = do
  [x,n] <- sequence $ replicate 2 ((read :: String -> Int) <$> getLine)
  print $ length $ filter (== x) $ getLeaves $ listToSumTree $ takeWhile (<= x) [i^n | i <- [1..]]

data Tree a = Leaf a | Node a (Tree a) (Tree a) deriving (Show)

listToTreeImpl :: (Num a, Eq a) => [a] -> Tree a -> Tree a
listToTreeImpl [] tree = tree
listToTreeImpl (l:ls) (Leaf x) = Node x
                         (listToTreeImpl ls $ Leaf x)
                         (listToTreeImpl ls $ Leaf (x + l))

getLeaves :: Tree a -> [a]
getLeaves (Leaf a) = [a]
getLeaves (Node _ (Leaf _) (Node _ _ _)) = error "this should not happen"
getLeaves (Node _ (Node _ _ _) (Leaf _)) = error "this should not happen"
getLeaves (Node _ left right) = getLeaves left ++ getLeaves right

listToSumTree :: (Num a, Eq a) => [a] -> Tree a
listToSumTree ls = listToTreeImpl ls (Leaf 0)

I can only think of getLeaves $ listToSumTree as the only critical part of the program, since listToSumTree constructs a full tree, which is not needed (only the leaves are), and getLeaves traverses all the tree, only to get to the bottom layer of it.


texts: Converting phone numbers to words with Python

texts:
For fun, I wrote a script to convert the last four digits (or fewer) of a phone number into a valid word. I wanted to see if my personal phone number could be converted into something like "999-9999-BEAR." I used the unix words file as my dictionary.

I'm wondering how I could make this simpler, since there seems to be a lot of repetition within the function. I'd also like to expand it to consider more digits of the phone number.

I am mostly self taught with Python, so please let me know if I can do anything to make my code prettier!

import pandas as pd

words_df = pd.read_csv(r'C:\Python\Scripts\Data_Playground\unix_words.csv',encoding='latin1')

words_list = words_df['WORDS'].tolist()

phone_dict = {
    '0':None,
    '1':None,
    '2':['a','b','c'],
    '3':['d','e','f'],
    '4':['g','h','i'],
    '5':['j','k','l'],
    '6':['m','n','o'],
    '7':['p','q','r','s'],
    '8':['t','u','v'],
    '9':['w','x','y','z']
}

my_number = '0000009376' # zero example
#my_number = '0000003357' # eels example

def generate_words(phone_number):

    winners = []

    num = str(phone_number[-4:])
    first_letter = ''
    second_letter = ''
    third_letter = ''
    fourth_letter = ''

    if '0' in num or '1' in num:
        print('Sorry, your phone number contains a "0" and/or a "1" and cannot be converted.')

    else:
        #print('Starting number: {0}'.format(num))

        for i in range(len(phone_dict[num[:1]])):
            first_letter = phone_dict[num[:1]][i]

            for j in range(len(phone_dict[num[1:2]])):
                second_letter = phone_dict[num[1:2]][j]

                potential_word = first_letter + second_letter
                if potential_word in words_list:
                    winners.append(potential_word)

                for k in range(len(phone_dict[num[2:3]])):
                    third_letter = phone_dict[num[2:3]][k]

                    potential_word = first_letter + second_letter + third_letter
                    if potential_word in words_list:
                        winners.append(potential_word)

                    for l in range(len(phone_dict[num[3:4]])):
                        fourth_letter = phone_dict[num[3:4]][l]

                        potential_word = first_letter + second_letter + third_letter + fourth_letter
                        #print(potential_word)
                        if potential_word in words_list:
                            winners.append(potential_word)

        if len(winners) == 0:
            print('\n No Winners. :(')

        else:
            print('\nWinners! \n')
            for winner in winners:
                full_winner = my_number[:(len(my_number)-len(winner))] + winner.upper()
                formatted_winner = full_winner[:3] + '-' + full_winner[3:6] + '-' + full_winner[6:]
                print(formatted_winner)

generate_words(my_number)


texts:
I'm learning Python and I'm building a basic random numbr generator. The code below works as expected. I'm just wondering if it uses best practice / can be made better.
Some future considerations might be adding a way for users to pick a random that isn't limited to 0-50 or 0-100, and finding a way to scale the number of guesses dynamically based on their choice.
import random

"""
Make a program in which the computer randomly chooses a number between 1 to 10,
1 to 100, or any range.
"""

def intro():
    print(f"Welcome to our number guessing game.")
    print(f"We'll ask you to pick a range of numbers from 0 up to 100."
          f"Then you'll get some chances to guess the number. "
          f"The number of guesses you get will scale based on the range you "
          f"choose. From 0 - 50, you'll get 5 chances. From 0 - 100, you'll"
          f"get 10 chances. Good luck!")
    print("Choose a range: ")
    print("1. 0 - 50")
    print("2. 0 - 100\n")
    num_guesses = {
        "1": (5, 50),
        "2": (10, 100)
    }
    num_range = input()
    while True:
        if num_range == "1" or num_range == "2":
            return num_guesses[num_range]
        else:
            print(f"{num_range} is not a valid selection. "
                  f"Please select either 1 or 2.")
            num_range = input()

def guess_number(num_guesses, num_range):
    random_number = random.randint(0, num_range)
    guess_count = 0
    print(f"Random num is: {random_number}")
    while guess_count < num_guesses:
        guess = int(input(f"Pick a random number between 0 and "
                          f"{num_range}: \n"))
        if guess == random_number:
            print("CONGRATS, YOU WIN!")
            break
        else:
            guess_count += 1
            print(f"Incorrect, try again! You have "
                  f"{num_guesses - guess_count} guess(es) left.\n")
    else:
        print("Womp womp, you lose :(.")

if __name__ == "__main__":
    num_guesses, num_range = intro()
    guess_number(num_guesses, num_range)


texts:
I need to store serialized objects in a database and I want to avoid duplicates. In order to be able to tell wheter an object is already stored, I have to compare them somehow. My idea was to calculate a hash for some of its properties that I consider as equatable and store it in a separate column.

The algorithm is very simple: I implemented it with a builder that allows me to define a hash function and how each property should be formatted. E.g. strings may be case insensitive, floats may be rounded or date-time may be stripped of its millisecond part etc. This transformation is done by each expression. It then serializes each value into bytes and adds them to the buffer. Finally the hash-function calculates the hash-value. Sorting the expressions by member-name should prevent bugs caused by simply changing their order.

public class FingerprintBuilder<T>
{
    private readonly List<(string MemberName, Func<T, object> Fingerprint)> _fingerprints;

    public FingerprintBuilder()
    {
        _fingerprints = new List<(string Expression, Func<T, object> Fingerprint)>();
    }

    public static FingerprintBuilder<T> Empty => new FingerprintBuilder<T>();

    public FingerprintBuilder<T> For<TProperty>(Expression<Func<T, TProperty>> memberExpression, Expression<Func<TProperty, TProperty>> fingerprint)
    {
        var getProperty = memberExpression.Compile();
        var getFingerprint = fingerprint.Compile();
        _fingerprints.Add((
            ((MemberExpression)memberExpression.Body).Member.Name,
            (Func<T, object>)(obj => getFingerprint(getProperty(obj)))
        ));
        return this;
    }

    public Func<T, byte[]> Build(Func<byte[], byte[]> computeHash)
    {
        return obj =>
        {
            var buffer = new List<byte>();

            var binaryFormatter = new BinaryFormatter();
            foreach (var t in _fingerprints.OrderBy(e => e.MemberName, StringComparer.OrdinalIgnoreCase))
            {
                var fingerprint = t.Fingerprint(obj);
                using (var memory = new MemoryStream())
                {
                    binaryFormatter.Serialize(memory, fingerprint);
                    buffer.AddRange(memory.ToArray());
                }
            }

            return computeHash(buffer.ToArray());
        };
    }
}

In this example I also use two helper extensions. One for calculating the hash and the other one to get its string representation:

public static byte[] ComputeSHA1(this byte[] source)
{
    if (source == null) throw new ArgumentNullException(nameof(source));

    using (var sha1 = new SHA1Managed())
    {
        return sha1.ComputeHash(source);
    }
}

public static string ToHexString(this byte[] source)
{
    if (source == null) throw new ArgumentNullException(nameof(source));

    return
        source
            .Aggregate(new StringBuilder(), (current, next) => current.Append(next.ToString("X2")))
            .ToString();
}

Example

Testing it with these examples:

var p1 = new Person { FirstName = "John", LastName = "Doe", Age = 20 };
var p2 = new Person { FirstName = "John", LastName = "DOE", Age = 30 };
var p3 = new Person { FirstName = "Johny", LastName = "DOE", Age = 30 };

var personFingerprint =
    FingerprintBuilder<Person>.Empty
        .For(p => p.LastName, x => x.ToUpperInvariant().Trim())
        .For(p => p.FirstName, x => x.ToUpperInvariant().Trim())
        .Build(SHA1.ComputeSHA1);

personFingerprint(p1).ToHexString().Dump();
personFingerprint(p2).ToHexString().Dump();
personFingerprint(p3).ToHexString().Dump();

produces these three results:

D46E5C869CDBA5775D7F8C9AF6BC497D5EEA76C4
D46E5C869CDBA5775D7F8C9AF6BC497D5EEA76C4
F450C1CE6B1A2041D8D7D0FEAA31AF7C5C214D81

What do you think of this algorithm? Does it have any weaknesses or can anything else be improved?


texts: Add Field To PDF with Options for Multiple Pages

texts:
This is related to here and here. These two methods are used to programatically add a text field to a PDF document. The field can be of any user determined size and have any user determined title, and will be on the pages specified by an enum value.

private void AddFieldToPdf(Field field,
    iTextSharp.text.pdf.PdfStamper pdfStamper, int numberOfPages)
{
    var parentField = iTextSharp.text.pdf.PdfFormField.CreateTextField(
        pdfStamper.Writer, false, false, 0);
    parentField.FieldName = field.Title;
    switch (field.Pages)
    {
        case Pages.All:
            for (var pageNumber = PdfFirstPageNumber;
                pageNumber <= numberOfPages; pageNumber++)
            {
                AddFieldToPage(field, pageNumber, pdfStamper,
                    parentField);
            }
            break;
        case Pages.Odd:
            for (var pageNumber = PdfFirstPageNumber;
                pageNumber <= numberOfPages; pageNumber+=2)
            {
                AddFieldToPage(field, pageNumber, pdfStamper,
                    parentField);
            }
            break;
        case Pages.Even:
            for (var pageNumber = PdfFirstPageNumber + 1;
                pageNumber <= numberOfPages; pageNumber += 2)
            {
                AddFieldToPage(field, pageNumber, pdfStamper,
                    parentField);
            }
            break;
        case Pages.First:
            AddFieldToPage(field, PdfFirstPageNumber, pdfStamper,
                parentField);
            break;
        case Pages.Last:
            AddFieldToPage(field, numberOfPages, pdfStamper,
                parentField);
            break;
    }
    pdfStamper.AddAnnotation(parentField, 1);
}

private void AddFieldToPage(Field field, int pageNumber,
    iTextSharp.text.pdf.PdfStamper pdfStamper,
    iTextSharp.text.pdf.PdfFormField parentField)
{
    var textField = new iTextSharp.text.pdf.TextField(
        pdfStamper.Writer, new iTextSharp.text.Rectangle(
            field.TopLeftX, field.TopLeftY, field.BottomRightX,
            field.BottomRightY), null);
    var childField = textField.GetTextField();
    parentField.AddKid(childField);
    childField.PlaceInPage = pageNumber;
}


texts: Follow-up: Randomizing Civilization 5 team choice

texts:
This is a follow-up on my previous question about a VBA macro for randomizing a draw from a table. It can be found here:
Randomizing Civilization 5 team choice

The code has been improved with the help I got earlier and I now seek even further improvements.

Public Enum CivilizationTableColumns
        CivilizationName = 1
        CivilizationLeader = 2
End Enum
Public Enum TextColumns
        PlayerTextColumn = 1
        CivTextColumn = 2
End Enum

Public Sub Draw()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet

Dim resultsRange As Range
Set resultsRange = GetResultsRange(ws)
resultsRange.ClearContents

Dim CivilizationsTable As ListObject
Set CivilizationsTable = Worksheets("Civilizations").ListObjects("tblCivilizations")

Dim randCiv As String

For noOfPlayers = 1 To GetPlayerNum(ws)

    resultsRange.Cells(GetPlayerNameRow(ws, noOfPlayers), PlayerTextColumn).Value = GetPlayerName(noOfPlayers)

    For noOfOptions = 1 To GetOptionsNum(ws)

        Dim endOfRange As Boolean
        endOfRange = False

        While Not endOfRange

            randCiv = GetCivilizationCaption(GetRandomNum(CivilizationsTable), CivilizationsTable)
            For Z = 1 To resultsRange.Rows.Count
                If resultsRange.Cells(Z, CivTextColumn) = randCiv Then
                    Exit For
                End If
                If Z = resultsRange.Rows.Count Then
                    endOfRange = True
                End If
            Next Z
        Wend

        resultsRange.Cells(GetCivNameRow(ws, noOfPlayers, noOfOptions), CivTextColumn).Value = randCiv
    Next noOfOptions
Next noOfPlayers
End Sub

Private Function GetRandomNum(ByVal CivilizationsTable As ListObject) As Integer
    GetRandomNum = CInt(Int((CivilizationsTable.Range.Rows.Count - 1) * Rnd())) + 1
End Function

Private Function GetCivilizationCaption(ByVal index As Long, ByVal CivilizationsTable As ListObject)
    Set Row = CivilizationsTable.ListRows(index)
    civName = Row.Range(ColumnIndex:=CivilizationName)
    civLeader = Row.Range(ColumnIndex:=CivilizationLeader)
    GetCivilizationCaption = civLeader & " (" & civName & ")"
End Function

Private Function GetPlayerNum(ByVal ws As Worksheet)
    GetPlayerNum = ws.Cells(3, 3).Value
End Function

Private Function GetOptionsNum(ByVal ws As Worksheet)
    GetOptionsNum = ws.Cells(3, 7).Value
End Function

Private Function GetPlayerName(ByVal noOfPlayers As Integer) As String
    GetPlayerName = "Player " & noOfPlayers
End Function

Private Function GetCivNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer, ByVal noOfOptions As Integer) As Integer
    GetCivNameRow = (GetOptionsNum(ws) + 2) * (noOfPlayers - 1) + (noOfOptions + 3)
End Function

Private Function GetPlayerNameRow(ByVal ws As Worksheet, ByVal noOfPlayers As Integer) As Integer
    GetPlayerNameRow = 3 + (GetOptionsNum(ws) + 2) * (noOfPlayers - 1)
End Function

Private Function GetResultsRange(ByVal ws As Worksheet) As Range
    Set GetResultsRange = ws.Range("K1:L50")
End Function


texts: Replacing occurrences in NSString and NSMutableString

texts:
I ran it and it's working, but I just want someone to double check that I followed the directions. Any suggestions or corrections will be appreciated.

  Assume you have a NSString *str object containing some text. Write a code fragment to create a new string with all substrings "aaa" deleted.

My answer:

NSString *str = @"aaa 123 yes there will be aaaa even more a y a y aaa, ";

NSString *str2 = [str stringByReplacingOccurrencesOfString:@"aaa" withString:@""];

NSLog(@"its %@", str2);

  Redo when this is NSMutableString *str, without creating a new object.

My answer:

NSMutableString *string1 = [NSMutableString stringWithString: @"aaa 123 yes there aaaa even more a y a y aaa,"];

[string1 replaceOccurrencesOfString:@"aaa" withString:@"" options:0 range:NSMakeRange(0, string1.length)];
NSLog (@"string1 = %@", string1);
    }


texts:
I have this jQuery click handler function that has three jobs:

Set the time interval for the refresh rate
Change the color on the clicked refresh rate selection
Callback the tablesort functions to resort the newly loaded data

I'd like to pull out the separate functionality into named functions, but I'm unsure (being a somewhat JS newb) how to do that an achieve the same behavior.

Javascript Code:

$(document).ready(function() {

    $("#refresh-buttons").on("click", "button", function(event) {

        var interval = 0;

        switch(event.target.id)  {
          case "refresh-off" :
                interval = 50000000;
                $(this).parent().children().removeClass("pressed-button");
                $(this).addClass("pressed-button");
                break;

          case "refresh-5-sec" :
              interval = 5000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;

          case "refresh-30-sec" :
              interval = 30000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;

          case "refresh-60-sec" :
              interval = 60000;
              $(this).parent().children().removeClass("pressed-button");
              $(this).addClass("pressed-button");
              break;
        }

        if (interval != 0)
        {
            clearInterval(intervalId);
            intervalId = setInterval(function(){
                $('#status-tables').load('/dashboard/index #status-tables', function(){
                  $("#workstation-table").tablesorter();
                  $("#report-table1").tablesorter({sortList:[[1,0]]} );
                  $("#report-table2").tablesorter({sortList:[[1,0]]});
                });
            }, interval);
        }

    });
});


texts: Refactoring with many duplicates using Bash

texts:
I have a curl based working bash script, but I have many duplicates on the "CURL" body.

How do I improve it efficiently to eliminate duplications?

if ! npm test
    then
      # Tell the human about the failure, if the npm output wasn't enough
      echo >&2 "Testing failed"
      curl -X POST -H 'Content-type: application/json' --data '{"text":"Tests failed for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' https://hooks.slack.com/services/rr/qq/pp

      # Exit and tell computers about the failure (0 = success, 1+ = failure)
      echo "A test Failed"
      exit 1

    else

      echo "Tests passed"
      curl -X POST -H 'Content-type: application/json' --data '{"text":"Tests passed for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' https://hooks.slack.com/services/rr/qq/pp

    fi


texts: Spotify's "Reversed Binary Numbers" Problem

texts:
I wrote some Java code for Spotify's Reversed Binary Numbers puzzle and I tested it on my machine and I am almost positive that it behaves as expected. However, when I send it to puzzle AT spotify.com it kicks it back saying I have the "wrong answer", and nothing else.

Frustrating as this is, I can't for the life of me seem to figure out why the code I have wouldn't work. I even went so far as to remove all error messages that result from bad input, thinking that maybe that was causing it to fail. I was wondering if anyone here with a keener eye than my own could possibly help me hunt down the bug?

Here is a snippet of the most relevant portion of the code:

/**
 * Reverse the bits of an integer between 1 ≤ n ≤ 1000000000.
 *    i.e. 11 (1011) becomes 13 (1101)
 *
 * @param n The integer to reverse.
 * @return The reversed integer.
 */
public static int reverseBits(int n) {
  // 1-indexed MSB Position
  int msbPosition = findMSBPosition(n);
  int reversed = 0;

  for (int i = 0; i < msbPosition; i++) {
    int mask = 1 << i;
    int bit = (n & mask) >> i;
    reversed |= (bit << (msbPosition - i - 1));
  }

  return reversed;
}

/**
 * Find the 1-indexed position of the MSB of a number.
 *    i.e. For the number 11 (1011), findMSBPosition() would return 4.
 *
 * @param n The number to find the MSB for.
 * @return The 1-indexed position of the MSB.
 * @protected
 */
protected static int findMSBPosition(int n) {
  int msbPos = 0;
  int testNum = 1;
  while (testNum <= n) {
    msbPos++;
    testNum <<= 1;
  }

  return msbPos;
}

The full code can be found in this gist.

As a caveat and as information I am NOT APPLYING TO SPOTIFY NOR HAVE ANY INTENTION TO. I'm just doing this to stay sharp and since "wrong answer" is less than helpful output I'd love to know where I messed up. Thank you so much.


texts: C++ program to swap links of a Linked List

texts:
In this code I tried to swap links in a linked list instead of swapping data.Please Review my code.

#include <iostream>

    template<class T>
    class LinkedList
    {
struct Node{
  T data;
  Node * next;
  Node(T val): data(val), next(nullptr){}
};

Node* head;

public:

  LinkedList() : head(nullptr) {}

  void insert(T val)
  {
    Node* node = new Node(val);
    Node* tmp  = head;

    if(tmp == nullptr)
    {
      head = node;
    }
    else
    {
      while(tmp->next != nullptr)
      {
        tmp = tmp->next;
      }
      tmp->next = node;
    }
  }

  void swapLinks(T val1, T val2)
  {
    Node* prevNode1 = nullptr;
    Node* prevNode2 = nullptr;
    Node* nextNode1 = nullptr;
    Node* nextNode2 = nullptr;
    Node* node      = head;
    Node* node1     = search(val1);
    Node* node2     = search(val2);

    while(node->next != node1)
    {
      node = node->next;
    }
    if(node->next == node1)
    {
      prevNode1 = node;
      nextNode1 = node1->next;
    }

    node = head;

    while(node-> next != node2)
    {
      node = node->next;
    }
    if(node->next == node2)
    {
      prevNode2 = node;
      nextNode2 = node2->next;
    }

    prevNode1->next = node2;
    Node* tmp       = node2->next;
    node2->next     = node1->next;
    prevNode2->next = node1;
    node1->next     = tmp;
  }

  friend std::ostream & operator <<(std::ostream & os, LinkedList<T>& ll)
  {
    ll.display(os);
    return os;
  }

private:

  struct Node *search(T val)
  {
    Node* node = head;
    while(node != nullptr)
    {
      if(node->data == val)
      {
        return node;
      }
      node = node->next;
    }
    std::cerr << "No such element in the List \n";
    return nullptr;
  }

  void display(std::ostream& out = std::cout) const
  {
    Node* node = head;
    while(node != nullptr)
    {
      out << node->data <<" ";
      node = node->next;
    }
  }
};

int main()
{
  LinkedList<int> ll1;
  ll1.insert(10);
  ll1.insert(15);
  ll1.insert(12);
  ll1.insert(13);
  ll1.insert(28);
  ll1.insert(14);
  ll1.insert(16);
  std::cout << "LinkedList1 : "<< ll1 <<"\n";
  ll1.swapLinks(12, 14);
  std::cout << ll1 <<"\n";

}

Is there any another solution or better solution? Please suggest.


texts: JavaScript singleton with methods and properties

texts:
I am diving deeper into JavaScript and starting to learn more about prototypes and simulating classes etc. I am used to working with the Module pattern and would like to try and combine this pattern along with working with prototyping into an own little framework (purely for learning purposes).

I have devised a little construct and I was hoping if some of you advanced users could give me some feedback on the particular construct.

What I am trying to achieve is to create a singleton with methods and properties one could access, I would like to extend/build this via the prototype as speed is something I care a lot about. The thing I still have doubts about is whether or not this would be a suitable construct for what I have in mind, whether or not this would be fast etc.

Much appreciated! Here's the code.

var Mui = (function (window, document, undefined) {

Mui = function () {
    this.Version = {
        Major  : '0',
        Minor  : '1',
        Bugfix : '0'
    };
};

Mui.prototype = {
    sayHi : function () {
        alert('hi');
    }
};

return new Mui;

}(window, this.document));


texts: Functions to hide and reclaim first visible publication on a page using Selenium

texts:
I have the following functions in JavaScript:

function SelectFirstVisiblePublicationAndHideIt ( PageObj )
{
    var hideButtonXpath = "//img[@title='To hide this item in your profile, mark it as invisible']";
    var hideButtonArray;
    var numberOfHideButton;
    var publicationTitle;

    aqUtils.Delay(500);
    hideButtonArray = PageObj.EvaluateXpath(hideButtonXpath);
    numberOfHideButton = hideButtonArray.length;
    hideButtonArray[0].Click();
    publicationTitle = hideButtonArray[0].parent.parent.FindChildByXPath("//a").innerText;

    return publicationTitle;
}

function SelectFirstVisiblePublicationAndReclaimIt ( PageObj )
{
    var reclaimButtonXpath = "//button[@title='Claim this publication and stay on this page']";
    var reclaimButtonArray;
    var numberOfReclaimButton;
    var publicationTitle;

    aqUtils.Delay(500);
    reclaimButtonArray = PageObj.EvaluateXpath(reclaimButtonXpath);
    numberOfReclaimButton = reclaimButtonArray.length;
    reclaimButtonArray[0].Click();
    publicationTitle = reclaimButtonArray[0].parent.parent.FindChildByXPath("//a").innerText;

    return publicationTitle;
}

SelectFirstVisiblePublicationAndHideIt and SelectFirstVisiblePublicationAndReclaimIt are very similar except for the Xpath expression.

I am wondering if I should merge them into one function by:

re-naming variables and functions names in a more generic way
introduce an additional input argument that serves as a flag to indicate which Xpath expression is to be used

Doing so has pros and cons:

Pros: reduce the number of function by one
Cons: purpose of a function can no longer be read from its name; having one more input argument; become further away from the principle of "one function should do one thing and one thing only"

Any suggestions?


texts:
I was fooling around with some maths and realized that I could use a parabola to represent a bouncing ball. So, naturally, I decided to make it in code.

var Ball = function(r, v, a, y, x) {
    this.r = r;
    this.v = v;
    this.a = a;
    this.y = y;
    this.x = x;
};

Ball.prototype.draw = function() {
    this.y = this.v*this.r*this.r + this.a*this.r;
    var NewBallY = 380 - this.y;
    ellipse(this.x, NewBallY, 20, 20);
    if(this.y < 0) {
        this.r = 0;}
    this.r += 2;
};

var Ball1 = new Ball(0, random(-0.05, -0.02), random(2.0, 6.0), 40, random(20, 380));
var Ball2 = new Ball(0, random(-0.05, -0.02), random(2.0, 6.0), 40, random(20, 380));
var Ball3 = new Ball(0, random(-0.05, -0.02), random(2.0, 6.0), 40, random(20, 380));

var draw = function() {
    background(255, 255, 255);
    Ball1.draw();
    Ball2.draw();
    Ball3.draw();
};

The equation I used to calculate the parabola representing a ball's \$y\$ position is here, where \$y\$ is the y position of the ball, \$V\$ is the velocity, \$A\$ is the acceleration, and \$r\$ is the amount of time passed since the start of the bounce:

$$y=Vr^{2}+Ar$$


texts: Tokenize a mathematical statement string

texts:
The function tokenize generates tokens from a mathematical string.

It can chain characters together to form longer tokens.

This can be used to build a parse tree, in order to evaluate the math expression.

def get_char_type(char):
    """
    Returns a string denoting the type of char.

    >>> get_char_type('x')
    'letter'
    """
    operators = {'*', '/', '+', '-', '=', \
                '%', '~', '/', '&', '|', '>', '<'}
    if char.isdigit():
        char_type = 'number'
    elif char.isalpha():
        char_type = 'letter'
    elif char in operators:
        char_type = 'operator'
    else:
        char_type = 'other'
    return char_type

def tokenize(string):
    """
    Generates tokens from a mathematical statement string.

    >>> list(tokenize('3 + (4 ∗ 5)'))
    ['3', '+', '(', '4', '∗', '5', ')']

    >>> list(tokenize('x+=10'))
    ['x', '+=', '10']

    >>> list(tokenize('(729 + 4 * variable) ** 22 // 3'))
    ['(', '729', '+', '4', '*', 'variable', ')', '**', '22', '//', '3']
    """
    token_type = get_char_type(string[0])
    token = ''
    for char in string:
        if char == ' ':
            continue  # Spaces are not included
        new_type = get_char_type(char)
        if new_type != token_type:  # A new type of token has been found
            yield token
            token_type = new_type
            token = ''
        token += char
    if len(token) > 0:
        yield token


texts:
Given the following algebraic data type, a Rose Tree:

data Tree a = Node {
    rootLabel :: a,
    subForest :: [Tree a]
}

I attempted a foldTree function to fold over this list: (credit to this class's homework from 2013:

treeFold :: (b -> [b] -> b) -> (a -> b) -> Tree a -> b
treeFold f g tree = f (g (rootLabel tree)) (map (g . rootLabel) (subForest tree))

test

*Party> let tree = Node { rootLabel = 100, subForest = [] }
*Party> let tree2 = Node { rootLabel = 200, subForest = [tree] }
*Party> add tree2
300

Please review this implementation.

Given my definition of treeFold, I don't see how I could fold over a Tree Char, producing a [Char]/String result.

My understanding is that, for the return type, b, it can't be [a].


texts: linearly interpolate NA values in Rcpp::NumericVector

texts:
I am trying to fill missing values with linearly interpolated values in an Rcpp::NumericVector -- leaving in place leading and trailing NA-values.

The desired output is below:

R> x <- c(NA, NA, NA, 1:4, NA, 6:8, NA, 10, NA, NA, NA)
R> naLinInt(x)
R> [1] NA NA NA  1  2  3  4  5  6  7  8  9 10 NA NA NA

I've implemented it via the below, but as i am very new to C++ i'd very much benefit from some help in understanding how to do this better.

I feel that i've really hacked my way through this -- in particular i suspect i've over-used pointers and that there's a better way to do this sort of indexing and offsetting.

#include<Rcpp.h>

//[[Rcpp::export]]
Rcpp::NumericVector naLinInt(Rcpp::NumericVector x) {
    // This function linearly interpolates between NA values

    Rcpp::Rcout << "We begin with: " << std::endl << x << std::endl;

    double * it1 = x.begin();
    double * it2 = x.begin();
    int step = 0;

    it1++;

    while( it1 < x.end() ) {
        if( Rcpp::NumericVector::is_na(*it1)) {
            if( Rcpp::NumericVector::is_na(*(it1 - 1))) {
                it1++;
                continue;
            } else {
            it2 = it1;
            step = 0;
            while(it2 < x.end() && Rcpp::NumericVector::is_na(*it2)) {
                step++;
                it2++;
            }
            if( it2 == x.end()) break;
            // step through missing values and replace
            for(int j = 0; j < step; j++) {
                *it1 = *(it1 - 1) + (*it2 - *(it1 - 1))/(step + 1 - j);
                it1++;
            }
            it1 = it2 + 1;
            }
        } else {
            it1++;
        }
    }

    return x;
}


texts: Python client to fetch JSON data from REST API, retrying on failure

texts:
As a beginner, I'd like to see if anyone can suggest any better way of coding the below, as I'm duplicating code and nesting identical if statements as part of the following problem.

I'm grabbing data from a REST API, which is returned in JSON format. However, the query may fail. One cause of failure is that the authorization token obtained earlier has expired. In this case, I want to get a new token, and retry the query. Then I need to reprocess the response, which may still be a failure (but, this time, not because of an expired token).

So, I've written this, but I'm thinking there might be a more elegant way to write it to avoid code repeats:

# Firstly, I get the data, which returns a dict from a JSON response
response = get_data(authorization)
if response["responseStatus"] == "FAILURE":
    # I believe I need to check this in a separate if statement
    # because even though there's always a responseStatus key
    # it will only contain an errors key if the former equals FAILURE
    if response["errors"][0]["type"] == 'INVALID_SESSION_ID':
        print("Session expired, initiating new session.")
        # I call the function that grabs a new Authorization token
        authorization = get_authorization(username, password)
        # Then I call again the function that gets the data
        response = get_data(authorization)
        # And now I need to look again for a possible failure
        if response["responseStatus"] == "FAILURE":
            print(response["errors"])
    else:
        print(response["errors"])
# Here I couldn't do a simple else because I need to process
# success for either calls of get_data() above (before or
# inside the if block)
if response["responseStatus"] == "SUCCESS":
    process_data()