texts: Most elegant approach to writing list renumbering function

texts:
I'm writing a function with the following signature:

(Ord a) => [a] -> [Int]

It's semantics is to find an order-preserving mapping from list of objects to list of Ints.

The version of mine:

import Data.List
import Data.Map (Map, (!))
import qualified Data.Map as Map

renumber :: (Ord a) => [a] -> [Int]
renumber list = let mapping = buildmapping list Map.empty in
                map (mapping!) list
        where
            -- buildmapping :: (Ord a) => [a] -> Map a Int -> Map a Int
            buildmapping list mapping = let
                mapped = Map.keys mapping
                (rest, nextindex) = if (null mapped) then
                      (list, 1) else
                      (filter (> maximum mapped) list,
                        (1+) $ maximum $ Map.elems mapping)
                in case rest of
                  [] -> mapping -- nothing left, return
                  _  -> buildmapping rest $ Map.insert (minimum rest) nextindex mapping


texts: Crawling for emails on websites given by Google API

texts:
I'm trying to build an app which crawls a website to find the emails that it has and prints them.  I also want to allow the user to type "false" into the console when they want to skip the website (maybe the user has already found 2 emails and doesn't need any more).

Is the way I'm approaching this the best way? If not, then how can I improve, and what am I missing?

require "nokogiri"
require "json"
require 'mechanize'
require 'anemone'
require "typhoeus"
require "timeout"

class String

    def to_bool()
        return true if self == "true"
        return false if self == "false"
        return nil
    end
end

class Query
            def initialize(keyword)
            10.times do |n|
                    num = (n * 10 + 1).to_s
                    p num
                    req = Typhoeus::Request.new("https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q=" + keyword + "&start=" + num, followlocation: true)
                    res = req.run
                    File.open("file.json","w") do |file|

                    file.write(res.body)
                    end
                    continue = "true"
                    fs = File.read("file.json");
                    string = JSON.parse(fs);

                  string["items"].each do |item|
                      p continue.to_s + "<- item"

  begin
    Anemone.crawl("http://" + item["displayLink"] + "/") do |anemone|
      anemone.on_every_page do |page|
        if continue.chomp.to_bool == false
          raise "no more please"
        end
        request = Typhoeus::Request.new(page.url, followlocation: true)
        response = request.run
        email = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/.match(response.body)
        if email.nil?
        else
          p email
          begin
            continue = Timeout::timeout(2) do
              p "insert now false/nothing"
              gets
            end
          rescue Timeout::Error
            continue = "true"
          end
        end
      end
    end
    rescue Exception => e
      p e
      continue = "true"
      next
    end
    p "---------------------------------------------------------"
end

                    p "new request"

                end

            end
    end

qs = Query.new("texas+web+development")


texts:
I've created a program to calculate Pascal's triangle:

#include <stdio.h>
#include <stdlib.h>
void pascal(int limit)
{
    int *begin;
    begin=(int*)malloc(2*sizeof(int));
    *begin=1;
    *(begin+1)=1;
    int* p,q,s,t;
    int row=2,n=3,x;
    p=begin;
    q=begin+1;
    for(n=3;n<=limit+1;n++)
    {
        if(n==4)
        {
            free(begin);
        }
        x=1;
        printf("Row (%d) : ",row);
        for(int* i=p;i&lt;=q;i=i+1)
        {
            printf("%d ",*i);
        }
        putchar('\n');
        s=(int*)malloc(n*sizeof(int));
        t=s+n-1;
        *s=*p;
        *t=*q;
        for(int* g=p;g&lt;q;g=g+1)
        {
            *(s+x)=*g+*(g+1);
            x++;
        }
        p=s;
        q=t;
        row++;
    }
}

int main(void)
{
    int i;
    printf("Till which row would you like to calculate the Pascal Triangle?\n\n");
    printf("Type your answer:\t");
    scanf("%d",&i);
    putchar('\n');
    if(i<n)
        printf("Nope, you can't do that\n");
    else
    {
        printf("Row (1) : 1\n");
        pascal(i);
    }
}

My idea was to work with 2 arrays at the same time, but there is still a problem in my algorithm. How am I supposed to free the memory I allocated before? The first 8 bytes of begin are easy to free, but what should I do so I can free the memory I allocated through the pointers?


texts:
My session controller has a method for creating new user session. According to Rubocop's output there is 'Assignment Branch Condition' metric is too high [15.17/15].

    def create
      agent = Agent.find_by(login: params[:session][:login])
      if agent && agent.authenticate(params[:session][:password])
        log_in agent
        redirect_to dashboard_url
      else
        flash.now[:danger] = 'Invalid login or password'
        render 'new'
      end
    end

log_in method:

    def log_in(agent)
      session[:agent_id] = agent.id
    end

I've extracted method for processing unsuccessful logins to reduce ABC size:

  def create
    agent = Agent.find_by(login: params[:session][:login])
    if agent && agent.authenticate(params[:session][:password])
      log_in agent
      redirect_to dashboard_url
    else
      unsuccessful_login 'Invalid login or password'
    end
  end

  private
    def unsuccessful_login(message)
      flash.now[:danger] = message
      render 'new'
    end

Is it appropriate to make new method I'm going to use only once in this case?
Is there any guideline when it's suitable to extract method?


texts: Riemann Sum Class (with variable endpoint behavior)

texts:
Here is my class for calculating a Riemann Sum.  I did a cursory google search for a built-in function with these specifications but didn't find anything (I'm sure I just missed it or didn't look hard enough, but this is good practice).

Your input is welcome and appreciated.  I'd like to not have to assign a lambda function to a variable but it works for me.  I just worry that someone using this code may get confused.

from numpy import arange

class RiemannSum(object):

    def __init__(self, index, upper, rectangles, func, endpoints='mid'):
        """
        Constructor for base class for Riemann Sums.
        Will be subclassed for left, right, or mid-points for rectangles.

        :param index: Where to begin 'n' value. [n = index]
        :param upper: Upper bound of sum.  Max 'n' value.  [Number above sigma notation]
        :param rectangles: The number of rectangles to be used in the calculation.
        :param func: pass series function here; suggest assigning lambda function to variable and passing here
        :param endpoints: default to 'mid'. Valid values are 'mid', 'left', 'right' as strings
        """
        self.total = 0
        self.index = index
        self.upper = upper
        self.delta = (upper - index) / rectangles
        self.function = func

        if endpoints.lower() == 'left':  # left endpoints
            self.points = arange(self.index, self.upper, self.delta)
        elif endpoints.lower() == 'right':  # right endpoints
            self.points = arange(self.index + self.delta, self.upper + self.delta, self.delta)
        else:  # mid endpoints, usually most accurate
            diff = self.delta / 2
            self.points = [i for i in arange((self.index + diff),
                                         (self.upper + diff), self.delta)]

    def sum(self):
        outputs = [i for i in map(self.function, self.points)]
        self.total = sum(outputs)
        return self.delta * self.total

Here is an example of the code in use:

from math import sqrt
series = sqrt(x) - 2
num = RiemannSum(1,6,5,series,'mid').sum()
print(num)


texts:
I made this as a personal challenge. It seems to work fine as I can't find any bugs and am happy with how it runs, but I am interested in what I should do to make the code more professional.

I think the draw() function can be replaced with two for loops but I could never get it working. The code for the input by each of the players and the check_board() function seems messy and I think it could be reduced by using arguments. I also think the while loop could be reduced somehow.

def tic_tac_toe():
    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    end = False
    win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))

    def draw():
        print(board[0], board[1], board[2])
        print(board[3], board[4], board[5])
        print(board[6], board[7], board[8])
        print()

    def p1():
        n = choose_number()
        if board[n] == "X" or board[n] == "O":
            print("\nYou can't go there. Try again")
            p1()
        else:
            board[n] = "X"

    def p2():
        n = choose_number()
        if board[n] == "X" or board[n] == "O":
            print("\nYou can't go there. Try again")
            p2()
        else:
            board[n] = "O"

    def choose_number():
        while True:
            while True:
                a = input()
                try:
                    a  = int(a)
                    a -= 1
                    if a in range(0, 9):
                        return a
                    else:
                        print("\nThat's not on the board. Try again")
                        continue
                except ValueError:
                   print("\nThat's not a number. Try again")
                   continue

    def check_board():
        count = 0
        for a in win_commbinations:
            if board[a[0]] == board[a[1]] == board[a[2]] == "X":
                print("Player 1 Wins!\n")
                print("Congratulations!\n")
                return True

            if board[a[0]] == board[a[1]] == board[a[2]] == "O":
                print("Player 2 Wins!\n")
                print("Congratulations!\n")
                return True
        for a in range(9):
            if board[a] == "X" or board[a] == "O":
                count += 1
            if count == 9:
                print("The game ends in a Tie\n")
                return True

    while not end:
        draw()
        end = check_board()
        if end == True:
            break
        print("Player 1 choose where to place a cross")
        p1()
        print()
        draw()
        end = check_board()
        if end == True:
            break
        print("Player 2 choose where to place a nought")
        p2()
        print()

    if input("Play again (y/n)\n") == "y":
        print()
        tic_tac_toe()

tic_tac_toe()


texts:
This is the first real program I've written in Go so have at it! I wrote it because I use a tiling window manager that doesn't have any brightness control functionality (at least not that I know of).

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "strconv"
    "strings"
    "os"
)

func main() {

    const BRIGHTNESS_AMOUNT = 25

    maxBrightness := func() int {
        buff, err := ioutil.ReadFile("/sys/class/backlight/gmux_backlight/max_brightness")
        if err != nil {
            log.Fatal(err)
            return -1
        }
        buffInt, err := strconv.Atoi(strings.Replace(string(buff), "\n", "", -1))
        if err != nil {
            log.Fatal(err)
            return -1
        }
        return buffInt
    }()

    currentBrightness := func() int {
        buff, err := ioutil.ReadFile("/sys/class/backlight/gmux_backlight/brightness")
        if err != nil {
            log.Fatal(err)
            return -1
        }
        buffInt, err := strconv.Atoi(strings.Replace(string(buff), "\n", "", -1))
        if err != nil {
            log.Fatal(err)
            return -1
        }
        return buffInt
    }

    http.HandleFunc("/increase", func(w http.ResponseWriter, r *http.Request) {
        brightness := maxBrightness
        if (currentBrightness() + BRIGHTNESS_AMOUNT) < maxBrightness {
                brightness = currentBrightness() + BRIGHTNESS_AMOUNT
        }
        buff := []byte(strconv.Itoa(brightness))
        err := ioutil.WriteFile("/sys/class/backlight/gmux_backlight/brightness", buff, os.ModeDevice)
        if(err != nil) { log.Fatal(err) }
        fmt.Fprintf(w, strconv.Itoa(brightness))
    })

    http.HandleFunc("/decrease", func(w http.ResponseWriter, r *http.Request) {
        brightness := 0
        if (currentBrightness() - BRIGHTNESS_AMOUNT) > 0 {
                brightness = currentBrightness() - BRIGHTNESS_AMOUNT
        }
        buff := []byte(strconv.Itoa(brightness))
        err := ioutil.WriteFile("/sys/class/backlight/gmux_backlight/brightness", buff, os.ModeDevice)
        if(err != nil) { log.Fatal(err) }
        fmt.Fprintf(w, strconv.Itoa(brightness))
    })

    log.Fatal(http.ListenAndServe(":5600", nil))

}


texts:
I have two functions to find the number of factors of a given number.
I was wondering which one will be more efficient to use?

def nu_of_factors2(n):
    return len(set(reduce(list.__add__,
            ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))

def nu_of_factors1(n):
    result_set = set()
    sqrtn = int(n**0.5)
    for i in range(1,sqrtn+1):
        q, r = n/i, n%i
            if r == 0:
            result_set.add(q)
            result_set.add(i)
    return len(result_set)


texts: Repeat an action for a set of elements until all succeed, or progression halts

texts:
Context

I'm trying to write a function that drops a list of tables from a database (e.g., tables A, B and C).
This function has the following type, it returns a list of booleans indicating whether each table was successfully dropped:

dropTables :: (IConnection conn) => conn -> [String] -> IO [Bool]

Now, imagine table C depends on table B, i.e., table B cannot be dropped while table C exists. The function will be able to drop tables A and C, but not B, and so it will return [True, False, True].

So, I wanted to write a function that takes a list of tables, and calls dropTables. If any of the operations fail, it calls dropTables again but this time only with the tables that could not be dropped in the first iteration. And so on, until either all tables have been dropped, or progression halts (i.e. all operations in a given iteration fail, due to e.g. a connection being closed)

This was my first stab at it:

dropTablesRec :: IConnection conn => conn -> [String] -> IO ()
dropTablesRec conn tables = do
  results <- dropTables conn tables
  let failures = map fst $ filter (not . snd) $ zip tables results

  unless (null failures) $
    if length failures == length tables
      then print $ "Failed to drop the following tables: " ++ intercalate ", " failures
    else dropTablesRec conn failures

I then tried to generalize the core algorithm, and remove all references to tables and database connections:

-- Repeats a given action for a set of elements, until it succeeds for all elements, or fails for all elements.
-- Elements for which the operation succeeds are not passed onto the next iteration.
-- Returns the elements for which the action failed.
repeatUntilAll :: Monad m => [a] -> ([a] -> m [Bool]) -> m [a]
repeatUntilAll xs f =
  let
    go [] = return []
    go failures
      | length failures == length xs  = return failures   -- halt
      | otherwise                     = repeatUntilAll failures f
  in
    do
      results <- f xs
      let failures = map fst $ filter (not . snd) $ zip xs results
      go failures

dropTablesRec can now be reduced to:

dropTablesRec' :: IConnection conn => conn -> [String] -> IO ()
dropTablesRec' conn tables = do
  failures <- repeatUntilAll tables (dropTables conn)
  unless (null failures) $ print $ "Failed to drop the following tables: " ++ intercalate ", " failures

I was wondering if there's a simpler way of implementing repeatUntilAll.

I had a look around Control.Monad.Loops to see if there was anything I could use, but no such luck. Being a Haskell novice doesn't help either, I'm only familiar with a very small part of the core libraries.

Other improvements (naming, conventions, greater generalization) are also welcome.


texts: Django view for both AJAX and normal request

texts:
I'm starting with new project where there will be used to delete product using AJAX, but sometimes with normal request. What do you think about this view? I'm trying to make it as universal as possible.

@login_required
@require_POST
def delete_products(request):
    products_ids = request.POST.getlist('products_ids')
    deleted = Product.objects.filter(id__in=products_ids,user=request.user).delete()
    if request.is_ajax():
        return JsonResponse({'success':True,
                             'ids':[x.id for x in deleted]})
    return HttpResponseRedirect(request.POST.get('next') or '/')


texts: Multivariate Kernel Density Estimation for objects with missing values

texts:
I am trying to perform a certain numerical computation in Python with Numpy.
More specifically, I am doing a multivariate Kernel Density Estimation (KDE) in a Euclidean space of dimension F for objects with missing values. For each incomplete object of index "k", the kernels is no Gaussians, but a Gaussians in the subspace where ev[k] is True and a uniform distribution otherwise.
I actually do not simply want to evaluate the kernel density, but the gradient for the KDE function. The complete derivation is a bit more envolved, especially for the constants.
Here I only write down a minimal working example. The constants for example - which are scalars - would need complex calculation beforehand. They are there as stability weights or for normalizations.
import numpy as np

# Given:

I = 100
O = 1000
F = 10

o = np.random.random((O,F))  # Euclideanv vectors that are kind of the means of the Gaussians
ev = np.random.choice(a=[False, True], size=(O,F)) # these represent evidence and make sure that we calculate within the respective subspace
x = np.random.random((I,F))  # positions where we want to evaulate the KDE

const1 = 1.3456
const2 = 2.3456
const3 = 3.3456
const4 = 4.3456

# My calculations:

# First we calcuate the differences between the x and o vectors
diff = o[np.newaxis, :, :] - x.reshape((-1, 1, x.shape[x.ndim - 1]))

# The following two lines might be accessible from cache:

# We calculate the squared Euclidean distance between the x and o vectors and multiply them with the respective evidence vecotrs and constants. The result is the exponents for the Gaussian kernels
nsh = np.einsum('iof,iof,of,->io', diff, diff, ev, 1 / const1)

# We calculate the Gaussian kernels and normalise them with the const2. The const3 is stability weight, to avoid overflows or underflows.
kv = const2 * np.exp(nsh + const3)

# :Might be accessible from cache

# Finally we add the kernels together and calculate the gradient:
result = np.einsum('io,iof,of->if', kv, diff, ev)

I was trying to optimize for speed using broadcasting in the first line diff = and einsum in the last line. However, as one can easily see, the first line produces a very large array diff. Is it possible to avoid the creation of this large array while improving the speed or at least keeping the current speed?
One idea would be to replace
nsh = np.einsum('iof,iof,of,->io', diff, diff, ev, 1 / const1)

with
X = x
Y = o
X_sqr = np.sum(X ** 2, axis=1)
Y_sqr = np.sum(Y ** 2, axis=1)
nsh = (X_sqr[:, np.newaxis] - 2.0 * X.dot(Y.T) + Y_sqr) / const1

which is much faster. However, it does not include ev yet, because I don't know how I have to include it, to get it right. And also it does not remove the need to create diff, because I still need it in the final line.


texts:
Please review my code to help improve its quality.

public void printHeadOfNonIntersectingLinkedList(List<Standalone> listStandalones) {
    final Map<Node, Node> tailHeads = new HashMap<Node, Node>();

    for (Standalone ll : listStandalones) {
        Node temp = ll.first;
        while (temp.next != null) {
            temp = temp.next;
        }
        if (tailHeads.containsKey(temp)) {
            tailHeads.put(temp, null);
        } else {
            tailHeads.put(temp, ll.first);
        }
    }

    for (Entry<Node, Node> entry : tailHeads.entrySet()) {
        if (entry.getValue() != null) {
            System.out.println(entry.getValue().element);
        }
    }
}


texts: Finding similar items in two arrays with multithreading in C++

texts:
I'm exploring multithreading for some code that I want to speed up in C++. I wrote a simple program to facilitate my understanding. The program takes in two arrays of equal length, the value of the length itself, and a threshold. It outputs all indices i (in any order) where abs(array_1[i]-array_2[i]) < threshold. Here is the code:

#include <mutex>
#include <vector>
#include <thread>
#include <iostream>

std::mutex output_mutex;

void process_element(const uint8_t* input_1, const uint8_t* input_2, const size_t i, const uint8_t threshold, std::vector<size_t>& output){
    uint8_t element_1 = input_1[i];
    uint8_t element_2 = input_2[i];
    uint8_t distance = (element_1 > element_2) ?
            element_1 - element_2 :
            element_2 - element_1;
    if(distance < threshold){
        output_mutex.lock();
        output.push_back(i);
        output_mutex.unlock();
    }
}

std::vector<size_t> process(const uint8_t* input_1, const uint8_t* input_2, const size_t length, const uint8_t threshold){
    std::vector<size_t> output;
    std::vector<std::thread> threads;
    for (size_t i = 0; i < length; ++i) {
        std::thread t([&](){
            process_element(input_1,input_2,i,threshold,output);
        });
        threads.push_back(std::move(t));
    }
    for(auto&& thread : threads){
        thread.join();
    }
    return output;
}

int main(){
    uint8_t input_1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    uint8_t input_2[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    std::vector<size_t> output = process(input_1,input_2,10, 7);
    for(auto&& element : output){
        std::cout << int(element) << ' ';
    }
}

It seems to do fine when I run it.

Am I applying multithreading correctly?

Are there any mistakes or things I can improve in my code?

Is there a better/more efficient way to compute the distance in process_element than the way I coded it?

Lastly, I didn't care about the order of the output indices when writing the code, but I couldn't help but notice that the reported values always seem to be in order. Is this just an artifact of the fact that process_element is very simple and takes almost no time at all, or will the output in general be ordered according to the order in which I run the threads?


texts: jQuery code to total the items in a shopping cart

texts:
I implemented a shopping cart with asp.net and jquery on my website, and here is my js code which calculates amount and total sum on client side:

 $(document).ready(function () {
            update();
        $(".quant").change(function() {

            update();
         });
        function update() {

            var id = $('.quant').attr('data-id');
            var sum = 0.0;
            var quantity;
            $('#myTable > tbody  > tr').each(function () {

                quantity = $(this).find('.quant').val();
                var price = parseFloat($(this).find('.price').attr('data-price').replace(',', '.'));
                var amount = (quantity * price);

                sum += amount;
                $(this).find('.amount').text('' + amount + ' грн');

            });

            $('.total').text(sum + ' грн');

            $.get(
             '/Cart/AddTocart',
             {
                 id: id,
                 returnUrl: '',
                 quantity: quantity

             }
         );
        }

        });

Some people review my code and said me that it needs refactoring:

this part of code  var id = $('.quant').attr('data-id');

is wrong because if we have 1 element jquery works correctly, but if we have array of elements  - jquery "takes" only first element and attr doesn't work good ,  so how can i  fix it?? This id I pass to server side.  I thought it needs write something like this:

var id = $(this).attr('data-id');

but id will always undefined.
Problem here:

var quantity;
      $('#myTable > tbody  > tr').each(function () {
         quantity = $(this).find('.quant').val();
         ...
}

It recalculates all elements of quantity and quantity "saves" last known value; what's wrong here??
I was told that I pass first id and last quantity, but it is all present when I call function in $(document) - Please explain this to me.

Here is html code:

        Товар
        К-сть
        Назва Товару
        Ціна
        Загальна ціна

    @foreach (var line in Model.Cart.Lines)
    {

        IEnumerable<FurnitureImages> images = line.Furniture.Images;
        FurnitureImages mainImage = images.Where(x => x.IsMainImage).FirstOrDefault();

               @if (mainImage != null)
               {

               }

            <input type="text" data-id="@line.Furniture.FurnitureId" data-price="@line.Furniture.Price" value="@line.Quantity" class="quant" />

            @line.Furniture.Name
            @((line.Furniture.Price).ToString("#.## грн"))
            @((line.Quantity * line.Furniture.Price).ToString("#.## грн"))

                @using (Html.BeginForm("RemoveFromCart", "Cart", new { Id = line.Furniture.FurnitureId }))
                {
                    @Html.Hidden("Id", line.Furniture.FurnitureId)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning" type="submit" value="Видалити з кошику" />
                }

    }

        Всього до оплати:
        @Model.Cart.ComputeTotalValue().ToString("#.## грн")


texts: Function to determine the direction of an arrow

texts:
I have a function in a project that I feel could be written better. The purpose of the function is to return the direction of an arrow based on two parameters.

positiveDirection: The direction for a positive result. The values could be increasing or decreasing.
changeType: Whether the result was positive, negative or no-change.

I guess it's the if statement that is bothering me the most; it looks like it could be reduced based on some logic gate that I don't know of.

  getArrowDirection = (positiveDirection, changeType) => {

    let direction = null

    if(changeType === 'no-change') {
      return direction
    }

    if(
        (changeType === 'positive' && positiveDirection === 'increasing') ||
        (changeType === 'negative' && positiveDirection === 'decreasing')
      ) {
      direction = 'up-arrow'
    } else if(
        (changeType === 'positive' && positiveDirection === 'decreasing') ||
        (changeType === 'negative' && positiveDirection === 'increasing')
      ) {
      direction = 'down-arrow'
    }

    return direction
  }


texts:
import pandas as pd
import pandas_read_xml as pdx
from lxml import etree
url2='http:'
url='http:'
tree=etree.parse(url)
st=etree.tostring(tree.getroot())

# The list "all_leaves" includes every node and leaf in the tree

from io import StringIO, BytesIO
#st above is encoded as binary

all_leaves=[]
events = ("start", "end")
# "start" are the xml tags start
# "end" are the xml tags with "</"
parent='root' #root of the xml tree
context = etree.iterparse(BytesIO(st), events=events)
for n, actel in enumerate(context):
  if actel[0]=='end': #this marks the end of a node
    parent = all_leaves[n-1][1] #use previous parent
    all_leaves.append([actel[0],parent,actel[1].tag])
    #append the action, parent and tag
  else:
    all_leaves.append([actel[0],parent,actel[1].tag])
    if actel[0]=='start': #the current become parent since this
                          #algorithm is depth first
      parent = actel[1].tag

# "leaves" includes only the first row of each table
leaves=[]
for entry in all_leaves:
  if (entry not in leaves) and (entry[0]=='start'):
    leaves.append(entry)

# These are the names of the tables
nf_nodes=[]
for entry in leaves[2:]:#ignore the first two:
  nf_nodes.append(entry[1])
nf_nodes=list(set(nf_nodes))

# The dictionary "all_dic" has keys labeled as the node
# above each set of leaves (i.e. DataFrames) with value equal to the corresponding
# DataFrame or leav
all_dic={}
for l in nf_nodes:
    all_dic[l]=pdx.read_xml(url, ['DRFAssessments',l])

I have the following code below that reads and parses xml files. The following code takes about 10:30 seconds to run. I wanted to see if there were any suggestions or any edits that could be made to the code to increase the speed. The code is used to parse the xml file before it is uploaded to a MYSQL database. It also parses 20 tables if that is any useful


texts:
A legacy project was upgraded from legacy code that used either SystemV FIFO device (or similar queue on Windows platform) which was deeply ingrained into every thread's implementation. Following implementation of locking queue with a wait was meant to emulate original FIFO use:
#include <queue>
// target platform doesn't have  std::mutex or support >C++14
#include <QWaitCondition>
#include <QMutex>

template < typename _Msg, typename _Alloc = std::allocator<_Msg> >
class WaitQue
{
public:
    typedef _Alloc  Allocator;
    typedef _Msg    DataType;

    // a thread calls this to place a copy of msg
    void post(const DataType& msg)
    {
        QMutexLocker lock_(&mx);
        que.push(msg);
        cv.wakeOne();
    }

    // a thread calls this to to wait for a message
    void wait(DataType& msg)
    {
        /// wait if que empty
        QMutexLocker cvlock_(&mx);
        while(que.empty())  // spurious exit from wait()
            cv.wait(&mx);

        msg = que.front();
        que.pop();
    }

    unsigned long size()
    {
        QMutexLocker lock_(&mx);
        return que.size();
    }

private:
    typedef std::deque<DataType, Allocator> Container;
    std::queue<DataType, Container> que;

    QWaitCondition cv;
    QMutex mx;
};

A simplest use of such queue without any fluff:
#include <QCoreApplication>
#include <QtConcurrent>
#include <QFuture>

struct Message {
    int value;
};

using Queue = WaitQue<Message>;

Queue east; // messages for east-side events
Queue west; // messages for west-side events

void westSide()
{
   Message msg = {};

   for(int i = 5; i-->0; )
   {
       qDebug() << "West side is working." << endl;
       east.post(Message{i}); //

       west.wait(msg); //
   }
}

void eastSide()
{
   Message msg = {};
   do
   {
       east.wait(msg);
       qDebug() << "East side received " << msg.value << endl;
       west.post(msg);
   }while(msg.value);
}

int main(int argc, char *argv[])
{
   QCoreApplication a(argc,argv);
   QFuture<void> future1 = QtConcurrent::run(westSide);
   QFuture<void> future2 = QtConcurrent::run(eastSide);

   future1.waitForFinished();
   future2.waitForFinished();
   return 0;
}

In reality most of workers are infinite state-machine loops operating only after receiving messages or generating such messages for other workers while some are actually doing ping-pong exchange as above.
Target platform got partial C++11 support and Qt < 5.4 support. std::queue was used instead of Qt container for sake of custom allocator support and condition variable QWaitCondition is used to lock queue. Custom allocator allows to avoid heap allocation. Is this correct implementation and if its not, what flaws are there? Is there a Qt analog for this maybe?
PS. Indefinite wait was a known problem that was solved by design of any scenario was ending with posting "stop thread" messages to all queues in past implementation of project.


texts:
This is a sequel to my previous question: Sieve of Sundaram for Project Euler 7: Python implementation slower than C++ and R

I am trying to implement the Sieve of Sundaram in various languages to solve Project Euler Problem #7.

I have written a solution in Haskell (to which I am still very new, but eager to learn) based loosely on the example available on this blog.

The approach is to find the upper bound for the value of the nth prime:
$$\mathrm{Bound}(n) = n \times (\log(n) + \log(\log(n))) $$

Then sieve all of the numbers up to the bound.

I would like some advice on improving my style (conciseness, clarity), and the performance of my code, which is about 30x slower than the C++ solution included in my previous question.

import Data.List

bound :: Int -> Int
bound n = floor (n' * ((log n') + log (log n')))
    where
        n' = fromIntegral n

marked :: Int -> [Int]
marked n = sort [ i + j + 2*i*j | i <- [1..iMax], j <- [i..jMax i]]
    where
        iMax = floor (sqrt (fromIntegral n))
        jMax i = quot (n - i) (2*i + 1)

removeComposites :: [Int] -> [Int] -> [Int]
removeComposites [] _          = []
removeComposites (s:ss) []     = 2*s + 1 : removeComposites ss []
removeComposites (s:ss) (c:cs)
    | s == c    = removeComposites ss cs
    | s > c     = removeComposites (s:ss) cs
    | otherwise = 2*s + 1 : removeComposites ss (c:cs)

sieveSundaram :: Int -> [Int]
sieveSundaram n = 2:(removeComposites [1..n'] (marked n'))
    where
        n' = quot (bound n) 2

pe_007 = last (take n (sieveSundaram n))
    where n = 10001

main :: IO ()
main = do
    print pe_007


texts:
I'm new to the world of BDD, but I'd like to get a grip of it as soon as possible. It's one of my first tests:

Fluent.js

'use strict';

var Fluent = module.exports = function Fluent(context, chain) {
    if (this.constructor === Fluent) {
        throw new Error("Can't initialize an abstract class!");
    }

    this.context = context;
    this.chain = chain;

    //Detect if we want to create new chainRoot or inherit it from parent
    if (this.chain) {
        this.chainRoot = this.chain.chainRoot;
    }
};

Fluent.prototype.end = function () {
    return this.chain;
};

fluent_test.js

'use strict';

var
    _ = require('lodash'),
    expect = require('expect.js')
;

var
    Fluent = require('../../lib/jawan/Fluent')
;

var FooFluent = function FooFluent() {
    Fluent.apply(this, arguments);
};

FooFluent.prototype = _.create(Fluent.prototype, { 'constructor': FooFluent });

var RootFluent = function FooFluent(context, chain) {
    Fluent.apply(this, arguments);

    this.chainRoot = this;
};

RootFluent.prototype = _.create(Fluent.prototype, { 'constructor': RootFluent });

var DummyObject = function DummyObject() {
    this.person = 'Hank';
};

describe('abstract fluent interface', function () {
    it('should refuse to be created', function (done) {
        expect(function() { new Fluent(new DummyObject()); }).to.throwError();
        done();
    });
});

describe('concrete fluent interface', function () {
    beforeEach(function () {
        this.dummyInstance = new DummyObject();
        this.foo = new RootFluent(this.dummyInstance);
        this.bar = new FooFluent(this.dummyInstance, this.foo);
        this.fizz = new FooFluent(this.dummyInstance, this.bar);
    });

    it('should set its context', function (done) {
        expect(this.foo.context).to.be.a(DummyObject);
        done();
    });

    it('should chain properly', function (done) {
        expect(this.bar.chain).to.be(this.foo);
        done();
    });

    it('should return its parent correctlz', function (done) {
        expect(this.bar.end()).to.be(this.foo);
        done();
    });

    it('should return its chain root properly', function (done) {
        expect(this.fizz.chainRoot).to.be(this.foo);
        done();
    });
});

I'm testing for node only, browser-specific stuff is not my concern.


texts:
Can I improve my code? There are 3 types of hamburgers.

The basic hamburger will have these properties:

prices
type of bread
type of meat
maximum 4 supplements

Then, create a  Bio burger  that will be gray bread, and which can receive in addition 2 elements supplement to the basic either 6 supplements max.

After, create a Deluxe Hamburger : that will be provided with fries and a drink, but it will not be possible to add supplements.

Class Hamburger

public class Hamburger {

  // Attributes

  double price;
  private String typeBread;
  private String typeMeat;
  int counter;

  public Hamburger(double price, String typeBread, String typeMeat)
  {
    this.price = price;
    this.typeBread = typeBread;
    this.typeMeat = typeMeat;
    this.counter = 0;

    System.out.println("Hamburger " + this.getTypeBread() + " - " + this.typeMeat + " - " + this.getPrice() + " euros");
  }

  // add supplement 4 maximum

  public void addSupplement(String type, double amount)
  {
    counter++;
    if(counter <= 4)
    {
      System.out.println("Supplement " + counter + " : " + type + " - " + amount + " euros");
      this.price = this.price + amount;
    }
    else
    {
      System.out.println("Error supplement maximum is 4 ");
    }
  }

  public void total()
  {
    System.out.println("Total => " + this.getPrice() + " euros");
  }

  // les getters

  public double getPrice()
  {
    return price;
  }

  public String getTypeBread()
  {
    return typeBread;
  }

  public String getTypeMeat()
  {
    return typeMeat;
  }

  public int getCounter()
  {
    return counter;
  }

}

Class Bio

public class Bio extends Hamburger  {

  public Bio(double price, String typeMeat) {
        super(price, "gray bread", typeMeat);

    }

    public void addSupplement(String type, double amount) {
        counter++;
        if (counter<=6){
            System.out.println("Supplement " + counter + " : " + type + " - " + amount + " euros ");
            this.price = this.price+ amount;
        }
        else{
            System.out.println("Error supplement 6 maximum ");
        }
    }

}

Class Deluxe

public class Deluxe extends Hamburger {

   private String accompaniment;
   private String drink;

   // Builders

     public Deluxe () {
         super (7.99, "white bread", "veal");
         this.accompaniment = "fried";
         this.drink = "drink";

         System.out.println ("Included in the DELUXE formula:" + this.getDrink () + "-" + this.getAccompaniment ());
     }

     public String getAccompaniment () {
         return accompaniment;
     }

     public String getDrink () {
         return drink;
     }

     public void addSupplement (String type, double price) {
         System.out.println ("No supplement allowed for this formula");
     }

     public void total () {
         super.total ();
     }
}

Class Main

public class Main {

    public static void main(String[] args) {

    System.out.println("BASIC");
    Hamburger myHamburger = new Hamburger(5.99, "white bread", "beef");
    myHamburger.addSupplement("Tomatos", 0.99);
    myHamburger.addSupplement("Bacons", 0.59);
    myHamburger.addSupplement("Onions", 0.49);
    myHamburger.addSupplement("Ketchup", 0.29);
    System.out.println("__________");
    myHamburger.total();
    System.out.println("-----------------------");

    System.out.println("BIO");
    Bio myBio = new Bio (6.99, "Veal");
    myBio.addSupplement ("Onions", 0.49);
    myBio.addSupplement("Tomatoes", 0.99);
    myBio.addSupplement ("Bacon", 0.59);
    myBio.addSupplement ("Cucumbers", 0.49);
    myBio.addSupplement("Ketchup", 0.29);
    myBio.addSupplement ("Mayo", 0.29);
    myBio.addSupplement ("Cocktail", 0.29);
    System.out.println ( "__________");
    myBio.total ();
    System.out.println("-----------------------");

    System.out.println("DELUXE");
    Deluxe myDeluxe = new Deluxe();
    myDeluxe.addSupplement("Tomatoes", 0.99);
    System.out.println("__________");
    myDeluxe.total();

}
}


texts:
I've recently ported an old project and made it object-oriented. However, I've noticed that rubocop points out the following status: Assignment Branch Condition size for fetch_images is too high. [22.41/15]. Can I make this method be made more efficient, perhaps?

Snippit

class WebCrawler
  attr_reader :agent, :tumblr, :images

  def initialize
    @agent = Mechanize.new
    @agent.user_agent_alias = Mechanize::AGENT_ALIASES.keys
      .reject { |agent| agent == 'Mechanize' }.sample
    @tumblr = URI('http://www.tumblr.com')
    @images = []
  end

  def fetch_images(blog, proxy)
    fail Exceptions::InvalidBlog unless valid_blog?(blog)
    fail Exceptions::InvalidProxy unless valid_ip?(proxy)

    tokens = proxy.split(':')
    proxy_addr = { ip: tokens[0], port: tokens[1].to_i }
    @agent.set_proxy(proxy_addr[:ip], proxy_addr[:port])

    @tumblr.host.gsub!(/^w{3}/, '').insert(0, "#{blog}")
    page = @agent.get(@tumblr)
    page.search('img[src$="jpg"], img[src$="png"]').each do |img|
      @images << img['src']
    end
    @images.keep_if do |img|
      img =~ %r{^https?://\d+|media} && img !~ /avatar/
    end
  end
end


texts: Scan a webpage to find the start time and date for an event

texts:
I am working on a simple web crawler that returns the start time and date for an event listed on a webpage. The webpage can be in two different formats and there are multiple other dates listed on the page. The part of the webpage I am scanning looks like this:

...

Time

        Starts: <time itemprop="startDate" datetime="2017-03-13T17:30:00ADT">Monday March 13, 2017 - 05:30 PM</time>

        Ends: <time itemprop="endDate" datetime="2017-03-13T19:00:00ADT">Monday March 13, 2017 - 07:00 PM</time>

Additional Dates/Times

        Starts: <time>Monday January 30, 2017 - 05:30 PM</time>

        Ends: <time>Monday January 30, 2017 - 07:00 PM</time>

Location

...

or like this:

...

Time

    <time itemprop="startDate" datetime="2017-03-17T13:30:00ADT">Friday March 17, 2017 - 01:30 PM</time>

Location

....

After using BeautifulSoup to find the links I am interested in I pass the link to these methods which find the text between 'Time' and 'Location'. Next it searches for a tag in that code block '">" which I know only appears before the date text and scans until the next closing tag, returning a date string.

MAX_CHARS = 140

def get_date(link):
    date_text = ""
    event_html = urllib2.urlopen(link['href']).read()
    start = find_date_location(event_html)
    # after the datetime closing tag the date begins until another tag opens
    for x in range(start, start + MAX_CHARS):
        if event_html[x] == '<':
            break
        date_text += event_html[x]

    return date_text

def find_date_location(html):
    date_starts = html.find('
Time
')
    date_ends = html.find('
Location
')
    for x in range(date_starts, date_ends):
        if html[x] + html[x+1] == '">':
            return x+2

    raise ValueError('Date not found in HTML within time range')

This would return "Monday March 13, 2017 - 05:30 PM" in the first case and "Friday March 17, 2017 - 01:30 PM" in the second case. My method seems really hacky. Any tips on how I could do this better?


texts: Process List asynchronously with SemaphoreSlim for throttling extension method

texts:
I've got some methods that follow a similar pattern, and wanted to abstract some of the logic away into an extension method. Specifically, I am processing lists of objects with the TPL, and throttling that processing with a SemaphoreSlim.

public static Task ValidateProxiesAsync(IList<Proxy> proxies, IList<ProxyJudge> judges, IList<ProxyTest> tests)
{
    return Task.Run(async () =>
    {
        await ValidateTestsAsync(judges.ToList<IProxyTest>());
        await ValidateTestsAsync(tests.ToList<IProxyTest>());
        var semaphore = new SemaphoreSlim(100);
        var tasks = new List<Task>();
        foreach (var proxy in proxies)
        {
            await semaphore.WaitAsync();
            tasks.Add(Task.Run(() =>
            {
                proxy.Status = proxy.TestValidity(judges[0]);
                semaphore.Release();
            }));
        }
        await Task.WhenAll(tasks);
    });
}

public static Task ValidateTestsAsync(IList<IProxyTest> tests)
{
    return Task.Run(async () =>
    {
        var semaphore = new SemaphoreSlim(100);
        var tasks = new List<Task>();
        foreach (var test in tests)
        {
            await semaphore.WaitAsync();
            tasks.Add(Task.Run(() =>
            {
                test.Status = test.TestValidity();
                semaphore.Release();
            }));
        }
        await Task.WhenAll(tasks);
    });
}

I wrote this extension method to reduce the LOC needed to do this. But I wanted to make sure I didn't overlook something. Perhaps there is a better solution that someone on here could suggest (TPL Dataflow?).

Extension method:

    public static Task ProcessWithSemaphoreAsync<T>(this IList<T> list, Action<T> action, int maxConcurrency)
    {
        return Task.Run(async () => {
            var semaphore = new SemaphoreSlim(maxConcurrency);
            var tasks = new List<Task>();
            foreach (var item in list)
            {
                await semaphore.WaitAsync();
                tasks.Add(Task.Run(() =>
                {
                    action.Invoke(item);
                    semaphore.Release();
                }));
            }
            await Task.WhenAll(tasks);
        });
    }


texts: Accepting user input for tickets and tips

texts:
I've done tutorials as well as searches. I need assistance in simplifying this code. Please don't do it for me- instead inform me of what, where and why you are trying to simplify or write less code. I'm already working on an if loop to exit on enter. This is just version 3 for me.

## Program gets the date, Employee ID, and amounts.
## It then places them into a text file which can be ported to excel.

## Get Date
import datetime
date = str(datetime.date.today())

## Get Employee I.D.
empnum = raw_input('Please enter Employee Number\n')

## Lists for the Users input.
amnt = []
amntt =[]

## Get Users Input and add to the appropriate list
num1 = raw_input('Please enter Ticket amount.\n')
amnt.append(num1)
numt1 = raw_input('Please enter tip amount.\n')
amntt.append(numt1)

num2 = raw_input('Please enter Ticket amount.\n')
amnt.append(num2)
numt2 = raw_input('Please enter tip amount.\n')
amntt.append(numt2)

num3 = raw_input('Please enter Ticket amount.\n')
amnt.append(num3)
numt3 = raw_input('Please enter tip amount.\n')
amntt.append(numt3)

num4 = raw_input('Please enter Ticket amount.\n')
amnt.append(num4)
numt4 = raw_input('Please enter tip amount.\n')
amntt.append(numt4)


texts:
I'm writing a utility that validates fields. I decided to try my hand at Behaviour Driven Development (BDD). The validator utilises "rules" to determine if field is valid.

Three different types of rules exist:

RegexRule A field conforms to specific pattern(s)
RequireRule A value is present
EqualityRule A field's value equals another's value

A rule is tested against a value. If the value does not conform to the rule, a flag is set which marks the rule as erroneous. Calling getError() on an erroneous rule returns a string that details the error. Furthermore, the rule is reset (no longer erroneous).

Is this the correct manner of implementing BDD on this class? I'd greatly appreciate advice on how I could improve on this.

describe('RequireRule', function()  {
    var nameErr = 'The name field is required';

    beforeEach(function()  {
        this.r = new RequireRule('name', nameErr);
    });

    describe('test()', function()  {
        it('should return false when value provided is null or undefined', function()  {
            expect(this.r.test('asd')).to.equal(true);
        });
        it('should return true when value provided is not null or undefined', function()  {
            expect(this.r.test(null)).to.equal(false);
        });
    });

    describe('isErroneous()', function()  {
        it('should become erroneous when value tested is null or undefined', function()  {
            r.test(null);
            expect(this.r.isErroneous()).to.equal(true);
        });
        it('should not be erroneous when value tested is not null or undefined', function()  {
            r.test('asd');
            expect(this.r.isErroneous()).to.equal(false);
        });
    });

    describe('getError()', function()  {
        it('should return null when the test() succeeded', function()  {
            r.test('asd');
            expect(this.r.getError()).to.equal(null);
        });
        it('should return the error string when the test() failed, and set erroneous to false', function()  {
            r.test(null);
            expect(this.r.getError()).to.equal(nameErr);
            expect(this.r.isErroneous()).to.equal(false);
        });
    });
});

The test framework is Mocha.


texts: Could this connection and query class be improved?

texts:
Wrote this class it allows me to connect to database and display as many columns as I wish to. I can just give it desired parameters and I'm done. I've commented about the parameters that need it to be passed.

     include('connect.php');
   //include this file. This is our class

   $connection = new connection_to_db;
   //instantiate class

   $connection->make_connection("host_name", "user", "pass", "database_name");
   //1st param: your host name
   //2st param: your username
   //3rd param: your password
   //4th param: your database name

   $connection->run_test_query("shouts", "id", 2);
   //1st param: your table name.
   //2nd param: which column to show.
   //3rd param: how many results to display.

class connection_to_db{
     function make_connection($host, $user, $pass, $db){
       global $conn;
       try{
         $conn = new pdo("mysql: host=". $host . ";dbname=". $db, $user, $pass);
       }catch(PDOException $error){
         echo $error->getMessage();
         die();
       }
     }

     function run_test_query($shouts, $column_to_show, $count){
       global $conn;
       $query = $conn->prepare("SELECT * FROM $shouts LIMIT $count");
       $query->execute();

       while($result = $query->fetch(PDO::FETCH_ASSOC) ){
         echo $result["$column_to_show"] . "</br>";
       }
     }
   }


texts:
I wanted to implement the cat function in Julia and I ran a few test cases but I am not sure if I am missing anything:

for line in eachline(STDIN)
    write(line)
end

It's really simple code and I tested it with the following test cases:

$ cat hello.txt | julia cat.jl
first line
second line
third line

$ cat hello.jpg | julia cat.jl > hello2.jpg
$

and hello2.jpg was the same as hello.jpg.


texts: A hash-signature-type which tests on comparing against normal strings

texts:
I decided to throw this together today figuring it would be cool to add to my repertoire. Before we always had performed this "task" externally. Find the value we want to compare, hash it and compare with a valid hash. But my idea was to bundle this into a object which behaves nicely with string types. It then could internally compare the two and determine if they match.

I'm just curious on what you all think here and where I can improve. And if I've even done something any of you find could save time and find more usable than not.

Benefits

No generic classes I have to drag around, it is now a type with a specific purpose.
The data for the type is never stored in plain text, therefore should be safe, right?

Usage

ProtectedString ThisIsMyProtectedString1 = "";

ThisIsMyProtectedString1 = "Test";

if (ThisIsMyProtectedString1 == "Test")
    MessageBox.Show("Equal");

Le Code

public struct ProtectedString
{

    private string _Data;

    public String Data
    {
        get { return _Data; }
        private set { _Data = value; }
    }

    private const int SALT_BYTE_SIZE = 24;

    private const int HASH_BYTE_SIZE = 24;

    private const int PBKDF2_ITERATIONS = 1000;

    public ProtectedString(String value)
    {
        _Data = "";
        _Data = CreateHash(value);
    }

    public static implicit operator ProtectedString(String value)
    {
        return new ProtectedString(value);
    }

    public static bool operator ==(ProtectedString c1, String c2)
    {
        return c1.Equals(c2);
    }

    public static bool operator !=(ProtectedString c1, String c2)
    {
        return !c1.Equals(c2);
    }

    public static bool operator ==(String c1, ProtectedString c2)
    {
        return c2.Equals(c1);
    }

    public static bool operator !=(String c1, ProtectedString c2)
    {
        return !c2.Equals(c1);
    }

    public bool Equals(String value)
    {
        Boolean result = false;
        result = ValidateHash(value, _Data);
        return result;
    }

    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }

    private string CreateHash(String value)
    {
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();

        byte[] salt = new byte[SALT_BYTE_SIZE];

        csprng.GetBytes(salt);

        byte[] hash = PBKDF2(value, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);

        return
            Convert.ToBase64String(salt) +
            Convert.ToBase64String(hash);
    }

    private bool ValidateHash(String value, String validHash)
    {
        byte[] full = Convert.FromBase64String(validHash);

        byte[] salt = full.Take(SALT_BYTE_SIZE).ToArray();

        byte[] hash = full.Skip(SALT_BYTE_SIZE).ToArray();

        byte[] testHash = PBKDF2(value, salt, PBKDF2_ITERATIONS, hash.Length);

        return SlowEquals(hash, testHash);
    }

    private bool SlowEquals(byte[] a, byte[] b)
    {
        uint diff = (uint)a.Length ^ (uint)b.Length;

        for (int i = 0; i < a.Length && i < b.Length; i++)
            diff |= (uint)(a[i] ^ b[i]);

        return (diff == 0);
    }

    private byte[] PBKDF2(string value, byte[] salt, int iterations, int outputBytes)
    {
        Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(value, salt);

        pbkdf2.IterationCount = iterations;

        return pbkdf2.GetBytes(outputBytes);
    }

}


texts:
Any suggestion to improve this, they ask me to input characters that should be an invalid input and ask you again to input the number of process without crashing the program.

#include<iostream>
#include<ctype.h>
using namespace std;

int main()
{
     int bt[20],wt[20],avwt=0,i,j;
     int n;

     cout<<"Enter total number of processes(maximum 20):";
     cin>>n;
     while(char (n))
     {
          if(isalpha(n))
          {
                cout<<"Invalid Input";
          }

       cout<<"\nEnter Process Burst Time\n";
       for(i=0;i<n;i++)
       {
            cout<<"P["<<i+1<<"]:";
            cin>>bt[i];
       }

       wt[0]=0;
       for(i=1;i<n;i++)
       {
             wt[i]=0+bt[i];
             for(j=0;j<i;j++)
             wt[i]+=bt[j];
       }

        cout<<"\nProcess\t\tBurst Time\tArrival Time";

        for(i=0;i<n;i++)
        {

             avwt+=wt[i];
             cout<<"\nP["<<i+1<<"]"<<"\t\t"<<bt[i]<<"\t\t"<<wt[i];
        }

        avwt/=i;

        cout<<"\n\nAverage Waiting Time:"<<avwt;
    }
    return 0;
  }


texts: Merge sort algorithm implementation using C++ (redux)

texts:
This is a follow up question to the one I asked a couple of days ago.

I reviewed the suggestions & did some research (specifically, read relevant info on CLRS). The new version is 3 times faster (210ms vs 71ms on 100,000 numbers) & looks cleaner.

One thing I still feel weird about is not using iterators except than to init the sub-vectors. However, any attempt in using them causes a drop in performance (down to 120ms).

I'm also curious if my code is good in terms of code style. Is this idiomatic C++?

void merge(std::vector<int>& a, int p, int q, int r)
{
    std::vector<int> l(a.begin() + p, a.begin() + q + 1);
    std::vector<int> ri(a.begin() + q + 1, a.begin() + r + 1);

    int n1 = q - p + 1;
    int n2 = r - q;

    int i, j; i = j = 0;

    while (i < n1 && j < n2) {
        if (l[i] < ri[j]) {
            a[p++] = l[i++];
        } else {
            a[p++] = ri[j++];
        }
    }

    while (i < n1) {
        a[p++] = l[i++];
    }

    while (j < n2) {
        a[p++] = ri[j++];
    }
}

void merge_sort(std::vector<int>& a, int p, int r)
{
    if (p < r) {
        int q = (p + r) / 2;
        merge_sort(a, p, q);
        merge_sort(a, q + 1, r);
        merge(a, p, q, r);
    }
}


texts: Counting athletes whose height is in a given range

texts:
Challenge: Sort by growth

  Input

  The first line of each query contains one number n (1 ≤ n ≤ 20000) - the number of members in corresponding delegation.
  The second line contains n unsorted integers - the heights of athletes in centimeters.  Every height is at least 150 cm, and no greater than 250 cm.
  The third line contains a and b: the lower and upper height limits.

  Output

  For each query print the count on a separate line.

  Time limit: 2 seconds
  Memory limit: 256 MiB

My program works correctly, but I have a running time of 3020 ms.

 import java.io.PrintWriter;
 import java.util.Scanner;

 public class OlimpGames {
   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
     PrintWriter out = new PrintWriter(System.out, true);
      {
       while (in.hasNextInt()) {
        int n = in.nextInt();

        int heigh[] = new int[100];
        for (int i = 0; i < n; i++) {
            heigh[in.nextInt() - 150]++;
        }
        int a = in.nextInt();
        int b = in.nextInt();

        int an = 0;
        for (int i = a - 150; i <= b - 150; i++) {
            an = an + heigh[i];
        }
        System.out.println(an);
       }
      }
  }
}


texts: A function that checks if a word is similar to another word and returns a boolean

texts:
This function will check a word with some letters missing, missing letters will be indicated by an "_ " (notice that there is a space after the underscore).
The word with missing letters needs to be checked against a full word and if both words are found to be identical ( disregarding the "_ " the function should return True otherwise False.

This is part of a problem set from the MIT Online Course.
here is how i managed to do this:

def match_with_gaps(my_word, other_word):
    '''
    my_word: string with "_" characters
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the
    corresponding letters of other_word, or the letter is the special symbol "_",
    and my_word and other_word are of the same length;
    False otherwise:
    '''
    my_word = my_word.replace(' ','')
    for char in my_word:
        if char.isalpha():
            if my_word.count(char) != other_word.count(char):
                return False
    return len(my_word) == len(other_word)

An example :

a = match_with_gaps('a p p _ e', 'apple')
b = match_with_gaps('a p p _ c', 'apple')
print(a) >> outputs : True
print(b) >> outputs : False

I also came up with another way:

def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise:
    '''
    my_word = my_word.replace(' ', '')
    if len(my_word) != len(other_word):
        return False
    else:
        for i in range(len(my_word)):
            if my_word[i] != '_' and (
                my_word[i] != other_word[i] \
                or my_word.count(my_word[i]) != other_word.count(my_word[i]) \
            ):
                return False
        return True

which will give the same output but using a different method.

Which way is more efficient / will give more accurate results? and is there a third better method?
Please give reason to your answer.
And thanks in advance.


texts: Logging errors with the same exception type

texts:
I wrote some code which simply retrieves the HTTP status code of the passed in URL.  There are multiple potential causes of the same error.  I am hoping to get some all around feedback on this code, but my primary concern is that I have low readability in an attempt to provide good feedback in the event of an error.

private static final String HOST_NAME = "proxy.mycompany.com";
private static final int PORT = 5555;
private static final Logger LOGGER = LoggerFactory
        .getLogger("HttpStatusCode");

public static int getHttpStatusCode(URL url) {
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                  HOST_NAME, PORT));
    HttpURLConnection connection = null;
    try {
           connection = (HttpURLConnection) url.openConnection(proxy);
    } catch (IOException e) {
           LOGGER.error("URL.openConnection(Proxy) failed in HttpStatusCode.getHttpStatusCode(URL)!");
           LOGGER.error("URL attempted: " + url);
    }
    int responseCode = -1;
    try {
           responseCode = connection.getResponseCode();
    } catch (IOException e) {
           LOGGER.error("HttpURLConnection.getResponseCode() failed in HttpStatusCode.getHttpStatusCode(URL)!");
           LOGGER.error("URL attempted: " + url);
    }
    connection.disconnect();
    return responseCode;
}

My original attempt was the following, but my co-worker advised that I change it to the former for better error handling:

private static final String HOST_NAME = "proxy.mycompany.com";
private static final int PORT = 5555;
private static final Logger LOGGER = LoggerFactory
        .getLogger("HttpStatusCode");

public static int getHttpStatusCode(URL url) {
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
            HOST_NAME, PORT));
    try {
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection(proxy);
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        return responseCode;
    }
    catch (IOException e) {
        LOGGER.error("IOException in HttpStatusCode.getHttpStatusCode(URL)!");
        LOGGER.error("URL attempted: " + url);
        return -1;
    }
}

Just to be clear, this code compiles and runs error free based on my testing.  I am looking for a review on the way I am handling potential errors.


texts: Stack implemented using a single linked list

texts:
I am studying data structures and I have implemented a stack using a linked list.

stack.h

#ifndef STACK_H
#define STACK_H

#include <stdbool.h>

typedef char StackElement;

typedef struct stack_CDT *Stack;

Stack stack_init();

void stack_destroy(Stack s);

bool stack_is_empty(Stack s);

void stack_push(Stack s, StackElement elem);

StackElement stack_pop(Stack s);

#endif

stack.c

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "stack.h"

typedef struct node {
    StackElement data;
    struct node *next;
} Node;

Node *node_create(StackElement data)
{
    Node *new = malloc(sizeof *new);
    new->data = data;
    new->next = NULL;
    return new;
}

void node_insert(Node **node_ref, Node *new)
{
    if (new == NULL)
        return;

    new->next = *node_ref;
    *node_ref = new;
}

void node_delete(Node **node_ref)
{
    if (*node_ref == NULL)
        return;

    Node *next = (*node_ref)->next;
    free(*node_ref);
    *node_ref = next;
}

void list_delete(Node **head_ref)
{
    while ((*head_ref) != NULL)
        node_delete(head_ref);
}

typedef struct stack_CDT {
    Node *top;
} StackCDT;

StackCDT *stack_init()
{
    StackCDT *new = malloc(sizeof *new);
    new->top = NULL;
    return new;
}

void stack_destroy(StackCDT *s)
{
    list_delete(&(s->top));
    free(s);
}

bool stack_is_empty(StackCDT *s)
{
    return s->top == NULL;
}

void stack_push(StackCDT *s, StackElement elem)
{
    Node *new = node_create(elem);
    node_insert(&(s->top), new);
}

StackElement stack_pop(StackCDT *s)
{
    if (stack_is_empty(s)) {
        fprintf(stderr, "Can't pop element from stack, stack is empty.\n");
        exit(1);
    }

    StackElement elem = s->top->data;
    node_delete(&(s->top));
    return elem;
}

stacktest.c

#include <stdio.h>
#include <string.h>
#include "stack.h"

#define MAX_STR_LEN 100

void stacktest()
{
    printf("Enter a string(not more than %d characters): ", MAX_STR_LEN);
    char input[MAX_STR_LEN + 1];
    fgets(input, sizeof input, stdin);
    char *pos;
    if ((pos = strchr(input, '\n')) != NULL)
        *pos = '\0';

    Stack stack = stack_init();
    for (char *c = input; *c; c++)
        stack_push(stack, *c);

    printf("Popped characters are: ");
    while (!stack_is_empty(stack))
        printf("%c", stack_pop(stack));
    printf("\n");

    stack_destroy(stack);
}

int main()
{
    stacktest();
    return 0;
}

Is my implementation all right?


texts:
StringBuilder class is a common class that many have become accustom to, including me.

An individual posted a question regarding if there was a comparable method in typescript. Several solutions were mention or linked, but none contained a class. Here is a small class that embodies some of the common StringBuilder methods.

In addition, when joining numeric strings, special care must be taken with the normal typescript/javascript operators. The StringBuilder class will treat all as strings and not attempt a numeric conversion and add values.

It can be expanded upon greatly to fit your needs.

export class StringBuilder
 {
    strArray: Array<string> = new Array<string>();
    constructor()
    {

    }
    Get(nIndex:number): string
    {
      let str:string = null;
      if( (this.strArray.length > nIndex) && (nIndex >= 0) )
      {
         str = this.strArray[nIndex];
      }
      return(str);
    }
    IsEmpty(): boolean
    {
       if(this.strArray.length == 0) return true;
       return(false);
    }
    Append(str: string): void
    {
        if(str != null)
           this.strArray.push(str);
    }
    ToString(): string
    {
        let str:string = this.strArray.join("");
        return(str);
    }

    ToArrayString(delimeter: string): string
    {
        let str:string = this.strArray.join(delimeter);
        return(str);
    }

    Clear()
    {
        this.strArray.length = 0;
    }
 }


texts: Reading a certain number of lines from a file

texts:
def getLinesFromFile(file:File, linesToGet:Int): List[String] ={
    val bufferedSource = Source.fromFile(file)
    val lb = ListBuffer[String]()
    try {
      val lines = bufferedSource.getLines()
      var counter = 0
      while (lines.hasNext && counter < linesToGet) {
        counter += 1
        lb.append(lines.next())
      }
    } finally {
      bufferedSource.close()
    }
    lb.toList
  }

I am trying to retrieve a certain amount of lines from a read text file, and return each line as a List back to the user. Validation for the file actually being a .txt file is done prior to this call, and I can say with certainty that each line won't be longer than @500 characters.

My primary concern is I'm wondering if there any reason this code would create any memory leaks?


texts:
From Simple IO to Monad Transformers presents the following exercise:

  The guts of our algorithm will be a function next_coin which does something like this

  (amt,coins) -> (amt,coins)

  Each transition either dispenses a coin and decreases amt accordingly, or  removes the largest coin from coins.  The first alternative takes precedence whenever amt is not smaller than the largest coin. Here is an example of how this sequence of pairs represents coin dispensing. Start with (11,[10,1]) which means we must make change for 11 cents with a dime and a penny.

  The first step is to (1,[10,1]) representing that a dime has been dispensed. The second step is to (1,[1]) representing that we have recognized dimes are no longer useful. The last step is to (0,[1]) representing that a penny has been dispensed.

Code

import Control.Monad.State
import Data.List

type Coins = [Int]

type StMach a = StateT Coins IO a

main :: IO ()
main =
  let
    coins = [1,5,10,25]
  in
    do
      putStrLn "Enter an amount: "
      input  <- getLine
      number <- return $ read input
      make_change coins number

make_change :: Coins -> Int -> IO () -- IO (Int, Coins)
make_change coins amt = runStateT (recurs amt) coins *> return ()

-- author: Monad Book
recurs :: Int -> StMach Int
recurs amt =
    if amt == 0
        then return amt
        else next_coin amt >>= recurs

data CoinState a = CoinLargerThanAmount a | FoundChange a | PennyMatch

--if amount is less than (max coins), then delete the max from coins
--otherwise subtract amount and delete that elem from coins (unless it's 1)
next_coin :: Int -> StMach Int
next_coin amt = do
  coinsLeft <- get
  dispense amt coinsLeft
  state $ \coins ->
            case coinState coins amt of
        PennyMatch             -> (amt-1, coins)
        FoundChange a          -> (amt-a, delete a coins)
        CoinLargerThanAmount a -> (amt,   delete a coins)

coinState :: Ord a => [a] -> a -> CoinState a
coinState xs a =
 let
  largerCoinInChange = find (> a) xs
 in
  case largerCoinInChange of
    Just a  -> CoinLargerThanAmount a
    Nothing -> case  filter (<= a) xs of
        [] -> PennyMatch
        as -> FoundChange (maximum as)

-- author: Monad Book
dispense :: Int -> Coins -> StMach ()
dispense i coins =
   ( lift $
      putStrLn ( "dispense "
                  ++(show i)
                  ++" cents"
                  ++ remaining)
    )
   where
     cents = (if i==1
                then " cent"
                else " cents") ++ remaining
     remaining = " with remaining coins: " ++ (show coins)

Code

*Main Control.Monad.State> main
Enter an amount:
16
dispense 16 cents with remaining coins: [1,5,10,25]
dispense 16 cents with remaining coins: [1,5,10]
dispense 6 cents with remaining coins: [1,5]
dispense 1 cents with remaining coins: [1]

*Main Control.Monad.State> main
Enter an amount:
10
dispense 10 cents with remaining coins: [1,5,10,25]
dispense 10 cents with remaining coins: [1,5,10]

*Main Control.Monad.State> main
Enter an amount:
1
dispense 1 cents with remaining coins: [1,5,10,25]
dispense 1 cents with remaining coins: [1,10,25]
dispense 1 cents with remaining coins: [1,25]
dispense 1 cents with remaining coins: [1]


texts: Specify table data in code, reference objects

texts:
public final class Descriptors {
public static final EnumValueDescriptor TIME_SETTING = new EnumValueDescriptor(
            R.string.pref_label_time_setting,
            Measures.TIME_SETTING_12, R.string.pref_time_setting_12,
            Measures.TIME_SETTING_24, R.string.pref_time_setting_24);

public static final EnumValueDescriptor MEASURE_BG = new EnumValueDescriptor(
        R.string.pref_label_bg,
        Measures.BG_MMOL_L, R.string.measure_mmol_l,
        Measures.BG_MG_DL, R.string.measure_mg_dl);

public static final EnumValueDescriptor MEASURE_СH = new EnumValueDescriptor(
        R.string.pref_label_ch,
        Measures.CH_G, R.string.measure_g,
        Measures.CH_EXCH, R.string.measure_exch);

    // Is there a better way to specify table data?
public static final NumericValueDescriptor TBG_MMOL_L = new NumericValueDescriptor(
        R.string.pref_label_target_blood_glucose,
        ValueFormat.ONE_SIGNIFICANT_DIGIT,
        0.0f,
        40.0f,
        0.1f,
        R.string.measure_mmol_l);

public static final NumericValueDescriptor TBG_MG_DL = new NumericValueDescriptor(
        R.string.pref_label_target_blood_glucose,
        ValueFormat.INT,
        0f,
        300f,
        1f,
        R.string.measure_mg_dl);

public static final NumericValueDescriptor CF_MMOL_L_U = new NumericValueDescriptor(
        R.string.pref_label_correction_factor,
        ValueFormat.ONE_SIGNIFICANT_DIGIT,
        0.1f,
        99.0f,
        0.1f,
        R.string.measure_mmol_l_u);

public static final NumericValueDescriptor CF_MG_DL_U = new NumericValueDescriptor(
        R.string.pref_label_correction_factor,
        ValueFormat.INT,
        1f,
        99f,
        1f,
        R.string.measure_mg_dl_u);

public static final NumericValueDescriptor MF_G_U = new NumericValueDescriptor(
        R.string.pref_label_meal_factor,
        ValueFormat.ONE_SIGNIFICANT_DIGIT,
        0.1f,
        99.0f,
        0.1f,
        R.string.measure_g_u);

public static final NumericValueDescriptor MF_U_EXCH = new NumericValueDescriptor(
        R.string.pref_label_meal_factor,
        ValueFormat.INT,
        1f,
        99f,
        1f,
        R.string.measure_u_exch);

public static final int TYPE_TBG_MMOL_L = 0;
public static final int TYPE_TBG_MG_DL = 1;
public static final int TYPE_CF_MMOL_L_U = 2;
public static final int TYPE_CF_MG_DL_U = 3;
public static final int TYPE_MF_G_U = 4;
public static final int TYPE_MF_U_EXCH = 5;

    // Actually this is mapping of TYPE_TBG_MMOL_L  to an object, how better link constants above with objects?
public static final NumericValueDescriptor[] NUMERIC_DESCRIPTORS = {
    TBG_MMOL_L,
    TBG_MG_DL,
    CF_MMOL_L_U,
    CF_MG_DL_U,
    MF_G_U,
    MF_U_EXCH
};
 }


texts: Checking the neighbor of the current cell

texts:
This is just checking the parameter you enter is a neighbour of the current Cell (which is obtained using getRow() and getColumn()).

Is there an easier way of doing this? How could I make this more compact and efficient?

public boolean isNeighbourOf(Cell c){

 boolean check = false;

 //check for not neighbours
 if(c.getRow() == getRow() && c.getColumn() == getColumn()){
     check = false;
 }

 else if(c.getRow() == getRow() - 1 && c.getColumn() == getColumn() - 1){
     check = false;
 }

 else if(c.getRow() == getRow() + 1 && c.getColumn() == getColumn() - 1){
     check = false;
 }

 else  if(c.getRow() == getRow() - 1 && c.getColumn() == getColumn() + 1){
     check = false;
 }

 else if(c.getRow() == getRow() + 1 && c.getColumn() == getColumn() + 1){
     check = false;
 }

 //check for neighbours
  else if(c.getRow() == getRow() - 1 && c.getColumn() == getColumn()){
     check = true;
 }
  else if(c.getRow() == getRow() + 1 && c.getColumn() == getColumn()){
         check = true;
  }
  else if(c.getRow() == getRow() && c.getColumn() == getColumn() + 1){
         check = true;
  }
  else if(c.getRow() == getRow() && c.getColumn() == getColumn() - 1){
         check = true;
  }
  return check;
}


texts: Algorithm that parses through input of points and finds distance

texts:
I'm wondering if someone could take some time to review this script. I'm parsing through a list of points of any length and calculating the distance. I'm wondering how to make my code better/more efficient (something I'm working on). A sample input file would be like so:

300.754178236262248 103.453277023380423 0,276.62980277988612 90.123295023340319 0,269.345711570634421 103.319531391674346 0,293.447811515317824 116.649513392506364 0,300.754178236262248 103.453277023380423 0

I'm not sure why the zeros are there; these are from the spacenet label csv's.

And this is my code:

import math

def calc(x1, y1, x2, y2):
    dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
    return dist

li = []
res = []
with open("/Users/jin/points.txt") as filestream:
    for line in filestream:
        temp = line.split(",") #splits by the comma in a single list

        for i in temp:
            temp = i.split(" ") #splits by spaces to individual lists of points
            li.append(temp) #list of lists containing each point
    # for item in li:
    #   x1 = item[1]
    #   y1 = item[0]

    # for item in li:
    #   for pt in item:
    #       print pt

    for index in range(len(li)-1):
        one = li[index]
        two = li[index+1]
        x1 = float(one[0])
        y1 = float(one[1])
        x2 = float(two[0])
        y2 = float(two[1])
        res.append(calc(x1, y1, x2, y2))
    print res


texts: Code for creating a dialog for choosing a date

texts:
I have code that creates an AlertDialog to select a date by a user. I ran into a problem that this code began to take up a lot of space. Could you offer ideas on how to shorten this code / put it into different methods. Thanks in advance

   public static AlertDialog getTextDialog(Context ctx, final OnSelectNewValueListener calendarListener) {
    View view = LayoutInflater.from(ctx).inflate(R.layout.calendar_dialog, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    builder.setView(view);
    CalendarView calendar = view.findViewById(R.id.calendarView);
    TextView yearTextView = view.findViewById(R.id.year);
    TextView dateTextView = view.findViewById(R.id.date);
    Button cancel = view.findViewById(R.id.cancel);
    Button ok = view.findViewById(R.id.ok);

    AlertDialog calendarAlertDialog = builder.create();

    LocalDate currentDate = getLocalDateFromMilli(calendar.getDate());
    showCurrentDate(currentDate, yearTextView, dateTextView);

    calendar.setOnDateChangeListener((view1, year, month, dayOfMonth) -> {
        LocalDate selectDate = LocalDate.of(year, Month.values()[month], dayOfMonth);
        showCurrentDate(selectDate, yearTextView, dateTextView);
        calendar.setDate(new GregorianCalendar(year,month,dayOfMonth).getTimeInMillis());
    });

    cancel.setOnClickListener(v -> {
        calendarAlertDialog.cancel();
    });

    ok.setOnClickListener(v->{
        calendarListener.onCalendarSelect(getLocalDateFromMilli(calendar.getDate()));
        calendarAlertDialog.cancel();
    });

    return calendarAlertDialog;
}

private static void showCurrentDate(LocalDate selectDate, TextView yearTextView, TextView dateTextView) {
    yearTextView.setText(String.valueOf(selectDate.getYear()));
    dateTextView.setText(selectDate.format(dateFormatMedium));
}

@Override
public void onCalendarSelect(LocalDate time) {
    date.setText(dateFormatShort.format(time));
}

OnSelectNewValueListener

interface OnSelectNewValueListener {
    void onCalendarSelect(LocalDate time);
}

Imports:

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;

import com.sgc.weightcontrol.R;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import butterknife.BindView;
import butterknife.ButterKnife;


texts: Spawning multiple child processes to preview Vue.js projects

texts:
Context:
I'm making a Codepen-like app but I want it to support sophisticated JS libraries/frameworks like Vue or Angular 2+ for example. I want to have a live preview of my snippet which updates in a reasonable time. So I came up with an idea that when I create a new snippet I'll initialize a blank starter project on my backend server and run npm start to have Hot reload enabled. When I update the code of my snippet on the frontend side, I'm making a request to the backend server and update files in the starter project which is making the Hot reload refresh the live preview. This is what I got at the moment and it is working.

What I came up with:
This is my function which first copies the starter project to the new location, searches for the free port and eventually spawns npm start:

function createStarter(request, snippetId, callback) {

    const fs = require('fs');
    const path = require('path');
    const portfinder = require('portfinder');
    const { technology } = request.params;

    const snippetPath = path.join(__dirname, '../../static/snippets/vue', snippetId.toString());

    spawnProcess('cp', ['-r', 'vue-starter/', snippetPath], { cwd: snippetPath.slice(0, snippetPath.lastIndexOf('/')) })
        .then(async () => {

            const lastPort = process.env.STARTER_LAST_USED_PORT || 1e4;
            const port = await portfinder.getPortPromise({ port: +lastPort + 1 }).catch(console.error);
            process.env.STARTER_LAST_USED_PORT = port;

            const packageJson = require(`${snippetPath}/package.json`);
            packageJson.scripts.dev += ` --port ${port}`;

            fs.writeFileSync(`${snippetPath}/package.json`, JSON.stringify(packageJson), 'utf8');

            console.log(`Starting project ${snippetId} at port ${port}`);

            spawnProcess('npm', ['start'], { cwd: snippetPath });
        })
        .catch(console.error);

    callback();
}

where spawnProcess() is just a simple helper which executes spawn(...args) and binds events to the streams.

Actual question:
Is it a good idea to have multiple child processes spawned in parallel? I'm not worried about cp -r from the function above because it's short command and lasts for a few seconds. What I am worried about is npm start which potentially can last for even hours and I'm wondering if this is a good practice to spawn potentially, say, 50 or 100 child processes with npm start running for a long time before it'll be killed. I was thinking about setting a timeout for this command and kill it after about a minute but it can cause another issue which is re-spawning a child process multiple times which requires more resources.


texts: What is wrong with my knapsack alghoritm?

texts:
My alghoritm works and produces good result, but it takes too much time(6 s for 300 input items that is too much for branch and bound alghoritm), so I have maken a mistake somewhere, but really can't find it :( It is supposed to be depth-first branch and bound. Any help would be appreciated!

public void knapsack2(Item[] items, int maxWeight)
{
    Item firstNode, secondNode, tempNode;

    int weight, bestValue = 0, bestWeight = 0;

    Stack stack = new Stack();

    firstNode = items[0];

    firstNode.setBound(bound(firstNode, maxWeight, items));

    stack.push(firstNode);

    Item bestNode = firstNode;

    while(!stack.isEmpty())
    {
        tempNode = (Item) stack.pop();
        weight = tempNode.getWeight();

        if( tempNode.getBound() > bestValue)
        {
            firstNode = new Item();
            firstNode.setLevel(tempNode.getLevel() + 1);
            firstNode.setValue(tempNode, items[firstNode.getLevel()].getValue());
            firstNode.setWeight(weight + items[firstNode.getLevel()].getWeight());
            firstNode.setBound(bound(firstNode, maxWeight, items));

            if(firstNode.getValue() > bestValue && firstNode.getWeight() <= maxWeight)
            {
                bestValue = firstNode.getValue();
                bestWeight = firstNode.getWeight();

                bestNode = firstNode;

            }

            if(firstNode.getBound() > bestValue)
            {
                stack.push(firstNode);
            }

            secondNode = new Item();
            secondNode.setLevel(tempNode.getLevel() + 1);
            secondNode.setValue(tempNode, 0);
            secondNode.setWeight(weight);
            secondNode.setBound(bound(secondNode, maxWeight, items));

            if(secondNode.getBound() > bestValue)
            {
                stack.push(secondNode);
            }
        }
    }

    System.out.println("Best value " + bestValue);
}

Bound function:

    public float bound(Item item, int maxWeight, Item[] items)
    {
    int j, k;
    int totalWeight;
    float result;

    if(item.getWeight() > maxWeight)
    {
        return 0;
    }
    else
    {
        result = item.getValue();
        j = item.getLevel() + 1;
        totalWeight = item.getWeight();

        while(j < items.length && (totalWeight + items[j].getWeight() <= maxWeight))
        {
            totalWeight += items[j].getWeight();
            result += items[j].getValue();
            j++;
        }
    }

    k = j;

    if(k < items.length)
    {
        result = result + (maxWeight - totalWeight) * (items[k].getValue() / (float) items[k].getWeight());
        return result;
    }

    return 0;
}


texts:
I'm studying C on K&R and I solved exercise 2.08:

  Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n positions

I've tested my code with some bit patterns and it seems to work, but I'm not sure that this solution covers all possible cases.

What do you think about this code?

unsigned rightrot(unsigned x, int n)
{
    int size;
    unsigned y;

    size = 0;
    y = x;

    while (y != 0) {
    y = y << BYTESIZE;
    size++;
    }
    size = size * BYTESIZE;

    return (x << (size-n)) | (x >> n);
}

Here is the main

#include <stdio.h>

#define BYTESIZE 8

unsigned rightrot(unsigned x, int n);

int main(void)
{
     unsigned x;
     int n;

     x = 0x23acb;
     n = 2;

     printf("%x\n", rightrot(x, n));

     return 0;
}


texts: Client/Server, Asynchronous ping-pong exchange

texts:
I'm mainly wondering about whether or not I have used the (TAP) async/await pattern correctly. I get a bunch of these warnings, "Because this call is not awaited, execution of the current method continues before the call is completed.", however that sounds like exactly what I want. Which is for the server to be able to handle clients independently and asynchronously.

As a side note, I know it's bad for performance to re-initialize the streams in for example HandleConnection, I just kept it that way for brevity's sake.

Client.cs:

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

class Client {
    TcpClient tcpClient;
    public void Connect() {
        ConnectAsync();
    }

    public async void Ping() {
        await SendMessage("Ping!");
    }

    private async Task ConnectAsync() {
        tcpClient = new TcpClient();
        await tcpClient.ConnectAsync(IPAddress.Parse("127.0.0.1"), 3344);
        MainWindow.ClientLog("Connected to server!");

        HandleConnection(tcpClient);
    }

    private async Task HandleConnection(TcpClient tcpClient) {
        NetworkStream ns = tcpClient.GetStream();
        StreamReader sr = new StreamReader(ns);
        string message = await sr.ReadLineAsync();
        MainWindow.ClientLog("Received message from server: " + message);

        HandleConnection(tcpClient);
    }

    private async Task SendMessage(string message) {
        NetworkStream ns = tcpClient.GetStream();
        StreamWriter sw = new StreamWriter(ns);
        await sw.WriteLineAsync(message);
        await sw.FlushAsync();
        MainWindow.ClientLog("Sent Ping! to server.");
    }
}

Server.cs:

using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

class Server {
    List<TcpClient> connectedClients;
    public void Host() {
        connectedClients = new List<TcpClient>();
        HostAsync();
    }

    private async Task HostAsync() {
        IPEndPoint local = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3344);
        TcpListener mainListener = new TcpListener(local);

        mainListener.Start();
        MainWindow.ServerLog("Server started.");
        while(true) {
            TcpClient client = await mainListener.AcceptTcpClientAsync();
            MainWindow.ServerLog("Client connected!");

            connectedClients.Add(client);
            HandleClient(client);
        }
    }

    private async Task HandleClient(TcpClient client) {
        NetworkStream ns = client.GetStream();
        StreamReader sr = new StreamReader(ns);
        string message = await sr.ReadLineAsync();
        MainWindow.ServerLog("Message from client nr. " + connectedClients.IndexOf(client) + ": " + message);

        if (message == "Ping!") {
            await SendMessage(client, "Pong!");
        }

        HandleClient(client);
    }

    private async Task SendMessage(TcpClient client, string message) {
        NetworkStream ns = client.GetStream();
        StreamWriter sw = new StreamWriter(ns);
        await sw.WriteLineAsync(message);
        await sw.FlushAsync();
        MainWindow.ServerLog("Sent message to client: " + message);
    }

    private async Task SendMessages(IEnumerable<TcpClient> clients, string message) {
        foreach (TcpClient client in clients) {
            SendMessage(client, message);
        }
    }
}


texts: Custom WordPress SQL query to get posts and users using term_id

texts:
I have a WordPress site with multiple custom post types, that all share a common custom taxonomy. Users can also be tagged with terms from this taxonomy.

After giving up on JOINS, I managed to conjure the following query to get all of the posts and users based on a term_ID.

global $wpdb;
$sql = "
    SELECT
        P.ID,
        P.post_type
    FROM
        $wpdb->posts P,
        $wpdb->term_relationships TR,
        $wpdb->term_taxonomy TT,
        $wpdb->terms T
    WHERE
        P.ID = TR.object_id AND TR.term_taxonomy_id = TT.term_taxonomy_id AND TT.term_id = T.term_id AND T.term_id = %d AND NOT P.post_status = 'trash'
    UNION
    SELECT
        U.ID,
        U.user_email
    FROM
        $wpdb->users U,
        $wpdb->term_relationships TR,
        $wpdb->term_taxonomy TT,
        $wpdb->terms T
    WHERE
        U.ID = TR.object_id AND TR.term_taxonomy_id = TT.term_taxonomy_id AND TT.term_id = T.term_id AND T.term_id = %d
";
$query = $wpdb->get_results( $wpdb->prepare( $sql, $term_id, $term_id ), OBJECT );

This works and gets the job done, but I have a feeling that there's room for improvement (performance-/efficiency-wise, mostly). Any suggestions?


texts: Calculating the point of intersection of two parabolas

texts:
I recently wrote a function to calculate the intersection point(s) of two parabolas.  Working it out on paper was a nightmare, but I eventually did it (I think it's correct), and ended up with:

\$ x = \frac{\sqrt{c_2 - c_1 + \frac{b_1^2}{4a_1} - \frac{b_2^2}{4a_2} + E}}{\sqrt{a_2 - a_1}} - \frac{b1 - b2}{2(a1 - a2)} \$

with

\$ E = \frac{b_1^2a_2^3(a_2 - 2a_1^2) - a_1^3b_2^2(a_1 - 2a_2^2) - 2a_1^2a_2^2b_2(b_2 - b_1)}{(4a_1^2a_2^2)(a_1 - a_2)^2} \$

For any two parabolas \$ a_1x^2 + b_1x + c_1 = 0\$ and \$a_2x^2 + b_2x + c_2 = 0\$.

That can't be the fastest way to do it, I must be missing something. Does anyone know of any better ways I could implement parabola to parabola intersection point calculations?

The function I wrote is below:

def parabola_to_parabola_poi(a1, b1, c1, a2, b2, c2):
    """
    Calculate the intersection point(s) of two parabolas.
    """
    a1_sqrd, a2_sqrd = a1*a1, a2*a2
    b1_sqrd, b2_sqrd = b1*b1, b2*b2
    c1_sqrd, c2_sqrd = c1*c1, c2*c2

    E1 = b1_sqrd*a2_sqrd*a2*(a2 - 2*a1_sqrd)
    E2 = a1_sqrd*a1*b2_sqrd*(a1 - 2*a2_sqrd)
    E3 = 2*a1_sqrd*a2_sqrd*b2*(b2 - b1)
    E4 = (4*a1_sqrd*a2_sqrd)*(a1 - a2)*(a1 - a2)

    E = (E1 - E2 - E3)/E4

    F = (c2 - c1 + b1_sqrd/(4*a1) - b2_sqrd/(4*a2) + E)/(a2 - a1)
    G = (b1 - b2)/(2*(a1 - a2))

    if not F:
        px = math.sqrt(F) - G
        py = a1*px*px + b1*px + c1
        return [
            (px, py)
            ]
    elif F < 0:
        return []
    sqrt_F = math.sqrt(F)

    px1 = sqrt_F - G
    px2 = -sqrt_F - G

    py1 = a1*px1*px1 + b1*px1 + c1
    py2 = a1*px2*px2 + b1*px2 + c1

    return [
        (px1, py1),
        (px2, py2)
        ]


texts: Taking the first few items of a list until a target sum is exceeded

texts:
I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt

  Write a procedure that takes a list of numbers, nums, and a limit,
  limit, and returns a list which is the shortest preﬁx of nums the sum
  of whose values is greater than limit. Use for. Try to avoid using
  explicit indexing into the list.

I wrote the following simple procedure

def numberlist(nums,limit):
    sum=0
    i=0
    for i in nums:
        sum=sum+i
        if sum>limit:
            return i
        else:
            print i

It gets the job done, but the division of labor between if and else seems inelegant, as does the use of both return and print. Is there a better way to structure this basic loop?


texts:
I finished the grading exercise from this list of beginner c++ exercises. I have a (probably unfounded) dislike of if elses to dispatch a grade to a note so contrarily to this similar question I implemented a vector of tuples to which I compare the received note. After completion, I realized that it probably amounts to mostly the same thing, if not worse (I am still comparing the value with an if).

I looking for any feedback, but possibly something about:

Is the vector of tuple an unnecessary overhead over the simple if/else?
Is it actually slower, or does compilation optimizes execution?
In this case it probably doesn't matter because the grade set is small, but is this approach considered a good/correct practice if we were to have a bigger set?

#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

char dispatchGrade(int grade) {
    vector<tuple<int, char>> fork {
            tuple<int, char> {90, 'A'},
            tuple<int, char> {80, 'B'},
            tuple<int, char> {70, 'C'},
            tuple<int, char> {60, 'D'},
            tuple<int, char> {0, 'E'},
    };
    for (vector<tuple<int, char>>::size_type i = 0; i != fork.size(); i++) {
        if (grade >= get<0>(fork[i])) {
            return get<1>(fork[i]);
        }
    }
}

int main() {
    int grade;
    char note;
    cout << "Hello, World! enter your grade:" << endl;
    cin >> grade;
    if (!cin.fail() && grade > -1 && grade < 101) {
        cout << "That is a valid grade. ";
        note = dispatchGrade(grade);
        cout << "That grade is good for a " << note << endl;
    } else {
        cout << "That is not a valid grade." << endl;
    }
}

cmake_minimum_required(VERSION 3.8)
project(grades)

set(CMAKE_CXX_STANDARD 17)

set(SOURCE_FILES main.cpp)
add_executable(grades ${SOURCE_FILES})


texts: Fetching a set of event IDs from a database based on a set of company IDs

texts:
The following code fetches a set of company IDs from a database if there are any events associated with a company that has a missing property. Because the set of company IDs is embedded into the SQL query using parameters, and the number of parameters may exceed the maximum for the RDBMS / database driver, the set is partitioned into maximal subsets.

Performance aside, in terms of maintainability and ability to debug, is the following "too Linq-y"?

HashSet<int> missingCompanyIds =
    companyEvents
        .Select(ev => ev.CompanyId).ToHashSet()
        .Partition(DataContext.MaxAvailableSqlParameters(usedParameters), true)
        .SelectMany(companyIdsPartition =>
                missingEventsQuery                                           // linq-to-sql
                    .Where(ev => companyIdsPartition.Contains(ev.CompanyId)) // linq-to-sql
                    .Select(ev => ev.CompanyId)                              // linq-to-sql
                    .Distinct())                                             // linq-to-sql
        .ToHashSet();

If any of the database side-effects of the query methods cause a crash, perhaps this is harder to debug, I don't know. I am able to set breakpoints inside lambdas, but my local environment might contain fewer of the objects I wish to inspect when debugging (e.g. the missingEventsQuery)? I'm unsure if these concerns would be relevant in practice.

Would there be any advantages in the case above if some of the .Select()s were written as for loops?