texts: Checking membership of object in set without pattern matching

texts:
I'm curious in how to best structure code that checks for membership of an instance of an ADT in a set of elements without using pattern matching.

Given the following ADT, methods and functions, which would be seen as the idiomatic way to check for membership in Scala?

sealed trait Code {
  def isEven: Boolean
  def isOdd: Boolean
  def isOther: Boolean
}
case class Even(num: Int) extends Code {
  def isEven = true
  def isOdd = false
  def isOther = false
}
case class Odd(num: Int) extends Code {
  def isEven = false
  def isOdd = true
  def isOther = false
}

case class Other(num: Double) extends Code {
  def isEven: Boolean = false
  def isOdd: Boolean = false
  def isOther = true
}

object Code {
  val EvensBelow5: Seq[Code] = Seq(
    Even(0),
    Even(2),
    Even(4)
  )
  val EvensAbove5: Seq[Code] = Seq(
    Even(6),
    Even(8)
  )

  val OddCodes: Seq[Code] = Seq(
    Odd(1),
    Odd(3),
    Odd(5)
  )

  val OtherCode: Code = Other(1.1)

  def isEvenBelow5(code: Code) = EvensBelow5.contains(code)
  def isEvenAbove5(code: Code) = EvensAbove5.contains(code)
  def isOdd(code: Code) = OddCodes.contains(code)
  def isOther(code: Code) = OtherCode == code
  def isOf(code: Code, codes: Seq[Code]) =
    codes.contains(code)
}

Setup

import Code._

val even: Code = Even(2)
val odd: Code = Odd(1)
val other: Code = Other(1.1)

1) Would it be using methods?

even.isOdd
odd.isEven
other.isOther

2) Would it be using membership check or equality

EvensBelow5.contains(even)
EvensAbove5.contains(even)
OddCodes.contains(odd)
other == OtherCode

3) Would it be using functions that rely on values on the companion object?

isEvenBelow5(even)
isOdd(odd)
isOther(other)

4) Would it be using functions that receive all values?

isOf(even, EvensBelow5)
isOf(even, EvensAbove5)
isOf(odd, OddCodes)
isOf(other, Seq(OtherCode))

5) Would it be another way?

Maybe something that I have not listed which is not pattern matching.

Bonus question:

Would the functions that rely on values / state on the companion object (isEvenBelow5, isEvenAbove5, isOdd, isOther) be considered purely functional?


texts: Finding large Fibonacci Number in Python

texts:
I'm doing Project Euler at 1000-digit Fibonacci number - Problem 25 which says

  The Fibonacci sequence is defined by the recurrence relation:

  Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.

  Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

  The 12th term, F12, is the first term to contain three digits.

  What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

I approached this by writing a recursive function in Python that finds the nth Fibonacci number as follows:

def Fibonacci(n):
    if n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        return (Fibonacci(n-1) + Fibonacci(n-2))

However, this function runs very, very slowly. It slows down severely as n approaches 100.

What can I do to make it faster?


texts:
Here is a code I want to simplify:

public void Method1(Context context, EventLog log = null)
{
    Class myClass = ConvertToMyClass();
    ApiCall1 apiCall = new ApiCall1(context);
    if (log != null)
    {
        eventLog.WriteEntry("Starting");
    }

    try
    {
        apiCall.Call1(myClass, null, false);
        IsCallSuccess = true;
    }
    catch (Exception e)
    {
        if (log != null)
        {
            eventLog.WriteEntry("error");
        }

        IsCallSuccess= false;
        CallErrorMessage = e.Message;
    }
}

public void Method2(Context context, EventLog log = null)
{
    Class myClass = ConvertToMyClass();
    ApiCall2 apiCall = new ApiCall2(context);
    if (log != null)
    {
        eventLog.WriteEntry("Starting");
    }

    try
    {
        apiCall.Call1(myClass);
        NewItemID = myClass.ItemID;
        IsCallSuccess = true;
    }
    catch (Exception e)
    {
        if (log != null)
        {
            eventLog.WriteEntry("error");
        }

        IsCallSuccess= false;
        CallErrorMessage = e.Message;
    }
}

public void Method3Context context, EventLog log = null)
{
    Class myClass = ConvertToMyClass();
    ApiCall3 apiCall = new ApiCall3(context);
    if (log != null)
    {
        eventLog.WriteEntry("Starting");
    }

    try
    {
        apiCall.Call3(myClass, "param1");
        UpdatedItemID = myClass.UpdatedItemID;
        IsCallSuccess = true;
    }
    catch (Exception e)
    {
        if (log != null)
        {
            eventLog.WriteEntry("error");
        }

        IsCallSuccess= false;
        CallErrorMessage = e.Message;
    }
}

There are 3 methods. I've been thinking about how I could simplify them using delegates or lambdas and didn't find anything.

Note that ApiCall1/2/3 are all defined in a third-party library.
Your thoughts?


texts:
Min Heap Implementation

As an exercise, I wanted to implement a min heap using JavaScript.

I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.

Notes

I decided to implement the min heap using an array.

I filled the first element with a null value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it

The actual MinHeap function is effectively a factory function (and not a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure.

The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).
I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters

In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <.
I decided to write this in ES5 - I'll probably refactor this to use ES6 conventions in the future.

Questions

The questions I have are

Is the factory function approach sound?
Are there any JavaScript best practices that I've violated or ignored?
Is my implementation flawed in any way?

Implementation

var MinHeap = function() {
  var values = [null];

  function getParentIndex(childIndex) {
    return Math.floor(childIndex / 2);
  }

  function getChildIndices(parentIndex) {
    var leftChild = parentIndex * 2;

    return {
      leftChild: leftChild,
      rightChild: leftChild + 1,
    };
  }

  function swap(firstIndex, secondIndex) {
    var firstValue = values[firstIndex];

    values[firstIndex] = values[secondIndex];
    values[secondIndex] = firstValue;
  }

  function getSmallestNode(firstIndex, secondIndex) {
    var firstValue = values[firstIndex];
    var secondValue = values[secondIndex];

    if (firstValue > secondValue) {
      return {
        value: secondValue,
        index: secondIndex,
      };
    }

    return {
      value: firstValue,
      index: firstIndex,
    };
  }

  function add(value) {
    var valueIndex,
        parentIndex,
        parentValue;

    values.push(value);

    valueIndex = getSize();
    parentIndex = getParentIndex(valueIndex);
    parentValue = values[parentIndex];

    while (parentValue > value && parentIndex >= 1) {
      swap(parentIndex, valueIndex);

      valueIndex = parentIndex;
      parentIndex = getParentIndex(valueIndex);
      parentValue = values[parentIndex];
    }
  }

  function remove() {
    var firstValue = values[1],
        lastValueIndex = values.length - 1,
        lastValue = values.splice(lastValueIndex, 1)[0];

    if (getSize() > 0) {
      values[1] = lastValue;
      lastValueIndex = 1;

      var childIndices = getChildIndices(lastValueIndex);
      var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

      while (lastValue > smallestNode.value) {
        swap(lastValueIndex, smallestNode.index);
        lastValueIndex = smallestNode.index;

        var childIndices = getChildIndices(lastValueIndex);
        smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
      }
    }

    return firstValue;
  }

  function getFirst() {
    return values[1];
  }

  function getSize() {
    return values.length - 1;
  }

  return {
    add: add,
    remove: remove,
    getFirst: getFirst,
    getSize: getSize,
  };
};


texts: Rooms and trapdoors - for-loop and while-loop efficiency

texts:
I'd like to know if I can make this code more efficient in terms of line saving, or any other way:

def missingDoor(trapdoor,roomwidth,roomheight,step):
    safezone = []
    hazardflr = givenSteps(roomwidth,step,True)
    safetiles = []

    for i,m in enumerate(hazardflr):
        safetiles.append((m,step))
        while i < len(safetiles):
            nextSafe = safetiles[i]
            ns0 = nextSafe[0]
            if knownSafe(roomwidth, roomheight, ns0, nextSafe[1]):
                if trapdoor[ns0/roomwidth][ns0 % roomwidth] is "0":
                    if ns0 not in safezone:
                        safezone.append(ns0)
                    for e in givenSteps(roomwidth,ns0,True):
                        if knownSafe(roomwidth, roomheight, e, ns0):
                            if trapdoor[e/roomwidth][e%roomwidth] is "0" and (e, ns0) not in safetiles:
                                safetiles.append((e, ns0))
            i += 1
    return sorted(safezone)

a community member suggest to fix the this code like this:

def missingDoor(trapdoor, roomwidth, roomheight, step):
    safezone, safetiles = [], []
    check = lambda a, b, c, l: knownSafe(roomwidth, roomheight, a, b) and       trapdoor[a/roomwidth][a%roomwidth] == '0' and c not in l

    for i, m in enumerate(givenSteps(roomwidth, step, True)):
        safetiles.append((m, step))
        for _ in range(i, len(safetiles)):
            nextSafe = safetiles[i]
            ns0 = nextSafe[0]

            if check(ns0, nextSafe[1], ns0, safezone):
                safezone.append(ns0)
                safetiles.extend([ (e, ns0) for e in givenSteps(roomwidth,ns0,True) if     check(e, ns0, (e, ns0), safetiles) ])
    return sorted(safezone)

the only issue I had with this though is when I run the code it now runs into this:

TypeError: givenSteps() takes exactly 4 arguments (3 given)

How can I make this code more efficient?  I initially started to use while loops and found that for loops are better when given a known list.  I've been trying all sorts of things, given that I am new to programming.


texts: Dijkstra's algorithm using a dictionary for the priority queue

texts:
Unrelated to code:

This is my first project in Python using classes and algorithms.
I have spent the last week self teaching myself about queues and stacks, so I am NOT trying to use any Python libraries for this as I would like to know how to implement my own priority queue

About the code:

Dictionary used for priority queue.
Priority queue should be its own class, but I dont know how to call a method from one class to another, I did research this and came across staticmethod but was unsure of its implementation.
This was all done on one single file.

What I would like from this:

A way to get the input for graph without having it already 'created'
when code is run. I had an idea to get user input for each node and
its arc length to every other node, but this is inefficient for
larger graphs.
General advice/feedback/issues with my code/logic

class Graph:

    def __init__(self):
        self.nodes = {}

    def add_node(self, key, neighbours):
        self.nodes[key] = neighbours

    def shortest_path(self, start, finish):
        distance = {}  # stores distance to start node of a vertex
        visited = {}  # stores previously visited node
        queue = {}  # PQ that gives the shortest value from start to a vertex

        for node in self.nodes:
            if node == start:
                distance[node] = 0  # as distance from start node is 0
                queue[node] = 0  # value of root node to root node is 0

            else:
                distance[node] = 1000  # set unvisited nodes arc length to large value
                queue[node] = 1000

        while len(queue) != 0:
            if start == finish:
                print("start node and end node are same so distance is 0")
                break

            # works out arc with lowest weight
            lowest = 1000
            lowest_key = None
            for key in queue:
                if queue[key] < lowest:
                    lowest = queue[key]
                    lowest_key = key
            del queue[lowest_key]

            if distance[lowest_key] == 1000:
                print("No traversable paths left")
                break

            elif lowest_key == finish:
                shortest_path = []
            while True:
                temp_val = visited[lowest_key]
                shortest_path.append(temp_val)
                lowest_key = visited[lowest_key]
                if lowest_key == start:
                     break
            print(shortest_path)

            else:
                for neighbour in self.nodes[lowest_key].keys():  # checks neighbours of node released from pq
                    # adds value of neighbour arc to distance of previous node
                    alt_path = distance[lowest_key] + self.nodes[lowest_key][neighbour]
                    # if new path is shorter than distance of node in pq , then pq should be updated
                    if alt_path < distance[neighbour]:
                        distance[neighbour] = alt_path  # changes distance
                        visited[neighbour] = lowest_key  # adds this node to visited dict
                        # now changes are made to pq
                        for node in queue.keys():
                            if node == neighbour:
                                queue[node] = alt_path

g = Graph()
g.add_node('A', {'B': 5, 'C': 1})
g.add_node('B', {'D': 2, 'A': 5})
g.add_node('C', {'D': 9, 'A': 1})
g.add_node('D',{'B': 2, 'C': 9})
g.shortest_path("A",'D')


texts:
This is my solution for the MaxProductOfThree from codility, it scores 100%, but I'm not a fan of the if if if structure it has going on.

  Task description

  A non-empty array A consisting of N integers is given. The product of
  triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).

  For example, array A such that:

  A[0] = -3   A[1] = 1   A[2] = 2   A[3] = -2   A[4] = 5   A[5] = 6
  contains the following example triplets:

  (0, 1, 2), product is −3 * 1 * 2 = −6 (1, 2, 4), product is 1 * 2 * 5 = 10 (2, 4, 5), product is 2 * 5 * 6 = 60 Your goal is to find the maximal product of any triplet.

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given a non-empty array A, returns the value of the maximal
  product of any triplet.

  For example, given array A such that:

  A[0] = -3   A[1] = 1   A[2] = 2   A[3] = -2   A[4] = 5   A[5] = 6
  the function should return 60, as the product of triplet (2, 4, 5) is
  maximal.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [3..100,000]; each element of array A
  is an integer within the range [−1,000..1,000].

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

class Solution {
    public int solution(int[] A)
    {
        List<int> B = A.ToList();
        int product = 1;
        int min1 = B.Min();
        if (A.Length > 3)
        {
            if (min1 < 0)
            {
                B.RemoveAt(B.IndexOf(min1));
                int min2 = B.Min();
                if (min2 < 0)
                {
                    int max1 = B.Max();
                    if (A.Length == 4)
                    {
                        product = min1 * min2 * max1;
                    }
                    else
                    {
                        product = Math.Max(min1 * min2 * max1, getProductOfMaximalsForMoreThanTwoElements(B));
                    }
                }
                else
                {
                    product = getProductOfMaximalsForMoreThanTwoElements(B);
                }
            }
            else
            {
                product = getProductOfMaximalsForMoreThanTwoElements(B);
            }
        }
        else
        {
            foreach (int element in B)
            {
                product *= element;
            }
        }
        return product;
    }

    private int getProductOfMaximalsForMoreThanTwoElements( List<int> B)
    {
        int max1 = B.Max();
        B.RemoveAt(B.IndexOf(max1));
        int max2 = B.Max();
        B.RemoveAt(B.IndexOf(max2));
        int max3 = B.Max();
        return max1 * max2 * max3;
    }
}

To be honest, the original idea was thought beforehand, but it took me a couple of tries until every test was passed, as with most of these exercises. Are there things to improve in terms of readability, logic and quality of this code?


texts:
I am trying to figure out a way to make finding duplicates in Java more efficient. I started off with this:

private boolean hasDuplicates(int[] array) {
    List<Integer> list = new ArrayList<Integer>(array.length);
    for(int num : array) {
        list.add(num);
    }
    for(int num : list) {
        if(list.indexOf(num) != list.lastIndexOf(num)) {
            return true;
        }
    }
    return false;
}

But the main problem here is it only can be used if you were to find duplicate numbers. So I made it generic:

private <E> boolean hasDuplicates(E[] array) {
    List<E> list = new ArrayList<E>(array.length);
    for(E e : array) {
        list.add(e);
    }
    for(E e : list) {
        if(list.indexOf(e) != list.lastIndexOf(e)) {
            return true;
        }
    }
    return false;
}

This is what I currently have, but it seems very inefficient, so I tried this:

private static <E> boolean hasDuplicates(E[] array) {
    Arrays.sort(array);
    int length = array.length - 1;
    for(int i = 0; i < length; i++) {
        if(array[i].equals(array[i + 1])) {
            return true;
        }
    }
    return false;
}

But that would throw a ClassCastException if it cannot be cast to java.lang.Comparable during Arrays.sort(). Which returns to the old, inefficient method.

Is there a better solution than this? If so, how?


texts:
I was bored and sketched out this idea in pseudocode( I will try to turn it into C++ later) for taking a set of numeric data and manipulating it. I ran through it manually and it seems to put the data in a range [0, something]

count =
data[count] = { d_0, d_1, … , d_(count -1) }
sigma = $Σ_{a∈ℕ} data_a$
avg = sum / count

newData[count] = {}

for x in data
  append (x · avg)/count to newData

What I am curious about, is if this "doodle" has any potential uses, or if it can be extended somehow?


texts: Implementing a queue in Java for a technical interview

texts:
This code is based off the Queue implementation in Chapter 3 of Cracking The Coding Interview. I modified the code to make it compile and give me the correct output. I'd appreciate any feedback on code style and correctness, assuming that I write this code in a technical interview.

public class Queue {
    Node first;
    Node last;

    public Queue(Node f, Node l) {
        first = f;
        last = l;
        first.next = last;
    }

    public void enqueue(int data) {
        if( first == null ) {
            last = new Node(data);
            first = last;
        } else {
            last.next = new Node(data);
            last = last.next;
        }
    }

    public int dequeue() {
        if (first != null) {
            int item = first.data;
            first = first.next;
            return item;
        }
        else {
            return -1;
        }
    }

    public static void main(String[] args) {
        Queue queue = new Queue(new Node(2), new Node(3));
        queue.enqueue(4);
        queue.enqueue(5);

        System.out.println(queue.dequeue() == 2);
        System.out.println(queue.dequeue() == 3);
    }

    public static class Node {
        int data;
        Node next;

        public Node(int d) {
            data = d;
        }
    }
}


texts:
I don't want to extend the functionality of this method to include say library objects.  I'm just looking for feedback on what it currently does.

ES5, section 8.6.2 "exposes" these global objects.  I added a few Browser or "Host" objects which I needed for my purposes.

If needed I can add some more Browser or Host objects but no library objects as there is too much variety here. (i.e. jQuery, Backbone, etc.).

/*log
**  dependencies - none
**  browser - N/A
**
*/
$A.error = $A.report = $A.log = function (obj, note) {
    var logger,
        temp,
        type,
        ES5a = ['Arguments', 'Array', 'Object'],
        ES5b = ['Boolean', 'Date', 'Error', 'Function', 'JSON', 'Math',
            'Number', 'Null', 'RegExp', 'String', 'Undefined'],
        kindex,
        length;
    note = note || '';
    if (window.console) {
        logger = window.console.log.bind(window.console);
    } else {
        return;
    }
    type = Object.prototype.toString.call(obj).slice(8, -1);
    if (!type) {
        logger("Object type not found: ");
        logger(obj);
        return;
    }

    // Language Objects

    for (kindex in ES5a) {
        if (type === ES5a[kindex]) {
            try {
                temp = JSON.stringify(obj, null, 1);
            } catch (error) {
                temp = false;
            }
            if (temp) {
                logger("LOG|" + ES5a[kindex] + ">" + note + ">" + temp);
            } else {
                logger("LOG|" + ES5a[kindex] + ">" + note + ">");
                logger(obj);
            }
            return;
        }
    }
    for (kindex in ES5b) {
        if (type === ES5b[kindex]) {
            logger("LOG|" + ES5b[kindex] + ">" + note + ">" + obj);
            return;
        }
    }

    // Host Objects

    if (type === 'Event') {
        logger("LOG|B|Event>" + note + ">");
        if (obj.type) {
            logger("LOG|Event.type>> " + obj.type);
        }
        temp = obj.target || obj.srcElement;
        if (temp && temp.id) {
            logger("LOG|Event.target.id>> " + temp.id);
        }
        return;
    }
    if (type === 'HTMLDivElement') {
        logger("LOG|B|Div>" + note + ">");
        if (obj.id) {
            logger("LOG|Div.id>> " + obj.id);
        }
        return;
    }
    if (type === 'Storage') {
        for (kindex in obj) {
            if (obj.hasOwnProperty(kindex)) {
                logger("LOG|Storage>" + note + ">" + kindex + " | " + obj[kindex]);
            }
        }
        return;
    }
    if (type === 'HTMLCollection') {
        for (kindex = 0, length = obj.length; kindex < length; kindex++) {
            logger("LOG|HTMLCollection>" + note + ">" + kindex + " | " + obj[kindex]);
        }
        return;
    }

    // Library Objects

    if (win.jQuery && (obj instanceof win.jQuery)) {
        logger('LOG|jQuery object>');
        return;
    }

    // Not Found

    logger("LOG|B|NotFound>" + note + "> obj: " + obj + " | str: " + type);
};


texts:
I would like to get images from other websites.

This is my current method but I'm not sure if it is alright.

<?php
  header('Content-Type: '.image_type_to_mime_type(exif_imagetype($_GET['url'])));
  echo(file_get_contents($_GET['url']));
?>

If not, how should I do it?


texts: Potential Security Threats With Custom Login

texts:
I'm looking to find what security flaws this code might have. I believe it's immune to time attacks, passwords are stored encrypted, and I'm using sessions to store local data.

Let's assume the following:

All traffic is over SSL
Users have to re-authenticate after 30 minutes of inactivity

Login page:

{% block body %}

CMS index

   <form id="login" action="/login" method="post">
      <input type="text" name="username" placeholder="Username">
      <input type="password" name="password" placeholder="Password">

      <input type="submit" class="success button" value="Submit">
   </form>

   <form id="createUser" action="/createUser" method="post">
      <input type="text" name="username" placeholder="Username">
      <input type="password" name="password" placeholder="Password">
      <input type="password" name="vPass" placeholder="Verify Password">

      <input type="submit" class="success button" value="Submit">
   </form>

{% endblock %}

Flask app:

@app.route('/cms/')
def cmsHome():
    return render_template('cmsIndex.html')

@app.route('/login', methods = ['POST', 'GET'])
def cmsLogin():
    result = request.form

    user = User()
    sessionId = user.loginUser(result['username'], result['password'])

    if sessionId != False:
        session['id'] = sessionId
        return redirect(url_for('cmsEvents'))
    else:
        return redirect(url_for('cmsHome'))

@app.route('/createUser/', methods = ['POST', 'GET'])
def createUser():
    result = request.form

    user = User()
    check = user.createUser(result['username'], result['password'], result['vPass'])

    if check == True:
        flash('Account created')
    elif check == False:
        flash("Your username/password is too short (3/8) or passwords don't match")

    return redirect(url_for('cmsHome'))

@app.route('/cmsevents/')
@app.route('/cmsevents/<page>')
def cmsEvents(page = 1):
    return "Made it"

Class:

import time, json, requests, pymysql, string, random
from passlib.hash import bcrypt

class User:
    def __init__(self):
        pass

    def createUser(self, username, password, vPass):
        dbm = Database()

        if len(username) < 3:
            return False

        if len(password) < 8:
            return False

        if password != vPass:
            return False

        password = bcrypt.hash(password)

        with dbm.con:
            dbm.cur.execute("INSERT INTO admin.users (username, password) VALUES (%s, %s)", (username, password))

        return True

    def loginUser(self, username, password):
        dbm = Database()

        with dbm.con:
            dbm.cur.execute("SELECT id FROM admin.users WHERE username = %s", (username, ))

            if dbm.cur.rowcount == 1:
                dbm.cur.execute("SELECT password FROM admin.users WHERE username = %s", (username, ))
                fetch = dbm.cur.fetchone()
                check = bcrypt.verify(password, fetch[0])

                if check == True:
                    sessionId = bcrypt.hash(username + ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(40)))
                    dbm.cur.execute("UPDATE admin.users SET session = %s WHERE username = %s", (sessionId, username))
                    return sessionId
                else:
                    return False
            else:
                return False

    def verifyUser(self, sessionId):
        dbm = Database()

        with dbm.con:
            dbm.cur.execute("SELECT id FROM admin.users WHERE session = %s", (sessionId, ))
            if dbm.cur.rowcount == 1:
                return True
            else:
                return False

I realize this code could use some touching up (properly redirect when there's no session, manage users by id instead of username, etc), but I want to know about any security issues before continuing.

I know about Flask-Login, please don't recommend it. I'm doing this by hand for the learning experience.


texts: Determine if the student has passing grades

texts:
I made a program in Java that asks for the student's name, course, and grades. After the required text inputs are filled, the program will then show the result. If the student passed, the program will show "PASSED"; if the student is failing, the program will show "ACADEMIC WARNING"; if the student failed, the program will show "FAILED".
So this is the code:
/*
 * Java Grades by fosionef
 */

import javax.swing.JOptionPane;
import java.util.Scanner;

public class JavaGrades {
    public static void main(String[] args) {
        getStudentName();
        getStudentCourse();
        getGrades();
    }

    // get student name
    public static void getStudentName() {
        Scanner input = new Scanner(System.in);
        String name = JOptionPane.showInputDialog(null,"Input Name: ");
        //String name = input.nextLine();
        JOptionPane.showMessageDialog(null,"Name: " + name.toUpperCase());
    }

    // get student course
    public static void getStudentCourse() {
        Scanner input = new Scanner(System.in);
        String course = JOptionPane.showInputDialog(null,"Input Course: ");
        //String course = input.nextLine();
        JOptionPane.showMessageDialog(null,"Course: " + course.toUpperCase());
    }

    // get student grades
    public static void getGrades() {
        Scanner input = new Scanner(System.in);
        double grades = Double.parseDouble(JOptionPane.showInputDialog(null,"Input grades: "));
        //double grades = input.nextDouble();

        if(grades == 90 || grades >= 80) {
            JOptionPane.showMessageDialog(null,grades + ": PASSED!");
        }else if(grades == 79 || grades >= 75) {
            JOptionPane.showMessageDialog(null, grades + ": ACADEMIC WARNING!");
        }else if(grades <= 74) {
            JOptionPane.showMessageDialog(null,grades + ": FAILED!");
        }else{
            JOptionPane.showMessageDialog(null, "Please input the required");
        }
    }
}

How was the code? I am looking forward to corrections and suggestions. That way I can improve my coding skills. Thank you.


texts: Check if 2 arrays have (exactly) the same elements recursively

texts:
I've been given a homework assignment to make a function to check whether 2 given arrays with the same given size have exactly the same set of elements.

My function seems to be working but I feel like I don't use the principles of recursion properly in my function.

I'm not allowed to use dictionary like data structures or sorts of all kinds.

Could you think of a simpler recursive approach to this problem?

bool sameElements(int Arr1[], int Arr2[], int size) {

    bool found; // flag to indicate whether element from Arr1 has been found in Arr2

    found = false;

    //base case
    if (size == 1) {

        if (Arr1[0] == Arr2[0])
            return true;
        else
            return false;
    }//if
    else { //size != 1
        int i; //index for loop

        for (i = size - 1; i >= 0 && !found ; i--) {

            if (Arr2[i] == Arr1[size-1]) { // check existence of element in Arr1
                swapInArray(Arr2, i, (size - 1)); // swap elements
                found = true;

            }//if

        }//for

        if (found)
            sameElements(Arr1, Arr2, size - 1); // send to recursion with size-1
        else
            return false;

    }//else
}//sameElements

void swapInArray(int arr[], int i, int j) {
    int temp; // temp value to hold arr[i]
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
 }//swapInArray


texts:
In a large project of mine, I've run into a situation where a client might need to run evaluated JavaScript code. I know, it makes me cringe too. One option is to manually parse it, but for future flexibility, I would like to evaluate the code safely.

Everything I've seen and researched says, NO. Ah, the nay-sayers.

This is my attempt to sandbox the eval:

jsFiddle

Can you shoot holes in it and try and break it? I should wrap it in a try so it doesn't throw ugly errors, but beyond that, tell me where I have gone awry.

/***************************************
 * Senica Gonzalez (senica@gmail.com)
 * This is an attempt to sandbox an eval
 * in javascript using an iframe.
 * Test it and let me know if you
 * can break it.
 ***************************************/

window.addEventListener("message", function(event){
    $('#result').text(event.data.eval);
    console.log(event.data.scope1);
    console.log(event.data.scope2);
}, false);

test = 'do I exist in the window?';

var input = $('[name=toeval]');
input.on('change', function(){
    var val = $(this).val();
    var code = btoa('<html>\
        <head><\/head>\
        <body>\
            <' + 'script>\
                var party_size = 10;\
                window.parent.postMessage({\
                    eval: eval('+val+'),\
                }, "*");\
            <\/script' + '>\
        <\/body>\
    <\/html>');
    var frame = $('<iframe sandbox="allow-scripts" src="data:text/html;base64,'+code+'"></iframe>');
    var sandbox = $('#sandbox');
    sandbox.html(frame);
});

I have been unsuccessful at accessing the parent document variables, or being able to do anything obnoxious other than to my self within the sandbox.


texts: Bundling JavaScript resources for an MVC app

texts:
This is my first MVC app. I'm looking for best practice feedback on how to best bundle the files that I need, the order to bundle them, the placement of the @render methods within the containing html page.

BundleConfig

namespace StateAssessment
{
    using System.Web.Optimization;

    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/jquery-ui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                    "~/Scripts/bootstrap.js",
                    "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                    "~/Content/bootstrap.css",
                    "~/Content/site.css"));

            // Set EnableOptimizations to false for debugging. For more information,
            // visit http://go.microsoft.com/fwlink/?LinkId=301862
            #if DEBUG
                BundleTable.EnableOptimizations = false;
            #else
                BundleTable.EnableOptimizations = true;
            #endif
        }
    }
}

_layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>State Assessment Recovery System - @ViewBag.Title</title>
    <link href="~/Content/themes/base/all.css" rel="stylesheet" />
    @Styles.Render("~/Content/css")
    @RenderSection("Styles", required: false)

    @using StateAssessment.CommonHelpers.HelperControls;

    <meta name="description" content="The description of my page" />
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jquery-ui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Index.cshtml

@model StateAssessment.ViewModels.StateAssessment.Index

@section Styles {
    <link href="@Url.Content("~/Content/ViewSpecific/StateAssessment/IndexItem.css")"  rel="stylesheet"/>
}

    <!--markup goes here -->

    @section Scripts {

         <script src="~/Scripts/ViewSpecific/StateAssessment/Index.js" type="text/javascript">
         }
        </script>
    }


texts: Program to determine ranges of char, short, int and long variables, both signed and unsigned

texts:
I wrote code to determinate ranges of char,short int and long variables,both signed and unsigned.Please help me to improve my code :) Here is the code:

#include <stdio.h>

//function declerations...
long power(int base, int power);

int main(void) {
    //From 2^(N-1) to 2^(N-1)-1 (Two's complement)
    int intmin = power(2, sizeof(int) * 8 - 1);
    int intmax = power(2, sizeof(int) * 8 - 1) - 1;
    unsigned unsignedintmax = power(2, sizeof(int) * 8) - 1;
    char minchar = -(power(2, sizeof(char) * 8 - 1));
    char maxchar = power(2, sizeof(char) * 8 - 1) - 1;
    unsigned char unsignedcharmax = power(2, sizeof(char) * 8) - 1;
    short shortmin = -(power(2, sizeof(short) * 8 - 1));
    short shortmax = power(2, sizeof(short) * 8 - 1) - 1;
    unsigned short unsignedshortmax = power(2, sizeof(short) * 8) - 1;
    long minlong = power(2, sizeof(long) * 8 - 1);
    long maxlong = power(2, sizeof(long) * 8 - 1) - 1;
    unsigned long unsignedlongmax = power(2, sizeof(long) * 8) - 1;
    minlong*=-1;
    printf("\nSigned char can be minimum: %d and maximum: %d\n", minchar, maxchar);
    printf("\nUnsigned char can be minimum: %d and maximum: %u\n", 0, unsignedcharmax);
    printf("\nSigned short can be minimum: %d and maximum: %d\n", shortmin, shortmax);
    printf("\nUnsigned short can be minimum: %d and maximum: %u\n", 0, unsignedshortmax);
    printf("\nSigned int can be minimum: %d and maximum: %d\n", intmin, intmax);
    printf("\nUnsigned int can be minimum: %d and maximum: %u\n", 0, unsignedintmax);
    printf("\nSigned long can be minimum: %ld and maximum: %ld\n", minlong, maxlong);
    printf("\nUnsigned long can be minimum: %d and maximum: %lu\n\n", 0, unsignedlongmax);

    return 0;
}

long power(int base, int power) {
    long pf = 1;
    for (int i = 0; i < power; i++) {
        pf *= base;
    }
    return pf;
}


texts:
Looking over Rock, Paper, Scissors. C++ from a beginning programmer prompted me to think about how I'd program this simple game in C++.  The RockPaperScissors class contains the essential features of printing and evaluating each round of the game, as well as generation of randomly selected moves.  I didn't encode a player input because that didn't seem too interesting; instead the sample program just plays 20 rounds against itself and prints the result of each.  No statistics are gathered or stored.

One feature that does exist is that there is a #define to select whether the classic game or the enhanced "Rock-Paper-Scissors-Lizard-Spock" version is used.  (With a bit more work, which I chose not to invest, one could allow for a fairly generic \$n\$-ary relation as the basis of the game.)  The other feature worth noting is that the operator< is deliberately private because the \$<\$ operation implemented here does not represent a partially ordered set because the operation is not transitive.  In simple terms, we would normally expect that \$(a < b) \land (b < c) \implies (a < c)\$ but this is expressly not true here.

I'd be interested in comments on those or any other design decisions or implementation details.

#include <iostream>
#include <string_view>
#include <array>
#include <stdexcept>
#include <random>

// define ENHANCED to non-zero for enhanced version with Spock, Lizard
#ifndef ENHANCED
#define ENHANCED 0
#endif

class RockPaperScissors
{
public:
    RockPaperScissors(std::size_t num) {
        if (num >= words.size()) {
            throw std::range_error("invalid choice");
        }
        choice = num;
    }
    static RockPaperScissors random();
    const std::string_view& vs(const RockPaperScissors &b) const;
    friend std::ostream& operator<<(std::ostream& out, const RockPaperScissors &rps);
private:
    bool operator==(const RockPaperScissors &b) const;
    bool operator<(const RockPaperScissors &b) const;
#if ENHANCED
    static constexpr std::array<std::string_view, 5> words{ "Rock", "Paper", "Scissors", "Spock", "Lizard", };
#else
    static constexpr std::array<std::string_view, 3> words{ "Rock", "Paper", "Scissors" };
#endif
    static constexpr std::array<std::string_view, 3> results{"LOSE", "TIE", "WIN" };
    std::size_t choice;
};

std::ostream& operator<<(std::ostream& out, const RockPaperScissors &rps) {
    return out << rps.words[rps.choice];
}

RockPaperScissors RockPaperScissors::random() {
    static std::random_device rd;
    static std::mt19937 gen{rd()};
    static std::uniform_int_distribution<> dis(0, RockPaperScissors::words.size()-1);
    std::size_t which{static_cast<std::size_t>(dis(gen))};
    return RockPaperScissors{which};
}

bool RockPaperScissors::operator==(const RockPaperScissors &b) const {
    return choice == b.choice;
}

bool RockPaperScissors::operator<(const RockPaperScissors &b) const {
    return (choice + 1) % words.size() == b.choice || (choice + 3) % words.size() == b.choice;
}

const std::string_view& RockPaperScissors::vs(const RockPaperScissors &b) const {
    if (*this == b) {
        return results[1];
    } else if (*this < b) {
        return results[0];
    }
    return results[2];
}

int main()
{
    for (int trials = 20; trials; --trials) {
        auto a = RockPaperScissors::random();
        auto b = RockPaperScissors::random();
        std::cout << a << " vs. " << b << ": " << a << " " << a.vs(b) << "S!\n";
    }
}


texts: Rating the quality of a response based on the number of typos

texts:
I have this method which returns the number, but Rubocop said:

  Assignment Branch Condition size for rating is too high. [15.84/15]

  def rating
    response = response_quality

    if response == 1 && @typos.zero?
      5
    elsif response == 2 && @typos.zero?
      4
    elsif response == 3 && @typos.zero?
      3
    elsif @typos.percent_of(@word_length) < 20
      2
    elsif @typos.percent_of(@word_length) < 30
      1
    elsif @typos.percent_of(@word_length) > 30
      0
    end
  end

What can I change?


texts: Ultimate functor class which can read/write to l-values/r-values

texts:
The aim is to provide a generic functor class which makes references able to bind to r-values. The trick is to trick the compiler into thinking that the r-value is an l-value by using a forwarding references.
Here is the code:
#include <type_traits>
template <typename Functor>
struct Function {
    Functor func;
    template <typename ...Args>
    inline auto operator() (Args&&... args) {
        //I tried to provide a suitable error message if args were not valid parameters, but I can't get it to work...
        //static_assert(std::is_invocable_v<Functor, Args...>);
        return func(args...);
    }
};

Example use case:
# include <iostream>
# include <vector>
int main () {
    // Define function
    auto push_back = Function([] (std::vector<int>& vec, int num) {vec.push_back(num); return vec;});
    auto x = std::vector{1 , 2 ,3 , 4};
    // Works on l-values
    push_back(x, 5);
    std::cout << x[4] << '\n'; // 5
    // Works on r-values
    auto y = push_back(std::vector{1 ,2 , 3 , 4 , 5}, 6);
    std::cout << y[5] << '\n'; // 6
    return 0;
}

And finally, one can do this if you want to use old-style c functions:
template <typename R, typename ...Args>
inline auto CFunc(R (*iFunc) (Args...)) {
    return Function<R (*) (Args...)>(iFunc);
}

Is this robust code? Are there edge cases I need to be aware about with which my functor class does not work? Also, how could I provide more suitable error messages, eg when typename Functor is not a functor, or when args... are not suitable parameters?


texts: Async task post method WebAPI controller

texts:
I have a post method in an WebAPI2 controller. I just want to make sure that everything I have done is correct. I want to create a new task run the method asynchronously and return a message.

public async Task<IHttpActionResult> Post([FromBody]Menu m)
{
    using (MySqlConnection con = new MySqlConnection(""))
    using (MySqlCommand cmd = new MySqlCommand("Insert into Menu (Description,LanguageId,IsActive) values (@Description,@LanguageId,@IsActive) ", con))
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                await con.OpenAsync();
                cmd.Parameters.AddWithValue("@Description", m.Description);
                cmd.Parameters.AddWithValue("@LanguageId", m.LanguageId);
                cmd.Parameters.AddWithValue("@IsActive", m.IsActive);
                await cmd.ExecuteNonQueryAsync();
            }
        }
        catch (MySqlException ex)
        {
            return Content(HttpStatusCode.NotFound,ex);
        }
        finally
        {
           await  con.CloseAsync();
        }
        return Ok("Inserted Succesfully");
    }
}

Should I create a new async method to execute the query and then return the message into the post method of the controller, or is this the correct way?


texts: Object for generating HTML for hyperlinks

texts:
I have a function that generates HTML for hyperlinks. It's arguments may be string literals or variables read from the database. An example call to this function looks like:

hLink('http://example.com', 'website', 'section', 'input=0', '_blank');

which returns:

'website'

The first argument is required, and the remaining four have defaults.

In my first foray into object-oriented programming, I've written a replacement for this function by a method defined in a class, so the function calls are replaced with calls to that method acting on an object from that class. I've written two versions:

In the first version, each link works by creating a new instance of the class, with the required arguments of hLink() handled by the class constructor, and optional arguments handled by setting properties of the object, and then an output method hLink() finally acting on those properties to generate the HTML link. If you want to see the code for this version, it's in the edit history of this question, but I've removed it in favor of the second version, which I think is probably better.
In the second version, the class has no constructor. One instance of the class is created and all links are generated by this one object. The class has a method clear() that resets all the properties to empty, as well as additional methods to set the values of any properties that are needed, and finally an output method hLink() to generate the HTML link.

I wrote the second version because it seemed that the first was wasteful by creating an object for each link, and those objects were never used again after generating the HTML. So the second version reuses the same object repeatedly for this task.

The code for the second version is as follows: (Pardon my formatting. I know it's unconventional, but I find this easier to read.)

<?php declare(strict_types = 1);
$oLink = new link;
class link
    {private $sURL;
     private $sText;
     private $sAnchor;
     private $sQuery;
     private $sWindow;
     public function clear()
        {$this->sURL    = '';
         $this->sText   = '';
         $this->sAnchor = '';
         $this->sQuery  = '';
         $this->sWindow = '';
         return $this;
         }
     public function URL(string $sURL)       {$this->sURL    = $sURL;    return $this;}
     public function text(string $sText)     {$this->sText   = $sText;   return $this;}
     public function anchor(string $sAnchor) {$this->sAnchor = $sAnchor; return $this;}
     public function query(string $sQuery)   {$this->sQuery  = $sQuery;  return $this;}
     public function window(string $sWindow) {$this->sWindow = $sWindow; return $this;}
     public function hLink()
        {return('sURL .
                              ($this->sQuery  == '' ? '' : '?' . $this->sQuery) .
                              ($this->sAnchor == '' ? '' : '#' . $this->sAnchor) .
                        '"' . ($this->sWindow == '' ? '' : ' target="' . $this->sWindow . '"') .
                 '>' . $this->sText . '');
         }
     }
echo('
Link to ' . $oLink->clear()->URL('http://example.com')->text('website')->anchor('section')->query('input=0')->window('_blank')->hLink() . ' in text
');

I've tested the above code as a freestanding script, and it does output the intended:

Link to website in text

I'd like to know if I'm doing this right, or even if I should be doing this at all (i.e., if this is a sensible use of objects). Is this the best way to generate HTML for hyperlinks embedded in text in PHP?


texts: Go API server - request handlers becoming excessively long

texts:
I'm developing a API server in Go. My route handlers are becoming excessively long, especially when the response needs a lot of information.

For the following response type:

// StateResponse is queried by the client to get the entire initial
// database state.
type StateResponse struct {
    StatusCode  int                `json:"status"`
    User        store.User         `json:"user"`
    Enrolled    []store.Enrol      `json:"enrolled"`
    Assessment  []store.Assessment `json:"assessment"`
    Submissions []store.Submission `json:"submissions"`
}

I have this handler:

func stateHandler(store *store.Store) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if !request.IsAuthorized(r) {
            log.Println("Unauthorized")
            unauthorizedHandler().ServeHTTP(w, r)
            return
        }
        if r.Method != http.MethodGet {
            notFoundHandler().ServeHTTP(w, r)
            return
        }
        urlParams, ok := r.URL.Query()["email"]
        if !ok || len(urlParams) != 1 {
            log.Println("Invalid email")
            badRequestHandler("invalid email").ServeHTTP(w, r)
            return
        }
        email := urlParams[0]
        user, err := store.GetUserByEmail(email)
        if user == nil || err != nil {
            log.Printf("Could not find user: %v", err)
            notFoundHandler().ServeHTTP(w, r)
            return
        }
        enrolled, err := store.GetEnrolByUser(user.UID)
        if enrolled == nil || err != nil {
            log.Printf("Could not find enrolled: %v", err)
            notFoundHandler().ServeHTTP(w, r)
            return
        }
        assessments, err := store.GetAssessmentForUser(user.UID)
        if assessments == nil || err != nil {
            log.Printf("Could not find assessment: %v", err)
            notFoundHandler().ServeHTTP(w, r)
            return
        }
        submissions, err := store.GetSubmissionsForUser(user.UID)
        if submissions == nil || err != nil {
            log.Printf("Could not find submissions: %v", err)
            notFoundHandler().ServeHTTP(w, r)
            return
        }
        // Send response
        resp := StateResponse{
            StatusCode:  200,
            User:        *user,
            Enrolled:    enrolled,
            Assessment:  assessments,
            Submissions: submissions,
        }
        respBytes, err := json.Marshal(resp)
        if err != nil {
            unauthorizedHandler().ServeHTTP(w, r)
            return
        }
        w.Write(respBytes)
    })
}

I know this is imperfect. The error handling is repetitive. I tried using the errWriter technique from Rob Pikes "errors as values" article, but I couldn't make it work since every database query (store functions, in this case) are slightly different.


texts: Rehashing a hash table in c++ with quadratic probing

texts:
The code below is my attempt at trying to create a hash table. I'm currently stuck with the rehash function as I think it's not efficient enough (I believe it's O(n^2). I'd be grateful if someone could give some comments and suggestions on how I could improve my rehash function.

class Hashtable{
private:
    int sze; //size: number of values are currently in the hashtable
    int cap; //capacity: the size of the hashtable

    struct HashNode{
        string value;
    };

    HashNode** arr;  //bucket

    //determine whether the number is prime or not
    bool IsPrime(int number){
        if (number == 2 || number == 3)
            return true;

        if (number % 2 == 0 || number % 3 == 0)
            return false;

        int divisor = 6;
        while (divisor * divisor - 2 * divisor + 1 <= number)
        {

            if (number % (divisor - 1) == 0)
                return false;

            if (number % (divisor + 1) == 0)
                return false;

            divisor += 6;

        }

        return true;

    }

    //find the next prime number that is >= a
    int NextPrime(int a){
        while (!IsPrime(++a)){ }
        return a;
    }

    int hashing(const string &s) const{
        int h = 0;
        for (int i = 0; i < s.size(); i++)
        {
            h += int(s[i]);
        }

        return h;
    }

    void rehashing ()
    {
        int oldCap = cap;
        sze = 0;
        //Doubling the capacity
        cap = NextPrime(cap*2);

        HashNode** oldArr = arr;
        arr = new HashNode*[cap]();

        //moving the values to the new after rehashing
        for (int i = 0; i < oldCap; i++){
            if (oldArr[i] != nullptr){
                for (int j = 0; j < cap; j++){
                    int index = (hashing(oldArr[i]->value) + j*j) % cap;
                    if (arr[index] == nullptr){
                        arr[index] = new HashNode {oldArr[i]->value};
                        sze++;
                        break;
                    } //if
                } //for
                delete oldArr[i];
                oldArr[i] = nullptr;
            } //if
        } //for

        delete[] oldArr;
    }

public:
    // Constructor
    Hashtable(int ini_cap = 101) : sze(0), cap(ini_cap), arr(new HashNode*[cap]){
        for (int i = 0; i < cap; i++)
        {
            arr[i] = nullptr;
        }

    }

    //Destructor
    ~Hashtable(){
        for (int i = 0; i < cap; i++){
            if (arr[i] != nullptr){
                delete arr[i];
                arr[i] = nullptr;
            }
        }
        delete[] arr;
    }

    double load_factor() const {return double(sze)/cap;}

    void put(const string& s){
        //Initialize a new node for the new input
        HashNode* temp = new HashNode{s};

        //Insert using quadratic probing
        for (int i = 0; i < cap; i++){
            int index = (hashing(s) + i*i) % cap;
            if (arr[index] == nullptr){
                arr[index] = temp;
                sze++;
                break;
            }
        }

        if (load_factor() > 0.5){
            rehashing();
        } //if

    } //add
 };

Ideally, I think i'd be the best If I could make it O(n). So if anyone have any idea on how I could do that please tell me. Thank you.


texts: Anything wrong with my typical module pattern?

texts:
The javascript I typically need to write seems to be a good fit for the module pattern, e.g., repeatable widgets such as photo galleries, forms, etc. that have their own internal states, but may need to be accessible or editable by other parts of the website.

The particular flavor of the module pattern I've been using I inherited from a senior dev, but with that person out of the picture I'm taking a look at how I write my code so I can really understand it and ensure it's optimal.

I'll usually have one global object to contain my code and a selector library on hand (such as Zepto or jQuery). That global object would return specified submodules that I can call when I need them. Below is what a sample photo gallery module in the app might look like in skeleton form.

I'd love any input. I don't have a formal background in computer science or programming, particularly not OOP, so please point out any errors I've made in terminology as well.

var App = (function($) {

    "use strict";

    // images is an array of image paths
    // container is a DOM node where we append the gallery
    var Gallery = function(images, container) {

        // private variables go here

        // create a Zepto object from the DOM node that was passed in
        // it makes DOM operations easier and less verbose
        var $container = $(container);

        // these are prev/next buttons that will have event handlers on them
        var $next;
        var $prev;

        // an anonymous function expression executes initializers and event bindings
        (function() {

            // init renders the DOM we want
            init();

            // bind events on elements we just rendered
            bindEvents();

        })();

        function init() {

            // create DOM nodes from images, an array of image paths
            for (var i = 0; i < images.length; i++) {
                $container.append(render(images[i]));
            }

            // create the nav elements
            $container.append('');

            var $nav = $container.find('nav');
            $nav.append('
Next
');
            $nav.append('
Prev
');

            $next = $nav.find('.next');
            $prev = $nav.find('.prev');

        }

        function bindEvents() {

            $prev.click(function() {
                // show previous image
            });

            $next.click(function() {
                // show next image
            });

        }

        // this is a method of Gallery that would allow us to add more images to the gallery after it's already instantiated
        function addImage(path) {
            $container.append(render(path));
        }

        function render(path) {
            return '';
        }

        // return only the parts of the module we need exposed publicly
        return {
            addImage: addImage
        };

    };

    function init() {

        // an init function for the global App

    }

    // return the public properties of App
    return {
        Gallery: Gallery,
        init: init
    };

})(Zepto);

(function($) {

    App.init();

    var imagepaths = ["image1.jpg", "image2.jpg", "image3.jpg"];
    var galleryNode = document.getElementById('#gallery');

    $(document).ready(function() {
        new App.Gallery(imagepaths, galleryNode);
    });

})(Zepto);


texts: Best practices to pass pcl::PointCloud to a function

texts:
I am trying to pass a point cloud to a function. Since the point cloud data is huge, I don't want the compiler to make a copy of it while passing. Hence I passed the reference of it as shown below-

void box_filter(pcl::PointCloud<pcl::PointXYZRGB>& in_cloud, pcl::PointCloud<pcl::PointXYZRGB>& out_cloud)
{
  pcl::CropBox<pcl::PointXYZRGB> filter;
  filter.setMin(Eigen::Vector4f(x_min, y_min, z_min, 1.0));
  filter.setMax(Eigen::Vector4f(x_max, y_max, z_max, 1.0));
  filter.setInputCloud(in_cloud);
  filter.filter(out_cloud);
}

I defined the point clouds as following-

pcl::PointCloud<pcl::PointXYZRGB> raw_cloud, filterd_cloud;

Later, I am visualizing the filtered cloud using PCLVisualizer. Please see the code snippet-

pcl::PointCloud<pcl::PointXYZRGB> raw_cloud, filterd_cloud;
pcl::io::loadPCDFile(pcd_filename, raw_cloud);
box_filter(raw_cloud, filterd_cloud);
pcl::visualization::PCLVisualizer viewer("Cloud Viewer");
viewer.addPointCloud(filterd_cloud, "filterd_cloud");
viewer.spin();

Unfortunately, the code throws following compilation errors-

In function ‘void box_filter(pcl::PointCloud<pcl::PointXYZRGB>&, pcl::PointCloud<pcl::PointXYZRGB>&)’:
error: no matching function for call to ‘pcl::CropBox<pcl::PointXYZRGB>::setInputCloud(pcl::PointCloud<pcl::PointXYZRGB>&)’
   filter.setInputCloud(in_cloud);
                                ^
candidate is: void pcl::PCLBase<PointT>::setInputCloud(const PointCloudConstPtr&) [with PointT = pcl::PointXYZRGB; pcl::PCLBase<PointT>::PointCloudConstPtr = boost::shared_ptr<const pcl::PointCloud<pcl::PointXYZRGB> >]
       setInputCloud (const PointCloudConstPtr &cloud);
       ^
error: no matching function for call to ‘pcl::visualization::PCLVisualizer::addPointCloud(pcl::PointCloud<pcl::PointXYZRGB>&, const char [14])’
   viewer.addPointCloud(filterd_cloud, "filterd_cloud");
                                                      ^
candidates are: template<class PointT> bool pcl::visualization::PCLVisualizer::addPointCloud(const typename pcl::PointCloud<PointT>::ConstPtr&, const string&, int)
         addPointCloud (const typename pcl::PointCloud<PointT>::ConstPtr &cloud,
         ^

It is clear that there is a mismatch between datatype as it is expecting for pcl::PointCloud<PointT>::ConstPtr instead of pcl::PointCloud<PointT>.

I modified the code as shown below-

void box_filter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr in_cloud, pcl::PointCloud<pcl::PointXYZRGB>::Ptr out_cloud)
{
  pcl::CropBox<pcl::PointXYZRGB> filter;
  filter.setMin(Eigen::Vector4f(x_min, y_min, z_min, 1.0));
  filter.setMax(Eigen::Vector4f(x_max, y_max, z_max, 1.0));
  filter.setInputCloud(in_cloud);
  filter.filter(*out_cloud);
}

and this too-

pcl::PointCloud<pcl::PointXYZRGB>::Ptr raw_cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr filterd_cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::io::loadPCDFile(pcd_filename, *raw_cloud);
box_filter(raw_cloud, filterd_cloud);
pcl::visualization::PCLVisualizer viewer("Cloud Viewer");
viewer.addPointCloud(filterd_cloud, "filterd_cloud");
viewer.spin();

It works but Is it fine?
I am looking for best practices while dealing with pcl::PointCloud<PointT> as it is making use of Boost Pointers.


texts: Auto classification of my bank transactions

texts:
This is my first Machine Learning algorithm using Python and SkLearn. The code works, which is pretty awesome. I'm getting about 65-70% of accuracy after training it with about 4k rows of data.

Although it works, it seems like is less than optimal. I'm guessing it would be better to organize it with functions and etc - I don't know - it just seems that is more complex than it should be...

Pre processing

data = pd.read_csv('data/class_full.csv',
                    encoding='latin1',
                    error_bad_lines=False,
                    delimiter=';')

# Define column names & Change label to Pandas "Category"
data.columns  = ['desc', 'value', 'label']
data['desc'] = data['desc'].str.replace('[^\w\s]','')
data['label'] = data['label'].astype('category')

# Assign data as "string"
labels   = data['label'].values.astype(str)
feature1 = data['desc'].values.astype(str)

# Vectorizes strings with Tf-IDF Vectorizer
vectorizer = TfidfVectorizer()
vectors    = vectorizer.fit_transform(feature1)   # Train Data
vectors_   = vectorizer.transform(feature1)       # Test Data

Fitting the model

#Test
train_features, test_features, train_labels, test_labels = tts(vectors, labels, test_size=0.05)

# ExtraTree Classifier
print('\nEstimating score with ExtraTree Classifier...')
extra_model = ExtraTreesClassifier(n_estimators=100, max_depth=None, min_samples_split=10, random_state=42)
extra_model.fit(train_features, train_labels)
predictions_extra = extra_model.predict(vectors_)
print('Score: {:.2f}'.format(extra_model.score(test_features, test_labels)*100) + ' ExtraTree Classifier')

Print accuracy

# Print of all results
print('Score: {:.2f}'.format(extra_model.score(test_features, test_labels)*100)    + ' ExtraTree Classifier\n')

# Voting Classifier
eclf = VotingClassifier(estimators=[('extra', extra_model)], voting='soft')

for clf, label in zip([extra_model, eclf], ['Extra']):

     scores = cross_val_score(clf, test_features, test_labels, cv=5, scoring='accuracy')
     print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label))

Make Predictions

# Statement to be classified
statement = pd.read_csv('data/extrato.csv',
                    encoding='latin1',
                    error_bad_lines=False,
                    delimiter=',')

# Defining the column and vectorizing it
newFeatures     = statement['memo'].values.astype(str)
newVectorizer   = TfidfVectorizer()
newVector       = newVectorizer.fit_transform(newFeatures)
newVector_      = newVectorizer.transform(newFeatures)

# Predictions with Random Forest, Decision Tree & SVC models
predictions_extra = extra_model.predict(vectorizer.transform(newFeatures))
predictions_extra  = numpy.asarray(predictions_extra)
predictions_extra  = pd.DataFrame(predictions_extra)

# Finding probabilities for each of the assigned categories
extra_prob = extra_model.predict_proba(vectorizer.transform(newFeatures))
extra_prob = numpy.asarray(extra_prob)
extra_prob = pd.DataFrame(extra_prob)
extra_prob = extra_prob.max(axis=1)


texts:
Any time that a row ID (oddly placed in column 8, i.e. row[7]) is repeated after the first instance, I want to write those rows into a second file.  The code I'm using is extremely slow -- it's a 40-column CSV with about a million rows.  This is what I have:

def in_out_gorbsplit(inf, outf1, outf2):
    outf1 = csv.writer(open(outf1, 'wb'), delimiter=',', lineterminator='\n')
    outf2 = csv.writer(open(outf2, 'wb'), delimiter=',', lineterminator='\n')
    inf1 = csv.reader(open(inf, 'rbU'), delimiter=',')
    inf1.next()
    checklist = []
    for row in inf1:
        id_num = str(row[7])
        if id_num not in checklist:
            outf1.writerow(row)
            checklist.append(id_num)
        else:
            outf2.writerow(row)


texts: Grabbing hashed password from a database

texts:
I have just discovered the beauty of prepared statements in PHP and how they protect against SQL injection. In my first time using them, I am attempting to grab a hashed password from a database and seeing if it matches up against the password the user inputted into the login form.

Is this the most efficient way to:

Grab the data from the database?
Match the passwords using password_verify()?

<?php
//will correspond with 'loginLogin.html page
require("opendboLogin.php");

$user = $_POST['username']; //these are grabbed from the login form (textbox)
$password = $_POST['password'];

$stmt2 = $conn->stmt_init();
$stmt2 = $conn->prepare("SELECT apassword FROM login WHERE auser = ?");
$stmt2->bind_param("s", $user);
$stmt2->execute();
$stmt2->store_result();
$stmt2->bind_result($hashedPassword);
$stmt2->fetch();
//echo $hashedPassword; this returns hashed password string from DB
$numberofrows = $stmt2->num_rows; //this is an integer!!
$stmt2 -> close();

if($numberofrows > 0) //if username exists in database
{
    if (password_verify($password, $hashedPassword)) //if user-inputted password (from form) equals hashed password from DB...
    {
        print("Password is valid, login successful!");
        session_start();
        $_SESSION['sess_user'] = $user;
        header("location:member.php"); //redirect user to member page
    }
    else
    {
        echo 'Invalid password for the username: ' . $user; //if password didn't match DB, we tell them
    }
}
else
{
    echo 'The username, ' . $user . ', does not exist! Please try again.'; //if num_rows is 0, we know username doesnt exist
}
?>


texts:
I'm trying to calculate a problem which requires sum of digits in \$a^b\$, where \$0 \le a \le 9\$ and \$0 \le b \le 4000\$.

I have seen various other posts similar to this, but I haven't acquired best way. I have created this:

#include<stdio.h>
int main() {
    int digits[4000]={0} ;
    long long int test,a,b,temp,newVar ;
    scanf("%lld",&test) ;
    newVar=1 ;
    while(test--) {
        scanf("%lld %lld",&a,&b) ;
        if(b==0) {
            printf("Case %lld: 0\n",newVar) ;
            newVar++ ;
            continue ;
        }
        b=b-1 ;
        digits[0]=a ;
        long long int len=1,carry=0,i ;
        while(b--) {
            carry=0 ;
            for(i=0 ; i<len  ; i++) {
                temp=digits[i]*a + carry ;
                digits[i]=temp%10;
                carry=temp/10 ;
            }
            if(carry!=0) {
                digits[i]=carry ;
                len++ ;
            }
        }
        long long int sum=0 ;
        for(i=len-1 ; i>=0 ; i--)
            sum+=digits[i] ;
        printf("Case %lld: %llu\n",newVar,sum) ;
        newVar++ ;
    }
    return 0 ;
}

I tested my code for large powers, which is giving the right results.

For example:

Input:

3
2 32
3 2
2 60

Output:

Case 1: 58
Case 2: 9
Case 3: 82

Is there any way to increase the speed or running time of this code? I have a time limit of 1 sec and this code is showing Time Limit Exceeded.

This is not a contest that is going to effect my(or anyone else) ratings. For me, it's a way to learn new things. So any help will be appreciated.


texts: Assigning properties based on string parameters

texts:
I am using the below method to assign value to my object(Team.Driver/Team.Codriver). This works fine but just wanted to know if I could improve this code via LINQ or other options.

public void MoveDriverCodriver(
    Team source, string sourceType, Team target, string targetType)
{
    if (sourceType == "Driver")
    {
        if (targetType == "Driver")
        {
            target.Driver = source.Driver;
        }
        else
        {
            target.Codriver = source.Driver;
        }
    }
    else
    {
        if (targetType == "Driver")
        {
            target.Driver = source.Codriver;
        }
        else
        {
            target.Codriver = source.Codriver;
        }
    }
}

Also second part is I want to update target Driver/Codriver details with the appropriate source. But I want to retain the id's of target Driver/Codriver.

class Driver
{
  public Guid Id { get; set; }
  public string Firstname { get; set; }
  public string Lastname { get; set; }
  public int Age { get; set; }
}

class Team
{
  public Guid Id { get; set; }
  public Driver Driver { get; set; }
  public Driver Codriver { get; set; }
}

calling move operation.

Team team1 = new Team(); //Do some operation on team1
Team team2 = new Team(); //Do some operation on team2
MoveDriverCodriver(team1, "Driver", team2, "Codriver"); //Here I am trying to assign team1's driver to team2's codriver.


texts: Dynamic array resizing and nesting conditions

texts:
This function filters a 2D VBA array base on the strKeeper value. Depending on the Boolean toggle it would either retain or skip "rows."

Two questions:

I went at length to size the arr_new in a separate loop to reDim it only once (did not want to put ReDim inside the loop). Is there a better way?
Is there a more efficient way to nest the following:

If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then

Function RemoveRows2D(arr As Variant, k As Long, strKeeper As String, headers As Boolean, Optional re_Tain As Boolean = True) As Variant
'removes rows not equal (re_Tain=False) or equal (re_Tain=True) to strKeeper in col k

Dim i As Long, j As Long, ii As Long, up_new As Long
Dim arr_col_k, arr_new

arr_col_k = Application.Index(arr, 0, k) 'col with strings
up_new = 0 'calc Ubound(arr_new) based on matched
For i = LBound(arr_col_k) To UBound(arr_col_k)
    If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then
        up_new = up_new + 1
    End If
Next
If headers Then up_new = up_new + 1
ReDim arr_new(LBound(arr) To up_new, LBound(arr, 2) To UBound(arr, 2))

i = LBound(arr)
ii = i
If headers Then 'handle header row
    For j = LBound(arr, 2) To UBound(arr, 2)
          arr_new(i, j) = arr(i, j)
    Next
    i = 1 + 1
    up_new = up_new + 1
End If

For i = i To UBound(arr) 'outter loop by rows to find match

    If (arr_col_k(i, 1) = strKeeper And re_Tain) Or (arr_col_k(i, 1) <> strKeeper And Not re_Tain) Then
       ii = ii + 1
       For j = LBound(arr, 2) To UBound(arr, 2) 'inner loop by columns to fill in arr_new row
           arr_new(ii, j) = arr(i, j)
       Next
    End If
Next
RemoveRows2D = Application.Transpose(arr_new)
End Function


texts: Arduino based ultrasonic sensor program, output HIGH to control electric motor

texts:
I am brand new to C++ and am working with the Arduino micro controller. The project I've been working on for my university requires me to write code to do the following:

  If the ultrasonic sensor detects a distance within a certain range, output HIGH to activate an electric motor
  If the sensor detects distance outside this range, outputs LOW to deactivate the motor

I hope to create an array that will average the readings from the ultrasonic sensor over a .5 sec - 1 second interval and then output that average.
I started with a rangefinder script that went along with a tutorial provided on Arduino's website, so my goal is to modify that script to fit into my goals to output HIGH or LOW based on the code that I've tested and already works well to test for distance.

I am looking for any tips to create an array to average the distance from the sensor, then using a for loop to test whether it is in the interval and output HIGH or LOW.

Any help and direction would be appreciated!

const int TriggerPin = 8;  //sensor trigger pin
const int EchoPin = 9;    //sensor echo pin
const int MotorPin = 7;  //motor out pin
long Duration = 0;

void setup(){
  pinMode(TriggerPin,OUTPUT);  //sets trigger as output
  pinMode(EchoPin,INPUT);      //sets echo as input
  pinMode(MotorPin,OUTPUT);    //sets motor as output
  Serial.begin(9600);          //displays to serial monitor
}

void loop(){
 digitalWrite(TriggerPin,LOW);  //trigger pin to 0V
 delayMicroseconds(2);          //waits 2 us
 digitalWrite(TriggerPin,HIGH); //trigger pin to 5V
 delayMicroseconds(10);         //10 us delay to recieve ping
 digitalWrite(TriggerPin,LOW);

Duration = pulseIn(EchoPin,HIGH);  //waits for echo pin to get high
//pulseIn returns the Duration in microseconds
long Distance_mm = Distance(Duration);  //uses function to calc. distance

delay(100);  //delay half second, do next measurement
}

long Distance(long time);
{

long DistanceCalc;  //calculation variable
DistanceCalc = ((time /2.9) / 2);

//want to average this DistanceCalc reading over 10 readings, then use this value to    compare to the desired range

void loop(){
  if  (dist_avg < 600 && dist_avg > 400);
  digitalWrite(MotorPin,HIGH);
  else
  digitalWrite(MotorPin,LOW);
}
//if average distance is within .4-.6 meter range, output HIGH; turns motor on
//if avergae distance is outside .4-.6 meter range, outut LOW; turns motor off


texts:
This is a statement that I use a lot in my code base:

 (LocalDateTime.now()).format(DateTimeFormatter.ofPattern("ssmmHHddMMMuu"))

Should I create a static method for this or is it overkill?

public static String getTodaysDateInFormat(String format){
  return (LocalDateTime.now()).format(DateTimeFormatter.ofPattern(format));
}


texts: line_to, fill_rect, and clear_rect functions

texts:
def line_to(x: 0, y: 0, rect: nil)
  unless rect.nil?
    x, y, width, height = rect.x, rect.y, rect.width, rect.height
  end

  `#{@context}.lineTo(#{x}, #{y})`
end

def fill_rect(x: 0, y: 0, width: 0, height: 0, rect: nil)
  unless rect.nil?
    x, y, width, height = rect.x, rect.y, rect.width, rect.height
  end

  `#{@context}.fillRect(#{x}, #{y}, #{width}, #{height})`
end

def clear_rect(x: 0, y: 0, width: 0, height: 0, rect: nil)
  unless rect.nil?
    x, y, width, height = rect.x, rect.y, rect.width, rect.height
  end

  `#{@context}.clearRect(#{x}, #{y}, #{width}, #{height})`
end

I am looking for a way to refactor the above code to take out the first three lines in the methods. I don't want to use Metaprogramming in this specific case; is there any other way?

In case full code will help, see the repo.


texts: Distinguishing user input numbers and characters

texts:
I am currently taking a computer science class in high school, and it is my first time programming (2 weeks since I started). I have currently finished my program; however, there were a few details that bothered me. I was supposed to create a program which can calculate average of individual marks and then calculate all of the average marks previously entered by user.

However, I noticed something that bothered me, which was the fact that if I were to enter a number when asked to enter a name, it would assume that number is a name. Also, when I asked for the 5 marks, the program would run fine until an error occurs if I accidentally type in a letter or word. I have done some research and found system scanners; however, I still don't understand the concept in a looping situation.

import java.io.*;
public class loopingEx6Final {
    public static void main(String args[]) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double average, totalaverage = 0;
        int Mark, Marktotal=0,  marktotalsum=0, count=0;
        String strName, strMark;
        System.out.println("This program will calculate an individual's personal average and then calculate the class average whn instructed.");
        System.out.println("Please type (finish) in order to calculate class average.");
        System.out.println("Please enter a name.");
        strName = br.readLine ();

        while (!strName.equals("finish")){
            System.out.println("The follwing will calculate the average five marks of "+ strName +".");
            System.out.println("Please enter 5 marks.");
            count++;
            for  (int i=0;i<5;i++) {
                Mark = Integer.parseInt(br.readLine());
                    Marktotal= Marktotal + Mark;

            }
            average = Marktotal/5;
            System.out.println(strName+"'s average is "+average);
            Marktotal= 0;
            System.out.println("\n"+"Please enter a name.");
            strName = br.readLine ();
            totalaverage=(totalaverage+average)/count;
        }
        System.out.println("The class average of all input grades is:");
        System.out.println(totalaverage);
        System.out.println();
        System.out.println("Thank you for using the program.");
    }
}


texts: Most efficient FizzBuzz solution in Ruby

texts:
I would appreciate any feedback concerning my analysis of the most efficient FizzBuzz solution programmed in Ruby. I submit that a Case-statement solution is more efficient than utilizing a ConditionalIf-statement in my recent blog-post within my conclusion provided thusly:

  Consequently, the predictability pattern is the reason why a "Case" statement, or branchIf, is optimal and less expensive than a "Conditional If" statement, as clarified by Igor Ostrovsky's Blog Post: Fast and Slow If-Statements: Branch Prediction in Modern Processors

    "If the condition is always true or always false, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the pattern is unpredictable, the if-statement will be much more expensive."

  Back to my optimized FizzBuzz solution- when the "Case" statement processes a number initializing the method, the constraint or case stops calculating when the condition is satisfied, and it will not continue to verify the constraint by branching unless divisible as it were for an IF/ELSIF construction, which saves time, performing faster, as the best solution possible, ultimately proving Danielle Sucher's point:

    "I'd expect if/elsif to be faster in situations where one of the first few possibilities is a match, and for case to be faster in situations where a match is found only way further down the list (when if/elsif would have to make more jumps along the way on account of all those branchUnlesses)."

  Furthermore, a real programmer can impress an interviewer by asking if the range invoked will be consecutive or random.  Although a "Case" statement solution for FizzBuzz is generally more efficient, it will certainly be faster for a random range of numbers called.

I've approached several academics and professionals alike but nobody has challenged, so I would like to broaden the forum for additional contribution:

require 'benchmark'

def fizzbuzz(array)
 array.map!{ |number|
 divisibleBy3 = (number % 3 == 0)
 divisibleBy5 = (number % 5 == 0)

 case
   when divisibleBy3 && divisibleBy5
    puts "FizzBuzz"
   when divisibleBy3
     puts "Fizz"
   when divisibleBy5
     puts "Buzz"
   else
   puts number
  end
 }
end

puts Benchmark.measure{fizzbuzz(Array(1..10000))}
puts "fizzbuzz"
# puts RubyVM::InstructionSequence.disasm(method(:fizzbuzz))

def super_fizzbuzz(array)
 array.map! { |number|
  if(number % 3 == 0 && number % 5 == 0)
   puts "FizzBuzz"
  elsif(number % 3 == 0)
   puts "Fizz"
  elsif (number % 5 == 0)
   puts "Buzz"
  else
  puts number
 end
 }
end

puts Benchmark.measure{super_fizzbuzz(Array(1..10000))}
puts "super_fizzbuzz"
# puts RubyVM::InstructionSequence.disasm(method(:super_fizzbuzz))

# Additional Documentation
 # https://en.wikipedia.org/wiki/Assembly_language
 # underTheHood => http://ruby-doc.org/core-2.0.0/RubyVM/InstructionSequence.html
 # http://ruby-doc.org/stdlib-2.0.0/libdoc/benchmark/rdoc/Benchmark.html

Upon executing the above, terminal-output correspondingly revealed the following when scraped with grep:

 Desktop  ruby fizzbuzz.rb | grep 0.0
 0.010000   0.000000   0.010000 (  0.010018)
 0.010000   0.000000   0.010000 (  0.011353)


texts: Using recursion schemes to avoid explicit corecursive unfolding

texts:
The code is self-contained and self-explaining. I want to improve the goal function. You can change everything below the -- My solution line as long as behaviour of goal :: Goal function is preserved and there is no explicit recursion. Basically I need to rearrange Strings from Graph in a Definition tree using children relationships from Postdominators.

I use ana from recursion-schemes, but you are free to use whatever you want to avoid the recursion. Think of it as an exercise in recursion schemes.

Below is an explanation of what the code does, all 5 lines of it. I removed inessential parts from the real code, but left names intact, so they are somewhat misleading.

I develop a source to source translator. I need to generate source text of a simple functional language with identifier scopes defined by "where" statements similar to what Haskell has.

I get an AST with scopes. Then I convert the AST to a scopeless control flow graph and optimize it. Then I restore the scopes approximately by using dominator analysis of variable references graph.

type Graph = M.Map Label (Maybe String) is the scopeless representation. Some labels point to Nothing and must be ignored.

data Definition = Definition String [Definition] is the scopeful representation - a rose tree of String.

type PostdominatorMap = M.Map Label [Label] - it shows which statements are immediate children of which. If there are no children, there is no key in the map. PostdominatorMap is essentially a tree of Label.

The real code is different, I simplified it a little to keep inessential stuff away. I can't really control the things above the --My solution line as they are dictated by the library I use.

{-# LANGUAGE TypeFamilies, DeriveFunctor, NoMonomorphismRestriction #-}

import Prelude hiding (Foldable)
import Data.Functor.Foldable
import Data.Maybe
import qualified Data.Map as M

type Label = Int

type PostdominatorMap = M.Map Label [Label]

type Graph = M.Map Label (Maybe String)

data Definition = Definition String [Definition]

type Goal = PostdominatorMap -> Graph -> Label -> Definition

-- My solution:

data DefinitionBase a = DefinitionBase String [a] deriving (Functor)

type instance Base Definition = DefinitionBase

instance Foldable Definition where
    project (Definition a b) = DefinitionBase a b

instance Unfoldable Definition where
    embed (DefinitionBase a b) = Definition a b

uncondLookup k = fromMaybe (error "uh-oh") . M.lookup k

goal :: Goal
goal pd g firstLabel = ana (mapWhere $ mapMaybe baz) $ fromJust $ baz firstLabel
    where
        baz :: Label -> Maybe (DefinitionBase Label)
        baz x = lookupValue2 g (M.findWithDefault [] x pd) x

mapWhere f (DefinitionBase a b) = DefinitionBase a (f b)

lookupValue2 g pd x = f <$> uncondLookup x g where
    f a = DefinitionBase a pd

ana offers significant freedom in choosing the seed, so a smart selection of the seed could simplify the code.


texts: Optimizing an implementation of the RKF method


texts:
I wrote a simple wrapper for the <random> header, as follows:

#include <random>

namespace Random
{

    static int getInt(int min, int max)
    {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> distribution(min, max);

        int rnd = distribution(gen);

        return rnd;
    }

    static float getFloat(float min, float max)
    {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<> distribution(min, max);

        float rnd = distribution(gen);

        return rnd;
    }

}

I basically just want to know: is there a better / more efficient way to do it?

I know for a fact that it works quite well, but I am no expert. I thank you in advance for your answers.


texts: Simple streaming parser to extract lines

texts:
It is meant to be given strings over time and output all NewLine delimited substrings. The ColumnReader is meant to be a solution for Delimiter-separated-value files, like CSV or TSV.

using System;

namespace fbstj
{
    public sealed class LineReader
    {
        public string NewLine { get; set; }

        string _buffer = "";

        public void Parse(string text)
        {
            _buffer += text;

            var lastline = _buffer.LastIndexOf(NewLine);
            if (lastline == -1)
                return;

            var lines = _buffer.Substring(0, lastline).Split(NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            _buffer = _buffer.Substring(lastline);

            foreach (var line in lines)
                Receive(line);
        }

        public event Action<string> Receive = (line) => { };
    }

    public struct ColumnReader
    {
        public readonly string Delimiter;
        public readonly LineReader Reader;

        public ColumnReader(string newline, string delimiter) : this()
        {
            Reader = new LineReader { NewLine = newline };
            Delimiter = delimiter;
            Receive += (columns) => { };
            Reader.Receive += _receive_line;
        }

        private void _receive_line(string line)
        {
            Receive(line.Split(Delimiter.ToCharArray()));
        }

        public event Action<string[]> Receive;
    }
}

My main use-case is reading lines from a SerialPort:

var parser = new IO.LineReader { NewLine = port.NewLine };
port.DataReceived += (o, e) => parser.Parse(port.ReadExisting());
parser.Receive += (line) => { };


texts:
I'm kind of new to Python, and I'm trying to improve (especially) my object oriented programming, and getting to know Python syntax better.

I'd love to know if there is something to improve, (especially) in the matter of object oriented, or making the code more Pythonic (Syntactic sugar).

import turtle

RIGHT = 'r'
LEFT = 'l'

class Dragon_Curve(turtle.Turtle):
    def __init__(self, iterations, length):
        super(Dragon_Curve, self).__init__()
        self.iterations = iterations
        self.length = length
        self.hideturtle()
        self.speed(50)
        self.sequence = self.create_seq("", iterations)
        self.draw_sequence(self.sequence)

    def draw_sequence(self, dragon_sequence):
        for i in dragon_sequence:
            if i == RIGHT:
                self.right(90)
                self.forward(length)
            elif i == LEFT:
                self.left(90)
                self.forward(length)

    #  Create the dragon's path, depending on the number of iterations.
    def create_seq(self, given_seq, num_iterations):
        self.seq = ""
        if num_iterations == 0:
            print("the dragon's path is {}".format(given_seq))
            return given_seq
        else:
            self.seq += given_seq
            self.seq += 'r'
            self.seq += self.opposite(given_seq)[::-1]
        return self.create_seq(self.seq, num_iterations - 1)

    # flip the given sequence.
    # If the argument is 'rrl', it will return 'llr'
    def opposite(self, str):
        seq = ""
        for i in str:
            if i == 'r':
                seq += 'l'
            elif i == 'l':
                seq += 'r'
        return seq

if __name__ == '__main__':
    iterations = int(input("Enter number of iterations - "))
    length = int(input("Enter length size (recommended 5) - "))
    dragon = Dragon_Curve(iterations, length)
    turtle.Screen().title("The Dragon Curve")
    turtle.done()


texts: Prime pair set finder (Project Euler problem 60)

texts:
I made a code that can find the prime sets:

  The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.

  Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

First I made a set of 2 primes that satisfies two conditions.The first condition was the digit sum cannot be 3. The other condition was the concentrating test. After finding these all 2 prime sets, I tried to add the third prime to the set and again I checked these 2 conditions are satisfied. After that, I tried to add the fourth prime and so on.

The problem is, it gives answer in 41 min so what should I do?

import itertools
import time

start = time.perf_counter()
def prime(N):
    if N == 0 or N == 1 or N == 5:
        return False
    for i in range(2, int(N ** 0.5) + 1):
        if N % i == 0:
            return False
    return True

def dig_sum(j, n):  # j is the number, n is the element in the list as tuple
    d = 0
    if j == 0:
        for k in n:
            d += sum(int(digit) for digit in str(k))
        if d%3 == 0:
            return False
        return True
    else:
        s = sum(int(digit) for digit in str(j))
        for k in n:
            w = s + sum(int(digit) for digit in str(k))
            if w % 3 == 0:
                return False
        return True

def con_test(j, n):  # j is the number, n is the element in the list as tuple
    if j == 0:
        w = int(str(n[0]) + str(n[1]))
        w1 = int(str(n[1]) + str(n[0]))
        if prime(w) == False or prime(w1) == False:
            return False
        return True
    else:
        for i in n:
            w = int(str(j) + str(i))
            w1 = int(str(i) + str(j))
            if prime(w) == False or prime(w1) == False:
                return False
        return True

def st(n):            #to get rid of the repeated elements
    H = [tuple(sorted(i)) for i in n]
    G = set(H)
    return G

Primes = [i for i in range(3,8000) if prime(i) == True]   #Prime range

Com_two = list(itertools.combinations(Primes,2))

G2 = [i for i in Com_two if dig_sum(0,i) == True and con_test(0,i) == True]

G2r = st(G2)

G3 = [(i,*j) for i in Primes for j in G2r if dig_sum(i,j) == True and con_test(i,j) == True ]

G3r = st(G3)

G4 = [(i,*j) for i in Primes for j in G3r if dig_sum(i,j) == True and con_test(i,j) == True ]

G4r = st(G4)

G5 = [(i,*j) for i in Primes for j in G4r if dig_sum(i,j) == True and con_test(i,j) == True ]

F = [(sum(j),j) for j in G5]

end = time.perf_counter()
Time = end-start
print(Time)
print(F)


texts:
How can I improve it and its running time efficiency?

Problem (SPOJ/CANDY)

  Jennifer is a teacher in the first year of a primary school. She has
  gone for a trip with her class today. She has taken a packet of
  candies for each child. Unfortunately, the sizes of the packets are
  not the same.

  Jennifer is afraid that each child will want to have the biggest
  packet of candies and this will lead to quarrels or even fights among
  children. She wants to avoid this. Therefore, she has decided to open
  all the packets, count the candies in each packet and move some
  candies from bigger packets to smaller ones so that each packet will
  contain the same number of candies. The question is how many candies
  she has to move.

  Input specification

  The input file consists of several blocks of data. Each block starts
  with the number of candy packets \$N (1 <= N <= 10000)\$ followed by
  \$N\$ integers (each less than 1000) in separate lines, giving the
  number of candies in each packet. After the last block of data there
  is the number -1.

  Output specification

  The output file should contain one line with the smallest number of
  moves for each block of data. One move consists of taking one candy
  from a packet and putting it into another one. If it is not possible
  to have the same number of candies in each packet, output the number
  -1.

Solution

 //candy.cpp
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int main()
{
string n;
int avg,t,k; // t = test cases , avg = average
while(true)
{
    scanf("%d",&t);
    int sum = 0; // initialise sum and cnt(next line) to 0
    int cnt = 0;
    if(t == -1) // Last line to end the program(Mentioned in the ques.)
        break;

    else
    {
        for(int i = 0 ; i < t ; i++)
        {
            cin >> n[i];
            sum += n[i];
        }

        if(sum % t != 0) // If it is not possible to have the same number of candies in each packet, output the number -1(mentioned in the question)
            cout << "-1" << endl;

        else
        {
            avg = sum/t;
            for(int i = 0 ; i < t ; i++)
            {
                k = n[i];
                while(k > avg) //Adds the moves
                {
                    k-- ;
                    cnt++ ;
                }
            }
            printf("%d\n", cnt);
        }
    }

}

}


texts:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

I started out with this solution. It's iterative, and not very efficient. It multiplies all number combinations, adds the products to an array, finds the palindromes, then chooses the max.

def palindrome?(number)
  number.to_s == number.to_s.reverse
end

def largest_palindrome(range = 1..999)
  array = []
  range.each do |x|
    range.each do |y|
      array.push(x * y)
    end
  end
  array.select { |n| palindrome?(n) }.max
end
puts largest_palindrome

I improved with my second iteration, but it still relies on iteration. I narrowed the range down reasoning that the largest palindrome is likely to be the product of two numbers within 901 and 999. This time I multiplied all the numbers, but only saved the palindromes in the array, then selected max, which saved a step. It's noticeably faster, but still not optimal.

def largest_palindrome(range = 1..99)
  palindromes = []
  range.end.downto(range.begin).each do |x|
    range.end.downto(range.begin).each do |y|
      palindromes << x * y if palindrome?(x * y)
    end
  end
  palindromes.max
end

puts largest_palindrome 901..999

My reasoning about narrowing the range feels like cheating. It's intuitive, and arbitrary.


texts: JavaScript mixins - extending and super methods

texts:
I've read a lot of stuff about mixins, inheritance and such, and in the end I came up with this solution for extending a class with multiple mixins. I haven't seen this anywhere else...

var Classes = {}; // I keep all classes inside this objects, so I can do new Classes[obj_name]();
Classes.asA = function () {
    var _init = this.init; // keep a copy of the previously declared method, if any
    this.init = function (a) {
        if (_init) _init.call(this, a); // call super method, if any
        this.a = a; // declare additional properties here
    }
    this.methodA = function () {
        console.log("a: "+this.a);
    }
}
Classes.asB = function () {
    var _init = this.init;
    this.init = function (a) {
        if (_init) _init.call(this, a);
        this.b = a+1;
    }
    this.methodB = function () {
        console.log("b: "+this.b);
    }
}
Classes.Obj = function () {
    var _init = this.init;
    this.init = function (a) {
        if (_init) _init.call(this, a);
        this.z = a-2;
    }
    this.methodZ = function () {
        console.log("z: "+this.z);
    }
}
Classes.asA.call(Classes.Obj.prototype); // extend Obj with asA
Classes.asB.call(Classes.Obj.prototype); // extend Obj with asB

var obj = new Classes.Obj();
obj.init(7); // will call in order asA.init, asB.init, Obj.init
obj.methodA(); // outputs "a: 7"
obj.methodB(); // outputs "b: 8"
obj.methodZ(); // outputs "z: 5"

Is this a good method? Do you see any problems with it?


texts:
On my quest to learn Ruby I figured exploring the proper usage of different data-structures would be invaluable, including strings, arrays and hashes.

I decided to build a hash containing the numbers 1 till 100 inclusive. These hashes would contain:

Whether the number is prime
What it's FizzBuzz output would be
The n-th Fibonacci number.

In the end the number itself turned into a value as well. I intended the number to be the key and the other 3 values to be a hash of that key but it got too complicated.

As a side effect my project got quite bulky and should probably be split up. Somehow. My gut tells me I should move the FizzBuzz and Fibonacci parts to their own module and import them like I did with the already existing prime module.

On top of that, I got a couple of concerns:

Is output += "Fizz" the idiomatic way of adding a string to a string?
Is my usage of the hash proper or is it not supposed to be used like this?
Did I adhere to variable naming rules?
How is the general readability?

Code:

require 'prime'

class Fibonacci
    def initialize(max)
        @max = max
        @list = [1, 1, 2]
        for i in 3..@max do
            @list << @list[i-2] + @list[i-1]
        end
    end
    def get_nth(n)
        return @list[n]
    end
end

numbers = []

def fizzbuzz(number)
    output = ""
    if (number % 3 == 0)
        output += "Fizz"
    end
    if (number % 5 == 0)
        output += "Buzz"
    end
    if output == ""
        output = number
    end
    return output
end

Fib = Fibonacci.new(100)

for number in 1..100 do
    hash = {
        :Number => number,
        :FizzBuzz => fizzbuzz(number),
        :Prime => Prime.instance.prime?(number),
        :Fibonacci => Fib.get_nth(number)
    }
    numbers << hash
end

The results can be called like this:

Primes:

numbers.each { |number| puts number[:Number], number[:Prime] }

FizzBuzz:

numbers.each { |number| puts number[:FizzBuzz] }

Fibonacci:

numbers.each { |number| puts number[:Number], number[:Fibonacci] }

Try it