texts: Hi there! I've recently been getting into java and was wondering how I can clean up or condense the code for this problem I've been working on

texts:
The program asks the user to enter values for items bought, the price of each item, the GST rate, the QST rate. The program calculates the subtotal based on these inputs. For every invalid input entered by the user the program will prompt the user to re-enter that value until it is a valid input. Items bought must be between 1 and 10. The price of each item must be between 1 and 1000. The GST must be between 0 and 14. The QST must be between 0 and 17.

Im wondering if there's a way I can make this code more efficient by including more methods or anything else. Thanks!

import java.util.Scanner;
        public class Taxes{
        public static void main(String[] args){
        double subtotal = 0;
        int errors = 0;
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number of items bought (1-10): ");
        int num_items = scan.nextInt();
        while (num_items < 1 || 10 < num_items){
            errors += 1;
            System.out.println("Please enter the number of items bought (1-10): ");
            num_items = scan.nextInt();
        }

        for (int i = 1; i <= num_items; i++){
            Scanner scn = new Scanner(System.in);
            System.out.println("Please enter the price of item " + i);
            Double item_cost = scn.nextDouble();
            while (item_cost < 1 || 1000 < item_cost){
                errors += 1;
                System.out.println("Please enter the price of item " + i);
                item_cost = scn.nextDouble();
            }
            subtotal += item_cost;
        }
        System.out.println("Please enter the tax rate of GST in %: ");
        double gRate = scan.nextDouble();
        while (gRate < 0 || 14 < gRate){
            errors += 1;
            System.out.println("Please enter the tax rate of GST in %: ");
            gRate = scan.nextDouble();
        }
        System.out.println("Please enter the tax rate of QST in %: ");
        double qRate = scan.nextDouble();

        while (qRate < 0 || 17 < qRate){
            errors += 1;
            System.out.println("Please enter the tax rate of QST in %: ");
            qRate = scan.nextDouble();
        }
        calculate(subtotal, gRate, qRate, errors);
}

    public static void calculate(double subtotal, double gRate, double qRate, int errors)
        {
            double gst = subtotal * (gRate/100);
            double qst = (subtotal + gst) * (qRate/100);
            double total = subtotal + gst + qst;
            System.out.println("GST: " + gst);
            System.out.println("QST: " + qst);
            System.out.println("Subtotal: "  + total);
            System.out.println("You entered " + errors + " invalid inputs");
        }

    }


texts:
This code simply receives a very basic 'password' (numbers, letters, nothing fancy). After you press enter, it will display it back. The only special key I'm handling is backspace (code 8 in ASCII).

uses crt;

var
    pass: string;
    key: char;
    len: integer;

begin

clrscr;

key := chr(0);
pass := chr(0);

write('Write the password:');

while key<>chr(13) do
begin
    key := readkey;
    len := length(pass);
    case ord(key) of
        8: begin
                if len > 0 then
                begin
                    delete(pass, len, 1);
                end;
            end;
        else
            pass := concat(pass, key);
    end;
end;

writeln('Password: ', pass);

readln; //pauses the code

end.

You will probably notice that the program block is missing. It was on purpose, since Free Pascal Compiler has issues with it.

The code compiles / runs fine, to the best of my knowledge. Remember that this is simply and purely made for ASCII 7-bit (I think the extended set will work).

In terms of clarity, structure and indentation, what else can I improve?


texts: Increase performance of a method which finds the element removed from an array

texts:
Imagine that you have a TreeSet of numbers, and you copy them into an array, but you remove one element of it. You want to know the element removed.

import java.util.Arrays;
import java.util.Set;

import com.google.common.collect.Sets;

public class Question {

    private static final Set<Integer> SET = Sets.newTreeSet(Arrays.asList(1, 3, 5, 7));

    public static void main(String[] args) {
        int[] unsorted = {1, 5, 3};

        int elementRemoved = checkElementRemoved(unsorted);
        System.out.println("Element removed " + elementRemoved);
}

private static int checkElementRemoved(final int[] unsorted) {
    Integer elementRemoved = null;
    for (Integer number : SET) {
        if (!arrayContains(unsorted, number)) {
            // O(n^2) complexity
            elementRemoved = number;
            break;
        }
    }
    return elementRemoved;
}

private static boolean arrayContains(final int[] unsorted, final int number) {
    for (Integer inArray : unsorted) {
        if (inArray == number) {
            return true;
        }
    }
    return false;
}

The problem is that this solution has \$O(n^2)\$ complexity and I would like to improve the performance.

I think that the best option would be to sort the array, am I right?


texts:
I'm developing on a web application where I have a start and a finish date and time and have to set the duration between it.

There are inputs for dates and times.

Then, I have this function which calculates the duration between the two of them, and they are working properly. The duration, though, needs to be dynamic. So, i made this piece of code, creating a "on" on each of then, so that when it changes, they mount an object with the four datetime values and then call it to the getDuration function.

$(document.body).on('change','.data-inicio > input',function () {
    var tr   = $(this).parent().parent();
    var time = {
        dstart:  dateDbToView($(this).val()),
        hstart:  tr.find('.hora-inicio').find('input').val(),
        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),
        hfinish: tr.find('.hora-final').find('input').val()
    };
    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);
    tr.find('.duracao').find('input').val(drc);
});

$(document.body).on('change','.hora-inicio > input',function () {
    var tr   = $(this).parent().parent();
    var time = {
        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),
        hstart:  $(this).val(),
        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),
        hfinish: tr.find('.hora-final').find('input').val()
    };
    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);
    tr.find('.duracao').find('input').val(drc);
});

$(document.body).on('change','.data-final > input',function () {
    var tr   = $(this).parent().parent();
    var time = {
        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),
        hstart:  tr.find('.hora-inicio').find('input').val(),
        dfinish: dateDbToView($(this).val()),
        hfinish: tr.find('.hora-final').find('input').val()
    };
    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);
    tr.find('.duracao').find('input').val(drc);
});

$(document.body).on('change','.hora-final > input',function () {
    var tr   = $(this).parent().parent();
    var time = {
        dstart:  dateDbToView(tr.find('.data-inicio').find('input').val()),
        hstart:  tr.find('.hora-inicio').find('input').val(),
        dfinish: dateDbToView(tr.find('.data-final').find('input').val()),
        hfinish: $(this).val()
    };
    var drc = getDuration(time.dstart, time.hstart, time.dfinish, time.hfinish);
    tr.find('.duracao').find('input').val(drc);
});

My question is: this looks pretty confusing for anyone but me, which can be an bad point when it comes about maintenance. There must be a better way of making this work, so, I'm asking for suggestions.


texts:
I am experimenting with ES6 using BabelJS in a codepen project you can find here. I am confused as to why my code breaks when I decide to use let instead of var in the following function:

function getUnits(country) {
const imperialCountries = ['US', 'BS', 'BZ', 'KY', 'PW'];

if (imperialCountries.indexOf(country) === -1) {
  var units = 'metric';
} else {
  units = 'imperial';
}
console.log(country, units);
return units;
}

Thank you!


texts:
I wanted to practice using sockets and multithreading. This is simple code where I start a Server and connect to it via Client and chat between them.

Server class:

public class Server {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(4545);
        SocketEnhancer socketEnhancer = new SocketEnhancer(serverSocket.accept());
    }
}

Client class:

public class Client {
    public static void main(String[] args) throws Exception{
        SocketEnhancer socketEnhancer = new SocketEnhancer(new Socket("localhost",4545));
    }
}

SocketEnchancer:

public class SocketEnhancer {

    DataReceiver dataReceiver;
    DataSender dataSender;
    Socket socket;

    public SocketEnhancer(Socket socket){
        this.socket = socket;
        dataReceiver = new DataReceiver(this);
        dataSender = new DataSender(this);
        new Thread(dataSender).start();
        new Thread(dataReceiver).start();
    }

    public Socket getSocket() {
        return socket;
    }
}

DataReceiver:

public class DataReceiver implements Runnable {

    SocketEnhancer socketEnhancer;

    public DataReceiver(SocketEnhancer socketEnhancer) {
        this.socketEnhancer = socketEnhancer;
    }

    @Override
    public void run() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socketEnhancer.getSocket().getInputStream()));
            while (true) {
                String readLine = bufferedReader.readLine();
                if(readLine != null){
                    System.out.println("Data received: " + readLine);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

DataSender:

public class DataSender implements Runnable {

    SocketEnhancer socketEnhancer;
    Scanner scanner = new Scanner(System.in);

    public DataSender(SocketEnhancer socketEnhancer) {
        this.socketEnhancer = socketEnhancer;
    }

    @Override
    public void run() {
        try {
            PrintWriter printWriter = new PrintWriter(socketEnhancer.getSocket().getOutputStream());
            while(true) {
                String readLine = scanner.nextLine();
                printWriter.write(readLine + System.lineSeparator());
                printWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Any comments and criticism is appreciated.


texts: Selecting form controls that are either inside or outside a rectangle

texts:
I have a function which loops over the controls on a form and checks to see if it's in a given rect, and then adds it or doesn't add it to a list<>.  The parameter bContained is used to determine if we want a list of "in the rect" or "not in the rect" controls.

List<Control> getControls(Control container, Rectangle rect, bool bContained = false)
{
    List<Control> Selected = new List<Control>();

    rect = RectangleToClient(rect);

    foreach (Control ctl in container.Controls)
    {
        //Do we want selected or non-selected controls
        if (bContained)
        {
            if (rect.IntersectsWith(ctl.Bounds)) Selected.Add(ctl);
            foreach (Control ct in ctl.Controls) Selected.Add(ct);
        }
        else
        {
            if (!rect.IntersectsWith(ctl.Bounds)) Selected.Add(ctl);
            foreach (Control ct in ctl.Controls) Selected.Add(ct);
        }
    }

    return Selected;
}


texts: Is this calculator written in Python clean/good?

texts:
As a beginner I wrote my first program (calculator) with Python and as far as functionality is concerned it just works fine but I have some concerns about one thing at the end of the code. Under CalculateAgain() in the if statement, Calculate() is without the return statement. If I used it, it would just run the function one time and then it exits the program. That's why i left it without the statement. Is this ok or should I change something?

#Choose the operation
def OperationType():

    while True:

        Type = input('What type of operation do you want? +, -, *, /: \n')

        if Type in ('+', '-', '*', '/'):
            return Type
        else:
            print('Invalid input')

#Enter the first number
def InputFirstNumber():

    while True:
        try:
            firstNumber = float(input('Enter your first number: '))
            return firstNumber
        except ValueError:
            print ('Please enter a number')

#Enter the second number
def InputSecondNumber():

    while True:
        try:
            secondNumber = float(input('Enter your second number: '))
            return secondNumber
        except ValueError:
            print ('Please enter a number')

#Calculating
def Calculate():

    Type = OperationType()
    firstNumber = InputFirstNumber()
    secondNumber = InputSecondNumber()

    if Type == '+':
        print('{} + {} = '.format(firstNumber, secondNumber), firstNumber + secondNumber)

    elif Type == '-':
        print('{} - {} = '.format(firstNumber, secondNumber), firstNumber - secondNumber)

    elif Type == '*':
        print('{} * {} = '.format(firstNumber, secondNumber), firstNumber * secondNumber)

    elif Type == '/':
        print('{} / {} = '.format(firstNumber, secondNumber), firstNumber / secondNumber)

    else:
        print('Input not valid')

Calculate()

#Asks if the User want to calculate again
def CalculateAgain():

    while True:

        calculating_again = input('Do you want to calculate again? Y/N \n')

        if calculating_again in ('Y','y'):
            Calculate()

        elif calculating_again in ('N','n'):
            print('Quitting the program')
            break

        else:
            print('Not a valid answer')

CalculateAgain()


texts: Expand spreadsheet ranges to lists of cells in Scala

texts:
Problem

Spreadsheet cells are referenced by column and row identifiers. Columns are labeled with alphabetical characters, starting with "A", "B", "C", ...; rows are numbered from 1 in ascending order.  Write a function that takes in a string identifying a range of cells in a spreadsheet and returns an ordered list of cells which compose that range.

Example:

"A3:D5" -> ["A3", "A4", "A5", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4", "D5"]
"A3:D4" -> ["A3", "A4", "B3", "B4", "B5", "C3", "C4", "C5", "D3", "D4"]

Here is scala implementation of the same ,

import scala.language.postfixOps

object PrintSpreadSheet extends App {

  val validAlphabets = ('A' to 'Z').toSeq

  def cells(range: String): Seq[String] = {
    val corners = (range split ":") flatMap { corner =>
      Seq(corner.head, corner.last)
    }
    val rows = (corners filter (r => validAlphabets.contains(r))) sorted
    val cols = (corners filter (c => !validAlphabets.contains(c))) sorted

    (rows.head to rows.last) flatMap { r =>
      (cols.head to cols.last) map { c =>
        r.toString + ":" + c.toString
      }
    }
  }
  cells("A1:D5") foreach println
}


texts:
I'm currently getting the Facebook comments count over a query request to the Facbeook api.

The problem is, there are about 15 queries on each site which makes it real slow to load (up to 6 seconds)

The next step is to get the comments count from the array object, as there's no native PHP function for that i wrote my own.

Is there any possibility to speed things up?

Is there something wrong with my code, which makes it slow, or is this up to the facebook query request?

Here's my code:

function objectToArray($object)
{
    if(!is_object($object) && !is_array($object))
    return $object;

    $array=array();
    foreach($object as $member=>$data)
    {
        $array[$member]=objectToArray($data);
    }
    return $array;
}

function count_comments($url)
{
    $fql  = "SELECT commentsbox_count FROM ";
    $fql .= "link_stat WHERE url = '".$url."'";

    $apifql='https://api.facebook.com/method/fql.query?format=json&query='.urlencode($fql);
    $json=file_get_contents($apifql);
    $obj = json_decode($json);
    $obj= objectToArray($obj);
    $obj = $obj[0]['commentsbox_count'];

    if($obj == 1)
    {
        echo '1 comment';
    }
    else if($obj == 0)
    {
        echo 'No comments yet';
    }
    else
    {
        echo $obj.' comments';
    }
}

Here I'm calling the function:

count_comments('http://example.com'.$data["id"].'');

Thanks in advance for any hints, tips and solutions!


texts: Code downloads a text file from a website, saves it to local disk, and then loads it into a list for further processing

texts:
My program opens a website and downloads a text file.  The text file is a simple file with one word per line. I save the file to local disk and then create a list to hold each line of the text file for later processing.  I would like to know if I am doing these first steps in a way that would be considered idiomatic Python and have I made any big mistakes that will hamper my efforts to expand on it later.

This is similar to an exercise in Think Python by Allen Downey.  He suggests using a browser to download the text file but I wanted to do it with Python.

import requests

def get_webpage(uri):
    return requests.get(uri)

def save_webpagecontent(r, filename):
    """ This function saves the page retrieved by get_webpage. r is the
    response from the call to requests.get and
    filename is where we want to save the file to in the filesystem."""

    chunk_size = 8388608                # number of bytes to write to disk in each chunk
    with open(filename, 'wb') as fd:
        for chunk in r.iter_content(chunk_size):
            fd.write(chunk)

def make_wordlist(filename):
    wordlist = []
    with open(filename) as fd:
        wordlist = fd.readlines()
    return wordlist

def get_mylist(wordlist, num_lines=10):
    if len(wordlist) <= num_lines:
        return wordlist
    return wordlist[:num_lines]

def print_mylist(mylist):
    for word in mylist:
        print(word.strip())
    return None

"""List of words collected and contributed to the public domain by
Grady Ward as part of the Moby lexicon project. See https://en.wikipedia.org/wiki/Moby_Project
"""
uri = 'https://ia802308.us.archive.org/7/items/mobywordlists03201gut/CROSSWD.TXT'
filename = 'wordlist.txt'

r = get_webpage(uri)
save_webpagecontent(r, filename)
wordlist = make_wordlist(filename)
mylist = get_mylist(wordlist)
print_mylist(mylist)

My program works as I expect it to.  I have basically found how to do each individual piece by reading this forum and but I would like to know if I'm putting all the pieces together correctly.  By correctly I mean something that not only functions as expected but also will be easy to build larger programs and modules from.

I hope it isn't wrong of me to post this much code.  I wasn't sure how I could trim it down and still show what I am doing.  Please let me know if I need to change the format of my question.


texts:
Is there a better, more efficient or nicer way to do this?

public static String sortString(String s){

    String[] strArray= s.split("\\s+");
    Arrays.sort(strArray);
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<strArray.length; i++){
        sb.append(strArray[i]);
        sb.append(" ");
    }
    return sb.toString();
}


texts: How I can make file multiple of `segmentSize`

texts:
I multiply the original file and cut a piece of final file with intention to do it a multiple of segmentSize times with minimum loss of data.

Example: I have a file size of 4 bits, and segment size of 3 bits;
I do extend my original in 3 times or 6 and so far and so forth.

or another example:
I have file size of 48 000 000 and segment (1024*1024*6*2)
and if I multiply the original file by 5 (make file that was contain 5 original files in row) (48 000 000 * 5)/(1024*1024*6*2) = 19.0734...1 -- I will have only 0.7% loss.
And then I make my extended file (five times of original) by copying original file into Temp.iqbin 5 times, and after read the segment (1024*1024*6*2) from Temp.iqbin and write it into my final.iqbin (I do this 19 times in the last cycle) and I get Final file that is multiple of segmentSize (because I trimmed some data by not copying it from Temp.iqbin size).

    double criteria = 0;
    int arraySize = 0;

    double box = 1;
    int box_i = 0;
    double coeff;
    int sizeFactor;
    if (size < 1300000)
        sizeFactor = 8;
    else
        sizeFactor = 2;

    //if original file too big, reduce the extend coeff
    if (size < segmentSize) {
        coeff = segmentSize / size;
        coeff = (int)coeff;
    }
    else
        coeff = 0;

    //optimization by criteria of minimum data loss in final file
    for (int i = 1; i < 4*sizeFactor; i++) {
        criteria = (size*(i+coeff)) / segmentSize;
        criteria = criteria - int(criteria);
        box = box < criteria ? box : criteria;
        box_i = box < criteria ? box_i : i+coeff;
    }

    std::vector<char> vector(segmentSize);

    //Remove old Temp file
    std::remove("Temp.iqbin");
    std::fstream ofs1("Temp.iqbin", std::ios::binary | std::ios::out | std::ios::app | std::ios::in);
    fs.seekg(0, std::ios::beg);

    //i do the file that is multiple of original file in box_i (the size
    //which guarantee minimum data loss after trim) times
    for (int i = 0; i < box_i; i++) {
        ofs1 << fs.rdbuf();
        fs.seekg(0, std::ios::beg);
    }

    //back to beginning of file
    ofs1.seekg(0, std::ios::beg);
    //remove old final.iqbin
    std::remove("final.iqbin");
    std::ofstream ofs("final.iqbin", std::ios::binary | std::ios::out |std::ios::app);
    //Write Segments one by one to final.iqbin file
    //i read segments(have size i want new file was multiple of) and write
    //it to the newfile
    coeff = ((size*box_i) / segmentSize);
    for (int i = 0; i < (int)coeff; i++) {
        //Read Segment from Temp file
        ofs1.read(&vector[0], segmentSize);
        //Write Segment to final.iqbin file
        ofs.write(&vector[0], segmentSize);
    }
    ofs1.close();
    //remove Temp file
    std::remove("Temp.iqbin");

This code is working and it even works fast for files that I feed to it, but I think it's not the optimal solution.


texts: Generating primes with Sieve of Eratosthenes

texts:
There are many problems on the Internet that require you to find prime numbers, so I decided to write a set of functions to find them. I used the Sieve of Eratosthenes for generating the primes as it was fast and easy to implement compared to other algorithms.

However, I'm wondering if my code, rather than my method, is inefficient. Am I using STL containers/iterators correctly? Is there any section in my code slowing down the program?

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

#define initial_prime_barrier 100
bool isFlagged(int i) { return i == 0; }
bool isNextStart(int i) { return i != 0; }

vector<int> generatePrimesBelow(int limit)
{
   vector<int> primes;
   for (int i = 2; i < limit; i++)
   {
      primes.push_back(i);
   }
   vector<int>::iterator currentStart = primes.begin();
   do
   {
      int numberAtStart = *currentStart;
      vector<int>::iterator currentNumber = currentStart + numberAtStart;
      do
      {
         *currentNumber = 0;
         advance(currentNumber, numberAtStart);
      } while (currentNumber < primes.end());
      currentStart = find_if(currentStart + 1, primes.end(), isNextStart);
   } while ((*currentStart) * (*currentStart) < limit);
   vector<int>::iterator newEnd = remove_if(primes.begin(), primes.end(), isFlagged);
   primes.erase(newEnd, primes.end());
   return primes;
}

bool isPrime(int number)
{
   static vector<int> primes = generatePrimesBelow(initial_prime_barrier);
   static int numPrimes = primes.size();
   static int largestPrime = primes[numPrimes-1];
   static int halfwayPrime = primes[numPrimes/2];
   if (number == largestPrime)
   {
      return true;
   }
   else if (number < largestPrime)
   {
      if (number == halfwayPrime)
      {
         return true;
      }
      else if (number > halfwayPrime)
      {
         for (int i = numPrimes/2; i < numPrimes; i++)
         {
            if (number == primes[i])
            {
               return true;
            }
         }
      }
      else if (number < halfwayPrime)
      {
         for (int i = numPrimes/2; i >= 0; i--)
         {
            if (number == primes[i])
            {
               return true;
            }
         }
      }
   }
   else if (number > largestPrime)
   {
      primes = generatePrimesBelow(number + number);
      numPrimes = primes.size();
      largestPrime = primes[numPrimes-1];
      halfwayPrime = primes[numPrimes/2];
      return isPrime(number);
   }
   return false;
}

int main (int argc, char * const argv[])
{
   const int number = 123123;
   cout << (isPrime(number) ? "YES" : "NO") << endl;
}


texts: Summing the Product of Array-member combinations

texts:
Find the sum of product of all numbers in first array with all the numbers in second array.

Input Format

1st line contains 2 space separated integers N and M.
2nd line contains N space separated integers Ai.
3rd line contains M space separated integers Bi.

Output Format

1 single line containing only the required answer.

#include<iostream>
using namespace std;

int sum(int product)
{
    static int temp = 0;
    temp = temp + product;
    return temp;
}

int main()
{
    int N, M, result, i, j;
    cin>>N>>M;
    int *a1, *a2;
    a1 = new int[N];
    a2 = new int[M];
    for(i = 0; i < N; i++)
        cin>>a1[i];
    for(i = 0; i < M; i++)
        cin>>a2[i];

    for(i = 0; i < N; i++)
    {
        for(j = 0; j < M; j++)
            result = sum(a1[i]*a2[j]);
    }
    cout<<result;
    return 0;
}


texts:
I have this python script that uses pandas read an excel sheet then to update a sqlite db it works perfectly just wondering if I can speed it up as I am at about 70k lines

"""
Created on Thu Aug  1 14:11:01 2019

@author: Shane Pitts
"""

# -*- coding: utf-8 -*-
import sqlite3
from sqlite3 import Error
import pandas as pd
import shutil

#Takes DB File path then creates connection to it
def create_connection(db_file):
    """ create a database connection to a SQLite database """
    try:
        conn = sqlite3.connect(db_file)
        return conn
        print(sqlite3.version)
    except Error as e:
        print(e)
    return None
#updates reported table
def update_dupi_reported(conn, dupi, userID, op):

    with conn:
        cur = conn.cursor()
        cur.execute("UPDATE reported SET dupi = :dupi WHERE userID = :userID AND operator = :op",
                       {'dupi':dupi, 'userID':userID, 'op':op})
#updates blocked table
def update_dupi_blocked(conn, dupi, userID, op):

    with conn:
        cur = conn.cursor()
        cur.execute("UPDATE blocked SET dupi = :dupi WHERE userID = :userID AND operator = :op",
                       {'dupi':dupi, 'userID':userID, 'op':op})
def Count():
    #Creates a dataframe with the Excel sheet information
    df = pd.DataFrame()
    df = pd.read_excel("/root/Shane_db/Count.xlsx")

    #Assigns a variable to the DataBase
    database = "/root/Shane_db/db.db"

    # create a database connection
    conn = create_connection(database)
    cur = conn.cursor()

    #Runs through the DataFrame once for reported
    for i in df.index:
        userID = df['userID'][i]
        dupi = df['dupi'][i]
        op = df['operator'][i]
        print(i)
        with conn:
            update_dupi_reported(conn, dupi, userID, op)
            #Runs through a Second time for blocked
    for x in df.index:
        userID = df['userID'][x]
        dupi = df['dupi'][x]
        op = df['operator'][x]
        print(x)
        with conn:
            update_dupi_blocked(conn, dupi, userID, op)

    shutil.copy("/root/Shane_db/db.db", "/var/www/html/site/db.db")

if __name__ == '__main__':
    Count()


texts: Python code that compares two files byte by byte

texts:
I wrote a Python (2.7) script that compares a file byte by byte. filecmp was not suitable for the application because it compares metadata as well. How can I improve this code?

def byte_comp(fname, fname2):
    """
        Compares two files byte by byte
        Returns True if the files match, false otherwise
    """
    read_size = 1048576 # Determined experimentally
    if os.path.getsize(fname) != os.path.getsize(fname2): # If two files do not have the same size, they cannot be same
        return False
    with open(fname, "rb") as f:
        with open(fname2, "rb") as f2:
            count = 0 # Counts how many bytes have been read
            while count <= os.path.getsize(fname): # Loops until the whole file has been read
                if(f.read(read_size) != f2.read(read_size)): # If the chunk of the file is not the same, the function returns false
                    return False
                count += read_size
    return True # If the files are the same, it returns True

I would also appreciate help on how to make the function faster and less CPU intensive.


texts: Asynchronous API calls with delegates and event handlers

texts:
I'm making a WindowsPhone 8 app in C#. With this an API so I can convert JSON data into useful objects. I've found a method but am wondering if it is any good at all.
The problem is it's been a while since I've really worked with C# and never for windows phone.

Because it's making use of web requests it has to be asynchronous. From somewhere User.getTracks() should be called and handled. To do this I've come up with a solution but I don't know if it's a good one.

I have an ApiCaller class which has a few different ApiAction methods, these methods receive a generic to know what type to eventually serialize to. The main method receives all the data, makes the web request and serializes the JSON to an object.

public static async void ApiAction<T>(Uri uri, CallExecuted cbDelegate, HttpMethod method, bool requireAuthentication)

Here it receives a CallExecuted this is the delegate from the calling class. After serializing the JSON data it calls this delegate with the item as parameter cbDelegate(new CallbackArgs(item));

The calling class will have the following to process everything

    public delegate void GetTracksExecuted(List<Track> tracks); // The delegate other classes use
    public static event GetTracksExecuted tracksExecuted; // The local event that calls the above delegate

    // This is called from elsewhere
    // The parameter is the delegate from that class
    public void GetTracks(GetTracksExecuted e)
    {
        tracksExecuted += e;
        ApiCaller.ApiAction<List<Track>>(ApiCall.UserTracks, TracksDelegate, Id);
    }

    // The delegate given to ApiCall class
    public delegate void CallExecuted(CallbackArgs e);

    // The delegate that is called from the ApiCall class (CallExecuted)
    private static void TracksDelegate(CallbackArgs args)
    {
        List<Track> tracks = (List<Track>) args.Item;
        tracksExecuted(tracks);
    }

Is there a better way to accomplish any of this? Was thinking about just using the event to do it, leaving the delegate out, but don't know if that's better. Your input is very welcome


texts:
I am trying to implement multiplication of two numbers without using the * operator, as a practice for programming interviews. I have written two functions.

1) Using Long Multiplication

    static int MultiplyTwoNumbers(int num1,int num2)
    {
        List<int> leftnumber = new List<int>();
        do
        {
            leftnumber.Add(num1% 10);
            num1/= 10;
        } while (num1!=0);

        List<int> rightnumber = new List<int>();

        do
        {
            rightnumber.Add(num2% 10);
            num2/= 10;
        } while (num2!= 0);

        int result = 0;
        int counter = 1;
        for (int i = 0; i <leftnumber.Count; i++)
        {
            int tempresult = 0;
            int carry = 0;
            int innercounter = counter;
            for (int j = 0; j<rightnumber.Count; j++)
            {
                int tempVal = leftnumber[i] * rightnumber[j];
                tempVal += carry;
                if (tempVal / 10 != 0)
                {
                    carry = tempVal / 10;
                    tempVal = tempVal % 10;
                }
                tempresult = tempresult + (innercounter * tempVal);
                innercounter = innercounter * 10;
            }

            result +=tempresult;
            counter = counter * 10;
        }

        return result;

    }

2) using Addition

  static int multiplicationUsingAdd(int num1,int num2)
    {
        int result = 0;
        for (int i = 0; i < num2; i++)
        {
            int temp=result+ num1;
            result = temp;
        }
        return result;
    }

Which one is better and how can I improve it ?


texts:
I have implemented my own Observer pattern. I want to post my events in a new thread. This thread would simply call all the the observers/listeners with the posted event.

public class EventManager
{
    private ArrayList<Observer> observerList = new ArrayList<>();

    public void post(Object event)
    {
       new Thread(new MyRunnable(this, event)).start();
    }

    public void postHelper(Object event)
    {
        for(int i = 0; i < observerList.size(); i++)
        {
            Observer observer = observerList.get(i);
            observer.handle(event);
        }
    }

    private static class MyRunnable implements Runnable
    {
        EventManager eventManager;
        Object event;

        public MyRunnable(EventManager eventManager, Object e)
        {
            this.eventManager = eventManager;
            event = e;
        }

        @Override
        public void run()
        {
            eventManager.postHelper(event);
        }
    }
}

public interface Observer
{
    void handle(Object event);
}

How can I improve this? My main concern is that I am creating a thread everytime, which could potentially leave me out of memory.


texts: Implement running hours function in PowerShell

texts:
So I am trying to create a function in PowerShell that:

Takes start time in form HHmm to denote beginning of time window
Takes an end time in format HHmm to denote end of time window
Calling the function outside that time window results in that function not
returning till we have entered the time window again
Optionally I can decide how regularly the polling for time happens

Function Stop-OutsideRunningHours
{
    [cmdletbinding()]
    PARAM
    (
        [Parameter( Mandatory = $True )]
        [string]
        $StartTime = "1800",

        [string]
        $FinishTime = "0800",

        [int]
        $SleepFor = 60
    )

    $StartHour = 0
    $StartMinute = 0
    $EndHour = 0
    $EndMinute = 0

    If( $StartTime -eq $EndTime )
    {
        Throw "StartTime cannot be the same as EndTime"
    }

    If( $StartTime -match "(?<StartHour>\d{2})(?<StartMinute>\d{2})" )
    {
        If( $Matches.StartHour -eq $Null -or $Matches.StartMinute -eq $Null )
        {
            Throw "Unable to process start time $( $StartTime )"
        }

        $StartHour = [int]::Parse( $Matches.StartHour )
        $StartMinute = [int]::Parse( $Matches.StartMinute )
    }
    Else
    {
        Throw "StartTime not in expected format: $( $EndTime )"
    }

    If( $FinishTime -match "(?<EndHour>\d{2})(?<EndMinute>\d{2})" )
    {
        If( $Matches.EndHour -eq $Null -or $Matches.EndMinute -eq $Null )
        {
            Throw "Unable to process start time $( $EndTime )"
        }

        $EndHour = [int]::Parse( $Matches.EndHour )
        $EndMinute = [int]::Parse( $Matches.EndMinute )
    }
    Else
    {
        Throw "EndTime not in expected format: $( $EndTime )"
    }

    $Now = Get-Date

    $ExactStart = $Now.Date.AddHours( $StartHour ).AddMinutes( $StartMinute )

    $ExactFinish = $Now.Date
    If( $EndHour -lt $StartHour -or
        ( $EndHour -eq $StartHour -and $EndMinute -lt $StartMinute ) ) { $ExactFinish = $ExactFinish.AddDays( 1 ) }

    $ExactFinish = $ExactFinish.AddHours( $EndHour ).AddMinutes( $EndMinute )

    If( $ExactStart -lt $Now -and $ExactFinish -lt $Now )
    {
        $ExactStart = $ExactStart.AddDays( 1 )
        $ExactFinish = $ExactFinish.AddDays( 1 )
    }

    $FirstPass = $True

    Do
    {
        $CurrentTime = Get-Date

        If( $ExactStart -lt $CurrentTime -and $ExactFinish -lt $CurrentTime )
        {
            $ExactStart = $ExactStart.AddDays( 1 )
            $ExactFinish = $ExactFinish.AddDays( 1 )
        }

        If( -not $FirstPass )
        {
            sleep -Seconds $SleepFor
        }

        $FirstPass = $False
    }
    While( $CurrentTime -lt $ExactStart -and $CurrentTime -lt $ExactFinish )
}


texts:
I'm making a neural network that comprises five populations of feature-selective neurons and one population of non-selective neurons.  Each neuron in this network receives connections from

c * f * N_E randomly selected neurons from each of the selective populations
c * (1 - f * p) * N_E randomly selected non-selective neurons.

Below is the code I've written to define all of the connections in this network.  Specifically, the code produces two arrays that together represent the source (ee_i) and target (ee_j) nodes of every connection.

Can anyone think of a way to reorganize this code to speed it up?

import numpy as np

N_E = 8000
p = 5
f = 0.1
c = 0.2
encoders = np.random.choice(np.arange(N_E), (p, int(f * N_E)), False)
non_selec = np.array([i for i in range(N_E) if i not in encoders])
ee_i = []
ee_j = np.repeat(np.arange(N_E), int(c * N_E))
for j in range(N_E):
    ee_i = np.concatenate([ee_i,
                           np.concatenate([np.random.choice(encoders[0, :],
                                                            int(c * f *
                                                                N_E),
                                                            False),
                                           np.random.choice(encoders[1, :],
                                                            int(c * f *
                                                                N_E),
                                                            False),
                                           np.random.choice(encoders[2, :],
                                                            int(c * f *
                                                                N_E),
                                                            False),
                                           np.random.choice(encoders[3, :],
                                                            int(c * f *
                                                                N_E),
                                                            False),
                                           np.random.choice(encoders[4, :],
                                                            int(c * f *
                                                                N_E),
                                                            False),
                                           np.random.choice(non_selec,
                                                            int(c * (1 - f *
                                                                     p) *
                                                                N_E),
                                                            False)])])


texts:
Inspired by This LeetCode Question.

Instead of checking if every layer is symmetric, it instead checks if any aren't. This allows the program to leave early is an early layer fails the test. I'm looking for performance mostly, as I loop through each element in the list, instead of each layer. All feedback is appreciated and considered.

"""
This program determines if a given binary
tree is a mirror of itself

Example:

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3
"""

def is_symmetric(tree: list) -> bool:
    """
    Returns if the passed tree is symmetric

    :param tree: A list representing a binary tree
    """

    interval = 2
    start = 0
    end = 1
    for _ in range(len(tree)):
        # Find next layer
        layer = tree[start:end]

        # Determine if layer isn't mirror
        if layer != list(reversed(layer)):
            return False

        # Setup for next layer
        start = end
        end = (2 ** interval) - 1
        interval += 1

    return True

if __name__ == '__main__':

    assert is_symmetric([1, 2, 2, 3, 4, 4, 3]) # True
    assert not is_symmetric([1, 2, 2, None, 3, None, 3]) # False


texts: Further Optimizing a Segmented Sieve of Eratosthenes

texts:
I've implemented a Segmented Sieve of Eratosthenes that assumes each segment is about length \$ \sqrt{N}\$ for some upper limit \$N\$.

I further optimized the function by skipping all the evens when sieving.

I'd like to know if anyone has any views or advice on further optimizing my implementation.

Note that there are three functions: the first, "SieveEratList" is a standard Sieve of Eratosthenes (to calculate primes in range \$ [1, \sqrt{N}] \$); the second, "find_first_multiple_odds", checks to find the initial index value in an interval of odd numbers (since we're skipping evens); and the third, "OptiSegment," is the optimized Segmented Sieve that calls the previous two when needed.

I'm open to any suggestions, whether it's space optimization or runtime optimization.

def SieveEratList(n):
    numbers = [False]*2+[True]*(n-2)
    result = []
    for index, prime_candidate in enumerate(numbers):
        if prime_candidate:
            result.append(index)
            for x in range(index*index, n, index):
                numbers[x] = False
    return result

def find_first_multiple_odds(p, low):
    # O(1)
    x = p*((low/p)+(low%p != 0))
    x += p*(x%2 == 0)
    return ((x-low)/2)

def OptiSegment(high):
    delta = int(high**0.5)+1*(int(high**0.5)%2)

    seed_primes = SieveEratList(delta+1)
    #boolean operator checks see if "high" is square
    segment_count = int(high/delta) - 1*((high**0.5)-int(high**0.5) == 0.0)

    for seg in range(1, segment_count+1):
        low_val = seg*delta+1
        top_val = delta*(seg+1)-1

        candidates = list(range(low_val, top_val+1, 2))
        prime_limit = top_val**0.5+1

        Q = iter(seed_primes)
        p = next(Q)
        p = next(Q)

        while p < prime_limit:
            q = find_first_multiple_odds(p, low_val)

            for i in range(q, delta/2, p):
                candidates[i] = False
            p = next(Q)

        seed_primes += [x for x in candidates if (x and x < high)]

    return seed_primes


texts:
I am initializing a PHP array as follows

$newArray = array();
$newArray['2014-13-03']['SMD']['IMPR'] = 5;
$newArray['2014-13-03']['SMD']['CLICK'] = 10;

I just wanted to check if you think this is a wrong way to insert data into an array. It is working just fine, but I still wanted to check from an optimization standpoint.


texts: Creating a ES6 class for every API endpoint's response

texts:
Background
I am writing a Node app that queries a third-party Web API.
The API returns JSON data in various formats, each endpoint in a different format. My app later processes this data.
I have decided to create a separate class representing each endpoint's response data, and convert the JSON received from the server into an instance of the class, rather than keeping it as a plain old object.
Goal
My goal is to increase visibility of what fields are available inside that JSON from server, and simplify coding by using auto-completion that my IDE (VS2017) will now provide.
However, the code looks a bit redundant - I am basically copying all properties from one object into another.
Question
I want to know your thoughts whether this approach makes sense, is an overkill or if there's a better way to do it.
Code
Here's some basic code how I query the server:
Api.prototype.publishApp = async function (appId, versionId) {
  let url = config.luis.paths.publishApp.replace('{appId}', appId);
  let serverResponse = await queryEndpoint(this.key, url, HttpMethod.POST, HttpStatus.CREATED);
  return new AppPublishResponse(serverResponse); // convert object to class instance
};

And that's the class - I create one class for each endpoint:
/**
 * Represents a response from LUIS when publishing an app
 */
class AppPublishResponse {
  constructor(serverResponse) {
    this.versionId = serverResponse.versionId;
    this.isStaging = serverResponse.isStaging;
    this.endpointUrl = serverResponse.endpointUrl;
    this.region = serverResponse.region;
    this.assignedEndpointKey = serverResponse.assignedEndpointKey;
    this.publishedDateTime = serverResponse.publishedDateTime;
  }
}

Just a note, the queryEndpoint() function above makes sure that the server response code matches the expected one (e.g. 201 Created), so I can be sure that the data passed to the constructor of AppPublishResponse is always a valid server response.


texts: Read CSV with 3 columns and group some elements

texts:
I have a csv with 3 columns (date, name, number) and it is about 20K rows long. I want to create a dictionary keyed by date whose value is a dictionary of name:number for that date. On top of that, I want add some elements together if the name contains a key word so they would be listed as keyword:sum of numbers, rather than their individual entries.

E.g. If the csv had four entries

 6/17/84, Blackcat, 10,
 6/17/84, Dog, 20,
 6/17/84, Tabbycat, 12,
 6/17/84, Lizard, 5

and the keyword is cat, the result should be

{6/17/84: {'Dog':20, 'Lizard':5, 'cat':22}}

Here's what I came up with. Is there a better way?

       import csv
        import operator
        import collections
        import time

            def dict_of_csv(file_name, group_labels_with):
                complete_dict = {}
                key_word = [x.lower() for x in group_labels_with]
                for i in file_name:
                    key = i[1].lower()
                    key_value = int(i[2])
                    row_date = time.strptime(i[0], "%m/%d/%y")
                    if row_date not in complete_dict:
                        complete_dict[row_date] = {}
                        for name in key_word:
                            complete_dict[row_date][name] = 0
                    if any(name in key for name in key_word):
                        for name in key_word:
                            if name in key:
                                key = name
                        complete_dict[row_date][key] += key_value
                    else:
                        complete_dict[row_date][key] = key_value
                return complete_dict

    weeks = open("../DataIn/Master List 14day.csv", "rU")
    real_labels = csv.reader(weeks)

print dict_of_csv(real_labels, ['keyword1', "keyword2", "keyword3"])

weeks.close()


texts: How do I compare two integer value hashes?

texts:
I created a function that compares two hashes and returns a report on whether the subtraction of their values is negative or not.

The problem comes down to having a cost hash for a building and a current resources hash like:

cost = {:wood => 300, :stone => 200, :gold => 100}
reqs = {:wood => 200, :stone => 220, :gold => 90}

This one should return a report hash like:

report = { :has_resources => false, :has_wood =>  true, :has_stone => false, :has_gold => true }

Now, in the cost hash, :gold, :stone or :wood can be nil, i.e. non-existent.

My first attempt is definitely not the Ruby way and I don't like the function. It works, but I want to find a way to write it in a better manner:

def has_resources?(cost)
  report = { :has_resources => true, :has_wood =>  true, :has_stone => true, :has_gold => true }
  if not cost[:wood].nil?
    if self.wood < cost[:wood]
      report[:has_wood] = false
      report[:has_resources] = false
    end
  end
  if not cost[:stone].nil?
    if self.stone < cost[:stone]
      report[:has_stone] = false
      report[:has_resources] = false
    end
  end
  if not cost[:gold].nil?
    if self.gold < cost[:gold]
      report[:has_gold] = false
      report[:has_resources] = false
    end
  end

end

How should I rewrite this? I don't like the .nil? checks here, but I have to include them since the < operator does not work on nil objects. I also don't like having so many ifs.


texts: Recursive and iterative Euclidean algorithms

texts:
Is this code too cryptic?  Simple yes or no question. Feedback is optional.

int recursive_euclidean( int num1, int num2 )
{
    int gcd=0;
    if( num1 == num2 || num1 < 0 || num2 < 0 )
        ( ( num1 == num2 ) ? ( gcd = num1 ) : ( ( num1 < 0) ? ( gcd = num2 ) :
            ( gcd = num1 ) ) );
    else
        ( ( num1 > num2 ) ? ( gcd = recursive_euclidean( num1-num2, num2 ) ) :
            ( gcd = recursive_euclidean( num1, num2-num1 ) ) );
    return gcd;
}

int iterative_euclidean( int num1, int num2 )
{
    while( num1 != num2 && num1 > 0 && num2 > 0 )
       (( num1 > num2 ) ? (num1-=num2) : (num2-=num1) );
    return (num1>0) ? num1 : num2;
}


texts: Helper function to solve Project Euler question 26

texts:
Project Euler problem 26 asks us to:

  Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

I wrote this function in Python to find the decimal representation of a rational number p/q. How can I improve it? Also suggest good coding styles.

#! /usr/bin/env python
# -*- coding - utf-8 -*-

"""This program converts a rational number
into its decimal representation.

A rational number is a number of the form p/q
where p and q are integers and q is not zero.
The decimal representation of a rational number
is either terminating or non-terminating but
repeating.

"""

def gcd(a, b):
    """Computes gcd of a, b
    using Euclid algorithm.

    """

    if not isinstance(a, int) or not isinstance(b, int):
        return None

    a = abs(a)
    b = abs(b)

    while b != 0:
        a, b = b, a % b

    return a

def decimal(p, q):
    """Computes the decimal representation
    of the rational number p/q. If the
    representation is non-terminating, then
    the recurring part is enclosed in parentheses.
    The result is returned as a string.

    """

    if not isinstance(p, int) or not isinstance(q, int):
        return ''

    if q == 0:
        return ''

    abs_p = abs(p)
    abs_q = abs(q)

    s = (p / abs_p) * (q / abs_q)
    g = gcd(abs_p, abs_q)

    p = abs_p / g
    q = abs_q / g

    rlist = []
    qlist = []

    quotient, remainder = divmod(p, q)
    qlist.append(quotient)
    rlist.append(remainder)

    if remainder == 0:
        return str(quotient)

    while remainder != 0:
        remainder *= 10
        quotient, remainder = divmod(remainder, q)
        qlist.append(quotient)

        if remainder in rlist:
            break
        else:
            rlist.append(remainder)

    qlist = map(str, qlist)

    if remainder:
        recur_index = rlist.index(remainder) + 1
        dstring = qlist[0] + '.' + ''.join(qlist[1:recur_index]) + \
            '(' + ''.join(qlist[recur_index:]) + ')'

        if s < 0:
            dstring = '-' + dstring
    else:
        dstring = qlist[0] + '.' + ''.join(qlist[1:])

        if s < 0:
            dstring = '-' + dstring

    return dstring

if __name__ == '__main__':
    p = raw_input('p: ')
    q = raw_input('q: ')

    try:
        p = int(p)
        q = int(q)

        if q == 0:
            raise ValueError

        print '%d/%d =' % (p, q), decimal(p, q)
    except ValueError:
        print 'invalid input'


texts:
This code is written to find substring count in a string in Python 3. The original problem description is here. Please suggest better ways of solving this.

string =input()
substring = input()
count = 0
i=0
while(i<(len(string)-len(substring))):
    if(string.find(substring,i,len(string))>=0):
        count+=1
        i=string.find(substring,i,len(string))+1
    else:
        break;
print(count)


texts: A UserService method that calls the UserRepository a few times

texts:
I'm trying to implement some domain driven design architecture, such as a repository to talk to the database, and a service that talks to the repository.
I have an action where I want to see if a User exists, and if he does, update his data, if he doesn't, create it and then perform a task (this could be done using event listeners but I'm not there yet).

Now I'm wondering if my service method can do all these things? Is there another actor that should be responsible for this?
This method is not very testable, since it's performing multiple actions? How would I test a method like this?

public function updateOrCreate($data)
{
    $userData = static::getUserDataFromAccessToken($data);

    // Find the user
    $user = $this->userRepository->find($userData['id']);

    // If we found the user, update and return
    if ($user) {
        $this->userRepository->update($userData);

        // Return the updated user
        return $this->userRepository->find($userData['id']);
    }

    // Else create
    $created = $this->userRepository->create($userData);

    if ($created) {

        // Get the newly created user
        $user = $this->userRepository->find($userData['id']);

        // Get the activities
        $this->activityTask->perform($user);

        return $user;
    }
}

public static function getUserDataFromAccessToken($token): array
{
    return [
        'id' => $token->getValues()['athlete']['id'],
        'username' => $token->getValues()['athlete']['username'],
        'photo' => $token->getValues()['athlete']['profile'],
        'access_token' => $token->getToken(),
        'refresh_token' => $token->getRefreshToken(),
    ];
}


texts: Looking for efficient python program for this following python script

texts:
I am looking for a memory efficient python script for the following script. The following script works well for smaller dimension but the dimension of the matrix is 5000X5000 in my actual calculation. Therefore, it takes very long time to finish it. Can anyone help me how can I do that?

def check(v1,v2):
    if len(v1)!=len(v2):
        raise ValueError,"the lenght of both arrays must be the same"
    pass
def d0(v1, v2):
    check(v1, v2)
    return dot(v1, v2)
import numpy as np
from pylab import *
vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]]
rav= np.mean(vector,axis=0)
#print rav
#print vector
m= vector-rav
corr_matrix=[]
for i in range(0,len(vector)):
    tmp=[]
    x=sqrt(d0(m[i],m[i]))
    for j in range(0,len(vector)):
        y=sqrt(d0(m[j],m[j]))
        z=d0(m[i],m[j])
        w=z/(x*y)
        tmp.append(w)
    corr_matrix.append(tmp)
print corr_matrix


texts:
I was attempting to remove items from an ArrayList while iterating through it, only to find out that Java doesn't like that.  So I quickly wrote up a Delay that I could pass operations to so I could run them later.

import java.util.HashSet;
import java.util.Set;

public class Delay {
    private Set<Runnable> tasks = new HashSet<Runnable>();

    public Delay(){}
    public Delay(Runnable... tasks){
        for(Runnable task : tasks) this.tasks.add(task);
    }

    public void add(Runnable task){
        this.tasks.add(task);
    }
    public void run(){
        for(Runnable task : tasks) task.run();
        tasks.clear();
    }
}

Code in use (in a card game):

Delay delay = new Delay();

...

// if a hand has no cards, remove it from play
for(Hand hand : hands) if(hand.size() == 0) delay.add(() -> hands.remove(hand));
delay.run();

Is there a flaw in my solution?  Or does Java already have a method of handling this, making my code redundant?  Any points of improvement?


texts: Mutex helper for interprocess sychronization of accessing a network drive

texts:
I have two windows services working in parallel. Each of them is using a network drive that is connected and disconected dynamically by each one as required. They do it by executing net use command. (This is necessary because there've been issues with automatic reconnection when the server is rebooted. Not it's running stable.)

However, from time to time both services overrun and one of them fails to connect the drive because it's already connected by the other one.

To address this problem I thought I use a named Mutex to prevent both services trying to use that network location at the same time.

I didn't want to think about mutexes each time I want to synchronize that access so I created this small helper encapsulating a named Mutex.

public static class InterprocessSynchronizer
{
    public static async Task<T> TryExecuteAsync<T>(string resourceName, Func<CancellationToken, Task<T>> func, TimeSpan timeout, CancellationToken cancellationToken)
    {
        using (var mutex = new Mutex(initiallyOwned: false, name: resourceName))
        {
            if (mutex.WaitOne(timeout))
            {
                try
                {
                    return await func(cancellationToken);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }
        }
        return default(T);
    }
}

I tested it with two threads and it succeeded. I used Task.Factory.StartNew here for test purposes (mutexes require different threads) but I'm not going to use it later when they will be running in two different processes anyway.

[TestClass]
public class InterprocessSynchronizerTest
{
    [TestMethod]
    public async Task TryExecuteAsync_TwoTasks_Synchronized()
    {
        var task1 = Task.Factory.StartNew(async () => await InterprocessSynchronizer.TryExecuteAsync("foo", token =>
        {
           Thread.Sleep(2000);
           return Task.FromResult("abc");
        }, TimeSpan.FromMilliseconds(-1), CancellationToken.None));

        var task2 = Task.Factory.StartNew(async () => await InterprocessSynchronizer.TryExecuteAsync("foo", token =>
        {
            Thread.Sleep(3000);
            return Task.FromResult("xyz");
        }, TimeSpan.FromMilliseconds(-1), CancellationToken.None));

        var stopwatch = Stopwatch.StartNew();

        var result = await Task.WhenAll(task1, task2);

        stopwatch.Stop();

        Assert.AreEqual("abc", task1.Result.Result);
        Assert.AreEqual("xyz", task2.Result.Result);

        Assert.IsTrue(stopwatch.ElapsedMilliseconds >= 5000);
    }
}

Is this solution acceptable or am I doing something terribly wrong?


texts:
This is the code I wrote for making a JavaScript typeahead/autocomplete, which displays cities based on the user input.

It would be great if you could suggest some improvements on the code quality.

'use strict';

var data = ['alabama','alaska', 'arizona','arkansas','california', 'colorado', 'connecticut', 'delaware'];

/**
 * variables: searchBox is where you type the city name
*/
var searchBox = getElementById('typeahead');

/**
 * methods
 */
function getElementById(id) {
    return document.getElementById(id);
}

function iterate(arr, callback) {
    for(var i=0;i<arr.length;i++) {
        callback(arr[i], i);
    }
}

var search = function(val) {
    var arr = [];
    iterate(data, function(item, index) {
        if(item.indexOf(val) !== -1) {
            arr.push(item);
        }
    })
    return arr;
}

var addEvent = function(elm) {
    elm.addEventListener('click', function(event) {
        if(event.target !== event.currentTarget) {
            searchBox.value = event.target.textContent;
            removeChild();
        }
        event.stopPropagation();
    });
}

var appendChild = function(parent, child) {
    parent.appendChild(child);
}

var removeChild = function() {
    var ul = getElementById('searchResults');
    if(ul) {
        document.body.removeChild(ul);
    }
}

var bindData = function(arr) {

    var ul = document.createElement('ul');
    ul.setAttribute('id','searchResults')
    iterate(arr, function(item, index) {
        var li = document.createElement('li');
        var a = document.createElement('a');
        a.textContent = item;
        appendChild(li, a)
        appendChild(ul, li);
    });

    appendChild(document.body, ul);
    addEvent(ul);
}

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if(!immediate) {
                func.apply(context, args);
            }
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if(callNow) {
            func.apply(context, args);
        }
    };
}

var typeAhead = debounce(function(event) {
    removeChild();
    var value = event.target.value;
    if(value !== '') {
        var arr = search(value);
        bindData(arr);
    }
}, 400);

searchBox.addEventListener('keyup', typeAhead);
<input type="text" placeholder="type to search" id="typeahead">


texts:
I'm using standard jQuery Ajax to update values in the database and reflect the result in an output. This repetition seems like bad practice and I don't know enough about jQuery to consolidate this correctly.

jQuery

        $("#vendorticket").change(function() { //Input/Select tag
            var output = ("#vendorticket-result");
            $.ajax({
                url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
                type: 'post',
                data: {
                    vendorticket: $(this).val(),
                    column: 'vendorticket',
                    id: 15
                },
                success: function(result) {
                    $(output).html(result); //Output span either "Saved" or "Save Failed"
                }
            });
        });

//Rinse & Repeat...

        $("#priority").change(function() {
            var output = ("#priority-result");
            $.ajax({
                url: 'includes/view.func.php',
                type: 'post',
                data: {
                    priority: $(this).val(),
                    column: 'priority',
                    id: 15
                },
                success: function(result) {
                    $(output).html(result);
                }
            });
        });

        $("#assignedto").change(function() {
            var output = ("#assignedto-result");
            $.ajax({
                url: 'includes/view.func.php',
                type: 'post',
                data: {
                    assignedto: $(this).val(),
                    column: 'assignedto',
                    id: 15 //
                },
                success: function(result) {
                    $(output).html(result);
                }
            });
        });

    });

HTML

<input type="text" id="assignedto" />

<input type="text" id="priority" />

<input type="text" id="vendorticket" />


texts: Suggestions on Python code to update/insert data in PRODUCTION system

texts:
I need suggestions on improving this code, the code is working fine ,but i'm gonna deploy this to production system, so before that would like to ask the community for any improvements/suggestions.

The script insert/update MySQL database using the data from PostgreSQL DB.

I have tested with some sample values and both insert and Updates are working fine.

Note: Using Python 3.5

import psycopg2
import os
import time
import MySQLdb
import sys

from pprint import pprint
from datetime import datetime
from utils.config import Configuration as Config
from utils.postgres_helper import get_connection
from utils.utils import get_global_config

#ef db_connect():

# MySQLdb connection
try:
    source_host = 'magento'
    conf = get_global_config()
    cnx_msql = MySQLdb.connect(host=conf.get(source_host, 'host'),
                               user=conf.get(source_host, 'user'),
                               passwd=conf.get(source_host, 'password'),
                               port=int(conf.get(source_host, 'port')),
                               db=conf.get(source_host, 'db'))
    print('Magento MySQL DB Connected')
except mysql.connector.Error as e:
   print ("MYSQL: Unable to connect!", e.msg)
   sys.exit(1)

# Postgresql connection
try:
   cnx_psql = get_connection(get_global_config(), 'pg_dwh')
   print('DWH PostgreSQL DB Connected')
except psycopg2.Error as e:
   print('PSQL: Unable to connect!\n{0}').format(e)
   sys.exit(1)

# Cursors initializations
cur_msql = cnx_msql.cursor()
cur_msql_1 = cnx_msql.cursor()
cur_msql_2 = cnx_msql.cursor()
cur_psql = cnx_psql.cursor()
cur_psql_1 = cnx_psql.cursor()

now = time.strftime('%Y-%m-%d %H:%M:%S')

##################################################################################
update_sql_base="""select gr.email from unsubscribed gr
                   INNER JOIN nl_subscriber sn on sn.email=gr.email"""

msql_update_1="""UPDATE `nl_subscriber` SET `status`=3, `timestamp`=now() WHERE `email`='%s'"""

msql_update_2="""UPDATE `nl_subscriber` SET `subscriber_status`=3,`change_status_at`=now() WHERE `subscriber_email`='%s';"""

cur_psql.execute(update_sql_base)

for row in cur_psql:
    email=row[0]
    cur_msql.execute(msql_update_1 %email)
    cur_msql_2.execute(msql_update_2 %email)
cnx_msql.commit()

##################################################################################

insert_sql_base="""select gr.email,c.customer_id,'',3,'',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP),'','',CAST(TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') AS TIMESTAMP)
                   from unsubscribed gr
                   LEFT JOIN nl_subscriber sn on sn.email=gr.email
                   LEFT JOIN customers c on c.customer_email=gr.email
                   WHERE sn.email IS NULL"""

msql_insert_1="""INSERT INTO `nl_subscriber`(
            `email`,  `customer_id`,  `options`,  `status`,  `confirm_code`,  `timestamp`,  `ip`,  `store_id`,`confirmed_at`) SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s"""

cur_psql_1.execute(insert_sql_base)

for row in cur_psql_1:
    print(msql_insert_1)
    cur_msql_1.execute(msql_insert_1, row)
cnx_msql.commit()

## Closing cursors'
cur_msql.close()
cur_psql.close()
cur_psql_1.close()
cur_msql_1.close()
cur_msql_2.close()
## Committing
#cnx_psql.commit()
## Closing database connections
cnx_msql.close()
cnx_psql.close()

#if __name__ == '__main__':
 #db_connect()


texts:
Im starting with MVC and I'd like you to see my code. Am I doing right? What can I improve in my classes?

Controller

class Logar extends Controller {

    private $view;
    private $modelDAO;

    function __construct() {
        $this->modelDAO = new LogarModel();
        $this->view = new LogarView();
    }

    public function Login() {
        if ($this->modelDAO->Login($_POST['funcionario'], $_POST['senha'])) {
            $idFuncionario = $this->modelDAO->rows['idFuncionario'];
            parent::redirect("view/funcionario/index.php");
        } else {
            $this->view->show("Funcionario nao cadastrado");
        }
    }

}

class controller {

    function redirect($url){
        header("location: {$url}");
    }
}

Model

class LogarModel extends Model {

    function __construct() {
        $this->conectar();
    }

    function Login($funcionario, $senha) {
        $sql = "select * from funcionario where login = ? and senha = ? ";
        $this->read($sql);
        $this->bindar(1, $funcionario, PDO::PARAM_STR);
        $this->bindar(2, $senha, PDO::PARAM_STR);
        $this->executar();
        $this->contar();
        $this->pegar_dados();
        $this->desconectar();
        if ($this->linhas == 1) {
            return true;
        } else {
            return false;
        }
    }
}

class model {

    function conectar(){
        $this->conn = new Connection();
    }
    function read($readQuery){
       $this->stm =  $this->conn-> prepare($readQuery);
    }
    function bindar($n,$var,$extensao){
        $this->stm->bindparam($n,$var,$extensao);
    }
    function contar(){
        $this->linhas = $this->stm->rowcount();
    }
    function pegar_dados(){
        while($this->rows = $this->stm->fetch()){
            return $this->rows;
        }
    }
    function executar(){
        $this->stm->execute();
    }
    function desconectar(){
        $this->conn = null;
    }
}

View

class LogarView extends view {

    function __construct(){
    }
    function mostrarlogado(){

    }
}

class view {

    function view(){

    }

    function get_var($var,$value){
        $this->var = $value;
    }

    function show($value){
        $this->value = $value;
        echo $this->value;
    }
    function alertar($value){
        echo "<script>alert('{$value}')</script>";
    }
}

So, how am I going?


texts: Rendering a large collection using BackboneJS and LoDash

texts:
I have a Playlist object which contains many PlaylistItem children. If I have 10,000 children then the UI gets blocked from rendering until all 10,000 children have been processed.

To avoid this, I've created a recursive function wrapped in a setTimeout. This allows a chunk of the playlist to be rendered, allow the UI to update by pausing for setTimeout and then continue to run until it is empty.

Is this a good implementation? Any critiques? I know I still should implement pagination in the long run, but this is for the short term.

render: function () {
    this.$el.html(this.template(
        _.extend(this.model.toJSON(), {
            //  Mix in chrome to reference internationalize.
            'chrome.i18n': chrome.i18n
        })
    ));

    //  Group playlistItems into chunks of 200 to render incrementally to prevent long-running operations.
    var chunkSize = 200;
    var playlistItemChunks = _.toArray(this.model.get('items').groupBy(function (playlistItem, index) {
        return Math.floor(index / chunkSize);
    }));

    var self = this;
    this.incrementalRender(playlistItemChunks, function () {

        self.$el.find('img.lazy').lazyload({
            container: self.$el,
            event: 'scroll manualShow'
        });
    });

    return this;
},

incrementalRender: function (playlistItemChunks, onRenderComplete) {
    //  Render a chunk:
    if (playlistItemChunks.length > 0) {
        var playlistItemChunk = playlistItemChunks.shift();

        //  Build up the views for each playlistItem.
        var items = _.map(playlistItemChunk, function(playlistItem) {
            var playlistItemView = new PlaylistItemView({
                model: playlistItem
            });

            return playlistItemView.render().el;
        });

        //  Do this all in one DOM insertion to prevent lag in large playlists.
        this.$el.append(items);

        var self = this;
        setTimeout(function() {
            self.incrementalRender(playlistItemChunks, onRenderComplete);
        });

    } else {
        onRenderComplete();
    }

},


texts: Faster way to render XML (10MB) file, loop the content and display output

texts:
<?php
$xml = simplexml_load_file("http://www.example.com/example.xml");
            //echo "
";
            //print_r($xml);
            $cnt =0;
            $customereview='';
            foreach($xml->comment as $comment){
                    if($comment->ProdNid == $productID){
                        if($comment->PostedOn != '' && $comment->PostedBy != '' && $comment->comment_text != ''){
                            if($cnt < 5) {
                            $cnt++;
                            $customereview.="
".$title."".(string)$comment->comment_text."".(string)$comment->PostedBy.",".(string)$comment->PostedOn ."

";
                                if($cnt==5)
                                {
                                    break;
                                }
                            }

                        }//end of if
                    }
                }

                echo $customereview;
 ?>


texts: Finding the intersection of elements in two sets

texts:
Is there another better way to implement those two methods in 1 and 2?

  Implement the method contains.
  contains returns true if the given element
  is a member of the set, and false otherwise.
  Implement the method intersection.
  intersection returns a set which contains the elements
  in the set that are also members of the given set

  output:

{9, 1, 4, 3, 7, 5}

{4, 2, 8, 5, 7}

{4, 7, 5}

public class IntSet {

private int[] elements = null;

public IntSet(int[] elements) {
    this.elements = new int[elements.length];
    for (int pos = 0; pos < elements.length; pos++) {
        this.elements[pos] = elements[pos];
    }
}

// toString returns a string representation of the set
public String toString() {
    String s = "{";
    if (elements.length == 0)
        s = s + "}";
    else {
        for (int pos = 0; pos < elements.length - 1; pos++)
            s = s + elements[pos] + ", ";
        s = s + elements[elements.length - 1] + "}";
    }

    return s;
}

// contains returns true if the given element
// is a member of the set, and false otherwise.
public boolean contains(int element) {

    for (int i = 0; i < this.elements.length; i++) {
        if (this.elements[i] == element)
            return true;
    }
    return false;
}

// intersection returns a set which contains the elements
// in the set that are also members of the given set
public IntSet intersection(IntSet set) {
    // use the method contains
    int members = 0;
    for (int i = 0; i < elements.length; i++) {
        if (set.contains(elements[i]))
            members++;
    }

    int[] newMembers = new int[members];
    int position = 0;
    for (int i = 0; i < elements.length; i++) {
        if (set.contains(elements[i]))
            newMembers[position++] = this.elements[i];

    }
    return new IntSet(newMembers);
}

//Some instances of the class IntSet are created and used like this:
public static void main(String[] args) {
    int[] numbers1 = {9, 1, 4, 3, 7, 5};
    IntSet set1 = new IntSet(numbers1);
    int[] numbers2 = {4, 2, 8, 5, 7};
    IntSet set2 = new IntSet(numbers2);
    System.out.println(set1);
    System.out.println(set2);

    IntSet set = set1.intersection(set2);
    System.out.println(set);
    //When this code fragment is executed, the following printout is produced:
    //{9, 1, 4, 3, 7, 5}
    //{4, 2, 8, 5, 7}
    //{4, 7, 5}
  }
}


texts: Using IQueryable.GroupBy to count related database entities

texts:
Given a DbSet<Client> from an Entity Framework 6 DbContext, I need to count the number of related Tickets of each type: Open, Responded, and Resolved.

The below code works, and results in only one query (according to DbContext.Database.Log), as desired. However, the fact that the call to GroupBy results in an IGrouping<Client, ICollection<Ticket>>, which is also an IEnumerable<ICollection<Ticket>>, requires me to call FirstOrDefault(), even though there is always only one ICollection<Ticket>.

I've never used GroupBy before, so I'm willing to bet I'm just misusing it.

public IEnumerable<DashboardItemViewModel> GetItems(IQueryable<Client> clients)
{
    return clients
        .Where(cli => cli.IsActive)
        .GroupBy(cli => cli, cli => cli.Tickets)
        .Select(grp => new DashboardItemViewModel
        {
            Id = grp.Key.Id,
            Name = grp.Key.Name,
            Open = grp.FirstOrDefault().Count(t => t.Status == StatusType.Open && !t.IsArchived),
            Responded = grp.FirstOrDefault().Count(t => t.Status == StatusType.Responded && !t.IsArchived),
            Resolved = grp.FirstOrDefault().Count(t => t.Status == StatusType.Resolved && !t.IsArchived),
        });
}

public enum StatusType
{
    Open,
    Responded,
    Resolved,
};

public class DashboardItemViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Open { get; set; }
    public int Responded { get; set; }
    public int Resolved { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
}

public class Ticket
{
    public int Id { get; set; }
    public StatusType Status { get; set; }
    public bool IsArchived { get; set; }
    public virtual Client Client { get; set; }
}


texts: Cleaning up the code of a C++-based Personal Web Page Generator

texts:
I have tried to implement the following challenge:

Personal Web Page Generator
Write a program that asks the user for his or her name, then asks the user to enter a sentence that describes himself or herself. Here is an example of the program's screen:
Enter your name: Julie TaylorEnter
Describe yourself: I am a computer science major, a member of the jazz club, and I hope to work as a mobile app developer after I graduate.Enter
Once the user has entered the requested input, the program should create an HTML file, containing the input, for a simple webpage. Here is an example of the HTML content, using the sample input previously shown:

Julie Taylor

  I am a computer science major, a member of the Jazz club,
  and I hope to work as a mobile app developer after I graduate.

I implemented this in C++. Here is my code:
ofstream outfile_webpage;
string name, description;

outfile_webpage.open("Webpage.html");

cout << "Enter your name: ";
getline(cin,name);

cout << "Describe yourself: ";
getline(cin,description);

outfile_webpage << "" << endl;
outfile_webpage << "" << endl;
outfile_webpage << "" << endl;
outfile_webpage << "" << endl;
outfile_webpage << "\t" << endl;
outfile_webpage << "\t\t
" << name << "
" << endl;
outfile_webpage << "\t" << endl;
outfile_webpage << "\t
" << endl;
outfile_webpage << "\t" << description << endl;
outfile_webpage << "\t
" << endl;
outfile_webpage << "" << endl;
outfile_webpage << "" << endl;

outfile_webpage.close();

return 0;

This works just fine, but I see that there are a lot of repetitive lines. How can I reduce these repetitive lines?
Also, is there a way to make this code cleaner in another way, like by using a custom HTML template?


texts:
I'm super excited to share my hangman game with you. (haven't added the graphics yet...)
I will be using this program as my final project (for school), but I would like to have this polished before handing it in. I have given my program the limit of 7 attempts, but if the user continues to guess the wrong letters and then suddenly guesses the right letter, the attempt count stays where it's at.
Here's what I mean:
Let's say the word the computer has chosen is 'cougar' (I'm going to pretend I don't actually know this).
BTW this is on my console:
Guess the word: ______
7 chances left

a # <-- my input (1st actual input)
Yes! a is in the word!

Guess the word: ____a_
7 chances left

b # <-- my input (2nd actual input)
Sorry, b is not in the word. Try again.

Guess the word: ____a_
6 chances left

b # <-- my input (this was just to test out if my program would let me know that I have repeated a letter)
You already guessed b. Please try another one!

Guess the word: ____a_
6 chances left

t # <-- my input (3rd actual input)
Sorry, t is not in the word. Try again.

Guess the word: ____a_
5 chances left

q # <-- my input (4th actual input)
Sorry, q is not in the word. Try again.

Guess the word: ____a_
4 chances left

r # <-- my input (5th actual input)
Yes! r is in the word!

Guess the word: ____ar
4 chances left

h # <-- my input (6th actual input)
Sorry, h is not in the word. Try again.

Guess the word: ____ar
3 chances left

c # <-- my input (7th actual input)

this is where the program should've initially said
'Sorry, you ran out of attempts. The word was cougar. Maybe next time ☹.
instead, I get this:
Yes! c is in the word!

Guess the word: c___ar
3 chances left # <-- this is WRONG!!

g # <-- my input (my 1st extra attempt)
Yes! g is in the word!

Guess the word: c__gar
3 chances left

i # <-- my input (my 2nd extra attempt)
Sorry, i is not in the word. Try again.

Guess the word: c__gar
2 chances left

o # <-- my input (my 3rd extra attempt)
Yes! o is in the word!

Guess the word: co_gar
2 chances left

u # <-- my input (my 4th extra attempt)
Yes! u is in the word!

Awesome! You guessed cougar!

So my program is supposed to allow only 7 attempts (with the exception of a repeated letter). As you can clearly see I got 12 attempts! Out of which only 8 were acceptable (7 actual attempts and 1 for repeating 'b'), meaning I got 4 EXTRA attempts. (this is what I need to fix).
Here's my code:
from random import choice

words = choice(['ant', 'alpaca', 'baboon', 'badger', 'bat', 'bear', 'beaver', 'camel', 'cat', 'clam', 'cobra', 'cougar',
                'coyote', 'crow', 'deer', 'dog', 'donkey', 'duck', 'eagle', 'ferret', 'fox', 'frog', 'goat', 'goose',
                'hawk', 'lion', 'lizard', 'llama', 'mole', 'monkey', 'moose', 'mouse', 'mule', 'newt', 'otter', 'owl',
                'panda', 'parrot', 'pigeon', 'python', 'rabbit', 'ram', 'rat', 'raven', 'rhino', 'salmon', 'seal',
                'shark', 'sheep', 'skunk', 'sloth', 'snake', 'spider', 'stork', 'swan', 'tiger', 'toad', 'trout',
                'turkey', 'turtle', 'weasel', 'whale', 'wolf', 'wombat', 'zebra'])

guessed = []
wrong = []
attempts = 7

while attempts > 0:

    out = ''

    for letter in words:
        if letter in guessed:
            out = out + letter
        else:
            out = out + '_'

    if out == words:
        break

    print('Guess the word:',out)
    print(attempts,'chances left\n')

    guess = input()

    if guess in guessed or guess in wrong:
        print('You already guessed',guess+ '.','Please try another one!')
    elif guess in words:
        print('Yes!',guess,'is in the word!')
        guessed.append(guess)
    else:
        print('Sorry,',guess,'is not in the word. Try again.')
        attempts = attempts - 1
        wrong.append(guess)

    print()

if attempts:
    print('Awesome! You guessed',words + '!')
else:
    print('Sorry you ran out of attempts. The word was',words + '.', 'Maybe next time ☹')


texts:
Are the words isomorphs? (Code-Golf)

This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:

  Two words are isomorphs if they have the same pattern of letter
  repetitions. For example, both ESTATE and DUELED have pattern abcdca

ESTATE
DUELED
abcdca

  because letters 1 and 6 are the same, letters 3 and 5 are the same,
  and nothing further. This also means the words are related by a
  substitution cipher, here with the matching E <-> D, S <-> U, T <-> E, A <-> L.

  Write code that takes two words and checks whether they are isomorphs.

As always tests are included for easier understanding and modification.

def repetition_pattern(text):
    """
    Same letters get same numbers, small numbers are used first.
    Note: two-digits or higher numbers may be used if the the text is too long.

    >>> repetition_pattern('estate')
    '012320'
    >>> repetition_pattern('dueled')
    '012320'
    >>> repetition_pattern('longer example')
    '012345647891004'

    #    ^  ^      ^  4 stands for 'e' because 'e' is at 4-th position.
    #           ^^ Note the use of 10 after 9.
    """
    for index, unique_letter in enumerate(sorted(set(text), key=text.index)):
        text = text.replace(unique_letter, str(index))
    return text

def are_isomorph(word_1, word_2):
    """
    Have the words (or string of arbitrary characters)
    the same the same `repetition_pattern` of letter repetitions?

    All the words with all different letters are trivially isomorphs to each other.

    >>> are_isomorph('estate', 'dueled')
    True
    >>> are_isomorph('estate'*10**4, 'dueled'*10**4)
    True
    >>> are_isomorph('foo', 'bar')
    False
    """
    return repetition_pattern(word_1) == repetition_pattern(word_2)


texts: Rendering elements (which can change numbers) using jQuery

texts:
Currently when the user selects some tags in my app I generate them in a function, like this:

// Show tags that are currently used in search
var htmlNodes = '
';

// If no pinned nodes, reset not found nodes
if (graphFactory.existPinnedNodes() == false) {
  graphFactory.updateNotFoundNodes();
}

// Add not found nodes as tags (gray)
for (let x = 0; x < graphFactory.getNotFoundNodes().length; x++) {
  htmlNodes = htmlNodes + '
' + graphFactory.getNotFoundNodes()[x] + '
';
}

// Add pinned nodes as tags (blue)
for (let q = 0; q < graphFactory.getPinnedNodes().length; q++) {
  htmlNodes = htmlNodes + '
' + graphFactory.getPinnedNodes()[q] + '
';
}

htmlNodes = htmlNodes + '

';
$('#pinnednodeslist').html(htmlNodes);

Basically I create a
 of class tags, add some li elements with a specific tag each, and then render it into the #pinnednodeslist element.

As you can see, the number of
 elements might change, depending on the number of getPinnedNodes or getNotFoundNodes, so I wonder if I have to reconstruct this html every time or if there is a more efficient way to do that...

Maybe a better way is that I don't have to mix so much HTML with my code?

For instance, I was thinking to leave all the elements there and just make them invisible, simply adding a class to show them and the html content to display within... But maybe you know of some other better way to do that?


texts: Checking the strength of a password using regexes

texts:
I'm a beginner in Python and I made a password checker. I'm following these rules:

I have to use regex
password must be at least 8 characters
must have at least one lower case character
must have at least one upper case character
must have at least one special character
must have at least one number

I also wanted to display a message letting the user know what conditions weren't met.

I'm a bit concerned by the succession of ifs.

#strong password checks
import re

#ask the user for the password to check
pwtocheck = input('please enter the password to be checked:')

#Error message to be
Err_mess = ''

#first regex : at least one lower case characters
pw_lc = re.compile(r'([a-z]+)')

#second regex : at least one upper case characters
pw_uc = re.compile(r'([A-Z]+)')

#third regex: at least one special character
pw_sc = re.compile(r'([\-_\?!@#$%^&\*]+)')

#fourth regex : password must have at least one number
pw_d = re.compile(r'([0-9])+')

#create a list to be given to all() to evaluate if all conditions are met or not
cond_pw = [len(pwtocheck) > 8, pw_lc.search(pwtocheck), pw_uc.search(pwtocheck), pw_sc.search(pwtocheck), pw_d.search(pwtocheck)]

#building an error message
#is the password at least 8 characters
if len(pwtocheck) < 8:
    Err_mess = Err_mess + 'password is too short\n'

#first regex is none
if pw_lc.search(pwtocheck) is None:
    Err_mess = Err_mess + 'password needs at least one lower case character\n'

#second regex is None
if pw_uc.search(pwtocheck) is None:
    Err_mess = Err_mess + 'password needs at least one upper case character\n'

#third regex is None
if pw_sc.search(pwtocheck) is None:
    Err_mess = Err_mess + 'password needs at least one special character\n'

#fourth regex is none
if pw_d.search(pwtocheck) is None:
    Err_mess = Err_mess + 'password needs at least one number\n'

if all (cond_pw) is True:
    print('password is ok')
else:
    print(Err_mess)


texts:
In my app I have a BaseCtrl, which is attached to the body element and is available everywhere.
In the mentioned controller I have the following code for opening modal:

    $scope.addFolder = function($event) {
        $event.preventDefault();

        // Opens an add folder modal
        var modal = ModalService.custom({
            templateUrl: '/partials/modals/create-folder.html',
            controller: ['$scope',
                function($innerScope) {
                    $innerScope.modal = modal;

                    $innerScope.create = function() {
                        var result = NodesService.createFolder($innerScope.new_folder, $scope.location);
                        result.then(function(resp) {
                            modal.close();
                            ModalService.flash('CREATED_SUCCESSFULLY');
                            $rootScope.$emit('update_nodes');
                        }, function(err) {
                            $innerScope.create_folder_error = Locales.get(err.data.message);
                        });
                    };

                }
            ]
        });
    };

I thought it's the most appropriate place to put this snippet, since I need to be able to access it app-wide.
My question is should I separate this method in different controller or should I place it in a factory/service? What is the right place to put such code in angular?


texts: Unwinding shortened URLs with Python, SQLite, and multithreading

texts:
I spent the last couple of days reading/researching and learning sqlite and python multithreading.

I'm unwinding shortened urls stored in a sql table with three fields...
id | url_starting | url_unwound

The code chunks the database results, sends the chunk to a thread pool of the same chunk size, unwinds the urls and writes the results back to the database, then iterates to the next chunk.

I'm happy with the results but am looking for feedback as this is my first attempt.

General thoughts are greatly appreciated.
Also, any ideas on making the future_to_url = section more readable would be great.

import time
import os
import sqlite3
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.request import Request, urlopen

class MyDatabase(object):
    def __init__(self, db):
        self.__conn = sqlite3.connect(db)
        self.__conn.row_factory = sqlite3.Row  # https://stackoverflow.com/a/41920171/25197
        self.__conn.execute('pragma foreign_keys = on')
        self.__conn.commit()
        self.__cursor = self.__conn.cursor()

    def __enter__(self):
        return self

    def __del__(self):
        self.__conn.close()

    def __exit__(self, exc_type, exc_value, traceback):
        self.__conn.close()

    def query(self, arg):
        self.__cursor.execute(arg)
        self.__conn.commit()
        return self.__cursor

    def updateUnwoundUrl(self, url_starting, url_unwound):
        self.__cursor.execute(
            'UPDATE url SET url_unwound = ? WHERE url_starting = ?', (url_unwound, url_starting))
        self.__conn.commit()
        return self.__cursor

def unwindUrl(starting_url, timeout):
    try:
        hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
        response = urlopen(Request(starting_url, headers=hdr), timeout=timeout)
        unwound_url = response.geturl()

    # For any http error just return error. Deal with specifics later.
    except Exception:
        unwound_url = 'error'

    return unwound_url

def chunk_iter(iterable, chunk_size):
    it = iter(iterable)
    while True:
        chunk = tuple(next(it) for _ in range(chunk_size))
        if not chunk:
            break
        yield chunk

def unwindUrls(workers=100, request_timeout=10):
    relative_path = os.path.dirname(__file__)
    my_db_path = os.path.join(relative_path, 'database', 'my.db')

    with MyDatabase(my_db_path) as my_db:
        wound_urls = my_db.query(
            'SELECT url_starting, id FROM url WHERE url_unwound IS NULL ORDER BY id ASC').fetchall()

        chunk_count = len(wound_urls) / workers
        for i, wound_urls_chunk in enumerate(chunk_iter(wound_urls, workers), start=1):

            print('starting chunk {0} of {1} at {2}'.format(
                i, chunk_count, datetime.now().strftime("%I:%M:%S %p")))

            with ThreadPoolExecutor(max_workers=workers) as executor:
                future_to_url = {executor.submit(
                    unwindUrl, row['url_starting'], request_timeout): row['url_starting'] for row in wound_urls_chunk}

                for future in as_completed(future_to_url):
                    try:
                        url_starting = future_to_url[future]
                        url_unwound = future.result()
                        my_db.updateUnwoundUrl(url_starting, url_unwound)
                        # print('starting: {0} unwound: {1}'.format(url_starting, url_unwound))
                    except Exception as exc:
                        print('!! {0}'.format(exc))

if __name__ == '__main__':
    startTime = time.time()
    unwindUrls()
    print('==--- unwind_urls took {0} seconds. ---=='.format(round(time.time() - startTime)))


texts:
I was looking around for a Swift wrapper around NSUserDefaults and found some very nice projects (see e.g. SwiftyUserDefaults). Unfortunately, it all boils down to stringy keys galore...

Eventually, I tried something myself and came up with the code below. I'm tempted to use it in production, but do not have much experience with user defaults and would be grateful for any comments regarding the safety of the solution below:

We start by declaring a pair of protocols that we can use to tag the types we wish to support:

public protocol UserDefaultsObject: AnyObject {}
public protocol UserDefaultsValue {
    var userDefault: UserDefaultsObject { get }
    init(UserDefaultsObject)
}

Tag all the classes supported by NSUserDefaults:

import Foundation

extension NSNumber: UserDefaultsObject {}
extension NSString: UserDefaultsObject {}
// etc...

We declare a struct because that allows us to decide on mutability simply but instantiating a UserDefault value as a let or a var:

public struct UserDefault<T: UserDefaultsValue> {

    public let key: String
    public var value: T? {
        get { return store }
        set {
            store = newValue
            NSUserDefaults.standardUserDefaults().setObject(store?.userDefault, forKey: key)
        }
    }

    public init(key: String, defaultValue: T?) {
        self.key = key
        if let object: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(key) {
            let userDefaultsObject = object as! UserDefaultsObject // this is the crucial line
            store = T(userDefaultsObject)
        } else {
            store = defaultValue
        }
    }

    private var store: T?
}

Now we can extend as many types as we wish. Let's start with Int:

extension Int: UserDefaultsValue {
    public var userDefault: UserDefaultsObject {
        return NSNumber(integer: self)
    }
    public init(_ object: UserDefaultsObject) {
        self = (object as! NSNumber).integerValue
    }
}

Which can be used like so:

var life = UserDefault(key: "Life %", defaultValue: 100) {
    didSet {
        // observe
    }
}

life.value = 50

We can add support for String:

extension String: UserDefaultsValue {
    public var userDefault: UserDefaultsObject {
        return NSString(string: self)
    }
    public init(_ object: UserDefaultsObject) {
        self = object as! String
    }
}

And use it like so (note that we can start with a nil default):

var answer = UserDefault<String>(key: "answer to life the universe and everything", defaultValue: nil)

answer.value ?? "42"

answer.value = "42"

answer.value //--> 42

And so on, we can similarly extend any type whatsoever, as long as we can think of a way of converting it to and from UserDefaultObject...

I'm primarily concerned with safety at this point (will this launch any missiles, etc.), but would certainly welcome any ideas about possible improvements as well as discussion about the general approach of wrapping individual user default values rather than NSUserDefaults class or its standard instance.