texts:
I solved this problem:

  Given two strings s and t, determine if they are isomorphic.

  Two strings are isomorphic if the characters in s can be replaced to
  get t.

  All occurrences of a character must be replaced with another character
  while preserving the order of characters. No two characters may map to
  the same character but a character may map to itself.

For example:

  Given "egg", "add", return true.

  Given "foo", "bar", return false.

  Given "paper", "title", return true.

Note:

  You may assume both s and t have the same length.

The code in C# on average took around 109ms to execute, which is pretty slow compared to the C++ version of the same algorithm, which executes in under 6ms. Although, the fastest C# solution for this problem is around 100ms.

public class Solution {
    public bool IsIsomorphic(string s, string t) {
            int[] map = Enumerable.Repeat(-1, 175).ToArray();
            bool[] marked = Enumerable.Repeat(false, 175).ToArray();
            for(int i=0; i<s.Length; ++i)
            {
                if (map[s[i]] ==  -1) // Unvisited
                {
                    if (marked[t[i]]) // Already has a mapping
                    {
                        return false;
                    }

                    marked[t[i]] = true;

                    map[s[i]] = t[i];
                }
                else if(map[s[i]] != t[i])
                {
                    return false;
                }
            }

            return true;
    }
}

Optimizations I had done:

Converted List<T> to array after reading this
Changed foreach to a plain for loop that helped remove another index variable for iterating over string t

Can you suggest any better way to squeeze some performance from the C# implementation?

And from the FAQ section of LeetCode I could see that C# uses mono 4.2.1 and C++ uses g++ 5.4.0.

I'm attaching the C++ solution as well just for reference:

#define MAX_CHARS 175
class Solution {
public:
    bool isIsomorphic(string str1, string str2) {
    bool marked[MAX_CHARS] = {false};

    // To store mapping of every character from str1 to
    // that of str2. Initialize all entries of map as -1.
    int map[MAX_CHARS];
    memset(map, -1, sizeof(map));

    // Process all characters one by on
    for (int i = 0; i < str1.size(); i++)
    {
        // If current character of str1 is seen first
        // time in it.
        if (map[str1[i]] == -1)
        {
            // If current character of str2 is already
            // seen, one to one mapping not possible
            if (marked[str2[i]] == true)
                return false;

            // Mark current character of str2 as visited
            marked[str2[i]] = true;

            // Store mapping of current characters
            map[str1[i]] = str2[i];
        }

        // If this is not first appearance of current
        // character in str1, then check if previous
        // appearance mapped to same character of str2
        else if (map[str1[i]] != str2[i])
            return false;
    }

    return true;

    }
};


texts: C# Code Optimization -- Finding nearest key in a SortedList

texts:
Just wondering if anyone can see a way to optimize this piece of code.  It is a key piece of my program and needs to run as quickly as possible. The part of the code I am unsure of is the while loop for finding the nearest key -- but any assistance with optimizing the code would be appreciated.

// TODO: Move to snippets lib or create a new collection type that supports this feature
private string _getTrait(SortedList<decimal, string> thisList, decimal thisValue)
{
    // Check to see if we need to search the list.
    if (thisList == null || thisList.Count <= 0) { return null; }
    if (thisList.Count == 1) { return thisList.Values[0]; }

    // Setup the variables needed to find the closest index
    int lower = 0;
    int upper = thisList.Count - 1;
    int index = (lower + upper) / 2;

    // Find the closest index (rounded down)
    bool searching = true;
    while (searching)
    {
        int comparisonResult = Decimal.Compare(thisValue, thisList.Keys[index]);
        if (comparisonResult == 0) { return thisList.Values[index]; }
        else if (comparisonResult < 0) { upper = index - 1; }
        else { lower = index + 1; }

        index = (lower + upper) / 2;
        if (lower > upper) { searching = false; }
    }

    // Check to see if we are under or over the max values.
    if (index >= thisList.Count - 1) { return thisList.Values[thisList.Count - 1]; }
    if (index < 0) { return thisList.Values[0]; }

    // Check to see if we should have rounded up instead
    if (thisList.Keys[index + 1] - thisValue < thisValue - (thisList.Keys[index])) { index++; }

    // Return the correct/closest string
    return thisList.Values[index];
}

I am using C#, .net4.0 -- I need to use a Generic SortedList ( http://msdn.microsoft.com/en-US/library/ms132319(v=vs.100).aspx )


texts:
I've written the following code ages ago (10+ years) which is part of a simple chat server. I'm going to refactor it a bit in Java and then for fun I'm going to convert it to Scala and use Akka actors instead of threading.

Do you see any thread issues that can arise from the method of synchronization?

If a thread appends a record and another thread performs a read on the thread that reads, is it not going to have the current data?

Upon reading this article, I assume that is not the case?

I could use a ConcurrentHashMap instead but it doesn't preserve the order of insertion.

final class UserRecord
{
    //unsynchronized version of hashtable which maintains the order
    //which the objects where inserted.
    private LinkedHashMap container;

    public UserRecord()
    {
        container = new LinkedHashMap();
    }

    //return true if the user name is not taken
    synchronized boolean add(ClientHandler handler)
    {
        if (container.containsKey(handler.getUserName()) == true)
            return false;

        container.put(handler.getUserName(), handler);
        return true;
    }

    synchronized void remove(ClientHandler handler)
    {
        container.remove(handler.getUserName());
    }

    synchronized int size()
    {
        return container.values().size();
    }

    synchronized ClientHandler getHandler(String userName)
    {
        return (ClientHandler) container.get(userName);
    }

    synchronized Iterator getIterator()
    {
        return container.values().iterator();
    }

    synchronized void clear()
    {
        this.container.clear();
    }
}


texts:
I have an event handling code, something like
void handleEventType1(EventType1 event1) {
    if (someCheck()){
        function1(event);
        postCheckTrue();
    } else {
        function2(event);
        postCheckFalse();
    }
}

void handleEventType2(EventType2 event2) {
    if (someCheck()){
        function3(event);
        postCheckTrue();
    } else {
        function4(event);
        postCheckFalse();
    }
}

I was hoping, I can do something like
handleEvent(event1, Handler::function1, Handler::function2);
handleEvent(event2, Handler::function3, Handler::function4);

that will somehow call functions (1 or 2) or (3 or 4), but I'm somehow not able to solve it to my satisfaction.


texts: Creating a database class in PHP with MySQLi

texts:
I am creating a database class in PHP but I feel that there's something wrong with my code. Is there any suggestion to refactor this?  I feel like there's something wrong and missing in this code.

<?php
    require_once("db_constants.inc.php");

    Class MySqli_Database
    {
        public $db;

        public  function __construct($db_host,$db_username,$db_password,$db_name)
        {
            $this->db = new mysqli($db_host,$db_username,$db_password,$db_name);
        }

        public function __performSql($sql)
        {

        }

        public static function closeConnection($conn)
        {
            $this->db_close();
        }

    }

    $conn = new MySqli_Database (DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME)
    or die("Could Not Connect To Database: " . mysqli_errno());

Perform SQL will just basically execute the query, though I haven't included the code yet,  but I will soon. Also if you have tutorials or guide when creating a database class for MySQLi please post it. It would be a great help.


texts: Determine whether any permutation of a string is a palindrome

texts:
The task:

  Given a string, determine whether any permutation of it is a
  palindrome.

  For example, "carrace" should return true, since it can be rearranged to
  form "racecar", which is a palindrome. "daily" should return false, since
  there's no rearrangement that can form a palindrome.

My solution:

const isPalindrome = str => {
  const letterOccurrences = str
  .split("")
  .reduce((acc, x) => {
    acc[x] = acc[x] ? acc[x] + 1 : 1;
    return acc;
  }, {});

  let numberOfOddOccurrences = 0;
  const isMaxOneOddNumberLetter = x => x % 2 === 0 || ++numberOfOddOccurrences <= 1;
  return Object.values(letterOccurrences).every(isMaxOneOddNumberLetter);
};

console.log(isPalindrome("carrace"));

Is it possible to write the function isMaxOneOddNumberLetter without mutation resp. side effects?


texts:
CodeEval FizzBuzz

  Quick Description:

  Take 1 command line argument of a file-path. This file will contain
  test cases formatted as such 3 space separated numbers per line. For
  numbers X, Y and Z you must print out all numbers between 1 and
  Z, space separated, replacing all numbers divisible by X with 'F'
  and all numbers divisible by Y with 'B'.

I am entirely new to Functional programming, and my Haskell knowledge is from a single Pluralsight class, so I am looking for any amount of feedback, particularly for best practices. I also feel like the actual fizzBuzzSingle function can be solved in a list comprehension instead, but I'm still uncomfortable with the syntax so I didn't use one.

If my code is reading too object-oriented please let me know. I also did look up the other FizzBuzz questions on this site, but they all seem to not being handling file input, which seemed the hardest part to me, so it seemed worth posting this.

import System.Environment

fizzBuzzSingle :: Int -> Int -> Int -> String
fizzBuzzSingle f b n
    | n `mod` f == 0 && n `mod` b == 0  = "FB"
    | n `mod` f == 0                    = "F"
    | n `mod` b == 0                    = "B"
    | otherwise                         = show n

fizzBuzz :: (Int, Int, Int) -> [String]
fizzBuzz (f,b,end) = map (fizzBuzzSingle f b) [1..end]

convertInputLine :: String -> (Int, Int, Int)
convertInputLine x = packageInputs ((map read . words) x :: [Int])

packageInputs :: [Int] -> (Int, Int, Int)
packageInputs [f,b,end] = (f, b, end)

concatOutput :: [String] -> String
concatOutput (x : xs) =
    foldl (\x y -> x ++ " " ++ y) x xs

handleFizzBuzz :: [String] -> [String]
handleFizzBuzz [] = []
handleFizzBuzz (x : xs) =
    (concatOutput . fizzBuzz . convertInputLine $ x) : handleFizzBuzz xs

main :: IO ()
main = do
    args <- getArgs
    let path = args !! 0
    file <- readFile path
    putStrLn . unlines . handleFizzBuzz . lines $ file


texts: Making sequence unique with removal records

texts:
I'm working on a tool to detect all exact tandem repeats in a DNA/RNA sequence. Part of the algorithm requires finding Longest Common Extension (LCE) values, which although can be computed in constant time, in practice it is (usually) better to use a naive \$O(n^2)\$ solution. The problem is that DNA sequences can contain long contiguous sequences of N's (unknown base). This can completely destroy the performance of the algorithm as it doesn't play nice with the \$O(n^2)\$ LCE algorithm. Solution: collapse all stretches of N's into a single N, no other repeats are missed (other than N's).

The problem is that then the repeats reported by the algorithm are in respect to the modified sequence, so I need to record how many N's have been removed before that position in the original sequence to get the correct position.

More generally: The algorithm should take as input a sequence sequence and a character c, collapse all contiguous sub-sequences of c into a single c (in-place), and record how many cs have been removed up until the next non-c character past the last removed c.

Here is my current attempt at this algorithm:

#include <map>
#include <cstddef>   // std::size_t
#include <algorithm> // std::adjacent_find, std::find_if_not, std::unique
#include <iterator>  // std::begin, std::end, std::distance, std::next

template <typename SequenceType>
std::map<std::size_t, std::size_t> collapse(SequenceType& sequence, char c)
{
    std::map<std::size_t, std::size_t> result {};

    auto first = std::begin(sequence);
    auto last  = std::end(sequence);

    std::size_t position {}, num_removed {};

    while (first != last) {
        auto it1 = std::adjacent_find(first, last, [c] (char lhs, char rhs) { return lhs == c && lhs == rhs; });

        if (it1 == last) break;

        auto it2 = std::find_if_not(it1, last, [c] (char b) { return b == c; });

        position    += std::distance(first, it1);
        num_removed += std::distance(it1, it2) - 1;

        result.emplace(position, num_removed);

        first = it2;
    }

    if (!result.empty()) {
        sequence.erase(std::unique(std::next(std::begin(sequence), result.cbegin()->first), last,
                                   [c] (char lhs, char rhs) { return lhs == c && lhs == rhs; }), last);
    }

    return result;
}

I'm wondering if there's a better way that would avoid having to potentially scan the entire sequence twice (note the last call to std::unique)?


texts:
I often see nested loops as a solution to the bubble sort, but my solution involves a recursive function. Is the following solution less efficient than the traditional method?
public static int[] BubbleSort(int[] arrayOfValues)
{
    var swapOccurred = false;

    for (var i = 0; i < arrayOfValues.Length; i++)
    {
        if (i == arrayOfValues.Length - 1)
            continue;

        if (arrayOfValues[i] > arrayOfValues[i + 1])
        {
            //swap values
            var current = arrayOfValues[i];
            var next = arrayOfValues[i + 1];

            arrayOfValues[i] = next;
            arrayOfValues[i + 1] = current;

            swapOccurred = true;
        }
    }

    if (swapOccurred)
    {
        // keep going until no further swaps are required:
        BubbleSort(arrayOfValues);
    }

    return arrayOfValues;
}


texts: Project Euler #1 in Go (counting multiples of 3 or 5 up to 1000)

texts:
I've been working on Project Euler, here was my solution for Problem #1. It gave me the proper answer, but it's egregiously slow. How can I implement this more efficiently? My math skills aren't top-notch, sorry.

package main

import (
    "fmt"
)

// Problem1: find the sum of all the multiples of 3 or 5 below 1000.
// x,y: multiples
// z: upper limit
func Problem1(x, y, z int) int {

    Multiples := make(map[int]struct{})

    var Sum int
    for i := 1; i < z; i++ {
        XFactor := x * i
        YFactor := y * i

        if XFactor < z {
            Multiples[XFactor] = struct{}{}
        }
        if YFactor < z {
            Multiples[YFactor] = struct{}{}
        }
    }

    for key, _ := range Multiples {
        Sum = Sum + key
    }

    return Sum
}

func main() {
    fmt.Println("The answer to problem 1 is: ", Problem1(3,5,1000))
}

Thanks! https://play.golang.org/p/MQLpjtMvmw


texts: Android layout with equal spacing between elements

texts:
I am trying to make a nice set of items, which are equally spaced from each other.
On example below, I set buttons between empty textview. Every button and text view has height = 0dip and weight=1. And it looks pretty nice. However, is there a way to clean up the layout file?

<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="" />

            <Button
                android:id="@+id/btn_distance_walked"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:clickable="false"
                android:text="Distance walked = " />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="" />

            <Button
                android:id="@+id/btn_exersise_time"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:clickable="false"
                android:text="Exercise time = " />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="" />

            <Button
                android:id="@+id/btn_average_speed"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:clickable="false"
                android:text="Average speed = " />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="" />

            <Button
                android:id="@+id/btn_calories_burned"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:clickable="false"
                android:text="Callories burned = " />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:clickable="false"
                android:text="" />

            <Button
                android:id="@+id/btn_back"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="Back" />

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="0dip"
                android:layout_weight="1"
                android:text="" />
        </LinearLayout>


texts: Checking CSS code for best practices when mimicking

texts:
I'm currently looking to try learn CSS properly and I'm looking to recreate the following image using CSS:

Now I've managed to recreate the image (sort of) what I am looking to know though is based on my code what am I doing wrong/what would be the best practice. Many solutions fix a problem I want to know if my solution is reasonable.

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's

Testing

Here is the CSS image:


texts: Improving sub select query on two tables without relationship

texts:
I am trying to return the count of employees by salary band and can return data using the following sql but wondered if this was the most efficient way of achieving it?

I know creating a join between the tables would be better but that is not possible in this instance.

select *, (select count(*) from EmployeeSalary where salary between minsalary and maxsalary) from SalaryBands


texts:
I'm trying to write a simple game. I have an Entity object, that has a list of Sprite objects. Each Sprite has a position property where it is drawn on the screen. Sometimes, an entity can contain a lot of Sprites in which case it is much easier to set the position property on the parent Entity.

Here's a simplified example of creating an Entity with a list of Sprites:

var player = new Entity( new List<Sprite>
                         {
                             new Sprite( "characters/walkcycle/body", new Vector2( 128, 128 ) ),
                             new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
                             new Sprite( "characters/walkcycle/shirt", new Vector2( 128, 128 ) ),
                             new Sprite( "characters/walkcycle/pants", new Vector2( 128, 128 ) ),
                             new Sprite( "characters/walkcycle/shoes", new Vector2( 128, 128 ) )
                         } );

Most of the Sprites have the same position, so I do this instead:

var player = new Entity( new Vector2( 128, 128 ),
                         new List<Sprite>
                         {
                             new Sprite( "characters/walkcycle/body" ),
                             new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
                             new Sprite( "characters/walkcycle/shirt" ),
                             new Sprite( "characters/walkcycle/pants" ),
                             new Sprite( "characters/walkcycle/shoes" )
                         } );

Notice the halo sprite is in a different position. Later in the code, I call the Load method on Entity, which passes its position property on to the children Sprites:

public class Entity
{
    // fields, constructor, properties ...

    public void Load()
    {
        foreach ( var sprite in this.sprites )
        {
            sprite.Load( this.position );
        }
    }
}

The Load method on Sprite will set its own position property to the value passed in if it doesn't already have one:

public class Sprite
{
    // fields, constructor, properties ...

    public void Load( Vector2 position )
    {
        if ( this.position == Vector2.Zero && position != Vector2.Zero )
        {
            this.position = position;
        }
    }
}

Is there a better way to do this? It smells a little to me.


texts: Making a simple session class more secured

texts:
I just wrote the session class below.  I humbly request for a review on how to make this even more secured/ how sessions are normally written. The code below works, but I would love to make it even more secure and robust.

<?php
session_start();

require_once('classes/function.php');
require_once('classes/user.php');

class Session{

    private $logged_in = FALSE;
    private $id ;
    private $user_data ;
    private $email ;

public function logout(){
    session_start();
    unset($_SESSION['id']);
    unset($this->id);
    session_destroy();
    $logged_in = FALSE;
    Misc::redirect('index.php');
}

public static function is_logged_in(){
    if(isset($_SESSION['id'])){
        $logged_in = TRUE;
        Misc::redirect('127.0.0.1/users/index.php');
    }
}

public static function login($email, $password){
    global $user;
    global $misc;

    if($misc->check_form()){
        echo $this->error;
    }
    if (!MIsc::check_email_format($email)) {
            echo "Email format is invalid";
          }
          $login_user = $user->authenticate($email, $password);
          if($login_user){
            $_SESSION['id'] = $this->id = $user->user_data['id'];
            $logged_in = TRUE;
            Misc::redirect('127.0.0.1/users/index.php');
          }
}
}

$session = new Session;
?>


texts:
I am writing a simple raytracer just for fun. I want to iterate over rows, and each row must be an iterator over columns. A strategy I produced is the following:

class ViewPlane(object):
    def __init__(self, resolution, pixel_size, gamma):
        self.resolution = resolution
        self.pixel_size = pixel_size
        self.gamma = gamma

    def __iter__(self):

        def genR():
            class IterRow(object):
                def __init__(self, plane, row):
                    self.plane = plane
                    self.row = row

                def __iter__(self):
                    def genC():
                        for column in xrange(self.plane.resolution[1]):
                            origin = (self.plane.pixel_size *
                                       (column - self.plane.resolution[0] / 2.0 + 0.5)
                                        ,
                                        self.plane.pixel_size *
                                         (self.row - self.plane.resolution[1] / 2.0 + 0.5)
                                        ,
                                        100.0
                                     )
                            yield ( Ray(origin = origin, direction = (0.0,0.0,-1.0)),
                                    (self.row,column)
                                )
                        return
                    return genC()
                def __str__(self):
                    return "Row iterator on row "+str(self.row)
            for row in xrange(self.resolution[0]):
                yield IterRow(self, row)

        return genR()

Briefly stated: ViewPlane contains the pixel plane. This class implements __iter__ which defines and returns a generator function. This generator function yields instances of an internal class IterRow, which in turn has a __iter__ method that returns a generator iterating over the columns.

I personally think that it's difficult to understand, so I was wondering if there's a cleaner strategy to achieve the same result.


texts:
Is it a bad idea for a model class hold the db handler as a property? Example code are as below. I think the second is better, but the first is not so bad in my opinion.

First:

class ActiveModel {
    protected $db;

    public function __construct() {
        $this->db = DbFactory::get('Foo');
    }

    public function save() {
        //use $this->db to do the job;
        ....
    }
}

Second:

class ActiveModel {

    public function save($db = null) {
        if ($db === null) {
            $db = DbFactory::get('Foo');
        }
        //then use $db to do the job;
        ....
    }
}


texts: Tarjan's Algorithm Python Implementation

texts:
I'm planning to use Tarjan's algorithm for a program in which I would be processing a file, converting the processed data to a dictionary, doing a topological sort on that dictionary (using this implementation), and then finding the longest path.

Is there any optimization that can be made to the below code, or can be be made more pythonic?

def strongly_connected_components(graph):

    index_counter = [0]
    stack = []; result = []
    lowlinks = {}; index = {}

    def tarjan(node):

        index[node] = index_counter[0]
        lowlinks[node] = index_counter[0]
        index_counter[0] += 1
        stack.append(node)

        try:
            successors = graph[node]
        except:
            successors = []
        for successor in successors:
            if successor not in lowlinks:
                tarjan(successor)
                lowlinks[node] = min(lowlinks[node],lowlinks[successor])
            elif successor in stack:
                lowlinks[node] = min(lowlinks[node],index[successor])

        if lowlinks[node] == index[node]:
            connected_component = []
            while True:
                successor = stack.pop()
                connected_component.append(successor)
                if successor == node: break
            component = tuple(connected_component)
            result.append(component)

    for node in graph:
        if node not in lowlinks:
            tarjan(node)

    return result

Source

The graph is unweighted, and would look something like this:-

test_graph = {
    'A' : ['B','S'],
    'B' : ['A'],
    'C' : ['D','E','F','S'],
    'D' : ['C'],
    'E' : ['C','H'],
    'F' : ['C','G'],
    'G' : ['F','S'],
    'H' : ['E','G'],
    'S' : ['A','C','G']
}


texts:
So this is the code to a calculator I made for a game. Essentially what the calculator does is, it calculates the cost of buying the next stat.
So I wrote the code just for the Human race and the strength stat. From the way I see it, I will have to do for each race the same code 3 times for each stat.
I was hoping there would be a shorter way around this like
instead of human.strength I would like it to be race.strength where race = user_race.
Thanks
class race:
    """The different races in the calculator"""
    def __init__(self, race, strength, agility, health, strength_cost, agility_cost, health_cost):
        self.race = race
        self.strength = strength
        self.agility = agility
        self.health = health
        self.strength_cost = strength_cost
        self.agility_cost = agility_cost
        self.health_cost = health_cost

human = race('Human', 15, 17, 18, 5, 3, 4)
elf = race('Elf', 11, 21, 14, 4, 3, 5)
giant = race('Giant', 25, 11, 27, 4, 8, 3)

print("Human, Giant, Elf")
user_race = str(input("Enter your race:")).lower()
print("Strength, Agility, Health")
user_stat = str(input("Enter your desired stat:")).lower()
user_present_stat_value = int(input("Enter your present stat value:"))
user_desired_stat_value = int(input("Enter your desired stat value:"))

if user_race == 'human' and user_stat == 'strength':
    human_strength_present_statdif = (user_present_stat_value - human.strength) # difference of present stat with respect of base stat

    human_strength_desired_statdif = (user_desired_stat_value - human.strength) #difference of desired stat with respect of base stat

    human_strength_present_stat_cost = (human.strength_cost + (human_strength_present_statdif - 1) * human.strength_cost) #The cost of present stat stat

    human_strength_total_present_cost = ((human_strength_present_statdif / 2) * (human.strength_cost + human_strength_present_stat_cost)) # The total cost from base stat to present stat

    human_strength_desired_stat_cost = (human.strength_cost + (human_strength_desired_statdif - 1) * human.strength_cost) #The cost of desired stat

    human_strength_total_desired_cost = ((human_strength_desired_statdif / 2) * (human.strength_cost + human_strength_desired_stat_cost)) # The total cost base stat to desired stat

    human_strength_net_cost = (human_strength_total_desired_cost - human_strength_total_present_cost) # The Net cost from the difference of Total desired stat and Total present stat

    print("Net cost: " + str(human_strength_net_cost))
```


texts: Classifying lexemes in a given C program

texts:
Please review my code and tell where I can improve my program.

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

#define BUFFER_SIZE 1024
#define TOKEN_SIZE 32
#define TRUE 1
#define FALSE 0

int isKeyword(const char* token)
{
    const char keywords[32][20]={"auto","break","case","char",
                                "const","continue","default","do","double",
                                "else","enum","extern","float",
                                "for","goto","if","int","long",
                                "register","return","short","signed",
                                "sizeof","static","struct","switch",
                                "typedef","union","unsigned",
                                "void","volatile","while"};
    for(int i=0;i<32;i++)
    {
        if(strcmp(token,keywords[i])==0)
            return TRUE;
    }
    return FALSE;
}

int isIntLiteral(const char* token)
{
    for(int i=0;token[i]!=(char)NULL;i++)
    {
        if(!isdigit(token[i]))
            return FALSE;
    }
    return TRUE;
}

int isFloatLiteral(const char* token)
{
    if(isdigit(token[0]))
    {
        for(int i=1;token[i]!=(char)NULL;i++)
        {
            if(!isdigit(token[i]) && (token[i])!='.')
                return FALSE;
        }
        return TRUE;
    }
    return FALSE;
}

int isCharLiteral(const char* token)
{
    if(token[0]=='\'' && strlen(token)==3 && token[2]=='\'')
        return TRUE;
    else
        return FALSE;
}

int isLiteral(const char* token)
{
    if(isCharLiteral(token)||isIntLiteral(token)||isFloatLiteral(token))
        return TRUE;
    else
        return FALSE;
}

int isIdentifier(const char* token)
{
    if(isalpha(token[0]) || token[0]=='_')
    {
        for(int i=1;token[i]!=(char)NULL;i++)
        {
            if(!isalnum(token[i]))
                return FALSE;
        }
        return TRUE;
    }
    return FALSE;
}

int isOperator(const char* token)
{
    const char operators[41][10] = {".","->","++","--","!","~","(type)","*","&",
                                 "sizeof","*","/","%","+","-","<<",">>","<",
                                 "<=",">",">=","==","!=","&","^","|","&&","||",
                                 "?:","=","+=","-=","*=","/=","%=","&=","^=",
                                 "|=","<<=",">>=",","};

    for(int i=0;i<41;i++)
    {
        if(strcmp(token,operators[i])==0)
            return TRUE;
    }
    return FALSE;
}

FILE* readFile(int param1,char* param2[])
{
    if(param1<2)
    {
        fprintf(stderr,"No file specifed to read. \n");
        exit(1);
    }

    if(param1>2)
    {
        fprintf(stderr,"Too many arguments for read to perform. \n");
        exit(1);
    }

    FILE *fp = fopen(param2[1],"r");

    if(!fp)
    {
        fprintf(stderr,"File access denied on read. \n");
        exit(1);
    }
    return fp;
}

int main(int argc,char* argv[])
{

    FILE *fp = readFile(argc,argv);

    char *token;
    char string[BUFFER_SIZE];
    const char delimiters[]=" .,;!=\n";

    fgets(string,sizeof string, fp);
    while(string!=(char *)NULL || (strcmp(string,"\n"))==0)
    {
        token = strtok(string,delimiters);

        while(token!=NULL)
        {
            if(isKeyword(token))
                printf("%s is a keyword. \n",token);
            else if(isOperator(token))
                printf("%s is an operator. \n",token);
            else if(isIdentifier(token))
                printf("%s is an identifier. \n",token);
            else if(isLiteral(token))
                printf("%s is a literal. \n",token);
            else
                printf("Unrecognized token : %s \n",token);

            token = strtok(NULL,delimiters);
        }
        fgets(string,sizeof string, fp);
    }

    fclose(fp);
    return 0;
}`


texts: Implement State Monad transformer in Haskell from scratch

texts:
When I was studying Monad Transformer, I decided to create StateT s m a from scratch with instances for Functor, Applicative and Monad.

This is what I have:

newtype StateT s m a = StateT { runStateT :: (s -> m (a, s)) }

instance Functor m => Functor (StateT s m) where
    -- fmap :: (a -> b) -> StateT s m a -> StateT s m b
    -- which is (a -> b) -> (s -> m (a, s)) -> (s -> m (b, s))
    f `fmap` (StateT x) = StateT $ \ s -> fmap run (x s)
        where run (a, s) = (f a, s)

instance Monad m => Applicative (StateT s m) where
    -- pure :: a -> StateT s m a
    pure a = StateT $ \ s -> pure (a, s)
    -- <*> :: f (a -> b) -> f a -> f b
    -- which is StateT s m (a -> b) -> StateT s m a -> State s m b
    k <*> x = StateT $ \ s -> do
        (f, s1) <- runStateT k s -- :: m ((a -> b), s)
        (a, s2) <- runStateT x s1
        return (f a, s2)

instance (Monad m) => Monad (StateT s m) where
    return a = StateT $ \ s -> return (a, s)
    -- >>= :: StateT s m a -> (a -> StateT s m b) -> StateT s m b
    (StateT x) >>= f = StateT $ \ s -> do
        (v, s') <- x s
        runStateT (f v) s'

My original intention is to implement Functor (StateT s m) with Functor m restriction, Applicative (StateT s m) with Applicative m restriction, and Monad (StateT s m) withMonad m) restriction. However I couldn't do the Applicative case and had to use Monad m restriction instead. Is there a way to do it with Applicative m?

Thank you in advance.


texts:
I'm writing a CHIP-8 emulator in C++, which has two timers. If these timers are non-zero, they are decremented by 1 at 60Hz. I'm still getting the hang of C++, so I wanted to see if I'm doing this the Right Way.

Here's the header file:

#include <chrono>

struct TimedRegister
{
  unsigned char value;
  std::chrono::time_point<std::chrono::high_resolution_clock> last_write;

  TimedRegister();
  void set(const unsigned char new_value);
  void decrement();
};

And this is the the implementation:

#include "chip8.hpp"

#include <chrono>

TimedRegister::TimedRegister()
  : value(0)
{}

void
TimedRegister::set(const unsigned char new_value)
{
  value = new_value;
  last_write = std::chrono::high_resolution_clock::now();
}

void
TimedRegister::decrement()
{
  if (value == 0)
    return;

  const auto now = std::chrono::high_resolution_clock::now();
  if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_write)
        .count() >= 1000 / 60) {
    --value;
    last_write = now;
  }
}

The decrement function is called from the main emulator loop like this:

while (!chip8.halted) {
  chip8.delay_timer.decrement();
}

They seem to work fine, but I'm not sure if I'm getting away with using a heavy-handed, brute-force approach.


texts: Encrypting and decrypting passwords in PHP

texts:
I am wanting to encrypt a password and decrypt a password using PHP. Is this a safe method?

$pass = "password"

//encrypt password
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", 10) . $salt;
$hash = crypt($pass, $salt);

//decryption in second program
if(crypt($pass, $hash) == $hash){
    echo "you are in";
}


texts:
I just some reviews on how I can make it more efficient or cleaner and what I should fix in general.

class bankAcc
{
public:
    bankAcc() = default;
    bankAcc(string fn, string ln) : firstName(fn), lastName(ln) {}
    bool createUser(istream &is);
    bool login() const;
private:
    bool correctLogin(const string&, const string&) const;
    static vector<string> usernames;
    static vector<string> passwords;
    string firstName, lastName;
    string username, password;
};

vector<string> bankAcc::usernames;
vector<string> bankAcc::passwords;

bool bankAcc::createUser(istream &is) {
    is >> username >> password;
    if (is.fail()) {
        cout << "Invalid option" << endl;
        cin.clear();
        return false;
    }
    usernames.push_back(username);
    passwords.push_back(password);
    return true;
}

bool bankAcc::login() const {
    bool login;
    string tempUser, tempPass;
    cin >> tempUser >> tempPass;
    if (cin.fail()) {
        cout << "Invalid options" << endl;
        cin.clear();
        return false;
    }
    login = correctLogin(tempUser, tempPass);
    if (login == true) {
        cout << "Logged on" << endl;
        return login;
    }
    else {
        cout << "Incorrect info" << endl;
        return login;
    }
    return login;
    }

bool bankAcc::correctLogin(const string &tempUser, const string &tempPass) const {

    if (usernames.empty() || passwords.empty())
        return false;
    bool usernamePassed, passwordPassed; int cnt = 0;
    for (auto c : usernames) {
        if (tempUser == c) {
            usernamePassed = true;
            break;
        }
        else {
            usernamePassed = false;
        }
        ++cnt;
    }
    if (passwords[cnt] == tempPass && cnt < passwords.size()) {
        passwordPassed = true;
    }
    else {
        passwordPassed = false;
    }
    return usernamePassed && passwordPassed;
}


texts: Mutual recursion - Naming the opponent serve - pingpong

texts:
Problem statement
Ping-pong

The ping-pong sequence counts up starting from 1 and is always either counting up or counting down. At element k, the direction switches if k is a multiple of 7 or contains the digit 7. The first 30 elements of the ping-pong sequence are listed below, with direction swaps marked using brackets at the 7th, 14th, 17th, 21st, 27th, and 28th elements:

Implement a function pingpong that returns the nth element of the ping-pong sequence without using any assignment statements.

You may use the function num_sevens, which you defined in the previous question.

Use recursion - the tests will fail if you use any assignment statements.

Hint: If you're stuck, first try implementing pingpong using assignment statements and a while statement. Then, to convert this into a recursive solution, write a helper function that has a parameter for each variable that changes values in the body of the while loop.

def pingpong(n):
    """Return the nth element of the ping-pong sequence.

    >>> pingpong(7)
    7
    >>> pingpong(8)
    6
    >>> pingpong(15)
    1
    >>> pingpong(21)
    -1
    >>> pingpong(22)
    0
    >>> pingpong(30)
    6
    >>> pingpong(68)
    2
    >>> pingpong(69)
    1
    >>> pingpong(70)
    0
    >>> pingpong(71)
    1
    >>> pingpong(72)
    0
    >>> pingpong(100)
    2
    >>> from construct_check import check
    >>> # ban assignment statements
    >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
    True
    """
    "*** YOUR CODE HERE ***"

Solution
package main

import "fmt"

func numSevens(x int) int {
    if x == 0 {
        return 0
    }
    if x%10 == 7 {
        return 1 + numSevens(x/10)
    } else {
        return numSevens(x / 10)
    }
}

func pingPong(n int) int {

    var player1 func(int, int, bool) int
    var player2 func(int, int, bool) int
    player1 = func(currentIndex int, pingPongValue int, receiveOpponentBall bool) int {
        if currentIndex == n {
            return pingPongValue
        }

        if receiveOpponentBall {
            return player1(currentIndex+1, pingPongValue+1, false)
        }

        if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
            return player2(currentIndex, pingPongValue, true)
        }
        return player1(currentIndex+1, pingPongValue+1, false)
    }

    player2 = func(currentIndex int, pingPongValue int, receiveOpponentBall bool) int {
        if currentIndex == n {
            return pingPongValue
        }

        if receiveOpponentBall {
            return player2(currentIndex+1, pingPongValue-1, false)
        }
        if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
            return player1(currentIndex, pingPongValue, true)
        }
        return player2(currentIndex+1, pingPongValue-1, false)
    }

    return player1(1, 1, false)
}

func main() {
    //fmt.Println(numSevens(12345))
    fmt.Println(pingPong(29))
}

Below code is written without using mutual recursion:
func pingPongRecur(n int) int {
    toggleValue := 1 ^ -1
    increment := 1

    var runSequence func(int, int) int
    runSequence = func(currentIndex int, pingPongValue int) int {
        if currentIndex == n {
            return pingPongValue
        }
        if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
            increment ^= toggleValue
        }
        return runSequence(currentIndex+1, pingPongValue+increment)

    }
    return runSequence(1, 1)
}

How to give better name than receiveOpponentBall variable? How to  improve other variable naming convention? based on given problem statement.

Please add improvements in the above code from aspect of readability & good abstraction


texts: generate a file name with format Name(Number).extension

texts:
I am writing a program which downloads a file from a URL. Because the name of the downloaded file depends on the url, there is a risk of duplication if the user downloads the same file twice.

For example if the url is : http://www.example.org/myfile.zip
The downloaded file name will be myfile.zip. and if the user downloads it again the name will be myfile(1).zip

To achieve this, I wrote the following code :

    //A file already exist, we use the usual name
    //but add a number before the extension like "Name(X).extension" X being a number

    //Append the number just before the file extension
    auto pos = name.find_last_of(".");
    std::string nameWithoutExt = name.substr(0, pos);
    std::string extension = name.substr(pos);

    std::ostringstream possibleName;
    int i = 1;
    do
    {
        //Clear the string stream
        possibleName.str("");
        possibleName.clear();
        possibleName<< nameWithoutExt << "(" << std::to_string(i) << ")" << extension;
        ++i;

      //Check if a file with the possible name exists
    } while (std::experimental::filesystem::exists(builder.str()));

    name = builder.str();

This solution does not look optimal to me, because it may require a lot of calls to std::experimental::filesystem::existsfunction. Are there any ways to improve this?


texts: Transform byte array into upside down array of floating point pixels

texts:
I need to do the following in Python 3.x:

Interpret an array of bytes as an array of single-precision floats.
Then group each four consecutive floats into subarrays, i.e. transform [a,b,c,d,e,f,g,h] into [[a,b,c,d], [e,f,g,h]]. The subarrays are called pixels, and the array of pixels forms an image.
Flip the image vertically.

Here is what I have now:

floats = array.array('f')
floats.fromstring(tile_data)
pix = []
for y in range(tile_h - 1, -1, -1):
    stride = tile_w * 4
    start_index = y * stride
    end_index = start_index + stride
    pix.extend(floats[i:i + 4] for i in range(start_index, end_index, 4))

tile_data is the input array of raw bytes, tile_w and tile_h are respectively the width and height of the image, pix is the final upside down image.

While this code works correctly, it takes around 50 ms to complete on my machine for a 256x256 image.

Is there anything obviously slow in this code? Would numpy be a potentially good avenue for optimization?

Edit: here is a standalone program to run the code and measure performance:

import array
import random
import struct
import time

# Size of the problem.
tile_w = 256
tile_h = 256

# Generate input data.
tile_data = []
for f in (random.uniform(0.0, 1.0) for _ in range(tile_w * tile_h * 4)):
    tile_data.extend(struct.pack("f", f))
tile_data = bytes(tile_data)

start_time = time.time()

# Code of interest.
floats = array.array('f')
floats.fromstring(tile_data)
pix = []
for y in range(tile_h - 1, -1, -1):
    stride = tile_w * 4
    start_index = y * stride
    end_index = start_index + stride
    pix.extend(floats[i:i + 4] for i in range(start_index, end_index, 4))

print("runtime: {0} ms".format((time.time() - start_time) * 1000))


texts: Extracting website names from link code cleanup

texts:
I'm working on a program that takes website links and extracts the website name. Right now, it works perfectly, but it is very much a brute force approach and very ugly in my opinion.

Some of the properties of the links are as follows:
- entirely random
- will all contain https:// and .com
- may not contain www.

Here's a random link that I pulled up while shopping to give an example of what I'm talking about. Just to be 100% clear.

https://www.walmart.com/ip/Glencairn-Crystal-Whiskey-Glass-Set-of-2-Hailed-as-The-Official-Whiskey-Glass/183116827

remove 'https://www.'
remove '.com/....827'

result = walmart

And here is the code for it all:

f = open("Links.txt").read().split("\n")
f.remove('')

results = []

for i in f:
    if 'https://' in i:
        results.append(i[8:])

f = results
results = [f[0]]

for i in f:
    if 'www.' in i:
        results.append(i[4:])

f = results
results = []

for i in f:
    results.append(i[:i.find('.com')])

f = open("Results.txt", 'w')

for i in results:
    f.write(i + "\n")

f.close()

I tried cleaning it up with the re module, but it was throwing some errors when trying to search using re.search('www.(.*).com', f).

I was thinking about using the [a:] through [:b] notation in python, but since each link may not have 'www.' it seemed like it would be a faulty solution.

As I mentioned, this code works perfectly well. It's just such a simple thing that I want to get some practice in computer science and make it look like an elegant-ish solution.


texts:
I need to parse logs and have got following code. I can see two problems: map().filter() may induce some performance penalties and copy-paste block

parser.py:

class Info(object):
    a = ""
    j = ""
    z = ""
    infoline = ""

    def __init__(self, a, j, z, infoline):
        self.a = a
        self.j = j
        self.z = z
        self.infoline = infoline

# function check if the line parameter is produced by provider 'prov'
# yes - returns certain substring of line
# no - returns None
def get_infoline(line, prov):
   ...

def process(line, prov):
    retA = None
    retJ = None
    retZ = None

    infoline = get_infoline(line, prov)line param from
    if infoline:
        # filling some of retA, retJ, retZ
        ...
        return Info(retA, retJ, retZ, infoline)

job.py:

from pyspark import SparkContext
import parser

...

prov = ...
log = sc.textFile(pathTofile)
parsed = log.map(lambda ln: parser.proccess(ln, prov)).filter(lambda i: i)

summaryA = parsed.map(lambda info: (info.a, 1)).reduceByKey(add) \
    .map(lambda (a,b): (b,a)).sortByKey(False) \
    .map(lambda (count, name): ("%s\t%i" % (name, count))) \
    .saveAsTextFile('/output/path/a.tsv')

summaryJ = parsed.map(lambda info: (info.j, 1)).reduceByKey(add) \
    .map(lambda (a,b): (b,a)).sortByKey(False) \
    .map(lambda (count, name): ("%s\t%i" % (name, count))) \
    .saveAsTextFile('/output/path/j.tsv')

summaryZ = parsed.map(lambda info: (info.z, 1)).reduceByKey(add) \
    .map(lambda (a,b): (b,a)).sortByKey(False) \
    .map(lambda (count, name): ("%s\t%i" % (name, count))) \
    .saveAsTextFile('/output/path/z.tsv')


texts: Ruby: comparing two Arrays of Hashes and mapping one to the other

texts:
Can you help me to optimize my code for the following problem:

An array of hashes named expected_tasks has tasks. Each task has a user that has to execute an action and contains fields.
The expected_tasks are related to the actual_tasks.
We want to execute the expected_task[action] on the actual_task["id]".
Therefor want to be able to select the actual_task["id"] where all the fields have the same value.

In the end this means that the expected_tasks[0] matches to the actual_tasks[0] because their fields are exactly the same. When their is a match, we can use actual_task["id"].

This is what the data looks like:

#the fields_to_check is an extraction of the keys of the expected_tasks minus user and action
fields_to_check = [ 'field_to_check_1', 'field_to_check_2' ]

expected_tasks = [{ 'user' => 'user',
                     'action' => 'action_y',
                     'field_to_check_1' => 'value_a',
                     'field_to_check_2' => 'value_a' },{
                     'user' => 'user',
                     'action' => 'action_x',
                     'field_to_check_1' => 'value_b',
                     'field_to_check_2' => 'value_b'} ]

sparse_actual_subtasks = [{ 'id' => '1' ,
                     'field_to_check_1' => 'value_b',
                     'field_to_check_2' => 'value_b' },{
                     'id' => '2' ,
                     'field_to_check_1' => 'value_a',
                     'field_to_check_2' => 'value_a' }]

The piece of code to map the id from actual_task to the right action + user from the expected_task:

expected_tasks.each do |expected_task|

  mapped_tasks = []

  actual_task = sparse_actual_subtasks.find do |actual_task|
    fields_to_check.all? do |field|
    expected_task[field] == actual_task[field]
    end
  end

  #map action and user to task with id
  actual_task['action'] = expected_task['action']
  actual_task['user'] = expected_task['user']
  mapped_tasks << actual_task

  puts mapped_tasks

end


texts:
I was hoping someone could provide some feedback with regards to this:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Bank {

    protected double myBalance = 10.40;
    protected double bankBalance = 1000000;
    protected double creditRating = 0.1;
    private static final int PIN = 1234;
    boolean access = false;
    protected Scanner s = new Scanner(System.in);

    public Bank() {

        int pin = 0000;
        int option;

        System.out.print("Please enter your 4 digit pin code: ");
        try {
            pin = s.nextInt();
        } catch (InputMismatchException e) {
            System.out.print("Invalid character entered, bye bye...");
        }

        if (pin != PIN) {
            System.err.println("Incorrect PIN entered, please try again later.");
            System.exit(0);
        }
        access = true;
        System.out.println("Welcome to JCBank please choose from the following options");
        System.out.println();
        System.out.println("Withdraw (1)\tDeposit (2)\tCheck Balance (3)\tApply for Loan(4) \tQuit (5)");
        System.out.println();

        do {
            option = s.nextInt();
        } while(!selectOption(option));
    }

    public boolean selectOption(int option) {
        switch (option) {
            case 1:
                System.out.println("You would like to withdraw");
                System.out.println();
                break;
            case 2:
                System.out.println("You would like to Deposit");
                System.out.println();
                break;
            case 3:
                System.out.println("Your account balance is £" + myBalance);
                System.out.println();
                break;
            case 4:
                System.out.println("Please wait whilst we perform a credit check.");
                try {
                    checkCreditRating();
                } catch (InterruptedException e) {
                    System.out.println("How embarrassing, the system is currently unavailable. Try again later.");
                }
                System.out.println();
                break;
            case 5:
                System.out.println("Successfully logged out, see you soon!");
                System.out.println();
                return true;
            default:
                System.out.println("Invalid option, please choose another option.");
                System.out.println();
                return false;
        }
            System.out.println("Please choose another option.");
            return false;
    }

    public void deposit(double amount) {
        myBalance += amount;
    }

    public void withdraw(double amount) {
        if (myBalance > amount) {
            System.out.println("Your funds have been successfully withdrawn.");
        } else {
            System.out.println("You don't have the funds to complete this transaction");
        }
    }

    public void checkCreditRating() throws InterruptedException {
        Thread.sleep(1000);
        if (creditRating <= 0.0) {
            System.err.println("Sorry, we can't lend you any money at this time.");
            return;
        }

        System.out.print("Please enter your loan amount: ");
        double amount = s.nextDouble();
        if (amount > bankBalance) {
            System.err.println("We are unable to loan you such an amount.");
        }
        double amountToPayBack = (20/100)*amount;
        System.out.println("The amount to payback is " + amountToPayBack);
    }

    public double checkAccountBalance() {
        return myBalance;
    }
}


texts: Scala Play Controller - Refactoring out Duplication for Restful Web Services

texts:
I'm new to scala and I'm noticing I have some repeating code in my controllers.

I'm wondering if anyone can give some hints for traits and parameterization for eliminating duplicate code for basic crud operations on the web services - I'm still a little confused about how to use scala 'generics'/parameters.

Don't mind the json - I've fixed this horrible scrappy code now using the objects to render themselves as json.

Code piece

package controllers

import play.api.mvc._
import securesocial.core._
import play.Logger
import models.{ResponseMessage, GraphedUser}
import com.tinkerpop.blueprints.Vertex
import service.{BaseFramedEntity, SecureSocialUserService, FramedGraphService, GraphDbService}
import play.api.libs.json._
import scala.util.parsing.json
import json.JSONArray
import play.api.libs.concurrent.{Akka, Promise}
import play.api.Play.current
import securesocial.core.UserId
import Predef._
import play.mvc.With

/**
 * Controller for user api
 */
object UsersController extends BaseController with securesocial.core.SecureSocial {

  val collectionName = "users"

  def index = Action {
    implicit request =>
    //get all users

      val pageOption = request.queryString.get("page")

      pageOption match {
        case Some(page) => {
          val resultsPerPageOption = request.queryString.get("numResults")
          resultsPerPageOption match {
            case Some(size) => Ok(renderUserJson(getUserList(page.head.toInt, size.head.toInt))) //Both page and size exists
            case None => Ok(renderUserJson(getUserList(page.head.toInt, defaultPageSize))) //only page exists
          }
        }
        case None => Ok(renderUserJson(getUserList(defaultPage, defaultPageSize))) //page doesn't exist. Ignore size.
      }
  }

  def view(id: String) = Action {
    implicit request =>

      val userOption = FramedGraphService.getFramedVertexByProperty("userId", id, classOf[GraphedUser])

      userOption match {
        case Some(user) => {
          Ok(user.toString)
        }
        case None => InternalServerError("Could not find user")
      }
  }

  def follow(id: String) = SecuredAction(true) {
    implicit request =>

    //Must validate user...
      val currentUserIdentityOption = SecureSocial.currentUser

      currentUserIdentityOption match {
        case Some(currentUser) => {

          val userToFollowOption = FramedGraphService.getFramedVertexByProperty("userId", id, classOf[GraphedUser])

          userToFollowOption match {
            case Some(userToFollow) => {
              GraphDbService.addEdge(null, currentUser.id.id, id, "follows")
              val message = ResponseMessage("ok", "following user: " + id.toString).toJsonString
              Ok(message)
            }
            case None => Ok(ResponseMessage("error", "cannot find user: " + id.toString).toJsonString)
          }
        }
        case None => InternalServerError(ResponseMessage("error", "unknown error").toJsonString)
      }
  }

  private def getUserList(page: Int, size: Int): Iterable[GraphedUser] = {
    val fullUsersList = FramedGraphService.getFramedVerticesByProperty(BaseFramedEntity.TYPE_KEY, GraphedUser.USER_TYPE, classOf[GraphedUser])
    fullUsersList.slice((page - 1) * size, (page - 1) * size + size)
  }

  private def renderUserJson(users: Iterable[GraphedUser]): String = {

    val listToConvert = for (user <- users) yield
      Json.toJson(Map(
        "userId" -> Json.toJson(user.getUserId),
        "graphId" -> Json.toJson(user.asVertex().getId.toString),
        "firstName" -> Json.toJson(user.getFirstName),
        "lastName" -> Json.toJson(user.getLastName),
        "fullName" -> Json.toJson(user.getFullName),
        "providerId" -> Json.toJson(user.getProviderId),
        "firstName" -> Json.toJson(user.getAvatarUrl)))

    val concatenated = listToConvert.foldLeft("")(_ + _)
    surroundJsonWithObject(concatenated, collectionName)
  }
}


texts: First Code, But I Feel It Is So Ugly, Can You Explain Why?

texts:
Question:- Why is this code so ugly ??
This is my first code, it is working fine, but I feel it doesn't looks as standard code … I am still studying java through youtube, as I have just completed two topics language fundamentals and operators and assignments in java.
I have tried to create code that calculates loan on particular date and at particular rate of interest, it takes user inputs.  Please Run This Code At Your IDE.
I have created this code by just knowing two topics or say first two chapters of basic java.

package learningJava;
import java.util.Scanner;

public class Test
{

    public static void main(String[] args)

     {
     Scanner sc = new Scanner (System.in);

    System.out.println("if Days is not calculated just type 0");

    System.out.print("Days: ");

    double day = sc.nextDouble();

    if (day<=0)
    {
    System.out.println("Old Year: ");

    double oldyear = sc.nextDouble();

    System.out.println("Old Month: ");

    double oldmonth = sc.nextDouble();

    System.out.println("Old Date: ");

    double olddate = sc.nextDouble();

    System.out.println("New Year: ");

    double newyear = sc.nextDouble();

    System.out.println("New Month: ");

    double newmonth = sc.nextDouble();

    System.out.println("New Date: ");

    double newdate = sc.nextDouble();

     day = ((newyear*365)+(newmonth*30)+(newdate))-(((oldyear*365)+(oldmonth*30)+(olddate)));

     System.out.println("Days = "+day);

     System.out.print("Principle: ");

     double principle = sc.nextDouble();

     System.out.print("Rate Of Interest: ");

     double rateofinterest = sc.nextDouble();

     double interest = (((principle*(rateofinterest/100))/30)*day);

     System.out.println("--------------------------------");

     System.out.println("Interest = Rs " +interest);

     System.out.println("                                 ");

     System.out.println("Total Amount = Rs " +(principle+interest));

     System.out.println("--------------------------------");

     System.out.println("Thankyou!!");

    }

else
    {

     System.out.print("Principle: ");

     double principle = sc.nextDouble();

     System.out.print("Rate Of Interest: ");

     double rateofinterest = sc.nextDouble();

     double interest = (((principle*(rateofinterest/100))/30)*day);

     System.out.println("--------------------------------");

     System.out.println("Interest = Rs " +interest);

     System.out.println("                                 ");

     System.out.println("Total Amount = Rs " +(principle+interest));

     System.out.println("--------------------------------");

     System.out.println("Thankyou!!");

     }

}

}


texts: Is there a more semantic way to markup Price Lists? Example as Table and as Description List

texts:
I have a pricing list that I can make sense of as both a table and as a description list.  Using a table feels hackish.  I thought a dl might be appropriate because description lists "are useful for displaying metadata as a list of key-value pairs" according to the docs at MDN

As a table

Server Cost

                        2VPU + 4GB Memory

                        $ 0.066666 / hr

                        10 GB Storage Disks

                        $ 0.088888 / hr

                        $0.155554 / hr

Monthly Licensing Cost

                    @0.00 per CPU x 1

                    $ 0.00 / month

As a description list

Server Cost

2VPU + 4GB Memory

$ 0.066666 / hr

10 GB Storage Disks

$ 0.088888 / hr

subtotal

$ 0.155554 / hr

Licensing Cost

@0.00 per CPU x 1

$ 0.00 / month

Here's a codepen with the examples:

http://codepen.io/anon/pen/bAoLe

You can see that they display more or less the same, I'm interested to know what is the more semantic way of representing data like this.


texts: Thread-safe bounded buffer FIFO queue using C++11

texts:
I have started learning multi-threading using C++ 11 and here I have posted the code for thread-safe FIFO queue for multiple producers and consumers.
Though it works fine but I want to know any suggestions,best practices or even any loop hole if you guys can find it.

#ifndef BOUNDEDBUFFER_H
#define BOUNDEDBUFFER_H

#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>

// T must implement operator <<

template< typename T>
class BoundedBuffer
{
public:
    BoundedBuffer(size_t size) :m_size(size), m_front(0), m_rear(-1), m_count(0)
    {
        m_queue = new T[m_size];
    }

    void enqueue( const T& obj )
    {
        std::unique_lock<std::mutex> writerLock(m_mutex);

        while ( m_size == m_count )
        {
            writers.wait(writerLock);
        }
        m_rear = (m_rear + 1) % m_size;
        m_queue[m_rear] = obj;
        ++m_count;
        std::cout << std::this_thread::get_id() << " has Enqueued Object =" << obj << std::endl;
        readers.notify_all();
    }

    void dequeue( T& obj )
    {
        std::unique_lock<std::mutex> readerLock(m_mutex);
        while (0 == m_count)
        {
            readers.wait(readerLock);
        }
        obj = m_queue[m_front];
        m_front = (m_front + 1) % m_size;
        --m_count;
        std::cout << std::this_thread::get_id() << " has Dequeued Object =" << obj << std::endl;
        writers.notify_all();
    }

    ~BoundedBuffer()
    {
        if (m_queue)
        {
            delete[] m_queue;
        }
    }

private:
    size_t m_size;
    T * m_queue;
    int m_front, m_rear, m_count;
    std::mutex m_mutex;
    std::condition_variable readers;
    std::condition_variable writers;
};

#endif


texts: How to reduce execution time for this clustering computation?

texts:
Is there any way to reduce total execution time for the function getSilhouetteIndex? P.S. I am using weka SimpleKMeans for getting kmeans and ceval.

private double getSilhouetteIndex(List<ITSPoI> _POIs, SimpleKMeans kmeans, ClusterEvaluation ceval)
{
    double si_index = 0;
    double[] ca = ceval.getClusterAssignments();
    double[] d_arr = new double[ca.length];
    List<Double> si_indexes = new ArrayList<Double>();

    for (int i=0; i<ca.length; i++)
    {
        // STEP 1. Compute the average distance between the i-th PoI and all other points of a given cluster
        double a = averageDist(_POIs,ca,i,1);

        // STEP 2. Compute the average distance between the i-th PoI and all PoIs of other clusters
        for (int j=0; j<ca.length; j++)
        {
            double d = averageDist(_POIs,ca,j,2);
            d_arr[j] = d;
        }

        // STEP 3. Compute the the distance from the i-th PoI to its nearest cluster to which it does not belong
        double b = d_arr[0];
        for (Double _d : d_arr)
        {
            if (_d < b)
                b = _d;
        }

        // STEP 4. Compute the Silhouette index for the i-th PoI
        double si = (b - a)/Math.max(a,b);
        si_indexes.add(si);
    }

    // STEP 5. Compute the average index over all observations
    double sum = 0;
    for(Double _si : si_indexes)
    {
         sum += _si;
    }
    si_index = sum/si_indexes.size();

    return si_index;
}

private double averageDist(List<ITSPoI> _POIs, double[] ca, int id, int calc)
{
    double avgDist = 0;
    List<ITSPoI> clusterPOIs = new ArrayList<ITSPoI>();

    // Distances inside the cluster
    if (calc == 1)
    {
        for (int i = 0; i<ca.length; i++)
        {
            if (ca[i] == ca[id])
                clusterPOIs.add(_POIs.get(i));
        }
    }
    // Distances outside the cluster
    else
    {
        for (int i = 0; i<ca.length; i++)
        {
            if (ca[i] != ca[id])
                clusterPOIs.add(_POIs.get(i));
        }
    }

    double latx, lonx, laty, lony;
    double[] dist = new double[clusterPOIs.size()];
    latx = _POIs.get(id).getLat();
    lonx = _POIs.get(id).getLon();
    for (int i=0; i<clusterPOIs.size(); i++)
    {
        laty = clusterPOIs.get(i).getLat();
        lony = clusterPOIs.get(i).getLon();
        dist[i] = distanceGeo(latx,lonx,laty,lony);
    }

    double sum = 0;
    for(Double d : dist)
    {
         sum += d;
    }
    avgDist = sum/dist.length;

    return avgDist;
}

private double distanceGeo(double lat1, double lon1, double lat2, double lon2)
{
    if (lat1 == lat2 && lon1 == lon2)
    {
        return 0;
    }
    else
    {
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        return dist;
    }
}


texts:
I have a large image and I am extracting and processing tiles in batches of a given size. A tile is normally a 256x256 region and batches are normally a power of 2.
In the below example the number of tiles per cols is 3 and the number of tiles per rows is 5, and I want batches of 3.

Legend: Yellow rectangle = tile, Red rectangle = batch of tiles, Blue rectangle = full image
Is my code Pythonic enough, can I get extra speed?
import numpy as np
batch_size = 3

input_raster = ... numpy array of shape (3,image_width,image_height)
output_raster = ...numpy array of shape (3,image_width,image_height)
nb_tiles_per_cols = 3
nb_tiles_per_rows = 5

total = nb_tiles_per_cols * nb_tiles_per_rows
remaining = total

for i in range(0,total,batch_size):
    size = min(remaining,batch_size)
    batch_input = np.ndarray((size,256,256,1))
    for j in range(0,size):
        # handle index i+j
        indexRC = i+j
        col = indexRC % nb_tiles_per_cols
        row = indexRC // nb_tiles_per_cols
        # read tile from input raster of shape (3,256*nb_tiles_per_rows,256*nb_tiles_per_cols)
        img = input_raster[:,row*256:(row+1)*256,col*256:(col+1)*256]
        # process img to get input_image
        ...
        batch_input[j] = input_image
    # inference.predict return an array of shape (size,256,256,1)
    predictions = inference.predict(batch_input)

    for j in range(0,size):
        # handle index i+j
        indexRC = i+j
        col = indexRC % nb_tiles_per_cols
        row = indexRC // nb_tiles_per_cols

        output_raster[row*256:(row+1)*256,col*256:(col+1)*256] = predictions[j]

        remaining -= size


texts:
Is there a way make the code better so that it does not have repeated code?

int totalDistance;

if (totalDistance < pow(10, 3)) {
    cout << "\nTotal (approx) travel distance = " << totalDistance << " million km\n" << endl;
}
else if (totalDistance < pow(10, 6)) {
    totalDistance = totalDistance / pow(10, 3);
    cout << "\nTotal (approx) travel distance = " << totalDistance << " billion km\n" << endl;
}
else if (totalDistance < pow(10, 9)) {
    totalDistance = totalDistance / pow(10, 6);
    cout << "\nTotal (approx) travel distance = " << totalDistance << " trillion km\n" << endl;
}

totalDistance is measured in km and minimum distance is million. My main concern is when totalDistance has reached 1,000 or 1,000,000 then instead "million" change to "billion" or "trillion".


texts:
I was tasked this in class today, so the teacher could judge where our skills are.

I am not an experienced C++ programmer, and I made a mistake on my sheet, so I came home and wrote this.

I saw other examples online, but this is the solution I came up with. It works from what I can see, and for these test values.

Did I make any mistakes? How can I improve my coding style and algorithm?

#include <iostream>
#include <string>

    int main()
    {
      int intnumbers[10]= { 10,11, 17,20,37,53,44,88,90,42 };
      for(int i=0;i<10;i++)
      {
         if(intnumbers[i]%2==1){
          if((intnumbers[i]%3==1) || (intnumbers[i]%3==2) )
          {
              std::cout<<intnumbers[i] <<std::endl;      }
         }

      }
      }


texts:
I'd like to find a way to do what this method does in a cleaner, less hacky looking way

 def self.create_from_person!(person)
    spi = new(:person => person, :provider => person.provider)
    spi.age_eligible_code = participant.age_eligible?(person) ? 1 : 2
    spi.county_of_residence_code = participant.psu_county_eligible?(person) ? 1 : 2
    spi.first_prenatal_visit_code = participant.first_visit?(person) ? 1 : 2
    spi.pregnancy_eligible_code = participant.pbs_pregnant?(person) ? 1 : 2
    spi.save!
  end

Any thoughts?


texts: How to shorten this code or make it more efficient?

texts:
How to shorten up this code? I know there's a way that this kind of code could be shortened, but I don't know how by myself yet. Who can help me?

            //CHOOSE LEVEL: FROZEN
case 1213:
    sendOption5("Level 1 " + (c.achievedFloor <= 1 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 2 " + (c.achievedFloor <= 2 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 3 " + (c.achievedFloor <= 3 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 4 " + (c.achievedFloor <= 4 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "More");
    c.dialogueAction = 1213;
    break;
case 1214:
    sendOption5("Level 5 " + (c.achievedFloor <= 5 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 6 " + (c.achievedFloor <= 6 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 7 " + (c.achievedFloor <= 7 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 8 " + (c.achievedFloor <= 8 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "More");
    c.dialogueAction = 1214;
    break;
case 1215:
    sendOption5("Level 9 " + (c.achievedFloor <= 9 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 10 " + (c.achievedFloor <= 10 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "Level 11 " + (c.achievedFloor <= 11 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "",
            "",
            "Choose Floor");
    c.dialogueAction = 1215;
    break;


texts:
I have a small script that checks what the user selects, and based in his selection (1, 2 or 3) show the elements, but I'm not quite happy with the result. I believe that it could be much better the code, and repeat less times, here is my code example.

$(function() {

            //Hide elements
            $('#input').hide();
            $('#textarea').hide();
            $('#option').hide();

            //Show element based on selection
            $('#input_type').change(function(){    // use class or use $('select')

                var option_selected = $(this).val();

                switch(option_selected) {
                    case "1":
                        $('#input').show();
                        $('#textarea').hide();
                        $('#option').hide();

                        break;
                    case "2":
                        $('#textarea').show();
                        $('#input').hide();
                        $('#option').hide();
                        break;
                    case "3":
                        $('#option').show();
                        $('#textarea').hide();
                        $('#input').hide();
                        break;
                    default:
                        $('#input').hide();
                        $('#textarea').hide();
                        $('#option').hide();
                }

            });
        });


texts:
Here's my first effort at reformation: a business letter I wrote for a friend.  I would appreciate a review.  (Yes, I know this is a trivial example and it would be much more beneficial to have something reviewed that is more complicated.  But I want to nip bad practices in the bud now, before they become embedded in me.)

<!DOCTYPE HTML>

            Lopes de Almeido, Evanildo

            Bl&auml;siring 161

            4057 Basel

            01 Dezember, 2012

            Betreff:  Vertretung waehrend Reise

                Sehr geehrte Frau Graf,

                Ich fliege nach Brasilien am 29. Dezember 2012 f&uuml;r 6 Wochen.
                Meine Nichte kann mich vertreten.  Sie arbeitet sehr gesissenhaft.
                Sie heisst Yasmin.  Ihre Nummer ist xxx.

            Freundliche Gr&uuml;sse

            Evanildo Lopes do Almeida

            Hauswart Binningerstrasse 19/23


texts: Repository pattern best practices using EF 6

texts:
I have been Googling for a few days and am trying to find the best practices when it comes to using the Repository pattern.  But what I found that there are no standards and everyone claims that their approach is the best approach.  However, I have come up with this design based on what I have read online.

It it good practice to pass DataContext?  Please feel free to correct me and explain.

I'm using MVC 5 with EF 6.

 public interface IRepository<T> where TEntity  : class
 {
        IEnumerable<TEntity> GetUsers();
        IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate);
        TEntity GetById(int id);
        void Save(TEntity model);
        void Delete(int id);
 }

public class HostRepository : IRepository<HostViewModel>
{
    private EntityDataModelContext db = new EntityDataModelContext();

    //
    public IEnumerable<HostViewModel> GetUsers()
    {
        var userList = from u in db.Hosts select u;
        var users = new List<HostViewModel>();

        if (userList.Any())
        {
            foreach (var user in userList)
            {
                users.Add(new HostViewModel() { Id = user.Id,  FirstName = user.FirstName });
            }

        }
        return users;
    }
    //implement rest here......
 }

//I use an IoC framework to inject the dependencies

public class HostController : Controller
{
    public IRepository<HostViewModel> hostRepository { get; set; }

    public HostController(IRepository<HostViewModel> hostRepo)
    {
        hostRepository = hostRepo;
    }

    public ActionResult Index()
    {
        var users = hostRepository.GetUsers();
        return View(users);
    }
}


texts: Refactor the code which performs "cross-product", "reduce", "product of list" and "sum of list"

texts:
I have come up with a sequence of steps to find the maximum product of y positive numbers which add up to x. But the program is highly inefficient.

Here's my code:

from itertools import product
from functools import reduce
from operator import mul

for i in range(int(input())):               # <-- number of pairs of input
    lgr = 1
    k = set()
    x, y = tuple(map(int, input().split())) #  <-- the input pairs
    p = product(range(1, x+1), repeat=y)    #  <-- gets the cross product
    for i in p:
        if sum(i) == x:                     #  <-- checks if sum is equal to x
            k.add(i)                        #  <-- adds it to a set() to remove duplicates
    for i in k:
        tmp = reduce(mul, i, 1)             #  <-- multiplies the items in the tuple to get the largest
        if tmp > lgr:
            lgr = tmp
    print(lgr)

But say for an input like 14 7 it just takes too long (around 20s). Is there a better way to do it?

Update 1:
I've managed to improve a bit by using combinations_with_replacement and set & list comprehension... but I believe it can be done better... any suggestions...?

from itertools import combinations_with_replacement
from functools import reduce
from operator import mul

for i in range(int(input())):
    lgr = 1
    x, y = tuple(map(int, input().split()))
    k = {i for i in combinations_with_replacement(range(1, x+1), y) if sum(i) == x}
    lgr = max([max(reduce(mul, i, 1), lgr) for i in k])
    print(lgr)


texts: Limit an integer to certain number of digits and suffix '+'

texts:
I am having a problem describing what the following code does. Below is my attempt at its javadoc.

/**
 * Convert an integer so that the notion of its size fits within a certain number digits.
 * e.g.
 * Fit 123 to 2 digits -> 99+
 * @param in The integer
 * @param order The order of magnitude to fit it in.
 * @return The 'countified' String.
 */
public static String countify(int in, int order) {
    final int max = (int) Math.pow(10, order);

    if (in >= max) {
        return String.valueOf(max - 1) + "+";
    } else  {
        return String.valueOf(in);
    }
}

The idea is simple enough. For any value greater than 10^order it returns 10^order - 1 plus a + (e.g. 123, with order 2 becomes 99+), else it returns the number itself. How do I better describe  it? Thanks!


texts: build a Xbonacci function that takes a signature of X elements ,each next element is the sum of the last X elements ,and returns the first n elements

texts:
this is a kata from codewars, here is the description of the kata:
think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more Italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.
Well, guess what? You have to build an Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence.
and this is my solution to it:
function Xbonacci(signature,n){
 let i=0;
  let k = n - signature.length;
   while(k--){
     let sumNums = 0;
     //let newArray = [...signature];
     signature.slice(i , signature.length ).map((num)=>{
      return sumNums += num;
     })

     signature.push(sumNums);
     i++
   }
  return signature;
}

the code works well but it doesn't pass the test because of optimization. Is there any way to make this code faster or more optimized? I think the problem is the slice method but I don't what to use it instead.


texts: JavaScript dynamic element filtering functionality

texts:
I am creating a Website with different boxes being displayed to the user, and he can filter them by their Status (the dates are stored on a Django database). The possible statuses are "Active", "Upcoming" and "Ended".

The filtering works with Radio buttons, so he clicks whichever he likes and all other elements that don't match that description will be hidden.

I am not sure to how elegant this solution is overall. It seems as if I should aim to remove the repetitive structure at the end.

$(function(){

  // Radio buttons functionality
  var displayAllOption = $('#display-all-infos');
  var displayActiveOption = $('#display-active-infos');
  var displayUpcomingOption = $('#display-upcoming-infos');
  var displayEndedOption = $('#display-ended-infos');

  function showAllInfos(){
    $('.info-box').parent().show();
  }

  function hideInfosThatDontMatchOption(selectedOption){

    var infos = $('.info-box').parent();

    [].forEach.call(infos, function(info){
      var countdownContent = $(info).find('.info-box').find('.card-block').find('.countdown').html();

      // Hide every info that has not started, yet, based on the prefix
      // that is displayed at the beginning of the countdown timer
      if (!countdownContent.startsWith(selectedOption)){
        $(info).hide();
      }
    });
  }

  /*
     First lines change the Color highlighting by toggling the 'active' class

     Filter Logic: Make sure all info boxes are displayed at the beginning, and then
     hide all the info boxes that the User doesn't want to see
  */

  displayAllOption.on('click', function(){
    showAllInfos();
  });

  displayActiveOption.on('click', function(element){

    displayActiveOption.addClass('active')
    displayUpcomingOption.removeClass('active')
    displayEndedOption.removeClass('active')

    showAllInfos();
    hideInfosThatDontMatchOption('Time Left')
  });

  displayUpcomingOption.on('click', function(element){

    displayUpcomingOption.addClass('active')
    displayActiveOption.removeClass('active')
    displayEndedOption.removeClass('active')

    showAllInfos();
    hideinfosThatDontMatchOption('Starts In')
  });

  displayEndedOption.on('click', function(element){

    displayEndedOption.addClass('active')
    displayActiveOption.removeClass('active')
    displayUpcomingOption.removeClass('active')

    showAllInfos();
    hideInfosThatDontMatchOption('Ended')
  });

});

Here is the Radio Button HTML snippet:

        <input type="radio" name="options" autocomplete="off" checked> All

        <input type="radio" name="options" autocomplete="off" checked> Active

        <input type="radio" name="options" autocomplete="off"> Upcoming

        <input type="radio" name="options" autocomplete="off"> Ended

I'd appreciate all feedback telling me how I can improve it.

Thanks in Advance!


texts: Parse a search condition into an expression tree

texts:
I had to implement a parser according to a given grammar as part of a school project. However, only the program execution was graded and I want to know if my code adheres to best practices. I would really appreciate it if you could give me pointers on how to improve my code.

Search conditions are of the form: a + b < 10 OR c = 1. The following code parses the search condition into an expression tree. The input to the function is a vector of the tokens in the search condition.

void recursiveSplit(node *parent, vector<string> const &tokens, string delimiter) {
    /* Given a string, parse it into an expression tree with nodes as the
     * operators and the children as the operands */
    if (tokens.size() == 1) {
        /* Base case for the recursion, the leaf nodes are either strings or
         * integers */
        node *mathNode;
        mathNode = new node(tokens[0]);
        parent->subTree.push_back(mathNode);
        return;
    } else {
        vector<string>::const_iterator it;
        for (it = tokens.begin(); it != tokens.end(); it++) {
            if (*it == delimiter) {
                break;
            }
        }
        if (it != tokens.end()) {
            /* Case 1 :delimiter was found */
            node *delimNode;
            delimNode = new node(delimiter);
            parent->subTree.push_back(delimNode);
            vector<string> leftTokens(tokens.begin(), it), rightTokens(it+1, tokens.end());
            string newDelimiter = switchDelimiter(delimiter);
            recursiveSplit(delimNode, leftTokens, newDelimiter);
            /* In rightTokens, we still need to search for the current
             * delimiter since we may have multiple instances of the delimiter
             * */
            recursiveSplit(delimNode, rightTokens, delimiter);
        } else {
            // delimiter is not found
            string newDelimiter = switchDelimiter(delimiter);
            recursiveSplit(parent, tokens, newDelimiter);
        }
    }
}

string switchDelimiter(string delimiter) {
    /* Return the next delimiter based on the priority. The priority of
     * operations is : OR, AND, <, >, =, +, -, * */
    char delim;
    if (delimiter == "OR") {
        delim = '|';
    } else if (delimiter == "AND") {
        delim = '&';
    } else {
        delim = delimiter[0];
    }

    switch(delim) {
        case '|':
            return "AND";
        case '&':
            return "<";
        case '<':
            return ">";
        case '>':
            return "=";
        case '=':
            return "+";
        case '+':
            return "-";
        case '-':
            return "*";
        case '*':
            return " ";
    }
}

node *createTree(const string& searchStrBuf) {
    string buf;
    stringstream ss(searchStrBuf);
    vector<string> tokens;
    while(ss >> buf) {
        if ((buf != ")") && (buf != "(")) {
            tokens.push_back(buf);
        }
    }
    node *root = new node("searchTreeRoot");
    recursiveSplit(root, tokens, "OR");
    return root;
}

class node {
    public:
    string nodeType;
    vector<node *> subTree;

    node(string strNodeType) {
        nodeType = strNodeType;
    }
};


texts: Circular Linked List implementation in C++

texts:
I want to improve this code.

#include <iostream>
#include <utility>

template <class T>
class circular_linked_list
{
  struct Node
  {
    T data;
    Node * next;
    Node(T value) : data(std::move(value)), next(nullptr) {}
  };
  Node *head;

public:
  circular_linked_list() : head(nullptr) {}
  circular_linked_list(const circular_linked_list& cll) = delete; //copy constructor
  circular_linked_list(circular_linked_list&& cll) = delete; //move constructor
  circular_linked_list& operator=(const circular_linked_list& cll) = delete; //copy assignment
  circular_linked_list& operator=(circular_linked_list&& cll) = delete; //move assignment
  ~circular_linked_list();
  void insert_at_begin(T);
  void insert_at_end(T);
  void delete_node(T);
  void print_list();

private:
  struct Node *search(T value)
  {
    Node *node = head;
    while(node->next != head)
    {
      if(node->data == value)
        return node;

      node = node->next;
    }
    std::cerr << "No such element in the List \n";
    return nullptr;
  }
};

template <class T>
void circular_linked_list<T>::insert_at_begin(T value)
{
  Node *node = new Node(std::move(value));
  if(head == nullptr)
  {
    node->next = node;
    head = node;
    return;
  }
  Node *tmp = head;
  while(tmp->next != head)
  {
    tmp = tmp->next;
  }
  tmp->next = node;
  node->next = head;
  head = node;
}

template <class T>
void circular_linked_list<T>::insert_at_end(T value)
{
  Node *node = new Node(std::move(value));
  if(head == nullptr)
  {
    node->next = node;
    head = node;
    return;
  }
  Node *tmp = head;
  while(tmp->next != head)
  {
    tmp = tmp->next;
  }
  tmp->next = node;
  node->next = head;
}

template <class T>
void circular_linked_list<T>::delete_node(T value)
{
  Node *node = search(value);
  Node *tmp = head;
  Node *tail = head;
  while(tail->next != head)
  {
    tail = tail->next;
  }

  if(tmp == node)
  {
    head = tmp->next; //deleting first element
    tail->next = head;
  }
  else
  {
    while(node != nullptr)
    {
      if(tmp->next == node)
      {
        tmp->next = node->next;
        return;
      }
      tmp = tmp->next;
    }
  }
  delete tmp;
}

template <class T>
void circular_linked_list<T>::print_list()
{
  Node *tmp = head;
  while(tmp->next != head)
  {
    std::cout << tmp->data << ' ';
    tmp = tmp->next;
  }
  std::cout << tmp->data << '\n';
}

template <class T>
circular_linked_list<T>::~circular_linked_list()
{
  Node *tmp = nullptr;
  Node *tail = head;
  while(tail->next != head)
  {
    tail = tail->next;
  }
  tail->next = nullptr;

  while(head != nullptr)
  {
    tmp = head;
    head = head->next;
    delete tmp;
  }
}

int main()
{
  circular_linked_list<int> cll1;
  cll1.insert_at_end(2);
  cll1.insert_at_end(3);
  cll1.insert_at_end(4);
  cll1.insert_at_begin(1);
  cll1.insert_at_begin(0);
  cll1.print_list();
  cll1.delete_node(2);
  cll1.print_list();
}


texts: RFID card reader validation routine in 8051 assembly

texts:
I came up with the following code to check to see if the last 2 bytes of a 12-byte value read in from a RDM6300 card reader is actually the checksum of the first 10 bytes.

  ;card sample data out in decimal: 88003FF259 1C
  ;in hex: 38h,38h,30h,30h,33h,46h,46h,32h,35h,39h  31h,43h

  ;main entry point here
  rfidvalidate:
;Wrecks R3,R2,R1,A. Returns: C=0=OK,1=bad

clr A           ;clear accumulator (used to calculate checksum)
mov R2,#6h      ;read 6 pairs of hex digits...
mov R1,#RFIDPSTART+1    ;starting at memory location R1 (start of data)
readbytes:
  push ACC      ;save accumulator
  lcall rfid2asc    ;read and convert hex character to binary equivalent
  mov A,R3      ;store it for now
  lcall rfid2asc    ;read and convert next hex character to binary equivalent
  swap A        ;1st hex character was high byte.
  orl A,R3      ;append 2nd hex character to make real byte
  mov R3,A      ;hold onto the byte
  pop ACC       ;restore checksum accumulator
  xrl A,R3      ;and xor checksum with new value received
djnz R2,readbytes   ;keep going until all 6 pairs of hex digits are read
clr C           ;assume everything is OK
jz rfidcsum     ;if after all xor operations, value is zero, there's no error
  setb C        ;here we indicate error (C=1)
rfidcsum:
  ret

  rfid2asc:
push ACC        ;save accumulator again to prevent high byte from corruption
mov A,@R1       ;get hex character (value is 30h through 39h or 41h through 46h)...
inc R1          ;and advance pointer
clr C           ;clear carry...
subb A,#30h         ;so subtract won't subtract #31h
anl A,#01Fh         ;force result to lower 5 bits **
jnb ACC.4,noa2f     ;if 5th bit is set then value is Ah through Fh...
  anl A,#0Fh        ;only accept low nibble **
  add A,#9h     ;and add 9 to the result to get proper value
noa2f:
anl A,#0Fh      ;only accept low nibble again **
mov R3,A        ;and save result
pop ACC         ;so that our old accumulator restores.
  ret

  ;** starred comments represent extra code I put in to increase sanity
  ; (incase the reader hardware breaks)

My card reader I bought on ebay is based on the RDM6300 protocol and a link to the data format is found here: https://www.scribd.com/document/234332424/RDM6300

Can this code somehow be improved so that it takes up less space, runs with fewer clock cycles and uses fewer registers and takes up less memory? The only thing OK with taking up memory is the data space for the 12 incoming characters.


texts: Haskell - Caching third party API token across requests

texts:
The following code is designed to cache a (UTCTime, Text) value that keeps the Text token around until it expires, preventing needing to re-fetch the token each time this third party API is called. I feel like this duplication in APIDefaults and APIEnv could be removed, perhaps through a type parameter, though there may be a better way of doing this than storing the MVar inside APIDefaults.

APIError and getApiToken are just stubbed out as their detail is not relevant here, but in my code these are not implemented as they are below, so you can just ignore those.

data APIDefaults = APIDefaults
  { apidefManager :: Manager
  , apidefPool :: ConnectionPool
  , apidefTokenRef :: MVar (UTCTime, Text)
  }

data APIEnv = APIEnv
  { apienvManager :: Manager
  , apienvPool :: ConnectionPool
  , apienvToken :: Text
  }

data APIToken = APIToken
  { apiTokenAccessToken :: Text
  , apiTokenExpiresIn :: Int
  }

data APIError

fireApiRequest
  :: MonadLogger m
  => MonadUnliftIO m
  => ReaderT APIEnv m (Either APIError a)
  -> ReaderT APIDefaults m (Either APIError a)
fireApiRequest req = runExceptT $ do
  env <- do
    t <- lift readCachedToken
    case t of
      Nothing -> fetchToken
      Just (savedExpiry, token) -> lift $ do
        updateTokenRef (savedExpiry, token)
        apd <- ask
        return (createAPIEnv apd token)
  ExceptT $ lift (runReaderT req env)

readCachedToken
  :: MonadUnliftIO m
  => ReaderT APIDefaults m (Maybe (UTCTime, Text))
readCachedToken = runMaybeT $ do
  mv <- lift (asks apidefTokenRef)
  (savedExpiry, token) <- MaybeT $ liftIO (tryTakeMVar mv)
  now <- getCurrentTime
  guard (savedExpiry > now)
  return (savedExpiry, token)

updateTokenRef
  :: MonadUnliftIO m
  => (UTCTime, Text)
  -> ReaderT APIDefaults m ()
updateTokenRef value = do
  tokenRef <- asks apidefTokenRef
  void $ liftIO (tryPutMVar tokenRef value)

fetchToken
  :: MonadLogger m
  => MonadUnliftIO m
  => ExceptT APIError (ReaderT APIDefaults m) APIEnv
fetchToken = do
  now <- getCurrentTime
  adef <- lift ask
  token <- getApiToken
  let expiration = addUTCTime (fromIntegral $ apiTokenExpiresIn token) now
  lift $ updateTokenRef (expiration, apiTokenAccessToken token)
  return $ createAPIEnv adef (apiTokenAccessToken token)

getApiToken :: Monad m => m APIToken
getApiToken =
  return undefined

createAPIEnv :: APIDefaults -> Text -> APIEnv
createAPIEnv adef token =
  APIEnv (apidefManager adef) (apidefPool adef) token


texts:
My method for sending emails with Send() is getting very slow when I send more than ten messages.
Sample

1 (1 sec)
2 (2 sec)
3 (4 sec)
4 (8 sec) and so on...

so I started to try SendAsync()
public Boolean sendSMTPMail(string subject, string body, customer[] recipients, string attachmentFileName = null)
{
    string css = "<style>*{font-family: Arial, Helvetica, sans-serif;}</style>";
    SmtpClient client = new SmtpClient();
    //some client settings..

    MailMessage mm = new MailMessage();
    mm.IsBodyHtml = true;
    mm.From = new MailAddress(MainForm.from, MainForm.fromName, Encoding.UTF8);
    mm.Subject = subject;

    foreach (var recipient in recipients)
    {
        Application.DoEvents();
        mm.To.Clear();
        mm.To.Add(new MailAddress(recipient.getEmail()));
        mm.AlternateViews.Add(getEmbeddedImages(css + doReplacements(body, recipient)));

        try
        {
            //client.Send(mm);
            client.SendAsync(mm, "userToken");
            //client.SendMailAsync(mm);
        }
        catch (Exception)
        {
            return false;
        }
    }
    return true;
}

Additional Information about my methods:
getEmbeddedImages replaces imagePath with needed cid:xxxx and adds the image so it can be sent as a part of the email and not only as attachment.
doReplacements replaces strings in my body to get the email text more recipient specific:
Hello my name is %name%,
I am %age% years old.

will be translated to
Hello my name is John Doe,
I am 100 years old.

Questions:

Is this the right way to do it?
Is it important to send different userTokens?
For what is this token needed anyway? Obviously it doesn't matter what I fill in there.


texts:
I'm taking an AI Class and I managed to get my algorithm to work it's not complex since the robot is surrounded and placed by the wall. However, in my opinion, the code doesn't look so clean and I would like to have multiple functions in my Wall_Following() to make it look nicer. I've never programmed in Python before so I don't have much experience. I would like my function to look something like this:

def Wall_Follow(self)
 forward()
 if( front sensor > 150) # turns left if the front hits a wall
   Turn_left()
 elif(right sensor < 150) # turns right if too far away from wall
   Turn_Right()
 return left, right

This is my original code. Any feedback would be most appreciated on whether I'm just making this too complicated for myself.

def Wall_Follow(self):
 # default left/right values:
 left = self.MAX_SPEED * 0.8
 right = self.MAX_SPEED * 0.8

 if(self.ps_val[0] > 150
 or self.ps_val[7] > 150):
  left = -self.MAX_SPEED/2   #turn left

 elif(self.ps_val[2] < 150):
  right = -self.MAX_SPEED/2   #turn right

 return left,right

def run(self):

# Main loop
 while True:
  # Perform a simulation step of 64 milliseconds
  # and leave the loop when the simulation is over
   if self.step(self.TIME_STEP) == -1:
     break

   # functions to read sensor data
   self.read_sensors()

   # Process sensor data here.
   left, right = self.Wall_Follow()

   # Enter here functions to send actuator commands

   self.setSpeed(left, right)

controller = PyController()
controller.run()