texts:
I have created a class to keep track of some internal states. You can see it as a very simple implementation of a state machine

class State extends Backbone.Model

  defaults:
   step: 'start'

  initialize: ->
    @stepDefs = [
        name        : 'start'
      ,
        name        : STAGE_1
        precondition: _.bind @_condition_1, @
      ,
        name        : STAGE_2
        precondition: _.bind @_condition_2, @
      ,
      name        : 'end'
   ]

  @steps = (step.name for step in @stepDefs)

  _condition_1: ->
    # test something

  _condition_2: ->
    # test something else

  gotoNextStep: (fromStepName) ->

    idx = @steps.indexOf(fromStepName)
    if idx < @steps.length
      step = @stepDefs[idx + 1]
      if not step.precondition
        return step.name
      else
        if step.precondition()
          return step.name
        return fromStepName  # stay as the current status
    else
      return 'end'

I am not entirely happy with this code because I want this class to only hold the step definitions and the current state (step). I think I should create another class to provide the implementation of function _condition_1 and _condition_2. However if I break the class State into two (One for purely keeping the state and the other for controlling state progression), I think it may introduce a circular dependency because:

State holder needs to reference the condition_1 and condition_2 function from the newly split-out state computation class
the state computation class needs to have a reference to an instance of the State holder class in order to update it to a new state.

Did I overthink the situation? Is the above class structure already OK?


texts: PHP & MySQLi Login Script - Is it safe from Injection?

texts:
I've been geeking up on MySQLi prepared statements to avoid potential SQL injection and I have managed to modify my legacy code (previously just using mysqli_real_escape_string).

I am looking for some advice regarding if this code template is safe enough to use as I will be looking to update the rest of my code across my site.  I received some help from Fred-ii so thanks for that.

One issue I know is present is the use of $_SERVER['HTTP_REFERER'] but I will be creating a workaround via an array of acceptable URLs.

<?php
// Starting Session

session_start();
include '../connection.php';

// Previous page variable

$previous = $_SERVER['HTTP_REFERER'];

//Acquire POST values Please note: Sanity checks will be added for these =)

$myusername = $_POST["username"];
$mypassword = $_POST["password"];

// Preparing the statement

$stmt = $connection-> prepare("SELECT username, password FROM $tbl_name WHERE username= ? ");
$stmt -> bind_param("s", $myusername);

// Sanity checks on the statement and binding

if($stmt ->execute() == true) {
    $stmt -> bind_result($user, $pass);
    $stmt -> fetch();

    //Checking hashed password

    if (password_verify($mypassword, $pass)) {

        $_SESSION['login_user']= $myusername;
        header("location: ../member"); // Redirecting To Other Page

    } else {

        $_SESSION["login_error"] = "

Incorrect username or password, please try again.

";

        header('Location:'.$previous);

    }

    }

/* Close statement */
$connection-> close();

Looking for any feedback to improve this and any other recommendations.

Thanks. Stan.


texts:
I had an interview yesterday where I had to write an algorithm on the whiteboard for working out if a value is a Palindrome in C#. The pressure got to me a bit but I've written my version of it in Visual Studio this evening.

 private bool Ispalindrome(string args)
        {
            var index = 0;
            var reverseArray = args.ToCharArray();

            do
            {
                if(index == args.Length)
                    return true;

                index++;
                var startingChars = args.Substring(0, index);
                var stringbuilder = new StringBuilder();

                for (var i = 0; i < index; i++)
                {
                    stringbuilder.Append(reverseArray[reverseArray.Length-i-1]);
                }

                if (startingChars != stringbuilder.ToString())
                    _isPalindrone = false;

            } while (_isPalindrone);
            return _isPalindrone;
        }

Doe anyone have any recommendations on how to make this more efficient?


texts: ReactJS code that allows at most one profile pic to be selected

texts:
I am making a profile picture selection screen, basically you select a picture pic1, if another picture pic2 is selected, then we cancel the highlight of pic2 and highlight pic1. Here is my code right now for it in React (btw, I am using CSS to take care of the highlighting).

How I am doing it currently (let's say I only have 3 options to choose from), this is the code taking care of determining which one is clicked:

`  this.state = {
      isClicked1: false,
      isClicked2: false,
      isClicked3: false
    };`

The JSX code that actually displays everything:

The class is actually what determines if it is highlighted or not (background color in CSS), if the class is animal selected then it has a background else no background.

let a_class1 = this.state.isClicked1 ? "animal selected" : "animal";
let a_class2 = this.state.isClicked2 ? "animal selected" : "animal";
let a_class3 = this.state.isClicked3 ? "animal selected" : "animal";

And the JS logic:

  profilePicClick1 = () => {
    this.setState({ isClicked1: !this.state.isClicked1 });
    this.setState({ isClicked2: false });
    this.setState({ isClicked3: false });
  };

  profilePicClick2 = () => {
    this.setState({ isClicked2: !this.state.isClicked2 });
    this.setState({ isclicked3: false });
    this.setState({ isClicked1: false });
  };

  profilePicClick3 = () => {
    this.setState({ isClicked3: !this.state.isClicked2 });
    this.setState({ isclicked1: false });
    this.setState({ isClicked2: false });
  };

Here's a run through sorry if my code is confusing: on load, the isClicked state for all images is false, that leads to each a_class being "animal", and on render, it will display the images with the a_classes, since it is only animal, we will display the normal image. Onclick of let's say image1, we will turn isClicked1 into true, which will make a_class1 "animal selected", and will thus render the picture with the background selected color. And onClick of another picture other than pic1, we will set all other isClicked to false besides the one just being clicked, and blah blah.


texts: Syncing Redux state with the URI in 2020

texts:
I have a React/Redux/Router/Reselect app in which I am syncing some parts of the redux state with the URL. As an interim, hacky measure (I've only been learning how to write wepapps for about 6 months so I'm very much a n00b right now) I’m currently implementing that sync as follows:

A selector provides the parts of the state which deviate from the default (e.g. the tab has changed from default and the filter bar is open and one of the filters has been changed from the default):

export const getStateConfiguration = createSelector(
  [getAllActiveFilters, getFilterBarVisible, getSelectedChart, getCurrentTab],
  (filters, filterBarVisible, selectedChart, currentTab) => {
    // inspect filters to create for deviations to default and return a config object with the stuff i need to write to the URI
     return config;
   }
);

A useEffect() in App.js is listening to that selector and when it changes calls a function in which JSON stringifies the selector's result to history. (I get that history object from router, because if I use uesHistory() from, say, BrowserRouter, I can't seem to escape infinite loop dependencies in useEffect().)

useEffect(() => {
  // some lines omitted for brevity
  writeToHistory(currentJsonConfig, stateConfiguration);
}, [dispatch, dbStatus, currentJsonConfig, decodedPathname, stateConfiguration]);

At app startup, another useEffect() in App.js calls a function which inspects the location and passes that to initialise the Redux reducers.

useEffect(() => {
    // some lines omitted for brevity
    dispatch(initialise(config));
  }
}, [dispatch, dbStatus, currentJsonConfig, location]);

As you can probably already see, all of this performs horrifically. Every time a single thing in state changes, the selector has to examine the whole state model, reparse it, provide that to useEffect(), which stringifies the whole thing again and writes it to history.

Due to performance and the hacky nature of my bespoke solution, I now plan to refactor it all to use a 3rd party library(s) which does all this for me. I’ve looked at things like use-query-params (https://github.com/pbeshai/use-query-params) and connected-router (https://www.npmjs.com/package/connected-react-router) but I was wondering if anyone has any experience, guidance, or opinions they can offer on the subject, for the most efficient, straightforward and current solution to the problem.

If it helps, you can see my source code here.  The most relevant files which contain my hacky solutions are probably /App.js, /state/selectors/StateConfigurationSelector.js and /HistoryWriter.js.  More generaly, if you do take a look and see any other n00b issues, do feel free to tell me!

Thanks :)


texts: Search in deeply nested array by array of "path ids" and exchange it

texts:
I wrote this map function, that should loop a very nested array of objects and find and exchange an item. To make my life easier, I also pass a path array:  [1, 4, 7, 23] that shows in which id-s my nesting happens. The last id is the item I need to swap. Here is my function:

() => {
  const { id, parentPath, question } = action;
  const fullPath = parentPath.concat(id);

  const findAndReplaceInSurveyItems = (item) => {
    if (fullPath[0] === item.id) {
      // pop the value, we found a match:
      fullPath.shift();
      // but we still need to continue searching...
      if (fullPath.length) {
        return {
          ...item,
          children: item.children.map(findAndReplaceInSurveyItems)
        };
      }
      // we found our match! Exchange it to the payload :)
      return {
        ...item,
        question
      };
    }

    return item;
  };

  return {
    ...state,
    questionnaire: {
      ...state.questionnaire,
      surveyItems: state.questionnaire.surveyItems.map(findAndReplaceInSurveyItems)
    }
  };
}

I would love your opinion on speed and overall performance.


texts:
I'm tutor for a university operating systems course, and part of my work is creating exercises for them. Those exercises are mostly about concurrency and synchronization issues. For the next exercise I intend to show them the finished implementation of an unfair counting semaphore, and their job is to make a fair one. Because of a lot of factors I'm constrained to using Java as implementation language.

Though I'm fully capable of writing Java programs, it's not exactly my "mother tongue". As such, I'm probably unaware of some idioms and best practices.

As I want to give my students not just something that "works", but code that could actually be found in a production system, I hope you can give me suggestions for my implementation:

/** Simple, unfair counting semaphore.

    This class implements a simple and unfair counting semaphore.
*/
public class UnfairSemaphore implements Semaphore {
    /** Count of available permits.
     */
    protected int count;

    /** Object used to communicate with waiting threads.

        A distinct object is used herefore (and not the semaphore itself)
        to keep any signals from notify() behind the abstraction.
     */
    protected Object wire = new Object();

    /** Construct a semaphore with the given initial count.

        Sets the initial count of the newly constructed semaphore to the
        given value, which may be negative.
    */
    public UnfairSemaphore(int initial) {
        count = initial;
    }

    /** Construct a semaphore with 1 initial permit.
     */
    public UnfairSemaphore() {
        this(1);
    }

    // Implementation
    public void acquire() throws InterruptedException {
        synchronized (wire) {
            while (count <= 0) {
                wire.wait();
            }
            --count;
        }
    }

    // Implementation
    public void release() {
        synchronized (wire) {
            ++count;
            if (count > 0) {
                wire.notifyAll();
            }
        }
    }
}

Semaphore is an interface with just the two methods acquire and release.

I'm using the member wire to synchronize on and to call notifyAll and wait in order to keep the signals resulting from these "behind the abstraction", that is to make them invisible to the code using the semaphore. (I could use just notify here, couldn't I?)

I'm neither interested in making this code faster or to use different, possibly better classes (Atomic* or whatever) to implement this.

What I do want is code that correctly handles all cases. (I just don't want to give them "educational code" which shows the idea, but fails to reliably work in practice)


texts:
When a user registers (creates a new account), I want to encrypt password before storing in a database, and when a user logs on (with username & password) I want to check password. I did it in the following way:

function password_encrypt($pass) {
    $hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of a 10
    $salt_length = 22; // Blowfish salts should be 22-characters or more
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($pass, $format_and_salt);
    return $hash;
}

function generate_salt($salt_length) {
    // Not 100% unique, not 100% random, but good enough for a salt
    // MD5 returns 32 characters
    $unique_random_string = md5(uniqid(mt_rand(), true));

    // Valid characters for a salt are [a-zA-Z0-9./]
    $base64_string = base64_encode($unique_random_string);

    // But not '+' which is valid in base64 encoding
    $modified_base64_string = str_replace('+', '.', $base64_string);

    // Truncate string to the correct length
    $salt = substr($modified_base64_string, 0, $salt_length);

    return $salt;
}

function password_check($password, $existing_hash) {
    // existing hash contains format and salt at start
    $hash = crypt($password, $existing_hash);
    if ($hash === $existing_hash) {
        return true;
    } else {
        return false;
    }
}

Can you do a review of this code, give some suggestions?

Also, I have one more question: Is it a good idea to use these functions as private methods of

User Model Entity Class OR
User Repository Class

or simply to have a file called functions.php and to put them there and to use them in controller?


texts:
I'm using a many-to-many relationship between users and roles with propel:

    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="username" required="true" type="varchar" primaryKey="true" size="50" />

    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="role" required="true" type="varchar" size="20" primaryString="true" />
    <column name="name" required="true" type="varchar" size="50" />

    <unique>
        <unique-column name="role" />
        <unique-column name="name" />
    </unique>

    <column name="user_id" type="integer" primaryKey="true"/>
    <column name="role_id" type="integer" primaryKey="true"/>
    <foreign-key foreignTable="user">
        <reference local="user_id" foreign="id"/>
    </foreign-key>
    <foreign-key foreignTable="role">
        <reference local="role_id" foreign="id"/>
    </foreign-key>

This is how I check if a user has a role:

class User extends BaseUser
{
    public function hasRole($checkRole)
    {
        foreach ($this->getRoles() as $role)
        {
            if ($role->getRole() == $checkRole)
            {
                return true;
            }
        }

        return false;
    }
}

This works, but I think it could be optimized. Any ideas?


texts: Datepickers for departure and return dates

texts:
I have to two datepickers. I want achieve the following functionality: the return date cannot be selected before the selected departure date and the departure date cannot be after the selected return date. Mainly I am interested in correctness of my angular architecture.

I have moved datepicker into my custom directive which I plan to reuse many times for different screen sizes.

Both datepickers reuse the same DatepickerContoller and I have one parent controller FormDatepickerController which shares information from both outbound and return datepickers.

Could you please review my code and let me know if my design is good enough?

index.html

            <date-picker date="fd.departDate" min-date="fd.departDate"></date-picker>

            <date-picker date="fd.returnDate" min-date="fd.departDate"></date-picker>

datepicker.html template

    <input type="text" class="form-control"
           datepicker-popup
           min-date="minDate"
           ng-model="date"
           is-open="isOpened"
           ng-required="true"
           close-text="Close" />

app.js

var app = angular.module("fridayFly", ['ui.bootstrap']);

datepicker-controller.js

var app = angular.module("fridayFly");

(function(){

    function Controller($scope) {
        $scope.open = function($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.isOpened = true;
        };

        $scope.today = function() {
            $scope.dt = new Date();
        };
        $scope.today();

        $scope.clear = function () {
            $scope.dt = null;
        };

        $scope.toggleMin = function() {
            $scope.minDate = $scope.minDate ? null : new Date();
        };
        $scope.toggleMin();

        $scope.dateOptions = {
            formatYear: 'yyyy',
            startingDay: 1
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
        $scope.format = $scope.formats[0];

    }

    app.controller('DatePickerController', Controller);

})();

(function(){

    function directive(){
        return {
            scope :{
                date:'=date',
                minDate:'=minDate',
                isOpened:'=isOpened'
            },
            restrict: 'E',
            templateUrl: 'templates/datepicker/datepicker.html',
            controller: 'DatePickerController'
        };
    };

    app.directive('datePicker', directive);

})();

form-datepicker-contoller.js

var app = angular.module("fridayFly");

app.controller('FormDatepickerController', ['$scope', function($scope) {

    $scope.toggleDepartDate = function() {
        $scope.departDate = $scope.departDate ? null : new Date();
    };
    $scope.toggleDepartDate();

    $scope.toggleReturnDate = function() {
        $scope.returnDate = $scope.returnDate ? null : new Date();
    };
    $scope.toggleReturnDate();

}]);


texts:
I am learning Java's NIO and as an exercise, I have implemented a simple chat server. I would like to ask if I am using NIO's features in the correct way.

public class ChatServer implements Runnable {
    private static final int BUFFER_SIZE = 256;
    private static final int DEFAULT_PORT = 10523;
    private static final String WELCOME_MESSAGE = "Welcome to NioChat!\n";

    private final int mPort;
    private ServerSocketChannel mServerChannel;
    private Selector mSelector;
    private ByteBuffer mBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    private final ByteBuffer mWelcomeBuffer = ByteBuffer.wrap(WELCOME_MESSAGE
            .getBytes());

    public ChatServer(int port) throws IOException {
        mPort = port;
        mServerChannel = ServerSocketChannel.open();
        mServerChannel.socket().bind(new InetSocketAddress(port));
        mServerChannel.configureBlocking(false);
        mSelector = Selector.open();
        mServerChannel.register(mSelector, SelectionKey.OP_ACCEPT);
    }

    public static void main(String[] args) throws IOException {
        ChatServer server = new ChatServer(DEFAULT_PORT);
        new Thread(server).start();
    }

    @Override
    public void run() {
        try {
            System.out.println("Server started on port " + mPort);

            Iterator<SelectionKey> iter;
            SelectionKey key;
            while (mServerChannel.isOpen()) {
                mSelector.select();
                iter = mSelector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    key = iter.next();
                    iter.remove();

                    if (key.isAcceptable())
                        handleAccept(key);
                    if (key.isReadable())
                        handleRead(key);
                }
            }
        } catch (IOException e) {
            System.out.println("IOException, server on port " + mPort
                    + " terminating. Stack trace:");
            e.printStackTrace();
        }
    }

    private void handleAccept(SelectionKey key) throws IOException {
        SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
        String address = (new StringBuilder(sc.socket().getInetAddress()
                .toString())).append(":").append(sc.socket().getPort())
                .toString();
        sc.configureBlocking(false);
        sc.register(mSelector, SelectionKey.OP_READ, address);
        sc.write(mWelcomeBuffer);
        mWelcomeBuffer.rewind();
        System.out.println("Accepted connection from: " + address);
    }

    private void handleRead(SelectionKey key) throws IOException {
        SocketChannel ch = (SocketChannel) key.channel();
        StringBuilder sb = new StringBuilder();

        mBuffer.clear();
        int read = 0;
        while ((read = ch.read(mBuffer)) > 0) {
            mBuffer.flip();
            byte[] bytes = new byte[mBuffer.limit()];
            mBuffer.get(bytes);
            sb.append(new String(bytes));
            mBuffer.clear();
        }
        String msg;
        if (read < 0) {
            msg = key.attachment() + " left the chat.\n";
            ch.close();
        } else {
            msg = key.attachment() + ": " + sb.toString();
        }

        System.out.println(msg);
        broadcast(msg);
    }

    private void broadcast(String msg) throws IOException {
        ByteBuffer messageBuffer = ByteBuffer.wrap(msg.getBytes());
        for (SelectionKey key : mSelector.keys()) {
            if (key.isValid() && key.channel() instanceof SocketChannel) {
                SocketChannel channel = (SocketChannel) key.channel();
                channel.write(messageBuffer);
                messageBuffer.rewind();
            }
        }
    }
}


texts:
So after watching week 5 of the machine learning course on Coursera by Andrew Ng, I decided to write a simple neural net from scratch using Python. Here's my code:

import numpy as np
import csv
global e
global epsilon
global a
global lam
global itr
e = 2.718281828
epsilon = 0.12
a = 1
lam = 1
itr = 1000

# The sigmoid function(and its derivative)
def sigmoid(x, derivative=False):
    if derivative:
        return sigmoid(x) * (1 - sigmoid(x))
    return 1 / (1 + e**-x)

# The cost function
def J(X, theta1, theta2, y, lam, m):
    j = 0
    for i in range(m):
        # The current case
        currX = X[i].reshape(X[i].shape[0], 1)
        z2 = theta1 @ currX
        a2 = sigmoid(z2)
        a2 = np.append([1], a2).reshape(a2.shape[0] + 1, 1)
        z3 = theta2 @ a2
        a3 = sigmoid(z3)
        j += sum(-y[i] * np.log(a3) - (1 - y[i]) * np.log(1 - a3)) / m + (lam / (2 * m)) * (sum(sum(theta1[:, 1:] ** 2)) + sum(sum(theta2[:, 1:] ** 2)))
    return j

# The gradients
def gradient(X, theta1, theta2, y, lam, m):
    theta1Grad = np.zeros(theta1.shape)
    theta2Grad = np.zeros(theta2.shape)
    Delta1 = np.zeros(theta1.shape)
    Delta2 = np.zeros(theta2.shape)
    for i in range(m):
        # The current case
        currX = X[i].reshape(X[i].shape[0], 1)
        z2 = theta1 @ currX
        a2 = sigmoid(z2)
        a2 = np.append([1], a2).reshape(a2.shape[0] + 1, 1)
        z3 = theta2 @ a2
        a3 = sigmoid(z3)
        delta3 = a3 - y[i]
        delta2 = theta2[:, 1:].T @ delta3 * sigmoid(z2, derivative=True)
        Delta1 += delta2 @ currX.reshape(1, -1)
        Delta2 += delta3 * a2.reshape(1, -1)
    theta1Grad = Delta1 / m
    theta2Grad = Delta2 / m
    theta1Grad[:, 1:] += (lam / m) * theta1[:, 1:]
    theta2Grad[:, 1:] += (lam / m) * theta2[:, 1:]
    thetaGrad = np.append(theta1Grad.reshape(theta1Grad.shape[0] * theta1Grad.shape[1], 1), theta2Grad.reshape(theta2Grad.shape[0] * theta2Grad.shape[1], 1))
    thetaGrad = thetaGrad.reshape(thetaGrad.shape[0], 1)
    return thetaGrad

# Gradient descent
def gradientDescent(X, theta1, theta2, y, lam, m):
    for i in range(itr):
        grad = gradient(X, theta1, theta2, y, lam, m)
        theta1Grad = grad[0:theta1.shape[0] * theta1.shape[1]].reshape(theta1.shape)
        theta2Grad = grad[theta1.shape[0] * theta1.shape[1]:].reshape(theta2.shape)
        theta1 = theta1 - a * theta1Grad
        theta2 = theta2 - a * theta2Grad
    return (theta1, theta2)

with open('data.csv', 'r') as f:
    data = csv.reader(f)
    d = []
    c = 0
    # Read the data
    for row in data:
        # Don't add the first line(it's our features' labels)
        if c == 0:
            c += 1
            continue
        curr_row = []
        k = 0
        for j in row:
            if j != '':
                if k == 1:
                    # Add a 1 between the y and x values(for the bias)
                    curr_row.append(1)
                curr_row.append(float(j))
                k += 1
        d.append(curr_row)
    d = np.array(d)
    x = d[:, 1:]
    y = d[:, 0]
    # Split the data into training cases(80%) and test cases(20%)
    x_train = x[0:(d.shape[0]//5) * 4, :]
    y_train = y[0:(d.shape[0]//5) * 4]
    x_test = x[(d.shape[0]//5) * 4 : d.shape[0], :]
    y_test = y[(d.shape[0]//5) * 4 : d.shape[0]]
    # Initialize theta(s)
    theta1 = np.random.rand(5, x[0].shape[0]) * 2 * epsilon - epsilon
    theta2 = np.random.rand(1, 6) * 2 * epsilon - epsilon
    print(J(x_train, theta1, theta2, y_train, lam, x_train.shape[0]))
    theta1, theta2 = gradientDescent(x_train, theta1, theta2, y_train, lam, x_train.shape[0])

Please note a that my data only has 2 possible outputs so no need for one-vs-all classification.

Thanks in advance!


texts:
I am having the following problem. My code works, but it seems like it can improve a lot. I am fairly new to python and can't seem to get this block any better. The logic behind it goes like this.

I have a dictionary that acts like a tree, it looks like this:

SampleTree[10000000] = ['ACC','ARRAY']
SampleTree[10010000] = ['ACC_ABO','ABO']
SampleTree[10020000] = ['ACC_CHILDLOCK','OPTION']
SampleTree[10030000] = ['ACC_RECO','ARRAY']
SampleTree[10030100] = ['ACC_RECO_ACTIVATE']
SampleTree[10030200] = ['ACC_RECO_ACTIVATE']
SampleTree[10030201] = ['ACC_RECO_ACTIVATE']
SampleTree[10030202] = ['ACC_RECO_ACTIVATE']
SampleTree[10040000] = ['ACC_ADDUSER','OPTION']
SampleTree[10050000] = ['ACC_SETTINGS','ARRAY']

Where the dict key acts like a unique key, which I use to recognize in my program. I use a for loop to iterate over the full dict like this:

KEYLIST = SampleTree.keys()
KEYLIST.sort()

for KEY in KEYLIST :
    if (KEY % 1000000) == 0 :
        BACKS = 0
    elif (KEY % 1000000) == 10000 and (LAST % 1000000) == 0 :
        BACKS = 1
    elif (KEY % 10000) == 0 and (LAST % 1000000) == 10000 :
        BACKS = 2
    elif (KEY % 10000) == 100 and (LAST % 10000) == 0 :
        BACKS = 1
    elif (KEY % 10000) == 0 and (LAST % 10000) == 0 :
        BACKS = 2
    elif (KEY % 10000) == 0 and ((LAST % 10000) % 100) == 0 :
        BACKS = 3
    elif (KEY % 10000) == 0 and (LAST % 100) != 0 :
        BACKS = 4
    elif (KEY % 100) == 1 and ((LAST % 10000) % 100) == 0 :
        BACKS = 1
    elif (KEY % 100) == 0 and (LAST % 100) == 0 :
        BACKS = 2
    elif (KEY % 100) == 0 and (LAST % 100) != 0 :
        BACKS = 3
    elif (KEY % 100) != 0 and (LAST % 100) != 0 :
        BACKS = 2

    LAST=KEY

As you can see in the code, it uses a bunch of if elif tests to see in which branch the Key currently is. And accordingly it sets the BACKS variable how it should be. After this code there are a bunch of operation based on the KEY value and on the BACKS variable.

The BACKS variable depends on the transition of each KEY. Some examples:

from : 10 00 00 00 00 to : 10 01 00 00 00 you need to go BACK 1 time

from : 10 01 00 00 00 to : 10 01 01 00 00 you need to go BACK 1 time

from : 10 01 01 00 00 to : 10 01 02 00 00 you need to go BACK 2 times

from : 10 01 02 00 00 to : 10 02 00 00 00 you need to go BACK 3 times

So what I am trying to say is that there doesn't seem to be a particular logic behind all this. Can you please help me?

My whole problem with the code is that it is so ugly and look like it can improve a lot. But I just can't see a better way. Another big issue is expansion. If I for example add another layer to the tree (add two more zeros to the KEY), the whole logic falls apart.


texts: Finding the sum of all the multiples of 3 or 5 below 1000

texts:
As a Lisp (and functional programming) newbie, I wrote the following code that finds the sum of all the multiples of 3 or 5 below 1000, and I suspect that it is lousy:

(defun multiple-of-3-or-5 (x)
    (or (eq (mod x 3) 0) (eq (mod x 5) 0)) )

(defun generate-list (min max)
    (cond ((> min max) nil)
          (t (cons min (generate-list (+ min 1) max )))))

(defun my-sum (my-list)
    (cond ((atom my-list) 0)
          (t (+ (cond ((multiple-of-3-or-5 (car my-list)) (car my-list))
              (t 0))
            (my-sum (cdr my-list))))))

Any general advice is most welcome. Specifically, I have these questions (other than what you could say):

I had to extend the stack multiple times (using LispWorks) to get a result. Is my use of recursion wrong?
Should I prefer iterative approach over recursion in Lisp too? (as in imperative languages)
Should I use the loop macro if I am to solve it in iterative fashion?


texts: Sorting an associative array alphabetically

texts:
I am using a foreach loop to sort an associative array alphabetically. I would like to know if there is a more proper and/or efficient way of doing it.

The array:

Array
(
    [gr_c] => Array
        (
            [f] => 'value...'
            [a] => 'value...'
            [d] => 'value...'
            [m] => 'value...'
            [c] => 'value...'
            [t] => 'value...'
        )

    [gr_a] => Array
        (
            [h] => 'value...'
            [e] => 'value...'
            [m] => 'value...'
            [a] => 'value...'
            [o] => 'value...'
            [i] => 'value...'
            [c] => 'value...'
            [t] => 'value...'
            [b] => 'value...'
        )

    [gr_b] => Array
        (
            [h] => 'value...'
            [d] => 'value...'
        )
)

became:

Array
(
    [gr_c] => Array
        (
            [a] => 'value...'
            [c] => 'value...'
            [d] => 'value...'
            [f] => 'value...'
            [m] => 'value...'
            [t] => 'value...'
        )

    [gr_a] => Array
        (
            [a] => 'value...'
            [b] => 'value...'
            [c] => 'value...'
            [e] => 'value...'
            [h] => 'value...'
            [i] => 'value...'
            [m] => 'value...'
            [o] => 'value...'
            [t] => 'value...'
        )

    [gr_b] => Array
        (
            [d] => 'value...'
            [h] => 'value...'
        )
)

used snippet:

foreach ($array_name as $key => $value) {
    ksort($array_name[$key]);
}


texts: HasPostgres instance for IO with Snap framework

texts:
I want to write my database access code for a Snap application in a way that makes the queries easy to test from the ghci repl, while also working within the Snap context. My solution so far is to define a HasPostgres instance for IO and to write all my DB access functions following the pattern of allUsers in the code snippet below. Am I doing this correctly?

{-# LANGUAGE OverloadedStrings #-}

module Database where
import Core
import Control.Applicative
import Database.PostgreSQL.Simple.FromRow (field, fromRow)
import Database.PostgreSQL.Simple.ToRow (toRow)
import Database.PostgreSQL.Simple.ToField (toField)
import Snap.Snaplet.PostgresqlSimple
import           Data.Pool
import qualified Database.PostgreSQL.Simple as P
import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.CatchIO

instance FromRow User where
  fromRow = User <$> field <*> field

instance ToRow User where
  toRow (User a b) = [toField a, toField b]

allUsers :: (HasPostgres m) => m [User]
allUsers = query_ "SELECT user_id, email from users"

instance HasPostgres IO where
  getPostgresState = do
    let stripes = 1
    let idle = 5
    let resources = 20
    let ci = P.ConnectInfo "localhost" 5432 "choi" "" "testDatabase"
    pool <- createPool (P.connect ci) P.close stripes (realToFrac (idle :: Double)) resources
    return $ Postgres pool


texts: Get vertical acceleration from rotation vector and accelerometer values

texts:
My goal here is to calculate the acceleration towards the ground, which I call "vertical acceleration". This seems to be working OK for the most part, except when there is a lot of rotation going on in many axis at the same time (see graphs below).

What I am most unsure about here is the math for calculating the vertical acceleration - more specifically, the implementation of matrixMult3x9() and rotationMatrixTranspose() and  getVerticalAcceleration().

What am I asking for?

I would appreciate if someone who knows their way around coordinate systems and matrixes could verify that my implementations look correct. Then I can at least rule out errors in the calculations, and assume that any inaccurate results probably come from the off-center placement of the sensors and/or noise/lag.

Also, I'm wondering what the acceleration in the other two dimensions of accelerationInWorldFrame are relative to.

private float[] rotationVector = {0,0,0};
private float[] accelerometerValues = {0,0,0};
private double verticalAcceleration = 0;

@Override
public void onSensorChanged(SensorEvent event) {
    if( event.sensor.getType() == ROTATION_SENSOR_TYPE ) {
        rotationVector = lowPass(lowPassAlpha, event.values, rotationVector);
    }
    else if( event.sensor.getType() == Sensor.TYPE_ACCELEROMETER ) {
        accelerometerValues = lowPass(lowPassAlpha, event.values, accelerometerValues);
        verticalAcceleration = getVerticalAcceleration(); // Account for rotations
    }
}

private double getVerticalAcceleration(){
    // Based on http://stackoverflow.com/questions/31268852/measuring-vertical-movement-of-non-fixed-android-device
    float[] rotationMatrix = new float[9]; // Both 9 and 16 works, depending on what you're doing with it
    SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVector);

    float[] accelerationInWorldFrame = matrixMult3x9(
            accelerometerValues,
            rotationMatrixTranspose(rotationMatrix)
    );

    return accelerationInWorldFrame[2];
}

private float[] matrixMult3x9(float[] a, float[] b){
    float[] result = new float[3];
    result[0] = a[0]*b[0] + a[1]*b[3] + a[2]*b[6];
    result[1] = a[0]*b[1] + a[1]*b[4] + a[2]*b[7];
    result[2] = a[0]*b[2] + a[1]*b[5] + a[2]*b[8];
    return result;
}

private float[] rotationMatrixTranspose(float[] rotationMatrix){
    float[] result = new float[9];
    result[0] = rotationMatrix[0];
    result[1] = rotationMatrix[3];
    result[2] = rotationMatrix[6];
    result[3] = rotationMatrix[1];
    result[4] = rotationMatrix[4];
    result[5] = rotationMatrix[7];
    result[6] = rotationMatrix[2];
    result[7] = rotationMatrix[5];
    result[8] = rotationMatrix[8];
    return result;
}

private float[] lowPass(float alpha, float[] input, float[] output ) {
    for ( int i=0; i<3; i++ ) {
        output[i] = alpha*output[i] + (1-alpha)*input[i];
    }
    return output;
}

This is a graph of the calculated vertical acceleration of a drop from 1.16m with rotation around both X- and Y-axis. Since I know the exact fall height, it's easy to calculate how long time the drop should take using this, which gives roughly 490ms:

$$d = \frac{(9.82 * t^2)}{2}$$

As you can see, the impact is preceded by a small "bump", and the actual impact spike doesn't even reach above \$\frac{0m}{s^2}\$ (which is of course impossible).

Below is a similar graph from a drop (of the same height) where the phone is not rotating (screen facing upwards). Here the vertical acceleration is spot on as you would expect; \$\frac{-9.82m}{s^2}\$ throughout the fall and a spike up to +\$\frac{5m}{s^2}\$ at the moment of impact.

The graphs for rotation along only one axis at a time roughly look the same as the one with no rotation, displaying a clear positive spike on impact.


texts:
This is a Markov text generator I've created in JavaScript. I'm pretty sure the term "Markov" applies, anyway.

The way the generator works is like this: it first divides the source text into unique "chunks" of length n (specified via the order parameter, greater = more coherent result), and, for each chunk, determines which characters follow it how often. When generating a new text, it looks at the last n characters of what it's generated so far, then randomly selects one of its possible followers and appends it to the text.

(The last bit is apparently slightly different from the Dissociated press algorithm, which would output each follower with the same probability and not account for how often they occur.)

Long story short, here's my code. I'd mainly like to know if I'm following the common best practices as far as object orientation goes, I've had little experience with it before, but any kind of feedback is appreciated.

function Markov(sourceText, order) {

    this.sourceText = sourceText;
    this.order = order;

    this._setupFrequencies();

}

Markov.prototype = {

    _setupFrequencies: function() {

        this.frequencies = {};

        // for each substring of length <order>,
        // create an array of characters that can follow it
        for (var i = 0; i < this.sourceText.length - (this.order - 1); i++) {
            var chunk = this.sourceText.substr(i, this.order);
            if (!this.frequencies.hasOwnProperty(chunk)) {

                var followers = [];
                for (var k = 0; k < this.sourceText.length - (this.order - 1); k++) {
                    if (this.sourceText.substr(k, this.order) == chunk) {
                        follower = this.sourceText.substr(k + this.order, 1);
                        followers.push(follower);
                    }
                }

                this.frequencies[chunk] = followers;

            }
        }

    },

    _getRandomChar: function(chunk) {

        if (!this.frequencies.hasOwnProperty(chunk)) {
            return '';
        }
        var followers = this.frequencies[chunk];
        var randIndex = Math.floor(Math.random() * followers.length);
        return followers[randIndex];

    },

    _getRandomChunk: function() {

        var randIndex = Math.floor(Math.random() * this.sourceText.length);
        return this.sourceText.substr(randIndex, this.order);

    },

    generateText: function(length) {

        if (this.sourceText.length <= this.order) {
            return '';
        }

        var text = this._getRandomChunk();

        // take the last <order> characters from the generated string,
        // select one of its possible followers, and append it
        for (var i = this.order; i < length; i++) {
            var currentChunk = text.substr(text.length - this.order);
            var newChar = this._getRandomChar(currentChunk);

            if (newChar != '') { // the last chunk of the source has no follower
                text += newChar;
            } else {
                text += this._getRandomChunk();
            }
        }

        return text;

    }

}

It would then be used like so:

var text = "Call me Ishmael.  Some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.";
var markov = new Markov(text, 3);
console.log(markov.generateText(100));

// results:
// " no money interest me Ishmael.  Some or no money in my particular to in my purse, and sail about a l"
// "y in my purse, I the would sail about a little on shore, and see thought I would sail about a little"
// "  Some Ishmael.  Some Ishmael.  Some Ishmael.  Some Ishmael.  Some years ago—never mind see the worl"


texts: Creating an iPad-style video frame with CSS and without images

texts:
In an effort to reduce the images being used on the page, I've manipulated box-shading, etc. to make a "vector" looking monitor/ipad look.

This is great and all, gets the job done, however, seems there is still a large load draw on the box-shading rendering. Is there a better method or tweak to this method that would be a better approach?

Original Demo |
Updated Demo

HTML

CSS

.vid{
    max-width:800px;
    width:80%;
    margin:0 auto}

  .vidlink{
    margin-top:50px;
    background:url('img/vidbg.svg') no-repeat;
    background-position:50%;
    background-size:cover;
    border:1px solid rgba(0,0,0,.6);
    box-shadow:0 0 0 25px #fff,
               0 0 5px 27px #777;
    border-radius:5px 5px 0 0;
    display:block;
    margin-bottom:-5px;
    padding:25% 0}

    .vidlink:before{
      content:" ";
      position:relative;
      left:50%;
      top:50%;
      margin:-40px 0 0 -40px;
      padding:28px 40px;
      background:url('img/icon/play.svg') no-repeat;
      background-size:75px;
      background-position:50%}

      .vidlink:hover:before{
        background:url('img/icon/play-hover.svg') no-repeat;
        background-size:75px;
        background-position:50%}


texts: Wrapper function to do polynomial fits with gsl

texts:
I have two arrays of double, say x and y containing some physical data.
I would like to find the best-fitting polynomial function at a given order:

\$y=pol_n(x)=c_0 + c_1*x + c_2*x^2 + ... + c_n * x^n\$

and return the coefficients (\$c\$) in an std::vector. There are no constraints on the function interface. The GNU Scientific Library, gsl, contains some handy functions to properly do the maths, however those functions are in plain old C. I have encapsulated them in this piece of C++ code:

std::vector<double> gsl_polynomial_fit(const double * const data_x,
                                       const double * const data_y,
                                       const int n, const int order,
                                       double & chisq) {
  gsl_vector *y, *c;
  gsl_matrix *X, *cov;
  y = gsl_vector_alloc (n);
  c = gsl_vector_alloc (order+1);
  X   = gsl_matrix_alloc (n, order+1);
  cov = gsl_matrix_alloc (order+1, order+1);

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < order+1; j++) {
      gsl_matrix_set (X, i, j, pow(data_x[i],j));
    }
    gsl_vector_set (y, i, data_y[i]);
  }

  gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (n, order+1);
  gsl_multifit_linear (X, y, c, cov, &chisq, work);
  gsl_multifit_linear_free (work);

  std::vector<double> vc;
  for (int i = 0; i < order+1; i++) {
    vc.push_back(gsl_vector_get(c,i));
  }

  gsl_vector_free (y);
  gsl_vector_free (c);
  gsl_matrix_free (X);
  gsl_matrix_free (cov);

  return vc;
}

Although it is pretty much self-contained it doesn't look very safe. With speed and code clarity in mind, what could be done to improve it?


texts:
This code has been developed with help on Stack Overflow. It is designed to compare two XML files and print the node for any differences (i.e if a entry appears in A.xml and not B.xml and vice versa).

#include "pugixml.hpp"

#include <iostream>
#include <unordered_map>

struct string_hasher
{
    unsigned int operator()(const char* str) const
    {
        // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)
        unsigned int result = 0;

        while (*str)
        {
            result += static_cast<unsigned int>(*str++);
            result += result << 10;
            result ^= result >> 6;
        }

        result += result << 3;
        result ^= result >> 11;
        result += result << 15;

        return result;
    }

    bool operator()(const char* lhs, const char* rhs) const
    {
        return strcmp(lhs, rhs) == 0;
    }
};

typedef std::unordered_map<const char*, pugi::xml_node, string_hasher, string_hasher> xml_node_map;

int main()
{
    pugi::xml_document doca, docb;
    xml_node_map mapa, mapb;

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml"))
        return 1;

    for (auto& node: doca.child("site_entries").children("entry"))
        mapa[node.child_value("id")] = node;

    for (auto& node: docb.child("site_entries").children("entry"))
        mapb[node.child_value("id")] = node;

    for (auto& ea: mapa)
        if (mapb.count(ea.first) == 0)
        {
            std::cout << "Removed:" << std::endl;
            ea.second.print(std::cout);
        }

    for (auto& eb: mapb)
        if (mapa.count(eb.first) == 0)
        {
            std::cout << "Added:" << std::endl;
            eb.second.print(std::cout);
        }
}

I was wondering if I could get some feedback on how it is designed, most notably if this is the optimal approach in terms of performance, since this has to sort hundreds of thousands of entries.

Example XML file:

<entry> <id><![CDATA[90007316]]></id> <url>< [CDATA[http://www.site.co.uk/cgi-bin/tr.cgi?tid=70952276]]></url> <content><![CDATA[Giant Sport Offroad Bike]]></content> <title><![CDATA[Bike]]></title> <price><![CDATA[£100]]></price> <date><![CDATA[11-AUG-15]]></date> <display_reference><![CDATA[2146433-50142933_370647]]></display_reference> <location><![CDATA[City of London]]></location> <category><![CDATA[Bike]]></category> </entry>


texts: Moving a rover and receiving current coordinates

texts:
I made a little text-based game where you move a rover and it gives you the current coordinates. You can essentially move around a 1000x1000 grid, and get output into stdout on what your coordinates are. I'm simply wondering if I could improve anything.

# Rover moving program
from random import randint

# Starting position for rover
r_pos = {'x': randint(1, 1000), 'y': randint(1, 1000)}

def move_rover(x_pos, y_pos):
    if x_pos <= 1000 and y_pos <= 1000:
        r_pos['x'] = x_pos
        r_pos['y'] = y_pos
        print('x{} y{}'.format(
            r_pos['x'], r_pos['y']))
    elif x_pos > 1000 and y_pos > 1000:
        print('Invalid position: x{} y{}'.format(
            x_pos, y_pos))

You run it like this.

>>> import rover
>>> rover.move_rover(234, 789)
x234 y789


texts:
Is this acceptable? What is the next step to improve algorithm and make them more clear and faster?

typedef struct heap_block
{
    struct heap_block* next;
    size_t size;
    bool isfree;
    int x; // for alligment
}header;

#define Heap_Capacity 16777216
unsigned long long active_size;  // # bytes in active allocations

static uint64_t heap[Heap_Capacity/sizeof(uint64_t)];

static char* max_heap =(char*)(&heap[0]);
static char* min_heap = (char*)(&heap[0]);
static char *END_CHK = "\xDE\xAD\xC0\xDA";
header* last_allocated;

void* malloc(size_t sz)
{
    if(sz == 0 || sz > Heap_Capacity)
    {
        return NULL;
    }

    header* block = (header*)heap;
    if(active_size == 0)
    {
        set_data_to_block(block, sz);
        return (void*)last_allocated;
    }

    while(block->next != NULL)
    {
        block = block->next;
    }

    block->next = (header*)((char*)to_end_data(block) + 8);
    header* new_block = block->next;
    set_data_to_block(new_block, sz);

    return (void*)last_allocated;
}

void set_data_to_block(header* block, size_t sz)
{
    block->size = sz;
    block->isfree = false;
    block->next = NULL;

    active_size += sz;
    last_allocated = block + 1;
    char* end_of_data_block = (char*)to_end_data(block);

    if(max_heap < end_of_data_block)
    {
        max_heap = end_of_data_block;
    }
    strcpy(end_of_data_block, END_CHK);
}

header* to_start_metadata(header* block)
{
    return --block;
}

header* to_end_data(header* block)
{
    return (header*)((size_t)(block+1) + block->size);
}


texts: Finding median of 3 elements in array, and sorting them

texts:
The method medianOfThree

returns the median of the first, center and last element in array
sorts the first, center, and last element of the array, so they are in order EXCEPT places the center in the second to last position.

Examples:

  INPUT: 1,2,3
  RETURN:2
  EFFECT:1,2,3

  INPUT: 3,2,1
  RETURN:2
  EFFECT:1,2,3

  INPUT: 2,3,1
  RETURN:2
  EFFECT:1,2,3

  INPUT: -2,-3,-8,1,20
  RETURN:-2
  EFFECT:-8,-3,1,-2,20

  INPUT: 15,20,5,10
  RETURN:15
  EFFECT:10,5,15,20

NOTE: when the center is moved to the second to last position, it doesn't matter where the value that was previously there goes (as long as it's still in the array). Though this probably isn't relevant. In fact, as long as the first, last and one before last are in the correct place, the rest of the elements can get scrambled.

Here is the code. I tested it, but since it is rather complex it was hard to test (need to check return value and array and think carefully of expected result). Any suggestions for tools that make testing code like this easier?

/*
*Sorts first, center and last element, swaps the new center element with the one before the new last and returns its value.
*/
public static int medianOfThree(int[] sample, int start, int end) {
    if(sample.length < 3) {
        throw new IllegalArgumentException("arrays of length three or greater");
    }

    int center = (int)Math.floor((end-start)/2);

    if(sample[start] > sample[end])
       swap(sample, start, end);

    if(sample[start] > sample[center])
       swap(sample, start, center);

    if(sample[center] > sample[end])
       swap(sample, center, end);

int secondLast = end - 1

    swap(sample, center, secondLast );

    return sample[secondLast];

}

//swaps two elements in array given their positions
private static void swap(int[] sample, int x, int y) {
    int temp = sample[x];
    sample[x] = sample[y];
    sample[y] = temp;
}


texts:
I'm writing a simple set/framework of extension methods for argument/parameter validation. What I'm mostly concerned about, ATM is the performance, against the simpliest boilerplate
if(obj == null)
   throw new ArgumentNullException()

The framework I came up with is like that:
The Validatable class packing the base object that will be validated through the ThrowIf() extension method.
public class Validatable<T>
{
    public T Value { get; }
    public Validatable(ref T argument)
    {
        Value = argument;
    }
}

public static Validatable<T> ThrowIf<T>(this T argument)
{
    return new Validatable<T>(ref argument);
}

And test methods themselves:
public static Validatable<T> IsNull<T>(this Validatable<T> argument) where T : class
{
    if (argument.Value == null)
        throw new ArgumentNullException();
    return argument;
}

public static Validatable<T> CollectionEmpty<T>(this Validatable<T> argument) where T: ICollection
{
    if (argument.Value.Count == 0)
        throw new ArgumentException();
    return argument;
}

This allows me to validate items with simple:
List<int> testList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
testList.ThrowIf().IsNull().CollectionEmpty();

Everything was fine untill I decided to test, how it fares against the simple boilerplate.
int iNumber = 1000000000;
Stopwatch sw1 = new Stopwatch();
Stopwatch sw2 = new Stopwatch();
sw1.Start();
for (int i = 0; i < iNumber; ++i)
{
    if (testList == null)
        throw new ArgumentNullException();
    if (testList.Count == 0)
        throw new ArgumentException();
}
sw1.Stop();
sw2.Start();
for (int i = 0; i < iNumber; ++i)
{
    testList.ThrowIf().IsNull().CollectionEmpty();
}
sw2.Stop();

Console.WriteLine($"sw1: {sw1.ElapsedTicks} ticks");
Console.WriteLine($"sw2: {sw2.ElapsedTicks} ticks");

and the output was:

sw1: 10720019 ticks
sw2: 161726524 ticks

That's an order of magnitute difference. It was over 1,000,000,000 iterations, but still the difference is there.
I also tried with
public static void IsNullLite<T>(this T argument)
{
    if (argument == null)
        throw new ArgumentException();
}

public static void CollectionEmpty2Lite<T>(this T argument) where T : ICollection
{
    if (argument.Count == 0)
        throw new ArgumentException();
}

And it's result came somewhere in the middle with

sw3: 84165637 ticks

My questions are:

Should I be concerned with the performance loss. It was +- 3sec vs 47secs on my PC, at 1,000,000,000 iterations. I do not plan to run it in such loops, over so many objects, but I was going to use it my game engine, where I have about 16ms per Update tick, to do much more than just validate some variables.
Is there a better/faster way of doing it. Preferably, I'd like to pack the validation object into some sort of Validatable class, to not clutter the intelisense with dozens of validation methods.
Is there some error on my part, in the way I tested it? I ran the tests in Debug mode with code optimalization turned off.


texts:
My team has developed an API and I've been tasked with creating an authentication layer that allows partners' applications to consume it. To that end, I've created a data store which houses an Application ID, Login and salted/hashed Password for that application to authenticate against. I want to hand back a Token for them to use (which is a key for session information that is kept on the server). The process to generate the Token is below. I have another process which reverses this to validate its authenticity. It seems to stand up to testing, but I'd like to know if there's anything else that should be done to make this properly secure.

private const string Password = "nottheactualpasswordthatisused..";

private static readonly byte[] _Salt =
{
    0x00, 0x01, 0x02, 0x03,
    0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b,
    0x0c, 0x0d, 0x0e, 0x0f
};

private static async Task<string> CreateSecureSessionTokenAsync(int applicationId, DateTime createDate)
{
    using (var aes = Aes.Create())
    {
        if (aes == null)
        {
            return null;
        }

        using (var deriveBytes = new Rfc2898DeriveBytes(Password, _Salt))
        {
            aes.Key = deriveBytes.GetBytes(32);
            aes.IV = deriveBytes.GetBytes(16);
        }

        using (var encryptor = aes.CreateEncryptor())
        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            using (var writer = new StreamWriter(cryptoStream))
            {
                await writer.WriteLineAsync(Convert.ToString(applicationId)).ConfigureAwait(false);
                await writer.WriteLineAsync(Convert.ToString(createDate, CultureInfo.InvariantCulture))
                    .ConfigureAwait(false);
            }

            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }
}


texts:
This isn't meant to be a fully-featured anything, isn't meant to involve any sort of api interactions. It's just meant to be a proof-of-concept of how I could implement nested reddit-style comments.

Every comment is either a top level comment or a reply to another comment. Each level of nesting is indented and is color coded. The color-coding wraps back in on itself (eg if there are 5 defined files, then the 6th layer of nesting should have the same color code as the 1st layer of nesting).

import * as React from 'react';

export class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments : [
                {
                    'user': 'user1',
                    'text': 'text1',
                    comments: [{
                        'user': 'user3',
                        'text': 'responding to text1',
                        comments: [
                            {
                                'user': 'user1',
                                'text': 'responding to user3'
                            }
                        ]
                    }]
                },
                {
                    'user': 'user2',
                    'text': 'text2'
                }
            ]
        }
    }
    render() {
        return

            {
                this.state.comments.map(comment => (
                    <Comment comment={comment}/>
                ))
            }

;
    }
}

class Comment extends React.Component {
    renderSidebar(level) {
        const colors = ['green','orange','red'];
        const index = level % colors.length;
        return {'border-left':'solid 3px ' + colors[index]};
    }

    render() {
        const comment = this.props.comment;
        const subComments = comment.comments || [];
        const level = this.props.level || 0;
        return (

{comment.user}

{comment.text}

                    {subComments.map(comment => (
                        <Comment comment={comment} level={level + 1}/>
                        ))}

        )
    }
}

jsfiddle here: https://jsfiddle.net/z318wsq6/


texts: Find number of divisors for integer and sum of integers

texts:
This function computes and returns the number of divisors an integer has. But it is very slow and I believe it can be optimized for speed.

unsigned long long int find_no_of_divisors(unsigned long long int myno,FILE *ifp)
{

    unsigned long long int divsrs = 2;
    unsigned long long int k = 2;

    if(myno == 1)
    {
        return 1;
    }

    if(myno == 2)
    {
        return 2;
    }

    while(1)
    {
        if((myno % k) == 0)
        {
            divsrs++;
            if(divsrs == MY_ULLONG_MAX)
            {
                printf("Overflow detected in the calculated value for divisors of a number... Exiting");
                fclose(ifp);
                exit(-1);
            }
        }

        k++;

        if(k > (myno/2))
        {
            break;
        }
    }

    return divsrs;
}

This one computes and returns the sum of first n integers:

unsigned long long int next_no(unsigned long long int idx,unsigned long long int cur_no,FILE *ifp)
{
    unsigned long long int next_no;

    next_no = ((idx)*(idx + 1))/2;

    if((next_no - idx) != cur_no)
    {
        printf("Overflow detected in the value of the calculated number... Exiting");
        fclose(ifp);
        exit(-1);
    }
    return next_no;
}

Could there be any glitches or functionality issues? (PS - I did not want to use a sqrt() function due to my portability constraints.)


texts: Class made to do some basic RGB analysis

texts:
I created this class to load in an image and get some specific values I needed.

from PIL import Image
import pandas as pd

class Img:
    def __init__(self,filename):
        self.name = filename
        self.image = Image.open(self.name) # open image using PIL

        # convert the image to a pandas df
        self.df = pd.DataFrame(data=list(self.image.getdata()))

        # get the RGB values from the image
        self.rList = self.df[0]
        self.gList = self.df[1]
        self.bList = self.df[2]

        # get the mean RGB values from the image
        def getMean(self,rgb):
            return rgb.mean()

        self.r = getMean(self,self.rList)
        self.g = getMean(self,self.gList)
        self.b = getMean(self,self.bList)

        # calculate luminance(brightness) based on the RGB values
        def lumi(self):
            l = (0.299*self.rList + 0.587*self.gList + 0.114*self.bList)
            return l[l!=0]

        self.l = lumi(self)

        # calculate the contrast using the Michelson contrast formula.
        def con(self):
            min = self.l.quantile(0.05)
            max = self.l.quantile(0.95)
            return ((max-min) / (max + min))

        self.contrast = con(self)

My goal: With the class structure created, I intend to create some instances into an list and plot values.

def loadImages(folder):
    images = []
    for image in os.listdir(folder+'/'):
        if image.endswith('.jpg'):
            name = folder+'/'+image
            images.append(Img(name))
    return images

images = loadImages('faces')

from matplotlib import pyplot as plt

plt.scatter([x for x in range(0,len(images))],[x.b for x in images])


texts: Simple autoloader, but trying to make it psr-compliat

texts:
I made this class, just to understand what PSR autloader is. I didn't want to download and use it without knowing how it works. So, the one I built is very simple, but I would like a review on how to improve it, and what it lacks to be 100% psr-1 compliant.

Here is the class loader.

namespace ClassLoader;

class Loader
{
    private $classDir;
    private $namespace;
    public $dirSeparatorSymbol = '\\';

    public function __construct($namespace, $classDir)
    {
        $this->classDir = $classDir;
        $this->namespace = $namespace;

    }

    private function load($class)
    {

        $include_path = str_replace($this->dirSeparatorSymbol, DIRECTORY_SEPARATOR, $this->classDir);

        $classFilename = substr($class, strrpos($class, '\\') + 1) . '.php';

        if(file_exists($class = $include_path.$classFilename)){
            require $class;

            return true;
        }

    }

    public function register()
    {
        spl_autoload_register([$this, 'load']);
    }
}

Also: You can see the constructor's first argument: __construct($namespace, ... has a namespace param. But I don't know how this is used. The class loads any functions just by doing:

$a = new ClassLoader\Loader('unused/param', 'path/to/bar');
$a->register();

new bar;


texts:
answer = input("what's the word")
answer_list = list(answer) #list version of the original word
presentation = []
for i in range(len(answer_list)):
    presentation.append("_") #makes a list that shows the progress of the player during the game

incorrect = 0 #number of allowed guesses
completion = False # condition for end game
while completion == False:
    attempt = input('guess')
    ind = 0 #index of the guess that appears in answer_list
    count = 0 #number of occurences of the guess in answer_list
    for x in answer_list: #searches for all occurences of the guess in answer_list and change presentation accordingly
        if x == attempt:
            num = answer_list.index(attempt)
            presentation[num] = attempt
            answer_list[num] = 0 #if there is an occurence, replace that occurence with 0 in answer_list
            count += 1
    if count>0:
        print ("Your guess is correct, there was/were {} matches in the word".format(count))
        print(presentation)
    elif count == 0:
        incorrect += 1

    if incorrect == 5:
        print("You lost")
        break

    if any(answer_list) == False: #since all 0 have a negative truthy value, we can use any() to check if any element has a truthy value
        print("Congrats, you got everything correct")
        completion = True
        break

I want to make clean up this hangman game and format it as 1 or 2 functions. How do I make it work? For example, initializing lists could be initialize() and from the declaration of incorrect to the end of the code can be play_hangman(). I am still very new to python.


texts: Checking if a given string is in alphabetical order

texts:
I wrote this function to check if a given string is in alphabetic order. How can I improve?

def alphacheck(x):
    '''This function checks if a given string is in Alphabetical order'''

    # Creating a variable to allow me to efficiently index a string of any length
    i = len(x) - 1
    # Using a recursive formula and checking for the base case when the string is of less than one character
    if len(x) <= 1:
        return True
    # This the recursive portion of the formula
    else:
        # This code checks if the last two characters are in alphabetical order
        # By utilizing the property that the letters of the alphabet increase in "value" accroding to python
        if x[i - 1] <= x[i]:
            # I remove the last letter of the string to reduce the probelm size
            x = x[:i]
            # I then repeat this on the smaller string until it reaches the base case or
            # Finds out the string is not in alphabetical order and returns False
            return alphacheck(x)
        else:
            return False


texts: How do I avoid over-using the garbage collector?

texts:
I'm wondering what the best way of initializing variables so that I don't over use the garbage collector with a for-loop.  Assuming the variable is only used inside the for-loop.  Is it better to declare the variable outside of the for-loop?

public void foo() {
    String tempName;
    for (Person person : personList) {
        tempName = person.getName();

        //Do work with name
    }
}

Or inside the for-loop?

public void foo() {
    for (Person person : personList) {
        String tempName = person.getName();

        //Do work with name
    }
}


texts: Correct implementation of Factory pattern in C++

texts:
I am primarily a java programmer and for the first time working in C++.

I have implemented a Factory design pattern in C++.

    class TaskFactory
    {
    public:
        typedef Task* (*create_callback)(map<string, string> vMap);
        static void register_task(const string& type, create_callback cb); // function for registering the classes with Factory
        static void unregister_task(const string& type); // function for unregistering the classess with factory
        static Task* create_task(const string& type,map<string, string> vMap); // function for creating instance of Tasks classes on the basis of class type
    private:
        static map<string, create_callback> mTasks; // map to store class types along with callback
    };

Following is the factory implementation.

    map<string, TaskFactory::create_callback> TaskFactory::mTasks;

    //registers the task with the factory
    void TaskFactory::register_task(const string& type, TaskFactory::create_callback cb){
        mTasks[type]= cb;
    }
    //unregisters the task with the factory
    void TaskFactory::unregister_task(const string& type){
        mTasks.erase(type);
    }
    //creates instance of Task subclasses on the basis of task
    Task* TaskFactory::create_task(const std::string& type, map<string, string> vMap){
        map<string, TaskFactory::create_callback>::iterator it=mTasks.find(type);
        if(it==mTasks.end()){
            return NULL;
        }else{
            return mTasks[type](vMap);
        }
    }

And my base Task class is below:

    class Task{
    private:
        map<string, string> vMap;
        Task(map<string, string>);
    public:
                    static Task* create(map<string, string>); // funtion is used for creating instance of the Task
            };

In code review I was told that Factory implementation is not doing its intended job. But in my opinion its working very well.
Is any thing wrong with this implementation?


texts:
This is a getter in a class.  It recursively generates a tree/hash to a certain level of depth.

def children(depth: 4, article_children: self.root.child_links)
  get_children = lambda do |depth, article_children|
    article_children.map do |uri|
      if (depth == 0)
        Article.new(uri: uri)
      else
        article = Article.new(uri: uri)
        { article => get_children.call(depth - 1, article.child_links) }
      end
    end
  end

  @children ||= get_children.call(depth, self.root.child_links)
  return @children
end

I would like feedback on these specific areas:

Readability/maintainability concerns
Is this an appropriate use of lambda?
Style concerns
General feedback


texts: How can i make this code more robust, fail proof?

texts:
I have some code that needs to update 2 separate databases with user credentials.
The first database, I just use standard sql to do it.  The second database, I have to use command line scripts to update a specific table.
What I'm worried about is what to do if the first update fails, or if any of the updates fail.
Here's what the code looks like right now:

local update_password = function(user_id, new_password, session_userid)
   local user = listusers(user_id,nil)
   if #user == 0 then
      return false, "User does not exist"
   else
      sql = "UPDATE users SET password='"..new_password.."', ".."updatedname='"..session_userid.."', updateddatetime="..os.date("%Y%m%d%H%M%S")..createwhereclause(uid)
      runsqlcommand(sql)
      -- remove user from second db
      local user = {}
      user.descr, user.errtxt = opencmd({"dbctrl", "rm", user_id})
      if not user.errtext then
         user.descr, user.errtxt = opencmd({"dbctrl", "add", user_id, new_password})
      else
         result = "Unable to update cdb with new credentials"
         return false, result
      end
      if not user.errtext then
         result = "User's password has been updated"
      else
         result = "Unable to update cdb with new credentials"
         return false, result
      end
   end
   return true, result
end

I guess I should check each step of the way to make sure that the previous sql worked.  So after updating database 1, I should do a select using the new credentials to make sure I get a result.
But do you have any other suggestions to improve the reliability of this code?
Thanks.


texts: Setting fixed height panes based on window's width

texts:
I have a webapp that follows responsive design and has following layout structure. The left layout appears when the window's width > 768px and right layout shows otherwise.

Based on preliminary research I think there are no modern pure CSS ways of doing it, so I implemented some jQuery code to solve it.

$(window).resize(function() {
    if (window.innerWidth > 768) {
        fixedHeight = window.innerHeight - $('.search__results').position().top;
        $('.search__results').addClass('overflow-y-scroll').height(fixedHeight);
    } else {
        $('.search__results').removeClass('overflow-y-scroll').height('auto');
    }
});

My CSS class is as follows:

.overflow-y-scroll {
    overflow-y: scroll;
}

I would like to leave my code up here for review and seek for DRY-er code, some spots I think may be up for improvement.

768px being fixed, should it be called from a global variable where it is the single point for setting the breakpoints? If so, I wonder where it should be placed so CSS & JavaScript can both use it?

Should I name $('.search__results') as a variable? Perhaps even make it a more generic helper function? If so, does any one have any tips on how to write it?

I'm also curious as to what is usually the best practice when creating such responsive layouts.


texts: "command preprocessing" with bash - string parsing and handling pipes

texts:
The following is a bash script named wrapper.sh:

#!/bin/bash

data="ZAA:huhu;ZBB:blub;___uname" # actually coming from a Python script

i=1 # counter
while true ; do # loop infinitely
    segment=$(echo $data | cut -d ';' -f$i)
    if [ -z "$segment" ] ; then # is segment empty?
        break
    fi
    if [[ $segment == ___* ]] ; then # is this a command?
        cmd="${segment:3}" # strip command prefix
        $cmd "${@:2}" # run *interactive* command
        # cat | $cmd "${@:2}" # "OPTIONAL": pass data from stdin ONLY IF THERE IS A PIPE (?)
    else
        varname=$(echo $segment | cut -d ':' -f1)
        vardata=$(echo $segment | cut -d ':' -f2)
        export $varname=$vardata # export environment variable
    fi
    i=$((i + 1)) # increment counter
done

# Just a test
echo $ZAA
echo $ZBB

The above script has to accomplish the following goals:

Pass its own parameters to a Python script, which processes them and returns a data string (intentionally left out of the above example)
Set (export) an arbitrary number of environment variables. Their names and contents are provided in data.
Run a command also provided in data and pass on all but the first argument given to the shell script.

Goal the code does not achieve yet: If a pipe is passed to the script (as in some_program | ./wrapper.sh), the pipe is supposed to passed on to the command called by wrapper.sh. The statement cat | $cmd "${@:2}" basically does this, but it hangs if no pipe is passed to wrapper.sh.

Why? Well actually, this thing started as a pure Python script, which was calling the command through subprocess.Popen. But it turned out insanely hard and error-prone to run an interactive command like this where an actual human user is supposed to interact with the (running) command. This is something bash is infinitely better at.

Example:

(env) user@box:~> ./wrapper.sh
Linux
huhu
blub
(env) user@box:~> ./wrapper.sh omitted
Linux
huhu
blub
(env) user@box:~> ./wrapper.sh omitted -a
Linux X.X 4.X.XXX #1 SMP XXX 2018 (XXX) x86_64 x86_64 x86_64 GNU/Linux
huhu
blub

I am not exactly a frequent bash coder, so any ideas on how to improve the above are highly welcome. I might also have overlooked "edge cases" where my script does something strange - I'd love to know.


texts:
I am trying to solve a problem on Hacker Rank and the question is as follows:

  Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value \$K\$. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with:

sweetness =(1× Least sweet cookie + 2× 2nd least sweet cookie).

  He repeats this procedure until all the cookies in his collection have a sweetness \$\ge K\$.
  You are given Jesse's cookies. Print the number of operations required to give the cookies a sweetness \$\ge K\$. Print \$−1\$ if this isn't possible.

  Input Format

  The first line consists of integers \$N\$, the number of cookies and \$K\$, the minimum required sweetness, separated by a space.
  The next line contains \$N\$ integers describing the array \$A\$ where \$Ai\$ is the sweetness of the \$i\$th cookie in Jesse's collection.

  Constraints

  \$1\le N\le 10^6\$
    \$0\le K\le 10^9\$
    \$0\le Ai\le 10^6\$

  Output Format

  Output the number of operations that are needed to increase the cookie's sweetness \$\ge  k\$.
  Output \$−1\$ if this isn't possible.

For this I have written code in Java like this:

    public class Solution {
        public int getMinStepsToGetK(long k,LinkedList<Integer> newList){
            Collections.sort(newList);
            int count=0;
            while(newList.getFirst()<k){
                if(newList.size()>=2){
                count++;
                int tempFirst = newList.removeFirst();
                int tempSecond = newList.removeFirst();
                newList.add(tempFirst+(tempSecond*2));
                Collections.sort(newList);
                }
                else{
                    return -1;
                }
            }
            return count;
        }
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Solution newObj = new Solution();
            Scanner scanObj = new Scanner(System.in);
            int numOfCookies = scanObj.nextInt();
            long minSweetness = scanObj.nextLong();
            LinkedList<Integer> newList = new LinkedList<Integer>();
            for(int i=0;i<numOfCookies;i++){
                newList.add(scanObj.nextInt());
            }
            System.out.println(newObj.getMinStepsToGetK(minSweetness,newList));
        }
    }

For the above code I am getting half of my test cases right and the other half is giving time out exception (taking more than 4 seconds to give output). My question is basically: where can I improve the performance of the code? Is there any other approach which I should go about?


texts:
In C++, to simplify string conversion between std::string and std::wstring, I created the following utility template functions:

#pragma once

#include <vector>
#include <string>
#include <cstring>
#include <cwchar>
#include <cassert>

template<typename Td>
Td string_cast( const char* pSource, unsigned int codePage = CP_ACP );

template<typename Td>
Td string_cast( const wchar_t* pSource, unsigned int codePage = 1200 );

template<typename Td>
Td string_cast( const std::string& source, unsigned int codePage = CP_ACP );

template<typename Td>
Td string_cast( const std::wstring& source, unsigned int codePage = 1200 );

template<>
std::string string_cast( const char* pSource, unsigned int codePage )
{
    assert( pSource != 0 );
    return std::string( pSource );
}

template<>
std::wstring string_cast( const char* pSource, unsigned int codePage )
{
    assert( pSource != 0 );
    std::size_t sourceLength = std::strlen( pSource );
    if( sourceLength == 0 )
    {
        return std::wstring();
    }

    int length = ::MultiByteToWideChar( codePage, 0, pSource, sourceLength, NULL, 0 );
    if( length == 0 )
    {
        return std::wstring();
    }

    std::vector<wchar_t> buffer( length );
    ::MultiByteToWideChar( codePage, 0, pSource, sourceLength, &buffer[ 0 ], length );

    return std::wstring( buffer.begin(), buffer.end() );
}

template<>
std::string string_cast( const wchar_t* pSource, unsigned int codePage )
{
    assert( pSource != 0 );
    size_t sourceLength = std::wcslen( pSource );
    if( sourceLength == 0 )
    {
        return std::string();
    }

    int length = ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, NULL, 0, NULL, NULL );
    if( length == 0 )
    {
        return std::string();
    }

    std::vector<char> buffer( length );
    ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, &buffer[ 0 ], length, NULL, NULL );

    return std::string( buffer.begin(), buffer.end() );
}

template<>
std::wstring string_cast( const wchar_t* pSource, unsigned int codePage )
{
    assert( pSource != 0 );
    return std::wstring( pSource );
}

template<>
std::string string_cast( const std::string& source, unsigned int codePage )
{
    return source;
}

template<>
std::wstring string_cast( const std::string& source, unsigned int codePage )
{
    if( source.empty() )
    {
        return std::wstring();
    }

    int length = ::MultiByteToWideChar( codePage, 0, source.data(), source.length(), NULL, 0 );
    if( length == 0 )
    {
        return std::wstring();
    }

    std::vector<wchar_t> buffer( length );
    ::MultiByteToWideChar( codePage, 0, source.data(), source.length(), &buffer[ 0 ], length );

    return std::wstring( buffer.begin(), buffer.end() );
}

template<>
std::string string_cast( const std::wstring& source, unsigned int codePage )
{
    if( source.empty() )
    {
        return std::string();
    }

    int length = ::WideCharToMultiByte( codePage, 0, source.data(), source.length(), NULL, 0, NULL, NULL );
    if( length == 0 )
    {
        return std::string();
    }

    std::vector<char> buffer( length );
    ::WideCharToMultiByte( codePage, 0, source.data(), source.length(), &buffer[ 0 ], length, NULL, NULL );

    return std::string( buffer.begin(), buffer.end() );
}

template<>
std::wstring string_cast( const std::wstring& source, unsigned int codePage )
{
    return source;
}

Are there any bugs or further optimizations?


texts: Python, numpy, optimize module to handle big file

texts:
With the help of some people here and there, I wrote the module below which works very well if the file targets.csv is not too big.

As soon as this file exceeds 100 MB, a MemoryError is returned.

The problem is that I used numpy to make the computations faster (and they became really fast compared to the previous versions of this module), and I think numpy requires to load the entire file into memory.

However, there should be a way to handle the MemoryError that happens there:

targets = np.array([(float(X), float(Y), float(Z))
           for X, Y, Z in csv.reader(open('targets.csv'))])

Any ideas?

Let me know if you need more details (files, etc.)

import csv
import numpy as np
import scipy.spatial
import cv2
import random

"""loading files"""

points = np.array([(int(R), int(G), int(B), float(X), float(Y), float(Z))
              for R, G, B, X, Y, Z in csv.reader(open('colorlist.csv'))])
    # load X,Y,Z coordinates of 'points' in a np.array
print "colorlist loaded"

targets = np.array([(float(X), float(Y), float(Z))
           for X, Y, Z in csv.reader(open('targets.csv'))])
    # load the XYZ target values in a np.array
print "targets loaded"

img = cv2.imread("MAP.tif", -1)
height, width = img.shape
total = height * width
# load dimensions of tif image
print "MAP loaded"

ppm = file("walladrien.ppm", 'w')
ppm.write("P3" + "\n" +  str(height) + " " + str(width) +"\n" + "255" + "\n")
# write PPM file header

"""doing geometry"""

tri = scipy.spatial.Delaunay(points[:,[3,4,5]], furthest_site=False) # True makes an almost BW picture
# Delaunay triangulation

indices = tri.simplices
# indices of vertices

vertices = points[indices]
# the vertices for each tetrahedron

tet = tri.find_simplex(targets)

U = tri.transform[tet,:3]
V = targets - tri.transform[tet,3]
b = np.einsum('ijk,ik->ij', U, V)
bcoords = np.c_[b, 1 - b.sum(axis=1)]
# find the barycentric coordinates of each point

"""looping through data"""

i = 0

for i in range(total):

    if tet[i] == -1:
        # this means that the point lies outside the convex hull

        R = G = B = 255

        ppm.write(str(R) + ' ' + str(G) + ' ' + str(B) + "\n")  # writes a pixel

    else:

        R0 = int(vertices[tet[i]][0][0])
        G0 = int(vertices[tet[i]][0][1])
        B0 = int(vertices[tet[i]][0][2])
        R1 = int(vertices[tet[i]][1][0])
        G1 = int(vertices[tet[i]][1][1])
        B1 = int(vertices[tet[i]][1][2])
        R2 = int(vertices[tet[i]][2][0])
        G2 = int(vertices[tet[i]][2][1])
        B2 = int(vertices[tet[i]][2][2])
        R3 = int(vertices[tet[i]][3][0])
        G3 = int(vertices[tet[i]][3][1])
        B3 = int(vertices[tet[i]][3][2])

        rand = random.uniform(0,1)

        BC_0 = bcoords[i][0]
        BC_1 = bcoords[i][1]
        BC_2 = bcoords[i][2]
        BC_3 = bcoords[i][3]

        i += 1

        if rand <= BC_0:
            ppm.write(str(R0) + ' ' + str(G0) + ' ' + str(B0) + "\n")  # writes a pixel

        elif rand <= BC_0 + BC_1:
            ppm.write(str(R1) + ' ' + str(G1) + ' ' + str(B1) + "\n")  # writes a pixel

        elif rand <= BC_0 + BC_1 + BC_2:
            ppm.write(str(R2) + ' ' + str(G2) + ' ' + str(B2) + "\n")  # writes a pixel

        else:
            ppm.write(str(R3) + ' ' + str(G3) + ' ' + str(B3) + "\n")  # writes a pixel

ppm.close()
print 'done'


texts:
I am trying to learn Ruby and made a simple Caesar cipher program and I was wondering if the following code follows the 'ruby way' or the way most ruby users would do it

# Implements the classes caesar cipher encryption and decryption.
class CaesarCipher
  def initialize(shift)
    @shift = shift
  end

  def encrypt(str)
    str_array = str.split("")
    str_array.map! { |char| round_over(char) }.join
  end

  def decrypt(str)
    str_array = str.split("")
    str_array.map! { |char| round_down(char) }.join
  end

  private
  def round_over(char)
    if char.ord + @shift > "z".ord
      (char.ord + @shift - 26).chr
    elsif char.ord + @shift > "Z".ord && char.ord <= "Z".ord
      (char.ord + @shift - 26).chr
    else
      (char.ord + @shift).chr
    end
  end

  def round_down(char)
    if char.ord - @shift < "a".ord && /[[:lower:]]/.match(char) # checks for lowercase
      (char.ord - @shift + 26).chr
    elsif char.ord - @shift < "A".ord
      (char.ord - @shift + 26).chr
    else
      (char.ord - @shift).chr
    end
  end
end


texts: Code to generate a random date of birth which will always represent an age less than 18 years from current date

texts:
I want to generate a random date of birth [mm/dd/yyyy]which will
represent an age equal to less than 18years old
My requirement is to dynamically generate test data [date of birth]
to negatively test a system which needs a date of birth (age) to be
always greater than 18 years old
The system which I am trying to test compares the user's input
D.O.B. with the current date and calculates the age, if the age is
less than 18 years old then throws an error
I have tried to create the below python snippet to generate a date
of birth [for age less than 18 years old] and kindly need expert opinions to know if this
is indeed the correct/best approach?

start_date = date.today() - relativedelta(years=18)
end_date = date.today()
time_between_dates = end_date - start_date
days_between_dates = time_between_dates.days
random_number_of_days = random.randrange(days_between_dates)
random_date = start_date + datetime.timedelta(days=random_number_of_days)
month = random_date.month
day = random_date.day
year = random_date.year
# Once I have the the day, month, year then I can convert it in ISO date format as per my needs


texts: Atbash Cipher in Rust - Exercism exercise

texts:
So I'm working on an implementation of the Atbash Cipher for Rust - it is an exercise on exercism.io. I come from a little C experience and found my code to be rather round about and kind of tortured. Doing str and String manipulation in Rust is something I haven't really grokked yet. It seems like this would take up fewer lines of code in C.

Below is my code - am I going about this in the right way for Rust, or am I missing some important concept or way of manipulating the data? Is this as simple as it should be?

The exercise involves getting an input &str and outputting a String, with each character changed as per the Atbash cipher, adding a space every 5 characters. Included is also a decode function. This all goes in a lib.rs.

// "Encipher" with the Atbash cipher.
pub fn encode(plain: &str) -> String {
    let mut coded: String = plain.to_string();

    coded.retain(|c| c.is_ascii_alphanumeric());
    coded.make_ascii_lowercase();

    let coded_no_spacing = String::from_utf8(
        coded
            .bytes()
            .map(|c| {
                if c.is_ascii_alphabetic() {
                    122 - c + 97
                } else {
                    c
                }
            })
            .collect(),
    )
    .unwrap();

    spacer(coded_no_spacing)
}

/// "Decipher" with the Atbash cipher.
pub fn decode(cipher: &str) -> String {
    let mut out = encode(cipher);
    out.retain(|c| c.is_ascii_alphanumeric());
    out
}

fn spacer(coded_no_spacing: String) -> String {
    let mut coded_no_spacing = coded_no_spacing.chars();

    let mut temp_char = coded_no_spacing.next();
    let mut counter = 0;
    let mut coded_with_spaces = "".to_string();
    while temp_char.is_some() {
        if counter % 5 == 0 && counter != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(temp_char.unwrap());
        temp_char = coded_no_spacing.next();
        counter += 1;
    }
    coded_with_spaces
}


texts:
I have recently written a Brainfuck interpreter in C#. I tested it with the examples given on EsoLang website. It does not handle errors right now.

Questions:

Even that it can run only one program at once, should I maybe put the variables into the class (create new class) or just leave them inside the BF method?
Should I split all of the code from the cases and create separate methods for them, accessing them from the switch?

Of course, I am also looking for all other suggestions on how I can improve this code.

using System;

namespace BF
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            if (args.Length == 0) {
                Console.WriteLine("Specify the source file!");
            } else {
                if (System.IO.File.Exists(args[0]) == true) {
                    BF(System.IO.File.ReadAllText(args[0]).ToCharArray());
                } else {
                    Console.WriteLine("The path to the file is not valid!");
                }
            }

        }

        private static void BF(char[] instructions)
        {
            int instructionPointer = 0;

            int[] memory = new int[30000];

            int pointer = 1;

            while (instructionPointer < instructions.Length) {

                switch (instructions[instructionPointer]) {

                    case '>': {
                            pointer += 1;
                            break;
                        }

                    case '<': {
                            pointer -= 1;
                            break;
                        }

                    case '+': {
                            memory[pointer] += 1;
                            break;
                        }

                    case '-': {
                            memory[pointer] -= 1;
                            break;
                        }

                    case '.': {
                            Console.Write((char)memory[pointer]);
                            break;
                        }

                    case ',': {
                            memory[pointer] = byte.Parse(Console.Read().ToString());
                            break;
                        }
                    case '[':
                        {
                        if (memory[pointer] == 0) {
                            int s = 0;
                            int ptr = instructionPointer + 1;
                            while (instructions[ptr] != ']' || s > 0) {
                                if (instructions[ptr] == '[') {
                                    s += 1;
                                } else if (instructions[ptr] == ']') {
                                    s -= 1;
                                }
                                ptr += 1;
                                instructionPointer = ptr;
                                }
                            }
                            break;
                        }

                    case ']': {
                            if (memory[pointer] != 0) {
                                int s = 0;
                                int ptr = instructionPointer - 1;
                                while (instructions[ptr] != '[' || s > 0) {
                                    if (instructions[ptr] == ']') {
                                        s += 1;
                                    } else if (instructions[ptr] == '[') {
                                        s -= 1;
                                    }
                                    ptr -= 1;
                                    instructionPointer = ptr;
                                }
                            }
                            break;
                        }
                }

                instructionPointer += 1;

            }

        }
    }
}


texts:
Objective

  Write a function JoinWithAnd in Java with the following signature:

String JoinWithAnd(String a, String b, String c, String d, String e)

  So that:

  If no input is provided, it returns an empty string
  If any one input is provided, it returns the string as it is
  If more than one inputs are provided, it combines all strings with AND in between and returns

  The input/output looks something like this:

 -----------------------------------------------------------
|Function Call                             |Returns         |
 -----------------------------------------------------------
|JoinWithAnd(null, null, null, null, null);|“”              |
|JoinWithAnd(“A”, null, null, null, null); |“A”             |
|JoinWithAnd(null, null, “C”, null, null); |“C”             |
|JoinWithAnd(“A”, “B”, null, null, null);  |“A AND B”       |
|JoinWithAnd(“A”, null, “C”, “D”, null);   |“A AND C AND D” |
 -----------------------------------------------------------

  Constraints

  DO NOT change the method signature
  DO NOT use arrays
  DO NOT use StringBuffer or any other type of optimized String variants
  DO NOT use Java Collection

The closest I could get is:

public class JoinWithAnd {

    private final String infix = " AND ";
    private final String regex = "( AND null)+";

    private String compute(String a, String b, String c, String d, String e) {
        return (a + infix + b + infix + c + infix + d + infix + e).replaceAll(regex, "");
    }

    public static void main(String[] args) {
        JoinWithAnd oj = new JoinWithAnd();
        System.out.println(oj.compute("P", null, "R", "S", null));
    }

}

But this doesn't seem to be sufficient since it uses replaceAll.

Could anyone please suggest in what other ways this problem could be solved keeping all the constraints in mind?


texts: A C++ program to check if a string is a pangram

texts:
I'm new to C++ and decided to implement a simple program that checks if a string is a pangram (i.e. the string contains all the English alphabet letters). It's my first program in C++ and I have some background with interpreted programming languages like Python and R.
I want to know what are the common beginners mistakes I'm making in this implementation, whether I'm following good practices, what I should avoid etc.
The Code
#include<iostream>
#include<string>
#include<vector>
#include <algorithm>

bool isPangram(std::string str) {
    std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Transforming a string to upper case
    std::vector<bool> hash_table(26, false); // a hash_table that maps the  index of a letter from the alphabet
                                             // and a boolean saying if the string contains this element
    int index;
    for(auto c: str){
        if(isalpha(c))
            // Checks if the element in the string is in the alphabet
            index = c - 'A';
            hash_table[index] = true;
            std::cout << index << std::endl;

    };

    if(std::any_of(hash_table.begin(), hash_table.end(), [](bool v) { return !v; })) {
        // if any of the items in the array evaluates to false
        // means that the string don't contain all the elements
        // in the alphabet,hence, it's not a pangram

        return false;
    }
    return true;
};

int main() {
    std::string str = "We promptly judged antique ivory buckles for the next prize";
    if (isPangram(str)){
         std::cout << "Yes" << std::endl;
     }
     else {
         std::cout << "No" << std::endl;
     };
     return 0;
}
```


texts: Slicing up an image into rows and columns in Java

texts:
I have created some code in Java that slices up an image into rows and columns and then saves each image to the file system. This works but there are some improvements I would like to make

I would like it to automatically know the original file name and extension using the StringTokenizer class so I do not have to hard code them into the class.

for example...

I want the filenames to be

targetFolder+"/"+originalfilename+"-"+(count++)"."+extension

Any general comments on the code would be appreciated too because there may be a better way of doing this

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class GridImage implements Runnable {
    private BufferedImage image;
    private int rows, columns;
    private BufferedImage[][] smallImages;
    private int smallWidth;
    private int smallHeight;

    public GridImage(String filename, int rows, int columns) {
        this.rows = rows;
        this.columns = columns;
        try {
            image = ImageIO.read(new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.smallWidth = image.getWidth() / columns;
        this.smallHeight = image.getHeight() / rows;
        smallImages = new BufferedImage[columns][rows];
    }

    public void run() {
        int count = 0;
        for (int x = 0; x < columns; x++) {
            for (int y = 0; y < rows; y++) {
                smallImages[x][y] = image.getSubimage(x * smallWidth, y
                        * smallHeight, smallWidth, smallHeight);
                try {
                    ImageIO.write(smallImages[x][y], "png", new File("tile-"
                            + (count++) + ".png"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        GridImage image = new GridImage("img/card-grid-image-mass-effect.jpg",
                4, 15);
        new Thread(image).start();
    }
}

This code actually produces the smaller images with a  different filetype from the original

What's the best way to slice up an image into a two dimentional array of tiles and save them to the bloody laptop?


texts: Attempting to build template but Having Issue with gets and posts

texts:
I am building my first real php web app. as many you know this requires building LOTS of pages.

in attempting to streamline the repetitive stuff i placed most of my stuff within a content.php page which looks like this

?php include_once ('config3.inc');?>
<?php if(isset($_GET['p'])){
    $page = $_GET['p'];

}else {
    $page ='';
}
?>
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo $_SERVER['PHP_SELF'];?></title>
    <?php include('styles.inc');?>

   <?php include('api.inc'); ?>
   <?php include('scripts.inc');?>

    <?php include ('header.inc');?>

    <?php include  ('./content/'.$page);?>

<?php include ('footer.inc');?>

This way when I want to call up a page I go to www.domain.com/content.php?p=pagename.php and it will "wrap" everything in the correct style sheets container and footer etc.

had been working well until I started making my CRUD pages requiring that pagename use POST data.

Is there a better approach for this or do I need to scrap this approach entirely?