texts: Alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes

texts:
As the title says, I have created an alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes but i feel uncomfortable to use it.(the app works fine with my class) Can you guys tell me is it ok or not? I feel like there is nothing changed. The reason i want to stop using AsyncTask is memoryleak issue.
import android.os.Handler;

public class BackgroundTask
{
    protected Handler localHandler;
    protected Thread localThread;

    public void execute()
    {
        this.localHandler = new Handler();
        this.onPreExecute(); //onPreExecute Method

        this.localThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                BackgroundTask.this.doInBackground(); //doInBackground Method
                BackgroundTask.this.localHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        BackgroundTask.this.onPostExecute(); //onPostExecute Method
                    }
                });
            }
        });
        this.localThread.start();
    }

    public void cancel()
    {
        if(this.localThread.isAlive())
            this.localThread.interrupt();
    }

    protected void onPreExecute()
    {

    }

    protected void doInBackground()
    {

    }

    protected void onPostExecute()
    {

    }
}

Example for use (I can interrupt the Thread when i want so this must be solving the leak issue but i want this code to be seen by some other programmers too.)
public class HttpPostUserScore extends BackgroundTask
{
    private final Context context;
    private Exception taskException;
    private final String point;

    public HttpPostUserScore(Context context, String point)
    {
        this.context = context;
        this.point = point;
    }

    @Override
    protected void doInBackground()
    {
        try
        {
            OkHttpClient client = new OkHttpClient();

            FormBody.Builder formBuilder = new FormBody.Builder();
            formBuilder.add("token", User.loggedUser.getToken());
            formBuilder.add("score", this.point);
            RequestBody requestBody = formBuilder.build();

            Request request = new Request.Builder().url(this.context.getString(R.string.user_score_api_url_body)).post(requestBody).build();
            Response response = client.newCall(request).execute();

            Log.println(Log.WARN, "ScorePost Response", response.body().string());
        }
        catch (Exception e) { this.taskException = e; }
    }

    @Override
    protected void onPostExecute()
    {
        if(this.taskException != null)
            Log.println(Log.ERROR, "ScorePost Error", this.taskException.getMessage());
        else
            Toast.makeText(this.context, this.point + " Points Added!", Toast.LENGTH_LONG).show();
    }
}

I have examined some codes from Facebook's android login api. They are still using AsyncTask for asynchronous programming. Is it a big deal or not?


texts: Trello list scraper that extracts all numbers from boards and logs the sum

texts:
I wrote a script that pulls all the cards in my food expenses list that are separated by months. I then extract all the numbers and log the sum to a file. Later I plan on graphing my monthly expenses and the names.

#!/usr/bin/python

from trollop import TrelloConnection
import logging
# Lots of issues with Python3. Lots of unicode, string errors, Just switched to
# py2. should try to use dicts for {name: cost} and to  practice using dicts

# TODO: Data Visualization, Error/exception handling, appending to log for running total
# TODO: clean up code, get feedback on reddit, maybe use args for spec params
# TODO: set up cron job to run every month

api_key = '####' # TRELLO_API_KEY
token = '####'
# idBoard': '577b17583e5d17ee55b20e44',
# idList': '577b17583e5d17ee55b20e45',
# Set up basic logging
logging.basicConfig(format='%(levelname)s %(message)s',
    level=logging.INFO, filename='trello_expenses.log', filemode='w')

# Establish connection
conn = TrelloConnection(api_key, token)
months = ['January', 'February', 'July', 'August', \
          'September','October','November', 'December']
# Get expenses board via ID

logging.info("Iterating through boards...")

# for board in conn.me.boards:
#     # logging.info("id: {}".format(each._id))
#     # print u"board name: {0}, board id {1}" . format( board.name, board._id )
#     logging.info (u"board name: {0}, board id {1}".\
#                     format( board.name, board._id ))

# for each_card in conn.me.boards[2].cards:
#     print u"{0},{1},{2}".format(each_card._id, each_card.url,each_card.desc)

def main():
    total = 0.0
    costs = list()
    names = list()

    # get first index i.e the list im currently working on
    board = conn.get_board('BE89pW61')
    board_lists = board.lists
    current = board_lists[0]
    # Get all lists  names and ids in board
    for entry in board_lists:

        if 'august' in entry.name.lower():
            # print u'List name: {0} list id: {1}'.format (entry.name, entry._id)

            for cards in entry.cards:
                name, cost =  cards.name.split('-')
                costs.append(float (cost) )
                # print cards.name
            # print costs
    total = sum (costs)
    print 'total is {}'.format( total )

if __name__=='__main__':
    main()


texts:
I'm trying to have the 3 buttons to each open its own list below whilst closing any current active lists open. I've tried my best with the jQuery, but it seems so bloated. Is there a way to streamline this jQuery code?

At the moment I have a very rough working example.

/***********************
Mobile Menus
*********************************/

(function() {
   var nav = $('.social_icons_list ul');
    $.fn.navtoggle = function(speed) {
         var $this = $(this);

        return $this.animate({
            'height': 'toggle'
        }, 500);
    }

    $('.socialNav').on('click', function() {
        nav.stop(true, true).navtoggle(300);
        $("ul").not(nav).hide();
        e.preventDefault();
    });
})();

(function() {
   var nav = $('.dogz_list ul');
    $.fn.navtoggle = function(speed) {
         var $this = $(this);

        return $this.animate({
            'height': 'toggle'
        }, 500);
    }

    $('.dogzNav').on('click', function() {
        nav.stop(true, true).navtoggle(300);
        $("ul").not(nav).hide();
        e.preventDefault();
    });
})();

 (function() {
   var nav = $('.navigation_list ul');
    $.fn.navtoggle = function(speed) {
         var $this = $(this);

        return $this.animate({
            'height': 'toggle'
        }, 500);
    }

    $('.Nav').on('click', function() {
        nav.stop(true, true).navtoggle(300);
        $("ul").not(nav).hide();
        e.preventDefault();
    });
})();


texts:
I just wrote a PHP code to register users.

It's called through AJAX and it looks like it's too slow because it often sent me a .status = 0 that it means it took too much time to proceed.

If i replace my php function that register only by :

echo "Ok";

It always sent me a .status = 200

Could someone helps me to improve this file to make it faster ? I'm not used to code in PHP.

<?php

require_once('../config/database.php');
require_once('../config/functions.php');
$keywords = preg_split("/MyWebSite\//", getcwd());
$folder = explode('/', $keywords[1]);

if (!isset($_POST['login']) || !isset($_POST['email']) || !isset($_POST['password']) || !isset($_POST['password_check']))
{
    echo "missing some fields, did you try to edit my html?";
    die();
}
if (strlen($_POST['login']) < 5 || strlen($_POST['email']) == 0 || strlen($_POST['password']) < 5 || strlen($_POST['password_check']) < 5)
{
    echo "fieds badly filled";
    die();
}
if ($_POST['password'] != $_POST['password_check'])
{
    echo "passwords field aren't same";
    die();
}

try
{
    $db = new PDO($DB_DSN, $DB_USER, $DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // to get an exception when caught an error :)
} catch (PDOException $e) {
    print "Erreur !: " . $e->getMessage() . "<br/>";
    die();
}

$count_login = $db->prepare("SELECT COUNT(*) FROM camagru_jgengo.user WHERE login = :login");
$count_login->bindValue(':login', $_POST['login']);
$count_login->execute();
if ($count_login->fetchColumn() > 0)
{
    echo "This username already taken";
    die();
}

$count_email = $db->prepare("SELECT COUNT(*) FROM camagru_jgengo.user WHERE email = :email");
$count_email->bindValue(':email', $_POST['email']);
$count_email->execute();
if ($count_email->fetchColumn() > 0)
{
    echo "This email already taken";
    die();
}

$insert = $db->prepare('INSERT INTO camagru_jgengo.user (email, login, password, admin, validate_link, created_at) VALUES (:email, :login, :password, 0, :validate_link, :created_at)');
$arr = array(
    ":login" => $_POST['login'],
    ":password" => hash_it($_POST['password']),
    ":email" => $_POST['email'],
    ":validate_link" => hash('md5', time()),
    ":created_at" => date('Y-m-d')
    );
$insert->execute($arr);

echo "Created!\n";

mail ($_POST['email'], "[Camagru] Active your account", "To active your account click that link : http://localhost:8080/".$folder[0]."/?p=activate&hash=".$arr[':validate_link']);

?>


texts: Wrapping a third party package class to achieve decoupling from the package

texts:
I want to create a wrapper around this third party package class so that I don't litter my app with calls to it. The idea being that if there are breaking changes to the package (rename the class or one of its members), or if I want to delete the package, I can just change my implementation of it in this one file. Here is the third party package class:
abstract class GetWidget<T extends DisposableInterface>
    extends GetStatelessWidget {
  GetWidget({Key key}) : super(key: key);

  final Set<T> _value = <T>{};

  final String tag = null;

  T get controller {
    if (_value.isEmpty) _value.add(GetInstance().find<T>(tag: tag));
    return _value.first;
  }

  @override
  Widget build(BuildContext context);
}

Here is my attempt to wrap it (Vp is my app prefix identifying that it was created by my app):
abstract class VpWidget<T extends DisposableInterface> extends GetWidget<T> {
  VpWidget({Key key}) : super(key: key);

  @override
  T get controller {
    return super.controller;
  }
}

It seems to work. The class is so small anyway so i don't think I can wrap anything more from it. Just wondering if this is an effective use of a wrapper for decoupling my app from the package, or if there is no use and I should just call the package class directly?


texts: Remove the first N elements from an array while reducing the N variable

texts:
I'm trying to remove the first $offset elements from an array and reduce the offset for future adds to the array. The loop must also end if I reach the end of the array.

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

I'm trying to find a better way to do it. At least a way to use the values of $offset and count($elements) (which are changing) without having to create aux variables.


texts:
Below I have a simple method that will merge a figure code with a uniform code, let me talk more about that and how it works so you guys have a neat understanding.

Each character on my gaming emulator has a unique figure code, unless their dressed the exact same of course but unlikely, here is an example of a few figure codes.

lg-285-76.hr-155-31.sh-300-92.ca-1819-63.hd-209-2.ch-3030-76
he-3149-1331.sh-3035-110.hr-170-61.fa-3276-72.ch-255-110.hd-209-2.lg-280-1331
ch-210-110.hd-209-7.hr-828-1407.he-3082-63.lg-280-1408.cp-3309-77.sh-290-92

Above is 3 examples of a figure string, I wont go as far as explaining each part as its not relevant in this question (as of now).

So, each character has a figure code and then there is a few uniform codes. Now the uniform codes usually only contain the ch and lg parts for chest and leg, which is usually all a uniform needs, except I have coded this method to replace any parts of the uniform into the figure code with the uniform part. Here is a few examples of the uniform figure codes..

(Legs, Shoes and Chest)
lg-285-76.sh-300-92.ca-1819-63.ch-3030-76
(Legs and Chest)
lg-280-110.ch-1004-110

So what am I asking?
I am asking for some ways to improve the performance of this method.

Edit: I've added functionality to choose which parts you want to replace, with a list string as the second parameter, which is default empty (replaces all parts).

Here is the method:

public static string ReturnUniform(string uniform, string figure, List<string> partsToReplace = new List<string>())
{
    List<string> uniformParts = uniform.Split('.').ToList();
    List<string> figureParts = uniform.Split('.').ToList();

    foreach (string uniformPart in uniformParts)
    {
        string[] parts = uniformPart.Split('-');
        string part = parts[0];

        if (partsToReplace.Any() && !partsToReplace.Contains(part))
        {
            continue;
        }

        if (figure.Contains(part + "-"))
        {
            var indexOfItem = figureParts.ToList().FindIndex(value => value.StartsWith(part));
            figureParts[indexOfItem] = uniformPart;
        }
        else
        {
            figureParts.Add(uniformPart);
        }
    }

    return string.Join(".", figureParts);
}


texts: Search for all matching users and security groups using System.DirectoryServices.AccountManagement

texts:
I am attempting to return all users and security groups that begin with the provided substring. The following does work but I suspect there may be a better way to write this and am interested in both improving the performance and the style of the Search function.

ActiveDirectory.cs

public static class ActiveDirectory
    {

        public static IEnumerable<Recipient> Search(string search)
        {
            var recipients = new List<Recipient>();

            using (var ctx = new PrincipalContext(ContextType.Domain))
            {
                search = $"{search}*";

                var userPrincipals = new List<UserPrincipal>
                {
                    new UserPrincipal(ctx) {DisplayName = search},
                    new UserPrincipal(ctx) {Name = search},
                    new UserPrincipal(ctx) {SamAccountName = search}
                };

                foreach (var principal in userPrincipals)
                {
                    foreach (var usr in new PrincipalSearcher(principal).FindAll())
                    {
                        if (!(usr is UserPrincipal user) || recipients.Any(m => m.Name == (user.DisplayName ?? user.Name) && m.Type == RecipientType.Group)) continue;
                        recipients.Add(new Recipient()
                        {
                            Name = user.SamAccountName,
                            DisplayName = user.DisplayName ?? user.Name,
                            Type = RecipientType.User
                        });
                    }
                }

                var groupPrincipals = new List<GroupPrincipal>
                {
                    new GroupPrincipal(ctx) {DisplayName = search},
                    new GroupPrincipal(ctx) {Name = search},
                    new GroupPrincipal(ctx) {SamAccountName = search}
                };

                foreach (var principal in groupPrincipals)
                {
                    foreach (var grp in new PrincipalSearcher(principal).FindAll())
                    {
                        if (!(grp is GroupPrincipal group) || recipients.Any(m => m.Name == (group.DisplayName ?? group.Name) && m.Type == RecipientType.Group)) continue;
                        recipients.Add(new Recipient()
                        {
                            Name = group.SamAccountName,
                            DisplayName = group.DisplayName ?? group.Name,
                            Type = RecipientType.Group
                        });
                    }
                }
            }

            return recipients;
        }

    }

Recipient.cs

public class Recipient
    {
        public Guid? Id { get; set; }
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public RecipientType Type { get; set; }

        public Guid? ChannelId { get; set; }
    }

RecipientType.cs

public enum RecipientType
    {
        User,
        Group
    }


texts:
I wrote this to sort of gauge my understanding of the bare basics of C++.Could you guys give me any pointers? (Ha, get it?). I would happy to hear what you have to say about the code. Also is it neat (aesthetically as well as functionally)?

#include <iostream>
bool end = false;
int w_combinations[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
int pos[] = {1,2,3,4,5,6,7,8,9};
void check (int x) {
    if ( x == 10) {
        std::cout << "X|";
    }
    else if (x == 11) {
        std::cout << "O|";
    }
    else {
        std::cout << x << "|";
    }
}
void printMatrix() {
    std::cout << "|" ; check(pos[0]) ; check(pos[1]) ; check(pos[2]);std::cout << "\n";
    std::cout << "|" ; check(pos[3]);check(pos[4]) ; check(pos[5]);std::cout << "\n";
    std::cout << "|" ; check(pos[6]) ; check(pos[7])  ; check(pos[8]); std::cout << "\n";
}
void input(int z , int player) {
    if (player == 1 && pos[z-1] != 10 && pos[z-1] != 11) {
        pos[z-1] = 10;
    }
    else if (player == 2 && pos[z-1] != 10 && pos[z-1] != 11){
        pos[z-1] = 11;
    }
    else {
        std::cout << "\nInvalid! Try again: ";
        int y;
        std::cin >> y;
        input(y,player);

    }
}

//Winning mechanism: Simply cylce through all combos.
bool win() {
    for (int i = 0 ; i < 8 ; ++i) {
        if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]] && pos[w_combinations[i][0]] == pos[w_combinations[i][2]])
        {
            return true;
            break;
        }
    }
    return false;
}
int main() {
    int count = 0;          //Cycle through draws
    while (1)
    {
        int z;
        printMatrix();
        std::cout << "1[X]:";
        std::cin >> z;
        input(z,1);
        if (win()) {std::cout << "Player 1 wins!\n";break;}
        ++count;
        printMatrix();
        if (count == 9) {
            std::cout << "Draw!";
            break;
        }
        std::cout << "2[O]:";
        std::cin >> z;
        input(z,2);
        if (win()) {std::cout << "Player 2 wins!\n";break;}
        ++count;
        if (count == 9) {
            std::cout << "Draw!";
            break;
        }
    }
    std::cout << "Play again[Yes = 1, No = 0]: ";
    int permission;
    std::cin >> permission;
    if (permission == 1) {
        std::cout << "\n\n";
        main();
    }
}


texts:
Intro
This simple script will allow me to check for a specific opened port on a list of domains that I own. Instead of manually doing this check, I found Python a pretty good idea for such a task.
After profiling my code, I found out that def check_for_open_ports(): is really slow. It takes about 0:01:16.799242 seconds for 4 domains.
I wondered if there's a good / recommended way of improving this (maybe multithreading / multiprocessing). While asking for an answer which implements one of the above two methods is forbidden here, I wouldn't mind seeing one. I know that one shall use multiprocessing when there're I/O bound tasks which makes me believe I might go with a multithreading solution.

The code
from socket import gethostbyname, gaierror, error, socket, AF_INET, SOCK_STREAM
from sys import argv, exit
import re

DOMAINS_FILE = argv[1]
PORT = argv[2]
OUTPUT_FILE = argv[3]

def get_domains():
    """
    Return a list of domains from domains.txt
    """
    domains = []
    if len(argv) != 4:
        exit("Wrong number of arguments\n")
    try:
        with open(DOMAINS_FILE) as domains_file:
            for line in domains_file:
                domains.append(line.rstrip())
    except IOError:
        exit("First argument should be a file containing domains")
    return domains

def check_domain_format(domain):
    """
    This function removes the beginning of a domain if it starts with:

    www.
    http://
    http://www.
    https://
    https://www.
    """
    clear_domain = re.match(r"(https?://(?:www\.)?|www\.)(.*)", domain)
    if clear_domain:
        return clear_domain.group(2)
    return domain

def transform_domains_to_ips():
    """
    Return a list of ips specific to the domains in domains.txt
    """
    domains = get_domains()
    domains_ip = []
    for each_domain in domains:
        each_domain = check_domain_format(each_domain)
        try:
            domains_ip.append(gethostbyname(each_domain))
        except gaierror:
            print("Domain {} not ok. Skipping...\n".format(each_domain))
    return domains_ip

def check_for_open_ports():
    """
    Check for a specific opened PORT on all the domains from domains.txt
    """
    ips = transform_domains_to_ips()
    try:
        with open(OUTPUT_FILE, 'a') as output_file:
            for each_ip in ips:
                try:
                    sock = socket(AF_INET, SOCK_STREAM)
                    result = sock.connect_ex((each_ip, int(PORT)))

                    if result == 0:
                        output_file.write(each_ip + '\n')
                    sock.close()
                except error:
                    print("Couldn't connect to server")
    except KeyboardInterrupt:
        exit("You pressed CTRL + C. Will exit now...\n")

if __name__ == '__main__':
    check_for_open_ports()

A step further
After some checks, I realised that what was mainly slowing down the program can be improved by reducing the default timeout from the socket module using setdefaulttimeout(2).
Even if this solved a part of the problem, I still don't find it to be the cleanest one. Any advice related to performance is really welcome !

Extra info:

I'll probably use this only on Linux OSs
I've used Python 2.7.13

PS: I'd like you to ignore the fact that I didn't use optparse or argparse for parsing CLI arguments.


texts:
To add line numbers to a file (via stdin to stdout) we can use cat -n or nl.

Given the file test.txt with:

hello
hello
bye

We can do:

$ cat -n < test.txt
     1  hello
     2  hello
     3  bye

In languages like AWK, Perl, and Ruby, we often get built-in constructs to process files line-by-line, making this program trivial to write. Here is what I have in Ruby:

line_number = 0;
ARGF.each {|line| printf("%6d\t%s", line_number += 1, line)}

and granted, in AWK, it is much simpler since the line number is already present.

I've just tried to write this same script in node.js but found myself having to import the built-in fs module and then import three separate third-party modules.  My solution is:

var fs = require('fs');
var through = require('through');
var split = require('split');
var sprintf = require('sprintf').sprintf;

var linenum = 0;

var number = through(function (line) {
  this.queue(sprintf('%6d\t%s\n', ++linenum, line));
});

process.stdin.pipe(split()).pipe(number).pipe(process.stdout);

This is not intended to be a code-golfing problem, but rather a question of whether I have missed some built-in support for doing this kind of thing in node.  I like the separation of concerns, but what I thought would be a simple script in node turned out rather long.  Can it be improved?


texts: Determine the height of a Tetris game's board after a sequence of moves

texts:
I have written a program that will determine the height of a Tetris board after a sequence of moves are made. These inputs are in the form of a comma-delimited list, and look like <piece><position>. List of pieces:

I - this is a 1x4 piece lying on its side
Q - this is a 2x2 square piece
T - this is a T-shaped piece
Z - this is a left-facing 2x2 offset
S - this is a right-facing 2x2 offset
L - this is a right-facing L
J - this is a left-facing L

Image (source) of the pieces. Pieces are always in the same orientation as below.

I've diagrammed them out below as well. Rotation is not in scope for this problem (e.g. a vertical I is out of scope).
I - xxxx
Q - xx
    xx
T - xxx
     x
Z - xx
     xx
S -  xx
    xx
L - x
    x
    xx
J -  x
     x
    xx

Positions are 0-indexed, and represent a location from the left side of the board (the board is 10-wide).
Example 1:
Input: I0,Q4
Output: 2
Board:
bbbbQQbbbb
IIIIQQbbbb

(b represents a blank space, and the blank lines above this are left out)
Example 2
Input: Q0,Q2,Q4,Q6,Q8
Output: 0
Board (intentionally left blank):

Explanation: Using normal Tetris rules, a row is removed whenever every block in a row is filled. This sequence would place 5 square cubes evenly spaced along the bottom, which then removes those two rows.
class Tetris:
    def __init__(self):
        self.board =[]
        self.pieces = {
            'I' : [[1,1,1,1]],

            'Q' : [[1,1],
                   [1,1]],

            'T': [[1,1,1],
                  [0,1,0]],

            'Z':[[1,1,0],
                 [0,1,1]],

            'S':[[0,1,1],
                 [1,1,0]],

            'L':[[1,0],
                 [1,0],
                 [1,1]],

            'J':[[0,1],
                 [0,1],
                 [1,1]]}

    def newRow(self):
        return [0 for _ in range(10)]

    def doesThePieceFit(self,row,pieceName,pos):
        #checks to see if a piece fits on the row at given position
        #check bottom to the top
        piece = self.pieces[pieceName]
        for i in range(len(piece)):
           pieceRow = piece[-1*(1+i)]
           if i+row == len(self.board): return True
           boardRow = self.board[i+row]
           for j in range(len(pieceRow)):
               if pieceRow[j] and boardRow[pos+j]: return False
        return True

    def removeFullRows(self,startRow,numRows):
        #removes full rows from the board
        #only checks rows between startRow and startRow+numRows
        fullRows = [i+startRow
                    for i in range(numRows)
                    if all(self.board[i+startRow])]
        for fullRow  in sorted(fullRows,reverse=True):
            del self.board[fullRow]

    def addPieceAt(self,row,pieceName,pos):
        #Adds piece at this row.
        piece = self.pieces[pieceName]
        for i in range(len(piece)):
           pieceRow = piece[-1*(1+i)]
           if i+row == len(self.board):
               self.board+=self.newRow(),
           boardRow = self.board[i+row]
           for j in range(len(pieceRow)):
               if pieceRow[j]:
                   boardRow[pos+j] = pieceRow[j]
        self.removeFullRows(row,len(piece))

    def addPiece(self,pieceName,pos):
        #1.find the first row where piece is blocked
        #2.Add the piece at the row above it
        blockedByRow = None
        for row in range(len(self.board)-1,-1,-1):
            if not self.doesThePieceFit(row,pieceName,pos):
                blockedByRow = row
                break

        targetRow = 0 if  blockedByRow == None else blockedByRow+1
        self.addPieceAt(targetRow,pieceName,pos)

    def addPieces(self,pieces):
        for piece in pieces.split(','):
            self.addPiece(piece[0],int(piece[1]))
        return len(self.board)


texts:
I started to learn data structures. How can I improve my implementation? For example, I don't now how to push 0 or how to realize my own resize.

public class Stack: IStack
{
    private int[] s;

    public Stack(int N)
    {
        s = new int[N];
    }

    public void push(int x)
    {
        int i = 0;
        while (s[i] != 0)
        {
            ++i;
        }

        if (i+1 >= s.Length)
        {
            Array.Resize(ref s, s.Length*2);
        }

        s[i] = x;
    }

    public int pop()
    {
        int i = 0;

        while (i != s.Length && s[i] != 0)
        {
            i++;
        }

        s[i] = 0;
        return s[i - 1];
    }
}


texts: Makefile for a document generation system

texts:
This is my first shot at writing a makefile for a document generation system. Please identify any more ways to refine it. Some pointers on how it works:

The INPUT files initially are templates to be edited and are copied to the "src" directory upon first execution only.
The code at the beginning tests for an environment variable equal to the directory path containing the input templates.
The desired files will be in the "output" directory
The file formats used include mustache templates for asciidoctor (.mst.adoc), asciidoctor (.adoc), HTML, and PDF. One adoc file uses asciidoctor-reveal.js, an HTML slide generator.

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))
#TEST ENVIRONMENT VARIABLES
$(call check_defined, TEACH_PROJ)

#DIRECTORIES:
PRJ=$(TEACH_PROJ)
OUT=../output/
BLD=../build/
ADC=asciidoctor
MST=mustache

#OUTPUT
HTM_NOT=$(OUT)notes.html
HTM_PRS=$(OUT)presentation.html
HTM_VOC=$(OUT)vocabulary.html
PDF_PRS=$(OUT)presentation.pdf
#INTERMEDIATE
ADC_PRS=$(BLD)presentation.adoc
ADC_VOC=$(BLD)vocabulary.adoc
#INPUT
YML_VOC=vocabulary.yml
FIL_GEM=Gemfile
MST_PRS=presentation.mst.adoc
MST_VOC=vocabulary.mst.adoc
#RECIPES
RCP_COPY=cp -an $(PRJ)$@
RCP_MKD=mkdir -p $@
RCP_ADC=$(ADC) $< -o $@
RCP_RJS=bundle exec $(ADC)-revealjs -o $@ $<
RCP_PDF=$(RCP_ADC) -r $(ADC)-pdf -b pdf -a pdf-stylesdir=$(PRJ) -a pdf-style=compact
RCP_MST=$(MST) $(YML_VOC) $< > $@

all: $(HTM_PRS) $(HTM_NOT) $(PDF_PRS) $(HTM_VOC)
$(HTM_PRS):  $(ADC_PRS) $(FIL_GEM)|$(OUT); $(RCP_RJS)
$(PDF_PRS): $(ADC_PRS)|$(OUT); $(RCP_PDF)

TARGETS=$(HTM_NOT) $(HTM_VOC)
$(HTM_NOT): $(ADC_PRS)|$(OUT)
$(HTM_VOC): $(ADC_VOC)|$(OUT)
$(TARGETS): ;$(RCP_ADC)

#build:
TARGETS=$(ADC_PRS) $(ADC_VOC)
$(ADC_PRS): $(MST_PRS) $(YML_VOC)|$(BLD)
$(ADC_VOC): $(MST_VOC) $(YML_VOC)|$(BLD)
$(TARGETS): ;$(RCP_MST)
#input
$(YML_VOC) $(MST_VOC) $(MST_PRS) $(FIL_GEM): ; $(RCP_COPY) .
$(OUT) $(BLD): ; $(RCP_MKD)
clean: ; rm -rf $(BLD) $(OUT)

```


texts: Tidying up jquery code for linking inputs

texts:
I have three input boxes that are all linked to each other by some pretty basic rules:

Editing the page title will copy the contents to menu title

  Unless menu title has been manually edited
  clearing menu title sets it back to automatic

Editing the menu title will copy the contents as a url slug to slug

  Unless the slug has been manually edited
  clearing the slug sets it back to automatic
  Editing page title counts as editing menu title if it is set to automatic

The Page Title, and the other two boxes are never visible at the same time!

Here is a demo: http://jsfiddle.net/6VPpj/1/

and here is my rather horrible code, how can I clean this up?

$(function(){
var automatic = true;
var pager = true;
var cache = {};

var slug = $('#slug');
var menu = $('#menu_title');
var page = $('#page_title');

page.on('change', function() {
    if (pager) {
        menu.val(page.val());
        menu.keyup();
    }
});

menu.on('keypress keyup keydown change', function() {

    if (automatic) {
        var n = menu.val();
        if (n in cache) {
            slug.val(cache[n]);
            return;
        }

        cache[n] = toSlug(n);
        slug.val(cache[n]);

        return;
    }
});
menu.on('change', function() {
    if (menu.val() == '') {
        pager = true;
        page.change();
    }
    else {
        pager = false;
    }
});

slug.on('change', function() {
    if (slug.val() == '') {
        automatic = true;
        menu.keyup();
    }
    else {
        automatic = false;
        var n = slug.val();
        if (n in cache) {
            slug.val(cache[n]);
            return;
        }
        cache[n] = toSlug(n);
        slug.val(cache[n]);
        return;
    }
});

function toSlug(Text) {
    return Text.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-');
}
});


texts:
I'm really concerned about my transaction with a database and my code structure. I have created more methods to insert, update, delete data to the database but sometimes some of them will break or miss. That's why I try to use Laravel transaction and PHP catch and throw exceptions to rollback and avoid any errors happening during those method processes.

By they way, I don't yet understand how try/catch and Laravel transaction catch those errors and return or throw to the end user.

However, I've tried to find all kind of errors will happen and how I can throw those error types to the end users in the catch block.

This function work find but I want to check if any errors happen and how I can return those type of errors to the end user by using Laravel transaction and try.

public function Dosomething($id)
    {
     if (Request::ajax()) {
        $data = [
          'till_account_id' => Request::input('till_account_id'),
          'from_account' => Request::input('from_account'),
          'to_account' => Request::input('to_account'),
          'till_user_id' => Request::input('till_user_id'),
          'branch_id' => Request::input('branch_id'),
          'operate_by' => Request::input('operate_by'),
          'type' => Request::input('type'),
         'tranx_time' => date('Y-m-d H:m:s', time())
       ];
      DB::beginTransaction();
     try {
         $update = Teller::where('id', '=', $id)->update(['balance' => Request::input('balanceCommision')]);
         if (!empty($update)) {
             $data['cash_out'] = Request::input('cash_out');
             $trans_cashIn = DB::table('till_transaction')->insertGetId($data);

             $data['cash_in'] = Request::input('cash_in');
             $data['cash_out'] = 0;
             $trans_cashOut = DB::table('till_transaction')->insertGetId($data);
        }
            $test = DB::commit();
            return ['up' => $update, 'insCashIn' => $trans_cashIn, 'insCashOut' => $trans_cashOut, 'data' => $data, 'cash_out' => $data['cash_out'],'commit'=>$test];
       } catch (Exception $e) {
           DB::rollBack();
           throw $e;
      }
   }
}


texts: Gray-level co-occurrence matrix feature computation

texts:
I have many images and want to compute the GLCM properties for every image. Below my code that runs many hours to complete the task:

import numpy as np
from skimage.feature import greycomatrix, greycoprops

ANGLES = [0., np.pi/4., np.pi/2., 3.*np.pi/4.]
DISTANCES = [1,2]
properties = ["correlation", "contrast", "homogeneity", "energy"]
n_img = 1000

I = np.random.randint(0,255,size=(n_img, 100, 100))

stats = []
for k in range(n_img):
    glcm = greycomatrix(I[k], distances=DISTANCES, angles=ANGLES, levels=256, symmetric=True, normed=True)
    prop = [np.mean(greycoprops(glcm, properties[i])) for i in range(len(properties))]
    stats.append(prop)
stats = np.array(stats)

This code is a real bottleneck. How can parallelize the task? Are there other ways to speed up the code?


texts:
I was given a school assignment to implement atoi(). Please review my code.

int my_atoi(char *ato)
{
    int res;
    int sign;

    res = 0;
    sign = 1;
    while (*ato == ' ' || *ato == '\t' || *ato == '\n' || *ato == '\f' || *ato == '\r')
        ato++;
    if (*ato == '-')
        sign = -1;
    if (*ato == '-' || *ato == '+')
         ato++;
    while (*ato >= '0' && *ato <= '9')
    {
        res = res * 10 + *ato - '0';
        ato++;
    }
    return (sign * res);
}


texts: Reacting to Boolean state in reactive ViewModels

texts:
When this ViewModel loads we kick off the IsAuthenticatedCommand:

If the result of IsAuthenticatedCommand is false we set the value of NeedsToLogin to true.
If the result of IsAuthenticatedCommand is true we set the value of IsAuthenticated to true.

There are (subscriptions?) to both NeedsToLogin and IsAuthenticated that are waiting for the true value.

Is there a better way to handle this if/else logic?
Should I be worried about race conditions?

public class LoadingViewModel : ReactiveObject, IRoutableViewModel {

    private bool _isAuthenticated = false;

    public bool IsAuthenticated {
    get { return _isAuthenticated; }
    set { this.RaiseAndSetIfChanged (ref _isAuthenticated, value); }}

    private bool _needsToLogin;

    public bool NeedsToLogin {
    get { return _needsToLogin; }
    set { this.RaiseAndSetIfChanged (ref _needsToLogin, value); }}

    public ReactiveCommand<bool> IsAuthenticatedCommand { get; protected set; }

    public LoadingViewModel (IScreen screen)
    {
        HostScreen = screen;

        this.WhenAnyValue (x => x.IsAuthenticated)
            .Where (x => x == true)
            .Subscribe (x => { HostScreen.Router.Navigate.ExecuteAsyncTask (new OnboardingViewModel (HostScreen));});

        this.WhenAnyValue (x => x.NeedsToLogin)
            .Where (x => x == true)
            .Subscribe (_ => { HostScreen.Router.Navigate.ExecuteAsyncTask (new LoginViewModel (HostScreen)); });

        //always return false for testing.
        IsAuthenticatedCommand = ReactiveCommand.CreateAsyncTask (async (_) => await Task.Run (() => {return false;}));

        IsAuthenticatedCommand.Subscribe (_ => {
        if (_) { this.IsAuthenticated = true;} else {this.NeedsToLogin = true;}
        });
    }
}


texts: Loop through database and run shell commands with Python and exiftool

texts:
Briefly, I'm looking at getting the code below to execute faster. I have 100k images to go through. I'm running a query against MySQL, looping through results and then running exiftool against an image, then moving it.

I started running it and it quickly became evident it wouldn't be a quick thing :-(

import mysql.connector
import os

cnx = mysql.connector.connect(user='root',database='database', password='password')
cursor = cnx.cursor()

query = ("SELECT post_title,Event,File,Name from a order by File")

cursor.execute(query)

def shellquote(s):
    return s.replace("'", "")

for (post_title, Event,File,Name) in cursor:
    olddir = r'/home/alan/Downloads/OLD/'
    newdir = r'/home/alan/Downloads/NEW/' + post_title

    oldfile = olddir + File
    newfile = newdir + "/"+File

    if not os.path.exists(newfile):
        os.makedirs(newfile)
    if os.path.isfile(oldfile):
        print " > PROCESSING: " + oldfile
        os.system("exiftool -q "+shellquote(oldfile)+" -xmp:title='"+shellquote(post_title)+"'")
        os.system("exiftool -q "+shellquote(oldfile)+" -xmp:description='"+shellquote(Name)+" courtesy of https://www.festivalflyer.com'")
        os.system("exiftool -q "+shellquote(oldfile)+" -description='"+shellquote(Name)+" courtesy of https://www.festivalflyer.com'")
        os.rename(oldfile, newfile)
cursor.close()
cnx.close()

I tried using subprocess but for whatever reason, I didn't get it to run. Any advice is welcome.

I suppose I could move the 3 lines of exiftool commands to just one and pass multiple arguments. I also saw -stay_open as an option to exiftool but not sure how to apply it


texts: Code to calculate minimum number of pushes required to put the whole dominoes set down

texts:
The question is this one on UVa, and it basically gives us n, the number of dominoes and (a,b) relations such that pushing a will cause b to fall down too. First t, the test cases is inputted and then number of vertices and edges, and the (a,b) relations.

My approach

My approach was I first run a dfs on the graph (till all elements are reached) and maintain an array that shows when each vertex was reached [somewhat inspired from Kosaraju's algo for SCCs]. If a->b->c is my dfs tree, reached[c] will be equal to 3, reached[b] be 2, and reached[a] be 1. This step is O(vertices+edges).

Then I run DFSs from vertices starting from those with minimum reached value. Every time the DFS runs, I increment a counter. This is also O(vertices+edges).

I tried for smaller test cases and got the right answer, but submitting on UVa gives me TLE. I don't know if my logic is wrong or if my implementation is messed up somewhere. The code is here:

#include<bits/stdc++.h>
using namespace std;

int n,counter,reached[100002],visited[100002],visiting[100002];
void dfs(int u,vector< vector<int> > graph){
    visiting[u]++;
    for(auto const& i:graph[u]){
        if(!visiting[i])
            dfs(i,graph);
    }
    visited[counter]=u;
    counter--;
}
void dfs2(int u,vector< vector<int> > graph){
    reached[u]++;
    for(auto const& i:graph[u]){
        if(!reached[i])
            dfs2(i,graph);
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        memset(visiting,0,sizeof visiting);
        memset(visited,0,sizeof visited);
        cin>>n;
        vector< vector<int> > graph(n+1);
        int m;
        counter=n;
        cin>>m;
        while(m--)
        {
            int a,b;
            cin>>a>>b;
            graph[a].push_back(b);
        }
        int mcounter=0;
        for(int i=1;i<n+1;i++)if(!visiting[i])dfs(i,graph);
        memset(reached,0,sizeof reached);
        for(int i=1;i<n+1;i++){
            if(!reached[visited[i]]){
                dfs2(visited[i],graph);
                mcounter++;
            }
        }
        cout<<mcounter<<'\n';
    }
    return 0;
}


texts:
I want to establish a hierarchy, where at each level of the hierarchy, each type can contain a list<its own type>.  So Node (root of object class hierarchy) contains a list<Node*>, SpecialNode : Node contains a list of SpecialNode.  SpecialNode should not "accidentally" put new SpecialNode children into the list<Node*> in the base class, so the list<> are private.

I personally hate the concept of namehiding, because it is extremely prone to mistakes, uninitialized values, etc.  So here I have made it impossible (via private) for SpecialNode to "accidentally" insert into the list<Node*> instead of its own list<SpecialNode*>.

struct Node
{
private:
  list<Node*> children ;

protected:
  int v ;

public:
  Node( int iv ) : v(iv) { }

  virtual void print( const char* msg )
  {
    printf( "REGULAR CHILD %d in %s\n", v, msg ) ;
    for( Node *sn : Node::children )
      sn->print( "regular" ) ;

  }
} ;

struct SpecialNode : public Node
{
private:
  list<SpecialNode*> children ;

public:
  SpecialNode( int iv ) : Node(iv) { }
  void add( SpecialNode* child ) {
    children.push_back( child ) ;
  }

  void print( const char* msg )
  {
    printf( "SPECIAL CHILD %d in %s\n", v, msg ) ;
    for( SpecialNode *sn : children )
      sn->print( "special" ) ;

    //for( Node *sn : Node::children )
    //  sn->print( "regular" ) ;
  }

} ;

int main(int argc, const char * argv[])
{
  SpecialNode *sn = new SpecialNode( 1 ) ;

  // SpecialNodes must contain SpecialNode children.
  sn->add( new SpecialNode( 2 ) ) ;
  //sn->children.push_back( new Node( 3 ) ) ; // fails b/c Node is too basic to fit in SpecialNode container.

  sn->print( "root" ) ;

}

Is this a good way to do this, or is there a better way?


texts: Sum of primes between two number from optimized Sieve of Eratosthenes

texts:
Here is the code that I wrote to give me sum of prime numbers between n and m:

class TestClass {
    final static int MAX=1000000;
    final static boolean[] isPrime=isPrime();
    public static void main(String args[] ) throws Exception {
        BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(keyboard.readLine());

        while(t>0 && t<=100){
            String[] tempInt=keyboard.readLine().split(" ");
            int n=Integer.parseInt(tempInt[0]);
            int m=Integer.parseInt(tempInt[1]);

            int sum=primeSum(n,m);
            System.out.println(sum);
            t--;
        }
    }

private static int primeSum(int n, int m) {
        int sum=0;

        for(int i=n;i<=m;i++){
            if(isPrime[i]){
                sum=sum+i;
            }
        }
        return sum;
    }

    private static boolean[] isPrime(){
        int maxFactor= (int)Math.sqrt(MAX);
        boolean[] isPrime=new boolean[MAX + 1];
        int len=isPrime.length;
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=0;i<=maxFactor;i++){
            if(isPrime[i]){
                for(int j=i+i;j<len;j+=i){
                    isPrime[j]=false;
                }
            }
        }
        return isPrime;

    }

}

Input:

2
1 99999
10000 99999

Output:

454396537
448660141

Now I'm trying to further optimize sieve by just taking odd number what usually in practice. Here is the optimized sieve function  that I have written:

private static boolean[] isPrime(){
        int root=(int) Math.sqrt(MAX)+1;
        int limit=(MAX-1)/2;
        boolean[] isPrime=new boolean[limit];
        Arrays.fill(isPrime, true);
        root = root/2 -1;
        for(int i = 0; i < root ; i++){
            if(isPrime[i]){
                for( int j = 2*i*(i+3)+3 , p = 2*i+3; j < limit ; j=j+p ){
                    isPrime[j]=false;
                }
            }
        }

    return isPrime;
}

Which I was able to do. I tested the above function till MAX=100. Here is the Ideone link.

Test results:

    truetruetruefalsetruetruefalsetruetruefalsetruefalsefalsetruetruefalsefalsetrue
falsetruetruefalsetruefalsefalsetruefalsefalsetruetruefalsefalsetruefalse
truetruefalsefalsetruefalsetruefalsefalsetruefalsefalsefalsetruefalse

i.e 3 5 7 9̶ 11 13 1̶5̶ 17 19 ̶2̶1̶  23 2̶5̶ ̶2̶7̶  29 31 ̶3̶3̶ ̶3̶5̶ ̶  37 3̶9̶ ̶  so on..

Now what really bugging me is the indexing I did in primeSum() method for this optimized sieve:

private static int primeSum(int n, int m) {
        int sum;
        if(n>0 && n<=2){
            sum=2;
        }else
            sum=0;
        //System.out.println(sum);
        for( int i = (n-3)/2; i <= (m-3)/2 ; i++){
            if(isPrime[i]){
                //System.out.println(i);
                sum=sum+2*i+3;
            }
        }
        return sum;
    }

But obviously, this indexing of n is failing for n<3, so I have to do this to get this code working:

if(n>0 && n<=2){
            sum=2;
            n=n+2;
        }

But then it still fails for the cases when I've to find it between ranges:

1 2
1 1
2 2

So should I again include these cases and deal with it separately like this?

private static int primeSumInRange(int n, int m) {
        int sum;
        if(m ==1) return 0;
        if(n<=2){
            sum=2;
            n=n+2;
        }else
            sum=0;
            if(m>2){
        for( int i = (n-3)/2; i <= (m-3)/2 ; i++){
            if(isPrime[i]){
                sum=sum+2*i+3;
            }
        } }
        return sum;
    }

Is my way of doing the indexing i in primeSum() method proper? Or can I improve it? What are the other possible way of indexing here?


texts: Gravity simulation using Numpy and Pygame

texts:
This is a simple gravity simulator coded in Python 3.7 using Numpy and Pygame. I was wondering if it can be optimized further. Initially I had coded it using pure Python lists, using nested loops to calculate forces between each body, but then the good people of Reddit suggested me to use Numpy, Cython or Numba to improve the runtime of the code. Some even suggested a few highly optimized algorithms which are used to improve the time complexity of N-Body simulations like the Barnes Hut algorithm. For v2, I decided to use Numpy and have kept Barnes-Hut for the scope of future. Here is the implementation in numpy :

Can it be optimized further?

import sys
import time

import numpy as np
import pygame

G = 6.67408e-11 * 100_000_000  # Otherwise the bodies would not move given the small value of gravitational constant
NUM_OF_BODIES = 4000
WIDTH = 1200
HEIGHT = 800
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (109, 196, 255)

vx = np.zeros((NUM_OF_BODIES,),dtype=np.float)
vy = np.zeros((NUM_OF_BODIES,),dtype=np.float)

px = np.random.uniform(low=10, high=WIDTH-10,size=NUM_OF_BODIES)
py = np.random.uniform(low=10, high=HEIGHT-10,size=NUM_OF_BODIES)

m = np.random.randint(1,25,size=NUM_OF_BODIES)

fx = np.zeros((NUM_OF_BODIES,),dtype=float)
fy = np.zeros((NUM_OF_BODIES,),dtype=float)

pygame.init()
size = WIDTH, HEIGHT
screen = pygame.display.set_mode(size)

font = pygame.font.SysFont('Arial', 16)
text = font.render('0', True, BLUE)
textRect = text.get_rect()
while True:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    in_t = time.time()
    for i in range(0,NUM_OF_BODIES):
        xdiff = (px - px[i])
        ydiff = (py - py[i])

        distance = np.sqrt(xdiff ** 2 + ydiff ** 2)

        f = G * m[i] * np.divide(m,distance ** 2)

        sin = np.divide(ydiff,distance)
        cos = np.divide(xdiff,distance)

        fx_total = np.nansum(np.multiply(f, cos))
        fy_total = np.nansum(np.multiply(f,sin))

        vx[i] = vx[i] + fx_total / m[i]
        vy[i] = vy[i] + fy_total / m[i]

        px[i] = px[i] + vx[i]
        py[i] = py[i] + vy[i]

        pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(px[i], py[i], m[i],m[i]))
    print(time.time() - in_t)
    pygame.display.flip()


texts:
I am implementing a like button for posts (Using a clustom Like model and the pre-defined User model from django.contrib.auth).

Would appreciate hearing how I can improve this code. Also, I am struggeling with loading in the last state of every like button with the correct highlighting (liked or not liked) if the user reloads the page.

Thanks in advance

post.html:

        {{ post.text }}

          ~

          {{ post.author }}

views.py:

def already_liked_post(user, post_id):

    post= Post.objects.get(id=post_id)
    return Like.objects.filter(user=user, post=post).exists()

def like_button_clicked(request, post_id):

    if request.user.is_authenticated():
        post = Post.objects.get(id=post_id)

        if not already_liked_post(request.user, post_id):
            Like.objects.create(user=request.user, post=post, timestamp=datetime.now())
        else:
            Like.objects.filter(user=request.user, post=post).delete()

        return redirect(reverse('index'))
    else:
        return redirect(reverse('login'))

index.html:

{% for post in posts %}
   {% include 'includes/post.html' %}
{% endfor %}

Javascript:

$(function(){

    $('.like-btn').on('click', function(){
      likePost(this);
    });

    function likePost(thumb){

      {% if user.is_authenticated %}
        // Visual like button highlighting
        $(thumb).toggleClass('btn-like-post')

        // route: /like/(id)
        // Take the index of the current like-button and add
        // 1 to it (so it starts at 1) to match the primary-key
        // of the database

        id = $('.like-btn').index(thumb)+1
        var url = '/like/' + id.toString()
        $.ajax({
          url: url,
          data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
          method: 'POST',
          success: function(){
          }
        })
      {% else %}
        window.location='/login'
      {% endif %}
    }

  });

models.py:

class Post(models.Model):
    id = models.AutoField(primary_key=True)
    text = models.TextField()
    author = models.CharField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return f'{self.text} ~ {self.author}'

class Like(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    timestamp = models.DateTimeField()

    def __str__(self):
        return f'{self.user.username} likes \'{self.post.text}\''


texts:
For a project I am working on, I need to use a lot of primes, frequently. To do this, I added a cache to Will Ness's prime sieve, that stores already generated primes so getting them is quick. How can I improve this code?

def prime_sieve(): # postponed sieve, by Will Ness
    for c in (2,3,5,7):                     # original code David Eppstein,
        yield c
    sieve = {}                              # Alex Martelli, ActiveState Recipe 2002
    ps = prime_sieve()                      # a separate base Primes Supply:
    p = next(ps) and next(ps)               # (3) a Prime to add to dict
    q = p*p                                 # (9) its sQuare
    for c in count(9,2):                    # the Candidate
        if c in sieve:                      # c’s a multiple of some base prime
            s = sieve.pop(c)                # i.e. a composite ; or
        elif c < q:
            yield c                     # a prime
            continue
        else:   # (c==q):            # or the next base prime’s square:
            s=count(q+2*p,2*p)       #    (9+6, by 6 : 15,21,27,33,...)
            p=next(ps)               #    (5)
            q=p*p                    #    (25)
        for m in s:                  # the next multiple
            if m not in sieve:       # no duplicates
                break
        sieve[m] = s                 # original test entry: ideone.com/WFv4f

class cached_primes:
    def __init__(self):
        self.prime_gen = prime_sieve()
        self.vals = [2]
        next(self.prime_gen)

    def get(self, start=2, end=float('inf')):
        vals = self.vals

        lo = self.get_ind(start)
        if vals[-1] >= end:
            hi = self.get_ind(end)
            yield from islice(vals, lo, hi)
            return
        else:
            while vals[-1] < end:
                if len(vals) > lo:
                    bound = len(vals)
                    yield from takewhile(lambda p: p <=end, islice(vals, lo, bound))
                    lo = bound
                vals.append(next(self.prime_gen))
        hi = self.get_ind(end)
        yield from islice(vals, lo, hi)

    def get_ind(self, x):
        if x <= 2:
            return 0
        vals = self.vals
        B = x/log(x)
        if x < 17:
            return bisect(vals, x, 0, min(len(vals), int(B)))
        return bisect(vals, x, int(B), min(len(vals), int(1.25506*B)))


texts: Factory for constructing directed graphs in C++

texts:
I want to implement a directed graph which has 3 main kind of edges:

self referencing edges
non directional edges between two nodes
directional edges between two nodes

Also I want to be able to do global operations on the graph, like e.g. counting or removing all edges fulfilling certain criteria.

The easiest program structure I came up with is:

#include <unordered_set>

using namespace std;

struct Edge;

struct Node
{
    Node(std::string name):name(name){}
    string name;
    std::unordered_set<Edge*> edges;
};

struct Edge
{
    Edge(Node * node1): node1(node1){}
    double weight;
    Node * node1;
};

struct EdgeBetweenTwoNodes: public Edge
{
    EdgeBetweenTwoNodes(Node * node1, Node * node2 ): Edge(node1), node2(node2){}
    Node * node2;
};

struct DirectionalEdge: public EdgeBetweenTwoNodes
{
    DirectionalEdge(Node * node1, Node * node2, bool direction ): EdgeBetweenTwoNodes(node1,node2), direction(direction){}
    bool direction;
};

struct EdgesContainer
{
    std::unordered_set<Edge*> all_edges;

    void register_new_edge(Edge * edge)
    {
        all_edges.insert(edge);
    }

    //do all kind of manipulations on all edges of a cetain type...
};

struct EdgeFactory
{
    EdgeFactory(){}

    void create_edge(Node* node1,EdgesContainer & edge_container)
    {
        Edge * edge = new Edge(node1);
        node1->edges.insert(edge);

        edge_container.register_new_edge(edge);
    }

    void create_edge(Node* node1, Node* node2, EdgesContainer & edge_container)
    {
        EdgeBetweenTwoNodes * edge = new EdgeBetweenTwoNodes(node1,node2);
        node1->edges.insert(edge);
        node2->edges.insert(edge);

        edge_container.register_new_edge(edge);
    }

    void create_edge(Node* node1, Node* node2, bool direction, EdgesContainer & edge_container)
    {
        DirectionalEdge * edge = new DirectionalEdge(node1,node2,direction);
        node1->edges.insert(edge);
        node2->edges.insert(edge);

        edge_container.register_new_edge(edge);
    }
};

int main()
{
    Node * A = new Node("A");
    Node * B= new Node("B");
    Node * C= new Node("C");

    EdgesContainer edges;

    EdgeFactory edge_factory;
    edge_factory.create_edge(A,edges);
    edge_factory.create_edge(A,B,edges);
    edge_factory.create_edge(A,C,1,edges);

    return 0;
}

What do you think about it? Is this the correct use of a so called "Factory?"


texts: Converting hex to binary in the form of string

texts:
This code returns a string of binary in 4-digit forms for a given hex in the form of string
def str_bin_in_4digits(aString):
    retStr = ''
    for i in aString:
        retStr = retStr+"{0:04b}".format(int(i, 16))+" "
    return retStr.strip()

for example,
>>> str_bin_in_4digits("20AC")
0010 0000 1010 1100

The code works as expected and my concern is could it be more elegant, like faster or less memory consumption?


texts: Class member method based multithreading [C++]

texts:
In briefly: I'm working on a little chat program just for fun.

I am using threads to control two main parts of the application. I am making a socket controller class based on the following design:

//this is a "main.cpp example" for the design

std::mutex mtx;

class AThreadedClass
{
public:
    AThreadedClass()
    {
        running = true;
        value1 = 0;
        value2 = 0;
        value3 = 0;
    }

    //first method which is used for threads
    void run()
    {
        {
            std::lock_guard<std::mutex> lck(mtx);
            value1 = 0; value2 = 0; value3 = 0;
        }

        while (running)
        {
            {
                std::lock_guard<std::mutex> lck(mtx);
                value1 += 2; value2 +=1; value3 -= 1;
                if (value1 > 1000000)
                {
                    running = false;
                }
            }
        }
    }

    //second method used as thread
    //this will possible be just a data
    //retrieving function, not necessarly
    //used as thread
    void writeOut()
    {
        while(running)
        {
            std::lock_guard<std::mutex> lck(mtx);
            std::cout << value1 << ';' << value2 << ';' << value3 << '\n';
        }
    }
private:
    int value1, value2, value3;
    std::atomic<bool> running;
};

int main()
{
    AThreadedClass class1;
    std::thread t1(&AThreadedClass::run, &class1);
    std::thread t2(&AThreadedClass::writeOut, &class1);

    t1.join();
    t2.join();

    std::cout << "Threads finished successfully!\n";

    return 0;
}

So, here are the things I was wondering about:

Is this a good way to manage things? (I mean, using classes and their member functions for threads could be a stupid idea :/)
Are there possible deadlocks, when I am mixing std::atomic with std::mutex like in the example? (So far it worked perfectly for me)

And if I didn't notice an existing question about this, please point to it.


texts: Clean up function in Javascript Event Listener

texts:
I am trying to refactor a chess game I am currently creating so the code is more flexible and maintainable, while doing this, I came across an event listener which I have no idea on how to make "cleaner". Some of the variable names in the event listener are unintuitive but apart from that, I would like to know how to structure the event listener such that it uses multiple methods. I have previously asked a question on Code Review which is also about refactoring, and contains the code from which this function came from, here is the link: Object-Oriented JavaScript chess game. If you have any questions or clarifications needed about the code, feel free to ask.

  document.addEventListener('click', function(event){
        if(!hasClicked){
          if(event.clientX < 480 && event.clientY < 480 && board[Math.floor(event.clientY / 60)][Math.floor(event.clientX / 60)] != "vacant"){
            if(humanPlayer.indexOf(board[Math.floor(event.clientY / 60)][Math.floor(event.clientX / 60)]) != -1){
              canMove = true;
              isHighlightPossibleMoves = true;
              hasClicked = true;
              highlightPos = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
              pieceMoves = processMoves({x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)}, board);
            } else {
              hasClicked = true;
              highlightPos = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
              canMove = false;
            }
          }
        } else {
          if(canMove){
            advancePosition = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
            for(i = 0; i < pieceMoves.moves.length; i++){
              if(advancePosition.x == pieceMoves.moves[i].x && advancePosition.y == pieceMoves.moves[i].y){
                if(board[highlightPos.y][highlightPos.x] == blackKing || board[highlightPos.y][highlightPos.x] == whiteKing){
                  if(pieceMoves.moves[i].x - 2 == highlightPos.x || pieceMoves.moves[i].x + 2 == highlightPos.x){
                    isCastling = true;
                  } else {
                    isCastling = false;
                  }
                }
                if(isCastling){
                  board = chess.returnCastledBoard({x: highlightPos.x, y: highlightPos.y}, pieceMoves.moves[i]);
                  chess = new Chess(board);
                  isCastling = false;
                } else {
                  if(
                    board[highlightPos.y][highlightPos.x] == whiteKingSideCastle ||
                    board[highlightPos.y][highlightPos.x] == whiteQueenSideCastle ||
                    board[highlightPos.y][highlightPos.x] == blackKingSideCastle ||
                    board[highlightPos.y][highlightPos.x] == blackQueenSideCastle ||
                    board[highlightPos.y][highlightPos.x] == blackKing ||
                    board[highlightPos.y][highlightPos.x] == whiteKing
                  ){
                    board[highlightPos.y][highlightPos.x].hasClicked = true;
                  }
                  board = chess.updateBoard(highlightPos, advancePosition);
                  chess = new Chess(board);
                  break;
                }
              }
            }
          }
          hasClicked = false;
          canMove = false;
          highlightPos = undefined;
          pieceMoves = undefined;
          advancePosition = undefined;
        }
      });

````


texts:
Task:

  Write a program that presents the user w/ a choice of your 5 favorite
  beverages (Coke, Water, Sprite, ... , Whatever). Then allow the user
  to choose a beverage by entering a number 1-5. Output which beverage
  they chose.

  ★ If you program uses if statements instead of a switch statement,
  modify it to use a switch statement. If instead your program uses a
  switch statement, modify it to use if/else-if statements.

  ★★ Modify the program so that if the user enters a choice other than
  1-5 then it will output "Error. choice was not valid, here is your
  money back."

#include <iostream>
using namespace std;

int main() {

int drink = 0;
string ifswitch;
string again = "y";

while( again == "y" || again == "Y")
{
    cout << "Would you like to use if or switch statements?: ";
    cin >> ifswitch;
    cout << endl;

    if(ifswitch == "switch" || ifswitch == "Switch")
    {
        cout << "Now using switch statements..." << endl << endl;

        cout << "Your choices of drinks are: " << endl;
        cout << "1 - Coke" << endl;
        cout << "2 - Sprite" << endl;
        cout << "3 - Water" << endl;
        cout << "4 - Orange Juice" << endl;
        cout << "5 - Apple Juice" << endl;

        cout << "What drink would you like (1/5): ";
        cin >> drink;
        cout << endl;

        switch(drink)
        {
            case 1 :
                cout << "You chose Coke." << endl;
                break;
            case 2 :
                cout << "You chose Sprite." << endl;
                break;
            case 3 :
                cout << "You chose Water." << endl;
                break;
            case 4 :
                cout << "You chose Orange Juice." << endl;
                break;
            case 5 :
                cout << "You chose Apple Juice." << endl;
                break;
            default :
                cout << "Error. Choice was not valid, Here is your money back.";

        }
    }
    else if(ifswitch == "if" || ifswitch == "If")
    {
        cout << "Now using if statements..." << endl << endl;

        cout << "Your choices of drinks are: " << endl;
        cout << "1 - Coke" << endl;
        cout << "2 - Sprite" << endl;
        cout << "3 - Water" << endl;
        cout << "4 - Orange Juice" << endl;
        cout << "5 - Apple Juice" << endl;

        cout << "What drink would you like (1/5): ";
        cin >> drink;
        cout << endl;

        if(drink == 1)
            cout << "You chose Coke." << endl;
        else if(drink == 2)
            cout << "You chose Sprite." << endl;
        else if(drink == 3)
            cout << "You chose Water." << endl;
        else if(drink == 4)
            cout << "You chose Orange Juice." << endl;
        else if(drink == 5)
            cout << "You chose Apple juice." << endl;
        else
        cout << "Error. Choice was not valid, Here is your money back.";

    }

    cout << "Would you like to go again? (Y/N)" << endl;
    cin >> again;
    cout << endl;

}

    cout << "Ending...";

}


texts:
I made a tree structure (Tree) that represents an algebraic expression that contains two binary opperators the "question mark" Q/"?" and the "exclamation mark" E/"!".
Both are associative (that means a!(b!c)=(a!b)!c, and the same for the questionmark; this means the order of evaluation doesn't matter and we can omit the parenthesis if we have a chain of the same operator), we do however have no precedence rules, that means we have to use parenthesis if we have a mix of operators: a?b!c would be invalid, it must be (a?b)!c or a?(b!c).
So now I wanted to make it a Show instance that prints out this expression in one line according to the rules outlined above. For that I wrote some helper functions surroundX that add parenthesis where needed.
So my question is: Is there a way to reduce the duplicated code, especially in the surroundX functions?
I thought that it would be nice to be able to pass E or Q as an additional parameter, but I didn't find a way to make that work. But maybe there are other ways to simplify this.

data Tree = Unit | E Tree Tree | Q Tree Tree

surroundE a@(E _ _) = "(" ++ show a ++ ")"
surroundE x = show x
surroundQ a@(Q _ _) = "(" ++ show a ++ ")"
surroundQ x = show x

instance Show Tree where
 show Unit = "1"
 show (E a b) = surroundQ a ++ "!" ++ surroundQ b
 show (Q a b) = surroundE a ++ "?" ++ surroundE b

--example output
main = do
 print $ E (E Unit Unit) (E Unit (Q Unit Unit))
 print $ Q (E Unit Unit) (Q Unit (Q Unit Unit))

Try it online!


texts:
I created a very simple interpreter in Python. It's capable of doing basic math (unfortunately with only two numbers), creating quines and printing text.

import re

def prompt():
    userInput = input("> ")
    return userInput

def parse(command):
    if command.startswith("+"):
        numbers = re.findall(r'\d+', command)
        nums = ''.join(numbers)
        nums.replace(" ", "")
        firstNumber = int(nums[0])
        secondNumber = int(nums[1])
        print(firstNumber + secondNumber)

    elif command.startswith("-"):
        numbers = re.findall(r'\d+', command)
        nums = ''.join(numbers)
        nums.replace(" ", "")
        firstNumber = int(nums[0])
        secondNumber = int(nums[1])
        print(firstNumber - secondNumber)

    elif command.startswith("*"):
        numbers = re.findall(r'\d+', command)
        nums = ''.join(numbers)
        nums.replace(" ", "")
        firstNumber = int(nums[0])
        secondNumber = int(nums[1])
        print(firstNumber * secondNumber)

    elif command.startswith("/"):
        numbers = re.findall(r'\d+', command)
        nums = ''.join(numbers)
        nums.replace(" ", "")
        firstNumber = int(nums[0])
        secondNumber = int(nums[1])
        print(firstNumber / secondNumber)

    elif command.startswith("q"):
        print(command)

    elif command.startswith("p"):
        print(command.strip("p "))

while True:
    userInput = prompt()
    parse(userInput)

Some examples:

Input: +65

Output: 11

Input: q This is a quine

Output: q This is a quine

It's working good for me, but there's a few things I'd like to add, like multiple statements on one line and math with 2+ numbers.

Is there anything I could do to improve this?

Please remember I'm not a professional programmer and that this is one of the first interpreters I've ever written.


texts: Hotel reservation system with discounts and deposits

texts:
I'm making a hotel reservation app that has the following features:

Promo Codes:

The guest can choose to pay half a certain percent of the total_amount or the entire total_amount. I want to use stripe, PayPal and authorize.net as payment gateways.

Reservations are stored here:

CREATE TABLE `reservations` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `guest_id` int(11) NOT NULL,
 `currency` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'USD',
 `accommodation_id` int(11) NOT NULL,
 `from_date` date NOT NULL,
 `to_date` date NOT NULL,
 `guests` int(11) NOT NULL,
 `total_amount` decimal(13,4) NOT NULL,
 `deposit_amount` decimal(13,4) NOT NULL,
 `remaining_amount` decimal(13,4) NOT NULL,
 `isDeposit` enum('true','false') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'false',
 `promo_id` int(11) NOT NULL,
 `paid` tinyint(1) NOT NULL DEFAULT '0',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

An example reservation:

id|user_id  | guest_id  | currency  | accommodation_id  | from_date  | to_date        | guests  | total_amount  | deposit_amount | remaining_amount
2 | 4       | 10        | USD       | 55                | 2015-07-02 | 2015-07-04     | 20      | 200           | 20             | 180

| isDeposit | promo_id | paid
| true      | 2        | 0

Payments are stored here:

CREATE TABLE `payments` (
 `id` int(11) NOT NULL,
 `reservation_id` int(11) NOT NULL,
 `method` enum('stripe','paypal','authorize') NOT NULL,
 `type` enum('deposit','total','remaining') NOT NULL,
 `reference` varchar(255) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1

If the guest pays that deposit_amount of 20 using stripe:

id | reservation_id | method | type     |  reference        |
1  | 2              | stripe | deposit  | 56544564545       |

and pays the remaining of 180 using PayPal:

id | reservation_id | method | type           | reference    |
1  | 2              | paypal | remaining      | 68985578474  |

then I will make column paid to 1 in reservations table.

How does this look to you?


texts: Python - Flask Middleware - Request Session Management Strategy

texts:
I am trying to determine what the most appropriate strategy for session management and authentication is for a middleware application which acts to receive a request, send it over to a database, and essentially echo those results back to the client.

I have a variety of functions that look like this

@app.route('/rest/results_mod', methods=['POST'])
@crossdomain(origin='*')
def rest_results_mod():
    if request.method == 'POST':
        with requests.session() as request_session:
                request_session.trust_env = False
                request_session.auth = HTTPDigestAuth("admin", "admin")
                posted_form = request.form
                text_search = posted_form['searchTerm']

                params = urllib.parse.urlencode({"rs:searchTerm": "{0}".format(text_search)})

                response = request_session.get(SHOW_SEARCH_MOD+'?{0}'.format(params))
                #print(response.content)

        return json.dumps(json.loads(response.content)), 200, {'Content-Type': 'application/json'}

For each request, I am currently creating a session, and issuing the request as context managed to make sure it closes. I have about 5 or so of these functions each with its own session invocation.

My question is:

Is there any reason this is a bad strategy? Should I initiate a session only when the application gets initalized, and then have each request use the open session? I've tried both ways, they both seem to work in limited testing, but my question is essentially are there any pro's and con's to one way or the other? Or is one way "preferred" or standard for this type of task?

Thank you for reading, I look forward to your advice


texts:
I just started learning C and the online book contained the exercise 'implement a stack'. So I did, but thought I'd put it here, because I still don't feel comfortable with pointers.

So here it is:

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

struct StackItem {
    struct StackItem *previous;
    int value;
};

void stack_push(struct StackItem **current, int value) {
    struct StackItem *tmp = malloc(sizeof(struct StackItem));
    tmp->previous = *current;
    tmp->value = value;
    *current = tmp;
}

void stack_pop(struct StackItem **current) {
    if ((*current)->previous != NULL) {
        struct StackItem *tmp = (*current)->previous;
        free(*current);
        *current = tmp;
    } else printf("%s\n", "Previous is NULL");
}

void stack_print(struct StackItem *current) {
    printf("%d\n", current->value);
    while (current->previous != NULL) {
        current = current->previous;
        printf("%d\n", current->value);
    }
}

int main(int argc, char **argv) {
    struct StackItem *current = malloc(sizeof(struct StackItem));
    current->value = 2147483647;
    current->previous = NULL;
    char input[10];
    int i = 0;
    while (i < 10) {
        puts("Enter integer value to add to the stack:");
        gets(input);
        char *end;
        int newVal = (int)strtol(input, &end, 10);
        if (*end != '\0') { puts("That was no integer value."); --i; }
        else stack_push(&current, newVal);
        ++i;
    }

    stack_print(current);
    puts("Stack printed once.");

    i = 0;
    while (i < 10) {
        stack_pop(&current);
        i++;
    }

    stack_print(current);
    puts("Stack printed twice.");

    return 0;
}

Is there anything wrong/not good (I mean two different things here) with this?


texts:
I have a function that adds a class name to a DOM element is met. The script provided works.
function rm_row(){

  var chk_inherent =  arcapi.dataResult().columnNameToIndex('Inherent Risk');
  var chk_residual = arcapi.dataResult().columnNameToIndex('Residual Risk')
  var chk_perf = arcapi.dataResult().columnNameToIndex(arcapi.getSetting('Column name'));

  d3.selectAll("#" + arcapi.chartId() + " .dataTables_scrollBody tbody tr").classed('removerow', function() {

    const perf = this.children[chk_perf].innerHTML
    const inherent = this.children[chk_inherent].innerHTML
    const residue = this.children[chk_residual].innerHTML
    const cf_regex = perf.replace(/[`~%]/gi, '');

    //  **** Check *****
    const inh_isEmpty = inherent === '' || inherent === 'Null'
    const rsk_isEmpty = residue === '' || residue === 'Null'
    const perf_isInvalid = cf_regex < 0 || cf_regex > 100

    /** Logic [if inherent is empty AND  Residual risk is empty AND is perf value is incorrect = True] **/
    return inh_isEmpty && rsk_isEmpty && perf_isInvalid === true
  });
}

However, I feel it's long-winded. I feel this can be further optimized. What is the best approach/best practices to further improve myself and optimize my script so that it will be easy to maintain?
I have thought of creating an array and store all my variables in an array, but I feel this approach will be expensive.


texts: Creating an async consumable object in Node

texts:
Background

I have a situation where I have fixed number of objects with their own routines that would need to be called with the same initial message.

To accomplish this, I have a Factory that binds objects to a Composite object whose main method is to call methods on its subordinates without having to know how many it has.

This routine is to be called upon receiving a message from a queue, the client to that queue is responsible for initiating that procedure.

Code/ Question

Just to keep the code looking succinct, here are the individual modules for completeness.

//-------------------------------------------------------------------
// module1/index.js
//-------------------------------------------------------------------

function A () {}

A.prototype.method = function(msg, cb) {
  console.log('A class: %j', msg );
  cb(null, 'done message');
};

//-------------------------------------------------------------------
// module2/index.js
//-------------------------------------------------------------------

function B () {}

B.prototype.method = function(msg, cb) {
  console.log('B scraper: %j', msg);
  cb(null, 'done message');
};

Here is the factory that has the job of knowing what it imports and attaching the objects defined above to the Factory's caller:

//-------------------------------------------------------------------
// - factory.js
//-------------------------------------------------------------------

var A = require('./module1');
var B = require('./module2');

function Factory () {
  var o = Object.create(null);
  o.obj1 = new A();
  o.object2 = new B();
  return o;
}

Now here's the part that is in question. The method method does some 'clever' stuff to make something that the async library can understand and use. This code runs, and it about as efficient as it needs to be but I would like to ask if there is another, more readable way to build an object for use in async.parallel().

//-------------------------------------------------------------------
// - composite.js
//-------------------------------------------------------------------
var async = require('async');

function Composite () {
  this.objects = new Factory();

}

Composite.prototype.method = function(msg) {
  var self = this;
  var enum = Object.keys(this.objects);
  var newObj = {};
  // for each member-name in the obj.
  enum.forEach(function (name) {
    // put a function in the newObj
    newObj[name] = function (callback) {
      // who calls the object's method with some initial values
      // and a callback
      self.objects[name].method(msg, function(err, results){

        if (err) { callback(err); }
        callback(null, results);

      });

    };
  });
  // actually do something
  async.parallel(
    newObj,
    function(err, results) {
      console.log(results);
  });
};

module.exports = Composite;

This is just here for extra context.

//-------------------------------------------------------------------
// RMQ Client
//-------------------------------------------------------------------
var Composite = require('./composite');
var Client = {};

Client.on('message', startJob, msg)

function startJob (msg) {
  var comp = new Composite();
  comp.method(msg);

}


texts: First go at my own form validation, and suggestions?

texts:
Well I just finished my first go at my own form validation (I always used validate plugin) for simple front end.  It's definitely small potatoes as it's only meant for a form with 4 fields; 3 required text and one required e-mail.

I'm new to Jquery so I am doing little exercises like these to help me learn and I was hoping someone could take a look and see if what I did was ok.  Did I make any newbie mistakes? Can I improve this? Perhaps I should use js objects (new to those too) to organize code? I know there is no one answer, in fact I'm sure there are countless ways to validate a form...But I was just hoping some JS expert could offer a little insight on better coding practices.

*EDIT - forgot to mention...I'm aware that I should probably use regex for better email validation, however, just threw the indexOf() method for the time being *

$(function() {

        var err = "Required field.";
        var errEmail = "Please enter valid email.";
        var errors = false;

        $('.submit').click(function() {
            $('.error').remove();

            $('.req').each(function() {
                if($(this).val() == '') {
                    $(this).after(err);
                    errors = true;
                }
            });

            if ($('.reqe').val().indexOf('@') === -1) {
                $('.reqe').after(errEmail);
                errors = true;
            }

            if (errors == true) {
                return false;
            }
            else {
                var errors = false;
                alert("Submitted");
                return true;
            }

        });
});

Any feedback would be greatly appreciated.  Thanks


texts:
I'm using C# in .NET 4. The class holds an array of double that represents a 2-D rectangular matrix but (due to business requirements) must be stored flattened (i.e. a double[]). The class also stores the dimensions of the array. I wish to sort the array by the (virtual) first column. Obviously I have to unflatten it, at least partially, in order to do this, right? I don't see anything in LINQ or System.Array that works on a flattened array.

If there's 1 column, System.Array.Sort() works fine and I don't think it can be improved.

If there's 2 columns, it's not hard to split it into two arrays and again use System.Array.Sort(). If you quickly see a way to improve it great, but if not, I'm happy with it as it stands.

I'm not happy with the code for 3 or more columns (it stinks) and suspect there's some way to improve it.

N.B. In real life the class has get-only properties. It's guaranteed that rows and cols are positive, array != null, and rows*cols==array.Length.

public partial class FlattenedArray
{
    public int rows;
    public int cols;
    public double[] array;
    public void sort()
    {
        double[] keys;
        switch(cols)
        {
            case 1:
                System.Array.Sort<double>(array);
                break;
            case 2:
                keys = new double[rows];
                double[] dItems = new double[rows];
                for (int i=0,k=0; i<rows; i++)
                {
                    keys[i] = array[k++];
                    dItems[i] = array[k++];
                }
                System.Array.Sort<double,double>(keys,dItems);
                for (int i=0,k=0; i<rows; i++)
                {
                    array[k++] = keys[i];
                    array[k++] = dItems[i];
                }
                break;
            default:
                keys = new double[rows];
                int[] items = new int[rows];
                double[] temp = new double[rows*cols];
                for (int i=0,k=0; i<rows; i++, k+=cols)
                {
                    keys[i] = array[k];
                    items[i] = k;
                }
                System.Array.Sort<double,int>(keys,items);
                for (int i=0,k=0; i<rows; i++)
                {
                    int spt = items[i];
                    for (int j = 0; j < cols; j++)
                    {
                        temp[k++] = array[spt++];
                    }
                }
                array = temp;
                break;
            }


texts:
I was asked this question in an interview:

Find all the factors of a given natural number, N
1 <= N <= 10**10
Example:
N = 6 => 1, 2, 3, 6
N = 60 => 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60

I wrote following code,but got an feedback that complexity could be improved.

How to optimise following code?

import math
def get_all_factors(n):
    ans = [1]
    if n==1:
        return ans
    factors = [False] * n
    for i in xrange(2,int(math.sqrt(n))):
        if not factors[i]:
            if n%i == 0:
                factors[i] = True
                factors[n/i] = True

    for i, is_factor in enumerate(factors[1:], 1):
        if is_factor:
            ans.append(i)
    ans.append(n)
    return ans

ans = get_all_factors(60)
print [x for x in ans]


texts: Finding mongodb records in batches using mongoid

texts:
I want to get records in batches. But mongoid doc says to avoid using skip due as it can be expensive. I wrote this method to iterate through a large number records efficiently.

module Mongoid
  module Batches
    def find_each(batch_size = 1000)
      return to_enum(:find_each, batch_size) unless block_given?
      find_in_batches(batch_size) do |documents|
       documents.each { |document| yield document }
     end
   end
   def find_in_batches(batch_size = 1000)
     return to_enum(:find_in_batches, batch_size) unless block_given?
     documents = self.asc(:created_at).limit(batch_size).asc(:id).to_a
     while documents.any?
       documents_size = documents.size
       primary_key_offset = documents.last.id

       yield documents
       break if documents_size < batch_size
       documents = self.where(:id.gt => primary_key_offset).asc(:created_at).limit(batch_size).asc(:id).to_a
     end
   end
 end
end
Mongoid::Criteria.include Mongoid::Batches


texts: Future in f# is this an unavoidable use of a mutable variable?

texts:
I have this type:

type Future<'a> () =
    let mutable _value: 'a option = None

    member x.Resolve value =
        if _value.IsSome then failwith "can only resolve once"
        _value <- Some value

    member x.IsResolved with get () = _value.IsSome

    member x.Value
        with get () =
            match _value with
            | Some v -> v
            | None -> failwith "hasn't resolved yet"

And I need something like this because I have something along the lines of:

let testHttpGet response =
    let urlFuture = Future<string>()

    let get url =
        urlFuture.Resolve url
        response

    (get, urlFuture)

Call that function and set the return value of the returned function

let get, urlFuture = testHttpGet "resp"

Call the returned func, thus resolving the Future

let response = get "http://test"

In the end we have the result of the function

response |> should equal "resp"

And we have the value with which the func was called

urlFuture.IsResolved |> should be True
urlFuture.Value |> should equal "http://test"

To me this looks like a sound approach but I also have a feeling that something like it must exist in f# allready

Here's where I use them.

Here is a fiddle.


texts:
This is my solution to exercise 1.6 in Cracking the Coding Interview.  I am interested in receiving feedback on the coding style and time/space complexity.

The exercise statement is:

  Implement a method to perform basic string compression using the counts of repeated characters.  For example, the string aabcccccaaa would become a2b1c5a3.  If the compressed string would not become smaller than the original string your method should return the original string.  You can assume the string has only uppercase and lowercase letters (a-z).

import unittest
from collections import defaultdict
from math import log10, floor

def compress_string(data: str) -> str:
    """A function to perform basic string compression using the counts of repeated characters
     If the compressed string is not smaller than the original string the function returns
     the original string.  The assumption is that the string has only uppercase and lowercase letters (a-z)."""
     curr_char_pos = 0
     frequencies = defaultdict(int)
     compressed_string = []
     compressed_string_size = 0

     for idx in range(len(data)):
        if compressed_string_size >= len(data):
            break
        if data[idx] == data[curr_char_pos]:
            frequencies[curr_char_pos] += 1
        else:
            compressed_string.append(data[curr_char_pos])
            compressed_string.append(frequencies[curr_char_pos])
            compressed_string_size += floor(log10(frequencies[curr_char_pos])) + 2
            curr_char_pos = idx
            frequencies[curr_char_pos] = 1

        compressed_string.append(data[curr_char_pos])
        compressed_string.append(frequencies[curr_char_pos])
        compressed_string_size += floor(log10(frequencies[curr_char_pos])) + 2

        if compressed_string_size < len(data):
            compressed_data = ''.join(str(char) for char in compressed_string)
            return compressed_data
       else:
            return data

class MyTest(unittest.TestCase):
    def test_compress_string(self):
        self.assertEqual(compress_string('aabcccccaaa'), 'a2b1c5a3')
        self.assertEqual(compress_string('abcd'), 'abcd')
        self.assertEqual(compress_string('tTTttaAbBBBccDd'), 'tTTttaAbBBBccDd')


texts: Script for concatenating delimited text files

texts:
I need to concatenate a bunch of delimited text files. In the process, I need to add a new column to the data based on part of the name of one of the directories containing each file. The script works, but I have a feeling that it is inelegant in the extreme.

In particular, I'm wondering whether I should be reading the source files into a data structure that can later be written to file as a delimited text file. It seems like such an approach would be more general and easily extended.

In its current structure, I have doubts about the efficiency of how I'm skipping the header lines in source files with the is_header variable. It seems like this approach requires more condition-checking than should be strictly necessary. Can't I just iterate over some object? I tried for row in reader[1:]: but apparently objects of type csv.reader don't allow subscripting.

#! /usr/bin/env Python3

import glob
import csv

file_names = glob.glob('*/unknown/*.dat')

with open(file_names[0], 'r') as csv_input:
  reader = csv.reader(csv_input, delimiter = '\t')
  header = ['seed'] + next(reader)

with open('output.dat', 'a') as csv_output:
  writer = csv.writer(csv_output, delimiter = '\t')
  writer.writerow(header)

  for file_name in file_names:
    param_dir = file_name.split('/')[0]
    seed = param_dir.split('-')[0]

    with open(file_name, 'r') as csv_input:
      reader = csv.reader(csv_input, delimiter = '\t')
      is_header = True
      for row in reader:
        if not is_header:
          out_row = [seed] + row
          writer.writerow(out_row)
        is_header = False


texts: Return a random line from a file when user enters a specific text

texts:
I am a beginner trying to fetch a random line from a file and wondering if this code can be improved. Should I use try and catch in this case? Should I take a parameter for the function "quote"? How can I take several alternatives for searchText? (E.g. "hello", "hi" or "hey" but one is enough to return true.)

def getInputFromUser(inputText, verifier, error=None):
    """
    General function to get input from the user, repeating the question until verifier returns true
    """
    while True:
        userInput = input(inputText)
        if not verifier or verifier(userInput):
            return userInput
        elif error:
            print(error)

def quote():
    """
    Return a random line from a file if user enters the text "hello"
    """
    searchText = "hello"
    text = getInputFromUser("Enter a sentence with the words 'hello', 'hi' or 'hey': ", lambda inputText: inputText)

    if searchText in text:
        lineFetched = random.choice(open('myquotes.txt').readlines())
        print("My quote: ", lineFetched)
    else:
        quote()


texts: Rust program, which reads, processes, and writes a file

texts:
I'm making a small program to benchmark Rust's performance compared to some other languages. The idea I came up with, was to take a file (with the numbers 1 to 10000000 written to it in separate lines) as a command line argument:

1
2
3
...
9999999
10000000

read the file, and then multiple every line in that file by two and write those back to the same file, so the end result would look like this:

2
4
6
...
19999998
20000000

My code works, and does exactly what it should do. I am especially looking for ways how I could make the code cleaner while also making it run faster. I'm currently running it with:

$ cargo run --release numbers.txt

The program:

use std::env;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Write;

fn main() {
    let args: Vec<String> = env::args().collect();
    let file_path = &args[1];

    let mut file = OpenOptions::new().read(true).open(file_path).unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    let vec: Vec<i32> = contents.lines()
        .map(|line| line.trim().parse::<i32>().unwrap() * 2)
        .collect();

    let mut file = OpenOptions::new().write(true).open(file_path).unwrap();
    for line in vec {
        write!(file, "{}\n", line).unwrap();
    }
}


texts: Calculating the difference between two (incomplete) arrays

texts:
EDIT:  Calculating the difference between 2 arrays

I'm coding PHP for only 4 months, and I need your help to improve this code

I have 2 arrays like this

//array1
 $array1[5] = 20;
 $array1[6] = 50;

 //array2
 $array2[6] = 60;
 $array2[7] = 30;

Now I need to get the difference between the values of each key between array2 and array1 i.e $array2 - $array1 (if this is legal)

So, I need the result array difference to be like this

$arraydiff[5] = -20; // NULL - $array1[5]
$arraydiff[6] =  10; // $array2[6] - $array1[6]
$arraydiff[7] =  30; // $array2[7] - NULL

I got this done by doing that

foreach($array2 as $key=> $value){
    //check if the key exists only in array2 or in both arrays
    if(isset($array1[$key])){$result[$key] = $array2[$key] - $array1[$key];}
    else{$result[$key] = $array2[$key];}
}

//get the keys that exist in array1 but not in array2
$array1diff = array_diff_key($array1,$array2);
foreach($array1diff as $key=> $value){
     $result[$key] = -1 * $array1[$key];
}
var_dump($result);

this results to

array(3) { [6]=> int(10) [7]=> int(30) [5]=> int(-20) }

Is there any better way or PHP built-in tools to get this done instead of that. Can't I do for example $result = $array2 - $array1;?


texts: Speed performance of sqlite3 queries looped in python

texts:
I have a table data stored in a database ships.db,
the data are informations of tracked ships hourly.
The table data looks like this.
time  |  shipId  |   longitude  |  latitude
---------------------------------------------------------------------
00:00:00          1              xx.xxxx       yy.yyyy
00:00:00          2              xx.xxxx       yy.yyyy
00:00:00          3              xx.xxxx       yy.yyyy
00:00:00          4              xx.xxxx       yy.yyyy
01:00:00          2              xx.xxxx       yy.yyyy
01:00:00          4              xx.xxxx       yy.yyyy
     ...                 ...                 ...                ...
23:00:00          4              xx.xxxx       yy.yyyy

Splitting the whole earth to a grid of 5-degree width and length for each cell,
I would get the number of fetched records hourly per cell of that grid.
Note that the number of records are not the same each hour because some ships are not more live therefore not fetched.
I wrote this code in python, it works but it takes large time because the database has roughly 250000 records.
Is there another method or approach to make it better and faster in python?
My script:
import sqlite3

def writeToFile(string, file):
    with open(file,"a") as ouf:
        ouf.write(string+"\n")

output = "report.txt"

with sqlite3.connect("ships.db") as con:
    cur = con.cursor()
    #iterate over times from 0 to 23 (hours)
    for hour in range(0,24):  # hours: from 0 to 23
        #make each loop of time in this time format "hh:00:00"
        time = str(hour).zfill(2)+":00:00"
        #scan from longitude -180 (180 W) to +180 (180 E) each 5 degree of longitude
        for longitude in range(-180,180,5):
                #scan from latitude -90 (90 S) to +90 (90 N) each 5 degree of latitude
                for latitude in range(-90,90,5):
                    sql = f'''SELECT time, count(*) AS occurence FROM 'data'
                    WHERE time ="{time}"
                    AND latitude BETWEEN {latitude} AND {latitude+5}
                    AND longitude BETWEEN {longitude} AND {longitude+5}
                    GROUP BY time'''
                    data = cur.execute(sql).fetchone() #fetchone because group by time
                    if data != None:
                        time, occurence = data
                    else: #some cell of grid may have no ship at a hour therefore this else
                        occurence = None
                    result = [time, occurence, longitude, latitude]

                    #writing the result to output
                    writeToFile("\t".join(result), output)


texts:
I was wondering if there's any way I can improve this code's execution.  I want to use it on a 9*9 grid, but it takes too long to solve this as 4*4.  This program takes as input a 4*4 matrix represented as a 1D matrix and returns the solution to the puzzle in the variable solution.  Any comments?

subset([],_).
subset([H|T],List):-
    !,
    member(H,List),
    subset(T,List).

different([]).
different([H|T]):-
\+member(H,T),
different(T),!.

valid([]).
valid([Head|Tail]) :-
    different(Head),
    valid(Tail),!.

sudoku(Puzzle, Solution) :-
    Solution = Puzzle,
    Puzzle = [S11, S12, S13, S14,
              S21, S22, S23, S24,
              S31, S32, S33, S34,
              S41, S42, S43, S44],

    subset(Solution, [1,2,3,4]),

    Row1 = [S11, S12, S13, S14],
    Row2 = [S21, S22, S23, S24],
    Row3 = [S31, S32, S33, S34],
    Row4 = [S41, S42, S43, S44],

    Col1 = [S11, S21, S31, S41],
    Col2 = [S12, S22, S32, S42],
    Col3 = [S13, S23, S33, S43],
    Col4 = [S14, S24, S34, S44],

    Square1 = [S11, S12, S21, S22],
    Square2 = [S13, S14, S23, S24],
    Square3 = [S31, S32, S41, S42],
    Square4 = [S33, S34, S43, S44],

    valid([Row1, Row2, Row3, Row4,
           Col1, Col2, Col3, Col4,
           Square1, Square2, Square3, Square4]).