texts: Expanding the region of interest of an image

texts:
I am solving a problem of increasing the ROI of a retinal image using the below algorithm-

  First, the set of pixels of the exterior border of the ROI is determined, i.e., pixels that are outside the ROI and are neighbors (using four-neighbourhood) to pixels inside it. Then, each pixel value of this set is replaced with the mean value of its neighbors (this time using eight-neighbourhood) inside the ROI. Finally, the ROI is expanded by the inclusion of this altered set of pixels. This process is repeated and can be seen as artificially increasing the ROI.

My image is of following type-

and the mask on which I am applying the algorithm is below-

Pseudocode for the above approach which I got from here is below-

while there are pixels not in the ROI:
    border_pixels = []

    # find the border pixels
    for each pixel p=(i, j) in image
        if p is not in ROI and ((i+1, j) in ROI or (i-1, j) in ROI or (i, j+1) in ROI or (i, j-1) in ROI)):
            add p to border_pixels

    # calculate the averages
    for each pixel p in border_pixels:
        color_sum = (0, 0, 0)
        count = 0
        for each pixel n in 8-neighborhood of p:
            if n in ROI:
                color_sum += color(n)
                count += 1
        color(p) = color_sum / count

    # update the ROI
    for each pixel p=(i, j) in border_pixels:
        set p to be in ROI

and my implementation for the above pseudocode is below-

img = Image.open(path_dir)
pixelMap = img.load()
@jit
def roifun(img,pixelMap):
    roi = []
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            if pixelMap[i,j] == 255:
                roi.append([i,j])

    return roi

roi= roifun(img,pixelMap)
notroi = img.size[0]*img.size[1] - len(roi)

@jit
def border_enhance(img,pixelMap,roi,notroi):
    while(notroi):
        border_pixels = []
        for i in range(img.size[0]):
            for j in range(img.size[1]):
                if [i,j] not in roi and ([i+1, j] in roi or [i-1, j] in roi or [i, j+1] in roi or [i, j-1] in roi):
                    border_pixels.append([i,j])

        for (each_i,each_j) in border_pixels:
            color_sum = 0
            count = 1
            eight_neighbourhood = [[each_i-1,each_j],[each_i+1,each_j],[each_i,each_j-1],[each_i,each_j+1],[each_i-1,each_j-1],[each_i-1,each_j+1],[each_i+1,each_j-1],[each_i+1,each_j+1]]
            for pix_i,pix_j in eight_neighbourhood:
                if (pix_i,pix_j) in roi:
                    color_sum+=pixelMap[pix_i,pix_j]
                    count+=1
            pixelMap[each_i,each_j]=(color_sum//count)

        for (each_i,each_j) in border_pixels:
            roi.append([each_i,each_j])
            border_pixels.remove([each_i,each_j])
            notroi = notroi-1
            print(notroi)

border_enhance(img,pixelMap,roi,notroi)

I run this code for image of dimension 50×50 and it is running correctly but for an image of larger size like 512×512, it is taking too long a time.
I also tried modifying it using numba but it gave me plenty of warnings and then taking the same time as before.


texts:
I'm trying to write code to solve water pouring problem in Clojure. The following code is strongly influenced by Martin Odersky's solution lectured in his coursera course, Functional Programming Principle in Scala. He first created a class Pouring with parameter capacity, which is accessible everywhere in the class. Though he made the best use of case class in his solution, I just used plain clojure map to represent the moves.

I tried to solve the problem in the same way, and end up with the following code:

(ns pouring)

(declare capacity init-state)

(defn empty [state glass]
  (assoc state glass 0))

(defn fill [state glass]
  (assoc state glass (capacity glass)))

(defn pour [state [from to]]
  (let [amt (min (state from) (- (capacity to) (state to)))]
    (-> state
        (assoc from (- (state from) amt))
        (assoc to (+ (state to) amt)))))

(defn change [state move]
  (if state
    (cond (:empty move) (empty state (:empty move))
          (:fill move) (fill state (:fill move))
          (:pour move) (pour state (:pour move)))
    (change init-state move)))

(defn moves [capacity]
  (let [glasses (range (count capacity))]
    (lazy-cat
     (map (fn [g] {:empty g}) glasses)
     (map (fn [g] {:fill g}) glasses)
     (for [from glasses, to glasses :when (not= from to)]
       {:pour [from to]}))))

(defn extend-path [path move]
  {:history (conj (:history path) move)
   :end-state (change (:end-state path) move)})

(defn extend
  ([paths explored]
   (if-let [more (for [path paths
                       next-path (map #(extend-path path %) (moves capacity))
                       :when (not (contains? explored (:end-state next-path)))]
                   next-path)]
     (lazy-cat paths (extend more (conj explored (map #(:end-state %) more))))))
  ([] (extend #{{:history [], :end-state init-state}} #{init-state})))

(defn init [c]
  (def capacity c)
  (def init-state (vec (repeat (count c) 0))))

(defn solve [capacity target]
  (init capacity)
  (first (for [path (extend)
               :when (some #(= % target) (:end-state path))]
           path)))

The part I don't like is init function. Most clojurians say that using def inside a function is bad. If I don't use init function, perhaps I have to add parameter  capacity to almost every function in the code, which doesn't look pretty.

I was considered using nested function.

(defn solve [capacity target]
  (defn empty ...)
  (defn fill ...)
  (defn pour ...)
  (defn extend ...)
  ...)

However, using defn inside function is also bad, and the functions defined inside are actually not local functions, which are accessible outside the outer function.

Yes, there's letfn in clojure. I can put every function except solve into letfn. But in this case, the code is not very readable. I think letfn is only for short (which can be expressed in 1 or 2 lines) functions.

Perhaps there are better ways to do this. Any suggestions?


texts:
I have a function which does the following:

When new Post Entity is added some fields in Category table are updated.
When new Thread Entity is added the same fields in Category table are updated.

Because of this, some lines are completely the same.

public function postPersist(LifecycleEventArgs $args)
{
    $entity = $args->getObject();
    $entityManager = $args->getObjectManager();

    if ($entity instanceof Post) {
        $post = $entity;

        $thread = $post->getThread();

        $category = $thread->getCategory();
        $category->setLastPostThreadTitle($thread->getTitle());
        $category->setLastPostThreadSlug($thread->getSlug());
        $category->setLastPostBody($post->getBody());
        $category->setLastPosterUsername($post->getUser()->getUsername());
        $category->setLastPostCreatedAt($post->getCreatedAt());
        $category->setIsLastPostOp(false);
        $category->setPosts($category->getPosts() + 1);

        $entityManager->merge($category);
        $entityManager->flush();
    }

    if ($entity instanceof Thread) {
        $thread = $entity;

        $category = $thread->getCategory();
        $category->setLastPostThreadTitle($thread->getTitle());
        $category->setLastPostThreadSlug($thread->getSlug());
        $category->setLastPostBody($thread->getBody());
        $category->setLastPosterUsername($thread->getUser()->getUsername());
        $category->setLastPostCreatedAt($thread->getCreatedAt());
        $category->setIsLastPostOp(true);

        $entityManager->merge($category);
        $entityManager->flush();
    }
}

How would be possible to refactor this code to avoid WET?


texts: Refreshing Google map until new data has been added to the database

texts:
  <title>GPS Tracker</title>
  <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="view/style.css">

Tracking

       <?php
         include"controller/connection.php";
         $query=mysql_query("SELECT id_history FROM tb_history");
         $count=mysql_num_rows($query);
       ?>
       <form method="POST" action="<?=$_SERVER['PHP_SELF']?>">
         <input type="hidden" name="count" value="<?php echo $count ?>">
         <input type="submit" name="submit" class="btn btn-primary" value="Get Location" style="width:280px"> </button>

       </form>

 kanvas peta

<?php
 if(isset($_POST['submit']))
   {
     include "controller/connection.php";
     $count1 = $_POST['count'];
     $count2 = $count1+1;
     $sql = mysql_query("SELECT id_history FROM tb_history");
     $count3 = mysql_num_rows($sql);
     if($count3==$count1)
     {
       echo"";
     }
     else if
     {
       echo"";
     }
   }
 ?>

The code that I wrote above will show a button and a Google map.

Once the button has been clicked, the code will send the amount of data that exist in the tb_history.

The PHP code at the bottom will always check if there's any new data added or not. If not, then it will refresh the Google map until new data has been added to the table tb_history.

Can anyone suggest a better algorithm for this?


texts: Searching for the location of a sub-image within an image

texts:
I have a number of images that were cropped and their backgrounds removed. I've tried to write a function that will search the original unmodified image for the cropped image so that I can restore the cropped image's original size and position. One confounding factor is that the cropped image has a line drawn through it in addition to the background being removed, so even with masking there can't be an exact match, so I'm attempting to find the best match.

I would appreciate any advice on how I can improve performance. For this to be feasible on my machine, I would need to increase speed by 100x.

code:

import numpy
import numexpr as ne
from skimage import io

def overlay(pix, rawImage):
    sizex, sizey, _ = pix.shape
    targetx, targety, _ = rawImage.shape

    bestMatchScore = float('inf')
    for x in range(1, targetx - sizex):
        for y in range(1, targety - sizey):
            start = time.clock()
            test = rawImage[x:pix.shape[0] + x, y:pix.shape[1] + y, :]
            matchScore = numpy.sum(ne.evaluate('sum((test-pix)**2)'))

            if matchScore < bestMatchScore:
                bestMatchScore = matchScore
                xshift, yshift = x,y
            print(time.clock() - start)

    background = numpy.full(rawImage.shape, 255)
    background[xshift: xshift + pix.shape[0], yshift:pix.shape + yshift, :] = pix

    return background

def main():
    pix = io.imread(pathToCropped)
    rawImage = io.imread(pathToRaw)

    background = overlay(pix, rawImage)

if __name__ == '__main__':
        main()

cropped

raw


texts: Login/registration part of an Android application

texts:
I made some PHP files for the login/registration part of my Android application and I would like to know if it can be made safer.

config.php:

<?php

    define('hostname', 'localhost');
    define('username', 'alexiz');
    define('password', '12qwas!@QWAS');
    define('db_name', 'shhaapp_db');

?>

connection.php:

<?php

    require_once 'config.php';

    class DB_Connection {

        private $connect;
        function __construct() {
            $this->connect = mysqli_connect(hostname, username, password, db_name) or die(" DB connection error");
        }

        public function get_connection() {
            return $this->connect;
        }

    }

?>

register.php:

<?php

    require_once 'connection.php';
    header('Content-Type: application/json');

    class User {

        private $db;
        private $connection;

        function __construct() {
            $this->db = new DB_Connection();
            $this->connection = $this->db->get_connection();
        }

        public function registration($email,$username,$password) {
            $query = "INSERT INTO users(email,username,password) VALUES ('$email','$username','$password')";
            $is_inserted = mysqli_query($this->connection, $query);
            if ($is_inserted == 1) {
                $json['success'] = 'account for '.$username.' was created';
            } else {
                $json['error'] = 'email or username is already taken';
            }
            echo json_encode($json);
            mysqli_close($this->connection);
        }

    }

    $user = new User();
    if (isset($_POST['email'],$_POST['username'],$_POST['password'])) {
        $email = $_POST['email'];
        $username = $_POST['username'];
        $password = $_POST['password'];

        if (!empty($email) && !empty($username) && !empty($password)) {
            $encrypted_password = md5($password);
            $user -> registration($email,$username,$encrypted_password);
        } else {
            $json['error'] = 'please fill in all fields';
            echo json_encode($json);
        }
    }

?>

login.php:

<?php

    require_once 'connection.php';
    header('Content-Type: application/json');

    class User {

        private $db;
        private $connection;

        function __construct() {
            $this->db = new DB_Connection();
            $this->connection = $this->db->get_connection();
        }

        public function login($username,$password) {
            $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
            $result = mysqli_query($this->connection, $query);
            if (mysqli_num_rows($result) > 0) {
                $json['success'] = 'welcome '.$username;
            } else {
                $json['error'] = 'incorrect username or password';
            }
            echo json_encode($json);
            mysqli_close($this->connection);
        }

    }

    $user = new User();
    if (isset($_POST['username'],$_POST['password'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        if (!empty($username) && !empty($password)) {
            $encrypted_password = md5($password);
            $user -> login($username, $encrypted_password);
        } else {
            $json['error'] = 'you must fill out all fields';
            echo json_encode($json);
        }
    }

?>


texts: Calling a function once a threshold is met

texts:
I'm currently writing an API for our codebase that allows us to use an Arduino Leonardo for our tests. This code is uploaded to the Arduino, and we read through the analog for work.
As stated in the docstring, this function calls a passed function once a threshold has been met. However, I need there to be a delay between function calls, as signals read from the analog can fluctuate and cause the callback function to be called more than expected. So, I devised a solution that requires the signals to depreciate 1/10 of the threshold value in order for callback to be executed again. The secondFactor is if the user wants to define their own limit of when they want the function to be called again. For example:
NeuroBoard board;
board.setTriggerOnEvenlope(700, Serial.println("Reached!");

This executes the statement once 700 is reached. Then once 630 is reached (700 - (700 x .10)), it set a boolean flag so that once 700 is reached again, it will be called. For another example:
NeuroBoard board;
board.setTriggerOnEnvelope(700, Serial.println("Reached!"), 500);

Same as above, however the boolean flag will only be set once the signals reach 500.
I hope I've explained everything so that it's easily understandable. If anything is unclear, please leave a comment and I'll address it! Below is the code:
NeuroBoard.hpp (code omitted for brevity)
class NeuroBoard {

    private:
        bool thresholdMet = false;

    public:
        /**
         * Calls the passed function when the envelope value is greater
         * than the passed threshold.
         *
         * @param threshold Threshold for envelope value.
         * @param callback Function to call when threshold is reached.
         * @param secondFactor Optional parameter for the second threshold the data must pass.
         *
         * @return void.
        **/
        void setTriggerOnEnvelope(const unsigned int& threshold, void callback(), const unsigned int& secondFactor=0);
}

NeuroBoard.cpp (code omitted for brevity)
The ISR is basically a timer that runs on the Arduino. I've configured it so every second I get about ~50,000 readings from the analog per second. The envelopeValue is the highest reading recorded, then subtracted by one every time a reading isn't equal to or greater than it.
int envelopeValue;

ISR (TIMER1_COMPA_vect) {
    int reading = analogRead(channel);
    envelopeValue = (reading >= envelopeValue) ? reading : envelopeValue - 1;
}

void NeuroBoard::setTriggerOnEnvelope(const unsigned int& threshold, void callback(), const unsigned int& secondFactor=0) {

    // TODO: Call callback when passed threshold is met by envelope value.

    const int THRESHOLD_SCALE_FACTOR = threshold / 10;
    int secondThreshold = secondFactor;

    if (secondFactor == 0) {
        secondThreshold = threshold - THRESHOLD_SCALE_FACTOR;
    }

    if (envelopeValue >= threshold) {
        if (!this->thresholdMet) {
            this->thresholdMet = true;
            callback();
        }
    } else {
        if (envelopeValue <= secondThreshold) {
            this->thresholdMet = false;
        }
    }

}

Note: Because this code is for an Arduino, I cannot use any standard library functions or imports. However, because this section of our code is pure c++, I don't think it will be an issue. But please consider that if you decide to write an answer. Thanks!


texts:
I'm very new to C, so pointing out better ways of doing things, errors, bad practices, etc would be optimal at this stage.

Code on GitHub

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

int *calculateFibonacciSequence(int n, int start)
{
  int i;

  // Allocate memory for our fibonacci sequence from the heap
  int *numbers = malloc(sizeof(int) * n);

  // Need to calculate at least one number
  if (n <= 0) {
    return 0;
  }

  // Can't start with a number under zero
  if (start != 0 && start != 1) {
    return 0;
  }

  // Get the seed values
  if (start == 0) {
      numbers[0] = 0;
      numbers[1] = 1;
  } else {
      numbers[0] = 1;
      numbers[1] = 1;
  }

  // Calculate the sequence
  for (i = 1; i < n; i++) {
    numbers[i + 1] = numbers[i] + numbers[i - 1];
  }

  return numbers;
}

int main(int argc, char *argv[])
{
  int i, n;
  int start = 0;
  int *sequence;

  // Check to see how many arguments we got
  if (argc <= 1) {
    puts("Please pass the number of iterations to run.");
    return 1;
  }

  // Get the number of iterations to run
  n = atoi(argv[1]);

  // Did they specify a start value
  if (argc > 2) {
    start = atoi(argv[2]);
  }

  // Calculate the sequence
  sequence = calculateFibonacciSequence(n, start);

  // Output the sequence
  if (sequence) {
    printf("%d", sequence[0]);

    for (i = 1; i <= n; i++) {
      printf(",%d", sequence[i]);
    }

    // Newline
    puts("");
  } else {
    puts("Error processing fibonacci sequence");
  }

  // Free memory
  free(sequence);

  return 0;
}


texts:
I'm trying to learn Crystal. I made this to create a web token for authorization. I keep it updated on github.

Here is how I use it:

user = {
    id: 1,
    name: "John",
    role: "user",
}

token = CWT.make(user)
# CWT.revoke(token)

begin
    # new_token is not nil if token was "stale", > 1 day old
    payload, new_token = CWT.get_payload(token)
    puts payload
    if new_token != nil
        puts new_token
    end
rescue ex
    puts ex.message # expired, invalid, etc.
end

Here is the source:

require "base64"
require "crypto/subtle"
require "openssl/hmac"

class CWT
    @@secret = ENV["CWT_SECRET"]
    @@life_span = Time::Span.new(24*3, 0, 0)
    @@stale_span = Time::Span.new(24, 0, 0)
    @@revoked_tokens = [] of String

    def self.make(payload) : String
        expires_payload = "#{Base64.strict_encode(Time.now.to_s)}.#{Base64.strict_encode(payload.to_json)}"

        return "#{expires_payload}.#{hmac(@@secret, expires_payload)}"
    end

    def self.get_payload(token : String) : {JSON::Any, String?}
        if token.split(".").size != 3
            raise "token not properly formatted"
        end

        if is_expired(token)
            raise "token expired"
        end

        if has_integrity(token) != true
            raise "token doesn't haave integrity"
        end

        if is_revoked(token)
            raise "token has been revoked"
        end

        payload_json = Base64.decode_string(token.split(".")[1])

        if is_stale(token)
            new_token = make(payload_json)
        end

        return JSON.parse(payload_json), new_token
    end

    def self.revoke(token : String) : Void
        @@revoked_tokens.push(token)
    end

    def self.is_revoked(token : String) : Bool
        if @@revoked_tokens.index(token) != nil
            spawn do
                @@revoked_tokens.delete(token)
                @@revoked_tokens.each do |revoked_token|
                    if is_expired(revoked_token)
                        @@revoked_tokens.delete(revoked_token)
                    end
                end
            end

            return true
        end

        return false
    end

    def self.is_expired(token : String) : Bool
        expires_str= Base64.decode_string(token.split(".")[0])
        made_at = Time.parse(expires_str, "%Y-%m-%d %H:%M:%S %z")

        return made_at + @@life_span < Time.now
    end

    def self.is_stale(token : String) : Bool
        expires_str= Base64.decode_string(token.split(".")[0])
        made_at = Time.parse(expires_str, "%Y-%m-%d %H:%M:%S %z")

        return made_at + @@stale_span < Time.now
    end

    def self.has_integrity(token : String) : Bool
        parts = token.split(".")
        expires_payload = "#{parts[0]}.#{parts[1]}"

        return Crypto::Subtle.constant_time_compare(hmac(@@secret, expires_payload), parts[2])
    end

    def self.hmac(key : String, data : String) : String
        return Base64.strict_encode(OpenSSL::HMAC.digest(:sha256, key, data))
    end
end

Do you see any potential bugs / crashes?
How can I improve the performance of this?
How can I improve the security of this?


texts: Limit choices for Django admin filter_horizontal interface

texts:
The Django ModelAdmin offers a filter_horizontal (or filter_vertical) interface for many-to-many relations, which allows the user to filter a list of available related objects.
My goal is to limit the set of choices for this interface, dynamically, based on the value of another form field.
This is somewhat similar to filtering the form field queryset or using limit_choices_to on the server side, but I want to do it dynamically, on the client side.
The implementation is supposed to be generic, because it is re-used on a variety of admin forms.
An example of the filter_horizontal interface is shown below (together with a normal select box).

Based on the source for Django's JavaScript filter interface, viz. SelectFilter2.js and SelectBox.js, I came up with the following JavaScript function:
function updateOptionsDisplay(fieldId, allowableOptions) {
    // fieldId is the id of the original <select> element, typically 'id_<model field name>'
    // allowableOptions is an array of allowable object id strings
    for (let side of ['_from', '_to']) {
        // window.SelectBox is set in django's SelectBox.js
        for (let option of window.SelectBox.cache[fieldId + side]) {
            // option is an object with value, text, and displayed properties, not an HTMLOptionElement
            // type of option.displayed in django source is int, not boolean, hence the Number()
            option.displayed = Number(allowableOptions.includes(option.value));
        }
        window.SelectBox.redisplay(fieldId + side);
    }
}

This function shows existing <option> elements if their value is in the allowableOptions array, and hides them otherwise.
The content of the allowableOptions array is a function of the value of another form element, e.g. another select box, and is obtained using AJAX in some cases, or from template context in other cases.
This seems to work well, and it also "remembers" previously selected choices.
However, I wonder if there may be some unexpected side effects. Also, any comments with respect to the JavaScript itself would be very welcome.
The whole thing is implemented by extending the admin change_form.html template, as described in the documentation.


texts: Sums for list of ranges (CodeFights Basic Skills)

texts:
I can solve this problem with a brute force naive solution, but need to optimize it for time. I'm not in school, but trying to learn fundamentals on my own.

I know I need to store the sum of the indices already counted so that I am not recounting ranges I've already covered. Like in the example below if I already summed [0,2] and [2, 5] I could just add those sums to get [0, 5] sum without iterating over array. But I don't know how to implement this.

Here is the description:

  You have an array of integers nums and an array queries, where
  queries[i] is a pair of indices (0-based). Find the sum of the
  elements in nums from the indices at queries[i][0] to queries[i][1]
  (inclusive) for each query, then add all of the sums for all the
  queries together. Return that number modulo 10^9 + 7.

Example:

  For nums = [3, 0, -2, 6, -3, 2] and queries = [[0, 2], [2, 5], [0,
  5]], the output should be sumInRange(nums, queries) = 10.

  The array of results for queries is [1, 3, 6], so the answer is 1 + 3
  + 6 = 10.

My solution:

func sumInRange(nums: [Int], queries: [[Int]]) -> Int {

    var sumArray = [Int]()

    for q in queries {

        var tempSum = 0

        for i in q[0]...q[1] {

            tempSum += nums[i]
        }

        sumArray += [tempSum]
    }

    let sum = sumArray.reduce(0, +)
    let bigNumber = 1000000000 + 7

    return sum > 0 ? sum % bigNumber : bigNumber + sum
}


texts:
I'm beginning to learn about Golang and I would like to have some advice about the following program.

package main

import (
    "fmt"
    "net/http"
    "time"
)

const BenchmarkTry = 1000

type PageBenchmark struct {
    url  string
    time int64 // microseconds
}

func execBenchmark(url string, channel chan PageBenchmark) {
    totalExecTimeChan := make(chan int64, BenchmarkTry) // set size to prevent blocked goroutine
    totalExecTime := int64(0)

    // start all the goroutines
    for i := 0; i < BenchmarkTry; i++ {
        go execHttpRequest(url, totalExecTimeChan)
    }

    // catch new values from totalExecTimeChan values come from execHttpRequest()) and add it to the total
    for i := 0; i < BenchmarkTry; i++ {
        totalExecTime += <-totalExecTimeChan // waiting to get a value from one of the goroutines started in the previous for loop
    }

    channel <- PageBenchmark{url, totalExecTime / BenchmarkTry}
}

// exec http request and attach exec time to channel
func execHttpRequest(url string, channel chan int64) {
    begin := time.Now()
    _, _ = http.Get(url)
    channel <- time.Since(begin).Nanoseconds() / 1000000 // convert to milliseconds
}

func main() {
    sites := [...]string{

    }

    pages := [...]string{

    }

    benchmarkChan := make(chan PageBenchmark, len(sites)*len(pages)) // set size to prevent blocked goroutine

    begin := time.Now()
    fmt.Println("Beginning !")

    // start all the goroutines
    for site := range sites {
        for page := range pages {
            go execBenchmark(sites[site]+pages[page], benchmarkChan)
        }
    }

    // catch new values from benchmarkChan and "print" the PageBenchmark
    for i := 0; i < len(sites)*len(pages); i++ {
        benchmark := <-benchmarkChan
        fmt.Printf("Url : %v\nResponse Time : %d ms\n\n", benchmark.url, benchmark.time)
    }

    // print execution time
    fmt.Println("End.")
    fmt.Println(fmt.Sprintf("%d ms", time.Since(begin).Nanoseconds()/1000000))

}

Basically, I'm making HTTP requests (GET method) to multiple URLs on multiple web sites. 1000 requests by URL in this example.

For now, I just want to start some goroutines in this order:

Main: start a benchmark (goroutine) for each web site pages, get the average execution time and print it.
Page routine: start 1000 goroutines (benchmark tries), get the execution times from a channel and store the average execution time in an other channel.
Execute an HTTP request on the page and store the execution time in a channel.

This piece of code works but there may be things I'm missing.

Is the execution scheduling valid?
Is it appropriate to use defined size channels here?
Is there a better/more effective way to achieve this task?


texts: Partition a linked list arround an element

texts:
This is my code to partition a list into two parts according to a value. I.e. nodes smaller than value x should precede nodes larger than the value x.
It seems correct. Any corner cases I am overseeing or corrections are highly appreciated.

public Node partition(Node head, int x){
   if(head == null) return head;
   Node prev = null;
   Node current = head;
   while(current != null){
       if(current.data > x || current == head){
           prev = current;
           current = current.next;
       }
       else{
           Node next = current.next;
           current.next = head;
           if(prev != null) {
              prev.next = next;
           }
           head = current;
           current = next;
      }
   }
   return head;
}


texts: Optimizing MD5 OpenSSL Implementation in C for Precomputed Hash

texts:
I am trying to port a piece of code from Python to C. What the code does is that it generates a list of precomputed MD5 hash from a plaintext wordlist.
The code also has its variations in SHA-1 and SHA-2 families in all 3 programming languages. The structure is the same.
I originally wrote the code in Bash, which was slow. So I ported it to Python which was significantly faster. Now, I have successfully ported the code to C, in hoping that it will run even faster. However, even with
-O faster flag on in gcc, the code still run slower than the Python version (the difference in execution time increases exponentially with the input size).
I have also doubted about the efficiency of the OpenSSL crypto libraries, but it seems to me that they are relatively well-established after reading through their Documentation.
I am guessing that it is the nested loop that I implemented in the C version of the code that is slowing the whole thing down.
Any suggestion to increase the performance?
Bash Version:

#/!bin/bash

while read line

do

printf $line | md5

done

Python Version:

import hashlib

infile = 'wordlist'

outfile = open("precomputed","a")

with open(infile, "r") as inf:

    for line in inf:

        outfile.write(hashlib.md5(line.strip().encode('utf8')).hexdigest()+'\n')

C Version:
//-----------Libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>

//------------------------------Main Function------------------------//
int main()
{

//------Define infile, outfile, file length. Define string to be read.---//
  FILE *infile, *outfile;
  char *string = NULL;
  size_t len = 0;
  ssize_t read;
//------Open File stream for read(r) and write (w). Error Handling.--//

  //Part of MD5 Hash Function (Taken out of While Loop for Optimization)
  int md5;
  unsigned char result[MD5_DIGEST_LENGTH];
  //

  infile = fopen("file.txt", "r");

  if (infile == NULL)
    exit(EXIT_FAILURE);

  outfile = fopen("MD.txt","w");

  if (outfile == NULL)
    exit(EXIT_FAILURE);

//-------------Read line-by-line in using a while loop.--------------//
  while ((read = getline(&string, &len, infile)) != -1) {

     string[strcspn(string, "\n")] = 0; // Remove newline '\n'

//-------------------------MD5 Hash Function-------------------------//

      MD5(string, strlen(string), result);

      //output
      for(md5 = 0; md5 < MD5_DIGEST_LENGTH; md5++)

      fprintf(outfile,"%02x",result[md5]); //convert the hash to hex

      fprintf(outfile,"\n"); //newline for the output file

  }

  free(string); //free string
  fclose(infile); // close file streams
  fclose(outfile);
  exit(EXIT_SUCCESS); //Program Ends
}

I can provide the execution time with different size of input if requested. Any help will be appreciated.


texts:
I can see a possible performance optimization with declaring 2 arrays and iterating the $fake_widgets only once, but how else can I  make the following conditional string building more elegant in Ruby?

pending_coloring = $fake_widgets.select do |widget|
  widget[:status] == 'awaiting_coloring' && widget[:owner_color] == @owner.id
end

pending_processing = $fake_widgets.select do |widget|
  widget[:status] == 'awaiting_processing' && widget[:owner_color] == @owner.id
end

notification_text = "You have "

if pending_coloring.size == 1
  notification_text += "#{pending_coloring.size} widget to color"
elsif pending_coloring.size > 1
  notification_text += "#{pending_coloring.size} widgets to color"
end

if pending_coloring.size > 0 && pending_processing.size > 0
  notification_text += " and "
end

if pending_processing.size == 1
  notification_text += "#{pending_processing.size} widget to process"
elsif pending_processing.size > 1
  notification_text += "#{pending_processing.size} widgets to process"
end

notification_text += ". Go to widget dashboard"


texts:
I've heard that Lbl and Goto use up memory that they don't give back. I've noticed clearing the RAM on my calculator frees up a lot of space and makes my programs run a lot faster. Any suggestions on how to minimize memory leaks here would be greatly appreciated. (This code does function correctly other than leaking memory).

:-1->B
:Lbl H
:B+1->B
:0->A
:If B=95
:Goto E
:Lbl V
:Pxl-Change(A,B)
:A+1->A
:If A=63
:Goto H
:Goto V
:Lbl E

I've represented the STO→ character, → with -> Also, the graph is 94 pixels wide and 62 pixels tall.


texts: Increase performance of a spate of 2x2 matrix multiplication

texts:
I would like to improve the performance of the piece of code below (in Fortran). It gives good results but the profiling tells me that it is where it spends most of its running time.

Basically, it increments over a time window (j loop) and performs a spate of 2x2 matrix multiplications. I was wondering where I can refactor it to make it much more efficient. For instance, is there a smarter and faster way to initialise the identity matrices?

do j=1,nb_pts_t + 1
   t = t + dt
   ! Compute Zgates for all pairs in up/down states
   call Z_gate (eigen_ener_up, t / dble(2 * CP_seq), Zgate_u)
   call Z_gate (eigen_ener_down, t / dble(2 * CP_seq), Zgate_d)

   ! Initialize identity matrices
   Tfu%elements(1,1) = dcmplx(1.d0, 0.d0)
   Tfu%elements(1,2) = dcmplx(0.d0, 0.d0)
   Tfu%elements(2,1) = dcmplx(0.d0, 0.d0)
   Tfu%elements(2,2) = dcmplx(1.d0, 0.d0)
   Tfd%elements(1,1) = dcmplx(1.d0, 0.d0)
   Tfd%elements(1,2) = dcmplx(0.d0, 0.d0)
   Tfd%elements(2,1) = dcmplx(0.d0, 0.d0)
   Tfd%elements(2,2) = dcmplx(1.d0, 0.d0)

   ! work out transition matrices in up/down states
   ! and compute the decoherence
   do i=1,nb_pairs
      ! rotate to eigenbasis and propagate
      Tu(i)%elements = matmul(Zgate_u(i)%elements, matrot_u(i)%elements)
      ! rotate back to bath basis
      Tu(i)%elements = matmul(matrottrans_u(i)%elements, Tu(i)%elements)
      ! Idem down state
      Td(i)%elements = matmul(Zgate_d(i)%elements, matrot_d(i)%elements)
      Td(i)%elements = matmul(matrottrans_d(i)%elements, Td(i)%elements)

      ! Initialize Tud and Tdu
      Tud(i)%elements = matmul(Tu(i)%elements, Td(i)%elements)
      Tdu(i)%elements = matmul(Td(i)%elements, Tu(i)%elements)

     do k=1,CP_seq
         if(modulo(k, 2) .ne. 0) then
            Tfu(i)%elements = matmul(Tfu(i)%elements, Tud(i)%elements)
            Tfd(i)%elements = matmul(Tfd(i)%elements, Tdu(i)%elements)
         else if(modulo(k, 2) == 0) then
            Tfu(i)%elements = matmul(Tfu(i)%elements, Tdu(i)%elements)
            Tfd(i)%elements = matmul(Tfd(i)%elements, Tud(i)%elements)
         end if
      end do

      ! Decoherence from initial |down-up> bath state
      L_pairs(i) = abs(conjg(Tfd(i)%elements(1, 1))*Tfu(i)%elements(1, 1) &
           - Tfd(i)%elements(1, 2) * Tfu(i)%elements(2, 1))

      ! average over the bath states
      L_pairs(i) = 0.5d0 + 0.5d0 * L_pairs(i)
   end do

   ! Final decay as the product over all pair decays
   L = product(L_pairs)

   ! write the output
   write(16, fmt)t, L

end do


texts: Calculating all prime palindromes from 0 to 1000 and printing the largest

texts:
I have often read about how important clear and efficient code is. Also often people talk and write about 'beautiful' code. Some hints and critic from experienced developers for the following code would be extremely helpful to me. Another question that I often ask myself is about list comprehensions: I feel that in the first specific code (about prime palindromes), especially the second function that verifies palindrome characteristics could be expressed on one line in a list comprehension - how would that work, and would it even be an advantage of some sort?

The code calculates all the prime palindromes from 0 to 1000 and prints the largest.

#My solution to codeval challenge Prime Palindrome. AUTHOR: S.Spiess
#initial count
counting_list = [x for x in range(0,1001)]

#prime number check. make list prime_list containing only primes from 0 to 1000
def prime_check(a_list):
    prime_list = []
    for k in a_list:
        count = 2.0
        d_test = 0
        while count < k:
            if k % count == 0:
                d_test += 1
                count += 1
            else:
                count += 1
        if d_test < 1 and k > 1:
            prime_list.append(k)

    return prime_list

#check prime numbers from previous function for palindrome characteristic. append in new list.
def palindrome_check(num_list):
    palindrome_list = []
    for i in num_list:
        temp = str(i)
        if temp == temp[::-1]:
            palindrome_list.append(i)

    return palindrome_list

#print biggest palindrome prime from 0 to 1000
print max(palindrome_check(prime_check(counting_list)))

Here is another sample of code I wrote. It contains two functions that can change the base of a number.

def to_mod20(any_num):
    a_list = []

    if any_num < 20 and any_num >= 1:
        a_list.append(int(any_num))

    while any_num >= 20:
        a_list.append(any_num % 20)
        if any_num / 20 < 20:
            a_list.append(any_num / 20)
        any_num = any_num / 20
    #invert list for proper output
    return a_list[::-1]

def decimal_mod20(any_dec):
    count = 0
    a_list = []
    while any_dec < 1 and count < 4:
        a_list.append(int(any_dec * 17.0))
        any_dec = any_dec * 17.0 - int(any_dec * 17.0)
        count += 1
        #print any_dec

    return a_list


texts:
There is nothing wrong, but is there a nicer way to re-write this program?

public IEnumerable<Employee> InsertEmployee(dynamic employees)
        {
            var newEmployeeRecord = new List<Employee>();

            foreach (dynamic employee in employees)
            {
                newEmployeeRecord.Add(

                    new Employee
                    {
                        EmployeeId = Convert.ToInt32(employee.EmployeeId)
                        ,
                        EmployeeName = Convert.ToString(employee.EmployeeName)
                        ,
                        Age = Convert.ToInt32(employee.Age)
                        ,
                        Salary = Convert.ToInt32(employee.Salary)
                        ,
                        DepartmentId = Convert.ToInt32(employee.DepartmentId)
                    }
                );
            }
            return EmployeeRecords.Concat(newEmployeeRecord);
        }

Also, can we avoid typecasting? (I think it's not possible, so it could require an extension method.)


texts: How long a PID has been running (taking multiple inputs)

texts:
Tonight I tried to write a POSIX shell script which would allow me to check how long a process is running (via it's ID) and be able to handle multiple inputs:

#!/bin/sh

is_this_a_number()
{
    if [ "$1" -eq "$1" ] 2> /dev/null
    then
        return 0
    else
        return 1
    fi
}

does_pid_exist()
{
    if ps --pid "$1" > /dev/null 2>&1
    then
        return 0
    else
        return 1
    fi
}

how_long_pid_has_been_running()
{
    ps --pid "$1" --format etime=
}

trim_leading_and_trailing_spaces()
{
    awk '{$1=$1;print}'
}

arg_pos=0

while [ "$#" -gt 0 ]
do

    arg_val="$1"
    arg_pos=$((arg_pos + 1))

    if ! is_this_a_number "$arg_val"
    then

        echo "The argument at position $arg_pos is not a number."

    else

        echo "Process ID $arg_val"

        if ! does_pid_exist "$arg_val"
        then

            echo "This process does not exist."

        else

            how_long_pid_has_been_running "$arg_val" | trim_leading_and_trailing_spaces

        fi

    fi

    printf "\\n"

    shift

done

Usage:

./how-long-pid-is-running 1 10078 c 40545454

Where 10078 is an instance of Chrome.

The output is as follows:

Process ID 1
09:04:31

Process ID 10078
07:32:32

The argument at position 3 is not a number.

Process ID 40545454
This process does not exist.


texts: Positioning the left-right arrow buttons for a carousel

texts:
I have a carousel (Owl Carousel) with vertically centered controls. Because of the structure, I have to absolutely position the previous and next arrow. Because the page is responsive, their position is dynamic. The size of the controls may also change.

I've written a function that runs on load and resize. It gets the height of the image and the height of the controls, subtracts the latter from the former, divides by two, and then uses that number as the controls' margin-top.

It works, but I'm questioning if I'm getting and using all the variables correctly. Does JavaScript read in order? Where it runs the first line, then the next, then the next... I'm strong in CSS but JS has always been a crutch.

Can I write this more efficiently?

function centerCarouselControls() {
  var carouselImage = $('.carousel-card > img');
  var carouselControls = $('.owl-nav > div');
  var carouselHeight = carouselImage.outerHeight();
  var controlHeight = carouselControls.outerHeight();
  var controlMargin = (carouselHeight - controlHeight) / 2;
  carouselControls.css('margin-top', controlMargin);
}

$('.carousel-card > img').load(centerCarouselControls);
$(window).on('resize', centerCarouselControls + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


texts:
This reverses the case of a character in a string (a string being an array of characters). How does it look? Anything I can improve on? Besides documentation, in particular, any thoughts on the type casting found in str_case_rev?

#include <stdio.h>  // fprintf
#include <stdlib.h> // malloc
#include <string.h> // strlen
#include <ctype.h>  // toupper, tolower

/*
 * a string is an array of characters, in C, all arrays
 * are always passed never passed value, always a pointer to
 * the variable
 * This is why the caller does not need to call the function like:
 * camel_case_rev(src, &dest, len)
 *
 * Since here the array of characters ("a string") is already being
 * passed as a pointer value
 */
void str_case_rev(const char *src, char *dest, size_t len)
{
        size_t i = 0;

        for(; i < len; i++)
        {
                if(src[i] <= 'Z' && src[i] >= 'A')
                {
                        *(dest + i) = (char)tolower((int)src[i]);
                }
                else if(src[i] <= 'z' && src[i] >= 'a')
                {
                        *(dest + i) = (char)toupper((int)src[i]);
                }
                else
                {
                        *(dest + i) = src[i];
                }
        }

        i++;
        *(dest + i) = '\0';
}

int main(int argc, char **argv)
{
        if(argc < 2)
        {
                fprintf(stderr, "Usage: %s <string>\n", argv[0]);
                return EXIT_FAILURE;
        }

        char *dest = NULL;

        size_t len = strlen(argv[1]);

        dest = malloc(len + 1);

        if(NULL == dest)
        {
                fprintf(stderr, "Memory error\n");
                return EXIT_FAILURE;
        }

        str_case_rev(argv[1], dest, len);

        fprintf(stdout, "%s\n", dest);

        free(dest);

        return EXIT_SUCCESS;
}


texts:
I'm new to c++ and that is my list-based stack implementation.
It works, but i'm not sure that my code is good.

Please help me to improve this code, any advices are welcome.

#include <iostream>

struct Node {
    int data;
    struct Node *next;
};

class Stack {
private:
    Node *top;
public:
    Stack()
    {
        top = nullptr;
    }

    void push(int value)
    {
        Node *n = new Node;
        n->data = value;
        n->next = top;
        top = n;
    };

    void pop()
    {
        if (top != nullptr)
        {
            Node *n = top;
            top = top->next;
            delete n;
        }
    }

    bool isEmpty() {
        return top == nullptr;
    }

    int getTop()
    {
        if (top != nullptr)
            return top->data;
        else return INT32_MIN; // my value is in range [-100; 100]
    }

    void display()
    {
        Node *n = top;
        while (n != nullptr)
        {
            if (n == top) std::cout << "\t\t\tTOP ELEMENT" << std::endl;
            else {
                std::cout << "                             |" << std::endl;
                std::cout << "                            \\|/" << std::endl;
            }
            // i need to print data, address of element and address to next element
            std::cout << "---------------------------------------------------------" << std::endl;
            std::cout << "Data: " << n->data << "\t\tAddress: " << n <<"\tNext: " << n->next << std::endl;
            std::cout << "---------------------------------------------------------" << std::endl;
            n = n->next;
        }
    }
};


texts: Is there a more elegant solution than this spaghetti code without completely revamping the whole page?

texts:
I use 'GROUP_CONCAT' to get comma separated lists of a person's educational background.  Included in those lists are the type of degree, major, issuing establishment, and year received.  degreeType is a required field and cannot empty.  Prior to looping, I split the lists into arrays, like so:

$degreeType = explode(",", $degreeType);
$major = explode(",", $major);
$issuingEstablishment = explode(",", $issuingEstablishment);
$yearReceived = explode(",", $yearReceived);

I can then do a foreach loop and echo out the information returned.  However, since explode() returns an array, even if it's empty, I have to check it first before starting the foreach.  As shown below:

$counter = 0;
//echo out education
if($degreeType[0]!=""){
  foreach($degreeType as $dType) {
    if($counter == 0) $info .= "
Educational Background

";
    $info .= "
$dType - ";
    $info .= ($major[$counter]!="") ? "$major[$counter], " : "";
    $info .= $issuingEstablishment[$counter];
    $info .= ($yearReceived[$counter]!="") ? ", $yearReceived[$counter]" : "";
    $info .= "
";
    $counter++;
  }
  $info .= "
";
}

Alternatively, I could run a check prior to separating the lists.  Either solution seems inelegant.  Is there a cleaner/faster/better way to split the lists and loop through them, but only if they actually contain information?  Initially I was going to dabble with using an object, but mysqli doesn't support that with prepared statements.  Any advice is much appreciated!


texts:
Given K descriptions for bus line paths that exists to lead students between N campuses. What is the minimum cost that a student will have to goes from campus 1 to campus N ?
The itinerary of each path L is a sequence of |L|( ≥ 2 ) campuses {C1, C2, …, CL}, and each line has only one bus, which passes by all campuses of the line, following the itinerary order, stopping in each of them and making a U-turn whenever it reaches an endpoint of the itinerary, reversing the itinerary order. The transport pass costs 1$, and has to be paid by the passenger while getting onto the bus, no matter the time the passenger is going to stay in it.
Input:

The first input line consists of two integers N and K (2 ≤ N ≤ 10^4, 1 ≤ K ≤ 10^3), which represent respectively the number of campuses and the number of public transport lines created by UFFS. Each one of the K input lines following describes a transport line L and consists of the integer |L| (2 ≤ |L| ≤ 10^2) followed by the |L| identifiers Ci (1 ≤ Ci ≤ N, 1 ≤ i ≤ |L|) of the campuses by which the ship passes, wherein C1 and C|L| are the endpoints of L. For every campus A and every campus B it is guaranteed that it is possible to go from A to B.

Output:

Output the minimum cost to go from campus 1 to campus N.

To solve this i've tried a BFS. Each node has its distance updated. The algorithm takes the minimum distance found.
The code is easy to understand ?
I'm getting time limit exceeded on the judge that has this problem. How can i make this solution faster ?
#include <cstdio>
#include <vector>
#include <queue>
#include <string.h>

struct Edge{
    int d,t,c; //distance , target and color
    Edge(int _d,int _t ,int _c):d(_d),t(_t),c(_c){}
    Edge(int _t, int _c):d(0),t(_t),c(_c){}
};

using adj_list = std::vector<Edge>    ;
using graph    = std::vector<adj_list>;

unsigned int BFS(graph &g, int source, int target, int max_colors){

    //init visited as false for every node
    bool visited[g.size()][max_colors];
    memset(visited,false,sizeof(visited));

    //put the source with an unexistent color(forcing int to buy all possible colors) and distance=0
    std::queue<Edge> q;
    q.push(Edge(0,source,0));

    unsigned int shortest_path = -1; //infinity
    while (!q.empty()) {
        Edge e = q.front();
        q.pop();

        //this path is already bigger than the minimum one
        if(e.d > mini)
            continue;

        if(e.t == target){ //target node was found
            shortest_path = e.d < shortest_path ? e.d : shortest_path;
            continue;
        }

        if(visited[e.t][e.c])
            continue;

        visited[e.t][e.c] = true;

        adj_list &adj_u = g[e.t];
        for (auto &v : adj_u) {
            //distance from adjacent node increases if its color is
            //different from the visited node color...
            //the target and color keeps the same
            q.push(Edge(e.d + (v.c != e.c), v.t, v.c));
        }
    }

    return shortest_path;
}

int main(void) {
    int n,k;
    scanf("%d %d",&n,&k);

    graph g(n + 1);
    for (int i = 1; i <= k; ++i) {
        int l,u,v;
        scanf("%d %d %d",&l,&u,&v);

        g[u].push_back(Edge(v,i));
        g[v].push_back(Edge(u,i));
        for (int j = 2; j < l; ++j) {
            u = v;
            scanf("%d",&v);
            g[u].push_back(Edge(v,i));
            g[v].push_back(Edge(u,i));
        }
    }

    /*
     for (int i = 0; i < g.size(); ++i) {
     printf("%d : ",i);
     for (int j = 0; j < g[i].size(); ++j) {
     printf("%d -> ",g[i][j].t);
     }
     printf("\\ \n");
     }
     */

    printf("%u\n",BFS(g, 1, n, k + 1));
}

For example consider the following input:

9 4
6 2 3 4 6 7 9
4 1 3 4 5
3 8 3 4
2 9 8

For this case the minimum cost is 2;


texts:
4sum problem

  Given an array S of n integers, are there elements a, b, c, and d in S
  such that a + b + c + d = target? Find all unique quadruplets in the
  array which gives the sum of target.

  Note: The solution set must not contain duplicate quadruplets.

Idea is to put all the pair sums a in hashmap along with corresponding indexes and once done check if -a is also present in the hashmap. If both a and -a is present and since the question is looking for unique quadruplets then we can just filter out with indexes.

class Solution(object):
    def fourSum(self, arr, target):
        seen = {}
        for i in range(len(arr)-1):
            for j in range(i+1, len(arr)):
                if arr[i]+arr[j] in seen:
                    seen[arr[i]+arr[j]].add((i,j))
                else:
                    seen[arr[i]+arr[j]] = {(i,j)}
        result = []
        for key in seen:
            if -key + target in seen:
                for (i,j) in seen[key]:
                    for (p,q) in seen[-key + target]:
                        sorted_index = sorted([arr[i], arr[j], arr[p], arr[q]])
                        if i not in (p, q) and j not in (p, q) and sorted_index not in result:
                            result.append(sorted_index)
        return result


texts: Haikuifier (Or at least Haiku Identifier)

texts:
All the usual stuff. Style, substance, algorithm please! I'm vaguely considering plugging it into a bot, hence the lacklustre catching of exceptions right now.

import requests
import sys

def get_num_syllables(value):
    try:
        res = requests.get("http://www.thefreedictionary.com/" + value)
    except requests.exceptions.ConnectionError as e:
        return -1

    for word in res.text.split():
        if "<h2>" not in word:
            continue
        word = word[word.find("<h2>")+ 4:word.find("</h2>")]

        if '·' in word:
            return word.count('·') + 1
    if "Word not found in the Dictionary and Encyclopedia." in res.text:
        return -1
    return 1

def haikuify(sentence):
    sentence = sentence.strip()
    num_syllables = []
    for word in sentence.split():
        num_syllables.append(get_num_syllables(word))

    if -1 in num_syllables:
        raise SyntaxError("Someone can't spell - can't find a word from the sentence in the dictionary")

    haiku_form = [5, 7, 5]
    haiku_indices = []
    i = -1
    run = 0
    line = 0

    for value in num_syllables:
        run += value
        if run is haiku_form[line]:
            haiku_indices.append(i)
            line += 1
            run = 0
        elif run > haiku_form[line]:
            raise SyntaxError("Not a haiku")
            break
        i += 1

    haiku_indices.append(len([len(x) for x in sentence.split()]) - 1)

    if len(haiku_indices) is not 3:
        raise SyntaxError("Not a haiku")

    i = -1
    line = 0
    this_line = ""
    haiku = []
    for word in sentence.split():
        word = word.replace(" ", "")
        if not word:
            continue

        this_line += " " + word
        i += 1
        if i is haiku_indices[line]:
            haiku.append(this_line)
            this_line = ""
            line += 1

    return haiku

if __name__ == "__main__":
    sentence = input("Sentence to haikuify: ")
    haiku = []
    try:
        haiku = haikuify(sentence)
    except SyntaxError as err:
        print(err.msg)
    print(haiku)


texts:
Inspired by Reddit r/dailyprogrammer

  Help! My keyboard is broken, only a few keys work any more. If I tell you what keys work, can you tell me what words I can write?

The program works fine, not really any additions I wish to make to it. Was just wanting some general feedback on the layout, structure and efficiency.

Note: The dictionary used can be found in the given link.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 7/1/2016.
 *
 * Inspired by r/dailyprogrammer
 * https://www.reddit.com/r/dailyprogrammer/comments/3pcb3i/20151019_challenge_237_easy_broken_keyboard/
 */

public class BrokenKeyboard {

    private static List<String> wordDict;
    private static final String dictPath = "Dictionaries/EnglishWords.txt";

    /**
     * The main acquires input from the user then
     * applies it to the other below methods.
     * @param args Unused.
     */

    public static void main(String args[]) {
        BrokenKeyboard.setDict(dictPath); // Stores dictionary in list.
        System.out.println("Processing...");
        System.out.println(String.join(", ", findMatches("bikn", wordDict)));
    }

    /**
     * Used to load a given text file into memory.
     * @param filePath Used to specify the path of the file that needs to be loaded into memory.
     */
    private static void setDict(String filePath){
        try {
            wordDict = Files.readAllLines(new File(filePath).toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Used to compare a given key to the text file loaded into memory.
     * @param key The inputted set of characters compared to the given dictionary.
     * @param dict The list of words that will be used to compare to the key.
     * @return The list of matches made when comparing the key with the given dictionary.
     */
    private static List<String> findMatches(String key, List<String> dict){
        List<String> matchList = new ArrayList<>();
        for(String word : dict){
            String temp = word; // Stores word so that it can be manipulated.
            for(char character : key.toCharArray()) {
                temp = temp.replace(Character.toString(character), "");
            }
            if(temp.equals("")){
                matchList.add(word);
            }
        }
        return matchList;
    }
}


texts: Loop variables over vector to plot all combination graphs in R

texts:
I have a vector of different string elements. I would like to plot all possible combination of the strings in that vector.

Is there a more effective method? I'm also looking for advice about better ways of handling large string vectors.

vc = c("ER","Ff","ac","al","NV")
 for(i in vc ){
  for(j in vc){
    ggplot(rt_engine_data,aes_string(i,j))+geom_point(aes(colour = factor(ft_state)),alpha =1/2)+geom_smooth()+scale_size_area()+
      ggtitle(paste(i," vs ",j,sep = ""))+scale_colour_brewer(palette = "Set1")

  }
}


texts:
Below is the code I would like some help with.  I'm just trying to understand if there a better way to use getters and setters.  Can someone fill me in on the correct way to use them if there is a textfield, JRadioButton set that I am trying to get info from?

//This class sets gets all the information that the user has entered.
package edu.witc.TrainTicket.model;

import java.text.NumberFormat;

import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import edu.witc.TrainTicket.view.*;

public class Destination {

    //Constructor with no arguments
    public Destination() {
    }

    public Destination(JRadioButton chicago, JRadioButton newYork, JRadioButton seattle, JRadioButton sanFransisco, JTextField name, JTextField phone) {

        String selectedDestination = getRadioButtonValue(chicago, newYork, seattle, sanFransisco);
        String custName = getCustName(name);
        String custPhone = getPhoneNum(phone);

        }

    public String getCustName(JTextField name){
        return name.getText();
    }

    public String getPhoneNum(JTextField phone){
        return phone.getText();
    }

    //get the type of paint
    public String getRadioButtonValue(JRadioButton chicago, JRadioButton newYork, JRadioButton seattle, JRadioButton sanFransisco) {

        String selected = "";

        if(chicago.isSelected())
            selected = "Chicago";
        if(newYork.isSelected())
            selected = "New York";
        if(seattle.isSelected())
            selected=  "Seattle";
        if(sanFransisco.isSelected())
            selected=  "San Fransisco";

        //JOptionPane.showMessageDialog(null, selected);

        return selected;
    }
}


texts: A regular expression parsing library in C

texts:
I've created a regular expression (regex) parsing library in C, and would like some feedback on it.  Speed is really important to me, but any and all suggestions are acceptable.

#include <ctype.h>

static int regex_matchHere(const char *regex, char *s, int *len);
static int regex_matchGroup(int c, int group);
static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len);

int regex_match(const char *regex, char *s, int *len)
{
    char *p = s;

    /* force match from the beginning of the string */
    if (regex[0] == '^') return (regex_matchHere(regex + 1, s, len) ? 0 : -1);

    /* iterate the string to find matching position */
    do
    {
        *len = 0;
        if (regex_matchHere(regex, p, len)) return (int)(p - s);
    } while (*p++ != '\0');
    return -1;
}

static int regex_matchHere(const char *regex, char *s, int *len)
{
    int c = regex[0];

    if (regex[0] == '\0') return 1; /* end of regex = full match */
    else if (regex[0] == '$' && regex[1] == '\0') return (*s == '\0'); /* check end of string */
    else if (regex[0] == '\\' && regex[1] != '\0') /* check escaped symbol */
    {
        c = regex[1];
        if (c != '^' && c != '$' && c != '\\' && c != '+' && c != '*' && c != '-' && c != '?') c = c | 0x100;
        regex = regex + 1;
    }
    /* check for special operators *,+,?,- */
    if (regex[1] == '*' || regex[1] == '+' || regex[1] == '-' || regex[1] == '?') return regex_matchQuantity(regex[1], c, regex+2, s, len);
    else if (*s != '\0' && regex_matchGroup(*s, c))
    {
        *len = *len + 1;
        return regex_matchHere(regex+1, s+1, len);
    }
    return 0;
}

static int regex_matchGroup(int c, int group)
{
    if ((group & 0xff) == '.') group ^= 0x100;
    if (group < 0x100) return c == group; /* a single char */
    /* a meta char, like \d, ... */
    switch (group & 0xff)
    {
        case 'd': return isdigit(c);
        case 's': return isspace(c);
        case 'D': return !isdigit(c);
        case 'S': return !isspace(c);
        case '.': return 1;
    }
    return 0;
}

static int regex_matchQuantity(int quant, int c, const char *regex, char *s, int *len)
{
    if (quant == '?')
    {
        if (regex_matchGroup(*s, c))
        {
            *len = *len + 1;
            s = s + 1;
        }
        return regex_matchHere(regex, s, len);
    }

    if (quant == '+' || quant == '*') /* match as much as possible */
    {
        char *p;
        for (p = s; *p != '\0' && regex_matchGroup(*p, c); p++) *len = *len + 1;
        if (quant == '+' && p == s) return 0;
        do
        {
            if (regex_matchHere(regex, p, len)) return 1;
            *len = *len - 1;
        } while (p-- > s);
    }
    else if (quant == '-') /* match as little as possible */
    {
        do
        {
            if (regex_matchHere(regex, s, len)) return 1;
            *len = *len + 1;
        } while (*s != '\0' && regex_matchGroup(*s++, c));
    }
    return 0;
}


texts:
Most concerned with improving efficiency and eliminating redundancy than anything else. a lot of Dominos rules have not been implemented yet.
Any form of feedback is appreciated.
from itertools import combinations_with_replacement
from random import sample, choice

def get_starting_board():
    domino = list(map(lambda x: list(x), combinations_with_replacement(range(7), 2)))
    while True:
        player_pieces = sample(domino, 7)
        computer_pieces = sample(list(filter(lambda x: x not in player_pieces, domino)), 7)
        stock_pieces = list(filter(lambda x: x not in (player_pieces + computer_pieces), domino))
        player_doubles = [piece for piece in player_pieces if len(set(piece)) == 1]
        computer_doubles = [piece for piece in computer_pieces if len(set(piece)) == 1]
        doubles = player_doubles + computer_doubles
        if doubles:
            highest_double = max(doubles)
            if highest_double in player_doubles:
                player_pieces.remove(highest_double)
                first_player = 'computer'
            else:
                computer_pieces.remove(highest_double)
                first_player = 'player'
            return {'player': player_pieces, 'computer': computer_pieces,
                    'stock': stock_pieces, 'snake': [highest_double],
                    'turn': first_player}

def get_board_status():
    if len(board['player']) == 0:
        return 'The game is over. You won!'
    elif len(board['computer']) == 0:
        return 'The game is over. The computer won!'
    flat_snake = [num for piece in board['snake'] for num in piece]  # Flatten the 2-dimensional list into one list
    for i in range(7):
        if i in board['snake'][0] and i in board['snake'][-1] and flat_snake.count(i) == 8:
            return "The game is over. It's a draw!"
    return 'game_not_done'

def display_board():
    print('=' * 70)
    print('Stock size:', len(board['stock']))
    print('Computer pieces:', len(board['computer']))
    print()
    snake = board['snake']
    if len(snake) > 6:
        for i in range(3):
            print(snake[i], end='')
        print('...', end='')
        for i in range(-3, 0):
            print(snake[i], end='')
    else:
        for p in snake:
            print(p, end='')
    print()
    print('\nYour pieces:')
    for i, piece in enumerate(board['player']):
        print(f'{i+1}:{piece}')
    print()

def is_valid_move(move):
    try:
        move = int(move)
    except ValueError:
        return False

    return len(board['player']) >= abs(move)

def make_move(move, player):
    """
    player: can either be "player" or "computer"
    """
    if move == 0:
        stock_piece = choice(board['stock'])
        board['stock'].remove(stock_piece)
        board[player].append(stock_piece)
        return
    index = abs(move) - 1
    piece = board[player][index]
    board[player].remove(piece)
    if move > 0:
        board['snake'].append(piece)
    else:
        board['snake'].insert(0, piece)

board = get_starting_board()
while True:
    display_board()
    game_state = get_board_status()

    if game_state != 'game_not_done':
        print('Status:', game_state)
        break

    turn = board['turn']
    if turn == 'player':
        print("Status: It's your turn to make a move. Enter your command.")
        while True:
            move = input()
            if is_valid_move(move):
                break
            print('Invalid input. Please try again.')
        move = int(move)
        board['turn'] = 'computer'
    else:
        input('Status: Computer is about to make a move. Press Enter to continue...\n')
        move = choice(range(-len(board['computer']), len(board['computer'])))
        board['turn'] = 'player'

    make_move(move, turn)


texts: Deleting a section of a website using Ajax

texts:
I am currently writing a decent amount of ajax to help me delete a section of a website.

It's already becoming a pretty big piece of code, I wondered if it were possible to compact a section of my code.

$('.trg-finished').on('click', function() {
    if(confirm('Are you sure?')) {
        var that = $(this);
        var catid = that.data("id");

        $.ajax({
            type: "POST",
            url: "./close-cat.php",
            data: { catID: catid }
        })
        .done(function(data) {
            if(data == 1) {
                that
                .css("background-color", "#27AE60")
                .css("color", "#FFF")
                .html('Success');
            } else {
                that
                .css("background-color", "#C0392B")
                .css("color", "#FFF")
                .html('Failure');
            };

            window.setTimeout(function() {
                that
                .css("background-color", "")
                .css("color", "")
                .html('Finished');
            }, 5000);
        })
        .fail(function(data) {
            that
            .css("background-color", "#C0392B")
            .css("color", "#FFF")
            .html('Failure');

            window.setTimeout(function() {
                that
                .css("background-color", "")
                .css("color", "")
                .html('Finished');
            }, 5000);
        });
    };
});

Is it possible to compact this code, or is this as small as it can get?


texts:
You are given a list of \$N\$ people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.

Note Suppose \$a\$, \$b\$, and \$c\$ are three different people, then \$(a,b)\$ and \$(b,c)\$ are counted as two different teams.

Input Format

The first line contains two integers, \$N\$ and \$M\$, separated by a single space, where \$N\$ represents the number of people, and \$M\$ represents the number of topics. \$N\$ lines follow.
Each line contains a binary string of length \$M\$ If the \$i\$'th line's j'th character is 1, then the i'th person knows the \$j\$'th topic; otherwise, he doesn't know the topic.

Constraints

\$2 ≤ N ≤ 500\$
\$1 ≤ M ≤ 500\$

Output Format

On the first line, print the maximum number of topics a 2-person team can know.
On the second line, print the number of 2-person teams that can know the maximum number of topics.

Imports System

Module Solution
    Public Sub Main()
        Dim input As String() = Console.Readline().Split(" ")
        Dim people As Integer = CInt(input(0))
        Dim topics As Integer = CInt(input(1))

        Dim peopleKnowledge(people-1)() As Char
        Dim maxScore As Integer = 0
        Dim teamsWithMaxScore As Integer = 0
        Dim score As Integer = 0

        For i As Integer = 0 To people-1
            peopleKnowledge(i) = Console.ReadLine().ToCharArray()
        Next i

        For i As Integer = 0 to people-2
            For j As Integer = i+1 To people-1
                score = GetTeamScore(peopleKnowledge(i),peopleKnowledge(j),topics)

                If score > maxScore Then
                    maxScore = score
                    teamsWithMaxScore = 1
                ElseIf score = maxScore Then
                    teamsWithMaxScore += 1
                End If
            Next j
        Next i

        Console.WriteLine(maxScore)
        Console.WriteLine(teamsWithMaxScore)
    End Sub

    Private Function GetTeamScore(m1 As Char(),m2 As Char(), topics As Integer) As Integer
        Dim score As Integer = 0

        For i as Integer = 0 to topics-1
            If m1(i).Equals("1"c) Or m2(i).Equals("1"c) Then
                score += 1
            End If
        Next i

        Return score
    End Function
End Module

Trying to become acquainted with VB.NET so I welcome any and all suggestions. This solution executes in 0.61s with \$N = M = 500\$; would love to know about any performance gains.


texts: Implementing an inner product using pyspark

texts:
I'm trying to implement a dot product using pyspark in order to learn pyspark's syntax.

I've currently implemented the dot product like so:

import operator as op
from functools import reduce

def inner(rdd, rdd2):
    return (rdd.zip(rdd2)
        .map(lambda x: reduce(op.mul, x))
        .reduce(lambda x,y: x + y)
    )

My solution feels inelegant (particularly my lambda function). I'd like to know if there would be a more 'pysparkian' way of writing this.

Furthermore, are there performance considerations that I should be thinking about with regards to this problem (i.e. does my dot product solution not scale well)?


texts: Converting string of hex values to numpy array of specific shape

texts:
I am working on a project that needs to take a .bdf font file and turn it into a Numpy array. I am using the code below to turn the bitmap for the font into a numpy array. It currently works, I just feel that it's nearly impossible to read but I'm not sure if there's a better way to do it.

How the current code works:

It splits the string by line since each line of the string is a row.
It selects the first two values from the row since the last two never seem to matter.
Using int() I convert the string of hex to an integer.
Using bin() I turn the integer to binary.
Then I use zfill() because leading zeros in the binary are important. This returns a string of 1's and 0's
Then I use list() to break the string of binary into a list of single 1's and 0's
Then I convert that all to a numpy array with dtype=int

The process feels really messy and it takes a millisecond which I feel like is pretty long for a (15, 9) numpy array. Any ideas for improvements would be greatly appreciated.

def hexToNumpy(hexValues, columns):

    return np.array(
        [
            list(bin(int(row[0:2], 16))[2:].zfill(columns))
            for row in hexValues.split("\n")
        ],
        dtype=int,
    )

T = """0000
0000
7F00
0800
0800
0800
0800
0800
0800
0800
0800
0800
0000
0000
0000"""

hexToNumpy(T, 9)


texts: A more Pythonic way to iterate over a list with duplicate items

texts:
Is there a more elegant and Pythonic way to handle counters in this solution to an exercise from the NLTK book? The exercise asks to print out the context (one word forward and one word back) for every verb of a particular type (tagged VN).

import nltk

wsj = nltk.corpus.treebank.tagged_words(simplify_tags=True)
cdf = nltk.ConditionalFreqDist((tag, word) for (word, tag) in wsj)

wordlist = cdf['VN'].keys()

# Bug 1: strange exceptions in the for loop when iterating over wsj
# Solution: wsj is a custom NLTK type "ConcatenatedCorpusView"
# cast wsj into a native python type "list" for better iteration.
# I am guessing ConcatenatedCorpusView chokes on empty tuples
wsj_list = list(wsj)

# Bug 2: repeated words return index of the first word only
# Solution: to deal with repeated words
# we keep indexing from the last location. The index method
# takes a second parameter
starts_at = 0

for t in wsj_list:
    if t[0] in wordlist and t[1] == 'VN':
        ndx = wsj_list.index(t,starts_at)
        starts_at = ndx + 1
        print wsj_list[ndx-1:ndx+1], ndx


texts:
For practicing Python I wrote a script which scans the harddrive for large files and lists them in a report. The script takes the root path and then all the subfolders are scanned aswell. Also the minimum size for the files needs to be defined. Smaller files are not listed.

The code:

find_big_files.py

"""
Find big files on the harddrive and writes a report were the big files
are located
Supply root folder and desired size to find the files.
"""

import os

def size_with_biggest_unit(size: int) -> str:
    """
    Turns size in Bytes into KB, MB, GB or TB
    """
    unit: str = ""

    if size > (1024 ** 4):
        unit = "TB"
        size = int(round(size / 1024 ** 4))
    elif size > (1024 ** 3):
        unit = "GB"
        size = int(round(size / 1024 ** 3))
    elif size > (1024 ** 2):
        unit = "MB"
        size = int(round(size / 1024 ** 2))
    elif size > 1024 ** 1:
        unit = "KB"
        size = int(round(size / 1024))

    return str(size) + unit

def size_in_bytes(size: str) -> int:
    """
    Turns size in KB, MB, GB or TB into Byte
    """
    ret_size: int = 0
    if size.endswith("TB"):
        ret_size = int(size.strip("TB")) * (1024 ** 4)
    elif size.endswith("GB"):
        ret_size = int(size.strip("GB")) * (1024 ** 3)
    elif size.endswith("MB"):
        ret_size = int(size.strip("MB")) * (1024 ** 2)
    elif size.endswith("KB"):
        ret_size = int(size.strip("KB")) * 1024
    elif size.isdigit():
        ret_size = int(size)
    else:
        raise Exception(("Input size should be digit + TB/GB/MB/KB or digit."
                         "Size was: ") + size)
    return ret_size

def sort_by_size(big_files: list) -> list:
    """
    Sort dictionary with folder_name, filename and size by
    filesize in decreasind order
    """
    return sorted(big_files, key=lambda k: k['file_size'], reverse=True)

def write_report_of_big_files(big_files: list):
    """
    Write report in same folder as the script is excecuted.
    Report contains formated output of found big files
    """
    with open('big_files_report.txt', 'w') as file:
        for big_file  in big_files:
            file.write(size_with_biggest_unit(big_file['file_size'])
                       + '\t'
                       + big_file['filename']
                       + '\t'
                       + big_file['folder_name']
                       + '\n')

def find_big_files(root_folder: str, input_size: str):
    """
    Checks from all files in root and sub folder if they are exceeding
    a certain size
    """
    size = size_in_bytes(input_size)
    big_files: list = []

    for folder_name, subfolders, filenames in os.walk(root_folder):
        for filename in filenames:
            file_size = os.path.getsize(folder_name + '\\' + filename)

            if file_size > size:
                big_file: dict = {'folder_name': folder_name,
                                  'filename': filename,
                                  'file_size': file_size}
                big_files.append(big_file)

    sorted_big_files = sort_by_size(big_files)
    write_report_of_big_files(sorted_big_files)

find_big_files("E:\\", "100MB")

I checked the code with PyLint and MyPy.

PyLint still gives one warning in line 86 (in find_big_files ):

  Unused variable 'subfolders' [W:unused-variable]

It is true I dont use the variable subfolders but I need to supply three variables in the for loop to use folder_name and filename which i get from os.walk(root_folder) or not?

Also I wonder if I used Type Annotations correctly. I used them here the first time and already found some bugs with MyPy (which are already fixed in the posted code).

Other than that:

Are there any other smells?

Is the code easy to follow?

Can anything be done easier?

Feel free to comment on anything suspicious you can find.


texts: Shuffle a sorted array so that left portions contains even indices and right portion contains odd indices numbers

texts:
I have been solving the following problem:

Input array: \$[7,4,2,5,1,9,6]\$

Output array: \$[1,4,6,9,7,5,2]\$

I tried to do it in the following way:

Sort the array. So, Input array becomes \$[1,2,4,5,6,7,9]\$ run time \$O(n \log n)\$
Numbers in even indices are \$[1,4,6,9]\$ an in odd indices are \$[2,5,7]\$. Move all the even indices into left part of the array. So it becomes \$[1,4,6,9,2,7,5]\$. Runtime \$O(n)\$.
Now, sort the \$[2,7,5]\$ i.e. the numbers from odd indices in descending order. So, the final array becomes \$[1,4,6,9,7,5,2]\$ Runtime : \$O(n \log n)\$

Can you please review it?

#include <iostream>
#include <algorithm>

void shuffleEvenOdd(std::vector<int>& nums)
{
    std::sort(nums.begin(),nums.end());

    int p1=0;
    int p2=0;

    while(p2 < nums.size())
    {
        if(p2 % 2 == 0)
        {
            int tmp = nums.at(p1);
            nums[p1] = nums[p2];
            nums[p2] = tmp;

            p1++;
            p2++;
        }
        else
        {
            p2++;
        }
    }

    std::sort(nums.begin()+p1, nums.end(),std::greater<int>());
}

void test( std::vector<int>& input, const std::vector<int>& expected, const std::string & testName)
{
    shuffleEvenOdd(input);
    std::cout<<"\n\n";

    std::cout<<"\n\n"<<"Test case : "<<testName;

    if(input == expected)
          std::cout<<" correct ";
    else
        std::cout<<"  failed. ";

}

void test1()
{
    std::vector<int>tmp= {2,2,2};
    const std::vector<int>expected= {2,2,2};
    const std::string tstName = " Test 1 ";

    test(tmp,expected, tstName);
}

void test2()
{
    std::vector<int>tmp= {2};
    const std::vector<int>expected= {2};
    const std::string tstName = " Test 2 ";

    test(tmp,expected, tstName);
}

void test3()
{
    std::vector<int>tmp= {3,3};
    const std::vector<int>expected= {3,3};
    const std::string tstName = " Test 3 ";

    test(tmp,expected, tstName);
}

void test4()
{
    std::vector<int>tmp= {1,-8,2,0,5};
    const std::vector<int>expected= {-8,1,5,2,0};
    const std::string tstName = " Test 4 ";

    test(tmp,expected, tstName);
}

void test5()
{
    std::vector<int>tmp= {-9,1,-8,2,0,5};
    const std::vector<int>expected= {-9,0,2,5,1,-8};
    const std::string tstName = " Test 5 ";

    test(tmp,expected, tstName);
}

int main()
{
    test1();
    test2();
    test3();
    test4();
    test5();

    return 0;
}


texts:
I am using a singleton in my DAO. Would I be better off with static methods? Also, should I be worried about synchronization of the singleton and my data structures?

public class RAMUserDAO implements GenericDAO<User, String, Boolean>
    {
        private static RAMUserDAO   userDAO = null;
        private Map<String, User>   userList;
        private Map<String, User>   banList;
        private static Logger       log     = LOG.PRODUCTION;

        private RAMUserDAO()
            {
                userList = new ConcurrentHashMap<String, User>();
                banList = new ConcurrentHashMap<String, User>();
            }

        public static RAMUserDAO getRAMUserDAO()
            {
                if (userDAO == null)
                    {
                        synchronized (RAMUserDAO.class)
                            {
                                if (userDAO == null)
                                    {
                                        userDAO = new RAMUserDAO();
                                    }
                            }
                    }
                return userDAO;
            }
    }


texts:
For my students (I am an Austrian math teacher) I would like to provide some simple online calculators on my blog.
Let's say there are two pages on my website("Circle" and "Cube") and on every page I want to have about 10 different calculators.
Here is an example of one page with two calculators:

My code
JSFiddle
HTML

Circle

Calculate circumference of circle

 Radius of circle: <input type="text" id="calc1-input"> <button onclick="calc1()">Calculate</button>

Circumference of circle:

Calculate area of circle

 Radius of circle: <input type="text" id="calc2-input"> <button onclick="calc2()">Calculate</button>

Area of circle:

Javascript
function commaToDot(number) {
    return parseFloat(number.replace(',','.').replace(' ',''));
}

function dotToComma(number){
    return number.toString().replace('.',',');
}

function calc1() {
    var input = document.getElementById("calc1-input").value;
    input = commaToDot(input);
    if (isNaN(input)) {
        document.getElementById('calc1-output').innerHTML = "Please enter a number!";
    } else {
      var output = 2 * Math.PI * input;
        document.getElementById('calc1-output').innerHTML = dotToComma(output);
    }
}

function calc2() {
    var input = document.getElementById("calc2-input").value;
    input = commaToDot(input);
    if (isNaN(input)) {
        document.getElementById('calc2-output').innerHTML = "Please enter a number!";
    } else {
      var output = Math.PI * Math.pow(input,2);
        document.getElementById('calc2-output').innerHTML = dotToComma(output);
    }
}

Explanation

Input: In my country we use commas as decimal separators.
So the students write 55,5 instead of 55.5 (see commaToDot()).
Output: The students expect the output to be with comma decimal separator, too (see dotToComma()).
Error: If the input is not a number (if (isNaN(input))) an error message will be displayed instead of the calculation result.

Questions

I see a lot of redundance in my code but I don't know how to improve it.
The only difference between calc1() and calc2() is the formula.
Maybe it is possible to improve the naming of the variables/functions?


texts: Reading a text file, need help cleaning exception handling

texts:
Which of the following is cleaner / more adopted standard of handling exceptions while coding a stream ? I would also appreciate a reason why one of the following trumps over other ?  In my opinion I find option 1 better but nested try where first try does nothing more than a wrapper is making me not satisfied with approach.

NavigableSet<String> dictionary = new TreeSet<String>();
BufferedReader br = null;
try {
    try {
        br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            dictionary.add(line.split(":")[0]);
        }

    } finally {
        br.close();
    }
} catch (Exception e) {
    throw new RuntimeException("Error while reading dictionary");
}

VS

NavigableSet<String> dictionary = new TreeSet<String>();
BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            dictionary.add(line.split(":")[0]);
        }

    }
} catch (Exception e) {
    throw new RuntimeException("Error while reading dictionary");
} finally {
     try{
        if(br != null) br.close();
        } catch (Exception ex){

        }
 }


texts:
I updated my code based on the feedback from my previous question. There is one for the home page and one for the product pages:

Home page code:

NAME OF TRAVEL AGENCY
<link itemprop="url" href="HOME PAGE URL">
SHORT DESCRIPTION OF THE TRAVEL AGENCY

Product page code:

    <link itemprop="author" href="http://schema.org/TravelAgency" />
    <link itemprop="url" href="HOME PAGE URL">

    <link itemprop="specialty" href="http://schema.org/PlasticSurgery" />
    <meta itemprop="aspect" content="treatment"/>

    TITLE OF PAGE
    SHORT DESCRIPTION OF PAGE CONTENT

    The cost of
    NAME OF TREATMENT
    ALTERNATE NAME OF TREATMENT is €600.00


texts: Is this use of JavaScript prototype functions for attaching event listeners going to meet design goals?

texts:
Please provide a sanity check on my below JavaScript pattern to be used for a custom edit control. The goals are:

Centralized code
Avoid name collisions
Minimize memory use (putting functions on the prototype chain to accomplish?)
Ease of use for other developers

My specific question is, are there any "gotchas" in below pattern that I may have overlooked or anything that I'm doing that is just plain wrong?

var CustomEditor = function (id) {
    'use strict';
    var evnt = null,
        funct = null;
    this.id = id;
    this.init();
};

CustomEditor.prototype.onCustomBlur = function () {
    'use strict';
    // alert("blur event handler");
    this.style.backgroundColor = "#fff";
    this.style.color = "#f00";
};

CustomEditor.prototype.onCustomKeyPress = function () {
    'use strict';
    // alert("keypress event handler");
    this.style.backgroundColor = "#000";
    this.style.color = "#ff0";
};

CustomEditor.prototype.onCustomFocus = function () {
    'use strict';
    // alert("focus event handler");
    this.style.backgroundColor = "#000";
    this.style.color = "#0ff";
};

CustomEditor.prototype.addEvent = function () {
    'use strict';
    var element = document.getElementById(this.id);
    // old IE work around
    if (element.attachEvent) {
        return element.attachEvent('on' + this.evnt, this.funct);
    }
    return element.addEventListener(this.evnt, this.funct, false);
};

CustomEditor.prototype.init = function () {
    'use strict';
    // initialize a custom editor
    this.evnt = 'blur';
    this.funct = this.onCustomBlur;
    this.addEvent();

    this.evnt = 'keypress';
    this.funct = this.onCustomKeyPress;
    this.addEvent();

    this.evnt = 'focus';
    this.funct = this.onCustomFocus;
    this.addEvent();
};

This code will be JavaScript code in the HTML page to allocate and initialize:

new CustomEditor('myInput1');
new CustomEditor('myInput2');
new CustomEditor('myInput3');

See this JSFiddle to try this pattern or fork as needed to correct.


texts:
I am trying to implement topological sort using STL. I have used vector of lists to store adjacency list. Indegree is an array which stores indegree of vertices.

Indegree0 is a queue implemented using STL list to store vertices with indegree 0. Can someone please help me improve my code?

# include <iostream>
# include <bits/stdc++.h>
using namespace std;

vector<int> topologicalsort(vector<list<int> > adjacencylist,int  indegree[],int v,int e)
{

    vector<int>ans(v+1);
    int k=1;
    //list to store vertices with indegree 0
    list<int>indegree0;
    for(int i=1;i<=v;i++)
    {
        if(indegree[i]==0)
            indegree0.push_back(i);
    }
    while(!indegree0.empty())
    {
        int x=indegree0.front();
        indegree0.pop_front();
        ans[k]=x;
        k++;
        list<int>::iterator itr=adjacencylist[x].begin();
        while(itr!=adjacencylist[x].end())
        {
            indegree[*itr]--;
            if(indegree[*itr]==0)
                indegree0.push_back(*itr);
            itr++;
        }
    }
    return ans;
}

int main()
{
    int v,e;
    cin>>v>>e;
    vector<list<int> > adjacencylist(v+1);
    int indegree[v+1];
    for(int i=1;i<=v;i++)
        indegree[i]=0;
    for(int i=1;i<=e;i++)
    {
        int v1,v2;
        cin>>v1>>v2;
        adjacencylist[v1].push_back(v2);
        indegree[v2]++;
    }
    //cout<<adjacencylist.size()<<endl;
    for(int i=1;i<=v;i++)
    {
        printf("adjacencylist[%d] :",i);
        list<int>::iterator itr=adjacencylist[i].begin();
        while(itr!=adjacencylist[i].end())
        {
            cout<<*itr<<"  ";
            itr++;
        }
        cout<<endl;
    }
    vector<int> ans=topologicalsort(adjacencylist,indegree,v,e);
    for(int i=1;i<=v;i++)
        cout<<ans[i]<<"  ";

}


texts: High performance wrapper for CSPRNG arc4random(3)

texts:
This function is a wrapper for arc4random(3), a cryptographic pseudo-random number generator on macOS and BSDs, but you can also get it by installing libbsd-devel on most Linux distros.

It serves the same purpose as arc4random_uniform(3), the official wrapper for arc4random(3), i.e. to generate a nonnegative random integer less than range.

static inline unsigned random_uniform(unsigned range) {
    static uint32_t random_32b;
    static uint32_t full_32b;

    if (full_32b < range) {
        random_32b = arc4random();
        full_32b = UINT32_MAX;
    }

    unsigned result = random_32b % range;
    random_32b /= range;
    full_32b /= range;

    return result;
}

You can find the implementation of arc4random_uniform(3) on macOS at the bottom of this page. Basically, it makes use of the rejection method to produce uniform deviates and eliminate the modulo bias. On the other hand, my implementation tries to eliminate the modulo bias by keeping track of the maximum possible range of the remaining random bytes in full_32b. What's more, it saves the unused random bytes in a static variable for future use, as a call to arc4random(3) can be costly. It appears to be faster according to my benchmark, but I'm not sure if it's correct.


texts: Reverse digits and add until a palindrome appears

texts:
The following code is a C solution to the following problem UVA 10018.

  The Problem

  The "reverse and add" method is simple: choose a number, reverse its
  digits and add it to the original. If the sum is not a palindrome
  (which means, it is not the same number from left to right and right
  to left), repeat this procedure.

  For example:

  195 Initial number
591

786
687

1473
3741

5214
4125

9339 Resulting palindrome

  In this particular case the palindrome 9339 appeared after the 4th
  addition. This method leads to palindromes in a few step for almost
  all of the integers. But there are interesting exceptions. 196 is the
  first number for which no palindrome has been found. It is not proven
  though, that there is no such a palindrome.

  Task

  You must write a program that give the resulting palindrome and the
  number of iterations (additions) to compute the palindrome.

  You might assume that all tests data on this problem:

  will have an answer
  will be computable with less than 1000 iterations (additions)
  will yield a palindrome that is not greater than 4,294,967,295.

  The Input

  The first line will have a number N with the number of test cases, the
  next N lines will have a number P to compute its palindrome.

  The Output

  For each of the N tests you will have to write a line with the
  following data : minimum number of iterations (additions) to get to
  the palindrome and the resulting palindrome itself separated by one
  space.

  Sample Input

3
195
265
750

  Sample Output

4 9339
5 45254
3 6666

My solution is as follows:

#include <stdio.h>

/* only works for unsigned longs */
unsigned long reverse(unsigned long original)
{
  unsigned long number = original;
  unsigned long reversed = 0;
  unsigned long place = 1;
  unsigned long i, q;

  for(i = 1000000000; i > 0; i = i / 10) {

    q = number / i;

    if ((q > 0) || (reversed > 0)) {
      reversed = reversed + (q * place);
      number = number - (q * i);
      place = place * 10;
    }
  }

  return(reversed);
}

int is_palindrome(unsigned long original)
{
  unsigned long reversed;
  reversed = reverse(original);
  return(reversed == original);
}

unsigned long reverse_add(unsigned long original, int *iterations)
{
  if (is_palindrome(original)) {
    return(original);
  }

  if (*iterations >= 1000) {
    return(0);
  }

  *iterations = *iterations + 1;
  reverse_add(original + reverse(original), iterations);
}

int main()
{
  int n = 0;
  unsigned long start;
  unsigned long end;
  int iterations = 0;

  while (scanf("%ld\n", &start) == 1) {
    if (n == 0) {
      n = start;
    }
    else {
      iterations = 0;
      end = reverse_add(start, &iterations);
      printf("%d %ld\n", iterations, end);
    }
  }

  return(0);
}


texts: Converting tensorflow v1 to v2 without compatability.v1

texts:
I am in the process of converting this code predictor.py located here to tensorflow v2 with Python 3.7.  I want to do this conversion part by part. So from the refence repo, I've been going through this example.

For this block:

def resBlock(x, num_outputs, kernel_size = 4, stride=1, activation_fn=tf.nn.relu, normalizer_fn=tcl.batch_norm, scope=None):
    assert num_outputs%2==0 #num_outputs must be divided by channel_factor(2 here)
    with tf.variable_scope(scope, 'resBlock'):
        shortcut = x
        if stride != 1 or x.get_shape()[3] != num_outputs:
            shortcut = tcl.conv2d(shortcut, num_outputs, kernel_size=1, stride=stride,
                        activation_fn=None, normalizer_fn=None, scope='shortcut')
        x = tcl.conv2d(x, num_outputs/2, kernel_size=1, stride=1, padding='SAME')
        x = tcl.conv2d(x, num_outputs/2, kernel_size=kernel_size, stride=stride, padding='SAME')
        x = tcl.conv2d(x, num_outputs, kernel_size=1, stride=1, activation_fn=None, padding='SAME', normalizer_fn=None)

        x += shortcut
        x = normalizer_fn(x)
        x = activation_fn(x)
    return x

Here is what I have

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Activation, BatchNormalization
from tensorflow.keras.layers import Conv2D, Conv2DTranspose
from tensorflow.keras.models import Sequential
from tensorflow.keras.regularizers import l2

def create_sub_model(
                   filters=16,
                   kernel_size=4,
                   stride=(1,1),
                   stage=0,
                   block='1a',
                   activation='relu',
                   normalizer=BatchNormalization()):

  assert (filters % 2 == 0), __file__ + ":filters is not an integer"
  name_base = 'conv' + str(stage) + block + '_branch'
  model = Sequential()
  #initial layer
  model.add(Conv2D(filters / 2, kernel_size=1, stride=(1, 1), padding='same',
                   name=conv_name_base + '2a'))
  model.add(BatchNormalization(name=bn_name_base + '2a'))
  model.add(Activation(activation))
  #add layer
  model.add(Conv2D(filters / 2, kernel_size=kernel_size, stride=stride, padding='same',
                   name=conv_name_base + '2b'))
  model.add(BatchNormalization(name=bn_name_base + '2b'))
  model.add(Activation(activation))
  # add layer
  model.add(Conv2D(filters, kernel_size=1, stride=(1,1), padding='same',
                   name=conv_name_base + '2c',activation=None, normalizer=None))
  model.add(BatchNormalization(name=bn_name_base + '2c'))
  model.add(Activation(activation))
  # add layer
  model.add(Conv2D(filters, kernel_size=1, stride=stride, padding='same',
                   name=conv_name_base + '2d', activation=None, normalizer=None))
  model.add(BatchNormalization(normalizername=bn_name_base + '2d'))
  model.add(Activation(activation))
  return model

I want to avoid defining the input tensor until later.  Is this going down the right way?


texts: Is there a better way to traverse an inheritance tree?

texts:
I have a method that ascends an inheritance tree and returns the element at the root, progressively yielding the elements if appropriate:

# Finds the root of the hierarchy.
def root
  element = self
  until element.root?
    yield element if block_given?
    element = element.parent
  end
  yield element if block_given?
  element
end

# Walks the inheritance tree, yielding each element from self to #root.
alias until_root root

If I have a hierarchy like:

1 > 2 > 3

3.root should return 1 and 3.until_root &block should yield 3, then 2, then 1, and finally return 1.

The line which yields elements appears twice in order to yield the actual root element, something I would've liked to accomplish inside the loop.

How can I improve this algorithm?