texts:
I'm taking my first steps in the Scala world, though I'm not wholly unfamiliar with functional style.

Apparently one way of calculating Pi is to sum the terms of the infinite series:

$$4 * (\frac{1}{1} - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} \dots)$$

So I wrote this simple implementation in a Scala worksheet:

def calculatePi(tolerance: Double): Double = {
  val s1 = Iterator.continually(List(4.0, -4.0)).flatten
  val s2 = Iterator.from(0).map(_ * 2 + 1)
  s1.zip(s2).map(p => p._1 / p._2).takeWhile(math.abs(_) > tolerance).sum
}

var tolerance = 1.0
while (tolerance > .0000001) {
  val approximation = calculatePi(tolerance)
  val error = math.abs(math.Pi - approximation)
  println(s"tol:$tolerance calc:$approximation error:$error within:${error < tolerance}")
  tolerance /= 10
}

Any thoughts? If possible can anyone address these:

Is Iterator really the best choice here? Stream? Something else?
I'm particularly unhappy about the snippet map(p => p._1 / p._2); it feels like I'm missing a better way to do that.
Is there a better/different way to do the tolerance while loop?
From an algorithm standpoint, I have to decide when to stop taking values from the sequence. Is math.abs([TERM]) < tolerance a good stopping point? Or is there a better, earlier termination point?

Note: I don't really care about the println statement. It's kinda ugly but it's just there for diagnostics.


texts: Combining two clock tick vectors with NumPy

texts:
I have two long (7683200 length) 1D arrays corresponding to two clock cycles, that I wish to combine into single 1D array. The clock_ticks_fine cycles between 0-255, and corresponds to a coarse division of 7.5 msec, with the reset to 0 signified by a 1 in the clock_ticks_coarse array.

I would like this to be much much faster (I have many of these files), but I can't work out how to vectorise the code. I don't care about the clock_ticks_fine value when clock_ticks_coarse is equal to 1.

First 100 datapoints in both arrays using a basic for loop:

corse_div = 7.5 # in msec
fine_div = 7.5/255.0

clock_ticks_fine = np.array([ 36,   1,  11,  22,  39,  66,  71,  78, 107, 121, 137, 142, 163,
       190, 211, 212, 239, 246,  36,   7,  13,  47,  56,  73,  78, 110,
       128, 143, 146, 175, 192, 203, 204, 239,  36,   0,  13,  19,  43,
        58,  74,  81, 111, 130, 139, 139, 175, 189, 208, 209, 238,  36,
         2,  19,  22,  39,  66,  76,  79, 101, 130, 145, 146, 163, 184,
       201, 214, 227, 255,  36,   9,  20,  45,  64,  75,  78, 103, 122,
       143, 144, 175, 184, 205, 208, 235, 250,  36,  14,  17,  46,  62,
        71,  72, 103, 119, 143, 144, 175, 186, 200])

clock_ticks_coarse = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0])

count = -1
for i,boolean in enumerate(clock_ticks_coarse):
    if boolean == 1:
        count +=1
        clock_ticks_coarse[i] = count
    else:
        clock_ticks_coarse[i] = boolean+count

fine_time_array = clock_ticks_fine*fine_div
coarse_time_array = clock_ticks_coarse*corse_div
time_array = fine_time_array+coarse_time_array

np.set_printoptions(precision=3, suppress = True)
print time_array

Output:

[  1.059   0.029   0.324   0.647   1.147   1.941   2.088   2.294   3.147
   3.559   4.029   4.176   4.794   5.588   6.206   6.235   7.029   7.235
   8.559   7.706   7.882   8.882   9.147   9.647   9.794  10.735  11.265
  11.706  11.794  12.647  13.147  13.471  13.5    14.529  16.059  15.
  15.382  15.559  16.265  16.706  17.176  17.382  18.265  18.824  19.088
  19.088  20.147  20.559  21.118  21.147  22.     23.559  22.559  23.059
  23.147  23.647  24.441  24.735  24.824  25.471  26.324  26.765  26.794
  27.294  27.912  28.412  28.794  29.176  30.     31.059  30.265  30.588
  31.324  31.882  32.206  32.294  33.029  33.588  34.206  34.235  35.147
  35.412  36.029  36.118  36.912  37.353  38.559  37.912  38.     38.853
  39.324  39.588  39.618  40.529  41.     41.706  41.735  42.647  42.971
  43.382]


texts: Orchestrating an unknown number of goroutines

texts:
I recently wrote a piece of code to parallelise some code with goroutines and I was wondering if I could get some feedback. It looks overly complex... but I'm not sure how I could make it simpler.
It's self contained, so you can just copy-paste it into the Go Playground and run it. Here's a link if anybody's interested: https://play.golang.org/p/Dyg4kZXCS9b
package main

import (
    "fmt"
    "sync"
)

func main() {
    fmt.Println("Hello World")
    input := []string{"foo", "bar", "baz"}

    products, err := findProducts(input)
    if err != nil {
        panic(err)
    }

    fmt.Printf("\n %d", len(products))
}

type productInfo struct{}

func findProduct(productCode string) (*productInfo, error) {
    return &productInfo{}, nil
}

func findProducts(productCodes []string) ([]*productInfo, error) {
    wg := sync.WaitGroup{}
    wg.Add(len(productCodes))

    output := make(chan []*productInfo)
    input := make(chan *productInfo)

    errInput := make(chan error)
    errOutput := make(chan []error)

    // consumer goroutine
    go func(input <-chan *productInfo, output chan<- []*productInfo, errInput <-chan error, errOutput chan<- []error, wg *sync.WaitGroup) {
        var results []*productInfo
        var errors []error

        for {
            select {
            case result, ok := <-input:
                if !ok {
                    input = nil
                    break
                }

                wg.Done()
                fmt.Println("input received through channel: appending productInfo")
                results = append(results, result)
            case err, ok := <-errInput:
                if !ok {
                    errInput = nil
                    break
                }

                wg.Done()
                fmt.Println("error received through channel: appending err")
                errors = append(errors, err)
            }

            if input == nil && errInput == nil {
                break
            }
        }

        output <- results
        errOutput <- errors
    }(input, output, errInput, errOutput, &wg)

    for _, code := range productCodes {
        go func(code string, input chan<- *productInfo, errInput chan<- error) {
            p, err := findProduct(code)
            if err != nil {
                fmt.Println("sending error through channel")
                errInput <- err
            } else {
                fmt.Println("sending input through channel")
                input <- p
            }
        }(code, input, errInput)
    }

    wg.Wait()
    close(input)
    close(errInput)

    products := <-output
    errs := <-errOutput

    // Just return the first one for simplicity
    if len(errs) > 0 {
        return nil, errs[0]
    }

    return products, nil
}
```


texts: Managing database connections for unit tests

texts:
I have a series of unit test classes that use various connections to a database. Every test class uses two methods with the JUnit annotations BeforeClass and AfterClass to start and stop the database connections like so:

public class AccountTest
{
    private static DatabaseConnection _adminConnection;
    private static DatabaseConnection _salesUserConnection;
    private static DatabaseConnection _salesManagerConnection;
    private static DatabaseConnection _financeUserConnection;

    private static DatabaseHelper _helper;

    private static ArrayList<DatabaseConnection> _connections = new ArrayList<>();

    @BeforeClass
    public static void CreateTestEnvironment()
    {
        _helper = new DatabaseHelper();

        _adminConnection = _helper.DoLogin(SessionType.Administrator);
        _salesUserConnection = _helper.DoLogin(SessionType.SalesUser);
        _salesManagerConnection = _helper.DoLogin(SessionType.SalesManager);
        _financeUserConnection = _helper.DoLogin(SessionType.FinanceUser);

        _connections.add(_adminConnection);
        _connections.add(_salesUserConnection);
        _connections.add(_salesManagerConnection);
        _connections.add(_financeUserConnection);
    }

    @AfterClass
    public static void DestroyTestEnvironment()
    {
        for(DatabaseConnection connection: _connections)
        {
            _helper.DoLogout(connection);
        }
    }
}

I would then pass the connection to my helper object in a test like this for example:

@Test
public void AdministratorCanCreateAccount()
{
    Account account = new Account();
    account = _helper.CreateObject(account, _adminConnection);

    Assert.assertNotNull(account.getId());
}

The login/logout process in CreateTesEnvironment and DestroyTestEnvironment is duplicated throughout many different test classes, with some classes having more connections than others.

How could I manage the connections in a better way so that I'm not just copying and pasting the same BeforeClass and AfterClass code every time but keep them easily accessible to the unit tests?


texts: Quicksort in JavaScript, using nested functions

texts:
I come from Java/Swift environment. So, I'm used to show the user of my code only "what is necessary".

For JavaScript I use Visual Code.

When I try to use the Intellisense feature, it shows all my functions/methods when I import it.

So, to hide the unnecessary functions, I opted for using nested functions.

Check out this quicksort code:

/**
 * Sorts the Array in-place
 *
 * @param {Array.<Number | String>} array Array to be sorted
 */
function sort(array) {
    quickSort(array, 0, array.length - 1);

    /**
     * Quicksort implementation
     *
     * @param {Array.<Number | String>} array
     * @param {Number} start Start index of the array for quicksort
     * @param {Number} end End index of the array for quicksort
     */
    function quickSort(array, start, end) {
        if (start < end) {
            let pivot = partition(array, start, end);
            quickSort(array, start, pivot - 1);
            quickSort(array, pivot + 1, end);
        }

        /**
         * Partitions the array for Quicksort
         *
         * @param {Array.<Number | String>} array
         * @param {Number} left Starting index of starting of array/sub-array
         * @param {Number} right Ending index of starting of array/sub-array
         * @returns {Number} Returns pivot index
         */
        function partition(array, left, right) {
            let pivot = array[right];
            let i = left - 1;
            for (var j = left; j < right; j++) {
                if (array[j] <= pivot) {
                    i++;
                    let temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;
                }
            }
            let temp = array[i + 1];
            array[i + 1] = array[right];
            array[right] = temp;
            return i + 1;
        }
    }

}

Is this nesting appropriate? Because I(beginner) feel like if the nested functions are big, the readability(I mean like figuring out what the code is doing) is an issue.

Or should I just follow the classic _ before the function names to indicate it as a private or not meant to be used by the user?

A simple code breaking example:

  For the user of the sort(), partition() and quickSort() is an
  unnecessary functions. Which in-turn can cause collisions if the user
  names their function partition() (because I might not have mentioned
  partition() in my API as it is not usable on its own).

And also any advice to improve the above code is welcome.


texts:
This example comes from a code snippet posted on Stack Overflow:

private double brickVal(Color c) {
    if (c == Color.RED) {
        return 10.0;
    } else if (c == Color.ORANGE) {
        return 8.0;
    } else if (c == Color.YELLOW) {
        return 6.0;
    } else if (c == Color.GREEN) {
        return 4.0;
    } else if (c == Color.CYAN) {
        return 2.0;
    } else if (c == Color.MAGENTA) {
        return 1.0;
    } else {
        return 1.0;
    }
}

Is the use of == here correct / best practice?


texts:
I want to generate a 'dictionary' containing all 8 character permutations of upper-case letters such that the output file looks like:

AAAAAAAA
AAAAAAAB
AAAAAAAC
...
ZZZZZZZZ

I came up with this solution that uses the product method of itertools:

from itertools import product

per = product('ABCDEFGHIJKLMNOPQRSTUVWXYZ', repeat=8)

f = open('myfile', 'w')

p = ""

for p in per:
    p = "".join(p)
    f.write(p + "\n")

f.close()

I know there's 208,827,064,576 (> 200 billion) possible permutations so it's going to take time no matter what, but how can I optimise this?


texts: Advent of Code 2018 day 1 part 2: find the first aggregated number that occures twice

texts:
I am using the coding puzzels of https://adventofcode.com for improving my F# skills.

Problem:

Day 1 Part 2:

Starting with frequency 0, a list of numbers should be added successive generating new frequencies. Searched is the first frequency which occurs twice. If the end of the list has been reached without success; the list should be processed again.

  Example Input: [+1, -2, +3, +1]

  Current frequency  0, change of +1; resulting frequency  1.
  Current frequency  1, change of -2; resulting frequency -1.
  C* urrent frequency -1, change of +3; resulting frequency  2.
  Current frequency  2, change of +1; resulting frequency  3.
  (At this point, we continue from the start of the list.)
  Current frequency  3, change of +1; resulting frequency  4.
  Current frequency  4, change of -2; resulting frequency  2, which has already been seen.

  In this example, the first frequency reached twice is 2.

Solution

let input = [1;-2;3;1]

type State =
    | FinalState of int
    | IntermediateState of int * int Set

type State with
    static member Zero = IntermediateState(0, Set.empty.Add(0))

let foldIntermediateState (freqHistory: int Set, freq : int) : State =
    let isFinal = freqHistory |> Set.contains freq
    if isFinal then
        FinalState (freq)
    else
        IntermediateState (freq, freqHistory.Add(freq))

let foldState state value =
    match state with
        | FinalState _ -> state
        | IntermediateState (lastFreq, freqHistory) -> foldIntermediateState (freqHistory, lastFreq + value)

let rec processListRec state lst =
    let result = lst |> Seq.fold foldState state
    match result with
        | FinalState result -> printfn "The result is: %i" result
        | IntermediateState _ -> lst |> processListRec result

input |> Seq.map int |> processListRec State.Zero

Questions

In fact, I am proud to have found a solution without mutable states that looks (at least for me) functional! :D. So any feeback that helps improving the solution or even alternative function approches for solving that problem are welcome :).


texts: Wrapping argparse to use configuration file

texts:
I want to be able to both provide options through command line and from a configuration file. A single option could be served either by the user or by the configuration. But if is provided by both, only user input is used. Such an option could be required and an error would be output if neither user nor configuration provide it.

My solution is to create a class that wraps argparse.ArgumentParser, and provide options from the configuration file as if it was provided by the user.

For the overwriting aspect (user option > configuration option), I rely on the fact that if the same option is provided several times to argparse, only the last one is used.

--option 'value1' --option 'value2' will result in Namespace(option='value2').

Here is how I went:

import sys
from argparse import ArgumentParser

class ConfArgParser(ArgumentParser):

    def __init__(self, *args, config=None, **kwargs):
        self.__config = config if config is not None else dict()
        self.__key_opts = {}
        super(ConfArgParser, self).__init__(*args, **kwargs)

    def add_argument(self, *args, conf_key=None, **kwargs):
        if conf_key is not None:
            self.__key_opts[conf_key] = args[0]

        return super(ConfArgParser, self).add_argument(*args, **kwargs)

    def parse_args(self, **kwargs):
        config_as_opts = []
        for key, opt in self.__key_opts.items():
            conf_value = self.__resolve_conf(key.split("."), self.__config)
            if conf_value is not None:
                config_as_opts.append(opt)
                config_as_opts.append(str(conf_value))
        sys.argv = sys.argv[0:1] + config_as_opts + sys.argv[1:]

        return super(ConfArgParser, self).parse_args(**kwargs)

    def __resolve_conf(self, key_frags, node):
        if key_frags[0] not in node:
            return None
        elif len(key_frags) == 1:
            return node[key_frags[0]]
        else:
            return self.__resolve_conf(key_frags[1:], node[key_frags[0]])

I could use it that way:

#!/usr/bin/env python3
from confargparse import ConfArgParser
import yaml

if __name__ == "__main__":

    with open("application.yml", "r") as config_file:
        config = yaml.load(config_file)

    parser = ConfArgParser(description="Cli prototype", config=config)

    parser.add_argument("--host", required=True, type=str, conf_key="mysql.host")
    parser.add_argument("-u", "--user", required=True, type=str, conf_key="mysql.user")

    args = parser.parse_args()

With such a configuration file, named application.yml:

mysql:
  host: 127.0.0.1
  user: root


texts: 4 solutions to leetcode 202. Happy Number have almost same performance

texts:
I am working on an easy math question Happy number Happy Number - LeetCode

  Happy Number

  Write an algorithm to determine if a number is "happy".

  A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

  Example:

Input: 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1

My solutions

Solution 1, 28ms 12.1mb

string operations

class Solution1:
    def isHappy(self, n):
        s = set()
        while n != 1:
            if n in s: return False
            s.add(n)
            n = sum([int(i) ** 2 for i in str(n)])
        else:
            return True

Solution 2,  24ms, 12.3mb

class Solution2:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        s = set()
        while n != 1:
            if n in s: return False
            s.add(n)

            _sum = 0
            while n:
                _sum += (n % 10) ** 2
                n //= 10
            n = _sum

        return n == 1

Solution 3  the save as solution 2 minor changes  (24ms, 12.3mb)

class Solution3:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        s = set()
        while n:
            if 1 in s:
                return True
            if n in s:
                return False
            s.add(n)
            _sum = 0
            while n:
                _sum += (n%10)**2 #leave unit digit
                n //= 10 #remvoe unit digit
            n = _sum

Solution 4 without extra space(24ms, 12.3mb)

class Solution4:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        while n != 1 and n != 4:
            _sum = 0
            while n :
                _sum += (n % 10) * (n % 10)
                n //= 10
            n = _sum

        return n == 1

TestCase

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution3()

    def test_1(self):
        n = 19
        check = self.solution.isHappy(n)
        self.assertTrue(check)

It's interesting that the last 3 solutions shared the same performance, though try best possibility to improve it.


texts:
I'm trying to let users log in with multiple columns (e.g. ID, email, phone). If one fails, it checks the next column.

I would like to minimise my if and else statements. Is there better way of doing it?

$email = $request->only('email', 'password');
        $ssn='';$badgenumber='';$ophone='';$fphone='';$pager='';

        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) < 6){
            $ssn = $request->only('ssn', 'password');
            $badgenumber = $request->only('badgenumber', 'password');
        }

        if(preg_match("/^[0-9]+$/",$email['email']) == 1 && strlen($email['email']) > 6){
            $ophone = $request->only('ophone', 'password');
            $fphone = $request->only('fphone', 'password');
            $pager = $request->only('pager', 'password');
        }

        if(filter_var($email['email'],FILTER_VALIDATE_EMAIL) === false)
            $email ='';

        $error = 1;

        try {
            // verify the $email and create a token for the user

            if ($error == 1 && $email) {
                $error = 0;
                if (!$token = JWTAuth::attempt($email)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ssn) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ssn)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $badgenumber) {
                $error = 0;
                if (!$token = JWTAuth::attempt($badgenumber)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $ophone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($ophone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $fphone) {
                $error = 0;
                if (!$token = JWTAuth::attempt($fphone)) {
                    $error = 1;
                }
            }
            if ($error == 1 && $pager) {
                $error = 0;
                if (!$token = JWTAuth::attempt($pager)) {
                    $error = 1;
                }
            }

            if($error == 1){
                return response()->json(['error' => 'invalid_credentials'], 401);
            }

        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }


texts: Saving record payment data to respective tables

texts:
I have following action in the controller and am wondering how I can refactor it.

# Saves the record-payment data to respective tables
  def record_payment
    payment_to_be_made =params[:payment_history][:amount].to_f
    remaining_payment = payment_to_be_made
    begin
      @project = @user.projects.find(@project_id)
      @bid = @project.bid
      payments = @bid.payments
      added_payment = 0
      @total_payment = payments.sum(:amount).to_f
      if (payment_to_be_made > @total_payment)
        flash.now[:error] = t('amount_exceeded_message', total_amount: @total_payment)
      else
        if @project.open?
          @payment_history = @project.payment_histories.new(payment_history_params).record_payment
          payments.each do |payment|
            if added_payment > 0 && payment.status
              payment.update(amount: payment.amount + added_payment)
              break
            end
            if payment.status
              payment.update(status: false)
              if payment.amount.to_f <= remaining_payment
                remaining_payment = remaining_payment - payment.amount.to_f
                if payment == payments.last && remaining_payment > 0
                  @bid.payments.create(amount: remaining_payment, status: true)
                end
              else
                added_payment = payment.amount.to_f - remaining_payment
                payment.update(amount: remaining_payment)
                remaining_payment = 0
                if payment == payments.last && added_payment > 0
                  @bid.payments.create(amount: added_payment, status: true)
                end
              end
            end
          end
          flash.now[:success] = t('added_payment_successfully') if @payment_history.errors.count == 0
        else
          flash.now[:error] = t('closed_project_record_payment')
        end
      end

    rescue ActiveRecord::RecordNotFound
      logger.error "No project exists with project_id: #{@project_id}"
      flash.now[:error] = t('project_details_not_found')
    end
    @payment_history = PaymentHistory.new
    respond_to do |format|
      format.html { render partial: 'projects/record_payment' }
    end
  end


texts: Use an existing invoice if one exists, else create one

texts:
Here are the requirements:

If initial_invoice? is false, existing_invoice always exists.
If initial_invoice? is true and existing_invoice exists, I'd love to use the existing_invoice.

I'd love to refactor this code.

 existing_invoice = find_existing_invoice(invoice_obj[:id])
   invoice = if !initial_invoice?(invoice_obj) || existing_invoice.present?
                existing_invoice
              else
                ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
                create_initial_invoice(invoice_obj, ac)
              end

  private

  def find_existing_invoice(id)
    Invoice.find_by(stripe_invoice_id: id)
  end

  def initial_invoice?(invoice_obj)
    sub_id = invoice_obj[:subscription]
    return false if sub_id.nil?

    sub = Stripe::Subscription.retrieve(sub_id)
    return false unless invoice_obj[:period_start] == sub[:created]
    true
  end

update

invoice = if initial_invoice?(invoice_obj)
            return existing_invoice if existing_invoice.present?

            ac = Account.find_by(stripe_customer_id: invoice_obj[:customer])
            create_initial_invoice(invoice_obj, ac)
          else
            existing_invoice
          end


texts:
I am pretty new in Python and I am not sure if I did everything right in my program. May someone to check it, please. Thank you!

First of all, I have a text file, for example, abc.txt.
I have to create a dictionary and for this, I have to split the
sentences into a list of words and convert each word to lowercase.
Then I have to assign a counter to each word in my dictionary and
increment it every time when I meet this word in sentence one more
time.
Finally, I have to divide the word count by sum of all counts (prob = count(word) / sum(count of all words in dict) and write this probability into new file called x.txt.

Here is what I got so far:

import sys
filename = 'abc.txt'
new_dict ={}
total_count = 0
with open(filename, "r") as fp:
    for line in fp:
        words = line.split()

        for word in words:
            word = word.lower()

        if not word in new_dict:
             new_dict[word] = 1
        else:
            new_dict[word] +=1
            total_count +=1
probab = new_dict[word]/ total_count
print(probab)
fp.close()
output_file = 'x.txt'
with open(output_file, "w") as fs:
           fs.write(str(probab))
fs.close()

and my output is 0.0006865437426441742


texts: Can casting to fragment be more efficient than using a variable?

texts:
I'm new to using fragments in Android. I'm working on an app using a sliding panel layout and I just came up with an idea for changing my fragments. I decided to create the following method:

    private void changeFrag(Object newFrag){
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
        .replace(R.id.fragment_secondpane, (Fragment) newFrag).commit();
    }

I'm calling the method in the following way:

    changeFrag(new myFragment());

Could this cause problems for me in the long run? I was hoping that by writing it this way, I could avoid extra code and hopefully cut down on any extra processing power the device would need for something like this:

        Fragment frag;
        frag= new myFragment();

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
        .replace(R.id.fragment_secondpane, (Fragment) frag).commit();


texts: Preview method for multiple types of panels

texts:
Using Rubocop, pretty much any case statement is caught by the Cyclomatic Complexity cop, often the Assignment Branch Condition and method length cops as well. To get around this, I've been refactoring code like this:

def preview
  case object.panel_type
  when "image"
    asset_image_path(object.asset)
  when "profile_block"
    Profile.find(object.type_id).try(:full_name)
  when "slider"
    if object.options.present? && object.options["slides"].present?
      Slide.find(object.options["slides"][0]).headline
    else
      "Empty"
    end
  when "menu"
    Menu.find(object.type_id).try(:name)
  else
    clean_content.try(:truncate, (object.span * 4))
  end
end

Into this:

def preview
  if %w(image profile_block slider menu search_list).include?(object.panel_type)
    send("#{object.panel_type}_preview")
  else
    clean_content.try(:truncate, (object.span * 4))
  end
end

private

def image_preview
  asset_image_path(object.asset)
end

def profile_block_preview
  Profile.find(object.type_id).try(:full_name)
end

def slider_preview
  if object.options.present? && object.options["slides"].present?
    Slide.find(object.options["slides"][0]).headline
  else
    "Empty"
  end
end

def menu_preview
  Menu.find(object.type_id).try(:name)
end

def search_list_preview
  GridPanel::SEARCH_TYPES.invert[object.type_id]
end

In general, I think dynamic method names can be a bit problematic for maintenance. One of the problems with legacy Rails code is finding all the usage of dynamic methods in a project when you have to add or remove things. But in this case, I think the names have consistency and a limited scope, so it doesn't seem like it would be difficult to maintain or update later. Is there are more conventional way to do this?


texts: Set + Queue + a get method backed by a Map

texts:
The other day I stumbled upon this question on Stack Overflow about the lack of a get method on the Set and loved the suggestion of using a Map<E,E> to back the Set. I decided to try this out. Since this is quite a generic object that could serve a lot of purposes, I would like to know if there is something weird with my implementation.

NB: I am using Java 7.

Here is the interface:

public interface QueuedSetWithGet<E> extends Set<E>, Queue<E> {
    public E get(E e);
}

And here is the implementation I wrote:

public class QueuedSetWithGetImpl<E> implements QueuedSetWithGet<E> {

    LinkedHashMap<E, E> map = new LinkedHashMap<E, E>();

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object paramObject) {
        return map.containsKey(paramObject);
    }

    @Override
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    @Override
    public Object[] toArray() {
        return map.keySet().toArray();
    }

    @Override
    public <T> T[] toArray(T[] paramArrayOfT) {
        return map.keySet().toArray(paramArrayOfT);
    }

    @Override
    public boolean add(E paramE) {
        boolean notAlreadyPresent = !map.containsKey(paramE);
        if (notAlreadyPresent) {
            map.put(paramE, paramE);
        }
        return notAlreadyPresent;
    }

    @Override
    public boolean remove(Object paramObject) {
        return map.remove(paramObject) != null;
    }

    @Override
    public boolean containsAll(Collection<?> paramCollection) {
        return map.keySet().containsAll(paramCollection);
    }

    @Override
    public boolean addAll(Collection<? extends E> paramCollection) {
        boolean mapChanged = false;
        for (E e : paramCollection) {
            mapChanged |= this.add(e);
        }
        return mapChanged;
    }

    @Override
    public boolean retainAll(Collection<?> paramCollection) {
        boolean mapChanged = false;
        for (Object e : paramCollection) {
            if (!this.contains(e)) {
                mapChanged = true;
                this.remove(e);
            }
        }
        return mapChanged;
    }

    @Override
    public boolean removeAll(Collection<?> paramCollection) {
        boolean mapChanged = false;
        for (Object e : paramCollection) {
            mapChanged |= this.remove(e);
        }
        return mapChanged;
    }

    @Override
    public void clear() {
        map.clear();
    }

    @Override
    public boolean offer(E paramE) {
        return this.add(paramE);
    }

    @Override
    public E remove() {
        E head = this.element();
        this.remove(head);
        return head;
    }

    @Override
    public E poll() {
        return this.isEmpty() ? null : this.remove();
    }

    @Override
    public E element() {
        E e = this.peek();
        if (e == null) {
            throw new NoSuchElementException("queue is empty");
        } else {
            return e;
        }
    }

    @Override
    public E peek() {
        return this.isEmpty() ? null : map.keySet().iterator().next();
    }

    @Override
    public E get(E e) {
        return map.get(e);
    }
}


texts: Connect Four game without diagonals check or validation

texts:
This is a simple implementation of Connect four in Java. It is working correctly so far.
 What I haven't done yet are the diagonals check and input validation.

package game;

import java.util.Scanner;
//TODO check for diagonals, input validation

public class Game {
    private char[][] gameBoard;
    private State gameState;
    private Turn turn;
    private int[] possiblePositions;
    private static final int BOARD_HEIGHT = 6;
    private static final int BOARD_WIDTH = 7;

    enum Turn {
        PLAYER_ONE, PLAYER_TWO
    }

    enum State {
        PLAYER_1_WIN, PLAYER_2_WIN, RUNNING
    }

    public Game() {
        gameBoard = new char[BOARD_HEIGHT][BOARD_WIDTH];
        for (int row = 0; row < BOARD_HEIGHT; row++) {
            for (int col = 0; col < BOARD_WIDTH; col++) {
                gameBoard[row][col] = '□';
            }
        }
        turn = Turn.PLAYER_ONE;
        gameState = State.RUNNING;
        possiblePositions = new int[] { 5, 5, 5, 5, 5, 5, 5 };
    }

    public void playerMove(int column) {
        switch (turn) {
        case PLAYER_ONE:
            gameBoard[possiblePositions[column]][column] = '■';
            turn = Turn.PLAYER_TWO;
            break;
        case PLAYER_TWO:
            gameBoard[possiblePositions[column]][column] = '⊠';
            turn = Turn.PLAYER_ONE;
            break;
        }
        possiblePositions[column]--;
    }

    public void printBoard() {
        System.out.println("0 1 2 3 4 5 6");
        for (int row = 0; row < BOARD_HEIGHT; row++) {
            for (int col = 0; col < BOARD_WIDTH; col++) {
                System.out.print(gameBoard[row][col] + " ");
            }
            System.out.println();
        }
    }

    public void checkRowAndCol() {
        int chainLength = 1;
        for (int row = 0; row < BOARD_HEIGHT - 1; row++) {
            for (int col = 0; col < BOARD_WIDTH - 1; col++) {
                if (gameBoard[row][col] == gameBoard[row][col + 1] && gameBoard[row][col] != '□') {
                    ++chainLength;
                    if (chainLength == 4) {
                        switch (gameBoard[row][col]) {
                        case '■':
                            gameState = State.PLAYER_1_WIN;
                            break;
                        case '⊠':
                            gameState = State.PLAYER_2_WIN;
                            break;
                        }
                    }
                } else {
                    chainLength = 1;
                }
            }
            chainLength = 1;
        }

        for (int col = 0; col < BOARD_WIDTH - 1; col++) {
            for (int row = 0; row < BOARD_HEIGHT - 1; row++) {
                if (gameBoard[row][col] == gameBoard[row + 1][col] && gameBoard[row][col] != '□') {
                    ++chainLength;
                    if (chainLength == 4) {
                        switch (gameBoard[row][col]) {
                        case '■':
                            gameState = State.PLAYER_1_WIN;
                            break;
                        case '⊠':
                            gameState = State.PLAYER_2_WIN;
                            break;
                        }
                    }
                } else {
                    chainLength = 1;
                }
            }
            chainLength = 1;
        }
    }

    public void start() {
        Scanner reader = new Scanner(System.in);
        printBoard();
        while (gameState == State.RUNNING) {
            playerMove(reader.nextInt());
            checkRowAndCol();
            printBoard();
        }
        System.out.println(gameState);
        reader.close();
    }
}


texts: Model and form validation in class based view

texts:
In an app which it is possible to transfer money between accounts I have the following logic:
View:
class GiftCardRegisterBuyConfirmationView(LoginRequiredMixin, generic.CreateView):
    template_name = "giftcard/buy-card-modal-content.html"
    model = BuyGiftCardOrder
    form_class = BuyGiftCardOrderForm
    success_url = reverse_lazy("giftcard:register-buy-list")

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

Form:
class BuyGiftCardOrderForm(forms.ModelForm):
    class Meta:
        model = BuyGiftCardOrder
        exclude = ('created_by', 'order_total_btc_value')

    def clean(self):
        cleaned_data = super().clean()
        amount = self.cleaned_data.get("amount")
        if amount:
            with transaction.atomic():
                try:
                    admin_wallet = Wallet.objects.filter(user__is_superuser=True).first()
                    user_wallet = Wallet.objects.select_for_update().get(user=self.user)

                    if user_wallet.balance - amount < 0:
                        raise Exception("Not enough balance")

                    if admin_wallet.pk == user_wallet.pk:
                        raise Exception("Admins can't buy cards. Create a normal account in order to buy one.")

                    user_wallet.transfer(
                        self.total_btc_price,
                        admin_wallet
                    )
                except Exception as e:
                    self.add_error(None, ValidationError(f"Error: {e}"))
        return cleaned_data

Model:
class Wallet(models.Model):
    currency = models.ForeignKey('Currency', on_delete=models.CASCADE)
    balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0)
    holded = models.DecimalField(_('Holded'), max_digits=18, decimal_places=8, default=0)
    unconfirmed = models.DecimalField(_('Unconfirmed'), max_digits=18, decimal_places=8, default=0)
    label = models.CharField(_('Label'), max_length=100, blank=True, null=True, unique=True)

    def __str__(self):
        return u'{0} {1} "{2}"'.format(self.balance, self.currency.ticker, self.label or '')

    def transfer(self, amount, deposite_wallet, reason=None, description=""):
        if amount < 0:
            raise ValueError('Invalid amount')

        if self.balance - amount < 0:
            raise ValueError('No money')

        self.balance -= amount
        self.save()
        deposite_wallet.balance += amount
        deposite_wallet.save()

This works correctly but the problem is that the transaction is happening at the form.
The correct way would be to handle the transfer operation in the view, but in the view, it should happen at the form_valid method. But in in the transfer operation, it would be possible that a user does not have enough money and from what I have researched, errors should not be handled after form is valid..
I could check for balance in form and perform the transfer operation in view. The problem I see is that they should happen within a transaction as it uses select_for_update and I see no way to keep object locked in form and view.
What is the best approach ?


texts: What is the best way to format a large has_many through line?

texts:
This question is about code style.

I have this line in one of my models:

has_many :owning_artists, :through => :artist_tracks, :source => :artist, :conditions => { :artist_tracks => { :artistic_role_id => 1, :another_memeber => 42 } }

What is the best way to break this up on multiple lines, and indented of course, and what would it would look like?

I'd love to hear a more general recommendation/guideline for how to break up and indent nested hashes too.


texts:
I wrote my very first directive and I'd like to get some suggestions for improvement.
My code - plnkr.

webApp.controller('AppCtrl', function ($scope) {

$scope.expandAdd = function() {
    $scope.hiddenAdd = true;

};

$scope.addWeb = function() {
    $scope.hiddenAdd = false;
};

});

webApp.directive('enter',function(){
return {

    link: function (scope, element, attrs){

        scope.hiddenAdd = false;   //hides the site details at first
        //Invoke expender on the controller on mouse click
        element.bind('click', function(){
            console.log('clicked');
            scope.$apply(attrs.enter);
        });
    }
}
});

I have three points I think I can improve here but I'm not sure how:

My directive is not modular enough, the line scope.hiddenAdd = false is bound to hiddenAdd. Is it possible to make it more flexible for future use?
Though it seems two be picking to different bindings I think that is because they are both start with hidden.
Inside the controller I'm doing DOM manipulation  $scope.hiddenAdd = true; & $scope.hiddenAdd = false; from what I've read it all best be inside directives and I can't find the way to make it a pure directive.
I read somewhere that it is not recommended to use $apply too often, is there a way to avoid using apply in my case?


texts: Counting the number of ways to decode a string

texts:
I am working on problem where I need to decode a string:

  A message containing letters from A-Z is being encoded to numbers
  using the following mapping:

    'A' -> 1
    'B' -> 2
    ...
    'Z' -> 26

  Given a non-empty string containing only digits, determine the total
  number of ways to decode it.

  Example 1:

  Input: "12"
  Output: 2
  Explanation: It could be decoded as "AB" (1 2) or "L" (12).

  Example 2:

  Input: "226"
  Output: 3
  Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

I came up with the following recursive approach and it works fine. Is there any better or efficient way to solve the same problem?

  public static int decode(String data) {
    int[] memo = new int[data.length() + 1];
    return helper(data, data.length(), memo);
  }

  private static int helper(String data, int k, int[] memo) {
    if (k == 0)
      return 1;
    int s = data.length() - k;
    if (data.charAt(s) == '0')
      return 0;
    if (memo[k] != 0) {
      return memo[k];
    }

    int result = helper(data, k - 1, memo);
    if (k >= 2 && Integer.parseInt(data.substring(data.length() - k, data.length() - k + 2)) <= 26) {
      result += helper(data, k - 2, memo);
    }
    memo[k] = result;
    return result;
  }


texts: Find largest substring which repeats to yield entire string

texts:
My job is to find the largest repeating substring in a given string, which repeats to re-create the entire string. For example, if input="cdcdcdcd" then the longest pattern would be "cdcd". If no substring can meet this requirement, return -1. Apparently the best possible time for this is 0(n), but I don't know what that means nor whether my solution meets that.

def StringPeriod(str)
  (str.length/2).downto(1) do |l|
     slices = str.chars.each_slice(l).to_a
     return slices[0].join if slices.uniq.size == 1
  end
  -1
end

Please let me know how this could be optimized or written more clearly. And if you don't mind, please give me an idea of how to find faster solutions in general.

EDIT: After some thought, I figured this might be faster, but I'm still not quite sure if I'm onto it. See below:

def StringPeriod(str)
  (str.size-1).downto(1) do |sub|
    if str.size%sub==0
      substring,n = str[0...sub],2
      until substring.size*n > str.size
        return substring if substring*n==str
        n+=1
      end
    end
  end
  -1
end

My third attempt:

def StringPeriod(str)

  n,f=1,str.size
  while n<=str.size/2 && f >=1
    n+=1 until str.size%n==0
    f-=1 until str.size%f==0
    return str[0...n] if str[0...n]*f == str
    n+=1
    f-=1
  end
  -1
end


texts: How can I improve this PHP MySQL rank query?

texts:
In my db MySQL, I have a table ranks with many fields, one for each page I want limit access for the user in the menu application with PHP control:

  <?php if ($row_ranks['padric'] == '1' ) {
    echo ('
Ricerca
');
        }
        else  {
        echo ('
Ricerca
');
        }
  ?>

In the admin panel, I have a page for seting the privileges to single page with relative checkbox.

The checkbox as a name equal at field name in table like this example:

<input type="checkbox" name="padric" value="1"
<?php if ($row_user_ranks['padric'] == 1) { echo "checked"; } ?>
>Ricerca

For set the privileges I make this PHP code:

    mysql_select_db($database_geomo, $geomo);
    $query_RSfields = sprintf("SHOW COLUMNS FROM ranks WHERE Field NOT IN ('ID', 'userID', 'gruppo')");
    $RSfields = mysql_query($query_RSfields, $geomo) or die(mysql_error());
    $row_RSfields = mysql_fetch_assoc($RSfields);
    $totalRows_RSfields = mysql_num_rows($RSfields);
    do {
     $field = $row_RSfields['Field'] ;

     if (!isset($_POST[$field])) { // set value = 0 for checkbox not checked
         $_POST[$field] = '0' ;
        }

    $updateSQL = sprintf("UPDATE ranks SET $field='".$_POST[$field]."' WHERE userID='".$_POST['ID']."'"); // set privileges for user
    mysql_select_db($database_geomo, $geomo);
    $Result1 = mysql_query($updateSQL, $geomo) or die(mysql_error());

    } while ($row_RSfields = mysql_fetch_assoc($RSfields));

I've made this code in this way because if the checkbox is not checked, it shouldn't return a value and should generate an error "unknown column" for the update SQL.

So, there is another more simply way for doing this job?


texts: Print the length of words as input as a histogram with horizontal bars

texts:
Input

A list of words separated by any number of spaces.

Output

A horizontal ASCII art histogram, where the n-th line is composed by as many asterisks (*) as the n-th word is long.

Example usage

The > signals user input, you should not input it when testing the program.

> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

> a aa aaa aaaa aaaaa
*
**
***
****
*****

> double space  example
******
*****
*******

The code

puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")


texts:
I am a total novice to Python and have been testing my skills recently. I found this particular challenge and wanted to give it a shot. I made this code and it functions well, but very slowly. I was looking for feedback on how to optimize in Python, as well as general Python best practices!

Main.py

from PIL import Image

IMGHeight = 2000
IMGWidth  = 2000

xmin = -2.0
xmax =  2.0

ymin = -2.0
ymax =  2.0

def Function(z):
    return z*z + complex(-0.221, -0.713)

def Pixel(point):
    #set up how the complex number will create a pixel

    limit = 255
    thresh = 2

    val = Function(point)
    for I in range(1, limit):
        if(abs(val) > thresh):
            return I

        val = Function(val)

    return limit

def main():
    myImg = Image.new('L', (IMGWidth+1,IMGHeight+1))

    for x in range(IMGWidth):
        zx = x * (xmax - xmin)/(IMGWidth - 1) + xmin
        for y in range(IMGHeight):
            zy = y * (ymax - ymin)/(IMGHeight - 1) + ymin
            z = complex(zx, zy)
            #pixels.append(Pixel(z))
            myImg.putpixel((x,y), Pixel(z))

    myImg.save('Fractals.png')

if __name__ == "__main__":
    main();


texts:
Previously, I posted an incorrect implementation of making a binary, balanced tree from a list of a's.

Here's my second implementation:

data Tree a = Leaf
              | Node Integer (Tree a) a (Tree a)
              deriving (Show, Eq)-- where Integer is the height (bottom = 0)

-- make balanced, binary tree (height diff is 1 at most)
foldTree :: [a] -> Tree a
foldTree []     = Leaf
foldTree xxs@(x:xs) = Node level (foldTree first) x (foldTree rest)
     where (first, rest) = splitInHalf xs
           level         = getBinTreeHt xxs

splitInHalf :: [a] -> ([a], [a])
splitInHalf xs = splitAt mid xs
    where mid = length xs `div` 2

-- Get the total height of a tree given a list of [a] to create a Tree
getBinTreeHt :: [a] -> Integer
getBinTreeHt = floor . (logBase 2) . fromIntegral . length

Testing

Note that prettyTree's implementation is excluded from this question since it's a library for visually representing a tree. Credit to this answer for prettyTree.

*Main> (putStrLn . prettyTree . foldTree) [0..15]
        15
      14
    12
      13
  8
      11
    9
      10
0
      7
    5
      6
  1
      4
    2
      3


texts:
I was recently going through and refactoring old code, and I eventually came across the code for my website's menu bar, so I started to refactor it.

I also recently was introduced to Heredocs, which I am very new to and not sure all the ins-and-outs yet.

Here is the refactored code for part of it (I am mostly interested in responses about this specific part of the menu, which is a dropdown menu that every logged in user gets that essentially has their name and then it drops down into some other options regarding themes):

<?php

    $showAdminPanel = ((hasPerms($_SESSION['users_perms'], $_SESSION['role_perms'], 8)) ? "
Admin Panel
":"");
    $devPerms = ((hasPerms($_SESSION['users_perms'], $_SESSION['role_perms'], 13)) ? "

Issues

Requests

Changelog

":"");

    $themes = "";
    foreach(scandir($assetsDir."themes/") as $file) {
        if((strcmp($file,".") != 0) && (strcmp($file,"..") != 0)) {
            $themes .= '
'.substr(ucfirst($file),0,-4).'
';
        }
    }

    echo <<<USERACCOUNTDROPDOWN

            {$_SESSION["user"]["name"]}

                {$showAdminPanel}

                    Themes

Default: Cosmo

                        {$themes}

                    Development

                        {$devPerms}

Logout

USERACCOUNTDROPDOWN;
?>

The reason that I am more interested in this section of the code rather than the entire menu bar is that, this part of it has some permissions baked in using the $devPerms variable, basically if user has perm ID 13 it creates a string which has links to specific parts of the website, if user does not, the string is blank.

This code works, but I feel like there is a better way to accomplish what I am trying to do here that will make it look cleaner.

My question is this: How would you have written this code? I would love to improve my Heredocs understanding as I believe it will improve my programming in general.


texts:
I want to build a small newsletter like tool which sends mails in pre-defined timespans. First after registration, second 14 days later, third 7 days later etc.

I came across for two database designs and those two queries:

Create a separate table (dispatch) and put the next mails into it (can be done by cronjob):

SELECT
    m.campaign_id,
    s.name,
    s.email,
    m.subject,
    m.body
FROM sp_dispatch AS d
    INNER JOIN sp_subscribers AS s
        ON s.id = d.recipient_id
    INNER JOIN sp_mailings AS m
        ON m.id = d.mailing_id
WHERE d.time
    BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 31 DAY)
LIMIT 0, 500

Without a separate table and search through all mails when sending.

SELECT
    r.campaignID,
    DATE_ADD(r.startDate, INTERVAL t.timeOffset DAY) AS sendDate,
    r.name,
    r.email,
    t.subject,
    t.textMail
FROM cw_recipients AS r
    INNER JOIN cw_triggerMails AS t
        ON r.campaignID = t.campaignID
WHERE DATE_ADD(r.startDate, INTERVAL t.timeOffset DAY)
    BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 31 DAY)
LIMIT 0, 500

What do you think is the better/faster/more reliable solution?

DB Design #1
DB Design #2


texts:
I need help fixing my gameloop. Sometimes the game feels very laggy and I think the reason is that the tick() method is called slower then the render() method. What I want is that update is called as often as possible and the tick method gets executed with some kind of value that determines how fast thinks are going. For example the value is 0.8 and I just multiply it to determine how fast Things should go.

And I think my current gameloop is just a mess!

public void run() {

    init();

    double timePerTick = 1000000000 / targetTicksPerSecond;
    double timePerFrame = 1000000000 / targetFramesPerSecond;
    double delta = 0;
    double delta2 = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    long renderTimer = 0;
    int ticks = 0;

    while (running) {

        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        delta2 += (now - lastTime) / timePerFrame;
        timer += now - lastTime;
        lastTime = now;
        if (delta >= 1) {

            tick();
            ticks++;
            delta--;
        }
        if(delta2 >= 1) {
            render();
            renderTimer++;
            delta2--;
        }
        if (timer >= 1000000000) {
            currentTicks = ticks;
            currentFPS = (int) renderTimer;

            ticks = 0;
            timer = 0;
            renderTimer = 0;
        }

    }

    stop();
}


texts: O Levels 2210 Computer Science Pre-Release: Senior Citizens Trip Organizer

texts:
Can anyone go over the code and suggest any edits and/or efficient solutions?

Attached below are the provided tasks and their solutions. The task is copyright of Cambridge International Examinations.

#©Nosher Zapoo 2017.
#Task 1 starts here.

number_of_citizens = int(input('Please Enter the number of citizens on the trip: '))

#Validation Check:

if number_of_citizens > 2 and number_of_citizens < 37:
    if number_of_citizens > 24 :
        carer = 3
    else:
        carer = 2
else:
    print('Sorry the range of people is 10 - 36. Please Try again.')
    exit()

#Calculating the cost using economies of scale.

total_people = number_of_citizens + carer
if total_people < 17:
    hire = 150
    cost_meal = 14*total_people
    cost_ticket = 21*total_people
elif total_people < 27:
    hire = 190
    cost_meal = 13.5*total_people
    cost_ticket = 20*total_people

elif total_people < 40:
    hire = 225
    cost_meal = 13*total_people
    cost_ticket = 19*total_people
else:
    exit()

#Working out the total cost
total_cost= hire + cost_meal + cost_ticket
avg_cost= total_cost / number_of_citizens
print('Number of Citizens = ',number_of_citizens)
print ('Total Cost = $', total_cost)
print ('Cost per Person = $', avg_cost)

#Task2 Starts!!!

#Creating Empty Lists to append as arrays.
names = []
amounts = []
total_amount  = 0

#Using an undefined loop
for x in range (0, total_people ):
    name = input('Name: ')
    amount = input ('Amount: ')
    names.append (name)
    amounts.append (amount)
    total_amount = total_amount + int(amount)

#Adding Spare people and their costs
if total_people < 17:
    extra_people = 16 - total_people
elif total_people < 27:
    extra_people = 26 - total_people
elif total_people < 40:
    extra_people = 39 - total_people

extra_cost = extra_people*avg_cost
total_cost = total_cost + extra_cost

if extra_people > 0:
    print ('There are', extra_people, 'seats available. Please enter the name & amount of people joining on extra seats')
    updated_people = total_people + extra_people
    for x in range (total_people, updated_people):
        name = input('Name: ')
        amount = input ('Amount: ')
        names.append (name)
        amounts.append (amount)
        total_amount = total_amount + int(amount)

for x in range (0, updated_people):
    print (names[x])

#Task 3 Starts here.

profit = total_amount - total_cost
if profit > 0:
    print ('Profit gained $', profit)
elif profit == 0:
    break_even_value = total_cost
    print ('The Outing has broken even as the Total Cost is equal to the Total Amount.')
else:
    print ('The Outing is in loss of $', profit)


texts: Finding the indices of the two items whose price adds up to to a value

texts:
I've solved the Google Jam store credit problem. but there's some inefficiencies that I want to get rid of them to improve the algorithm and reduce the multiple iteration. What are other better ways to do so?

Problem:

  You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).

  Input:

  The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:

  One line containing the value C, the amount of credit you have at the
  store.
  One line containing the value I, the number of items in the
  store.
  One line containing a space separated list of I integers. Each
  integer P indicates the price of an item in the store.
  Each test case
  will have exactly one solution.

  Output:

  For each test case, output one line containing "Case #x: " followed by
  the indices of the two items whose price adds up to the store credit.
  The lower index should be output first.

  Limits

  5 ≤ C ≤ 1000 1 ≤ P ≤ 1000

  Small dataset

  N = 10 3 ≤ I ≤ 100

  Large dataset

  N = 50 3 ≤ I ≤ 2000

Solution:

#!/usr/bin/env python3.4
import sys
from itertools import combinations, count

cases = []
credits = []
items = []

with open(sys.argv[1]) as file_:
    next(file_)
    cases = (list(zip(*[file_]*3)))

for case in cases:
    credits.append(int(case[0]))
    items.append([int(item) for item in case[2].split()])

for credit, prices, i in zip(credits, items, count()):
    for tow_items in combinations(prices, 2):
        if sum(tow_items) == credit:
            print("Case #{}:".format(i+1), end=' ')
            print(' '.join([str(i+1) for i, price in enumerate(prices)
                            if price in tow_items]))


texts:
For a Student object in the package entity, I have a control.studentpackage with classes that are relevant to the Student object.

The Student is a class with only private properties and getters/setters for every property. The setters do no validation on their own.

My project structure is as follows:

src/
  control/
    student/
      StudentControl.java
      StudentValidator.java
      ValidationError.java
  entity/
     Student.java

ValidationError is just a String wrapper with getters and setters.

The StudentValidator is a functional interface that extends Function<Student, Optional<ValidationError>>.

interface StudentValidator extends Function<Student, Optional<ValidationError>> {}

The StudentControl class is as follows:

package control.student;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import entity.Student;

public class StudentControl {

  private static final Pattern namePattern = Pattern.compile("[aA-zZ]+");

  /**
   * List of functions that validate a Student.
   */
  private static final List<StudentValidator> validatorFunctions = new ArrayList<>();
  static {
    validatorFunctions.add(validateNamesFunction());
  }

  /**
   * Validates a Student's fields.
   *
   * @param student Student to validate
   * @return an Optional that may contain a List of ValidationError. Those ValidationError(s) will
   *         have error messages describing each error occurred while validating the student.
   */
  public static Optional<List<ValidationError>> validate(Student student) {
    List<ValidationError> errors = validatorFunctions.stream()
        .map(f -> f.apply(student))
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());

    return errors.isEmpty() ? Optional.empty() : Optional.of(errors);
  }

  /**
   * Returns a function that validates a Student's name.
   */
  public static StudentValidator validateNamesFunction() {
    return student -> {
      return namePattern.matcher(student.getName()).matches()
          ? Optional.empty()
          : Optional.of(new ValidationError("Invalid name"));
    };
  }

  /**
   * Returns a function that validates a Student's birth date.
   */
  public static StudentValidator validateBirthDateFunction() {
    return student -> {
      return student.getBirthDate().getTime() > new Date().getTime()
          ? Optional.of(new ValidationError("Student was born in the future."))
          : Optional.empty();
    };
  }

  /**
   * Returns a function that validates a Student's join date.
   */
  public static StudentValidator validateJoinDateFunction() {
    return student -> {
      return student.getJoinDate().getTime() > new Date().getTime()
          ? Optional.of(new ValidationError("Student joined in the future."))
          : Optional.empty();
    };
  }
}

Is this code readable? Does it easily convey to the programmer what it is meant to do? Does it comply with the MVC pattern? How could I change my code to make it look, feel and run better?


texts: Write strings to a file while downloading new one simultaneous

texts:
I created this console app that gets some JSON strings from a web request using a Parallel.For loop,

class Program
{
    private static readonly object ConsoleLock = new object();

    static void Main(string[] args)
    {
        //DECLARATION
        var link = "http://www.mytestrequest.com/id="
        int start = 1000;
        int end = 2000;
        var requestDid = 0;
        var requestToDo = end - start;
        ParallelOptions parallelOptions = new ParallelOptions();
        parallelOptions.MaxDegreeOfParallelism = 8;

        List<string> jsonResponses = new List<string>();
        var baseAddress = new Uri("http://www.mytestrequest.com");
        var cookieContainer = new CookieContainer();
        cookieContainer.Add(baseAddress,new Cookie("JSESSIONID", "xxx"));
        var handler = new HttpClientHandler() {CookieContainer = cookieContainer};
        var client = new HttpClient(handler) {BaseAddress = baseAddress};

        //CODE START HERE
        var task = Parallel.For((long)start, (long)end, parallelOptions, async i =>
        {
            lock (ConsoleLock)
            {
                Console.SetCursorPosition(0, 0);
                Console.Write($"Progress {requestDid++}/{requestToDo}     ");
            }

            jsonResponses.Add(client.GetStringAsync(link + i).Result);
        });

        while (!task.IsCompleted)
        {
            Thread.Sleep(1000);
        }

        Console.WriteLine("Writing to file");

        using (var streamWriter = new StreamWriter("N:/sctest.txt"))
        {
            foreach (var sc in jsonResponses)
            {
                streamWriter.WriteLine(sc);
            }
        }
        client.Dispose();
        handler.Dispose();
    }

I was trying to achieve the best result performance for this purpose and I thought it was possible to write to a file what I already got in the list while still downloading other elements but didn't know how to achieve it, should I use ContinueWith()? But how?

I would also like to avoid to make too many requests at the same time, what I've noticed is that if I try to add the await to the GetStringAsync() it seems to make thousands of requests at same time, instead, if I wait the Result this seems to only move over following the MaxDegreeOfParallelism.


texts:
This is my Fibonacci generator:

package main

import "fmt"

func main() {
    for i, j := 0, 1; j < 100; i, j = i+j,i {
        fmt.Println(i)
    }
}

It's working, but I don't know how I can improve it, so I'd like more expert approaches to solving it.


texts: Swift HackerRank Missing Numbers Challenge

texts:
I'm attempting to solve the "Missing Numbers" challenge on HackerRank where I'm tasked with finding missing elements comparing two arrays.

Foundation's NSCountedSet is a little pokey on large data sets, I rolled my counted set with a Swift Dictionary. I'm able to pass all the test cases with the exception of the last case which has ~10,000 elements in each array.

I looked through some of the comments for hints on how to complete the challenge, but they're all in other languages with uncommented code and non-descriptive variable naming.

// I put this in to save non-HackerRank users the hassle of getting inputs
let firstArrayCount = Int(readLine()!)! // unused
let listA = readLine()!.components(separatedBy: " ").map({Int($0)!})
let secondArrayCount = Int(readLine()!)! // unused
let listB = readLine()!.components(separatedBy: " ").map({Int($0)!})

// This is my method to create a countedSet
func countedSet(array: [Int]) -> Dictionary<Int, Int> {
    var dict = Dictionary<Int, Int>()

    for element in array {
        if dict[element] == nil {
            dict[element] = 1
        } else {
            dict[element] = dict[element]! + 1
        }
    }

    return dict
}

// Works fine on everything except large data sets
func missingNumbers(listA: [Int], listB: [Int]) -> String {
    var output: [Int] = []

    let comparisonSet = Set(listB) // list be is larger

    let ctdSetListA = countedSet(array: listA)
    let ctdSetListB = countedSet(array: listB)

    for element in comparisonSet {
        if ctdSetListA[element] != ctdSetListB[element] {
            output.append(element)
        }
    }

    return output.sorted().map({String($0)}).joined(separator: " ")
}

I welcome suggestions on how to speed up my code. Thank you for reading.


texts:
The idea is that i want any size string to put the corresponding hex value into a byte array. I've seen a million ways to do it. Some of them didn't look to clean. My needs are speed over memory, so chose to try and implement a lookup table. Tell me what you think

const BYTE HEX[0x80] = //This is the ASCII table in number value form
{   //0     1     2     3     4     5     6    7      8     9     A     B     C     D     E     F
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//0
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//1
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//2
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//3
    0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//4
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//5
    0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//6
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 //7
};
void ByteUtil::StringToHex(const char* str, BYTE* hex)
{
    int len = strlen(str)/2;
    for(int i=0; i<len; i++)
    {
        hex[i] =  (HEX[*str++] << 4);
        hex[i] += (HEX[*str++]);
    }
}

This method assumes you've already figured out the length of the array. So to use it it would look somethign like this.

char* gky = "55D38577093A88F3B5EA40BBF11158813A2C662EB71FBAB9";
int len = strlen(gky)/2;
BYTE* GKY = new BYTE[len];
ByteUtil::StringToHex(gky, GKY);
ByteUtil::LogArray("GKY", GKY, len);
delete[] GKY;

this particular code snippet outputted this

2013-02-15.10:03:19     GKY(24)- 55:D3:85:77:09:3A:88:F3:B5:EA:40:BB:F1:11:58:81:3A:2C:66:2E:B7:1F:BA:B9:


texts:
I am developing a BlackJack game using Java, and it came to a point that I am using instanceof operator to determine if it is a type of some subclass.

Here's an example:

public void checkForBlackJack(Player player) {
        Hand fHand = player.getHands().get(0);
        if (fHand.getCardScore() == 21) {
            fHand.setBlackjack(true);
        }

        if(player instanceof BlackJackPlayer){
            BlackJackPlayer bjplayer = (BlackJackPlayer) player;

            if(bjplayer.isSplit()){
                //Check the users other hand if it is already blackjacked
            }
        }
    }

Is using instanceof considered to be bad for such example?  Just as an overview, here is my class diagram:

I've decided to use instanceof to check for blackjack because The Dealer can also get blackjack.


texts:
This is based (somewhat loosely) on the code written in this railscast. I'm planning to re-use it in different places throughout the site, so I made it a bit more generic rather than based on IDs. However, I'm certain there's probably room for improvement.

jQuery ->
  $('.org_type_choice').each ->
    cat_obj = $(this).find('.org_category')
    type_obj = $(this).find('.org_type')
    categories = cat_obj.html()

    org_type = type_obj.find(':selected').text()
    opts = $(categories).filter("optgroup[label='#{org_type}']").html()
    cat_obj.html(opts)

    type_obj.change ->
      org_type = $(this).find(':selected').text()
      opts = $(categories).filter("optgroup[label='#{org_type}']").html()
      cat_obj.html(opts)


texts: Increase performance creating Mandelbrot set in python

texts:
I created a program in python that generates an image of the mandelbrot set. The only problem I have is that the program is quite slow, it takes about a quarter of an hour to generate the following image of 2000 by 3000 pixels:

I first created a matrix of complex numbers using numpy according to amount of pixels. I also created an array for the image generation.

import numpy as np
from PIL import Image

z = 0

real_axis = np.linspace(-2,1,num=3000)
imaginary_axis = np.linspace(1,-1,num=2000)

complex_grid = [[complex(np.float64(a),np.float64(b)) for a in real_axis] for b in imaginary_axis]

pixel_grid = np.zeros((2000,3000,3),dtype=np.uint8)

Then I check whether each complex number is in the mandelbrot set or not and give it an RGB colour code accordingly.

for complex_list in complex_grid:
    for complex_number in complex_list:
        for iteration in range(255):
            z = z**2 + complex_number
            if (z.real**2+z.imag**2)**0.5 > 2:
                pixel_grid[complex_grid.index(complex_list),complex_list.index(complex_number)]=[iteration,iteration,iteration]
                break
            else:
                continue
        z = 0

Finally I generate the image using the PIL library.

mandelbrot = Image.fromarray(pixel_grid)
mandelbrot.save("mandelbrot.png")

I am using jupyter notebook and python 3. Hopefully some of you can help me improve the performance of this program or other aspects of it.


texts:
My solution to implement a status (string) from combining two other ones.
I need to declare a function which takes two params (two strings) and needs to return another one based on the combination of those two strings.
For ex:
carStatus(status, secondaryStatus) => string

where secondaryStatus can have multiple options.
I'm using an if/else if statement which returns a third status which I need.
For ex when status is 'OPEN' and secondaryStatus is 'payment1' or 'payment2' or 'payment3', the function must return a new string (status) like 'CONFIRMED'.
So, my solution at this moment would be something like this:
carStatus = (status, secondaryStatus) => {
  if(status === 'OPEN' && (secondaryStatus === 'payment1' || 'payment2' || 'payment3')){
    return 'CONFIRMED';
  } else if(status === 'CANCELLED' && (secondaryStatus === 'payment4' || 'payment5' || 'payment6')){
    return 'REMOVED';
  } else if(status === 'REVIEW' && (secondaryStatus === 'payment2' || 'payment5' || 'payment5')){
    return 'CHECKED';
  }
}

carStatus('OPEN', 'payment1')

In div must be rendered 'CONFIRMED'.
In my implementation, I'll have to write I think other 5 else if statements.. so maybe there is a cleaner way to implement this.
Any help will be appreciated.


texts: A singly linked list implementation in C

texts:
How is this Implementation of a list in C?

Please tell me whether it is good or please mention any problems.
It is a singly linked List and I tried to do it recursively.

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

struct node{
    int value;
    struct node *next;
};

void add(struct node *lst, int num){
    if(lst->next == NULL){
        lst->value = num;
        lst->next = (struct node*)malloc(sizeof(struct node*));
        lst->next->next = NULL;
    }else{
        add(lst->next, num);
    }
}

void print_lst(struct node *lst){
    if(lst->next == NULL){

    }else{
        printf("\n%d", lst->value);
        print_lst(lst->next);
    }
}

int length(struct node *lst){
    if(lst->next == NULL){
        return 0;
    }else{
        return 1 + length(lst->next);
    }
}

int get(struct node *lst, int pos){
    if(pos < 0 ||  pos >= length(lst)){
        fprintf(stderr ,"\nIndexOutOfBoundsException\n");
    }else if(pos > 0 && pos <length(lst)){
        pos += -1;
        get(lst->next, pos);
    } else if (pos == 0){
        return  lst->value;
    }
}

int main ( ) {

    struct node lst;
    lst.next = NULL;
    add(&lst, 13);
    add(&lst, 12);
    add(&lst,  1);
    add(&lst, 10);
    add(&lst, 10);
    add(&lst, 4);
    //print_lst(&lst);
    printf("\n%d", get(&lst, 2));
    printf("\n%d", get(&lst, 5));
    printf("\n%d", get(&lst, 13));

    printf("\n\n%d", length(&lst));
    return 0;
}


texts: Bash functions to run/manage MySQL, Redis, Sidekiq, Rails server

texts:
I'm working with a Rails app that requires a few layers of infrastructure to run: MySQL, Redis, Sidekiq, and (of course) the Rails server. I wrote some functions to help me manage the various servers (start/stop/check and one to kill the rails server when it gets hung up and decides to eat all my memory rather than shutting down).

I'm still new to Bash scripting, and looking for all the feedback/criticism I can get, so please, don't hold back. I'm particularly interested in how I can further DRY up this code.

Generic helpers to check if a named process is running and get its pid:

function running {
  pgrep -f "$1" &> /dev/null
}

function rpid {
  pgrep -f "$1" 2> /dev/null
}

MySQL server:

function msta {
  if ! running mysql; then
    mysql.server start
  else
    echo "MySQL already running"
  fi
}

function msto {
  if running mysql; then
    mysql.server stop
  else
    echo "MySQL not running"
  fi
}

function mstat {
  if running mysql; then
    echo "MySQL running"
  else
    echo "MySQL not running"
  fi
}

Redis server:

function resta {
  if ! running redis; then
    redis-server ~/.redis/redis.conf
    until running redis; do
      sleep 1
    done
    echo "Redis daemon started"
  else
    echo "Redis daemon already running"
  fi
}

function resto {
  if running redis; then
    kill $(rpid redis)
    while running redis; do
      sleep 1
    done
    echo "Redis daemon stopped"
  else
    echo "Redis daemon not running"
  fi
}

function restat {
  if running redis; then
    echo "Redis daemon running"
  else
    echo "Redis daemon not running"
  fi
}

Sidekiq:

function sksta {
  if ! running sidekiq; then
    sidekiq -d
    until running sidekiq; do
      sleep 1
    done
    echo "Sidekiq daemon started"
  else
    echo "Sidekiq daemon already running"
  fi
}

function sksto {
  if running sidekiq; then
    kill $(rpid sidekiq)
    while running sidekiq; do
      sleep 1
    done
    echo "Sidekiq daemon stopped"
  else
    echo "Sidekiq daemon not running"
  fi
}

function skstat {
  if running sidekiq; then
    echo "Sidekiq daemon running"
  else
    echo "Sidekiq daemon not running"
  fi
}

Rails server:

# kill the Rails server
function krs {
  if running 'rails s'; then
    kill $1 $(rpid 'rails s')
    for i in 1 2; do
      if ! running 'rails s'; then
        break
      else
        sleep 1
      fi
    done
    reportkill
  else
    echo "Rails server not running"
  fi
}

function reportkill {
  if ! running 'rails s'; then
    echo "Rails server killed"
  else
    echo "Rails server survived (pid $(rpid 'rails s'))"
  fi
}

# when a `kill -9` is required
function krs9 {
  krs '-9'
}

function rastat {
  if running 'rails s'; then
    echo "Rails server running"
  else
    echo "Rails server not running"
  fi
}

MySQL + Redis + Sidekiq

function asta {
  msta && resta && sksta
}

function asto {
  sksto && resto && msto
}

function astat {
  mstat && restat && skstat
}


texts:
This is a little yet unfinished RPG I made with C#. It runs well but I'm wondering if there are things I could improve to make it more clear or optimal.  I'm basically asking for some feedback and suggestions.

The program is obviously not finished but I'm asking now before I move on so I know if I got some serious design or logic issues there. I'm a beginner in programming so keep that in mind when answering.

class Main
{
    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("1. New Game\n" +
                          "2. Load Game\n" +
                          "3. Exit Game\n");
        string choice = Console.ReadLine();
        bool correctChoice = false;
        Hero newHero = new Hero();
        while (correctChoice == false)
        {
            switch (choice)
            {
                case "1":

                    CharacterCreation.createChar(newHero);
                    correctChoice = true;
                    break;
                case "2":
                    Console.WriteLine("This feature is not yet implemented.");
                    correctChoice = false;
                    break;
                case "3":
                    Environment.Exit(0);
                    break;
                default:
                    Console.WriteLine("Please enter a correct value.");
                    break;
            }
            if (correctChoice == true)
                break;
            else
                choice = Console.ReadLine();
        }
        Console.WriteLine("\n Your character is {0}, a {1}.", newHero.heroName, newHero.heroClass);

        Console.ReadLine();
    }
}

class CharacterCreation
{
    public static void createChar(Hero newHero)
    {
        Console.WriteLine("\n We will proceed in character creation.");
        Console.WriteLine("Please enter your character name:");
        newHero.heroName = Console.ReadLine();

        Console.WriteLine("\nNow choose your character's class: \n" +
                          "Warrior......1\n" +
                          "Mage........2\n" +
                          "Rogue........3");
        string classChoice = Console.ReadLine();
        bool correctChoice = false;
        while (correctChoice == false)
        {
            switch (classChoice)
            {
                case "1":
                    newHero.heroClass = "Warrior";
                    correctChoice = true;
                    break;
                case "2":
                    newHero.heroClass = "Mage";
                    correctChoice = true;
                    break;
                case "3":
                    newHero.heroClass = "Rogue";
                    correctChoice = true;
                    break;
                default:
                    Console.WriteLine("Please enter a correct value.");
                    break;
            }
            if (correctChoice == false)
                classChoice = Console.ReadLine();
            else break;
        }
        Hero.ClassSelect(newHero);
    }
}

class Character
{
    public int charHealth, charMaxHealth, charStr, charInt, charAgi;
}

class Hero : Character
{
    public string heroName, heroClass;
    public int level, experience, gold;

    public static void ClassSelect(Hero newHero)
    {
        newHero.charAgi = 10;
        newHero.charInt = 10;
        newHero.charMaxHealth = 100;
        newHero.experience = 0;
        newHero.gold = 0;
        newHero.level = 1;

        switch (newHero.heroClass)
        {
            case "Warrior":
                newHero.charMaxHealth = newHero.charMaxHealth * 115 / 100;
                newHero.charStr = newHero.charStr * 12 / 100;
                break;
            case "Mage":
                newHero.charInt = newHero.charInt * 12 / 100;
                break;
            case "Rogue":
                newHero.charAgi = newHero.charAgi * 12 / 100;
                break;
        }
        newHero.charHealth = newHero.charMaxHealth;
    }
}


texts: Convert boolean list to list of base10 integers

texts:
Context:

I'm coding up a simple genetic optimization algorithm from first principles, and have decided to use boolean/binary strings as genes so that I can flip bits on or off as a form of mutation. In order to evaluate the fitness of the solutions that it generates I need to be able to decode the binary strings produced into the integer values that I'm optimizing for. The genetic optimization technique that I'm using returns it's individuals as a list, so I am extracting the integers as follows:

Problem:

Take the boolean/binary list...

l = [1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1]

...split it into 8-bit sublists...

[[1, 0, 1, 0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0, 1, 1]]

...concatenate each sublist into a string...

[10100111, 101010, 111011]

...convert those strings from binary to decimal...

[167, 42, 59]

...then scale those integers between 50 and 150...

[115, 66, 73]

My solution:

[int(int(str(bin), 2)/2.55)+50 for bin in [int(''.join(\
    map(str,num))) for num in [l[i:i +8] for i in range(0, len(l), 8)]]]

This feels like a very ugly way to go tackle the problem - can anyone come up with a nicer way to go about it?


texts:
I have recently implemented a code to accomplish Object-to-String. Can you suggest any pros and cons with regard to the code?

public static string ObjectToXml(object obj)
{
    var oXmlSerializer = new XmlSerializer(obj.GetType());
    var oStringWriter = new StringWriter();
    var oXmlSerializerNamespaces = new XmlSerializerNamespaces();
    oXmlSerializerNamespaces.Add(string.Empty,string.Empty);
    var oXmlWriterSettings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = false,
        Encoding = Encoding.GetEncoding("ISO-8859-1")
    };

    var oXmlWriter = XmlWriter.Create(oStringWriter,oXmlWriterSettings);
    oXmlSerializer.Serialize(oXmlWriter, obj, oXmlSerializerNamespaces);
    oXmlWriter.Close();
    return oStringWriter.ToString();
}


texts: optimize binary classification method for speed

texts:
I have the following code for determining TP, TN, FP and FN values for binary classification given two sparse vectors as input (using the sparse library):
def confused(sys1, ann1):
    # True Positive (TP): we predict a label of 1 (positive), and the true label is 1.
    TP = np.sum(np.logical_and(ann1 == 1, sys1 == 1))

    # True Negative (TN): we predict a label of 0 (negative), and the true label is 0.
    TN = np.sum(np.logical_and(ann1 == 0, sys1 == 0))

    # False Positive (FP): we predict a label of 1 (positive), but the true label is 0.
    FP = np.sum(np.logical_and(ann1 == 0, sys1 == 1))

    # False Negative (FN): we predict a label of 0 (negative), but the true label is 1.
    FN = np.sum(np.logical_and(ann1 == 1, sys1 == 0))

    return TP, TN, FP, FN

I'm trying to find a way to optimize this for speed. This is based on how-to-compute-truefalse-positives-and-truefalse-negatives-in-python-for-binary-classification-problems where my addition was to add the sparse arrays to optimize for memory usage, since the input vectors for the current problem I am trying to solve have over 7.9 M elements, and the positive cases (i.e., 1), are few and far between wrt the negative cases (i.e., 0).
I've done profiling of my code and about half the time is spent in this method.


texts:
I implemented qsort() like this. I was wondering what improvements I could do to make it better.

public static void qsort(int[] a, int start, int end) {
    if (start >= end) return;
    int pivot = start;
    int lt = start + 1;
    int gt = end;
    int temp;
    while (lt <= gt) {
        if (a[pivot] > a[lt]) {
            temp = a[pivot];
            a[pivot] = a[lt];
            a[lt] = temp;
            pivot = lt++;
        } else {
            while (gt >= lt)  {
                if (a[gt] < a[lt]) {
                    temp = a[lt];
                    a[lt] = a[gt];
                    a[gt] = temp;
                    break;
                }
                gt--;
            }
            gt--;
        }
    }
    qsort(a, start, pivot - 1);
    qsort(a, pivot + 1, end);
}


texts: Raising an error if a variable is not created during class initalization

texts:
I would like to properly raise an error if self._header was not created when I initialize a NewFile object.

This is working now, but perhaps there is more formal way of catching the error below:

class NewFile(object):
    """ Docstring """

    def __init__(self, filename):
        self.localdir = 'C:\\Users\\User\\Documents'
        self.filename = filename
        self.filepath = os.path.join(self.localdir, self.filename)
        self._data = []

        try:
            with open(self.filepath, 'rU') as c:
                rows = csv.reader(c)
                for row in rows:
                    row[:] = [r.lower().strip() for r in row]

                    if row[0].startswith('name'):
                        self._header = row     # Create Header Variable

                    self._data.append(row)

        except IOError:
            raise IOError(
                '"{}" not found in "{}"'.format(self.filename, self.localdir))

        # I would like to raise error if "self._header" was not created
        try:
            self._header
        except AttributeError:
            raise AttributeError(
                'No Header not found in "{}"'.format(self.filename))

def main():
    f = 'samplefile.csv'
    new = NewFile(f)

if __name__ == '__main__':
    main()


texts: Creating a backup of a website directory inside the Web Application Root directory in *nix

texts:
In CentOS I have a Web Application Root on which I have a website directory.
I would like to make an immediate backup of that website's directory by using the zip utility. The code works and tested.

Although I already use set -x and zipping is verbose (I'm not sure if due to set -x or zip default behavior), the trace is super long and hard to follow - I cant vertically-scroll all of the way top of it through Putty Window in Windows10 Home.
I fear I don't have enough testing to ensure that the file was created, in what size (to assume the size is plausible) and such (maybe just adding ls -la ${war}/mediawiki_general_backups, is enough):

date="$(date +%F-%T)"
war="$HOME/public_html" # Web Application Root
domain="example.com"
zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${date}.zip" "${war}/${domain}"


texts:
I have created a scraper for yell.com in vba. The scraper is efficient enough to pull data from that site, whatever the search parameter is. If any link from that site is given to my parser, it is able to scrape the whole records irrespective of how many pages it has spread across. There is no "a" tag for the first page in pagination option for this reason it was previously scraping all the records except for the first page. However, I've fixed that issue and now it is working flawlessly pulling all the records available there. I tried to make it accurate yet there are always rooms for improvement.

Sub Yell_parser()
Const mlink = "https://www.yell.com"
Dim http As New XMLHTTP60
Dim html As New HTMLDocument, html2 As New HTMLDocument
Dim page As Object, newlink As String
Dim I As Long, x As Long

With http
    .Open "GET", "https://www.yell.com/ucs/UcsSearchAction.do?keywords=coffee&location=United+Kingdom&scrambleSeed=1370600159", False
    .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
    .send
    html.body.innerHTML = .responseText
End With

Set page = html.getElementsByClassName("row pagination")(0).getElementsByTagName("a")

' First page first, selected already, 'row pagination' doesn't have 'a' for it
GetPageData x, html

For I = 0 To page.Length - 2
    newlink = mlink & Replace(page(I).href, "about:", "")
    With http
        .Open "GET", newlink, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        .send
        html2.body.innerHTML = .responseText
    End With

    ' Next pages start from here

    GetPageData x, html2
Next I
End Sub

Sub GetPageData(ByRef x, ByRef html As HTMLDocument)
    Dim post As HTMLHtmlElement
    For Each post In html.getElementsByClassName("js-LocalBusiness")
        x = x + 1
        With post.getElementsByClassName("row businessCapsule--title")(0).getElementsByTagName("a")
            If .Length Then Cells(x + 1, 1) = .item(0).innerText
        End With
        With post.getElementsByClassName("col-sm-10 col-md-11 col-lg-12 businessCapsule--address")(0).getElementsByTagName("span")
            If .Length > 1 Then Cells(x + 1, 2) = .item(1).innerText
        End With
        With post.getElementsByClassName("col-sm-10 col-md-11 col-lg-12 businessCapsule--address")(0).getElementsByTagName("span")
            If .Length > 2 Then Cells(x + 1, 3) = .item(2).innerText
        End With
        With post.getElementsByClassName("col-sm-10 col-md-11 col-lg-12 businessCapsule--address")(0).getElementsByTagName("span")
            If .Length > 3 Then Cells(x + 1, 4) = .item(3).innerText
        End With
        With post.getElementsByClassName("businessCapsule--tel")
            If .Length > 1 Then Cells(x + 1, 5) = .item(1).innerText
        End With
    Next post
End Sub


texts: Reading Maps of strings and doubles from CSV

texts:
I want to have 2 classes responsible for reading dictionaries from CSV.
The 1st class takes 2 columns from CSV and makes Map<String, String>.
The 2nd class takes 2 columns from CSV and makes Map<String, Double>.

I want to solve it according to DRY rule so I've made a generic method for making Map<T1, T2> from csv which will be used by 1st class and 2nd class. It goes like this:

package Main;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;

public interface MapFromCsv<T1, T2> {

    public default Map<T1, T2> getMap(String FILE_TO_LOAD, Function<String, T1> foo1, Function<String, T2> foo2){
        Map<T1, T2> mapResult = new HashMap<>();
        File f = new File(FILE_TO_LOAD);
        try (Scanner sc = new Scanner(f)) {
            while (sc.hasNextLine()) {
                String tmp = sc.nextLine();
                String[] tmp2 = tmp.split(";");
                mapResult.put((T1) foo1.apply(tmp2[0]), (T2) foo2.apply(tmp2[1]));
            }
        } catch (FileNotFoundException fntf) {
            System.err.println("File " + f.getPath() + "was not found.");
        } catch (Exception e) {
            System.err.println("Something went wrong with reading " + f.getPath());
        }
        return mapResult;
    }
}

and implementation of the first class for making Map<String, String> goes like this:

package Main;

import java.util.Map;

public enum StringMapFromCsv implements MapFromCsv<String, String> {

    INSTANCE;
    final String FILE_TO_LOAD = "resources/stringMap.csv";
    private Map<String, String> stringMap;

    private StringMapFromCsv() {
        initStringMap();
    }

    private void initStringMap() {
        this.stringMap = getMap(FILE_TO_LOAD);
    }

    public void reloadStringMap() {
        initStringMap();
    }

    public Map<String, String> getStringMap() {
        return stringMap;
    }

}

and implementation of the second class for making Map<String, Double> goes like this:

package Main;

import java.util.Map;

public enum DoubleMapFromCsv implements MapFromCsv<String, Double>{

    INSTANCE;
    final String FILE_TO_LOAD = "resources/doubleMap.csv";
    private Map<String, Double> doubleMap;

    private DoubleMapFromCsv() {
        initDoubleMap();
    }

    private void initDoubleMap() {
        this.doubleMap = getMap(FILE_TO_LOAD);
    }

    public void reloadDoubleMap() {
        initDoubleMap();
    }

    public Map<String, Double> getDoubleMap() {
        return doubleMap;
    }

}

Anu suggestions?


texts:
A parallel map written in Rust. I am new to Rust and wondering if there is things that could be done better or more efficiently.
use crossbeam_channel::unbounded;
use std::{thread, time};

fn parallel_map<T, U, F>(mut input_vec: Vec<T>, num_threads: usize, f: F) -> Vec<U>
where
    F: FnOnce(T) -> U + Send + Copy + 'static,
    T: Send + 'static,
    U: Send + 'static + Default,
{
    let mut output_vec: Vec<U> = Vec::with_capacity(input_vec.len());
    let mut threads = Vec::new();

    let (in_s, in_r) = unbounded::<(T, usize)>();
    let (out_s, out_r) = unbounded::<(U, usize)>();

    for _ in 0..num_threads {
        let in_r = in_r.clone();
        let out_s = out_s.clone();
        threads.push(thread::spawn(move || {
            while let Ok((value, index)) = in_r.recv() {
                let res = f(value);
                out_s.send((res, index)).expect("Failed to send");
            }
        }));
    }

    while let Some(val) = input_vec.pop() {
        in_s.send((val, input_vec.len())).expect("Failed to send");
    }

    drop(in_s);
    drop(out_s);

    let mut collect_results: Vec<(U, usize)> = Vec::with_capacity(output_vec.capacity());
    while let Ok(res) = out_r.recv() {
        collect_results.push(res);
    }

    collect_results.sort_by(|(_, a_index), (_, b_index)| a_index.partial_cmp(b_index).unwrap());

    output_vec.extend(collect_results.into_iter().map(|(val, _)| val));

    for thread in threads {
        thread.join().expect("Failed to join thread");
    }

    output_vec
}

fn main() {
    let v = vec![6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 12, 18, 11, 5, 20];
    let squares = parallel_map(v, 10, |num| {
        println!("{} squared is {}", num, num * num);
        thread::sleep(time::Duration::from_millis(500));
        num * num
    });
    println!("squares: {:?}", squares);
}
```


texts: Returning the lowest and highest number based on input

texts:
This simple console program prompts the users for a number and returns the lowest and highest numbers from their inputs. It is difficult to add more user inputs, though. How can I make this easier to maintain and extend?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1 = 0, num2 = 0, num3 = 0;

            Console.WriteLine("lowest");

            Console.WriteLine("input 1st number");
            num1 = int.Parse(Console.ReadLine());

            Console.WriteLine("input 2nd number");
            num2 = int.Parse(Console.ReadLine());

            Console.WriteLine("input 3rd number");
            num3 = int.Parse(Console.ReadLine());

           Console.WriteLine("input 4th number");
            num4 = int.Parse(Console.ReadLine());

               Console.WriteLine("input 5th number");
            num5 = int.Parse(Console.ReadLine());

            Console.Clear();

            int lowest = ((num1 < num2 ? num1: num2) < num3 ?
                (num1 < num2 ? num1 : num2) : num3);
            int highest = ((num1 > num2 ? num1: num2) > num3 ?
                (num1 > num2 ?  num1 : num2)  : num3) ;

            Console.WriteLine(" lowest is {0} ", lowest);
            Console.WriteLine(" highest is {0} ", highest);
            Console.ReadLine();
        }
    }
}


texts: Reader for graph-file with ugly return and questionable use of streams

texts:
I wrote a class that contains a static method that reads in files from NetworkRepository and converts them into a list of integer-arrays, each representing an edge. The file format from NetworkRepository is, that each line which is not a comment contains two integer numbers, the IDs of vertices connected by an edge, seperated by whitespace (tabs/spacebar).
Example:

corresponds to:

1 2
1 3
2 3
3 4

Can my code for this be improved? I really don't like the unreachable return null, but I don't need error-handling except that I know I provided the wrong path.

public static List<Integer[]> edges_from_path(final String filePath) {
    //captures only lines that consist of two positive integer numbers separated by whitespace (each line encodes an edge)
    final String LINE_DATA_FORMAT = "\\d+\\s+\\d+";
    final String SEPARATOR = "\\s+";
    try {
        return Files.lines(Paths.get(filePath))
                .filter(str -> str.matches(LINE_DATA_FORMAT))
                .map(str -> Arrays.stream(str.split(SEPARATOR)).map(Integer::parseInt).toArray(Integer[]::new))
                .collect(toList());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

My method doesn't return a graph because I want to be able to create graphs from different sources, and a list of integer-pairs is the interface the constructor for graphs is supposed to use.