texts: Getting around CORS error for displaying images on my website

texts:
I have my images stored in an S3 bucket and I am serving them from AWS CloudFront. I have created 2 CNAME records for the CloudFront: mywebsite.com and www.mywebsite.com

So the image path being served from AWS CloudFront could be either of the following urls:

www.mywebsite.con/s3-folder/img-1.jpg

mywebsite.com/s3-folder/img-1.jpg

The relative image path is stored in DB, and to display the image I would add www.mywebsite.com before the path...

But then I started getting CORS (Cross Origin Request Sharing). This was when user was vising the page using:  mywebsite.com url and I was building the path to the image like: www.mywebsite.com/s3-folder/img-1.jpg

To prevent this error, I built the following PhotoPathMapper, which checks the current request to see if it contains www or not and build the image url accordingly:

public static class PhotoPathMapper
{
    private static readonly string _wwwSubDomain = "www.";
    private static readonly string _fileUploadRootWithWWW;
    private static readonly string _fileUploadRootWithoutWWW;

    static PhotoPathMapper()
    {
        if (EnvironmentConfig.IsDevEnvironment)
        {
            // ignore CORS violation for DEV Environment as it runs under localhost
            _fileUploadRootWithWWW = _fileUploadRootWithoutWWW = GlobalConfig.FileUploadRoot;
        }
        else
        {
            int indexOfWWW = GlobalConfig.FileUploadRoot.IndexOf(_wwwSubDomain, StringComparison.InvariantCultureIgnoreCase);
            if (indexOfWWW >= 0)
            {
                // build 2 website roots: https://www.mywebsite.com and https://mywebstite.com
                _fileUploadRootWithWWW = GlobalConfig.FileUploadRoot;
                _fileUploadRootWithoutWWW = GlobalConfig.FileUploadRoot.Remove(indexOfWWW, _wwwSubDomain.Length);
            }
            else
            {
                throw new Exception($"FileUploadRoot '{GlobalConfig.FileUploadRoot}' Config value should include www subdomain, e.g. use https://www.mywebsite.com instead of https://mywebsite.com");
            }
        }
    }

    public static string AddAbsoluteRootOfPhotos(string relativePath)
    {
        // check to see if current request includes www subdomain or not (i.e is it mywebsite.com or www.mywebsite.com)
        // and build the absolute path accordingly. This would prevent any CORS access violation
        if (IncludeWWWSubdomain())
        {
            return _fileUploadRootWithWWW + relativePath;
        }

        return _fileUploadRootWithoutWWW + relativePath;
    }

    public static string RemoveAbsoluteRootOfPhotos(string absolutePath)
    {
        if (!string.IsNullOrEmpty(absolutePath))
        {
            int indexOfDomainWithWWW = absolutePath.IndexOf(_fileUploadRootWithWWW);
            if (indexOfDomainWithWWW >= 0)
            {
                return absolutePath.Remove(indexOfDomainWithWWW, _fileUploadRootWithWWW.Length);
            }

            int indexOfDomainWithoutWWW = absolutePath.IndexOf(_fileUploadRootWithoutWWW);
            if (indexOfDomainWithoutWWW >= 0)
            {
                return absolutePath.Remove(indexOfDomainWithoutWWW, _fileUploadRootWithoutWWW.Length);
            }
        }

        return string.Empty;
    }

    private static bool IncludeWWWSubdomain()
    {
        if (!string.IsNullOrEmpty(HttpContext.Current.Request.Url.Host))
        {
            if (HttpContext.Current.Request.Url.Host.StartsWith(_wwwSubDomain, StringComparison.InvariantCultureIgnoreCase))
            {
                return true;
            }

            return false;
        }

        throw new Exception($"Host name is empty string.");
    }
}

This has resolved the CORS issue.

I have seen this article where they change the XMLHttpRequest and change certain permissions on S3 bucket to get around the CORS error. I am wondering if my solution is good or would it be better to follow the above article.

Appreciate any feedback about this solution.


texts:
The following text is from Hal Daumé III's "A Course in Machine Learning" online text book (Page-41).

I implemented the following:

Is the implementation correct?

D = 2;
MaxIter = 100;
w = zeros(1, D);
b = 1;
for i=1:MaxIter
    output = zeros(D,1);
    for j=1:D

        a = activ_func(product(x(j,:), w') + b);

        if product(y(j,1), a)>0
            output(j)  = a;

            delta = y(j) - output(j);

            inc = x(j,:) * (coeff  * delta);

            w(1, j) = w(1, j) + inc';

            b = b + y(j, 1);
        end
    end
end

w_ret = w;

I have a few confusions.

What does it mean by ya? Is it the multiplication of a scalar value of a and the entire vector y? Or, between a and the j-th element of y (given that the inner for loop uses j as the loop counter)?

Also, what does that Algorithm-6 do? It should be calling Algorithm-5 rather than. Right?


texts: Implementing simplified Jaipur board game

texts:
I wanted to build a bot for playing Jaipur board game. I started by implementing a simplified version of the game without bot. Want to make sure I'm going in the right direction.
Few of the simplifications from the actual game:

Prices of commodities are fixed
No camels
Only one card is visible and can be picked from the market
Cards are not shuffled at the start

Code:

import random
import numpy as np

DIAMOND = 0
GOLD = 1
SILVER = 2
SILK = 3
SPICE = 4
LEATHER = 5
commodities = [DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER]

price = [7, 6, 5, 3, 3, 1] # DIAMOND, GOLD, SILVER, SILK, SPICE, LEATHER

TAKE = 0
SELL = 1
actions = [TAKE, SELL]

class Jaipur():
    def __init__(self, player1, player2):
        self.market = [DIAMOND] * 6 + [GOLD] * 6 + [SILVER] * 6 + [SILK] * 8 + [SPICE] * 8 + [LEATHER] * 10

        player1 = globals()[player1]
        player2 = globals()[player2]

        self.player1 = player1(tag='P1')
        self.player2 = player2(tag='P2')

        self.winner = None
        self.player_turn = self.player1

    def play_game(self):

        # while len(self.market != 0):
        while self.winner is None:
            self.state = self.play_move()
            self.game_winner()

            if self.winner is not None:
                print('P1 score: ', self.player1.score)
                print('P2 score: ', self.player2.score)

                print('Winner is ', self.winner)

    def play_move(self, learn=False):

        if self.player_turn == self.player1:
            self.print_game()
            new_market = self.player1.make_move(self.market, self.winner)
            self.player_turn = self.player2

        elif self.player_turn == self.player2:
            self.print_game()
            new_market = self.player2.make_move(self.market, self.winner)
            self.player_turn = self.player1

    def print_game(self):
        print(self.market)
        print('turn: ', self.player_turn.tag)
        print('market: ', self.market)
        print('player hand: ', self.player_turn.hand)
        print('player score: ', self.player_turn.score)

    def game_winner(self):

        if len(self.market) == 0:
            if self.player1.score > self.player2.score:
                self.winner = self.player1.tag
            else:
                self.winner = self.player2.tag
        return self.winner

class Player():
    def __init__(self, tag):
        self.tag = tag
        self.hand = [0] * len(commodities)
        self.score = 0

    def hand_size(self):
        return sum(self.hand)

    def take(self, market):
        print('taking..')
        if self.hand_size() == 7:
            return market

        if len(market) == 0:
            return market

        taken = market.pop()
        self.hand[taken] += 1

        return market

    def sell(self, market, commodity=None):
        print('selling..')
        if commodity is None:
            commodity = np.argmax(self.hand)

        if commodity in [DIAMOND, GOLD, SILVER] and self.hand[commodity] < 2:
            return market

        if self.hand[commodity] < 1:
            return market

        self.score += self.hand[commodity] * price[commodity]
        if self.hand[commodity] == 3:
            self.score += 2
        elif self.hand[commodity] == 4:
            self.score += 5
        elif self.hand[commodity] >= 5:
            self.score += 9

        self.hand[commodity] = 0

        return market

    def make_move(self, market, winner):
        # move = int(input('0: Take, 1: Sell. Choose move..'))
        move = random.randint(0, 1)
        new_market = market
        if move == 0:
            new_market = self.take(market)
        elif move == 1:
            new_market = self.sell(market)

        return new_market

def play():
    game = Jaipur('Player', 'Player')
    game.play_game()

play()


texts:
Challenge
Given two strings, determine if the second string is a rotation of the first.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case represented by two comma separated strings.
For each test case print out True/False if the second string is a rotation of the first.

Sample Input

Code,deCo
Review,wRevie
testcase,casetoast

Sample Output

True
True
False

Source
My solution
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LINE_LENGTH 64

char* str_mul(char* str, int times) {
    char *string_multiplied = malloc(sizeof(str) * times + 1);
    for (int i = 1; i <= times; i++) {
        strcat(string_multiplied, str);
    }
    return string_multiplied;
}

bool is_rotated(char *original, char *test_case) {
    int original_length = strlen(original);
    char *rotation_superset = str_mul(original, 2);
    bool is_substring = strstr(rotation_superset, test_case) != NULL;
    return original_length == strlen(test_case) && is_substring;
}

char* parse_and_evaluate(char *line) {
    const char tokens[] = ",\n\r";
    char *original = strtok(line, tokens);
    char *test_case = strtok(NULL, tokens);
    return is_rotated(original, test_case) ? "True" : "False";
}

int main(int argc, char *args[]) {
    if (argc < 2) {
        fprintf(stderr, "File path not provided. Exiting...\n");
        return 1;
    }

    if (argc > 2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    FILE *file = fopen(args[1], "r");
    if (file == NULL) {
        perror("Error");
        return 1;
    }

    char line[LINE_LENGTH];
    while (fgets(line, LINE_LENGTH, file)) {
        printf("%s\n", parse_and_evaluate(line));
    }

    fclose(file);
}


texts:
I am in the process of learning JS and I constantly have feeling that my code is bloat and not optimal.

I built this simple DEMO of background changing on click.  Can somebody tell me if this is good approach to build this, what can be improved?  Can I write this with less code?

jsFiddle

HTML

CSS

div {
width: 200px;
height: 200px;
border: 1px solid dimgrey;
display: flex;
margin: auto;
transition: background-color .4s ease-out;
}

div > div {
width: 100px;
height: 100px;
border: 1px solid darkgray;
}

JS

var divOne = document.getElementById("one"),
    divTwo = document.getElementById("two"),
    divOneStyle = divOne.style,
    divTwoStyle = divTwo.style,
    RGB = ["red","green","blue"],
    YPB = ["yellow","purple","black"];

var colorMeRGB = function (event) {
    divOneStyle.backgroundColor = RGB[Math.floor(Math.random() * RGB.length)];
    event.stopPropagation();
};
divOne.addEventListener("click",colorMeRGB,false);

var colorMeYPB = function (event) {
    divTwoStyle.backgroundColor = YPB[Math.floor(Math.random() * YPB.length)];
    event.stopPropagation();
};
divTwo.addEventListener("click",colorMeYPB,false);


texts:
https://leetcode.com/problems/find-bottom-left-tree-value/

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:
Input:

  2
 / \
1   3

Output:
1
Example 2:
Input:

    1
   / \
  2   3
 /   / \
4   5   6
   /
  7

Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.

Please review for performance. Thanks

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GraphsQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/find-bottom-left-tree-value/
    /// </summary>
    [TestClass]
    public class FindBottomLeftTreeValue
    {
        //Input:

        //   2
        //  / \
        // 1   3
        [TestMethod]
        public void SmallTreeTest()
        {
            TreeNode root = new TreeNode(2);
            root.left = new TreeNode(1);
            root.right = new TreeNode(3);
            Assert.AreEqual(1, FindBottomLeftValue(root));
        }

        //Input:

        //         1
        //        / \
        //       2   3
        //      /   / \
        //     4   5   6
        //        /
        //       7
        [TestMethod]
        public void BigTreeTest()
        {
            TreeNode root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.left.left = new TreeNode(4);

            root.right = new TreeNode(3);
            root.right.left = new TreeNode(5);
            root.right.right = new TreeNode(6);
            root.right.left.left = new TreeNode(7);
            Assert.AreEqual(7, FindBottomLeftValue(root));
        }

        public int FindBottomLeftValue(TreeNode root)
        {
            if (root == null)
            {
                throw new NullReferenceException("root is empty");
            }
            Queue<TreeNode> Q = new Queue<TreeNode>();
            Q.Enqueue(root);
            int left = root.val;
            while (Q.Count > 0)
            {
                // we always push the left node first then we peek, so the first item is the most left
                //for the entire level of the tree
                int qSize = Q.Count;
                left = Q.Peek().val;
                for (int i = 0; i < qSize; i++)
                {
                    var current = Q.Dequeue();
                    if (current.left != null)
                    {
                        Q.Enqueue(current.left);
                    }

                    if (current.right != null)
                    {
                        Q.Enqueue(current.right);
                    }
                }
            }

            return left;
        }
    }

    /*
      Definition for a binary tree node.*/
    public class TreeNode
    {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) { val = x; }
    }
}


texts: Counting the number of words in a string using C

texts:
I wrote a simple program to count the number of words in a string using C. Would you mind reading it and telling me if the method used is acceptable? Or if there are style errors or ways I can improve it?

 /*Procedure that counts the number of words in a string
    A word is any set of characters (or a single character)  separated
    from the word after it and before it by a space*

    For example, "a" is one word, "!" is one word, "peut-etre" is one word, "Builder Jack" are two words*/

    #include <stdio.h>

    int word_count(char *array){
        int count = 0; /*Number of words*/

        while(*array != '\0'){
            if(*array == ' '){
                count++;
            }
            array++;
        }
        return (count+1);
    }

    int main(void){
        char line[1000];

        puts("Enter text");

        fgets(line, sizeof(line), stdin);

        printf("Word count is %i", word_count(line));

        return 0;
    }


texts: Reading SQL query from a resource, with error logging

texts:
I've created a utility class that expects a logger to be passed at a method level, since I prefer legitimate errors to be written out for troubleshooting later on.  Another developer hates passing the logger to the method, because he does not care.

Cannot use optional attribute, since ILogger is not a constant.
Cannot use params because it would be a singleton, not a collection.

So I implemented it in the following manner:

public static class EmbeddedResourceUtility
{
     public static string GetSqlQuery(string namespaceAndFileNameWithExtension, ILogger logger)
     {
          try
          {
               using(var stream = typeof(EmbeddedResourceUtility).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileNameWithExtension))
                   using(var reader = new StreamReader(stream, Encoding.UTF8))
                        return reader.ReadToEnd();
          }

          catch(Exception exception)
          {
               logger.Error($"Failed to read query file {namespaceAndFileNameWithExtension}. {Environment.NewLine}{exception.HResult}: {exception.Message}");
               throw new Exception(exception.Message);
          }
     }
}

Would be incorrect to expect someone to pass an ILogger even if they do not intend to use it?  Or would there be a better way to handle this?


texts:
I started learning compilers development and as pet project decided to implement c compiler.
The first step is implementing simplest lexer.
Also, I decided to try new programming language and chose go. This is my first go program and I will be grateful for any advice. Thanks.

package lexer

import (
    "errors"
    "fmt"
    "unicode"
)

type tokenType int

const (
    EOF tokenType = iota

    Identifier
    NumericConstant

    IntType

    ReturnKeyword

    OpenRoundBracket
    CloseRoundBracket
    OpenCurlyBracket
    CloseCurlyBracket
    Semicolon
)

type token struct {
    tokenType tokenType
    value string
}

type parser struct {
    code []rune
    currentIndex int
}

func (p *parser) nextToken() token {
    p.skipSpaces()

    if p.isEOF() {
        return token{tokenType: EOF}
    }

    var newToken token

    r := p.currentRune()
    if unicode.IsLetter(r) {
        newToken = p.parseLetterStartToken()
    } else if unicode.IsNumber(r) {
        newToken = p.parseNumberStartToken()
    } else if r == '(' {
        newToken = token{tokenType: OpenRoundBracket, value:string(r)}
    } else if r == ')' {
        newToken = token{tokenType: CloseRoundBracket, value:string(r)}
    } else if r == '{' {
        newToken = token{tokenType: OpenCurlyBracket, value:string(r)}
    } else if r == '}' {
        newToken = token{tokenType: CloseCurlyBracket, value:string(r)}
    } else if r == ';' {
        newToken = token{tokenType: Semicolon, value:string(r)}
    } else {
        errorText := fmt.Sprintf("Unexpected character: %c", r)
        panic(errors.New(errorText))
    }

    p.currentIndex += 1
    return newToken
}

func (p *parser) skipSpaces() {
    if p.isEOF() {
        return
    }

    for unicode.IsSpace(p.currentRune()) {
        p.currentIndex += 1

        if p.isEOF() {
            return
        }
    }
}

func (p *parser) parseLetterStartToken() token {
    startIndex := p.currentIndex

    for unicode.IsLetter(p.currentRune()) || unicode.IsNumber(p.currentRune()) {
        p.nextRune()
    }

    endIndex := p.currentIndex

    tokenValue := string(p.code[startIndex: endIndex])
    p.currentIndex -= 1

    return letterStartToken(tokenValue)
}

func letterStartToken(tokenValue string) token {
    var tokenType tokenType

    switch tokenValue {
    case "int":
        tokenType = IntType
    case "return":
        tokenType = ReturnKeyword
    default:
        tokenType = Identifier
    }

    return token{tokenType:tokenType, value:tokenValue}
}

func (p *parser) parseNumberStartToken() token {
    startIndex := p.currentIndex

    for unicode.IsNumber(p.currentRune()) {
        p.nextRune()
    }

    endIndex := p.currentIndex

    tokenValue := string(p.code[startIndex: endIndex])
    p.currentIndex -= 1

    return token{tokenType: NumericConstant, value:tokenValue}
}

func (p parser) isEOF() bool {
    return p.currentIndex >= len(p.code)
}

func (p parser) currentRune() rune {
    return p.code[p.currentIndex]
}

func (p *parser) nextRune() rune {
    p.currentIndex += 1
    return p.currentRune()
}

func Tokenize(code []rune) []token {
    parser := parser{code:code, currentIndex:0}
    tokens := []token{}

    for newToken := parser.nextToken(); newToken.tokenType != EOF; {
        tokens = append(tokens, newToken)
        newToken = parser.nextToken()
    }

    return tokens
}


texts:
I'm doing the Racket track on exercism.io and solved the grains exercise:

  Write a program that calculates the number of grains of wheat on a chessboard given that the number on each square doubles.

(test cases etc on exercism)

So I wrote a straightforward recursive solution:

#lang racket

(provide square total)

(define (square n)
  (cond
    [(n . = . 1)    1]
    [(n . > . 1)    (* 2 (square (- n 1)))]
    [else           (error "invalid number:" n)]))

(define (sum n)
  (cond
    [(n . = . 1)    1]
    [(n . > . 1)    (+ (square n) (sum (- n 1)))]
    [else           (error "invalid number:" n)]))

(define (total)
  (sum 64))

Then I went to clean it up by factoring out the induction:

#lang racket

(provide square total)

(define-syntax (induction stx)
  (syntax-case stx ()
    ((induction base rule)
     (with-syntax ((n (datum->syntax stx 'n)))
       #'(lambda (n)
           (cond
             ((n . = . 1)   base)
             ((n . > . 1)   rule)
             (else          (error "invalid number:" n))))))))

(define square  (induction 1 (* 2 (square (- n 1)))))
(define sum     (induction 1 (+ (square n) (sum (- n 1)))))

(define (total)
  (sum 64))

I got a couple of questions:

1) Is that the most straightforward way to introduce a new binding for the macro user?

Like, this is quite wordy. I guess I could wrap the "with-syntax" part into another macro, 'cause right now this feels very "built out of raw plumbing" to me.

It's also annoying that "define-syntax-rule" doesn't give me "stx", so I don't see a way to introduce new bindings. I'd like to write something like:

(define-syntax-rule (induction base rule)
  (syntax-let ((n))
    (lambda (n)
      (cond
        ((n . = . 1)    base)
        ((n . > . 1)    rule)
        (else           (error "invalid number:"))))))

Is there anything built-in for that?

2) For argument clarity, I'd like to write it more like this:

(define (square n)
  (induction 1 (* 2 (square (- n 1)))))

How'd I do that? Like, I'd... have to capture the "n" argument correctly (how?), and return, uh... the body of the lambda? I'm confused.


texts: Creating custom random access iterator in C++ 2011

texts:
I would like an opinion on my code. I need a random access iterator for my custom container.
If I read the C++ 2011 standard, specially chapter 24, I understood that an implementation
could be the following:

class my_iterator : public std::iterator<std::random_access_iterator_tag, my_element>
{
    private:
       my_container *_ref;
       my_iterator_state state; // some useful state
    public:
       my_iterator ();
       my_iterator (const my_iterator &);
       my_iterator (my_iterator &&);
       ~my_iterator ();
       my_iterator &operator = (const my_iterator &);
       my_iterator &operator = (my_iterator &&);
       reference operator * ();
       my_iterator &operator ++ ();
       bool operator != (my_iterator);
       value_type operator * ();
       pointer operator -> ();
       my_iterator &operator * ();
       void operator ++ (int);
       value_type operator ++ (int);
       const my_iterator &operator ++ (int);
       reference operator ++ (int);
       my_iterator &operator -- ();
       const my_iterator operator -- (int);
       reference operator -- (int);
       my_iterator &operator += (difference_type);
       my_iterator operator + (difference_type);
       my_iterator operator - (difference_type);
       reference operator [] (difference_type);
       bool operator < (my_iterator);
       bool operator > (my_iterator);
       bool operator <= (my_iterator);
       bool operator >= (my_iterator);
       friend difference_type (my_iterator, my_iterator);
       friend my_iterator operator + (difference_type, my_iterator);
       friend void swap (iterator &, iterator &);
};

void swap (iterator &, iterator &);
difference_type (my_iterator, my_iterator);
my_iterator operator + (difference_type, my_iterator);

The above implementation is correct and full-featured? There are too members?


texts: Coin tossing simulation to get x heads in a row, ten times - timely at higher amount of heads

texts:
I have created a program to simulate a coin being tossed to land on heads/tails x amount of times in a row, where x can be defined by the user. The program then gets x amount of heads in a row, a fixed ten times. This is to generate an average.

using System;

namespace HeadsStreak
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter a head streak to get. This will be executed ten times to generate an average.");
            int desiredStreak = Convert.ToInt32(Console.ReadLine());
            int grandTotalAttempts = 0;
            int executionCount = 1;
            int currentStreak = 0;
            int totalAttempts = 0;
            Random rnd = new Random();
            do
            {
                while (currentStreak != desiredStreak)
                {
                    if (rnd.Next(0, 2) == 0)
                    {
                        currentStreak += 1;
                    }
                    else
                    {
                        currentStreak = 0;
                    }
                    totalAttempts += 1;
                }
                Console.WriteLine("Attempt Number: {0}", executionCount);
                Console.WriteLine("Total Attempts: {0}", totalAttempts);
                Console.WriteLine("");
                grandTotalAttempts += totalAttempts;
                executionCount += 1;
                currentStreak = 0;
                totalAttempts = 0;
            } while (executionCount <= 10);
            Console.WriteLine("Average Attempts: {0}", grandTotalAttempts/10);
        }
    }
}

Let's say I ask for fifteen heads. The console may look something like this:

Enter a head streak to get. This will be executed five times to generate an average.
15
Attempt Number: 1
Total Attempts: 82761

Attempt Number: 2
Total Attempts: 42464

Attempt Number: 3
Total Attempts: 157531

Attempt Number: 4
Total Attempts: 79750

Attempt Number: 5
Total Attempts: 19214

Attempt Number: 6
Total Attempts: 4573

Attempt Number: 7
Total Attempts: 8161

Attempt Number: 8
Total Attempts: 99553

Attempt Number: 9
Total Attempts: 41036

Attempt Number: 10
Total Attempts: 84431

Average Attempts: 61947

This can execute fairly quickly within a reasonable timeframe. Time issues begin at 24, I assume this is because it takes 2^24 attempts to get 24 heads in a row. However, I am wondering if there is anything to improve in the code in order to improve performance so that higher streaks can be achieved within a reasonable timeframe?


texts:
I come today with a state machine I'm currently working on.

Problem:

  Given any State that the Character is in, a button press or combination of button presses can modify that state in a different way than how the initial state was entered.

I've looked at several different methods of creating a solution, but I feel that my current solution is lacking in its ability to be extendable. Would a Behavior Tree be more suitable for this kind of problem?

public class StateManager<T> where T : Engine.Object
{
    //See notes in the Constructor.
    IState _currentState,_lastState,_nextState,_defaultState;

T _objectReference;

StateCompletion _onCompletion,_nextOnComplete;

public StateManager(T objectRef)
{

    //Creating a "NullState" removes any and all possibilities of a NRE in the event that the next state is considered Null.
    //It can also be used for error handling or testing deadlock cases.
    _defaultState = new NullState();
    _onCompletion = OnComplete;
    _nextOnComplete = OnComplete;

    //This is to store the object that we are currently manipulating with the state machine itself.
    _objectReference = objectRef;

    //The various states of the state machine shift and store the various states it passes through.
    _currentState = _defaultState;
    _nextState = _defaultState;
    _lastState = _currentState;

    //Enter the default "NullState"
    _currentState.Enter(_objectReference,_lastState,_onCompletion);
}

//Used for the default NullState
private void OnComplete(object isComplete)
{
    Debug.LogWarning("Warning! You are acting on a Null State");
}

public void ChangeState<TU>(StateCompletion onComplete) where TU : IState, new()
{
    //Assign next OnComplete Delegate
    _nextOnComplete = onComplete;

    //Assign the appropriate state.
    _nextState = new TU();
    if(_lastState != _currentState) //Set previous state if applicable.
    {
        _lastState = _currentState;
    }
}

public void Execute()
{
    //This is essentially wrapping the inner state machines update loop.
    _currentState.Execute();

    //Check Completion of the current State to catch when the state is finished calculating it's information.
    if(_currentState.IsComplete()) //States can be
    {
        SwitchState();
    }
}

public void CheckModifier(KeyCode key)
{
    //This would pass the keycode into the state and check to see if it could modify its current actions.
    _currentState.CheckStateModifiers();
    //Something about this screams that this is going to lead to loads of repeated codes.
}

public void PhysicsExecute()
{
    _currentState.PhysicsExcecute();
}

private void SwitchState()
{
    //Call the current states OnComplete delegate.
    _onCompletion(_objectReference);
    _onCompletion = _nextOnComplete; //Assign the next delegate based on the last state change request.

    //Begins calculating the next states information in Excecute.
    _currentState = _nextState;
    _currentState.Enter(_objectReference,_lastState,_onCompletion);

    //Set next OnComplete to the Null completion method.
    _nextState = _defaultState;
    _nextOnComplete = OnComplete;
}
}


texts: Shell agnostic startup flow - env, profile, rc, login

texts:
The goal of these files is to have some common behavior between Bash and Zsh
when starting them. As is known, when Bash starts as a login shell it will
source the first found of the following in your home director: .bash_profile,
.bash_login, or .profile. If Bash is a nonlogin interactive it will source
.bashrc. Meanwhile, Zsh behaves pretty differently. First, it always sources
.zshev. Next, if it's a login shell it will source .zprofile followed by
.zshrc (it sources this even if it's just interactive) and finally .zlogin.
I wanted there to be some common behavior here, so I made it so the flow for
both are:

Common environment
Shell specific environment
Common profile (if login)
Shell specific profile (if login)
Common "rc" (if interactive)
Shell specific "rc" (if interactive)
Common login (if login)
Shell specific login (if login)

The new files I have had to add are .bash_env, .common_env, .common_login,
and .common_rc.

A lot of these files only have some debug statements at the top (which all of
them do), so I won't be posting those. In addition, all of the Zsh files are the
same pattern so I'll only be posting one. I'm not including any of the "actual"
things these do (like set aliases or environment variables) because they're not
relevant to what I want reviewed.

.bash_profile

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "* In .bash_profile"

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_env if it exists"
[ -f "${HOME}/.common_env" ] && source ${HOME}/.common_env

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.bash_env if it exists"
[ -f "${HOME}/.bash_env" ] && source ${HOME}/.bash_env

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.profile if it exists"
[ -f "${HOME}/.profile" ] && source ${HOME}/.profile

# Start of "actual content"

# End of "acutal content"

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_rc if it exists"
[ -f "${HOME}/.common_rc" ] && source ${HOME}/.common_rc

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.bashrc if it exists"
[ -f "${HOME}/.bashrc" ] && source ${HOME}/.bashrc

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_login if it exists"
[ -f "${HOME}/.common_login" ] && source ${HOME}/.common_login

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.bash_login if it exists"
[ -f "${HOME}/.bash_login" ] && source ${HOME}/.bash_login

.bashrc

This one checks to make sure it's not a login shell before sourcing to avoid sourcing twice.

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "* In .bashrc"

shopt -q login_shell || ([ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_env if it exists")
shopt -q login_shell || ([ -f "${HOME}/.common_env" ] && source ${HOME}/.common_env)

shopt -q login_shell || ([ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.bash_env if it exists")
shopt -q login_shell || ([ -f "${HOME}/.bash_env" ] && source ${HOME}/.bash_env)

[[ "$-" != *i* ]] && return

shopt -q login_shell || ([ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_rc if it exists")
shopt -q login_shell || ([ -f "${HOME}/.common_rc" ] && source ${HOME}/.common_rc)

# Start of "actual content"

.zshenv

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "* In .zshenv"

[ "$MY_STARTUP_DEBUG" = "true" ] && echo "\t* Sourcing ${HOME}/.common_env if it exists"
[ -f "${HOME}/.common_env" ] && source ${HOME}/.common_env

# Start of "actual content"


texts: A shim to make make Node GRPC bindings more JavaScript-y

texts:
This function allows me to write this code

const audioOutConfig = new AudioOutConfig();
audioOutConfig.setSampleRateHertz(16000);
audioOutConfig.setEncoding(AudioOutConfig.Encoding.LINEAR16);
audioOutConfig.setVolumePercentage(100);

as this code

const audioOutConfig = config(new AudioOutConfig(), {
  sampleRateHertz: 16000,
  encoding: AudioOutConfig.Encoding.LINEAR16,
  volumePercentage: 100
});

Is this a bad idea, and is the function I wrote to do it acceptable?

function config(obj, opts) {
  for (var opt in opts) {
    if (opts.hasOwnProperty(opt)) {
      obj[`set${opt.charAt(0).toUpperCase() + opt.slice(1)}`](opts[opt]);
    }
  }
  return obj;
}


texts:
Advent of Code 2019: Day 4
I'm doing Advent of Code this year. Below is my attempt at day 4:
Problem
Part One

--- Day 4: Secure Container ---
You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.
However, they do remember a few key facts about the password:

It is a six-digit number.
The value is within the range given in your puzzle input.
Two adjacent digits are the same (like 22 in 122345).
Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).

Other than the range rule, the following are true:

111111 meets these criteria (double 11, never decreases).
223450 does not meet these criteria (decreasing pair of digits 50).
123789 does not meet these criteria (no double).

How many different passwords within the range given in your puzzle input meet these criteria?

Part Two

--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following are now true:

112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.
123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22).

How many different passwords within the range given in your puzzle input meet all of the criteria?

Solution
from itertools import groupby

bounds = (265275, 781584)

rules = [
    # Digits are never decreasing
    lambda s: all(int(s[i]) <= int(s[i+1])
                  for i in range(len(s)-1)),
    # Two adjacent digits are equal.
    lambda s: any(s[i] == s[i+1] for i in range(len(s)-1)),
    # Two adjacent digits don't form a larger group.
    lambda s: any(len(list(v)) == 2 for _, v in groupby(s))
]

def test(num, rules):
    return all(f(str(num)) for f in rules)

def solve(bounds, rules):
    return sum(1 for i in range(bounds[0], bounds[1]+1) if test(i, rules))

def part_one():
    return solve(bounds, rules[:2])

def part_two():
    return solve(bounds, rules[::2])

print(part_one())  # 960
print(part_two())  # 626

Notes
I don't consider myself a beginner in Python, however I am not proficient in it either. I guess I would be at the lower ends of intermediate. I am familiar with PEP 8 and have read it in its entirety, thus, any stylistic deviations I make are probably deliberate. Nevertheless, feel free to point them out if you feel a particular choice of mine was sufficiently erroneous. I am concerned with best practices and readability, but also the performance of my code. I am not sure what tradeoff is appropriate, and would appreciate feedback on the tradeoffs I did make.
My style tends to over utilise functions. This is partly because I genuinely think separating functionality into functions is a good thing, but is also an artifiact of my development practices. I tend to write the program in a Jupyter notebook (the ability to execute arbitrary code excerpts in semi isolated cells is a very helpful development aid and lends itself naturally to one function per cell (with the added benefit of being able to easily test functions independently)). I would welcome thoughts on this, but unless it is particularly egregious, I am unlikely to change it.


texts:
I am trying to convert this velocity into another 2 dimensional vector at some specified angle:

float maximumVelocity = 1.5f;
float angleInDegrees = 23f;
Vector2 actualVelocityAs2DimensionalVector = {?,?}

At first, I was going to take 1.5, and rotate it after converting the degrees to radians, like so:

double radians = Math.toRadians(angleInDegrees);
Vector2 actualVelocityAs2DimensionalVector = new Vector2(x * Math.cos(radians) - y * Math.sin(radians),
                                                         x * Math.sin(radians) + y * Math.cos(radians));

Is this the fastest way to achieve this? This will be happening a lot in my application, and I would think all the cos and sin calls are somewhat expensive.


texts: Returns Google Sheet cells from a named range

texts:
I've got this function that's called in several places in some of my Google Spreadsheets. It accepts a Range object, a string to search for, and an optional boolean to determine whether to make the search case-sensitive or not, and defaults to true.

function getCellsWithValueInRange(SearchRange, search_string, case_sensitive) {
    var case_sensitive = (case_sensitive !== undefined && case_sensitive === false) ? false : true;
    var result = [];
    var RangeValues = { values: SearchRange.getValues(),
                         width: SearchRange.getWidth(),
                        height: SearchRange.getHeight(),
                         start: { column: SearchRange.getColumn(),
                                     row: SearchRange.getRow() }};
    for (var x = 0; x < RangeValues.width; x++) {
        for (var y = 0; y < RangeValues.height; y++) {
            if (!case_sensitive) {
                // Lower case the search term and potential result, but ONLY if either terms have the toLowerCase method (like date objects).
                search_string = search_string.toLowerCase ? search_string.toLowerCase() : search_string;
                RangeValues.values[y][x] = RangeValues.values[y][x].toLowerCase ? RangeValues.values[y][x].toLowerCase() : RangeValues.values[y][x];
            }
        if (search_string === RangeValues.values[y][x]) {
            result.push(SearchRange.getCell(y + RangeValues.start.row, x + RangeValues.start.column));
        }
      }
    }
    return result;
}

Right now, this code works, but I'm not terribly happy with for several reasons:

It uses multiple nested loops, which feel and look horrible (debugging this was a pain).
I have doubts on its performance. Right now I've attempted to follow the best practices by batching retrieval (the first draft of this code just directly referenced the specific Ranges via getCell in the nested loops, but performance was so bad that any range that was over 600 rows just simply gave up, hence the use of getValues() instead. I haven't looked at the performance of this version, but at least it will accept large ranges (approximately 12 columns × 1300+ rows) without failing because it exceeded the maximum execution time.
I have no idea if there are any search values that would cause this function to fail. I mean, it already throws an error if the Cell Range is an object (i.e. when it's a date). Where else would it fail? Can I protect myself from other instances?

In any case, are there better, more maintanable and performant ways to code this? I've kind of accepted that it won't exactly be the fastest code (it literally has to go through any kind of range, no matter it's state), but any kind of improvement will do.

I'm kind of stymied, mostly because after searching high and low, I've discovered that it's kind of hard to get indexes for nested Arrays in JavaScript (and, by extension, Google Apps Script), so my initial attempts to make this more functional by using map or filter (I was toying with using Underscore for Google Apps Script) just hit a brick wall.


texts:
Using Python's LXML I must read an XML file and print from each "basic" and "expert" tag, the name and email text from it. I've done a script that works but I don't think is the best way of doing this. Is there a better (simpler) way for getting the data of the XML without having to make 2 iterations on it?

Python so far:

from lxml import etree

myXML = "data.xml"
tree = etree.parse(myXML)
root = tree.getroot()
for node in root:
    if node.tag == "basic" or node.tag == "expert":
        user = [None] * 4
        for i, child in enumerate(node):
            if child.tag == "name":
                user[0] = i
                user[1] = child.text
            if child.tag == "email":
                user[2] = i
                user[3] = child.text
        print user
        if user[3].startswith('_'):
            # do some other things with data if email begins with _ ...

Will print:

[0, 'f.bar', 1, 'foobar@me.com']
[0, 'm.bob', 3, 'm.bob@email.com']
[0, 'm.bab', 3, 'm.bab@email.com']

XML sample:

<?xml version="1.0"?>
<users>
    <id>11111</id>
    <checked>True</checked>
    <version>A12</mode>
    <basic>
        <name>f.bar</name>
        <email>foobar@me.com</email>
        <forename>Foo</forename>
        <surname>Bar</surname>
    </basic>
    <expert>
        <name>m.bob</name>
        <forename>Mak</forename>
        <surname>Bob</surname>
        <email>m.bob@email.com</password>
    </expert>
    <expert>
        <name>m.bab</name>
        <forename>Mak</forename>
        <surname>Bab</surname>
        <email>m.bab@email.com</password>
    </expert>
    <guru>
        <name>e.guru</name>
        <forename>Nick</forename>
        <email>nick@email.com</password>
        <surname>Gru</surname>
    </guru>
</users>


texts: Improving efficiency of Project Euler 185 (16-place Mastermind)

texts:
This a solution for Project Euler Problem 185.  It works fine for the example but slow for the problem statement. How can I improve its speed and efficiency?

import itertools
from collections import defaultdict
def mrange(start, stop, step=1):
    i = start
    while i < stop:
        yield i
        i += step
#produces the list of numbers
number= mrange(10**4,10**5)
newlist=[]
def combination(x,n):
    if n==0:
        temp=[]
        for i in range(1,len(x)+1):
            temp.extend(list(itertools.combinations(x,i)))
        return temp
    return list(itertools.combinations(x,n))

def combineDictTuple(dt):
    d = {}
    for item in dt:
        d.update(item)
    return d
def prob(a,n):
    temp=[]
    if n==0:
        temp=number
    #modchar is indexing the numbers eg:[{0: '9'}, {1: '0'}, {2: '3'}, {3: '4'}, {4: '2'}]
    modchar=[{i: c} for i, c in enumerate(a)]
    combos = combination(modchar,n)
    newCombos = [combineDictTuple(dt) for dt in combos]
    # newCombos gives combination of the indexes
    #[{0: '9', 1: '0'}, {0: '9', 2: '3'}, {0: '9', 3: '4'}, {0: '9', 4: '2'}, {1: '0', 2: '3'}, {1: '0', 3: '4'}, {1: '0', 4: '2'}, {2: '3', 3: '4'}, {2: '3', 4: '2'}, {3: '4', 4: '2'}]
    for j in number:
        for i in newCombos:
            index=i.keys()
            val=i.values()
            # print index,val
            if n==0:
                if all(str(j)[index[l]]==val[l] for l in range(0,len(val))):
                    if j in temp:
                        del temp[temp.index(j)]
                        break
            else:

                if all(str(j)[index[l]]==val[l] for l in range(0,len(val))):
                    temp.append(j)
                    break
    return temp

val='''90342 ;2 correct
70794 ;0 correct
39458 ;2 correct
34109 ;1 correct
51545 ;2 correct
12531 ;1 correct'''
val=val.replace('correct','').replace(';','').split('\n')
for i in val:
    i=i.split()
    number=prob(i[0],int(i[1]))

print number

How the function works:

Generate numbers using mrange()
In prob method  first I find the index of the each number in problem statement, e.g. 90342
That produces [{0: '9'}, {1: '0'}, {2: '3'}, {3: '4'}, {4: '2'}]
Using n (n is no. of correct values) I produce combinations of the above dict example as stated in comments
For every number I am checking the condition which satisfy the index:value append into temp and at last my new numbers become temp values. This iterates for all values until it arrives at the answer.

note: if n=0. i calculate all the combinations and delete the numbers from temp which satisfy that.


texts: Improving JavaScript - using objects vs. just functions

texts:
I'm no stranger to JS, but I think I still have a lot to learn. I originally wrote this code to manipulate a "help" bar, which would be positioned as a thin ribbon on the side of the browser window, which when hovering over or clicking would open up and display it's contents. Nothing major, but an okay example to use here.

$(document).ready(function () {
var open = false;
var peek = false;
var helpBar = $(".help-bar");
var helpIcon = $(".help-icon");
var help = helpBar.add(helpIcon); // Put both together to do the same things

helpBar.click(function () {
    toggleHelp();
});

helpBar.hover(function () {

    togglePeek();
});

function toggleHelp() {
    if (open) {
        changeRightValue(help, "0", "slow");
        toggleArrow("Open");
        open = false;
    }
    else {
        changeRightValue(help, "280", "fast");
        toggleArrow("Close");
        open = true;
    }
}

function togglePeek() {
    if (open == false) {
        help.stop();
        if (peek) {
            changeRightValue(help, "0", "fast");
            peek = false;
        }
        else {
            changeRightValue(help, "5", "fast");
            peek = true;
        }
    }
}

function changeRightValue(element, amount, speed) {
    element.animate({ right: amount }, speed);
}

function toggleArrow(direction) {
    helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
}
});

It works fine, but then I wondered whether grouping related items into objects might help a little:

    $(document).ready(function(){
    var open = false;
    var peek = false;

    var helpBar = $(".help-bar");
    var helpIcon = $(".help-icon");

    var helpSection = helpBar.add(helpIcon); // Put both together to do the same things

    var help = {};
    var utils = {};

    help.toggle = function(){
        if (open) {
            utils.changeRightValue(helpSection, "0", "slow");
            utils.toggleArrow("Open");
            open = false;
        }
        else {
            utils.changeRightValue(helpSection, "280", "fast");
            utils.toggleArrow("Close");
            open = true;
        }
    };

    help.peek = function(){
        if (open == false) {
            helpSection.stop();
            if (peek) {
                utils.changeRightValue(helpSection, "0", "fast");
                peek = false;
            }
            else {
                utils.changeRightValue(helpSection, "5", "fast");
                peek = true;
            }
        }
    };

    utils.changeRightValue = function(element, amount, speed){
        element.animate({right:amount}, speed);
    };

    utils.toggleArrow = function(direction){
        helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
    };

    // jQuery DOM
    helpBar.click(function () {
        help.toggle();
    };

    helpBar.hover(function () {

        help.peek();
    };
});

Is this that much of an improvement over the first? Is there another way that I should be writing this kind of code?


texts:
I have this code so far:

Input

A dictionary, which has Excel Data

DATA_DICT = {
  '1238': {
    'ipAddrPrim': ['IP1', 'IP2', 'IP3'],
    'mmeName': ['N1', None, 'N3'],
    's1LinkStatus': ['available', 'unavailable', 'available']
  },
  '1236': {
    'ipAddrPrim': ['IP1', 'IP4'],
    'mmeName': ['N4', 'N5'],
    's1LinkStatus': ['available', 'available']
  },
  '1238': {
    'ipAddrPrim': ['IP3', 'IP4', 'IP5'],
    'mmeName': ['N7', 'N9', None],
    's1LinkStatus': ['available', 'available', 'unavailable']
  },
  ....
}

Code

This gives the source and target lists

def finding_distinct_ips():
    result_list, source_list, target_list, src_mrbts_key = [], [], [], []
    unique_mrbts_list = remove_duplicates(MRBTS) #MRBTS has all MRBTS ids [1234,1234,1234,1236,1236,1238,1238,1238]
                                                 #remove_duplicates(MRBTS) -> [1234,1236,1238]
    for mrbts_id in unique_mrbts_list:
        rest = {k: v for k, v in DATA_DICT.items() if k != mrbts_id}
        main_key_ip_list = DATA_DICT[mrbts_id].get('ipAddrPrim')
        status = DATA_DICT[mrbts_id].get('s1LinkStatus')
        mme_name = DATA_DICT[mrbts_id].get('mmeName')
        for key, val in rest.items():
            rest_key_ip_list = val['ipAddrPrim']
            result = compare(main_key_ip_list, rest_key_ip_list) #--> lst3 = list(set(main_key_ip_list) - set(rest_key_ip_list))
            for ip_addr in result:
                ip_row_index = main_key_ip_list.index(ip_addr)
                if ip_addr != [] and status[ip_row_index] != 'unavailable':
                    mme_at_ip = mme_name[ip_row_index]
                    result_list = (mrbts_id, key, mme_at_ip, ip_addr)
                    if result_list[0:2][::-1] not in src_mrbts_key:
                        src_mrbts_key.append(result_list[0:2])
                        source_list.append(result_list)
                    else:
                        target_list.append(result_list)
    return source_list, target_list

Explanation

I have an Excel spreadsheet:

MRBTS  IPs  NAMES STATUS
1234   IP1   N1    Yes
1234   IP2   -     No
1234   IP3   N3    Yes
1236   IP1   N4    Yes
1236   IP4   N5    Yes
1238   IP3   N7    Yes
1238   IP4   N9    Yes
1238   IP5   -     No

My Code fulfils these requirements:

compare each MRBTS with each other just like

comp(1234,1236),comp(1234,1238),comp(1236,1234),comp(1236,1238),comp(1238,1234),comp(1238,1236),...]

but not with same mrbts like comp(1234,1234).
take (if status=Yes) for comp(1236,1238): In 1236, I have some list(IPs[IP1,IP4] and Ns[N4,N5]) so again I need to compare those list with 1238's list (IP[IP3,IP4] and Ns[N7,N9]).  Here we don't consider IP5, since its status is No.  If any IP in the first list is missing from the second, then return that IP and Name only if status is Yes.

compare(1236,1238) = [1236,IP1,N4] and compare(1238,1236) = [1238,IP3,N7]

Now do the comparison for all combinations and store the results in the format source = [compare(1236,1238)] and target = [compare(1238,1236)] Note: here we can observe source has right ordered comparison and target has reverse ordered comparison.

I want to make my code more efficient and reduce its time complexity.

Note:

I avoid Nested for loops, as my original spreadsheet has a huge number of data it'll take time to read.
I'm restricted to openpyxl and pyxlsb packages only.


texts: Roll the dice - to give a random output with a die


texts:
function fillFormInputs(data) {
  $('input[name="name"]').val(data.name);
  $('input[name="surname"]').val(data.surname);
  $('input[name="patronymic"]').val(data.patronymic);
  $('input[name="email"]').val(data.email);
  $('input[name="skype"]').val(data.skype);
  $('input[name="icq"]').val(data.icq);
  $('input[name="homeAddress"]').val(data.homeAddress);
  $('input[name="additionalInfo"]').val(data.additionalInfo);
  $('input[name="birthday"]').val(dateInISOFormat(new Date(data.birthday)));
  for (var i = 0; i < data.phones.length; i++) {
    var phone = data.phones[i];
    insertPhoneNumber(phone.number, phone.type);
  }
  $("img:first").attr("src", "data:image/png;base64, " + data.image.content);
}

function dateInISOFormat(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var year = date.getFullYear();
    return year + "-" + month + "-" + day;
}

function insertPhoneNumber(number, type) {
    if (checkValidPhone(number)) {
        document.getElementById("incorrectNumber").hidden = true;
        insertRow(number, type);
    } else {
        document.getElementById("incorrectNumber").hidden = false;
    }
}

var phoneCount = document.getElementById("phoneTable").getElementsByTagName("tr").length;

function insertRow(number, type) {
    var phoneTable = document.getElementById("phoneTable");
    var row = phoneTable.insertRow(0);
    insertInput(row.insertCell(0), "number", number);
    insertInput(row.insertCell(1), "type", type);
    var tdForDelBtn = row.insertCell(2);
    var deletePhoneBtn = document.createElement("button");
    deletePhoneBtn.setAttribute("name", "deletePhone");
    deletePhoneBtn.setAttribute("onclick", "deleteRow(this)");
    deletePhoneBtn.innerHTML = "delete";
    tdForDelBtn.appendChild(deletePhoneBtn);
    phoneCount++;
}

data it is planeObject.

Method works fine, but can I rewrite this simpler?
data contains pairs key - value, where value string. Most interesting for me fillFormInputs(data) method, but i ready look at other problems in my code. Thanks.


texts:
Here is my code:

def odd_numbers_from(n):
    if n % 2 == 0:
        n = n + 1
    while True:
        yield n
        n = n + 2

def takeWhile(pred, lst):

    for item in lst:
        if pred(item):
            yield item
        else:
            break

def takePrimes(iterator):

    for n in iterator:

        if not 0 in (n % k for k in takeWhile(lambda x: x**2 <= n, primes())):

            yield n

# -- memoized prime generator
def primes(earlier_primes=[2]):

    yield from earlier_primes

    for new_prime in takePrimes(odd_numbers_from(earlier_primes[-1]+1)):

        earlier_primes.append(new_prime)

        yield new_prime

if __name__ == "__main__":

    for k in primes():

        print(k)
        if k > 300:
            break

In first run, it will produce prime numbers as long as they are requested. On subsequent runs, it will just yield from previously generated primes. We can test this behaviour like this:

# -- memoized prime generator
def primes(earlier_primes=[2]):

    yield from earlier_primes

    for new_prime in takePrimes(odd_numbers_from(earlier_primes[-1]+1)):
        print("generated new prime")
        earlier_primes.append(new_prime)

        yield new_prime

if __name__ == "__main__":

    for k in primes():

        print(k)
        if k > 20:
            break

    print("=====")

    for k in primes():

        print(k)
        if k > 30:
            break

This should output:

2
generated new prime
3
generated new prime
5
generated new prime
7
generated new prime
11
generated new prime
13
generated new prime
17
generated new prime
19
generated new prime
23
=====
2
3
5
7
11
13
17
19
23
generated new prime
29
generated new prime
31

How does it look?


texts:
I'm making a game battle system, where there are 2 players.

Every player can have multiple units to control, but only one at a time.
Every unit has an int curSpeed variable;

I need to have in 2 variables who attacks first (Player f) and who attacks second (Player s), based on the speed of the current controlling unit.

At the moment I have this code:

player_1 and player_2 are instances of Player Class
current, is a instance of Unit Class, it is the current controlling unit.

Player f = null; //Player attacking first
Player s = null; //Player attacking second

//Check the speed of the units, and determine who attack first
f = player_1.current.curSpeed > player_2.current.curSpeed ? player_1 : player_1.current.curSpeed < player_2.current.curSpeed ? player_2 : null;

//if f is null (units have the same speed)
if(f==null){
    //Randomize who goes first
    System.Random rnd = new System.Random();
    int rng = rnd.Next(0,2);
    f = rng == 0 ? player_1 : player_2;
    s = rng == 0 ? player_2 : player_1;
}else{
    s = f.id == player_1.id ? player_2 : player_1;
}

It is working, but I feel that this is confusing and the 'wrong way' to do it.

I need tips on how I can code this in a better way.

UPDATE:
New version of the code including all the suggestions can be found here.


texts:
I want some feedback on the program I developed in C for printing the permutations of a given string.

#include <stdio.h>
bool isUnique(char x[], int y)
{
   int i, j;
   for (i = 0; i < (y-1); i++)
     for (j = i+1; j < y; j++)
       if (x[i] == x[j])
          return false;
   return true;
}
void perm(char a[], char b[], int x, int y)
{
   if ((y == x) && isUnique(b,x))
   {
     b[y] = '\0';
     printf("%s\n", b);
   }
   else
     for (int i = 0; i < x; i++)
     {
        b[y] = a[i];
        if (y < x)
          perm(a,b,x,y+1);
     }
}
int main()
{
   char a[] = {'1','2','3','4'}, b[] = {'\0','\0','\0','\0','\0'};
   perm(a,b,4,0);
   return 0;
}

Also, please tell me where I'm making blunders as far as conventions and good practice are concerned.


texts:
I am trying to check a bunch of files that should have a leading | delimiter but sometimes don't. If the first line doesn't have the |, the rest of the file won't, if it does have it, then the rest of the file will.

I'm checking the first line which works and enters the update logic, which advances to the next row once I read the line in. So I added a writer.Write before I go into the Do While loop and it works, but it seems like there would be a better way of doing this.

    Dim fileList As FileInfo() = dirList.GetFiles

    For Each fiName In fileList
        sFullName = fiName.FullName
        sFileName = Path.GetFileNameWithoutExtension(fiName.ToString)
        sDir = fiName.DirectoryName
        Dim reader As New StreamReader(sFullName)
        Dim line As String = reader.ReadLine()

        If Not line.StartsWith("|") Then

            Dim sNewFullName As String = sDir + "\" + sFileName + "_Temp.txt"
            Dim writer As New StreamWriter(sNewFullName)
            Dim sLine As String

            sLine = "|" + line + System.Environment.NewLine
            writer.Write(sLine)

            Do While reader.Peek() <> -1
                sLine = "|" + reader.ReadLine() + System.Environment.NewLine
                writer.Write(sLine)
            Loop

            writer.Close()
            reader.Close()
            File.Delete(sFullName)
            File.Move(sNewFullName, sFullName)

        End If
        reader.Close()
    Next fiName


texts: Using  element instead of  to get clickable rows

texts:
I want to create clickable rows in an html table. Each row should be a link leading to a different page. I can of course add onclick handler, but that will create kind of a crappy UI - poor accessibility, no keyboard navigation, no right/middle click...
I found a better way to do it. Instead of using normal table element, force divs to act as different table tags through css display rules. And for rows, use a-s, with appropriate href attribute.
Here's what I mean:

  .table {
    display: table;
    border-collapse: collapse;
    font-family: sans-serif;
    width: 100%;
  }
  .thead {
    display: table-header-group;
  }
  .tbody {
    display: table-row-group;
  }
  .td, .th {
    display: table-cell;
    padding: 5px 10px;
    text-align: center;
  }
  .tr {
    display: table-row;
  }
  .thead > .tr {
    background: #ccc;
    color: #555;
  }
  a.tr {
    text-decoration: none;
    color: black;
  }
  a.tr:hover {
    background: #eee;
    cursor: pointer;
  }

ID

Name

524

John Smith

331

Miles Corner

Note how rows are clickable, you can tab through them and there is a nice tooltip showing link you will go to. Much better than onclick.
If I use a framework like React, I don't even have to replace all elements with div-s. I can just add  tags instead of
s and it will work.
My question is, what's the catch? What am I missing? Is there some accessibility, browser compatibility, or other reason not to do this?


texts: Udacity Intro to HTML and CSS layout sample

texts:
I'm going through the Udacity Intro to HTML and CSS course at the moment, and one of the exercises is to convert this mockup to HTML and CSS.

I did the following, and it looks ok-ish:

HTML:

<!DOCTYPE html>

  <title>Jane Doette / Front-end Ninja</title>
  <link rel="stylesheet" href="css/style.css">

Jane Doette

Front-end Ninja

Featured Work

Appify

https://github.com/udacity/Appify/

Sunflower

https://github.com/udacity/Sunflower/

Bokeh

https://github.com/udacity/Bokeh/

CSS:

@import url(http://fonts.googleapis.com/css?family=Lato:100,300);

/* Sample framework supplied with the course */

* {
  /*border: 1px solid red !important;*/
  font-family: Lato, sans-serif;
  color: #1f1f1f;
}

* {
  -ms-box-sizing: border-box;
  box-sizing: border-box;
}

.row {
  margin-bottom: 20px;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

/* End of the sample framework */

div.page-content {
  width: 960px;
  margin: auto;
}

div.main-title {
  margin-left: auto;
  text-align: right;
  text-transform: uppercase;
}

div.main-title h1 {
  font-size: 58px;
  font-weight: 100;
  margin-bottom: 0;
}

div.main-title h2 {
  font-size: 18px;
  font-weight: 300;
  margin-top: 0;
}

header.main-header {
  align-items: center;
  border-bottom: 5px solid silver;
  margin-bottom: 30px;
}

div.hero-image {
  max-height: 400px;
  overflow: hidden;
}

div.hero-image img {
  width: 100%;
}

section.featured-work .row {
  justify-content: space-between;
  margin-left: auto;
  margin-right: auto;
}

div.work-screenshot {
  width: 300px;
  height: 200px;
  overflow: hidden;
  position: relative;
}

.featured-work div {
  text-align: center;
}

.featured-work p {
  margin-top: 0;
}

.featured-work p a {
  color: #bebebe;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

div.work-screenshot img {
  max-width: 300px;
}

h2 {
  font-size: 38px;
  font-weight: 300;
  color: #9e9e9e;
  margin: 30px 5px 10px 5px;
}

h3 {
  font-size: 36px;
  text-transform: uppercase;
  margin: 10px 0;
  color: #6e6e6e;
}


texts: Parse user data in to student and teacher details

texts:
Initially I have a code in JavaScript which looks like -
const createUsersInfo = obj => {
    const studentDetails = [];
    const teacherDetails = [];
    obj.forEach(x => {
      if (x.type) {
        if ( x.type === 'teacher' && x.group !== 'admin' ) {
            teacherDetails.push(x);
        } else if ( x.type === 'student' && x.group !== 'admin' ) {
            studentDetails.push(x);
        }
      }
    });

    return {
        studentDetails,
        teacherDetails
    };
};

Then, I refactored it to -
const createUsersInfo = obj => {
  const studentDetails = [];
  const teacherDetails = [];
  obj.forEach(x => {
    const type = x.type;
    if ( type && x.group !== 'admin' ) {
      if ( type === 'teacher' ) {
        teacherDetails.push(x);
      }
      if ( type === 'student' ) {
        studentDetails.push(x);
      }
    }
  });

  return {
    studentDetails,
    teacherDetails
  };
};

Is this better as compared to my initial version or it can  further improved ?
Thanks.


texts:
I'm just a Clojure noob (started learning yesterday). Here is my helloworld program. It factorizes number into primes. Do you have any comments? How could I make this code cleaner and shorter? Maybe I can deduplicate some things?

(defn lazy-primes
  ([] (cons 2 (lazy-seq (lazy-primes 3  [ 2 ]))))
  ([current calculated-primes]
   (loop [ [first-prime & rest-primes] calculated-primes]
     (if (> (* first-prime first-prime) current)
       (cons current (lazy-seq (lazy-primes
                                (inc current)
                                (conj calculated-primes current))))
       (if (= 0 (mod current first-prime))
         (lazy-seq (lazy-primes (inc current) calculated-primes))
         (recur rest-primes))))))

(defn factorize
  ([num] (factorize num '(1) (lazy-primes)))
  ([num acc primes]
   (if (= num 1) acc
       (loop [ [head & rest] primes ]
         (if (= 0 (mod num head))
           (factorize (/ num head) (cons head acc) primes)
           (recur rest))))))


texts: Less insane interface design for a trigger component for T types?

texts:
Disclaimer: I just asked this on the regular SE, but was suggested to post it in here since it's kind of a code review.

I've recently been playing around with component frameworks, and I'm trying to create a basic trigger component. The component should be able to take one (or more) pair of values that can be compared against each other, triggering upon certain conditions.

The value pair should be of a generic type, I suggest an interface like IComparable. The TriggerComponent itself cannot be templated (i think?), as the component system must register it and would not be able to do so without supplying type information via angle brackets. Here's my current prototype version. It works, but some awkward issues that I'll explain below:

  /* interface IComparable.h */
  class IComparable
  {
  public:
    virtual ~IComparable() {}

    virtual bool lessOrEqual(const IComparable& other) const = 0;
  };

  /* Derived type container, intended for primitive values like int, float etc */
  template<class T>
  class NumberType : public IComparable
  {
  public:
    NumberType(const T& number) : m_number(number) {}
    bool lessOrEqual(const IComparable& other) const
    {
      NumberType& nt = (NumberType&)other;
      return m_number <= nt.m_number;
    }

    const T& m_number;
  };

  /* Component with threshold/trigger values made up by number types, but also objects of IComparable */
  class TriggerComponent : public artemis::Component
  {
  public:
    TriggerComponent(const IComparable& threshold, const IComparable& triggerValue)
      : m_thresholdValue(threshold), m_triggerValue(triggerValue) {}

    const IComparable& threshold() const { return m_thresholdValue; }
    const IComparable& triggerValue() const { return m_triggerValue; }

    void execute() const { qDebug() << "execute!"; }

  private:
    const IComparable& m_thresholdValue;
    const IComparable& m_triggerValue;
  };

The triggerValue parameter should be a reference as it is supposed to be monitored and checked against the threshold. Threshold should ideally be a copy, and not refer to anything. I would ideally like to have IComparable/NumberType as structs as it would make it easy to reference or copy as needed, but I don't think it is possible due to the pure interface.. As they're both reference values, I'm in a lot of cases forced to allocate heap memory, which i'd like to avoid for simple types.

If I had a cube in a 3D world with an ongoing scaling reduction, here's how I'd use the TriggerComponent to detect when it's X component reaches 1.0f:

    Entity* cubeEntity = /* omitted */
    ScaleComponent* scaleComp = /* omitted*/
    float* cubeScaleMinThreshold = new float(1.0f);
    NumberType<float>* threshold = new NumberType<float>(*cubeScaleMinThreshold);
    NumberType<float>* currScale = new NumberType<float>(scaleComp->getx());
    cubeEntity .addComponent(new TriggerComponent(*threshold, *currScale));

I need the flexibility to create components on the fly, and I'd like to pass stack-created values as copies rather than passing raw pointer refs, but I'm not exactly sure how I can make it work in my current interface setup. I don't see how I can make generic comparisons between values (of same type) without one, but that seems to also require members to not be abstract value types.

I would be very appreciative on possible changes to make the design less insane. Maybe I'm just overlooking an obvious simple approach?

PS. I know raw pointers set up like I just did, leak like a 2 year old. It's to show why the design is terrible! :)


texts: Moving method from derived class to base

texts:
I've some classes (Derived1, Derived2, etc.) derived from class Base. All of derived classes have a following methods (reduced sample):

void Derived1::handleTimer(const StatusType &st) {
  if (!st.isOk()) {
    m_timer->WakeUpPeriod(10); // wait for 10 seconds;
    m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
    return;
  }

  try {
    ... // there is some specific for Derived's code
    m_timer->WakeUpPeriod(10 * 60); // wait for 10 minutes;
    m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
  }
  catch(...) {
    m_timer->WakeUpPeriod(10); // wait for 10 second;
    m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
  }
}

void Derived1::start() {
  m_timer->WakeUpPeriod(1); // wait for 1 second;
  m_timer->SetHandler(boost::bind(Derived1::handleTimer, this, _1));
}

I'd like to move these methods to Base. However, my trying looks pretty ugly. Is there more appropriate way?
There is my current solution.

class Base {
public:
  typedef boost::function <void (const StatusType&)> HandlerType;
  Base(HandlerType handler) : m_hadler(handler) {}
  void start() {
    m_timer->WakeUpPeriod(1); // wait for 1 second;
    m_timer->SetHandler(m_handler);
  }
protected:
  virtual void doSomeSpecific() = 0;

  void handleTimer(const StatusType &st) {
    if (!st.isOk()) {
      m_timer->WakeUpPeriod(10); // wait for 10 seconds;
      m_timer->SetHandler(m_handler);
      return;
    }

    try {
      doSomeSpecific();
      m_timer->WakeUpPeriod(10 * 60); // wait for 10 minutes;
      m_timer->SetHandler(m_handler);
    }
    catch(...) {
      m_timer->WakeUpPeriod(10); // wait for 10 second;
      m_timer->SetHandler(m_handler);
    }
  }

private:
  HandlerType m_handler;

  ... // other data and function members
};

Now Derived classes

void Derived1::doSomeSpecific() { ... }

Derived1::Derived1() : Base(boost::bind(Derived1::handleTimer, this, _1) {}

void Derived1::handleTimer(const StatusType &st) { Base::handleTimer(st); }


texts:
I know my way around jQuery and JavaScript a little bit but as for optimising, I'm a bit weak but willing to learn new stuff.

I'm currently loading videos onto our site from Vimeo when a user clicks the appropriate image area.  This is working fine, but I feel it's not an entirely performant way to go about doing it.

Does anyone see any issues with the code I've written below which could be done better?

var videoData = [
{
    'player_id':'video1',
    'videoURL':'<?php the_field('two_vimeo_video_url'); ?>',
    'width':'1000',
},
{
    'player_id':'video2',
    'videoURL':'<?php the_field('six_vimeo_video_url'); ?>',
    'width':'1000',
}];

function loadVideo(target, videoid) {
    $.getJSON('http://www.vimeo.com/api/oembed.json?url=' + encodeURIComponent(videoData[videoid]['videoURL']) + '&api=1&player_id='+ videoData[videoid]['player_id'] +'&width='+videoData[videoid]['width']+'&byline=0&color=ffffff&title=0'+'&callback=?', function(data){

        $(target).find('.video-container').html(data.html); // puts an iframe embed from vimeo's json

        $(target).closest('iframe').load(function(){

            $f(player).addEvent('ready', function(id){
                var vimeoVideo = $f(videoid);
            });
        });
    });
}

$(function(){
    // Create array to store values
    var vimeoArray = [];
    var videoContainer = $('.video-container');

    // loop through st
    $(videoContainer).each(function(index, value) {

        // get the image with the data attr on each loop
        var dataAttr = $(this).attr('data-video');

        // if dataAttr is not false
        if ( dataAttr !== undefined) {

            // push data attribute value into array
            vimeoArray.push(dataAttr);

            // Store last element of array on iteration
            var videoid = vimeoArray[vimeoArray.length-1];

            // attach click handler to the parent of the scoped element
            $(this).parent().click(function(){

                // load the video
                loadVideo(this, videoid);
                $(this).unbind('click');
                $(this).find('.b-studio__image').hide();

            });
        }
    });
});

I've created a jsfiddle as well with all the code and some dummy data. Any suggestions would be really helpful.


texts: Fastest way of removing a substring from a string

texts:
Taking a break from my C++ series, I recently reviewed the code in this question.  I ended up writing my own separate derivation of the function so that I could remove all of the substrings from a certain string.

#include <stdio.h>
#include <string.h>
#include <time.h>

#define NUM_CYCLES 10000000

void rmSubstr(char *str, const char *toRemove)
{
    size_t length = strlen(toRemove);
    while((str = strstr(str, toRemove)))
    {
        memmove(str, str + length, 1 + strlen(str + length));
    }
}

clock_t runTest(void (*fn)(char*, const char*), char *str, char *substr)
{
    clock_t start = clock();
    for (int i = 0; i < NUM_CYCLES; ++i)
    {
        fn(str, substr);
    }
    return clock() - start;
}

int main(void)
{
    char* str1 = strdup("test this string out");
    char* str2 = strdup("test this ...........slightly............ longer thing which contains a sub string out");
    char* str3 = strdup("string");
    char* str4 = strdup("this string is not a string test");

    printf("Function ran in %lu clock cycles\nProduced output: %s\n\n", runTest(rmSubstr, str1, " string"), str1);
    printf("Function ran in %lu clock cycles\nProduced output: %s\n\n", runTest(rmSubstr, str2, " string"), str2);
    printf("Function ran in %lu clock cycles\nProduced output: %s\n\n", runTest(rmSubstr, str3, " string"), str3);
    printf("Function ran in %lu clock cycles\nProduced output: %s\n\n", runTest(rmSubstr, str4, " string"), str4);
}

Generates on my MacBook Pro (Intel Core i5 2.4 GHz with 2 cores, 4 GB RAM, running Mac OS X 10.10 beta 4):

Function ran in 319220 clock cycles
Produced output: test this out

Function ran in 1293377 clock cycles
Produced output: test this ...........slightly............ longer thing which contains a sub out

Function ran in 198460 clock cycles
Produced output: string

Function ran in 448832 clock cycles
Produced output: this is not a test

Program ended with exit code: 0

The only thing I would like to be reviewed in this question is the speed of the rmSubstr function.  Other comments are welcome, but alone will not be accepted.  Also, please include the output of the program with your answer so that I can get a feeling for how much my function was improved.


texts: Two Knockout computed dependent on each other

texts:
I have 3 fields:

Net Price (ex. tax)
tax amount
Total price (price ex. vat + tax amount)

The NetPrice and the Total are writable (i.e. you can change either of them and the other 2 values must be auto-calculated).

The way I've done it is using 3 observable and 2 computed knockout objects but I thought perhaps someone who knows Knockout a lot better could suggest a more efficient way to achieve this.

Working jsFiddle

HTML:

Net Price:
<input type="textbox" data-bind="value: NetPriceCalc" />

Tax Amount:

Total:
<input type="textbox" data-bind="value: TotalCalc" />

Script:

var viewModel = {
    NetPrice: ko.observable(100),
    TaxAmt: ko.observable(20),
    Total: ko.observable(120),
    TaxRate: 0.2
};

viewModel.updateTaxAmt = function (useNetPrice) {
    if (useNetPrice) {
        return this.TaxAmt(this.NetPrice() * this.TaxRate);
    } else {
        var total = Number(this.Total());
        var taxAmt = total - total / (1 + this.TaxRate);
        return this.TaxAmt(taxAmt);
    }
};
viewModel.updateNetPrice = function () {
    this.NetPrice(Number(this.Total()) - Number(this.TaxAmt()));
};
viewModel.updateTotal = function () {
    this.Total(Number(this.NetPrice()) + Number(this.TaxAmt()));
};

viewModel.NetPriceCalc = ko.computed({
    read: function () {
        console.log("NetPriceCalc read");
        return viewModel.NetPrice();
    },
    write: function (value) {
        console.log("NetPriceCalc write");
        viewModel.NetPrice(value);
        viewModel.updateTaxAmt(true);
        return viewModel.updateTotal();
    }
});
viewModel.TotalCalc = ko.computed({
    read: function () {
        console.log("TotalCalc read");
        return viewModel.Total();
    },
    write: function (value) {
        console.log("TotalCalc write");
        viewModel.Total(value);
        viewModel.updateTaxAmt(false);
        return viewModel.updateNetPrice();
    }
});

ko.applyBindings(viewModel);


texts:
I need to intersect lots of arrays with each other. Those arrays are like:
$a = array(4 => true, 10 => true, 18 => true...);
$b = array(6 => true, 10 => true, 73 => true...);
$c = array(106 => true, 293 => true, 297 => true...);

In PHP there is a function array_intersect_key, which intersects keys; it works fine but it's not very efficient. There is also another function array_intersect, which intersects values, and is much slower than array_intersect_key because it's O (n^2) instead of O (n) (array_intersect_key).
The problem with array_intersect_key is that it does lots of pre computation before executing the intersection, like ordering the arrays, verifying data types... at every call but I don't need that because my arrays are already ordered and contain only numbers. So I came up with this function:
function array_intersect_key_custom($a,$b) {

    $intersection = array();

    foreach ($a as $chave1 => $valor1) {

        if (isset($b[$chave1])) {

            $intersection [$chave1] = true;

        }

    }

    return $intersection;

}

This function runs a little faster than any other alternative I came up, but it's still too slow. Is there any code optimization, mathematical operation, matrix operation... that I can do in order to make this code run faster?


texts: Filling an array with the same data at a regular interval without a for loop

texts:
I have some code which generates the coordinates of a cylindrically-symmetric surface, with coordinates given as \$(r, \theta, \phi)\$.  At the moment, I generate the coordinates of one \$\phi\$ slice, and store that in a \$2 \times N\$ array (for \$N\$ bins), and then in a for loop I copy this array for each value of \$\phi\$ from \$0\$ to \$2\pi\$:

import numpy as np

# this is the number of bins that my surface is chopped into
numbins = 50

# these are the values for r
r_vals = np.linspace(0.0001, 50, numbins, endpoint = True)

# these are the values for theta
theta_vals = np.linspace(0, np.pi / 2, numbins, endpoint = True)

# I combine the r and theta values into a 2xnumbins array for one "slice" of phi
phi_slice = np.vstack([r_vals,theta_vals]).T

# this is the array which will store all of the coordinates of the surface
surface = np.zeros((numbins**2,3))
lower_bound = 0
upper_bound = numbins

# this is the size of the bin for phi
dphi = (2 * np.pi) / numbins

# this is the for loop I'd like to eliminate.
# For every value of phi, it puts a copy of the phi_slice array into
# the surface array, so that the surface is cylindrical about phi.
for phi in np.linspace(0, (2 * np.pi) - dphi, numbins):
    surface[lower_bound:upper_bound, :2] = phi_slice
    surface[lower_bound:upper_bound,2] = phi
    lower_bound += numbins
    upper_bound += numbins

I'm calling this routine in a numerical integration of 1e6 or 1e7 steps, and while numbins is 50 in the example above, in practice it'll be in the thousands.  This for loop is a choking point, and I'd really like to eliminate it to speed things up.  Is there a good NumPythonic way to do the same thing as this for loop?


texts:
I tried to write a function bin_add() in C to add two positive binary numbers represented as zero terminated strings:

#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX(x, y) ((x) > (y) ? (x) : (y))

size_t gpp(char const *s)
{
    char *n = strchr(s, '.');
    return n  ? (size_t)(n - s + 1) : 0;
}

char* bin_add(char const *a, char const *b)
{
    char const *inp[] = { a, b };
    size_t ll[] = { strlen(a), strlen(b) };
    size_t pp[] = { gpp(a), gpp(b) };
    size_t OO[2], off[2];

    for (size_t i = 0; i < 2; ++i) {
        OO[i] = pp[i] ? pp[i] - 1 : ll[i];
        pp[i] = pp[i] ? ll[i] - pp[i] : 0;}

    for (size_t i = 0; i < 2; ++i)
        off[i] = OO[i] < OO[!i] ? OO[!i] - OO[i] : 0;

    size_t ML = MAX(OO[0], OO[1]) + MAX(pp[0], pp[1]) + (!!pp[0] || !!pp[1]);
    char *Ol = calloc(ML + 2, 1);
    if(!Ol) return Ol;

    char ops[2];
    int xc = 0;
    size_t lO = ML;
    unsigned cc[2] = { 0 };
    for (size_t i = ML; i; --i) {
        bool pt = false;
        for (size_t l = 0; l < 2; ++l) {
            ops[l] = i <= ll[l] + off[l] && i - off[l] - 1
                       <  ll[l] ? inp[l][i - off[l] - 1] : '0';
            if (ops[l] == '.') {
                if (cc[l]) {
                    free(Ol);
                    return NULL;
                }
                pt = true;
                ++cc[l];
            }
            ops[l] -= '0';
        }
        if (pt) {
            Ol[i] = '.';
            continue;
        }
        if ((Ol[i] = ops[0] + ops[1] + xc) > 1) {
            Ol[i] = 0;
            xc = 1;
        }
        else xc = 0;
        lO = (Ol[i] += '0') == '1' ? i : lO;
    }
    if((Ol[0] = '0' + xc) == '1') return Ol;
        for (size_t i = 0; i <= ML - lO + 1; ++i)
            Ol[i] = Ol[lO + i];

    return Ol;
}

int main(void)
{
    char a[81], b[81];

    while (scanf(" %80[0.1] %80[0.1]", a, b) & 1 << 1) {
        char *c = bin_add(a, b);
        if (!c && errno == ENOMEM) {
            fputs("Not enough memory :(\n\n", stderr);
            return EXIT_FAILURE;
        }
        else if (!c) {
            fputs("Input error :(\n\n", stderr);
            goto clear;
        }

        char* O[] = { a, b, c };
        size_t lO[3], Ol = 0;
        for (size_t i = 0; i < 3; ++i) {
            lO[i] = gpp(O[i]);
            lO[i] = lO[i] ? lO[i] : strlen(i[O]) + 1;
            Ol = lO[i] > Ol ? lO[i] : Ol;
        }

        putchar('\n');
        for (size_t i = 0; i < 3; ++i) {
            for (size_t l = 0; l < Ol - lO[i]; ++l, putchar(' '));
        puts(O[i]);
        }
        putchar('\n');

        free(c);
        clear :{ int c; while ((c = getchar()) != '\n' && c != EOF); }
    }
}

The main() is just included to provide input to the function and pretty-print its results. Every C99 compliant compiler should be able to compile above code.

Do you see any flaws in my code and anything that could be improved?


texts: Socket.io wrapper for an app with ReactJS components

texts:
I am upgrading a traditional jQuery based app by converting a few parts of it into ReactJs components and use Socket.io for the data transfer medium.

There are a few React components spread across the page. The React components will receive updates from the socket connection in their componentDidMount method.

For example:

componentDidMount: function(){
    socket.on('connect', function(data){....});
    socket.on('anotherEvent', function(data){....})
}

Now, the thing is that the React components will be scattered across the page and will not be under a single app structure, and they will be subscribing to the same socket events to stay in sync.

For this, I wrote the below Socket.io wrapper, this way multiple subscriptions for the same events can be avoided but all the interested React components can be notified on an event update.

window.socketEvents = (function(){
    var socket = io.connect("http://localhost:3000"),
        events = {},                    //events structure = {'event_name':subscribers:[callback functions], isSubscribed:true}
        callOnConnect = [];

    var _register = function(event, callback){
        events[event] = events[event] || {};
        events[event].subscribers = events[event].subscribers || [];
        events[event].subscribers.push(callback);
    };

    var _subscribe = function(event){
        console.log('Subscribingto: ', event);
        socket.on(event, function(data){    // notifiy the subscribers of this event by firing their callbacks.
            console.log('received evt: ', data);
            for(var cb=0;cb<events[event].subscribers.length;cb++){
                events[event].subscribers[cb](data);
            };
        });
        events[event].isSubscribed = true;
    };

    var _emit = function(event, data, onConnect){
        console.log('_emit called for: ', event);
        socket.emit(event, data);
        if(onConnect){
            callOnConnect.push(function(){
                socket.emit(event, data);
            });
        }
    };

    var _listen = function(event, callback){
        _register(event, callback);
        if(!events[event].isSubscribed){
            _subscribe(event);
        };
    };

    setTimeout(function(){  // register a little late to avoid multiple callbacks.
        socket.on('connect', function(){
            console.log('connect fired');
            for(var i=0;i<callOnConnect.length;i++){
                callOnConnect[i]();
            }
        });
    },1000);

    return {
        listen: _listen,
        emit: _emit
    }

})();

React example with the new wrapper:

In ReactClassOne:

componentDidMount: function(){
    socketEvents.emit('join_service', {name:'Some name'}, true); // the third boolean param states that should the event be emitted if the socket disconnects and then reconnects.
    socketEvents.listen('anotherEvent', function(data){...})
}

In ReactClassTwo:

componentDidMount: function(){
    socketEvents.emit('join_service', {name:'Some name'}, true);
    socketEvents.listen('anotherEvent', function(data){...})
}

The code is currently working fine during the preliminary development but I am worried about the timeout in the socketEvents. So, I would like this to be reviewed.


texts:
I am looking for assistance in optimizing a partition method I wrote for a class. It does its job correctly, but I only received half points on it, so I was wondering if there was a way to make it more efficient?

private int runPartition(int lowIndex, int highIndex)
  {
     //Sets up pivot index and values
     int pivotIndex = lowIndex;
     int pivotValue = localArray[pivotIndex];

     //Inner counter value
     int counterOne = highIndex + 1;

     //Loops through array from top down
     for (int counterTwo = highIndex; counterTwo >= lowIndex; counterTwo--)
        {
           //If element is bigger than pivot, move to end
           if (localArray[counterTwo] > pivotValue)
              {
                 //Decrements inner counter and swaps values
                 counterOne--;
                 swapValuesAtIndex(counterTwo, counterOne);
              }
        }

     //At end, swap pivot value with value BEFORE larger elements
     counterOne--;
     swapValuesAtIndex(counterOne, pivotIndex);

     //Sets new pivot index and returns
     pivotIndex = counterOne;
     return pivotIndex;
  }


texts:
I want to know if there's a better way of doing a select on dropdown and selecting the items. I bound ng-click to every anchor and assign a value on click, but it just doesn't feel like a clean way to do it.

Also, is there a way to use ng-repeat to create the dropdown list dynamically? The problem I get if I use the ng-repeat is the separator. Is there a cleaner way to use ng-repeat or another way?

plunker link

JavaScript

angular.module('demo', ['ui.bootstrap']);

function SortCtrl($scope) {
    $scope.sortBy = [
        {
            "name": "Name",
            "sortName": "name",
            "type":"string"
        },
        {
            "name": "Date modified",
            "sortName": "dateModified",
            "type":"date"
        },
        {
            "name": "Date created",
            "sortName": "dateCreated",
            "type":"date"
        },
        {
            "name": "Date last sent",
            "sortName": "dateLastSent",
            "type":"date"
        },
        {
            "name": "separator"
        },
        {
            "name": "Subscribers",
            "sortName": "subscribers",
            "type":"number"
        },
        {
            "name": "Opens",
            "sortName": "opens",
            "type":"number"
        },
        {
            "name": "Clicks",
            "sortName": "clicks",
            "type":"number"
        }
    ];

    $scope.order = true;
    $scope.orderBy = $scope.sortBy[0];

    $scope.$watch('orderBy', function() {
        $scope.sortItems();
    });
    $scope.sortItems = function (){
    //perform sort
    if($scope.order){
            $scope.order = false;
          //reverse order here
        }else{
            $scope.order = true;
        }
  };

}

HTML

Sort by                                 {{orderBy.name}}

      Name

      Date modified

      Date created

      Date last send

      Subscribers

      Opens

      Clicks


texts: Calculate total miles per gallon and average per trip

texts:
Assignment: Develop a Java application that will input the number of miles driven and gallons used (both as integers) for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should use floating point results.

See my implementation below.
YES the class name is weird but I didn't feel like changing it.
Does the code satisfy the assignment requirements?
Have I missed the target completely, and if so how far off was I?

 import java.util.Scanner;

    public class MagicNumber
    {
        public static void main(String[] args)
        {
            float AvgMPG = 0;
            int MilesDriven = 0;
            int totalTrips = 0;
            int GallonsUsed = 0;
            int totalMilesPerGallon = 0;
            int MilesPerGallon = 0;

            Scanner input = new Scanner(System.in);
            System.out.println("Enter Miles Driven or -1 to quit:  ");
            MilesDriven = input.nextInt();

            System.out.println("Enter Gallons used to fill tank or -1 to quit:  ");
            GallonsUsed = input.nextInt();

            while ( MilesDriven != -1)
            {
                MilesPerGallon = MilesDriven / GallonsUsed;
                System.out.println("Miles Per Gallon for this trip:  "           +MilesPerGallon);

                totalMilesPerGallon = MilesPerGallon + totalMilesPerGallon;

                totalTrips = totalTrips + 1;

                System.out.println("Enter Miles Driven or -1 to quit:  ");
                MilesDriven = input.nextInt();

                System.out.println("Enter Gallons used to fill tank or -1 to quit:  ");
                GallonsUsed = input.nextInt();
            }
        if (totalTrips != 0)
        {
          System.out.println("Number of trips taken:  "+ totalTrips);

          AvgMPG = (float) totalMilesPerGallon / totalTrips;

          System.out.println("Total Miles Per Gallon for all trips is :"             +totalMilesPerGallon);
          System.out.println("Average Miles Per Gallon Per Trip is :"  +AvgMPG);

                }
                else
                System.out.println("No data entered");

        }
    }


texts:
I would like to hear some feedback about style on my program, and which one is better "do while" or "while loop" to run my program.

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

#define Tequila 20
#define Whiskey 25

int main()
{

    int choice = 0;
    int bottle1= 0;
    int bottle2= 0;
    int final_total= 0;
    int total1 =0;
    int total2 =0;

    do{
        printf("\tMain Menu MK liquor Store\n");
        printf(" \tEnter your choice: \n");
        printf("\t 1-  Buy Tequila Jose Cuervo\n");
        printf("\t 2-  Buy Whiskey Jack Daniels\n");
        printf("\t 3-  Quit\n");

        scanf("%d", &choice);

        switch(choice)
        {
            case 1:
                printf("how many bottles of Tequila would you like\n");
                scanf("%d", &bottle1);
                printf("so far you got %d bottles in your basket \n", bottle1);

                break;
            case 2:
                printf("how many bottles of Whiskey would you like\n");
                scanf("%d", &bottle2);
                printf("so far you got %d bottles in your basket\n", bottle2);

                break;
            case 3:
                total1=bottle1 * Tequila;
                total2= bottle2 * Whiskey;
                final_total = total1+total2;
                printf("You obtained %d bottles of Tequila and %d of Whisky\n", bottle1,bottle2);
                printf("Your total  is %d dollars\n",final_total);

                break;
            default:

                printf("ERROR INVALID OPTION.\n\n");

                break;

        }

    }while (choice != 3);
        return 0;

    }


texts: Can I return an object on which a function is applied?

texts:
I'm wondering if it is possible or if it is correct to proceed in such a way:

var initiate_shop = function(shop_navigation, shop_container_id, items_per_page) {
    return $(shop_navigation).jPages({
        containerID     : shop_container_id,
        first           : false,
        previous        : false,
        next            : false,
        last            : false,
        midRange        : 15,
        perPage         : items_per_page,
        animation       : "fadeInUp",
        links           : "blank",
        keyBrowse       : true,
        scrollBrowse    : false,
        callback        : function(pages){
            current_page = pages.current;
            total_pages = pages.count;
        }
    });
};

If the above isn't correct what could be a better way to write it?


texts: Check before proceeding if the task in BackgroundWorker has completed

texts:
I have a Login Form (which has a label that will show status of background process, username and password text boxes, Login and Cancel buttons) along with that I have a background worker to do some time taking task (in the meanwhile when Login Form loads and user provide details in text boxes).

Background task keep running while the user will be providing username and password on Login Form. As soon as the user hits the Login button I want to check the status if the background process has completed successfully and then only it should proceed (launch the MainForm)

Otherwise should pop-up error. Following is what I did to achieve but the 'while()' strategy doesn't look elegant. Is there any more appropriate way?

  public partial class LoginForm : Form
    {
        private static BackgroundWorker bw = new BackgroundWorker();
        private static ManualResetEvent mre = new ManualResetEvent(false);

        enum status
        {
            Blank,
            Success,
            Error
        };

        public LoginForm()
        {
            InterimProceedings();
            InitializeComponent();
        }

        private void InterimProceedings()
        {

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

            if (!bw.IsBusy)
            {
                bw.RunWorkerAsync();
            }
            else
            {
                throw new InvalidOperationException("BackgroundWorker is busy");
            }
        }

        private static void bw_DoWork(object sender, DoWorkEventArgs e)
        {
          //  Time taking task
              mre.Set();
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!(e.Error == null))
            {
                this.lbl_status.Text = "Cannot proceed, Error occured";
                appStatus = status.Error;
            }
            else
            {
                this.lbl_status.Text = "Good to go...";
                appStatus = status.Success;
            }
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            mre.WaitOne();

            if(appStatus == status.Success)
            {
                // Proceed with intended work
            }

            else
            {
                // Pop-up error occurred
            }
        }
}


texts:
I'm trying to implement the enumerate built-in using iterators. So far it works but for unordered objects, such as sets or dictionaries, I'm not sure if this implementation is considered valid, although it works.

class myEnumerate:
    def __init__(self, iterable):
        self.iterable = list(iterable)
        self.index = -1

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        if self.index >= len(self.iterable):
            raise StopIteration
        return self.index, self.iterable.__getitem__(self.index)

if __name__ == '__main__':
    for (i, ch) in myEnumerate("Python"):
        print(i, ch)

    # Output:
    # 0 P
    # 1 y
    # 2 t
    # 3 h
    # 4 o
    # 5 n

    for (i, ch) in myEnumerate(set(["a", "b", "c"])):
        print(i, ch)

    # Output: (order might differ)
    # 0 a
    # 1 b
    # 2 c

What do you guys think?