texts:
Here is my code:

defmodule LineScanner do
    @spec scan(String.t()) :: [Token.t()]
    def scan(line) when is_binary(line), do: scan_(line, {[], ""}) |> Enum.reverse()

### The function below needs some refactoring ######

    @spec scan_(String.t(), {[Token.t()], binary()}) :: [Token.t()]
    def scan_(line, {acc, fragments}) when is_binary(line) do
        case token(line, fragments) do
            {nil, "", f} -> [%TextNode{text: f} | acc]
            {nil, rest, f} -> scan_(rest, {acc, f})
            {t, "", ""} -> [t | acc]
            {t, "", f} -> [t | [%TextNode{text: f} | acc]]
            {t, rest, "" = f} -> scan_(rest, {[t | acc], f})
            {t, rest, f} -> scan_(rest, {[t | [%TextNode{text: f} | acc]], ""})
        end
    end

#####################################################

    @spec token(String.t(), binary()) :: {Token.t(), String.t()}
    def token(<<c::utf8, rest::binary>>, fragments) do
          case c do
              ?# -> {%Header{}, rest, fragments}
              ?> -> {%BlockQuoteCaret{}, rest, fragments}
              x when x in [?-, ?*] -> {%Bullet{}, rest, fragments}
              ?` -> {%BackTick{}, rest, fragments}
              _ = cp -> {nil, rest, fragments <> <<cp>>}
          end
    end
end

A brief synopsis. I'm building a scanner for Markdown syntax. It needs to pick up significant tokens but also intermediary text fragments.

Given that token() returns a 3-tuple, my case statement will need to test 2^3 combination. Since the nil case only ever returns a non-empty string, 2 of those are automatically eliminated, leaving the 6 below. But it is still rather clunky. This is what's going on:

A text fragment exists, but the end of the line has been reached.
RETURN: the accumulator + text node
A text fragment exists
RETURN: another call to scan
A token has been found at the end of the line.
RETURN: the accumulator + token
A token has been found at the end of the line AND a text fragment exists.
RETURN: The accumulator + text node + token
A token has been found and there is not fragment
RETURN: another call to scan with the new token added to the accumulator
A token has been found AND there is a text fragment
RETURN: another call to scan with the token and text node added to the accumulator

I'm racking my brain to figure out how to slim this down, but every case seems significant. Please help.


texts: Checking for a condition, even if it's always true

texts:
In my program there is the following piece of code where I must delete a ' ' from the second to last index in a StringBuilder:

builder.deleteCharAt(builder.length() - 2);

I do not surround it with checks to either condition builder.length() >= 2 or builder.charAt(builder.length() - 2) == ' '), because I am 100% sure that both these conditions will always be true, even though at first glance, it is not so obvious.

I'm torn between feeling that just because I have a higher understanding of the code, doesn't mean I should neglect the conditions for the sake of others in the team. But at the same time, if I do check for these conditions, it would be absolutely unnecessary.

My solution is to simply add a comment, but I was wondering if is this considered to be good practice?

builder.deleteCharAt(builder.length() - 2); // should always be ' '


texts: Return new thymeleaf page from controller

texts:
0

I have a web app built using Spring boot and thymeleaf. I have used only the index page so far which has different models in it and it work just fine.

Now I want to add a new page. By new page I mean in the url it says http://localhost:8081/app/index

Now I have added a dropdown on the page Let's say About Us. When I try to do that it stays on that page and don't do much or it takes me to logout page, here is my code:

In Thymeleaf index page:

Change Password

What's New

                Sign Out

About Us

In javascript:

   function loadAboutUs() {
   $.ajax({
     type: "GET",
     url: "/app/aboutUs/",
     cache: false,
     timeout: 100000,
     success: function (result) {
     console.log("Success",result);
     $("#mainBody").html(result);

     // Trying below takes me to logout page
      window.location.href = "/app/aboutUs";

     },
    error: function (e) {
      window.location = "/app/login";
      console.log("ERROR: ", e);
     },
   done: function (e) {
      console.log("DONE");
     },
   });
  }

In my controller:

 @RequestMapping(value = "/aboutUs", method = RequestMethod.GET)
public ModelAndView aboutUs(HttpServletRequest request, Model model, HttpServletResponse
 response) throws Exception {
session = request.getSession(false);
return new ModelAndView("th_aboutUs");

}

I have a SecurityConfiguration file which has the below function and I added the Url pattern in it if in case it is effecting it:

     @Override
 public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers("/","/images/**",
     "/login**","/callback/","/**/*.js","/**/*.css","/**/*.scss","/**/*.map");
  }

@Bean
 public FilterRegistrationBean<SessionFilter> loggingFilter(){
   FilterRegistrationBean<SessionFilter> registrationBean
        = new FilterRegistrationBean<>();

registrationBean.setFilter(new SessionFilter());
registrationBean.addUrlPatterns("/index/*");
registrationBean.addUrlPatterns("/aboutUs/*");

return registrationBean;

}

Would somebody please guide me what is going on?


texts: Printing every 10th result in an alternating ± series

texts:
Problem:

In the following expression 1-2+3-4+5-6 ... -98+99-100, print result every 10th (10, 20, 30, ...) calculation.

My code:

result  = 0
operand = 1
counter = 0
for i in range(1, 101):
    result = result + (i * operand)
    counter = counter + 1
    operand = operand *  -1 #Convert between positive and negative number
    if counter >= 10:
        counter = 0
        print(result)

My problem:

I think this code has not good readability. For example, I used * -1 for changing positive and negative number. But it requires math skill(multiplying a negative number) to understand code.

And I don't sure variable name 'counter' and 'operand' is appropriate for this context.

Is there any suggestion?


texts: Reverse Polish Notation evaluator in Haskell

texts:
I've created an RPN evaluator in Haskell, as an exercise because I'm new to this language.

It runs well:

$ ./rpn
2 3 4 5 + - +
-4

And the source code:

{-# LANGUAGE BangPatterns #-}
import Data.String
import System.IO

data Token = TNum Int | TOp Operator
data Operator = Add | Sub | Mul | Div

main :: IO ()
main = do
    line <- getLine
    let tokens      = tokenise line
        (numc, opc) = countTok tokens
        !junk       =
            if numc == opc + 1
                then ()
                else error "Not a correct expression."
    print $ eval [] tokens

tokenise :: String -> [Token]
tokenise = map str2tok . words

eval :: [Int] -> [Token] -> Int
eval (s:_) []                   = s
eval stack (TNum t:ts)          = eval (t : stack) ts
eval (x:y:stacknoxy) (TOp t:ts) = eval (applyOp t y x : stacknoxy) ts

str2tok :: String -> Token
str2tok tkn@(c:_)
    | c `elem` ['0'..'9'] = TNum (read tkn :: Int)
    | otherwise = TOp $ case tkn of
        "+" -> Add
        "-" -> Sub
        "*" -> Mul
        "/" -> Div
        _   -> error $ "No such operator " ++ tkn

applyOp :: Operator -> Int -> Int -> Int
applyOp Add a b = a + b
applyOp Sub a b = a - b
applyOp Mul a b = a * b
applyOp Div a b = a `div` b

countTok :: [Token] -> (Int, Int)
countTok [] = (0, 0)
countTok (t:ts) =
    let (x, y) = case t of
            TNum _ -> (1, 0)
            _      -> (0, 1)
     in (x, y) `addPair` countTok ts

addPair :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b)
addPair (x, y) (z, w) = (x + z, y + w)

How can this code be improved? I hope my implementation is elegant, and if it isn't - what are the ways to clean it up?  In particular, I really don't like the errors because they're just ugly:

./rpn
5 6 + +
rpn: Not a correct expression.
CallStack (from HasCallStack):
  error, called at rpn.hs:16:22 in main:Main

I know they can be replaced with fail, which has a much nicer output, but from what I've read it can only be done inside a function that returns IO ().


texts: Checking for a win along the top row of a Tic Tac Toe board

texts:
This code works so far and it is a TicTacToe game (Personal Project of Mine). I'm kinda new to programming. My question is I really do not like how the Connected method is at all, because well it's fairly large for no reason. Is there a way to make it more compact because I have to add the middle and bottom row then do the vertical columns then do the diagonal lines and that will make method very big so what do you guys think?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by Usman on 5/17/2016.
 */
public class TicTacToeGUI extends JPanel {

    boolean turn = true;
    JButton[] board;

    public TicTacToeGUI() {
        setLayout(new GridLayout(3,3));

        board = new JButton[9];
        for (int i = 0; i < board.length; i++) {
            board[i] = new JButton("");
            board[i].setPreferredSize(new Dimension(70, 60));
            board[i].setFont(new Font("Arial", Font.PLAIN, 40));
            int finalI = i;
            board[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                    if(board[finalI].isEnabled()){
                        if(turn){
                            board[finalI].setText("X");
                            turn = false;
                        }
                        else{
                            board[finalI].setText("O");
                            turn = true;
                        }
                        board[finalI].setEnabled(false);
                    }
                    Connected();
                }
            });
            add(board[i]);
        }
    }
    public void Connected(){
        //Horizontal top row
        if((!board[0].isEnabled()) || (!board[1].isEnabled()) || (!board[2].isEnabled())){
            if((board[0].getText() == board[1].getText()) && (board[0].getText() == board[2].getText())){
                if((!board[0].isEnabled()) == (!board[1].isEnabled()) == (!board[2].isEnabled())){
                    JOptionPane.showMessageDialog(null, "You've Won The Game!");
                }
            }
        }
    }
    public static void main(String []args){
        TicTacToeGUI game = new TicTacToeGUI();
        JFrame frame = new JFrame("Tic Tac Toe");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(game);
        frame.pack();
        frame.setVisible(true);
    }
}


texts: Search string by regex in files and write line of found string

texts:
I am searching in files with extensions .xml, .java, and .properties strings that match a certain regular expression.

When I find it, I write it to the file with the filename, line and string information.

def search(param):
    filename = "search-result.txt"
    try:
        os.remove(filename)
    except OSError:
        pass
    os.path.walk(param, step, None)

def step(ext, dirname, names):
    output = open("search-result.txt", "a")
    for name in names:
        if name.lower().endswith(".xml") or name.lower().endswith(".properties") or name.lower().endswith(".java"):
            path = os.path.join(dirname, name)
            filters = ["\\bin\\", "\\build\\", "logback", "\\test\\", "\\target\\"]
            if all(not filter in path for filter in filters):
                with open(path, "r") as lines:
                    print "Read: {}".format(path)
                    i = 1
                    for line in lines:
                        m = re.search(r"(!|$|RUP)\{[^:]*:[^\}]*\}", line)
                        if m is not None:
                            output.write("Path: {0}; \n    Line number: {1}; \n        {2}\n".format(path, i, line))
                        i += 1
    output.close()

I divided it into two functions - search, where I can check where result file is existed and remove it, and then step for os.path.walk. Param is a folder to search in.

How can this code be adjusted to look better?


texts:
I want to write a header file for c++. When included in a program, the header file overloads the new and delete operators so that it can count the number of allocations and deallocations. The header file will also print out the number of allocations and deallocations when the program exits. Is this the proper way to go about doing that? Will this code cause any problems or leave any gaps? The header file is only meant to be included when debugging.

#pragma once
#include <cstdint>
#include <cstdlib>

size_t __allocations = 0;
void* operator new(std::size_t sz) {
    ++__allocations;
    return std::malloc(sz);
}

size_t __array_allocations = 0;
void* operator new[](std::size_t sz) {
    ++__array_allocations;
    return std::malloc(sz);
}
size_t __deallocations = 0;
void operator delete(void* ptr) noexcept
{
    ++__deallocations;
    std::free(ptr);
}
size_t __array_deallocations = 0;
void operator delete[](void* ptr) noexcept
{
    ++__array_deallocations;
    std::free(ptr);
}

#include <iostream>
struct EnsureOutput
{
    ~EnsureOutput()
    {
        using namespace std;
        cout << "Allocations:   " << __allocations << endl;
        cout << "Deallocations: " << __deallocations << endl;
        cout << "Array Allocations:   " << __array_allocations << endl;
        cout << "Array Deallocations: " << __array_deallocations << endl;
        if(__allocations == __deallocations && __array_deallocations == __array_deallocations)
        {
            cout << "No leaks discovered" << endl;
        }
        else
        {
            cout << "You have a memory leak." << endl;
        }
    }
};
EnsureOutput o = {};


texts: Implementation of the linked list data structure in C++

texts:
How is this designed so far?

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <memory>
#include <iostream>

template <typename T> using ptr = std::shared_ptr<T>;

template <typename V>
class LinkedList
{
private:
    class Node
    {
    private:
        V data;
        ptr<Node> next;
    public:
        Node() : next{} {}
        Node(V _data) : next{}, data{_data} {}
        ptr<Node>& getNext(){
            return this->next;
        }
        V getData(){
            return this->data;
        }
    };

    ptr<Node> head;
    ptr<Node> tail;
    size_t _size;

public:

    LinkedList() : head{}, tail {}, _size{} {}

    void add(V _data){
        auto _tmp = std::make_shared<Node>(_data);
        if(isEmpty()){
            head = _tmp;
            tail = _tmp;
        } else {
            tail->getNext() = _tmp;
            tail = _tmp;
        }
        _size++;
    }

    bool isEmpty(){
        if(head == nullptr) return true;
        else return false;
    }

    V operator[](int index){
        int _c {};
        ptr<Node> tmp = head;
        while(tmp!=nullptr){
            if(_c == index){
                break;
            }
            tmp = tmp->getNext();
            _c++;
        }
        return tmp->getData();
    }

    void addFirst(V _data){
        auto _tmp = std::make_shared<Node>(_data);
        if(isEmpty()){
            _tmp->getNext() = head;
            head = _tmp;
            tail = _tmp;
        } else {
            _tmp->getNext() = head;
            head = _tmp;
        }
        _size++;
    }

    template <typename V>
    void insertAfter(int index, V _data){

        auto _tmp = std::make_shared<Node>(_data);
        std::shared_ptr<Node> _curr;
        std::shared_ptr<Node> _afterIndex;

        if(index<0 || index > size()-1){std::cerr << "__INDEX_OUT_OF_RANGE__" << std::endl;}
        else {
            int _c {};
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                if(_c == index){
                     _curr = tmp;
                     _afterIndex = _curr->getNext();
                     break;
                }
                tmp = tmp->getNext();
                _c++;
            }

            _curr->getNext() = _tmp;
            _tmp->getNext() = _afterIndex;
            _size++;
        }
    }

    void traverseList(){
        {
            ptr<Node> tmp = head;
            while(tmp!=nullptr){
                std::cout << tmp->getData() << std::endl;
                tmp = tmp->getNext();
            }
        }

    }

    size_t size(){ return _size; }
};

#endif // LINKEDLIST_H

#include "linkedlist.h"
#include <string>
int main(){

    auto list = std::make_shared<LinkedList<std::string>>();

    list->addFirst("Bob");
    list->add("Carl");
    list->add("Mario");
    list->add("Elliot");
    list->addFirst("Neo");
    list->insertAfter(0,"I'm inserted after " + (*list)[0]);

    for (int i {} ; i < list->size(); ++i) {
        std::cout << (*list)[i] << std::endl;
    }

    return 0;
}


texts: dput() concatenated vector with no quotes, separated by commas in R

texts:
An oddly specific task - I have a dataframe with columns with values I need to concatenate in order to prepare a query for a website that requires very specific inputs: unquoted strings, separated by commas.  Here's a dput() of a subset of the dataframe with the columns needed:

d = structure(list(CodeSpace = c(1303L, 1303L, 1303L, 1303L, 1303L,
1303L), TagID = c(23041L, 23042L, 23044L, 23046L, 23043L, 23045L
)), class = "data.frame", row.names = c(NA, -6L))

The output I need is:

A69-1303-23041, A69-1303-23042, A69-1303-23044, A69-1303-23046, A69-1303-23043, A69-1303-23045

I can approximate it (though I end up with a trailing comma) with:

cat(paste0(noquote(paste("A69", d$CodeSpace, d$TagID, sep = "-")) , ","))

Is there a better (i.e. more principled) way to do this?


texts: Unit test an ExecutorService in a deamon

texts:
To execute tasks sequentially with a timeout I use ExecutorService.submit() and Future.get(). As I don't want to block calling clients, I implement producer–consumer pattern with a queue into a Thread while(true) loop:

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExecutorWithQueue {
    private int timeout = 1;
    private TimeUnit timeoutUnit = TimeUnit.SECONDS;
    private LinkedBlockingQueue<Task> queue = new LinkedBlockingQueue<Task>();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    private TaskProcessor taskProcessor = new TaskProcessor();

    public ExecutorWithQueue(int timeout, TimeUnit timeoutUnit)
    {
        this.timeout = timeout;
        this.timeoutUnit = timeoutUnit;

        taskProcessor.start();
    }

    public void push(Task task)
    {
        queue.add(task);
    }

    class TaskProcessor extends Thread
    {
        public void run() {
            while (true)
            {
                try
                {
                    final Task queueTask = queue.take();
                    Future<Boolean> future = executor.submit(queueTask);

                    try {
                        future.get(timeout, timeoutUnit);
                    } catch (TimeoutException e) {
                        System.out.println("TimeoutException");
                    }
                    catch (ExecutionException e)
                    {
                        System.out.println("ExecutionException");
                    }
                }
                catch (InterruptedException e)
                {
                    break;
                }
            }
            executor.shutdownNow();
        }
    }
}

I have two unit tests. The first to check if task is executed, the second to check that a task that takes two long doesn't block the execution flow:

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class TestExecutorWithQueue {

    ExecutorWithQueue executor = new ExecutorWithQueue(9, MILLISECONDS);

    @Test public void fastTaskIsExecuted() throws Exception {
        assertExecuted(0, true);
    }

    @Test public void slowTaskIsNotExecuted() throws Exception {
        assertExecuted(50, false);
    }

    public void assertExecuted(int waiting, boolean expected) throws InterruptedException
    {
        WaitingTask task = new WaitingTask(waiting);

        executor.push(task);
        Thread.sleep(100);

        assertEquals(expected, task.executed);
    }

    class WaitingTask implements Task {
        boolean executed;
        int seconds_to_wait;

        public WaitingTask(int milliseconds_to_wait) {
            this.executed = false;
            this.milliseconds_to_wait = milliseconds_to_wait;
        }

        @Override
        public Boolean call() throws Exception {
            Thread.sleep(this.milliseconds_to_wait);
            this.executed=true;
            return executed;
        }
    }
}

What do you think of this code?


texts: Distance between 2 points using Haversine Formula

texts:
This is an implementation of the Haversine formula in SQL.

How can I simplify and improve the function?

SELECT to_char(MIN((day::timestamp at time zone 'UTC') at time zone 'America/Los_Angeles'), 'YYYY-MM-DD'),
   device_id,
   dblat,
   dblong,
   min(distance_in_km) AS dist
FROM
  (SELECT day,
      device_id,
      dblong,
      dblat,
      111.045*  DEGREES(ACOS(COS(RADIANS(latpoint))
                           * COS(RADIANS(cast(dblat as double precision)))
                           * COS(RADIANS(longpoint) - RADIANS(cast(dblong as double precision)))
                           + SIN(RADIANS(latpoint)) * SIN(RADIANS(cast(dblat as double precision))))) AS distance_in_km
  FROM
   (SELECT MIN(DATE(created_at)) AS day,
           device_id,
           MAX(doorbot_longitude) AS dblong,
           MAX(doorbot_latitude) AS dblat
  FROM bi_dev.jcc_doorbot_web_setups
    WHERE status = 'valid'
      AND doorbot_longitude != 0
      AND device_id IS NOT NULL
      AND doorbot_kind IN ('bell', 'bell_v3', 'lpdv_1')
      AND created_at > '2016-01-01'
    GROUP BY 2)s
JOIN
  (SELECT 38.5848702 AS latpoint, -77.7923891 AS longpoint) AS p
    ON 1=1)a
 WHERE distance_in_km < 5
 GROUP BY 2,
          3,
          4
ORDER BY dist


texts:
I decided to go with a very simple CGI user registration program to pair with Apache's mod_auth_form wrapper around a private site. It was only just after I finished writing that I realized I'd written security-sensitive code in a language I'm not my best at.

Is this code secure from parameter injection attacks? I.e., if the attacker fiddles with the POST values, can they run arbitrary commands on the server as the web server user?

#!/bin/bash

echo "Content-type: text/html"
echo ''

cat <<EOT
<!doctype html>

                <title>Registered</title>
                <link rel="icon" href="/favicon.png">

EOT

POST=$(cat)
if [ "$REQUEST_METHOD" != "POST" ] || [ ! "$POST" ]; then
        echo "
Error

Please go back and try again
";
        exit 1;
fi

function input {
        echo "$POST" | sed 's/^.*'"$1"'=\([^&]\+\)&.*$/\1/' | python -c "import sys, urllib.parse as p; print(p.unquote(sys.stdin.read()));"
}

USERNAME=$(input username)
PASSWORD=$(input password)
PASSWORD2=$(input password2)

if [ "$PASSWORD" != "$PASSWORD2" ]; then
        echo "
Error

Your passwords do not match.
";
        exit 1;
fi

if [ ${#PASSWORD} -lt 10 ]; then
        echo "
Error

Please pick a longer password.
";
        exit 1;
fi

echo "$PASSWORD" | htpasswd -i ../registrations "$USERNAME"

cat <<EOT

You have registered

Now, please email me so I can enable your account.

EOT

exit 0

To clarify - I'm not concerned about the line of python - it urldecodes/unescapes the field from the POST data and is extremely battle-tested. I put that in to avoid bugs/security concerns over other solutions with fewer dependencies (many with scary-looking bash constructs).

The sed is also pretty straightforward - it pulls out the named parameter from the urlencoded POST data. & is escaped as %26 and so will never show up in the input. I wrote/modified the sed there and am confident enough that it'll behave as I expect (sed is more familiar to me than bash).

Essentially, please feel free to ignore the implementation of the input function and assume it properly extracts POST variables into bash variables. My concerns center entirely around whether that user supplied data (which can be essentially any sequence of bytes) in bash variables will break or escape from any of the places I use it.


texts: Best way to refactor this loop of animations with delay?

texts:
I have some animations happening after some delay calls the code to animate.  It works fine, but the code to call the functions is not nice.

    double delayInSeconds = 0.2;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.1 * NSEC_PER_SEC);
    dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.2 * NSEC_PER_SEC);
    dispatch_time_t popTime3 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.3 * NSEC_PER_SEC);
    dispatch_time_t popTime4 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.4 * NSEC_PER_SEC);
    dispatch_time_t popTime5 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.5 * NSEC_PER_SEC);
    dispatch_time_t popTime6 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.6 * NSEC_PER_SEC);
    dispatch_time_t popTime7 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.7 * NSEC_PER_SEC);
    dispatch_time_t popTime8 = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds + 0.8 * NSEC_PER_SEC);

    if (self.menuType == kRacingMenu) {

        self.menuAnimationSequence = @[@0, @1, @3, @2, @4]; //animation sequence!

        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:0];
        });
        dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
        [self animateWithCoreAnimaGenerallyWithIndex:1];
        });
        dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){
        [self animateWithCoreAnimaGenerallyWithIndex:2];
        });
        dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){
        [self animateWithCoreAnimaGenerallyWithIndex:4];
        });
        dispatch_after(popTime5, dispatch_get_main_queue(), ^(void){
        [self animateWithCoreAnimaGenerallyWithIndex:3];
        });

    }else if (self.menuType == kLoginMenu) {
        self.menuAnimationSequence = @[@0, @1, @3, @2]; //animation sequence!
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:0];
        });
        dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:1];
        });
        dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:2];
        });
        dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:3];
        });

    } else {
        [self animateWithCoreAnimaGenerallyWithIndex:1];
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:0];
        });
        dispatch_after(popTime2, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:2];
        });
        dispatch_after(popTime3, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:4];
        });
        dispatch_after(popTime4, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:3];
        });
        dispatch_after(popTime5, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:5];
        });
        dispatch_after(popTime6, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:7];
        });
        dispatch_after(popTime7, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:6];
        });
        dispatch_after(popTime8, dispatch_get_main_queue(), ^(void){
            [self animateWithCoreAnimaGenerallyWithIndex:8];
        });

    }

How best to abstract this timer?  And the calls to start the animation?


texts:
The problem. To represent a finite-state automaton capable of recognizing and extracting a token from a character stream.

This is my quick attempt at it. I've included both the class definition and an example usage below.

I would appreciate tips on simplifying or optimizing the design and everything as a whole.

#include <string>
#include <unordered_map>
#include <utility>
#include <iterator>
#include <vector>
#include <tuple>

template<typename State,
    typename String = std::string,
    typename StringIterator = std::string::iterator, // might use custom utf8 adapter
>
class FiniteStateMachine
{
public:
    using state_type = State;
    using string_type = String;
    using string_iterator = StringIterator;
    using function_type = bool(*)(typename std::iterator_traits<string_iterator>::value_type);

private:
    const state_type initial;
    state_type current; // reset to initial after every run()

    // one state may transition to many states hence the vector
    // vector's elements are <function returning bool, new state if true>
    std::unordered_map<state_type, std::vector<std::pair<function_type, state_type>>> input;

public:
    explicit FiniteStateMachine(const state_type& state)
        : initial{ state }, current{ state }
    {}

    FiniteStateMachine(const state_type& state,
                       std::initializer_list<std::tuple<state_type, function_type, state_type>> ilist)
        : initial{ state }, current { state }
    {
        for (auto&& i : ilist) {
            input[std::get<0>(i)].emplace_back(std::get<1>(i), std::get<2>(i));
        }
    }

    void add_function(state_type in_state, function_type fun, state_type out_state) {
        input[in_state].emplace_back(fun, out_state);
    }

    bool run(string_type& str, string_type& extracted)
    {
        string_type res;
        for (string_iterator first{ str.begin() }; first != string_iterator{ str.end() }; ++first)
        {
            auto search = input.find(current);
            if (search == input.end()) {
                return false;
            }
            else
            {
                bool fin = true;
                for (auto&& f : search->second)
                {
                    if (f.first(*first))
                    {
                        fin = false;

                        current = f.second;
                        res += *first;
                        break;
                    }
                }
                if (fin) {
                    break;
                }
            }
        }

        current = initial;

        str.erase(0, res.size());
        return res.size() ? extracted = std::move(res), true : false;
    }
};

And usage:

#include <iostream>
#include <cctype>

enum class State
{
    initial,
    secondary
};

bool NonDigit(char c) { return std::isalpha(c) || c == '_'; }
bool Digit(char c) { return std::isdigit(c); }
bool Space(char c) { return std::isspace(c); }

int main()
{
    std::string input = "int main int _asf char 23_asf, double _asf23";

    FiniteStateMachine<State> identifier{
        State::initial,
        { { State::initial, [](auto c) { return NonDigit(c); }, State::secondary },
        { State::secondary, [](auto c) { return NonDigit(c) || Digit(c); }, State::secondary } }
    };

    FiniteStateMachine<State> space{ State::initial };

    space.add_function(State::initial, [](auto c) { return Space(c); }, State::initial);

    while (!input.empty())
    {
        std::string word;
        if (identifier.run(input, word)) {
            std::cout << word;
        }
        else if (space.run(input, word)) {
            std::cout << word;
        }
        else
        {
            std::cout << "\nError!\n";
            break;
        }
    }
    std::cin.get();
}


texts: Select list items in ViewModel fetched using a Repository

texts:
Doing database access in ViewModel is generally considered a bad practice. However, when you have a <select> in your view, you need to populate it using the ViewBag or the ViewModel (I prefer the ViewModel). This leads to the following code:

public class NewUserViewModel
{
    public string Username {get;set;}
    public IEnumerable<SelectListItem> Cities {get;set;}
    public User User // Helper to retrieve user
    {
        get { return new User() { Username = this.Username; }}
        set { this.Username = value.Username; }
    }
}

We now have to populate the Cities twice:

public ActionResult New()
{
    var vm = new NewUserViewModel();
    vm.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id });
    return View(vm);
}

[HttpPost]
public ActionResult Create(NewUserViewModel vm)
{
    if(ModelState.IsValid)
    {
        userRepository.Add(vm.User);
        return RedirectToAction("Index");
    }
    else
    {
        vm.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id }); // Copy this line
        return View(vm);
    }
}

I came up with an approach to solve this problem:

public NewUserViewModel(AddressRepository addressRepository) {
    this.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id });
}

I overrode the DefaultModelBinder to inject the Repository into the ViewModel.

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
    return DependencyResolver.Current.GetService(modelType);
}

Now my controller is free:

public ActionResult New()
{
    // Is this bad too?
    return View(DependencyResolver.Current.GetService<NewUserViewModel>());
}

public ActionResult Create(NewUserViewModel vm)
{
    if(ModelState.IsValid)
    {
        userRepository.Add(vm.User);
        return RedirectToAction("Index");
    }
    else
    {
        return View(vm);
    }
}

If I think about it, having all the cities listed is ViewModel's job, not the controller's. This has one immediate downside: it fetches the Cities even when the ModelState.IsValid. However, that is not my concern. Is this bad practice? I won't do any more database access than this.


texts: Trying to convert imperetive code to functional -Haskell

texts:
I'm very new to Haskell and I was trying to implement a DFT which is very imperative into Haskell and I wanted to get a feedback. More specially how can I avoid so many helper functions and I avoid limiting to Double everywhere. Thank you.

My DFT algorithm:

 void dft(double[] inreal , double[] inimag, double[] outreal, double[] outimag) {
     int n = inreal.length;
     for (int k = 0; k < n; k++) {      // For each output element
         double sumreal = 0;
         double sumimag = 0;
         for (int t = 0; t < n; t++) {  // For each input element
             double angle = 2 * Math.PI * t * k / n;
             sumreal +=  inreal[t] * Math.cos(angle) + inimag[t] * Math.sin(angle);
             sumimag += -inreal[t] * Math.sin(angle) + inimag[t] * Math.cos(angle);
         }
         outreal[k] = sumreal;
         outimag[k] = sumimag;
     }
 }

My Haskell code:

-- Length of the array
ownLength :: [t] -> Int
ownLength [] = 0
ownLength (_: xs) = 1 + ownLength xs

dft_resolve_nested :: [((Double, Double), Double)] -> Double -> Int -> [(Double, Double)]
dft_resolve_nested [] _ _ = []
dft_resolve_nested (((x, y), t) : xs) k n = do
  let angle = 2.0 * pi * ( t) * ( k) / (fromIntegral n)
  let sumreal = x * (cos angle) + y * (sin angle)
  let sumimag = - x * (sin angle) + y * (cos angle)
  (sumreal, sumimag) : (dft_resolve_nested xs k n)

tuples_sum :: [(Double, Double)] -> (Double, Double)
tuples_sum [] = (0, 0)
tuples_sum ((x1, y1) : xs) = do
  let (x2, y2) = tuples_sum xs
  (x1 + x2, y1 + y2)

dft_resolve ::  [((Double, Double), Double)] -> [(Double, Double)]
dft_resolve [] = []
dft_resolve ls = do
  let n = ownLength ls
  let (((x, y), k) : xs) = ls
  let (xr, yr) = tuples_sum (dft_resolve_nested ls k n)
  (xr, yr) : (dft_resolve xs)

dft :: [(Double, Double)] -> [(Double, Double)]
dft [] = []
dft ls = dft_resolve (zip ls [0..])

-- Main driver
main = do
  print (dft [(1,2), (3,4)])


texts: Parsing a complex number using regular expressions

texts:
Requirements were to create a constructor for a complex number, that receives a string. For example: \$3+5i\$. The regex extracts positive or negative numbers from the string with optional decimal.

My professor told me that my regex was "beyond wrong":

public Complex(String str) {

        ArrayList<Double> list = new
            ArrayList<Double>();

        Pattern p = Pattern.compile("[-+]?[0-9]*\\.?[0-9]");
        // toString() handles the letter i

        // find positive and negative doubles in string and add to list
        Matcher m = p.matcher(str);
        while (m.find()) {
            double num = Double.parseDouble(m.group());
            list.add(num);
        }
        this.re = list.get(0);
        this.im = list.get(1);
}

Here is a link to the class if you need a better understanding of the code.

He then posted his chosen correct solution, which I found to be repetitive. He may argue that I am not checking for i, but I see no point of storing i if we are not using it later.

In addition, if he argues that I am not checking for and storing i, that would mean that if I did store them, I would explicitly have to go exclude the i from the string when I perform mathematical operations on the numbers. It seems counter-productive.

Here is the solution he preferred:

public Complex(String c) {

      String numberNoWhiteSpace = c.replaceAll("\\s","");

      // Matches complex number with BOTH real AND imaginary parts.
      // Ex: -3-2.0i
      Pattern patternA = Pattern.compile("([-]?[0-9]+\\.?[0-9]?)([-|+]+[0-9]+\\.?[0-9]?)[i$]+");

      // Matches ONLY real number.
      // Ex: 3.145
      Pattern patternB = Pattern.compile("([-]?[0-9]+\\.?[0-9]?)$");

      // Matches ONLY imaginary number.
      // Ex: -10i
      Pattern patternC = Pattern.compile("([-]?[0-9]+\\.?[0-9]?)[i$]");

      Matcher matcherA = patternA.matcher(numberNoWhiteSpace);
      Matcher matcherB = patternB.matcher(numberNoWhiteSpace);
      Matcher matcherC = patternC.matcher(numberNoWhiteSpace);

      if (matcherA.find()) {
          real = Double.parseDouble(matcherA.group(1));
          imaginary = Double.parseDouble(matcherA.group(2));
      } else if (matcherB.find()) {
          real = Double.parseDouble(matcherB.group(1));
          imaginary = 0;
      } else if (matcherC.find()) {
          real = 0;
          imaginary = Double.parseDouble(matcherC.group(1));
      }
}


texts: Rails models for Users, Offers, Comments, Documents, and Reviews

texts:
I want to simplify my Rails models, current looks like this:

class User < ActiveRecord::Base
  has_many :offers, dependent: :destroy
  has_many :reviews, dependent: :destroy
  has_many :comments, dependent: :destroy
end

class Offer < ActiveRecord::Base
  belongs_to :user
  has_many :documents, as: :documentable
  has_many :comments, dependent: :destroy
  has_many :reviews, dependent: :destroy
end

class Review < ActiveRecord::Base
  belongs_to :user
  belongs_to :offer
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :offer
end

class Document < ActiveRecord::Base
  belongs_to :documentable, polymorphic: true
end

As you can see, I have the same relations on Comment and Review models, but they have some difference in columns, what are the options do I have to minimize the amount of models?


texts: What do you think about this uint64 random generator?

texts:
I've looked for a good method to generate an integer inside a range of values.  I think using modulo is not a good method because the values are not perfectly mapped in the range.  So I mapped the pseudo random generated number in the range by using double variables types.

What do you think about this method?  I know that performance is not better when using a modulo. How would you improve the method or the performance by keeping a perfect match?

quint32 randquint32(quint32 low, quint32 high)
{
    const quint32 uint_max = 0xffffffff;

    if (low == 0 && high == 0)
    {
        high = uint_max;
        if (RAND_MAX > high)
        {
            return (qrand() & high);
        }
    }
    else if (low > high)
    {
        qSwap(low, high);
    }

    const quint8 numberOfBits = bitCount(RAND_MAX);
    quint32 myRand = 0;
    int i = qCeil(((double)32) / ((double)numberOfBits));
    while (i--)
    {
        myRand += qrand();
        if (i)
        {
            myRand <<= numberOfBits;
        }
    }

    if (low == 0 && high == uint_max)
    {
        return myRand;
    }
    if (myRand == uint_max)
    {
        return high;
    }

    const double uint_max_double = (double)uint_max;

    double range = high - low + 1;
    double tmpRand = ((double)myRand) / uint_max_double * range;
    return qFloor(tmpRand);
}

quint8 bitCount(quint32 n)
{
    quint8 count = 0;
    while (n)
    {
        if (n & 1)
        {
            count++;
        }
        n >>= 1;
    }
    return count;
}

NEW VERSION:

// count setted bits at the right of a mask
quint8 bitCountRightMask(quint64 mask)
{
    quint8 bc = 0;
    while (mask & 1)
    {
        mask >>= 1;
        bc++;
    }
    return bc;
}

const quint64 uint64_max = 0xffffffffffffffff;
const int bitCountRandMax = bitCountRightMask(RAND_MAX);

// randomise an uint64 variable
quint64 rand64()
{
    quint64 myRand = qrand();

    if (uint64_max > RAND_MAX)
    {
        int i = qCeil(64 / (double)bitCountRandMax) - 1;
        do
        {
            myRand <<= bitCountRandMax;
            myRand += rand();
        } while (i--);
    }

    return myRand;
}

// randomize an uint64 variable between low and high (fast method (modulo))
quint64 rand64(quint64 low, quint64 high)
{
    if (low == 0 && high == 0)
    {
        high = uint64_max - 1;
    }
    else if (low > high)
    {
        qSwap(low, high);
    }

    return low + (rand64() % (high - low + 1));
}

// randomize an uint64 variable between low and high (precise method (double))
quint64 prand64(quint64 low, quint64 high)
{
    if (low == 0 && high == 0)
    {
        return rand64();
    }
    else if (low > high)
    {
        qSwap(low, high);
    }

    quint64 myRand = rand64();

    if (myRand == uint64_max)
    {
        return high;
    }

    static double uint64_max_double = static_cast<double>(uint64_max);

    return low + (myRand / uint64_max_double * (high - low + 1));
}


texts:
Here is a login system I am working on.  I just want an opinion on it and whether I am going in the right direction or am just completely missing something.

The main thing I would like to know is: am I initializing my user session IDs correctly? Basically once the user enters their credentials, the system goes into the database to see if there is a match. If there is, then it adds the session_id variable if it's not already set.

Now if it is set, then it checks your value against the one in the database.  If they match, then you are entered into the system and then the session_ids are changed on both sides (server/client), otherwise it returns false.  Is this a correct or incorrect method?

function userIsLoggedIn()
{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (isset($_POST['action']) and $_POST['action'] == 'login') {
  if (!isset($_POST['user']) or $_POST['user'] == '' or !isset($_POST['password']) or $_POST['password'] == '') {
        return FALSE;
  }

  array_push($_SESSION['mintime'], time());
  array_shift($_SESSION['mintime']);

  // minimum time (in seconds) between valid form submissions
  if ($_SESSION['mintime'][1] - $_SESSION['mintime'][0] < 2) {

        echo "to quick";
        return FALSE;

  } else {

        $user = test_input($_POST['user']);

        if ($GLOBALS['adminPage'] == 1 and $user != 'admin') {
        return FALSE;
        }

        $passtemp = test_input($_POST['password']);

        $password = hash('sha512', $passtemp . $user);

        if ($user == 'admin') {
        $GLOBALS["isAdmin"] = TRUE;
        }

        if (databaseContainsUser($user, $password)) {

            if (!isset($_SESSION['session_id'])) {
            setSessionID($user);
        $_SESSION['loggedIn'] = TRUE;
        $_SESSION['user']     = $user;
        $_SESSION['password'] = $password;
        return TRUE;
        }
        if ((isset($_SESSION['session_id'])) and (checkSessionID($user))) {

        updateSessionID($user);
        setSessionID($user);
        $_SESSION['loggedIn'] = TRUE;
        $_SESSION['user']     = $user;
        $_SESSION['password'] = $password;
        return TRUE;
        } else {
                unset($_SESSION['session_id']);
            unset($_SESSION['loggedIn']);
                unset($_SESSION['user']);
                unset($_SESSION['password']);
                return FALSE;
        }

        } else {
        unset($_SESSION['loggedIn']);
        unset($_SESSION['user']);
        unset($_SESSION['password']);
        return FALSE;
        }
  } //end else time check
  } //end if login check
  if (isset($_POST['action']) and $_POST['action'] == 'logout') {
  unset($_SESSION['loggedIn']);
  unset($_SESSION['user']);
  unset($_SESSION['password']);
  header('Location: ' . $_POST['goto']);
  exit();
  }

  if (isset($_POST['action']) and $_POST['action'] == 'admin') {
  header('Location: ' . $_POST['gotoadmin']); // gotoadmin = '..'
  exit();
  }
 } //end if POST check

if (isset($_SESSION['loggedIn'])) {
  return databaseContainsUser($_SESSION['user'], $_SESSION['password']);
}

} //end function

//validate input
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
return $data;
}

I store all passwords like this:

sha($password + salt, 512)

and the session IDs are made like this:

UUID()


texts: Hold a list of items stored in recursive class?

texts:
Alright, well the title doesn't really explain anything, so I'll show a pared down version of my code:

class Handler {
    Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>(); //This list

    Leaf RootLeaf = new Leaf();
    public void Add (object obj)
    {
        Leaf AddedTo = RootLeaf.Add(obj); //Adds to a leaf, then returns the leaf it was added to
        AllItems.Add(obj, AddedTo); //adds references to the obj and the leaf it's in.
    }
}

class Leaf {
    private Leaf _Parent;
    public Leaf SubLeaf;
    public List<object> Children = new List<object>();

    public Leaf (Leaf parent)
    {
        this._Parent = parent;
    }

    public void Add (object obj)
    {
        if (Children.Count > 5)
        {
            SubLeaf = new Leaf();
            return SubLeaf.Add(obj); //recursively return the reference to the end leaf
        }
        Children.Add(obj);
        return this; //start the recursive return
    }

    public Leaf Parent { get { return this._Parent; } }
}

Note: The above isn't real code, just an example of what I plan to do.

So the idea of the above is to organize all the items into leaves, but I need a quick way to loop through every object, and its leaf.  Would doing the above (storing a reference of every object & its parent in a list in the Handler class) cause a drop in performance?  Or would there be a better way to do this?

I hope this was clear enough, if not, please ask any questions.


texts: Showing one category and hiding two others when one of three buttons is clicked

texts:
How can I refactor this code? I know it's repetitive but I'm not sure how to fix it.

$(function() {
    $('#category-1-button a').bind('click', function() {
        $(this).css({opacity:'1'});
        $('#category-2-button a,#category-3-button a').css({opacity:'0.4'});
        $('#blog-headers').css({backgroundPosition: '0 0'});
        $('#category_2,#category_3').hide(0, function() {
            $('#category_1').show(0);
        });
    });
});

$(function() {
    $('#category-2-button a').bind('click', function() {
        $(this).css({opacity:'1'});
        $('#category-1-button a,#category-3-button a').css({opacity:'0.4'});
        $('#blog-headers').css({backgroundPosition: '0 -144px'});
        $('#category_1,#category_3').hide(0, function() {
            $('#category_2').show(0);
        });
    });
});

$(function() {
    $('#category-3-button a').bind('click', function() {
        $(this).css({opacity:'1'});
        $('#category-1-button a,#category-2-button a').css({opacity:'0.4'});
        $('#blog-headers').css({backgroundPosition: '0 -288px'});
        $('#category_1,#category_2').hide(0, function() {
            $('#category_3').show(0);
        });
    });
});


texts: Moving business logic towards the domain object as a design pattern

texts:
My project is composed of several parts: Repositories, Services, Domain objects, etc in a .NET MVC web application.

My repositories handle all data i/o, the services are responsible for CRUD operations as well as other logic, such as getting a count of objects from the database.

I am trying to shift from an "anemic" domain model where my domain objects are simply classes with properties to having more business logic where it belongs. In this case, I would like to have the domain object handle the logic where it checks the database for duplicates, but I also don't want to have the code that communicates with the repository inside of the domain object (I read it is bad practice to have an object responsible for persistence with the database, so I'm assuming this is the same thing.)

I don't particularly like this solution, as it just doesn't feel good, and I'd like to get a better handle on how to handle these sorts of situations. Can anybody give me some advice here?

public interface IDuplicateChecker<T> where T : class
{
    bool IsDuplicate(T t);
}

public class DuplicateDocumentChecker : IDuplicateChecker<Document>
{
    public bool IsDuplicate(Document doc)
    {
        IDocumentService documentService = new DocumentService();

        // simplified check -- really there are a few other properties to match
        if (documentService.Count(doc.DocumentNumber) > 0)
        {
            return true;
        }

        return false;
    }
}

public class Document
{
    public Document(string documentNumber)
    {
         // validation and other removed for brevity
         DocumentNumber = documentNumber;
    }

    // simplified document properties for brevity
    public string DocumentNumber { get; set; }
    public bool IsDuplicate { get; set; }

    public void CheckForDuplicates(IDuplicateChecker<Document> checker)
    {
        IsDuplicate = checker.IsDuplicate(this);
    }
}


texts: Am I risking a deadlock in this manner of re-queueing up events?

texts:
I have a DelayQueue in Java, which multiple threads will read from. They will then perform a task, and call a requeue method which performs some mathematical logic (no odd concurrent access), and then calls queue.put(this). I'm aware that both take and put are blocking methods on the queue, so will this risk any deadlocks?

Here's the processing code (to be run on 8 threads concurrently):

 Task task;
            try {
                task = queue.take();
            } catch (InterruptedException e) {
                logger.error("InterruptedException in futures processor trying to take from queue.");
                continue rLoop;
            }
           task.getCallback().run();
           task.requeue();

task.requeue(), again, makes a blocking call of queue.put() but the queue is unbounded and I'm not expecting any more than 10,000 actual queue elements over application lifetime, and no more than 100 or so at once.


texts: Continuous sequence against target number

texts:
Post problem and my code written in Python 2.7. Any advice for code bugs, performance in terms of algorithm time complexity and code style are appreciated. I did PEB8 self-check in PyCharm.

BTW, a small issue in my code is, I feel this condition end_index == len(numbers) - 1 and cur_sum < target is a bit ugly, but I do not find a better way to remove it for safe boundary check purpose.

'''
Question: Given a sequence of positive integers A and an integer T, return whether there is a continuous sequence of A that sums up to exactly T
Example
[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20
[1, 3, 5, 23, 2], 8. Return True because 3 + 5 = 8
[1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7
'''

def sum_target(numbers, target):
    start_index = 0 # inclusive
    end_index = 0 # inclusive
    cur_sum = numbers[0]
    while end_index < len(numbers):
        if end_index < len(numbers) - 1 and cur_sum < target:
            end_index += 1
            cur_sum += numbers[end_index]
        elif end_index == len(numbers) - 1 and cur_sum < target:
            return False
        elif cur_sum > target:
            cur_sum -= numbers[start_index]
            start_index += 1
        elif cur_sum == target:
            return True

    return False

if __name__ == "__main__":
    print sum_target([23, 5, 4, 7, 2, 11], 20)
    print sum_target([1, 3, 5, 23, 2], 8)
    print sum_target([1, 3, 5, 23, 2], 7)


texts:
The program is a little code about guns with user input. The program is a perfect representation of the beauty of functions. What do you think of it?

import sys
import time

#determines reload time
def reloading(reload_time):
    print('\nReloading', end='')

    for dot in range(reload_time):
        time.sleep(1)
        print('.', end='')

#parameters including the numerator/denominator, fire rate, and reload speed
def gun(ROUNDS, left, fire_rate, the_reload):
    print('\nshoot!')
    #hold enter
    rounds = ROUNDS
    print('\n{}/{}'.format(rounds, left))

    while rounds > 0 or left > 0:
        shoot = input()
        rounds -= 1
        #decrement each time input is given
        print('{}/{}'.format(rounds, left))

        if rounds == 0 and left == 0:
            print('OUT OF AMMO')
            break
        elif shoot.upper() == 'DONE':
            sure = input('Are you sure?\n> ')
            if sure.lower() == 'y':
                start()
                #allocates back to gun selection
        elif rounds == 0:
            if left <= ROUNDS:
                reloading(the_reload)
                rounds += left
                left -= left
                print('\n{}/{}'.format(rounds, left))
                #if bullets left is less than the magazine
            else:
                reloading(the_reload)
                rounds += ROUNDS
                left -= ROUNDS
                print('\n{}/{}'.format(rounds, left))

        time.sleep(fire_rate)
        #fire rate

def start():
    firearm = input('CHOOSE YOUR GUN (ENTER to exit)\n> ')

    if firearm.upper() == 'ASSAULT' or firearm.upper() == 'ASSUALT':
        gun(40, 130, 0.1, 7)
    elif firearm.upper() == 'SHOTGUN':
        gun(6, 30, 2, 12)
    elif firearm.upper() == 'SMG':
        gun(40, 200, 0, 5)
    elif firearm.upper() == 'SNIPER':
        gun(1, 15, 0, 5)
    elif firearm.upper() == 'MARKSMAN':
        gun(20, 100, 0.8, 9)
    elif firearm.upper() == 'PISTOL':
        gun(10, 100, 0.6, 3)
    else:
        sys.exit()
start()


texts:
Background

I am re-writing a series of algorithms together with a colleague that we are going to later on publish in a packet for the community.

To start, I picked the typical bubble sort algorithm.

Objectives

The function must be pure
It must be efficient
It must obey the complexities listed in https://en.wikipedia.org/wiki/Bubble_sort

Please note that by "being pure" it doesn't mean that it's inside code cannot have impurity. It merely means that the PUBLIC API of the function must be pure and it must not affect anything outside of its scope.

Code

//PS: NOT really using lodash. Just copy pasted this one function xD
const isFunction = require("lodash.isfunction");
const defaultCompare = require("./defaultCompare");

const bubble = ( array, fnCompare = defaultCompare ) => {

    if( !isFunction(fnCompare) )
        throw new Error("fnCompare must be a function");

    if(!Array.isArray(array))
        throw new Error("array must be an Array");

    if (array.length === 0)
        return [];

    //shallow copy
    const clonedArray = array.slice();

    //Optimized bubble sort: https://en.wikipedia.org/wiki/Bubble_sort
    let size = clonedArray.length;
    do{
        let newSize = 0;
        for( let i = 1; i < size; i++){
            if( fnCompare( clonedArray[i - 1], clonedArray[i] ) > 0 ){
                swap( clonedArray, i - 1, i );
                newSize = i;
            }
        }
        size = newSize;
    }while( size !== 0);

    return clonedArray;
};

const swap = (array, index1, index2) => {
    const temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
};

module.exports = bubble;

What do I want?

I am looking for any flaws in the code that could compromise objectives 1 and 3.

If you have an idea on how to improve object 2 (efficiency), I am all ears as well!


texts: Changing the width of a centered progress bar

texts:
I am making a game in which the player has a certain amount of available boost. To show this, I am using a blue bar inside a black frame. The bar can grow and shrink at different rates as available boost goes up and down. It works well and looks nice, but it almost halves my FPS.

The relevant snippet:

var boostStyle = document.getElementById("available-boost").style;
var currBoost = 100;
var maxBoost = 100;

function setBoost(boostAmount) {
  boostStyle.width = (boostAmount / maxBoost) * 100 + "%";
};

function demonstrateBoostChange() {
  currBoost -= 1;
  setBoost(currBoost);
  if (currBoost < 1) {
    currBoost = maxBoost;
  }
  requestAnimationFrame(demonstrateBoostChange);
}
requestAnimationFrame(demonstrateBoostChange);
#boost-bar {
  bottom: 10px;
  position: absolute;
  right: 20%;
  left: 20%;
  height: 20px;
  border-radius: 12px;
  border-style: solid;
  border-width: 2px;
  border-color: rgb(0, 0, 0);
}

#available-boost {
  margin: 0 auto;
  height: 20px;
  width: 100%;
  text-align: center;
  font-weight: bold;
  border-radius: 10px;
  background-color: rgb(0, 225, 255);
}

Boost

(I see the slight glitch where the text moves when very little boost remains, but I can solve that later. )

The performance hit is probably not noticeable  since it is the only thing running, but I have used Chrome DevTools to see that it is the slowest part of my code. I think this is because changing the width is triggering a reflow.

How can I improve the performance of the above code?

Some considerations:

I am already using a canvas for some other things, would it be faster to just put the bar on that?
The boost can change at different rates, depending on the maxBoost.


texts: Query: user can see all posts by him and his friends

texts:
This query is serving me a home page for users where a user can see all posts by him/her and his/her friends. This is an excellent query without any errors but I only wish to make it shorter if possible!

select U.fname, U.lname, P.postid, P.status, P.date, U.usernick, P.visible
from posts as P natural join users as U where
  U.visible=1 and P.visible=1
  and
  (P.userid='{$_SESSION['user_id']}' or P.userid in
    (select distinct U.userid from users as U inner join friends as F where
      (U.userid=F.userid and F.friend='{$_SESSION['user_id']}' and F.status=1) or
      (U.userid=F.friend and F.userid='{$_SESSION['user_id']}' and F.status=1)))
  or
  (P.streamid='{$_SESSION['user_id']}' or P.streamid in
    (select distinct U.userid from users as U inner join friends as F where
      (U.userid=F.userid and F.friend='{$_SESSION['user_id']}' and F.status=1) or
      (U.userid=F.friend and F.userid='{$_SESSION['user_id']}' and F.status=1)))
ORDER BY P.date DESC

CREATE  TABLE IF NOT EXISTS `users` (
  `userid` INT NOT NULL AUTO_INCREMENT ,
  `fname` VARCHAR(45) NOT NULL ,
  `lname` VARCHAR(45) NOT NULL ,
  `usernick` VARCHAR(45) NOT NULL ,
  `useremail` VARCHAR(45) NOT NULL ,
  `visible` INT(1) NOT NULL DEFAULT 1     //visible shows id is disables or not
 )

CREATE  TABLE IF NOT EXISTS `posts` (
  `postid` INT NOT NULL AUTO_INCREMENT ,   //Simple postid index
  `userid` INT NOT NULL ,                  //userid of poster
  `streamid` INT NOT NULL ,                // post is posted on his wall
  `status` VARCHAR(5000) NOT NULL ,        //the post that has been posted
  `date` TIMESTAMP NOT NULL DEFAULT now(), //post was posted on
  `visible` INT(1) NOT NULL DEFAULT 1 )    //post is deleted or not

CREATE  TABLE IF NOT EXISTS `network`.`friends` (
  `userid` INT NOT NULL ,                   //user who sent friend req
  `friend` INT NOT NULL ,                   //to whom friend req has been sent
  `status` INT(1) NOT NULL ,                //0 -> above both are not friends : 1->
                                            //both above are friends
  `date` TIMESTAMP NOT NULL DEFAULT now() , //
  `visible` INT(1) NOT NULL DEFAULT 1 )     //both are friends still


texts:
We have an integer array as:

private int[] arr = {1, 3, 5, 14, 18, 29, 78};

We have a function which takes three inputs of the array and checks whether:

a * a = b * b + c * c

If the function returns true then those 3 inputs are stored in an ArrayList:

private boolean findTriplet(int a, int b, int c) {
    int squareA = a * a;
    int squareB = b * b;
    int squareC = c * c;
    int sum = squareB + squareC;
    if (squareA == sum) {
        return true;
    }
    return false;
}

Iterating through the array:

 private void getTriplets(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = 1; j < arr.length; j++) {
            if (i != j) {
                for (int k = i+j; k < arr.length; k++) {
                    if ((i != k) || (j != k)) {
                        boolean tripResult = findTriplet(arr[i], arr[j], arr[k]);
                        if (tripResult) {
                            tripList.add(new Triplet(arr[i], arr[j], arr[k]));
                        }
                    }
                }
            }
        }
    }
}

According to the above solution the complexity of the program is \$O(n^3)\$.

How can I optimise this solution or get a more flexible complexity?


texts: Display relevant contents if radio button is clicked using knockout.js

texts:
I have four radio buttons and I want to display relevant contents for each of them if they are clicked. I am using knockout.js for data binding.

Is there a better way to write the if statement block?

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Standard" />Standard (Letter)

    No. of Copies
      <input type="text" data-bind="value:print_size_standard_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="13 x 19" />13" x 19"

    No. of Copies
      <input type="text" data-bind="value:print_size_13_19_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Contact Sheet">Contact Sheet

    No. of Images/Page
      <input type="text" data-bind="value:print_size_contact_q, valueUpdate:'keyup'" />

      <input type="radio" data-bind="checked: print_size_radio" name="print-size" value="Custom Size" />Custom Size

        Width
          <input type="text" data-bind="value:print_size_custom_w, valueUpdate:'keyup'" />

        Height
          <input type="text" data-bind="value:print_size_custom_h, valueUpdate:'keyup'" />

        Pixels/Inches
          <select data-bind="options: print_size_custom_units, value: print_size_custom_sel"></select>

        No. of Copies
          <input type="text" data-bind="value:print_size_custom_q, valueUpdate:'keyup'" />

self.print_size_radio.subscribe(function(p) {
  if (p == 'Standard') {
    self.print_size_standard(true);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(false);
  } else if (p == '13 x 19') {
    self.print_size_standard(false);
    self.print_size_13_19(true);
    self.print_size_contact(false);
    self.print_size_custom(false);
  } else if (p == 'Contact Sheet') {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(true);
    self.print_size_custom(false);
  } else if (p == 'Custom Size') {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(true);
  } else {
    self.print_size_standard(false);
    self.print_size_13_19(false);
    self.print_size_contact(false);
    self.print_size_custom(false);
  }
});


texts: Adding a custom field to Routes - clever solution or terrible hack?

texts:
I need to make sure the correct menu item is highlighted according to which URL is currently being viewed.

Now the problem with our site is that each menu item can represent several pages. So the Client menu will show the client list - but should still be highlighted when you go to the edit client page. So I can't parse the current URL and match it against the menu item to determine if it should be highlighted.

Instead I have decided to add a custom field - menu - to the $routeProvider setup. So when setting up the routes :

$routeProvider
            .when(
                '/SecurityGroup/Index',
                {
                    templateUrl: '/SecurityGroup/IndexPartial',
                    controller: 'GroupListController',
                    menu: 'group'
                }
            )
            .when(
                '/SecurityGroup/MemberClients/:groupId&:groupName',
                {
                    templateUrl: '/SecurityGroup/MemberClientsPartial',
                    controller: 'MemberClientsController',
                    menu: 'group'
                }
            )

Then in the HTML, the menus are specified as (the tr-menu attribute matches against the name field in the route) :

Groups

Clients

Then I have a directive that manages the menu highlighting - essentially adding and removing the Active class if the current route contains the correct name :

(function() {
    'use strict';
    angular.module('Administration')
        .directive('menuitem', ['$location', function($location) {
            return {
                restrict: 'A',
                scope: false,
                transclude: true,
                replace: false,
                template: '',
                link: function (scope, element, attrs) {
                    var href = attrs.href;
                    var name = attrs.trMenu;
                    var link = element.find('a');
                    link.attr('href', href);

                    scope.$on('$routeChangeSuccess', function (event, currentRoute, previousRoute) {
                        var menu = currentRoute.$$route.menu;
                        if (menu === name)
                            element.addClass('active');
                        else
                            element.removeClass('active');
                    });

                }
            };

        }]);
}());

Is this a clever solution, or a terrible abuse of javascripts dynamic abilities? Is there a more Angular way of doing things rather than relying on adding my own fields to the existing Angular data structures?


texts:
On the attached fiddle is what I hope will the be future UI for navigation on my own personal portfolio site. I was hoping you guys could critique the JavaScript I wrote to accomplish the most compatibility with the most browsers. I've tested as far back as IE 7 with this code and it works. Whereas the CSS solution is only IE 10+, and the jQuery Animate method is only usable in Chrome.

Below is the attached fiddle and all of the script I use to facilitate this process. Please be as brutal as possible.  I am very new to JS and would like to know as much as possible!

http://jsfiddle.net/PhilFromHeck/um8Pp/

var key = "off";
var menuKey=["off","off","off","off"];
var menuID = [];
var menuState=[0,0,0,0];

$(document).ready(function () {
    init();
    $('.menu').mouseenter(function () {
      for (var i = 0; i < 4; i++) {
        if(menuID[i] == this){
          menuKey=["off","off","off","off"];
          menuKey[i] = "on";
        }
      }
      if(key=="off"){
        key="on";
        doMove();
      }
    });
    $('.menu').mouseleave(function () {
          menuKey=["off","off","off","off"];
    });
});

function init() {
  menuID[0] = document.getElementById('menuOne');
  menuID[1] = document.getElementById('menuTwo');
  menuID[2] = document.getElementById('menuThree');
  menuID[3] = document.getElementById('menuFour');
}

function doMove() {
  var check = "no";
  if(key == "on"){
    for (var i = 0; i < 4; i++) {
      if(menuKey[i] == "on"){
        check = "yes";
        if(menuState[i] < 100){
          menuState[i] = menuState[i]+2;
          menuID[i].style.backgroundPosition="0px " + menuState[i] + "px";
        }
      }
      if(menuKey[i] == "off"){
        if(menuState[i] > 0){
          check = "yes";
          menuState[i] = menuState[i]-2;
          menuID[i].style.backgroundPosition="0px " + menuState[i] + "px";
        }
      }
    }
  if(check=="yes"){
    setTimeout(doMove,1); // call doMove in 20msec
  }
  else{
    key = "off";
  }
  }
}


texts:
I've recently started learning about lenses and for practice, I wrote a function that finds all paths from the root to a leaf of a tree for which the total of the nodes' weights is equal to a given value.

My first version works on binary trees and is my first attempt at wrapping my head around lenses and prisms.

{-# LANGUAGE TemplateHaskell #-}

module BSTSums where

import Control.Applicative
import Control.Lens
import Data.Monoid
import Data.Function

data Node a = Node1 { _v :: a, _c1, _c2 :: Node a }
            | Node2 { _v :: a, _c1 :: Node a }
            | Node3 { _v :: a }
    deriving Show
makeLenses ''Node

find :: (Eq a, Monoid a) => a -> Node a -> [[a]]
find x node = findRec x mempty node

findRec :: (Eq a, Monoid a) => a -> a -> Node a -> [[a]]
findRec x cur n = (:) val <$> fr (n ^? c1) (n ^? c2)
                  where val = (n ^. v)
                        fr  = on mappend $ maybe mempty (fr' . Just)
                        fr' (Just n) = findRec x (val<>cur) n
                        fr' Nothing  = if val <> cur == x
                                        then [[]]
                                        else  []

I'm pretty happy with this one in general, but would be interested in any suggestions for improving readability. In particular, would you recommend replacing fr with the pointful version:

fr a Nothing = fr' a
fr Nothing b = fr' b
fr a b       = fr' a <> fr' b --or on mappend fr' a b

And would it be better to move the Maybe handling from fr' into findRec? I tend to dislike handling too much of the logic in a where clause at the end, but this case is borderline for me.

For my second version I wrote a solution for the same problem with a rose tree instead of a binary tree in order to test out Traversals.

{-# LANGUAGE TemplateHaskell #-}

module RTSums where

import Control.Applicative
import Control.Lens
import Data.Monoid

data Node a = Node { _value :: a, _branches :: [Node a] }
    deriving Show
makeLenses ''Node

find :: (Eq a, Monoid a) => a -> Node a -> [[a]]
find x node = findR x mempty node

findR :: (Eq a, Monoid a) => a -> a -> Node a -> [[a]]
findR x cur n
  | s@(_:_) <- n ^. branches
                  & each %~ findR x (cur<>val)
                  & mconcat
                  = (:) val <$> s
  | otherwise     = if x == cur<>val then [[val]] else []
  where val = n ^. value

In both cases, I'd be interested to hear about better ways of handling the logic at leaves. If you can do it with lenses, that would be ideal. But anything cleaner than my current tests for Nothing/Nil would be appreciated.

I would also like some advice on commenting, (which parts would you recommend commenting, and how/how thoroughly?) and on module conventions. I probably shouldn't export findRec but what about the lenses for Node.


texts: Function that checks two objects with same fields and assigns old non-null values to new object if new values are empty or null

texts:
I have a function that checks two reference objects. They both have the same properties.

The purpose of this method is to ensure that any non-null old values are not overwritten with null or empty values after an API call. I'd appreciate any feedback.

evaluateEmptyValues: function(reference, originalReference) {
    var vm = this;

    // Get length
    referenceLength = Object.entries(reference).length;
    originalReferenceLength = Object.entries(originalReference).length;

    // Evaluate both if they are the same length -- they always should be
    if (referenceLength == originalReferenceLength) {
        try {
            for (var prop in reference) {
                // First check for undefined or null
                if (reference[prop] != undefined || reference[prop] != null) {
                    if (typeof (reference[prop]) == 'string' && reference[prop].trim() == '') {
                        // Assign original value to new object if new value is empty string
                        reference[prop] = originalReference[prop];
                    }

                    // Check if current prop in both objects is an object
                    if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object') {
                        var length = Object.keys(reference[prop]).length;

                        // Do another loop
                        for (var property in reference[prop]) {
                            // Check for undefined or null value in original
                            if (originalReference[prop][property] != undefined) {
                                if (originalReference[prop][property] != null) {
                                    if (reference[prop][property] == null || reference[prop][property] == '') {
                                        // Assign old non-null value to new object if new value is empty or null
                                        reference[prop][property] = originalReference[prop][property];
                                    }
                                }
                            }
                        }
                    }

                    // Check for array
                    if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {
                        // Recurse if both are arrays
                        reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]));
                    }
                } else {
                    if (originalReference[prop] != undefined) {
                        if (originalReference[prop] != null) {
                            // Assign original value to new object
                            reference[prop] = originalReference[prop];
                        }
                    }
                }
            }
        } catch(err) {
            console.log(err);
        }
    }
},


texts:
At the moment I am learning algorithms and here I am trying to implement a simple binary search tree. I would like to know your suggestions on whether I am on the right track or not, and how this can be improved.

BinaryTree.cs

class BinaryTree
{
    private Node root;
    private int count;

    public BinaryTree()
    {
        root = null;
        count = 0;
    }
    public bool isEmpty()
    {
        return root == null;
    }

    public void insert(int d)
    {
        if (isEmpty())
        {
            root = new Node(d);
        }
        else
        {
            root.insertData(ref root, d);
        }

        count++;
    }

    public bool search(int s)
    {
        return root.search(root, s);
    }

    public bool isLeaf()
    {
        if(!isEmpty())
        return root.isLeaf(ref root);

        return true;
    }

    public void display()
    {
        if(!isEmpty())
        root.display(root);
    }

    public int Count()
    {
        return count;
    }
}

Node.cs

class Node
{
    private int number;
    public Node rightLeaf;
    public Node leftLeaf;

    public Node(int value)
    {
        number = value;
        rightLeaf = null;
        leftLeaf = null;
    }

    public bool isLeaf(ref Node node)
    {
        return (node.rightLeaf == null && node.leftLeaf == null);

    }

    public void insertData(ref Node node, int data)
    {
        if (node == null)
        {
            node = new Node(data);

        }
        else if (node.number < data)
        {
            insertData(ref node.rightLeaf, data);
        }

        else if (node.number > data)
        {
            insertData(ref node.leftLeaf, data);
        }
    }

    public bool search(Node node, int s)
    {
        if (node == null)
            return false;

        if (node.number == s)
        {
            return true;
        }
        else if (node.number < s)
        {
           return search(node.rightLeaf, s);
        }
        else if (node.number > s)
        {
            return search(node.leftLeaf, s);
        }

        return false;
    }

    public void display(Node n)
    {
        if (n == null)
            return;

        display(n.leftLeaf);
        Console.Write(" " + n.number);
        display(n.rightLeaf);
    }

}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        BinaryTree b = new BinaryTree();

        b.insert(1);
        b.insert(6);
        b.insert(2);
        b.insert(4);
        b.insert(5);
        b.insert(3);

        b.display();

        Console.ReadLine();
    }
}

Output

  1 2 3 4 5 6


texts:
This is code of a rails app. The code has the logic used in a search form. It queries a MySQL database. Any thoughts on something that would make this unsafe or violated a rails principle?

/app/models/query.rb

class Query < ActiveRecord::Base
  attr_accessible :customer_email, :customer_first_name, :customer_last_name,
                  :max_total_amount, :min_total_amount, :order_id, :order_is_deleted,
                  :order_max_date, :order_min_date, :results_limit, :postal_code,
                  :subscribes_to_daily_emails

 def orders
   @orders ||= find_orders
 end

  #TO DO:
  #1. Pagination:
  #2. Add limit if not present when there could be too many results. DONE! Set limit to 50.
  #3. Add export feature and remove limit for export.

  private
  def find_orders

    @results_limitVar = nil

    if results_limit.nil? == true
      @results_limitVar = 50
    else
      @results_limitVar = results_limit
    end

    @subscribes_to_daily_emailsVar = nil

    if subscribes_to_daily_emails.nil? == false
      if subscribes_to_daily_emails
        @subscribes_to_daily_emailsVar = 1
      else
        @subscribes_to_daily_emailsVar = 0
      end
    end

    @order_is_deletedVar = nil

    if order_is_deleted.nil? == false
      if order_is_deleted
        @order_is_deletedVar = 1
      else
        @order_is_deletedVar = 0
      end
    end

    #Added orders explicitly because otherwise first_name, etc is ambiguous
    #since it is in multiple models.

    orders = Order.order(:order_id)
    orders = orders.where("orders.first_name LIKE ?", "%#{customer_first_name}%")     if customer_first_name.present?
    orders = orders.where("orders.last_name LIKE ?", "%#{customer_last_name}%") if customer_last_name.present?
    orders = orders.where("orders.email_address LIKE ?", "%#{customer_email}%") if customer_email.present?
    orders = orders.where("orders.order_id like ?", "%#{order_id}%") if order_id.present?
    orders = orders.where("orders.is_deleted = ?", "#{@order_is_deletedVar}") if !@order_is_deletedVar.nil?
    orders = orders.where("total_amount >= ?", min_total_amount) if min_total_amount.present?
    orders = orders.where("total_amount <= ?", max_total_amount) if max_total_amount.present?
    orders = orders.where("order_date >= ?", order_min_date) if order_min_date.present?
    orders = orders.where("order_date <= ?", order_max_date) if order_max_date.present?
    orders = orders.joins("INNER JOIN customers ON customers.customer_id = orders.customer_id AND customers.postal_code LIKE ", "'%#{postal_code}%'") if postal_code.present?
    orders = orders.joins("INNER JOIN email_preferences ON email_preferences.customer_id = orders.customer_id AND email_preferences.subscribes_to_daily_emails = ", "#{@subscribes_to_daily_emailsVar}") if !@subscribes_to_daily_emailsVar.nil?
    orders = orders.limit(@results_limitVar) if !@results_limitVar.nil?
    orders
  end

end


texts: Python - Simple wrapper class for a bot API

texts:
Is the following in poor taste?

This would be contained within a groupme module. Does it make sense to re-define a RequestException class within this module? If I didn't, wouldn't consumers of the module need to be aware of the underlying requests.exceptions.RequestException being thrown:

...

class Bot(object):

    API_BASE_URL = 'http://api.groupme.com/v3/bots/{route}'
    API_POST_URL = API_BASE_URL.format(route='post')

    def __init__(self, bot_id):
        self.bot_id = bot_id

    def post(self, message):
        try:
            data = {'bot_id': self.bot_id, 'message': message}
            response = requests.post(Bot.API_POST_URL, data)
            response.raise_for_status()
        except requests.exceptions.RequestException as ex:
            raise RequestException('Failed to post bot message') from ex

class RequestException(Exception):

    ...

And the groupme module / above code would then be used in the following manner:

import groupme

bot = groupme.Bot('abcdef123')
try:
    bot.post('Hello, world!')
except groupme.RequestException as ex:  # this seems cleaner as opposed to requests.exceptions.RequestException
    print(ex)


texts:
Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way to reset the currentYearMeetingCount to -1. I just want to print the data if there is data for that year and for the past 3 years.

 class Program
    {
        static void Main(string[] args)
        {
            List<Meeting> Meeting = new List<Meeting>();
            Meeting.Add(new Meeting() { Name="a", Year = 2019 });
            Meeting.Add(new Meeting() { Name="b", Year = 2019 });
            Meeting.Add(new Meeting() { Name = "c", Year = 2019 });
            Meeting.Add(new Meeting() { Name = "d", Year = 2018 });
            Meeting.Add(new Meeting() { Name = "e", Year = 2018 });
            Meeting.Add(new Meeting() { Name = "f", Year = 2017 });
            Meeting.Add(new Meeting() { Name = "g", Year = 2016 });
            Meeting.Add(new Meeting() { Name = "h", Year = 2015 });
            //string Ids = peopleList.Select(x => x.ID);

            int totalYearCount = 3;
            DateTime aDate = DateTime.Now;

            int currentYearMeetingCount = Meeting.Where(x => x.Year == aDate.Year).Count();

            if (currentYearMeetingCount == 0)
            {
                aDate = DateTime.Now.AddYears(-1);

            }

            foreach (var year in Enumerable.Range(aDate.Year - totalYearCount + 1, totalYearCount).Reverse())
            {

                var meetingList = Meeting.Where(x => x.Year == year);
                foreach (var meeting in meetingList)
                {
                    Console.WriteLine("{0}-{1}", meeting.Name, meeting.Year);
                }

            }
        }

        class Meeting
        {
            public int Year { get; set; }
            public string Name { get; set; }
        }
    }


texts: I think I should use JOIN but I did this instead

texts:
Let me start by saying that I am brand new to PHP and MySQL.

I have two tables. One table is called domains and it contains the "rep" column which is an integer. It is related to the column "id" in the reps table. The reps table also houses the First and Last names of the rep assigned to a particular domain and when I query the database to show all of the domains, I need to show rep.first_name instead of domain.rep.

The first way I thought to do it was to make a loop that will create variables with the rep names and then inside of my loop to list the domains, I'll show them. It looks like this:

//Make Query
$rep_query = "SELECT * ";
$rep_query .= "FROM reps";
$rep_query_result = mysqli_query($connection, $rep_query);
//Test for Query Error
confirm_query($rep_query_result);
$rep_i = 1;
$rep_array = array("");
while($rep = mysqli_fetch_assoc($rep_query_result)) {
    ${'rep_' . $rep_i} = $rep['first_name'];
    array_push($rep_array, ${'rep_' . $rep_i});
    $rep_i++;
}

and inside of the loop where I'm looping through the domains, I can use the variable

$rep_array[$domains['rep']]

I then did some research on JOINs and realized this is the more common way to handle relationships and things of this sort, but my way seems okay.

What would you do differently?

Here is the domain query:

    //Make Query
    $domain_query = "SELECT * "; //IGNORE THIS FOR NOW <_<
    $domain_query .= "FROM domains ";
    $domain_query .= "WHERE status = 'Available' ";
    $domain_query .= "ORDER BY ". $order;
    $domain_query_result = mysqli_query($connection, $domain_query);
    //Test for Query Error
    confirm_query($domain_query_result);

and this is the join I came up with:

    $rep_query = "SELECT ";
    $rep_query .= "r.first_name, d.rep ";
    $rep_query .= "FROM `domains` AS d ";
    $rep_query .= "INNER JOIN `reps` AS r ";
    $rep_query .= "ON r.id = d.rep ";

How is it that I use the JOIN inside of the other query / loop to automatically set the IDs to the first_name? This seems to be the part that doesn't get explained in many of the tutorials and such that I've found.


texts: Determining whether (x,y) points in the input constitute a function

texts:
I'm learning Haskell, and I've finally gotten around to coding up some Haskell. This code passed my tests.

This code takes a line from standard in which tells it how many cases it's going to have (1 to 5), and for each case, it takes a line telling it how many pairs (max of 100) of x's and y's it will get (integers from 0 to 500), and it should print YES if x to y is a function, and NO otherwise.

e.g. with a file called input:

2
2
1 1
2 1
2
1 1
1 2

The following command should work like this:

$ runhaskell main.hs < input
YES
NO

In my source code the only difference is I have two blank lines for style instead of one between each group of code. My main.hs:

import Control.Monad (replicateM_, replicateM, forM)
import Data.String (words)

main = do
  times <- readLn :: IO Int
  replicateM_ times input_is_a_function

input_is_a_function = do
  n_inputs <- readLn :: IO Int
  inputs <- replicateM n_inputs getLine
  if (null inputs) || (is_function inputs) then
    putStrLn "YES"
  else
    putStrLn "NO"

is_function inputs = is_func ([map read $ words i | i <- inputs] :: [[Int]])

is_func (x_y : rest)
  | rest == [] = True
  | otherwise  = (no_other_y x_y rest) && (is_func rest)

no_other_y [x1, y1] rest
  | rest == [] = True
  | otherwise  = this_y_ok && (no_other_y [x1, y1] (tail rest))
      where
        this_y_ok = not (x_is_target && y_not_equal)
        x_is_target = x1 == head (head rest)
        y_not_equal = y1 /= ((head rest) !! 1)
        -- if target is false, y is ok.
        -- if target is True, y must be equal

The algorithm starts with the first pair of x and y, and does a search for a repetition of x and determines if it matches y or not. Any found x with a mismatch on y should stop the algorithm.

I come from a Python background, so I tend to use snake-case and idioms I am more immediately familiar with (list comprehensions FTW!), but I want to learn idiomatic Haskell.

I also value readability. I could probably have better names. Perhaps more typing would improve readability, but I tried to take as much advantage of Hindley-Milner type inference as I could.

Please address efficiency, typing, style, naming, or any other important issues you identify.

On my workflow: I've been using a basic ghc (7.10.3) from the Ubuntu repos with a test file and that command mentioned above.

Is there a better approach? e.g. a way to watch the file and run tests as I code and save? In Haskell?


texts:
I'm looking to optimize my for loop to search faster. I've turned off ScreenUpdating, EnableEvents, Calculation, and DisplayStatusBar to speed it up a litte. I have about 10,000 rows to search for in the FAR tab. It works by reading the FAR tab rows and if it matches the master account list ("Account_Range") located in the Input tab, it won't delete the row. It will then update the rows (not shown above). I ran this and it took exactly an hour to run.

Sub DeleteRowsWithArray()

Dim dontDelete() As Variant
Dim actRange As range
Set actRange = Sheets("Input").range("Account_Range")

dontDelete = actRange

Dim i As Long, j As Long

Dim isThere As Boolean

Sheets("FAR").Select

For i = Cells(Rows.Count, "B").End(xlUp).Row To 3 Step -1
    For j = LBound(dontDelete) To UBound(dontDelete)
        If StrComp(range("B" & i), dontDelete(j, 1), vbTextCompare) = 0 Then
            isThere = True
        End If
    Next j
    If Not isThere Then
        range("B" & i).Delete shift:=xlUp
    End If
        isThere = False
Next i

End Sub


texts: Implement an algorithm to find the Kth to last element of a singly linked string

texts:
I wrote this algorithm to find the Kth element of a singly linked list and I would like your feedback because I want to know if there is a better version.

In my eyes, this is the most optimized way of doing it and I've covered every edge case (I also assumed that the only possible input is a number, if I removed that assumption, I would add another if block), but I really would appreciate your feedback.

PS: I also only added these two main methods (add and findLast) because I figured that there were the only two required to find a solution, but I'm not sure if I should add more in an interview (i.e. remove, removeAt, addAt, isEmpty, etc.)

function LinkedList() {
  let length = 0;
  let head = null;

  function Node(element) {
    this.element = element;
    this.next = null;
  }

  this.length = function() {
    return length;
  }

  this.head = function() {
    return head;
  }

  this.add = function(element) {
    let node = new Node(element);

    if (head == null) {
      head = node;
    } else {
      currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
      }
      currentNode.next = node;
    }
    length++;
  }

  this.findLast = function(index) {
    if(index > length) {
      return false;
    }
    if (index < 0) {
      return false;
    }

    let realIndexes = length-1; // if length = 5, realIndexes = 4
    let realPosition = index-1; // if index = 2, realPosition = 1
    // We are looking for the real position here.
    let realTarget = realIndexes - realPosition;
    let currentNode = head;
    let counter = 0;

    while (counter < realTarget) {
      currentNode = currentNode.next;
      counter++;
    }
    return currentNode.element;
  }
}

let congo = new LinkedList();
console.log(congo)
congo.add(5);
congo.add("Homeless");
congo.add("Real eyes realize real lies");
congo.length()
congo.head()

Output: => 5


texts:
I've created a recursive depth-first search implementation in Java as an example for an article I am writing on my website. It needs to be concise in order to fit on the page easily (independent of screen sizes), hence the lack of extra spacing.

public static boolean depthFirstSearch(TreeNode find, TreeNode top){
   if(top == null || find == null) return false;
   else if(top.equals(find)) return true;
   Enumeration children = top.children();
   while(children.hasMoreElements()){
       TreeNode next = (TreeNode) children.nextElement();
       if(depthFirstSearch(find, next)){
           return true;
       }
   }
   return false;
}

I am using javax.swing.tree.TreeNode so that I don't have to include any custom node implementations and the search is only looking for the presence of a node, not position.


texts: Managing rendering targets in XNA using IDisposable

texts:
I came up with the following class that I can use as an XNA service to manage rendering to things other than the screen as I didn't want to be passing Games/GraphicsDevices around all over the place for testing reasons. I can't see anything wrong with it, but I'm curious what other people think about the design/etc. of it and the general theory of it. Is this abusing IDisposable, or is this an ok way to do things?

Typical Usage:

using(Services.GetService<IRenderTargetController>().SetRenderTarget(renderTarget, Color.Black)) {
    // [snip] Render stuff as normal here.
}

Implementation:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

sealed class RenderTargetController : IRenderTargetController
{
    private readonly GraphicsDevice _graphicsDevice;
    private readonly Stack<RenderTarget2D> _targets;

    public RenderTargetController(GraphicsDevice graphicsDevice)
    {
        _graphicsDevice = graphicsDevice;
        _targets = new Stack<RenderTarget2D>();
    }

    public IDisposable SetRenderTarget(RenderTarget2D target)
    {
        return SetRenderTarget(target, Color.Transparent);
    }

    public IDisposable SetRenderTarget(RenderTarget2D target, Color resetColor)
    {
        _targets.Push(target);
        _graphicsDevice.SetRenderTarget(target);
        _graphicsDevice.Clear(resetColor);

        return new TargetManager(this);
    }

    private class TargetManager : IDisposable
    {
        private readonly RenderTargetController _controller;

        public TargetManager(RenderTargetController controller)
        {
            _controller = controller;
        }

        public void Dispose()
        {
            _controller._targets.Pop();

            RenderTarget2D target = null;
            if (_controller._targets.Count > 0)
            {
                target = _controller._targets.Peek();
            }

            // Setting render target to null returns control to the screen.
            _controller._graphicsDevice.SetRenderTarget(target);
        }
    }
}


texts:
I saw this question and answer about calculating pi on Stack Overflow, and I decided to write my own program for calculating pi. I used Python and only integers (I didn't want to use floating point numbers), and used the Gauss–Legendre algorithm because it was the simplest to implement (I considered using the Borwein's algorithm, but I didn't want to calculate third roots of numbers, and the Chudnovsky algorithm seemed a little complicated, although maybe I'll give it a try). I would like to know how efficient are the algorithms above, in \$\mathcal{O}(n)\$ (n is the number of digits to calculate), and how efficient is my program?

# Calculate next square root approximation of the number.
def calculate_next_square_root(number, square_root):
    next_square_root = ((number / square_root) + square_root) / 2
    return next_square_root

# Calculate the square root of the number.
def calculate_square_root(number, digits, add):
    # Start with 1, followed by (digits + add) zeros.
    square_root = 1 * (10 ** (digits + add))
    # Calculate next square root approximation of the number.
    next_square_root = calculate_next_square_root(number=number, square_root=square_root)
    while (next_square_root != square_root):
        # Replace square root with next square root.
        square_root = next_square_root
        # Calculate next square root approximation of the number.
        next_square_root = calculate_next_square_root(number=number, square_root=square_root)
    return square_root

# Calculate next pi approximation.
def calculate_next_pi(a, b, t, digits, add):
    next_pi = ((10 ** (digits + add)) * ((a + b) ** 2)) / (4 * t)
    return next_pi

# Calculate pi to 5,000 digits.
digits = 5000
add = 500
a = 10 ** (digits + add)
b = calculate_square_root(number=(10 ** ((digits + add) * 2)) / 2, digits=digits, add=add)
t = (10 ** ((digits + add) * 2)) / 4
p = 1
pi = -1 # pi must be different than next_pi
next_pi = calculate_next_pi(a=a, b=b, t=t, digits=digits, add=add)
n = 0
while (next_pi != pi):
    pi = next_pi
    next_a = (a + b) / 2
    next_b = calculate_square_root(number=a * b, digits=digits, add=add)
    next_t = t - (p * ((a - next_a) ** 2))
    next_p = 2 * p
    a = next_a
    b = next_b
    t = next_t
    p = next_p
    next_pi = calculate_next_pi(a=a, b=b, t=t, digits=digits, add=add)
    n += 1

# Remove the last 500 digits.
pi /= (10 ** add)

# Print the results.
print pi
print n

My program takes 52 lines of code (including comments), and I'm not interested in programs which take too many lines to implement, up to 100 or 200 lines are fine. I checked and it takes about one second to calculate 5,000 digits of pi (with add = 500), and a little less than two minutes to calculate 50,000 digits (with add = 5000). With 5,000 digits it took 14 iterations, and with 50,000 digits 17 iterations, but I didn't count how many iterations it took to calculate the square roots. Is my program efficiently using the Gauss–Legendre algorithm, or can it be made more efficient?

By the way, add doesn't have to be 500, even 4 or 5 is enough. But I wanted to make sure all the digits of pi are correct (and they are). With add = 0 the last 2 or 3 digits are not correct.

I took the square root program from a program I wrote in 2013, but I don't know the name of the algorithm I used and whether it's the most efficient algorithm or not.

Update: I remind you my question: I would like to know how efficient are the algorithms above, in \$\mathcal{O}(n)\$ (n is the number of digits to calculate), and how efficient is my program? I prefer not to import modules, but use pure Python (either 2 or 3) without any import. And of course if we start with a number closer to the square root (such as a or b) then it will take fewer iterations to calculate the square root.