Arithmetic on numbers provided by user import java.util.Scanner;

public class CAI {

    public static void main(String[] args) {

        Scanner cai = new Scanner(System.in);

        System.out.println("Caluclator");

        System.out.println("\nHere are your options:");
        System.out.println("\n1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Division");
        System.out.println("4. Multiplication");

        System.out.print("\nWhat would you like to do?: ");
        int choice = cai.nextInt();
        System.out.println();

        if (choice == 1){
            addition();
        }
        else if (choice == 2){
            subtraction();
        }
        else if (choice == 3){
            division();
        }
        else if (choice == 4){
            multiplication();
        }

        System.out.println();
        cai.close();
    }

    public static void addition(){

        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Addition");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " + " + Two + " = " + (One + Two));
    }

    public static void subtraction(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Subtraction");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " - " + Two + " = " + (One - Two));
    }

    public static void division(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Division");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " / " + Two + " = " + (One / Two));
    }

    public static void multiplication(){
        int One, Two;
        Scanner cai = new Scanner(System.in);

        System.out.println("Multiplication");

        System.out.print("\nFirst Number: ");
        One = cai.nextInt();

        System.out.print("\nSecond Number: ");
        Two = cai.nextInt();

        cai.close();
        System.out.println("\nSum: " + One + " x " + Two + " = " + (One * Two));
    }
}

ok So i have this project for a class and what i am trying to do is make addition questions that would pick the numbers i chose randomly and make questions out of them, i am also trying to have the user to write the answer and let them know if the answer they chose is right or wrong. I know its a lot to ask but my project is due in 2 hours and i need help

Validating user input
The way that you capture user input is quite brittle. While it will work fine as long as the user knows they should only input integers, it's never safe to assume that users will provide valid input:
What would you like to do?:  hello
Exception in thread "main" java.util.InputMismatchException

We first need to handle this InputMismatchException for cases where the user enters an invalid value, by using try-catch:
try {
    choice = cai.nextInt();
} catch (InputMismatchException exc) {
    System.out.println("Invalid input");
}

This is not quite right yet, though; even though it handles the exception and prevents a program crash, we need to not leave this block until we actually have input we can use. So let's introduce a validation condition and a while loop:
int choice = 0;
boolean inputIsInteger = false;
while (!inputIsInteger) {
    System.out.print("\nWhat would you like to do?: ");
    try {
        choice = cai.nextInt();
        inputIsInteger = true;
    } catch (InputMismatchException exc) {
        System.out.println("Input must be an integer.");
        cai.next();
    }
}

Now, that works pretty well:
What would you like to do?:  hello
Input must be an integer.

What would you like to do?:  1

Addition

You may think: "But, that seems like a lot of code to handle one single user input!"
And you would be right! Fortunately, Scanner has a built-in method hasNextInt() that does this in a much simpler way:
System.out.print("\nWhat would you like to do?: ");
while (!cai.hasNextInt()) {
    System.out.println("Input must be an integer.");
    cai.nextLine();
    System.out.print("\nTry again: ");
}
int choice = cai.nextInt();

This way our Scanner will keep looping until it finds a valid int in the input buffer, making it safe to then call nextInt().

So far, so good. Now, I noticed that you are needing to get integer inputs everywhere in your code... We could save us a lot of copying and pasting of the above code by making a method that does this for us:
private static int getIntInput(Scanner sc) {
    while (!sc.hasNextInt()) {
        System.out.println("Input must be an integer.");
        sc.nextLine();
        System.out.print("\nTry again: ");
    }
    return sc.nextInt();
}

Then, each time we need to scan for an int, we just call it with an instance of Scanner:
System.out.print("\nWhat would you like to do?: ");
int choice = getIntInput(cai);

You should also validate that the input is usable according to your program logic, for instance that the choice is a valid choice (i.e. 1 - 4) otherwise ask the user for valid input. This should be easily done using another while loop or some similar construct.
boolean isValidChoice = false;
int choice = 0;
while (!isValidChoice) {
    System.out.print("\nWhat would you like to do?: ");
    choice = getIntInput(cai);
    if (choice > 0 && choice <= 4) {
        isValidChoice = true;
    } else {
        System.out.println("\nChoose an option from 1 to 4: ");
    }
}

if (choice == 1){
    addition();
}
// etc...

Other things
Here are some other concerns & suggested improvements on the code.

Consider moving your menu selection out of main and into its own method, like calculatorMainMenu() and call that when you need it.

The (One / Two) calculation in your division() method can result in ArithmeticException due to possible division-by-zero error. You should validate Two to make sure that 0 is never acceptable as input.

Consider using a switch statement instead of a lot of if-else for things like your menu, where you're just comparing a variable against some constants.

Naming an instance of Scanner as cai is pretty odd. Writing something like scanner or sc for short is much more commonplace.

The names One and Two are also a bit odd. Something like num1 and num2 would be better, I think, to make it simple and clear that there's no particular significance to them other than the order in which they appear.

"Caluclator" should be spelled "Calculator"

Only the result of an addition is called "sum". To be correct, you should use "difference" for subtraction, "product" for multiplication, and "quotient" for division.


Parsing an array of comma-numbers obtained from an input dialog I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some incite as to how I can do this more efficiently i.e. fewer lines of code.

I love to make my code elegant, but I don't see how to do it any better.

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    int w = 0, a = 0, y = -1;
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            w++;
        }
    }
    Double[] z = new Double[w];
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            z[a] = Double.parseDouble(x.substring((y + 1), i));
            y = i;
            a++;
        }
    }

I suggest next way:

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    String[] split = x.split(",");
    Double[] z = new Double[split.length];
    int i = 0;
    for (String s : split) {
        if(s.trim().isEmpty()){
            continue;
        }
        try {
            z[i++] = Double.valueOf(s.trim());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

1)split() instead of loop for ','

2)validate spaces

read more about String class and it's functions.


Calculate a month later than current month (without rolling over to next month) I needed a script for working out billing dates over a period of time.  The date should be the same day every month however if the billing date starts on a date that doesn't exist in another month, then it should be on the last day of that month. This rules out the DateTimeInterval Object, because that causes months to 'rollover' (31/01 becomes 03/03 etc.) which is unacceptable for my use case.

Try as I might, I couldn't find anything in-built to accommodate for this, so I wrote the following, however it seems like a lot of code for what I'm trying to achieve so I was wondering if anyone could suggest a better / in-built way?

$replaceVars = array(
    'effectivedate' => '30-9-2014',
    'vatpc'         => 0.15,
    'paymentamount' => 150.00,
    'duration'      => 12
);

$effectivedateObj = new DateTime($replaceVars['effectivedate']);

$iD = array(
    'd' => $effectivedateObj->format('d'),
    'm' => $effectivedateObj->format('m'),
    'y' => $effectivedateObj->format('Y')
);

$payments = '';

for ($i=0; $i < $replaceVars['duration']; $i++)
{
    $newDate = array(
        'd' => $iD['d'],
        'm' => (($iD['m'] + $i) > 12) ? (($iD['m'] + $i) % 12) : $iD['m'] + $i,
        'y' => (($iD['m'] + $i) > 12 ? $iD['y'] + 1 : $iD['y'])
    );

    if($newDate['d'] > cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']))
    {
        $newDate['d'] = cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']);
    }

    $paymentString = '
';

    $paymentString .= 'Payment Number '.($i+1).'	';
    $paymentString .= ''. $newDate['d'] .'/'. $newDate['m'] .'/'. $newDate['y'] .'	';
    $paymentString .= '&pound;'. round(( $replaceVars['paymentamount'] + ( $replaceVars['paymentamount'] * $replaceVars['vatpc'] )), 2) .'	';

    $paymentString .= '
';

    $payments .= $paymentString;

    echo $paymentString . '
';
}

The top array and the lines that build the string are just for testing, but it still seems like a lot of code?

Also I have no idea how necessary my parenthesis are when creating ternary statements, and I do feel a bit neurotic about the amount that I use, so some advice on that would be appreciated.

I'm inclined to keep it simple:

$start = new DateTime('30-Jan-2014', new DateTimeZone("America/Toronto"));
$end = clone $start;
$end->modify('+1 month');
while (($start->format('m')+1)%12 != $end->format('m')%12) {
    $end->modify('-1 day');
}
echo $end->format('d-M-Y');

This just checks to see if the month is the expected one, and if not, backs up one day at a time until it is.  The advantage is that it's short, clear, and will work even in leap years (try 2004 to verify that).

Edit: It's also easy to make this into a user-defined function:

function addMonth($begin)
{
    $end = clone $begin;
    $end->modify('+1 month');
    while (($begin->format('m')+1)%12 != $end->format('m')%12) {
        $end->modify('-1 day');
    }
    return $end;
}


Memory efficient Log Parser I wrote this together for a test I'm doing that parses the Heroku access log. What I'm mainly interested is if this code follow common best practices and if there are any improvements I can make in terms of memory efficiency.

Here is a line from the Heroku from their docs:

  2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET
  path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204"
  dyno=web.1 connect=1ms service=18ms status=200 bytes=975

And an endpoint is a line that looks like this:

  GET /api/users/{user_id}/count_pending_messages

class FileReader

  def initialize(filename, start_at = nil, end_at = nil, endpoints = nil)
    @filename = filename
    @start_at = start_at
    @end_at = end_at
    @endpoints = endpoints
  end

  def read
    File.foreach(@filename).map { |l|
      # saving some memory here by only loading data into memory that we need
      unless @start_at.nil? or @end_at.nil?
        start = l.index(@start_at)
        finish = l.index(@end_at) - 2
        l[start..finish]
      else
        l
      end
    }
  end

  def endpoints
    File.foreach(@endpoints).map { |line| line.split }
  end

end

require 'forwardable'

class AccessParser
  extend Forwardable

  def_delegators :@reader, :read, :endpoints

  REGEX_MATCH_DIGITS = /\d+/
  PLACEHOLDER = '{user_id}'

  Uris = Struct.new(:method, :uri, :stats)
  Stats = Struct.new(:dyno, :response_time)

  def initialize(reader)
    @reader = reader
  end

  def parse

    uris = endpoints_to_uris

    read.each.map { |line|

      data = line_to_hash line

      method = data['method']
      uri = data['path'].sub(REGEX_MATCH_DIGITS, PLACEHOLDER)

      uris.each.map { |e|
        if uri == e.uri.to_s and method == e.method
          (e.stats.dyno ||= []) << data['dyno']
          response_time = data['connect'].to_i + data['service'].to_i
          (e.stats.response_time ||= []) << response_time
        end
      }
    }
    uris

  end

  private

  def endpoints_to_uris
    # using structs because it's faster than hashes
    endpoints.each.map { |e| Uris.new(*e, Stats.new) }
  end

  def line_to_hash(line)
    # using split because it's faster than regex
    Hash[line.split.each.map { |a| a.split('=') }]
  end

end

module Enumerable

  def sum
    inject(0.0) { |result, el| result + el }
  end

  def mean
    sum / size
  end

  def median
    len = sort.length
    (sort[(len - 1) / 2] + sort[len / 2]) / 2.0
  end

  def mode
    counter = Hash.new(0)
    entries.each.map { |i| counter[i] += 1 }
    mode_array = []
    counter.each.map { |k, v|  mode_array << k if v == counter.values.max }
    mode_array.sort.first
  end
end

class AccessConsoleWriter
  extend Forwardable

  def_delegators :@parser, :parse

  def initialize(parser)
    @parser = parser
  end

  def call
    parse.each do |d|
      puts "# #{d.method} #{d.uri}"
      puts "# " + "-" * (d.uri.length + d.method.length + 1)
      if d.stats.dyno.nil?
        puts "# Calls: 0"
      else
        puts "# Calls: #{d.stats.dyno.count}"
        puts "# Mean: #{d.stats.response_time.mean.round(2)}"
        puts "# Median: #{d.stats.response_time.median.round(2)}"
        puts "# Mode: #{d.stats.response_time.mode}"
        puts "# Dyno: #{d.stats.dyno.mode}"
      end
      puts ""

    end
  end

end

reader = FileReader.new('sample.log', 'method=', 'status=', 'endpoints.txt')
parser = AccessParser.new(reader)
AccessConsoleWriter.new(parser).call

I don't think that reading in entire files into memory, File.foreach(@filename).map { }.each.map { }.each { }, is going to be memory efficient. Which appears to be what would happen with AccessConsoleWriter.new(parser).call.

What you probably want to do is operate on one line at a time. For instance, you might be able to rewrite FileParser.endpoints to look like:

def endpoints(&block)
  File.foreach(@endpoints) do |line|
    block.call(line)
  end
end

A few other notes:

I don't see a lot of state being stored, so instantiating classes seems unnecessary.
For multi-line blocks, use do ... end instead of { ... }. https://github.com/bbatsov/ruby-style-guide#syntax
each in each.map is redundant.
each.map maps the returns of a block to a new array, but you seem to be ignoring that returned array in some places. In which case, using just each would be fine.
#call is a little confusing, as that's a method on Proc and others.
"...premature optimization is the root of all evil (or at least most of it) in programming."


Searching for something at a location I'm using Searchkick in a situation where a user might write the location they are searching for, or the thing they are searching for, or both.

I've been working on the below code for most of the day. As you can tell, I'm quite the beginner.

Ideally, what I want is something like this:

@portfolios = Portfolio.where(:published => true)
@portfolios = @portfolios.search
    params[:search] unless params[:search].nil?,
    where: {location: {near: coords, within: "300mi"}} unless params[:where].nil?

Is there any way to do that?

I'm asking because, currently this search uses two options. It's about to become quite a bit more complicated. The next step for instance, is to let the user select the range to search in.

Here's my code:

class SearchController < ApplicationController
  def index
        # Search functionality
        if params[:search].nil? or params[:search].empty? && params[:where].empty?
            @portfolios = Portfolio.where(:published => true).includes([:user, :portrait]).order('created_at DESC')
            return
        end

        if params[:where].empty?
            # User entered a query but not a location
            @portfolios = Portfolio.search params[:search], include: [:user, :portrait]

        elsif params[:search].empty?
            # User entered a location but not a query
            coords = Geocoder.coordinates(params[:where])
            @portfolios = Portfolio.search where: {location: {near: coords, within: "300mi"}}, include: [:user, :portrait]

        else
            # User entered a location and a query
            coords = Geocoder.coordinates(params[:where])
            @portfolios = Portfolio.search params[:search], where: {location: {near: coords, within: "300mi"}}, include: [:user, :portrait]
        end
  end
end

Just a quick review with changes I'd make if I were working with this controller in a rails project. I'll not changes I make in a list and paste your code with the alterations I've made at the end.

In the third line, you have if params[:search].nil? or params[:search].empty? && params[:where].empty?. I'm assuming you're aware of the operator precedence of or vs ||, but I personally prefer to avoid the or and and keywords as they can cause confusion (both to people new to ruby and myself when I inevitably derp something up)
I saw a lot of duplication in checking for the presence of params[:search] and params[:where]. Repetition of common logic is usually a good candidate for a new method. I created two new methods (search_params and where_params) which preformed these checks internally and returned nil whenever the respective parameter failed the presence checks you were already performing
A lot of what this controller was doing was figuring out what parameters were available in order to construct a list of arguments for Portfolio.search. I'm repeating what I did with the search_params and where_params methods I created and put together a new method for constructing the desired arguments for Portfolio.search
I considered making another method to DRY up the code in search_params and where_params, but I figured there wasn't enough duplication here to justify another method.

Results

class SearchController < ApplicationController
  def index
    if search_params.blank? && where_params.blank?
      @portfolios = Portfolio
        .includes([:user, :portrait])
        .where(published: true)
        .order('created_at DESC')

    else
      @portfolios = search_portfolio search_params, where_params
    end
  end

  private

  # Construct a search query using search arguments
  def search_portfolio(search: nil, coordinates: nil)
    search_args = [ { include: [:user, :portrait] } ]

    # Find portfolios near a given location if coordinates
    # have been provided
    if coordinates
      search_args.unshift({
        where: {
          location: {
            near: Geocoder.coordinates(coordinates),
            within: '300mi'
          }
        }
      })
    end

    # Filter results with a search query if a search
    # term was provided
    search_args.unshift(search) if search

    Portfolio.search(*search_args)
  end

  # Return `params[:search]` if it is present and non-empty,
  # otherwise return nil
  def search_params
    params.fetch(:search, nil).present? ? params[:search] : nil
  end

  # Return `params[:where]` if it is present and non-empty,
  # otherwise return nil
  def where_params
    params.fetch(:where, nil).present? ? params[:where] : nil
  end
end


Map reduce tester ported from bash to Python My MapReduce tester is clearly ported from Shell, short of args=None for line in args or read_input(), what's a better way of importing->testing the function outside of subprocess?
Or does it not matter, i.e.: my "hack" is fine?
test_mapreduce.py
from unittest import TestCase, main as unittest_main
from subprocess import check_output as run
from os import path

class TestMapReduce(TestCase):
    top_path = ''
    map_reduce = lambda self, mapper_name, reducer_name, datafile_name: run(
        ['python', path.join(self.top_path, reducer_name),  # Reduce
         run(['sort',  # Shuffle, could be replaced with python `sorted`
              run(['python', path.join(self.top_path, mapper_name),  # Map
                   path.join(self.top_path, 'data', datafile_name)])])])

    @classmethod
    def setUpClass(cls):
        if not path.isfile('setup.py'):
            cls.top_path = path.join('..', '..')
            if not path.isfile(path.join(cls.top_path, 'setup.py')):
                raise AssertionError("Haven't found right directory to `cd` into")

    def test_with_student_test_posts(self):
        print self.map_reduce('mapper.py', 'reducer.py', 'student_test_posts.csv')

if __name__ == '__main__':
    unittest_main()

mapper.py
#!/usr/bin/env python

from fileinput import input as read_input

def mapper():
    for line in read_input():
        data = line.strip().split('\t')

        if len(data) != 6:
            continue

        date, time, store, item, cost, payment = data
        print "{0}\t{1}".format(store, cost)

if __name__ == '__main__':
    mapper()

PS: Should I refactor to use the map and reduce inbuilt functions?

It's strange to use map_reduce = lambda ... to define a method. This is the same, written the common way:

def map_reduce(self, mapper_name, reducer_name, datafile_name):
    run(
        ['python', path.join(self.top_path, reducer_name),  # Reduce
         run(['sort',  # Shuffle, could be replaced with python `sorted`
              run(['python', path.join(self.top_path, mapper_name),  # Map
                   path.join(self.top_path, 'data', datafile_name)])])])

And this hack of calling python -> sort -> python is not fine at all. Python can certainly sort. Then your pipeline would become python -> python -> python, and at that point it's beyond silly to call subprocesses for this. You should do the whole thing in a single Python process, instead of 3 different processes.

Refactoring with map and reduce

Here's one way to refactor mapper to use Python's map function:

def line2cols(line):
    return line.strip().split('\t')

def has6cols(cols):
    return len(cols) == 6

def cols2out(cols):
    return '{}\t{}'.format(*cols)

def mapper():
    return map(cols2out, filter(has6cols, map(line2cols, read_input())))

And here's an example reducer using Python's reduce:

def reducer(seq):
    def f(a, b):
        if len(a) > len(b):
            return a
        return b
    return reduce(f, seq, '')

This is quite stupid, it just finds the longest string in the sequence.

I hope this helps.

UPDATE

It's a bit difficult to understand what you're trying to do.

  My MapReduce tester is clearly ported from Shell, short of args=None for line in args or read_input(), what's a better way of importing->testing the function outside of subprocess?

When I read this I didn't quite get what you're talking about shell. In the code I saw you're calling Python, twice, which is clearly not fine.

Let me try again, to guess what you're trying to do. Maybe you have a Python mapper script, and you have a Python reducer script, which you use in some framework? And you want to write some unit tests to check that these scripts in fact work? I mean the scripts as black boxes, as in, you want to test the complete scripts, rather than the underlying Python functions / classes? I'm really just guessing here, maybe I'm completely wrong.

If this is indeed what you want, then don't. Don't try to test the scripts, test the underlying implementation. If the implementation passes, the scripts should print correct output too. If you want to test the script outputs in addition to the underlying implementation, then you'd be just testing the basic ability to print, which seems rather pointless.


Check whether a string contains exactly one distinct vowel Over on Stack Overflow, someone asked a simple Haskell question: how to test whether there is exactly one distinct vowel in a given string. To clarify, there can be any number of non-vowel characters, and the vowel may be repeated any number of times (at least once!), but no other vowels may occur.

I proposed the below solution, and am feeling fairly proud of it: it seems clean, short, general, and readable. I have a hard time imagining an improvement to it, but I know there is still plenty of room for me to get better at Haskell, so there is probably something cool I'm missing. Would someone please look over this, and tell me what could be better, or confirm that it truly has reached Nirvana?

exactlyOne :: Eq a => (a -> Bool) -> [a] -> Bool
exactlyOne pred [] = False
exactlyOne pred (x:xs)
  |    pred x = not . any pred . filter (/= x) $ xs
  | otherwise = exactlyOne pred xs

exactlyOneVowel :: String -> Bool
exactlyOneVowel = exactlyOne (`elem` "aeiouAEIOU")

exactlyOne pred l = case filter pred l of
  [] -> False
  (x:xs) -> all (==x) xs

or equivalently

exactlyOne pred = (== (1 :: Natural)) . genericLength . nub . filter pred

since nub is lazy and takes O(optimal) time for this problem: If its input list has exactly one distinct member, the list is traversed once; if it has at least two, the list is traversed up to the second member and then (== (1 :: Natural)) knows to shortcut to False.

(I also like the operator .: and keep using it everywhere:)

infixr 8 .:
(f .: g) x = f . g x
exactlyOne = (== (1 :: Natural)) . genericLength . nub .: filter


Implementation of k-d-Tree I am a complete beginner in C and I have started learning it by implementing binary trees. So have implemented a basic k-d-Tree. I provide two structs and two methods for comparing values on different axis.

typedef struct Point2D {
    double x;
    double y;
} Point2D;

int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = (Point2D *) v1;
    const Point2D *p2 = (Point2D *) v2;
    if (p1->x < p2->x)
        return -1;
    else if (p1->x > p2->x)
        return +1;
    else
        return 0;
}

int y_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = (Point2D *) v1;
    const Point2D *p2 = (Point2D *) v2;
    if (p1->y < p2->y)
        return -1;
    else if (p1->y > p2->y)
        return +1;
    else
        return 0;
}

#define DIMENSION 2

typedef struct KdNode {
    Point2D *p;
    struct KdNode *left, *right;
    int splittingAxis;
} KdNode;

and my method for building the k-d-Tree :

KdNode* build(Point2D data[], int splittingAxis, int numberElements) {
    KdNode *temp = (KdNode*) malloc(sizeof(KdNode));
    KdNode *left = (KdNode*) malloc(sizeof(KdNode));
    KdNode *right = (KdNode*) malloc(sizeof(KdNode));
    if (temp == NULL || left == NULL || right == NULL) {
        exit(1);
    }
    if (numberElements == 0) {
        return NULL;
    }

    int median, numberElementsLeft, numberElementsRight;
    median = floor(numberElements / 2);
    Point2D leftSide[median], rightSide[numberElements - median - 1];
    splittingAxis = splittingAxis % DIMENSION;

    if (splittingAxis == 0) {
        qsort(data, numberElements, sizeof(Point2D), x_comparator);
    } else {
        qsort(data, numberElements, sizeof(Point2D), y_comparator);
    }

    numberElementsLeft = median;
    numberElementsRight = numberElements - median - 1;

    memcpy(leftSide, data, numberElementsLeft * sizeof(Point2D));
    memcpy(rightSide, &data[numberElements - median],
        numberElementsRight * sizeof(Point2D));

    Point2D *tPoint = (Point2D*) malloc(sizeof(Point2D));

    tPoint->x = data[median].x;
    tPoint->y = data[median].y;
    left = build(leftSide, (splittingAxis + 1) % DIMENSION,numberElementsLeft);
    right = build(rightSide, (splittingAxis + 1) % DIMENSION,
        numberElementsRight);
    temp->p = tPoint;
    temp->left = left;
    temp->right = right;
    temp->splittingAxis = splittingAxis;
    return temp;
}

Is this a correct implementation of a k-d-Tree in C? What would you criticize and how could it be improved?

malloc
You should not cast the return value from malloc() in C.  Instead, include its header file, and let the compiler's conversion from void* to specific pointer happen naturally.:
KdNode *temp = malloc(sizeof (KdNode));

It's often better to use the size of the actual object(s) you're allocating, rather than the size of the type.  This isn't an issue here, where your declaration is on the same line as the allocation, but consider this:
temp = malloc(sizeof (KdNode));

If you can't see the declaration, then it's harder to be sure that sizeof KdNode is the right size.  Instead we can write:
temp = malloc(sizeof *temp);

This also eliminates some irritating parentheses, which is nice!
error behaviour
What should happen when you misuse the function?  Here, you have two different behaviours:
if (temp == NULL || left == NULL || right == NULL) {
    exit(1);
}
if (numberElements == 0) {
    return NULL;
}

If anything, these are the wrong way around - you abort the whole program for an unpredictable run-time failure from malloc(), but nicely return a null value when you're (avoidably) given nonsense arguments.  It's generally best not to invoke exit() from a function you want anybody to be able to use anywhere; I'd make both cases return NULL.  And change the test for numberElements to be <= 0, or its type to unsigned.
comparators
Comparators for qsort can return any positive value or any negative value or zero as results.  So they don't need to be coerced to -1/0/+1; however, as you've noticed, the difference may be out of range for an int.  However, there's an easier way to obtain a value of correct sign, and the default conversion will work for us:
#include <math.h>
int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->x - p2->x);
}

I took out the unnecessary casts from void* here, too.
avoid floor() with integer division
This has an unnecessary round-trip through floating-point and back:
median = floor(numberElements / 2);

Integer division rounds down, so numberElements / 2 is sufficient.
possible simplification of if/else
Most of this is invariant between the two branches:
if (splittingAxis == 0) {
    qsort(data, numberElements, sizeof(Point2D), x_comparator);
} else {
    qsort(data, numberElements, sizeof(Point2D), y_comparator);
}

You might choose to make only the comparator argument dependent on the condition:
qsort(data, numberElements, sizeof *data, splittingAxis ? y_comparator : x_comparator);

If that's too opaque, then you could define a variable:
int (*const comparator)(const void*, const void*)
    = splittingAxis ? y_comparator : x_comparator;

qsort(data, numberElements, sizeof *data, comparator);

In honesty, the original may well be the best option here (but using sizeof *data rather than sizeof (Point2D) helps ensure a type match).
One approach that works well is to use splittingAxis to index an array.  To me, this looks compact and clear :
/* qsort-compatible comparator functions */
typedef int Comparator(const void*, const void*);
Comparator *const comparators[] = {x_comparator, y_comparator };

    qsort(data, numberElements, sizeof *data, comparators[splittingAxis]);

copy whole struct
Here you copy a Point2D member-by-member:
tPoint->x = data[median].x;
tPoint->y = data[median].y;

We can write that as:
*tPoint = data[median];

always check allocators' return value before use
You got this right early in the function, but tPoint is accessed immediately after allocation with no check it isn't null.

Modified version:
I've reordered some code and eliminated some local variables to give something that reads better to me.  See whether you agree.
#include <math.h>
#include <stdlib.h>
#include <string.h>

typedef struct Point2D {
    double x;
    double y;
} Point2D;

static int x_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->x - p2->x);
}

static int y_comparator(const void *v1, const void *v2) {
    const Point2D *p1 = v1;
    const Point2D *p2 = v2;
    return copysign(1, p1->y - p2->y);
}

typedef struct KdNode {
    Point2D *p;
    struct KdNode *left, *right;
    int splittingAxis;
} KdNode;

/* qsort-compatible comparator functions */
typedef int Comparator(const void*, const void*);
Comparator *const comparators[] = {x_comparator, y_comparator };

KdNode* build(Point2D data[],
              unsigned int splittingAxis,
              unsigned int numberElements)
{
    if (numberElements <= 0 || splittingAxis > 1) {
        return NULL;
    }

    KdNode *temp = malloc(sizeof *temp);
    KdNode *left = malloc(sizeof *left);
    KdNode *right = malloc(sizeof *right);
    if (!temp || !left || !right) {
        return NULL;
    }

    temp->p = malloc(sizeof *temp->p);
    if (!temp->p) {
        return NULL;
    }

    qsort(data, numberElements, sizeof *data, comparator[splittingAxis]);

    const unsigned int median = numberElements / 2;
    const unsigned int numberElementsLeft = median;
    const unsigned int numberElementsRight = numberElements - median - 1;
    Point2D leftSide[numberElementsLeft];
    Point2D rightSide[numberElementsRight];

    memcpy(leftSide, data, sizeof leftSide);
    memcpy(rightSide, &data[numberElements - median], sizeof(rightSide));

    const int other_axis = 1 - splittingAxis;

    *temp->p = data[median];
    temp->left = build(leftSide, other_axis, numberElementsLeft);
    temp->right = build(rightSide, other_axis, numberElementsRight);
    temp->splittingAxis = splittingAxis;
    return temp;
}

Performance improvement
Given that we're allowed to modify data and that we're not using it after finding the median value, we don't need to copy its elements into new arrays - we can sort its sub-arrays in-place:
KdNode* build(Point2D data[],
              unsigned int splittingAxis,
              unsigned int numberElements)
{
    if (numberElements <= 0 || splittingAxis > 1) {
        return NULL;
    }

    KdNode *temp = malloc(sizeof *temp);
    KdNode *left = malloc(sizeof *left);
    KdNode *right = malloc(sizeof *right);
    if (!temp || !left || !right) {
        return NULL;
    }

    temp->p = malloc(sizeof *temp->p);
    if (!temp->p) {
        return NULL;
    }

    qsort(data, numberElements, sizeof *data, comparator[splittingAxis]);

    const unsigned int median = numberElements / 2;
    const int other_axis = 1 - splittingAxis;

    *temp->p = data[median];
    temp->left = build(data, other_axis, median);
    temp->right = build(data + median + 1, other_axis, numberElements - median - 1);
    temp->splittingAxis = splittingAxis;
    return temp;
}

Side note: if you ever re-write this in C++, you'll find std::partial_sort() useful for finding the median with less computation than a full qsort().


Storing and loading functions The class Functions can store/load any functions. It does this by assigning a unique name to every function that gets added. You can then call the function by specifying its name and return type.

Here is a sample usage

//Create class
Functions funcs;

//Add 2 functions (foo -> void(int, int) | add -> int(int, int))
funcs.add("foo", foo);
funcs.add("add", add);

//Call them
int r = funcs.call<int>("add", 3, 2);
funcs.call<void>("foo", r, 2);

Here is the actual class

class Functions
{
public:
    template<typename T, typename... Ts>
    void add(std::string name, T(*func)(Ts...))
    {
        mFunctions.insert(std::make_pair(name, func));
    }

    template<typename T, typename... Ts>
    T call(std::string name, Ts... args)
    {
        try
        {
            return boost::any_cast<T(*)(Ts...)>(mFunctions.at(name))(args...);
        }
        catch (const std::out_of_range&)
        {
            throw std::invalid_argument("Function doesn't exist!");
        }
    }
private:
    std::map<std::string, boost::any> mFunctions;
};

Is there anything to be improved, like maybe naming, programming techniques, ...? Some general feedback would be appreciated.

Its a good start.
But function pointers are not the only type callable objects. Functors were a big part of C++03 and with C++11 lambdas are even more important.

Rather than using:

T(*func)(Ts...)

Which handles function pointers. You can generalize this with std::function<>.

std::function<T(Ts...)>

Which generalizes the callable construct.


"Class" design in javascript I'm a systems programmer teaching myself javascript.  Prototypal inheritance is completely new to me, so I could use some best practices advice here.

I made a simple game (breakout) for my first practice project.  Here is a simple example of a game object.

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
    this.__defineGetter__('width', function() {
        return sprite.width;
    });
    this.__defineGetter__('height', function() {
        return sprite.height;
    });
    this.__defineGetter__('rect', function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    });
}

Every object has an associate sprite and said sprite defines the width and height of the object.  So, coming from C++, I defined a few of getters that depend on the sprite.

Any and all advice is obviously appreciated.  Hopefully this example isn't overly trivial.

There hasn't been any standard for how to define getters and setters in Javascript until recently, so the implementations have various custom syntaxes, and not much seems to work in Internet Explorer... The defineGetter method is marked as non-standard and deprecated.

The thing that works reliably right now is to not use setters and getters at all, but methods that are named to indicate what they do (just as how it's done in Java).

(Of course, if you only need it to work in a specific browser, you can use whatever syntax works there. There are some syntax examples in the test code that I linked to above.)

To use prototypal interface, you put the methods in the prototype rather than in the object instance:

function GameObject(sprite) {
    this.xVelocity = 0;
    this.yVelocity = 0;
    this.x = 0;
    this.y = 0;
    this.sprite = sprite;
}

GameObject.prototype = {

    get_width: function() {
        return sprite.width;
    },
    get_height: function() {
        return sprite.height;
    },
    get_rect: function() {
        return {
            left   :this.x,
            top    :this.y,
            right  :this.x + this.width,
            bottom :this.y + this.height
        };
    }

};


Designing a sorting algorithm from scratch I'm taking a Python course and the current assignment is to create an algorithm that sorts numbers in ascending order (without using built-in sorting functions). I've had no programming experience before taking this course, so this might be a bit rough.

I got my script to successfully sort the numbers by figuring out the smallest number in the list each time through and moving it to a new list. This is obviously not very efficient since it has to loop dozens of times just for a short list, but I'm happy I finally got something to work! (Also, I think I need another elif to account for lists with repeat numbers.)

How can I clean it up? Is it more complex than it needs to be? I know there are far more efficient ways to sort, but I don't want to just copy someone else's established algorithm. I'd like to keep as much of this code in tact as possible while nipping and tucking.

def sortFunc(*arg):

    numList = list(arg)                     # Converts arguments into a list
    print('Before sorting: ',numList)       # Prints that list before sorting happens
    numSort = []                            # Creates an empty list to put sorted numbers into
    i = 0                                   # This is the index
    a = 1                                   # 'a' is the comparison number (this is the magic sauce)

    while numList:                          # As long as numList has numbers in it, loop the following

        if numList[i] == numList[-1] and\
           numList[i] <= a:                 # If we're at the final index AND that last number is smaller than 'a'
            basket = numList.pop(i)         # then place that number in a basket
            numSort.append(basket)          # and dump the basket into the new list (numSort)
            i = 0

        elif numList[i] == numList[-1]:     # Otherwise, if we reach the last position in numList
            i = 0                           # reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        elif numList[i] <= a:               # If we're anywhere else in the list and that number is smaller than 'a'
            basket = numList.pop(i)         # then pop that number into the basket
            numSort.append(basket)          # and dump it unceremoniously into the new list (numSort)
            i = 0                           # Then reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        else:                               # If none of those things happen
            i = i+1                         # then move on to the next number in the list

    print('After sorting: ',numSort)        # Once the while loop is up, print the result!

sortFunc(67, 45, 2, 13, 1, 998)

Congrats of making your own sorting algorithm!
Speed/Efficiency
There are plenty of sorts on Wikipedia that are more efficient, if you want to take a look at them. I added rough speed (given random data) and difficulty estimates:

Bubble sort (very slow, very easy)
Selection sort (slow, easiest)
Insertion sort (also slow, but harder)
Merge sort (fast, hard)
Quicksort (faster, also hard)

Output
Typically it is bad practice to put a print statement inside a function, because you don't want your console flooded with text if you are calling that function a bunch of times. Instead, you can do return numSort inside your function and print(sortFunc(myList)) outside.
Naming
Now, I'm sure you will also get answers pertaining to variable names, but I'm not a stickler for that, plus your variables and functions seem good already.
Happy coding!


Enhance a Caesar cipher I have just written a simple program to implement the Caesar cipher using lists. The program assumes the input will be all capital letters. I'm quite new to Python and am just curious of some more efficient ways to write this code. Honestly I just want to work on defining functions and all that jazz.

print("This encryption program uses the Caesar cipher to encrypt your message.")
mode = input("E to Encrypt or D to Decrypt")
if mode == "E":
    string = input("Input your message to encrypt in all capital letters: ")
    key = int(input("Create your encryption key (remember this)"))
    length = len(string)

    old_values = [0]*length
    new_values = [0]*length

    olds_position = 0
    news_position = 0

    for char in string:
        old_values[olds_position] = ord(char)
        olds_position += 1

    for value in old_values:
        if value != 32:
            new_values[news_position] = (value + key)
        else:
            new_values[news_position] = value
        news_position += 1

    for newvalue in new_values:
        if newvalue != 32:
            if newvalue > ord('Z'):
                newvalue -= 26
            elif newvalue < ord('A'):
                newvalue += 26
            print(chr(newvalue)+"", end="")
        else:
            print(" ", end="")

if mode == "D":
    key = int(input("Enter your encryption key: "))
    string = input("Input your encrypted message to descrypt it: ")
    length = len(string)

    old_values = [0]*length
    new_values = [0]*length

    olds_position = 0
    news_position = 0

    for char in string:
        old_values[olds_position] = ord(char)
        olds_position += 1

    for value in old_values:
        if value != 32:
            new_values[news_position] = (value - key)
        else:
            new_values[news_position] = value
        news_position += 1

    for newvalue in new_values:
        if newvalue != 32:
            if newvalue > ord('Z'):
                newvalue -= 26
            elif newvalue < ord('A'):
                newvalue += 26
            print(chr(newvalue)+"", end="")
        else:
            print(" ", end="")

Here are some changes that you could make to your code. I'll explain various parts of the script below.

import sys

mode = input("E to encrypt, D to decrypt: ").upper()

if mode == 'E':
    string = input("Input your message to encrypt : ").upper()
    def op(x, y): return x + y
elif mode == 'D':
    string = input("Input your message to decrypt : ").upper()
    def op(x, y): return x - y
else:
    print "Please enter either D or E for mode option. Terminating script!"
    sys.exit()

key = int(input("Create your encryption key (remember this): "))

ord_space = ord(' ')
ord_A = ord('A')
ord_Z = ord('Z')
alpha_num = 26

def inner_func(value):
    newvalue = op(value, key) if value != ord_space else value
    return newvalue

def outer_func(value):
    newvalue = (value - alpha_num) if value > ord_Z else ( value + alpha_num if value < ord_A else value)
    return newvalue

text = [chr(outer_func(inner_func(ord(char)))) for char in string]

Checking User Input

The first thing I do is import the Python module sys. At the
beginning of your program you ask the user to enter E or D
depending on whether they want to encrypt or decrypt their string. In
your programs current form it isn't robust to the case where the user
inputs some symbol(s) that isn't equivalent to E or D. So after
taking the users mode input I check that it is either E or D
and if it isn't I exit the program by calling sys.exit().
The next way I help the user (and in turn help our program) is to automatically transform their input to upper case charachters by calling .upper() in every place where you take user input.
Question: Are there any other user inputs we should check? (Hint: Key)

Taking Advantage of Object Scope

Notice that I'm defining string and the function op within the first if-elif statement. I'm then reusing these objects inside of functions later on without having to pass them in as parameters. Within each function Python will search 1st for a local object (in this case op) and then if there is no object with the given name inside of the function it will search the global namespace of the program. In this case because op is defined outside of a function, it belongs to the global namespace. The above also applies to ord_space, ord_A, etc, which again are also used inside the functions inner_func and outer_func. A more detailed description of Python scoping rules can be found here.

Conditional Expressions

Within inner_func and outer_func I'm using what is known in Python as a conditional expression. In other programming languages such as C++ they are also called ternary operators. As explanation consider: x = a if foo else b. The variable x will be assigned the value of a if the statement foo evaluates to true. If foo is false then x will be assigned the value of b. Conditional expressions often lead to more concise code which in the end will lead to less bugs and easier maintenance. Admittedly in outer_func I went a bit overboard and chained two of them together, e.g. x = a if foo else ( b if bar else c ). I wouldn't recommend doing this generally but I thought I'd demonstrate the possibility just for fun.

Tying it all together: List Comprehensions

Finally, on the last line of the code I've demonstrated one of the cornerstones of Python, list comprehensions. All a list comprehension does is build a list by looping over the elements of another container and applying some operator to them. For example if we had a list x = [1, 2, 3] and we wanted to add 1 to each element in x while at the same time creating a new list y we could do it like so:

y = [i + 1 for i in x]

This code has the same effect as the following:

    y = [0] * len(x)
    counter = 0
    for i in x:
        y[counter] = i + 1
        counter = counter + 1


What is the best way to use the database connection file in PHP? I have a connection.php file into my root folder and at the bottom, I added BASE_URL
<?php
$hostname = "localhost";
$username='root';
$password='';
$db='demo';

$charset = 'utf8mb4';
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$hostname;dbname=$db;charset=$charset";
try {
        $pdo = new PDO($dsn, $username, $password, $options);
    }
    catch (PDOException $e) {
        throw new PDOException($e->getMessage(), (int)$e->getCode());
  }

define('BASE_URL', 'http://example.com/');
?>

Now, On each file, I am adding the connection.php file
<?PHP
require($_SERVER["DOCUMENT_ROOT"].'/connection.php');
?>// HTML code start

Is this the correct way to use the database connection file? What should I use include or require?

Good question. Although the connection code itself is good, some improvements can be made.
A separate config file
When your code goes live, most likely database credentials will be different from those at home. Therefore, having them hardcoded in the script will make it extremely inconvenient. Instead, create a separate file for your configuration as follows:

add the config.php line in .gitignore (in case you are not using git yet, you definitely should)

create a file called config.sample.php with all variables set to empty values like this:
  return [
      'db' => [
          'host' => '127.0.0.1',
          'username' => '',
          'password' => '',
          'dbname' => '',
          'port' => 3306,
          'charset' => 'utf8mb4',
      ],
      'base_url' => 'http://example.com/',
  ];

add it to the version control

then in your application bootstrap file have a code like this:
  <?php
  if (!file_exists('config.php'))
  {
      throw new \Exception('Create config.php based on config.sample.php');
  }
  $config = require __DIR__.'/config.php';

  define('BASE_URL', $config['base_url']);

  $options = [
      PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES   => false,
  ];
  $dbconf = $config['db'];
  $dsn = "mysql:host=$dbconf[host];dbname=$dbconf[dbname];charset=$dbconf[charset]";
  try {
          $pdo = new PDO($dsn, $username, $password, $options);
  } catch (PDOException $e) {
      throw new PDOException($e->getMessage(), (int)$e->getCode());
  }
  unset($dbconf, $config['db']);

then, as suggested, create config.php on the every server that your application runs, each with its own set of values.

Actually using the connection
Just use this $pdo variable. When PDO is needed in a function - then pass it as a function parameter. If some function do not need PDO but it calls some other function that needs PDO - then pass $pdo into both. Yes it seems a bit a nuisance but this way you will always know what's going on and where. Avoid using dirty tricks like declaring variable global, singletons and such.
Some minor issues

closing PHP tag is not necessary and forbidden by the standard
// HTML code start reveals completely wrong approach to structure the code. Never an HTML code should start from the very beginning. Your PHP code should perform all the data manipulations first, and only then start the output
require should be always used for the files that are vital for the application. As this file surely is, then it must be require'd. Note that you should avoid using require_once and the likes - nowadays it's not more than a dirty hack to cover an inconsistent code


Matrix multiplication using functions in C This exercise surprised me a little bit. I did not expect that gcc (GCC 6.3.0 in the MinGW suite) would use the C11 standard by default, which I realised after I read the documentation. Here's the code that compiles without any errors or warnings:

matrix.c

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

void input(int m, int n, int a[m][n])
{
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d, %d : ", i, j);
            scanf("%d", &a[i][j]);
        }
    }
}

void print(int m, int n, int a[m][n])
{
    int i, j;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%3d ", a[i][j]);
        }
        printf("\n");
    }
}

void multiply(int m, int n, int p, int a[m][n], int b[n][p], int c[m][p])
{
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < p; j++) {
            c[i][j] = 0;
            for (int k = 0; k < n; k++) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

int main()
{
    int r1, c1, r2, c2;
    printf("Row and column for matrix #1 :\n");
    scanf("%d %d", &r1, &c1);
    printf("Row and column for matrix #2 :\n");
    scanf("%d %d", &r2, &c2);

    if (r2 != c1) {
        printf("The matrices are incompatible.\n");
        exit(EXIT_FAILURE);
    }

    int mat1[r1][c1], mat2[r2][c2], ans[r1][c2];
    printf("Enter elements of the first matrix.\n");
    input(r1, c1, mat1);
    printf("The elements of the first matrix are :\n");
    print(r1, c1, mat1);
    printf("Enter elements of the second matrix.\n");
    input(r2, c2, mat2);
    printf("The elements of the second matrix are :\n");
    print(r2, c2, mat2);

    multiply(r1, r2, c2, mat1, mat2, ans);
    printf("The product is :\n");
    print(r1, c2, ans);

    return EXIT_SUCCESS;
}

Feedback and criticism on any and all aspects are welcome.

I suggest you roll an explicit matrix type. For example:

typedef struct matrix_t {
    size_t rows;
    size_t cols;
    int* data;
} matrix_t;

void matrix_t_multiply(matrix_t* left, matrix_t* right, matrix_t* result) {
    ...
}


nodeJS, fs, path - creating new directorties I wrote this function that takes 2 arguments - the path to an existing file - file, and the newRoot name. The function splits the new path into directories, replaces the first directory in the path to the file with newRoot, , then loops trough all the directories checking if the director exists, and if not creates one:

/**
 * Creates directories for the file in newRoot if not there
 * @param {String} file - the path to the file
 * @param {String} newRoot - the new root directory for the file
 */
functions.makeDirectory = (file, newRoot) => {
  let dirPath = path.dirname(file);
  let directories = dirPath.split('/');
  let currentPath = '';
  directories[0] = newRoot;
  directories.map(directory => {
    currentPath = path.join(currentPath, directory);
    if(!fs.existsSync(currentPath)) {
      fs.mkdirSync(currentPath);
    };
  });
};

The string operations here seem a bit redundat, but I can't figure out how to get rid of them. Is there a more optimal solution for this or am I on the right track?

Would it increase performance to rewrite the fs function as a promise?

There are util libraries for this:fs-extra.

From its doc:

  mkdirs(dir, callback) Creates a directory. If the parent hierarchy
  doesn't exist, it's created. Like mkdir -p.

  Alias: mkdirp()

  Sync: mkdirsSync() / mkdirpSync()

  Examples:

var fs = require('fs-extra')

fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
  if (err) return console.error(err)
  console.log("success!")
})

fs.mkdirsSync('/tmp/another/path')

If you write function as a promise it would enable other code to run between each step of your function (eg. between each subdir being created) so it will not block other code like sending some request after calling this function.


Generic sequence splitter in Common Lisp I wrote a function split-seq-by-n which accepts a sequence and a number and splits the sequence into subsequences of length n (the last subsequence getting the remaining elements). It works on all subclasses of 'sequence, among others 'string, 'cons, 'vector etc.

;; Splits sequence into subsequences of length n
(defun split-seq-by-n (seq n)
  (labels ((seq-split (seq n &optional acc orig-n)
         (cond ((zerop (length seq)) (nreverse acc))
           ((zerop n) (seq-split seq
                          orig-n
                          (cons (subseq seq 0 0) acc)
                          orig-n))
           (t (seq-split (subseq seq 1)
                      (1- n)
                      (cons (concatenate (class-of seq)
                             (if acc (car acc) (subseq seq 0 0))
                             (list (elt seq 0)))
                        (cdr acc))
                      orig-n)))))
    (seq-split seq n nil n)))

Any comments, improvements, critiques welcome.

It looks okay for a recursion exercise, but it's naive code. Not usable in 'production'.

it conses like mad. It creates a lot of intermediate garbage. Splitting a string involves making lots of smaller strings.
for lists it is not efficient, too
CONCATENATE in loops or recursive functions is a code smell
the recursive implementation with the subroutine is good style in a functional language, but makes it hard to debug in the real world. For example, how do you TRACE the internal function?
Common Lisp does not guarantee tail call optimization (TCO). Individual implementations do support it. Still, for general portable code it might be preferable to code loop.


Tic Tac Toe implementation in Ruby Here's my first shot at implementing Tic Tac Toe in Ruby. After watching Gary Bernhardt's Functional Core, Imperative Shell, I thought this would be a great exercise in trying out the ideology presented in that screencast. Tear my code apart.

Link to GitHub repo (includes video of usage)

tic_tac_toe.rb -- the procedural shell

require_relative "board"
require_relative "cell"
require "pry"

def initialize_board
  @board = Board.new
end

def choose_characters
  puts "X or O?"
  @player_character = gets.chomp
  @computer_character = case @player_character
                        when "X" then "O"
                        when "O" then "X"
                        end
end

def start_game
  initialize_board
  choose_characters
  play
end

def play
  loop do
    puts "Make a move: "
    move = gets.chomp
    board_index = Board::POSITIONS[move]
    winner = @player_character

    @board.board[board_index].value = @player_character

    if !@board.winner?
      @board.available_cells.sample.value = @computer_character
      winner = @computer_character if @board.winner?
    end

    if @board.winner?
      p "#{winner.upcase} WINS!!!"
      @board.display
      puts "Do you want to play again?"

      start_game if gets.chomp == "Yes"
    else
      @board.display
      play
    end

    break if @board.winner?
  end
end

start_game

board.rb

class Board
  attr_accessor :board

  WINNING_COMBINATIONS = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ]

  POSITIONS = {
    "top left" => 0,
    "top middle" => 1,
    "top right" => 2,
    "middle left" => 3,
    "center" => 4,
    "middle right" => 5,
    "bottom left" => 6,
    "bottom middle" => 7,
    "bottom right" => 8
  }

  def initialize
    @board = Array.new(9) { Cell.new }
  end

  def winner?
    winner = false
    WINNING_COMBINATIONS.each do |combination|
      first_cell = board[combination[0]].value
      second_cell = board[combination[1]].value
      third_cell = board[combination[2]].value
      consideration = [first_cell, second_cell, third_cell]

      if consideration.uniq.length == 1 && first_cell.is_a?(String)
        winner = true
      end
    end
    winner
  end

  def available_cells
    board.select { |cell| cell.value == :blank }
  end

  def display
    rows = board.each_slice(3).to_a

    rows.each do |row|
      p row.map(&:value)
    end
  end
end

cell.rb

class Cell
  attr_accessor :value

  def initialize(options = {})
    @value = options.fetch(:value, :blank)
  end
end

You require pry, and you don't seem to use it.  Perhaps it is being used for troubleshooting, and the binding.pry or other code, has been removed.  In that case it may be more appropriate to simply use the -rpry option as in ruby -rpry file.rb.  Then you don't have to remember to remove that line, just the troubleshooting line.  (Or even better, set up a system that lets you leave things in but turn them off and on from an option in the system call.  Perhaps -w or -v flags.  Perhaps an environment variable.  A line in with this in mind may look like this:  binding.pry if $VERBOSE  And a require 'pry' if $VERBOSE)

Looking at your loop do tells me that you have an infinite loop.  But you have a well defined exit strategy, there is no need for an infinite loop.  Using something like until @board.winner? will run the block at least once, and will stop when your method returns true/truthy value.  You also call 'play' from inside the loop inside of play, but it is already going to start from the beginning of the loop.

If you had folders bin/, lib/, I would expect some of the code in your tic-tac-toe.rb file to be in maybe bin/tic-tac-toe. The start equivalent for sure.  This will allow you to use the lib/tic-tac-toe.rb file in a way that someone that requires that library would expect.  Right now, you are unable to require that library file without starting the game.

The interface of using words like top left seems clumsy and error prone, even if it is nice.  Creating a numbered or lettered menu or presenting the grid with numbers or letters could make play easier, less typing to do, less error prone.  Perhaps a lettered 'x, y' grid.  Presenting that grid would also document the game play, and make initial play more straight forward.

Your "choose_character" method does two things, it prompts and processes the choice.  The @player_character and @computer_character is repetitive, confusing in a way.  Simply having @player and @computer is probably clear enough.  @player.character might be better, though I think we consider that letter a 'marker', as the player mark may be 'X' and the AI mark may be 'O'.

Looking at cell.rb you could be using the new named arguments in Ruby 2.0.

In the Board file you can likely use the all? Enumerable method, if an array has all? the markers that match the current players marker, then that player is the winner.


Find all the countries I can visit by just crossing direct borders I was helping on this question. There you have a table border to indicate countryA and countryB have a common border. And want to know what country you can reach starting from country S Sweden.

I did my recursion and works ok. But I feel I cheat a little bit. Taking advantage the number of countries are limited put a break on 300. But in a different problem where I don't know the upper limit won't be able to do the same.

How I optimize my query so recursion doesn't travel the same path again?

SQL Fiddle Demo

WITH RECURSIVE travel(r_level, country) AS (
    select distinct 1 as r_level,
                    CASE WHEN country1 = 'S' THEN country2
                         ELSE country1
                    END as country
    from borders
    where country1 = 'S'
       or country2 = 'S'
    UNION
    select distinct t.r_level + 1 as r_level,
                    CASE WHEN b.country1 = t.country THEN b.country2
                         ELSE b.country1
                    END as country
    from borders b
    join travel  t
      ON (b.country1 = t.country OR b.country2 = t.country)
     AND (b.country1 <> 'S' AND b.country2 <> 'S')
    WHERE t.r_level < 300
)
SELECT DISTINCT country
FROM travel

I can't use subquery based on the same recursive table:

AND (    b.country1 NOT IN (SELECT country FROM Travel)
     AND b.country2 NOT IN (SELECT country FROM Travel)
    )

You don't need to artificially limit number of iterations, according to PG manual using UNION without ALL is enough:

  Recursive Query Evaluation

  Evaluate the non-recursive term. For UNION (but not UNION ALL), discard duplicate rows. Include all remaining rows in the result of the recursive query, and also place them in a temporary working table.
  So long as the working table is not empty, repeat these steps:

  a) Evaluate the recursive term, substituting the current contents of the working table for the recursive self-reference. For UNION (but not UNION ALL), discard duplicate rows and rows that duplicate any previous result row. Include all remaining rows in the result of the recursive query, and also place them in a temporary intermediate table.

  b) Replace the contents of the working table with the contents of the intermediate table, then empty the intermediate table.

with recursive travel(country) as (
  select 'S'
  union
  select unnest(array[country1, country2]::text[])
    from travel
      join borders on (country = any(array[country1, country2]))
)
select country from travel where country <> 'S';

Btw, the problem is related to calculating transitive closure on a graph.


Calculate cumulative salary including raises Is there a way to make this more pythonic?

def money():
    current_salary = float(input("What is your current salary? "))
    years = int(input("How many years would you like to look ahead? "))
    amount_of_raise = float(input("What is the average percentage raise you think you will get? ")) * 0.01

    for years in range(1, years + 1):
        current_salary += current_salary * amount_of_raise
        print('Looks like you will be making', current_salary,' in ', years,'years.')
money()

As others have noted, you'll probably want to do some error-checking on your inputs, which means writing a helper function to handle your prompts.
You're writing a program that handles money and using binary floats, which are designed for scientific calculations. You are likely to run into a variety of small calculation errors! Python has a decimal module for calculations involving money. This will also make your input-handling easier.
Don't reuse "years" as the iterator in the for loop when you already have a variable with that name. It works here, but only by luck.
Prefer the format() method to straight concatenation. In this case it allows you to easily print your numbers with comma separators.

For example:

from decimal import *

def get_decimal(prompt):
    while True:
        try:
            answer = Decimal(input(prompt + " "))
            return answer
        except InvalidOperation:
            print("Please input a number!")

def money():
    current_salary = get_decimal("What is your current salary?")
    years = int(get_decimal("How many years would you like to look ahead?"))
    percent_raise = get_decimal("What is the average percentage raise you think you will get?") * Decimal("0.01")
    for year in range(1, years+1):
        current_salary += percent_raise * current_salary
        line = "Looks like you will be making ${0:,.2f} in {1} years.".format(current_salary, year)
        print(line)


Best way to structure this PHP code I have this PHP code. I wrote it for a webpage it uses parameters. Only one set of parameters can be set at any one time. If both are set its invalid, if None are set its invalid

How would be the best way to write it, looks too long to me and i Feel like I have complicated it

if($_REQUEST['b_id'] && $_REQUEST['s_id']) {
        die('Not A Valid Request URL');
}
if(!$_REQUEST['b_id']) {
        $b = false;
} else {
        $b = true;
}

if(!$_REQUEST['s_id']){
           $s = false;
} else {
           $s = true;
}

if($b === $s) {
        die('Not A Valid Request URL');
} else if($_REQUEST['b_id'] == $_REQUEST['s_id']) {
      die('Not A Valid Request URL');
}

PS the code works as expected. I just need help making it neater little less confusing.

You can combine the conditions. It's invalid if both are set: $_REQUEST['b_id'] && $_REQUEST['s_id'] OR if neither are set: !$_REQUEST['b_id'] && !$_REQUEST['s_id']. The intermediary variables are unnecessary.

Additionally, the  tag has been deprecated for some 20 years now and the use of inline styles is discouraged. You should make the element a
 with a class and set the style in CSS, including a text-align: center; rule to get the same effect.

if( ($_REQUEST['b_id'] && $_REQUEST['s_id']) || (!$_REQUEST['b_id'] && !$_REQUEST['s_id']) ) {
    die('
Not A Valid Request URL
');
}


Return path to rubygems.rb From the command line, I can easily find the path to rubygems.rb

$ gem which rubygems
/usr/lib/ruby/1.9.1/rubygems.rb

and from a Ruby script I can also do this

require 'rubygems/commands/which_command'
wc = Gem::Commands::WhichCommand.new
puts wc.find_paths 'rubygems', $LOAD_PATH

However is a simpler way available to do this, for example without using
require 'rubygems/commands/which_command', and without a system() call?

Update from posted answer

puts $".grep(/rubygems.rb/).first

Update from posted comment

puts Gem.method(:dir).source_location.first

Whether a simpler solution exists depends on what your motivation is.

Let's look inside the implementation of Gem::Commands::WhichCommand#find_paths.

  def find_paths(package_name, dirs)
    result = []

    dirs.each do |dir|
      Gem.suffixes.each do |ext|
        full_path = File.join dir, "#{package_name}#{ext}"
        if File.exist? full_path and not File.directory? full_path then
          result << full_path
          return result unless options[:show_all]
        end
      end
    end

    result
  end

That's the code you need.  If there were a simpler way, find_paths would have used it.

However, there is a way to cheat: Kernel#require needs to do a very similar thing when it actually tries to load a module:

  require(name) → true or false

  Loads the given name, returning true if successful and false if
  the feature is already loaded.

  If the filename does not resolve to an absolute path, it will be
  searched for in the directories listed in $LOAD_PATH ($:).

  If the filename has the extension “.rb”, it is loaded as a source
  file; if the extension is “.so”, “.o”, or “.dll”, or the default
  shared library extension on the current platform, Ruby loads the
  shared library as a Ruby extension. Otherwise, Ruby tries adding
  “.rb”, “.so”, and so on to the name until found. If the file named
  cannot be found, a LoadError will be raised.

  For Ruby extensions the filename given may use any shared library
  extension. For example, on Linux the socket extension is “socket.so”
  and require 'socket.dll' will load the socket extension.

  The absolute path of the loaded file is added to $LOADED_FEATURES
  ($"). A file will not be loaded again if its path already appears in
  $". For example, require 'a'; require './a' will not load a.rb
  again.

Or, it might be more accurate to say that find_paths simulates what require would do.

Therefore, if you are willing to let Ruby actually load the file first, then you could ask Ruby after the fact:

require 'rubygems'
$LOADED_FEATURES.grep /\/rubygems\./


Stack implementation using linked list This is a working stack implementation using a linked list.  I'm just curious to know if this is a good way of doing it.  Any suggestions are welcome. Can we keep track of the number of elements in the stack using a count variable as used in the code?

#include <cstdlib>
#include<iostream>
using namespace std;

class node
{
 public:
    int data;
    node* next;
};

class StackusingList
{
public:
StackusingList(int max)
{
    top = NULL;
    maxnum = max;
    count=0;
}

void push(int element)
{
    if(count == maxnum)
            cout<<"stack is full";
    else
    {
        node *newTop = new node;
        if(top == NULL)
        {
            newTop->data = element;
            newTop->next = NULL;
            top = newTop;
            count++;
        }
        else
        {
            newTop->data = element;
            newTop->next = top;
            top = newTop;
            count++;
        }
    }
}

void pop()
{
    if(top == NULL)
            cout<< "nothing to pop";
    else
    {
        node * old = top;
        top = top->next;
        count--;
        delete(old);
    }
}
void print()
{
    node *temp;
    temp = top;
    while(temp!=NULL)
    {
        cout<<temp->data<<",";
        temp=temp->next;
    }
}
private:
    node *top;
    int count; //head
    int maxnum;
    int stackData;
};

int main(int argc, char** argv) {
    StackusingList *sl = new StackusingList(5);
    sl->push(1);
    sl->push(2);
    sl->push(3);
    sl->push(4);
    sl->push(5);
    sl->push(6);

    sl->pop();
    cout<<"new stack\n";
    sl->print();

    return 0;
}

At some point, I'd recommend using template here. This will allow you to store any date type, not just ints, in your structure.
It'd be better to define node as a struct inside StackusingList as private. In your current implementation, node's fields are not hidden because they are all made public.

class LinkedList
{
private:
    struct Node
    {
    };

public:

};

Prefer nullptr to NULL if you're using C++11.
StackusingList() should be an initializer list:

StackusingList(int max) : top(NULL), maxnum(max), count(0) {}

count should be of type std::size_t.
In both push() and pop(), you'll need to return if the stack is full or empty respectively. Otherwise, the function will continue to execute, defeating the purpose of the check.
print():

// no data members are being modified,
//   so make this const
void print() const
{
    // could just be initialized
    // the asterisk is commonly
    //   put next to the type in C++
    node* temp = top;

    while (temp)
    {
        cout << temp-> data << ",";
        temp = temp->next;
    }
}

Watch out:

StackusingList *sl = new StackusingList(5);

You do not call delete with this new, thereby causing a memory leak!  Always call delete properly with every new.

At the end of main() before the return:

delete s1;

Beyond that, you really don't need to use new here.  It's only necessary with the nodes, which you're already doing. It's best to just avoid manual allocation/deallocation as much as possible.
stackData isn't used anywhere (and doesn't have a clear meaning), so just remove it.
You're missing a few useful public member functions:

std::size_t size() const { return count; } // put into header

bool empty() const { return count == 0; } // put into header

template <typename T>
T StackusingList<T>::top() const { return top->data; }

There is no destructor! You're allocating new nodes, so you have to define the destructor to properly delete them:

StackusingList::~StackusingList()
{
    node* current = top;

    while (current)
    {
        node* next = current->next;
        delete current;
        current = next;
    }

    top = NULL;
}

With the destructor defined, you'll need to satisfy The Rule of Three.  This is also important because the default copy constructor and assignment operator will perform a shallow copy of top. This means that the pointer itself will be copied instead of just the data at that pointer. This will cause problems if you try to copy list objects or initialize new ones with existing ones.


Reverse a sentence quickly without pointers I am trying to reverse a sentence contained in a string and return a string in the quickest way possible using the least amount of memory. Also I don't want to use any unsafe code, so no pointers are allowed. Please let me know if anything can be improved.

My input example is

string mystring = "Hello! my name is";

My result is

  "is name my Hello!"

My results on i7 4770S for 1000000 iterations is on average around 650ms.

public static string ReverseTheString(string MyString)
{

    int Length = MyString.Length;
    Char[] NormalArray = new char[Length];
    Char[] FinalArray = new char[Length];

    for (int i = 0; i < Length; i++)
    {
        NormalArray[i] = MyString[i];
    }
    Length = Length - 1; //use for last index
    int SpacesCount = 0;
    int AlphaCount = 0;

    Stack<char[]> ReversedArray = new Stack<char[]>();

    for (int i = 0; i < NormalArray.Length; i++)
    {
        if (NormalArray[i] == ' ' && i != Length)//Space
        {
            if (i != Length)
            {
                if (AlphaCount > 0)
                {
                    char[] temparray = new char[AlphaCount];
                    int tempindex = i - AlphaCount;
                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    AlphaCount = 0;
                    temparray = null;
                }

                SpacesCount++;
            }
            else
            {

                SpacesCount++;
                if (SpacesCount > 0)
                {
                    char[] temparray = new char[SpacesCount];
                    int tempindex = i + 1 - SpacesCount;
                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    SpacesCount = 0;
                    temparray = null;
                }

            }
        }

        if (NormalArray[i] != ' ' ) //alpha
        {
            if (i != Length)
            {
                if (SpacesCount > 0)
                {
                    char[] temparray = new char[SpacesCount];
                    int tempindex = i - SpacesCount;
                    for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    SpacesCount = 0;
                    temparray = null;
                }
                AlphaCount++;
            }
            else
            {
                AlphaCount++;
                if (AlphaCount > 0)
                {
                    char[] temparray = new char[AlphaCount];
                    int tempindex = i + 1 - AlphaCount;
                    for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
                    {
                        temparray[k] = NormalArray[j];
                    }

                    ReversedArray.Push(temparray);
                    AlphaCount = 0;
                    temparray = null;
                }
            }
        }
    }

    int Pos = 0;
    while (ReversedArray.Count > 0)
    {
        char[] temparray = ReversedArray.Pop();

        for (int j = 0; j < temparray.Length; j++)
        {
            FinalArray[Pos] = temparray[j];
            Pos++;
        }
    }

    return new string(FinalArray);
}

The shortest code I can produce is:

private static string Reverse(string input)
{
    return String.Join(" ", input.Split(' ').Reverse());
}

But the following alternative should be much faster:

private static string Reverse(string input)
{
    // Create a new StringBuilder and allocate the same space as in the input string:
    StringBuilder builder = new StringBuilder(input.Length);

    // Declare 2 index variables:
    int index;
    int lastIndex = input.Length;

    // Iterate from the end to the start of the string
    // while the ' ' char is found:
    while ((index = input.LastIndexOf(' ', lastIndex - 1)) != -1)
    {
        builder.Append(input, index + 1, lastIndex - index - 1).Append(' ');
        lastIndex = index;
    }
    // Last iteration (for the first token in the input string):
    if (lastIndex != index)
    {
        builder.Append(input, 0, lastIndex);
    }
    return builder.ToString();
}

The main idea is to iterate from the end of the input string to the beginning, looking for the space char.
Also it makes sense to rely on the .NET built-in methods as much as possible.
Therefore I used:

The StringBuilder class for accumulation of a result.
The String.LastIndexOf method for searching for the space char.

The reasons to use the StringBuilder:

It is very effecient.
It contains the Append(string value, int startIndex, int count) method which copies specified substring to the inner buffer directly (without creating an intermediate substring from the input string).

EDIT.
A new approach not using the StringBuilder class and with the same main idea:

private static string Reverse(string inputString)
{
    // Get array of chars from the inputString,
    // and allocate the same space in the output array:
    char[] input = inputString.ToCharArray();
    char[] output = new char[input.Length];

    // Declare 3 index variables:
    int index;
    int lastIndex = input.Length;
    int outputIndex = 0;

    // Iterate from the end to the start of the string
    // while the ' ' char is found:
    while ((index = inputString.LastIndexOf(' ', lastIndex - 1)) != -1)
    {
        Array.Copy(input, index + 1, output, outputIndex, lastIndex - index - 1);
        outputIndex += lastIndex - index;
        output[outputIndex - 1] = ' ';
        lastIndex = index;
    }
    // Last iteration (for the first token in the input string):
    if (lastIndex != index)
    {
        Array.Copy(input, 0, output, outputIndex, lastIndex);
    }
    return new string(output);
}

It is slightly less efficient than previous approach, but it is still very fast.


User Authentication PHP script few days ago i made small PHP Authentication API with all basic functionalities (log in, log out, registration, getting authenticated member) and i got suggestions that i should use prepared statements for better performance and SQL Injection defense, so i made some changes to my script and it looks like this, can anyone confirm if it is good, did i miss something and is there anything else that i can improve here.

<?php
require_once '../dbConnect.php';
session_start();

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password'])) {

    $email = $object['email'];
    $password = $object['password'];

    $stmt = $mysqli->prepare("select id, password from members where email = ?");

    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->bind_result($id, $password);
    $stmt->fetch();

    if($id) {
        if (password_verify($object['password'], $password)) {
            $message = array('message' => 'Authentication Successful!');
            $_SESSION["id"] = $id;
            echo json_encode($message);
        } else {
            $message = array('message' => 'Wrong Credentials, Authentication failed!');
            session_destroy();
            http_response_code(400);
            echo json_encode($message);
        }
    } else {
        session_destroy();
        http_response_code(406);
    }

    $mysqli->close();

} else {
    session_destroy();
    http_response_code(400);
}
?>

SQL Injection defense, so i made some changes to my script and it looks like this, can anyone confirm if it is good

Yes, you are using prepared statements correctly. You didn't post all your updated code, so just remember to always use prepared statements and to never directly put any variables in the query.

Returning early

Your code is quite nested, which makes it difficult to read. If I want to know what happens in the else cases, I have to try to find the matching else, which can be difficult.

If you return early / introduce guard clauses, you can avoid this:

if (!isset($object['email']) || !isset($object['password'])) {
    session_destroy();
    http_response_code(400);
    return;
}
$email = $object['email'];
$password = $object['password'];

$stmt = $mysqli->prepare("select id, password from members where email = ?");
if(!$stmt) {
    session_destroy();
    http_response_code(400);
    return;
}

$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($id, $password);
$stmt->fetch();

if(!$id) {
    session_destroy();
    http_response_code(406);
}

if (password_verify($object['password'], $password)) {
    $message = array('message' => 'Authentication Successful!');
    $_SESSION["id"] = $id;
    echo json_encode($message);
} else {
    $message = array('message' => 'Wrong Credentials, Authentication failed!');
    session_destroy();
    http_response_code(400);
     echo json_encode($message);
}
$mysqli->close();

Structure

Now, you sill have some duplication (session destroy and response code setting) which you may want to remove, for example by returning error codes or success messages from the function and only setting it once from the calling code.

Your code also does a bit too much for my taste (db interaction, printing, retrieving user input, session management, etc). You could introduce functions such as getUserByEmail, etc to structure your code.

Misc

4xx are client side errors, but a non-working prepare is actually a server error; you should return a 500.
406 has to do with content encoding, so it is definitely the wrong code to send when a user is not found. It is also generally good practice to handle wrong username and wrong password the same way as to not leak information.
Upper-case all your SQL keywords to make queries easier to read.


Parsing from one enum to another I face a problem I think I am not approaching appropiately.

I have two independent enumerators that both will contain the same members, the only difference being the values given.

I have to be able to parse from one enum type to the other on the fly and I've seen the following code works as intended:

(enumType)Enum.Parse(typeof(enumType), enum1.ToString());

But I feel like there's something I am doing wrong, I believe this code is prone to errors and I feel like I need some help approaching this problem.

The code involved is the following:

public enum AdjustCircuitsCurrent
{
    _2V = 0x0001,
    _1_28V = 0x0002,
    _333mV = 0x0003,
    _0_25A = 0x0004,
    _0_01V = 0x0005,
    _0_1V = 0x006,
    _1V = 0x0007,
}

public enum VerificacionCircuitsCurrent
{
    _2V = 0x000B,
    _1_28V = 0x000C,
    _333mV = 0x000D,
    _0_25A = 0x000E,
    _0_1V = 0x00F,
    _0_01V = 0x0011,
    _1V = 0x0012,
}

public VerificacionCircuitsCurrent ConvertToVerificationCircuit(AdjustCircuitsCurrent circuit)
{
    return (VerificacionCircuitsCurrent)Enum.Parse(typeof(VerificacionCircuitsCurrent), circuit.ToString());
}

Again, this code works as intended, I can convert from one enum to the other, but I feel there's something wrong with it.

There's nothing particularly wrong with the code.  It happens often enough that this question has plenty of upvotes.

Marc Gravell gives the exact code that you have.  But you can go take a look at the link for ideas about using extension methods to make calling the conversion nicer and possibly adding an "IsDefined" check in case the enums get out of sync sometime in the future.


Matching words with a scrambled word I have this code that reads in a "scrambles" and a "words" file. It compares both files using their canonical form and prints out the words from the "words" file that match a particular scrambled word. I'm looking for ways to make this quicker.

public class scramble
{

    public static void main(String[] args) throws Exception
    {
        if (args.length < 2 ) die( "Must pass name of input files on cmd line." );

        BufferedReader scrambles = new BufferedReader( new FileReader( args[1] ) );
        BufferedReader words = new BufferedReader ( new FileReader( args[0] ) );
        ArrayList<String> scramblesList= new ArrayList<String>();  // default initial capacity is 10
        ArrayList<String> wordList= new ArrayList<String>();

        long startTime = System.currentTimeMillis();  // like clicking START on your stopwatch

        while (scrambles.ready())
        {
             String scramble = scrambles.readLine();
             scramblesList.add( scramble );
         }

        Collections.sort( scramblesList );
        while (words.ready())
        {
            String word = words.readLine();
            dictionaryList.add( word );
        }
        Collections.sort( wordList );

        for(String scramble: scramblesList)
        {
            System.out.print(scramble + " ");
                for(String word: wordList)
                {
                if(toCanonical(scramble).equals(toCanonical(word)))
                    System.out.print(word + " ");
                }
        System.out.println();
        }
        long endTime = System.currentTimeMillis();  // like clicking STOP on your stopwatch
        long ms = endTime-startTime;
        System.out.println("Elapsed time in seconds: " + ms/1000.0 + "\n"); // 1 ms is a 1,000th of a second
    } // END MAIN

    private static void die( String errmsg )
    {
                System.out.println( "\nFATAL ERROR: " + errmsg + "\n" );
                System.exit(0);
    }

    private static String toCanonical( String word )
    {
        char[] array = word.toCharArray();
        // #1 declare a char[] array and assign into it the return value from word.toCharArray()

        Arrays.sort(array);
        // #2 pass that char[] into Arrays.sort(...)
        String C = new String (array);
        // #3 return a new a new String that is constructed using that char[]
            return C;

    }
}

There are a bunch of things in here that @nanny has not yet covered, so let's go through some of those:

Java class names should be CamelCase. Your class scramble should be Scramble.
use whitespace in lines consistently, especially around keywords and operators. Lines like:

... wordList= new ....

should be:

... wordList = new ....

You have done this correctly in most places, so the places you have it wrong stand out....
There is no need, and it is now discouraged, for you to add the generic type to instance constructor calls. The generic type can be inferred from the target. i.e. your line:

ArrayList<String> scramblesList= new ArrayList<String>();

should be:

ArrayList<String> scramblesList = new ArrayList<>();

When possible, you should use the interface type for your variables, not the concrete type. For example, the line above should actually be:

List<String> scramblesList = new ArrayList<>();

No need to "type" variable names ... (hungarian notation). We know that scramblesList is a list, so there's no need for the List suffix on scramblesList, it should just be scrambles (good thing we renamed the class to Scramble to avoid confusion...).
1-liners are a maintenance problem. Sure, they look smart, and take less space, but the person maintaining your code in the furture will dislike you. This:

if (args.length < 2 ) die( "Must pass name of input files on cmd line." );

should be:

if (args.length < 2 ) {
    die( "Must pass name of input files on cmd line." );
}

while we are on it, you have successfully turned your Java semantics in to Perl... was that the intention? If so, there's better ways to handle problems like this... an IllegalArgumentException is the better/right solution.
try-with-resources is your friend, learn to use it: try-with-resources
Know your standard libraries... Java can do a lot of what you are doing in it's native libraries. Learn them....
use printf:

long endTime = System.currentTimeMillis();  // like clicking STOP on your stopwatch
long ms = endTime-startTime;
System.out.println("Elapsed time in seconds: " + ms/1000.0 + "\n");

can be:

long ms = System.currentTimeMillis() - startTime;
System.out.printf("Elapsed time in seconds: %.3f\n", ms / 1000.0);

Oh, and you have added a \n to a println which seems redundant.

Let Java work for you:

This code throws lots of potential exceptions which you don't handle... and there's a lot simpler ways to do things....:

   BufferedReader scrambles = new BufferedReader( new FileReader( args[1] ) );
    BufferedReader words = new BufferedReader ( new FileReader( args[0] ) );
    ArrayList<String> scramblesList= new ArrayList<String>();  // default initial capacity is 10
    ArrayList<String> wordList= new ArrayList<String>();

    long startTime = System.currentTimeMillis();  // like clicking START on your stopwatch

    while (scrambles.ready())
    {
         String scramble = scrambles.readLine();
         scramblesList.add( scramble );
     }

    Collections.sort( scramblesList );
    while (words.ready())
    {
        String word = words.readLine();
        dictionaryList.add( word );
    }
    Collections.sort( wordList );

The above code, excluding the sorts, and stopwatch, can be replaced with:

List<String> words = Files.readAllLines(Paths.get(args[0]));
List<String> scrambles = Files.readAllLines(Paths.get(args[1]));

As @nanny pointed out, the sorting is unnecessary.

Performance

Once you have your two word lists, the fastest way to match these things is to use a map...., a map of Lists....

Convert the words in to a Map<String,List<String>>:

    Map<String, List<String>> canonWords = new HashMap<>();

    for (String word : words) {
        String canon = toCanonical(word);
        if (!canonWords.containsKey(canon)) {
            canonWords.put(canon, new ArrayList<>());
        }
        canonWords.get(canon).add(word);
    }

Then, with canonWords, search for matches with scrambled words:

    for (String scram : scrambles) {
        String canon = toCanonical(scram);
        List<String> match = canonWords.get(canon);
        if (match != null) {
            System.out.printf("Scramble %s Matches words %s\n", scram, match.toString());
        }
    }


Compute count of unique words using ES6 sets I have written a function which counts how many unique words are included in a given text.

The source-code:

const computeCountUniqueWords = (strToExamine) => {
  let parts = strToExamine.split(" ");

  let validWords = parts.filter((word) => {
    return /^\w/.test(word);
  });

  let uniqueWords = new Set(validWords);

  return uniqueWords.size;
}

let text1 = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
let text2 = "Etiam ultricies nisi vel augue. Curabitur ullamcorper";

console.log(`Text 1 has ${computeCountUniqueWords(text1)} words`);
console.log(`Text 2 has ${computeCountUniqueWords(text2)} words.`);

I think it has become quite neat and short.

Nevertheless: Is there a better way to solve the described task?

Moveover: Is my checking with the regular expression sufficient? Or should it be enhanced?

Looking forward to reading your answers.

Two problems

Your code has two problems.

It does not remove punctuation from the words resulting in the same words not matching. Eg text1 has 12 unique words not 13. You count dolor and dolor. as different words.
You are ignoring capitalization. You would count Dolor and dolor as different words rather than the same.

String.match

Update I was not paying attention on first posting. There is no /*RegExp.match*/

The better solution is to use the String.match to convert the matches to an array and then directly create the set from that. The code is just one line and the performance is 2.5 times faster than using String.replace as shown.

thus the ideal solution becomes...

const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size;

String.replace

You can use a string replace to iterate over RegExp matches. It's a little hacky but I much prefer it over other methods such a using a RegExp to split the string, or RegExp.match, or RegExp.exec which have an ugly interface and are slower than String.replace.

Converting the text to lowercase  using String.toLowerCase solves the capitalization problem

const countUniqueWords = text => {
    const words = new Set();
    text.toLowerCase().replace(/\w+/g, word => words.add(word));
    return words.size;
}

const a = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
const b = "Etiam ultricies nisi vel augue. Curabitur ullamcorper.";
info1.textContent = `A has ${countUniqueWords(a)} unique words`;
info2.textContent = `B has ${countUniqueWords(b)} unique words.`;

A: "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor."

B: "Etiam ultricies nisi vel augue. Curabitur ullamcorper."