texts: Testing a template function in GoLang using mocking - making it DRY & easy to follow

texts:
TL;DR
I'm wondering how to organise test functions using mocks for GoLang drier & easier to follow.
Function
I have a template function that is very similar to ACF's getField:

It take's in a string (field name) & the post ID.
It checks if the ID exists and the obtains the post by ID (the f.store.Posts belongs to the fields struct)
If the post doesn't exist or if the fields could not be unmarshalled it will return an empty string.

func (f *fields) getField(field string, id ...int) interface{} {

    fields := f.fields
    if len(id) > 0 {
        post, err := f.store.Posts.GetById(id[0])
        if err != nil {
            return ""
        }
        var m map[string]interface{}
        if err := json.Unmarshal(*post.Fields, &m); err != nil {
            return ""
        }
        fields = m
    }

    val, found := fields[field]
    if !found {
        return ""
    }

    return val
}

Testing
From the function, presumably I need to test if, The post exists, the json could be unmarshalle or if the field exists.
I have started to use github.com/golang/mock/gomock but am finding it confusing!
In each of the test functions below I create a new controller and mockPost, add assigning the fields Post to it.

func TestGetField(t *testing.T) {
    f, err := helper(`{"text": "content"}`)
    if err != nil {
        t.Error(err)
    }

    if field := f.getField("text"); field == "" {
        t.Errorf(test.Format("content", nil))
    }

    if field := f.getField("wrongval"); field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := []byte(`{"posttext": "postcontent"}`)
    mockPost := domain.Post{
        Id:     2,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    f.store.Posts = posts
    posts.EXPECT().GetById(2).Return(mockPost, nil)

    field := f.getField("posttext", 2)
    if field != "postcontent" {
        t.Errorf(test.Format("postcontent", field))
    }
}

func TestGetField_No_Post(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    posts := mocks.NewMockPostsRepository(controller)
    var mockErr = fmt.Errorf("No post")
    posts.EXPECT().GetById(gomock.Any()).Return(domain.Post{}, mockErr)
    f.store.Posts = posts

    field := f.getField("text", 1)

    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

func TestGetField_Invalid_JSON(t *testing.T) {
    f, err := helper("{}")
    if err != nil {
        t.Error(err)
    }

    controller := gomock.NewController(t)
    defer controller.Finish()

    data := []byte(`"text "content"`)
    mockPost := domain.Post{
        Id:     1,
        Fields: (*json.RawMessage)(&data),
    }

    posts := mocks.NewMockPostsRepository(controller)
    posts.EXPECT().GetById(1).Return(mockPost, nil)
    f.store.Posts = posts

    field := f.getField("text", 1)
    if field != "" {
        t.Errorf(test.Format("", field))
    }
}

Feedback

Without using the mock package, how would you approach this?
Are there any areas for improvement with the current codebase?
Is there away to consolidate any of the testing methods? It seems quite long winded for such a short function


texts: How to re-factor dynamic menu code to OOP in a MVC framework?

texts:
I have a MVC framework, and I am struggling with the following dynamic menu code.

A menu is pretty much HTML, so technically it should reside in the View, but the dynamic part is driven by PHP and a config class that holds all the menu items.

Where would I place this class? (model layer, view, library, or helper folder)
How would I re-factor this to be OOP?
How would I deploy this from my View?

Note: It should all be in regards to MVC principles.

class Menu {
    public static function get() {
        $URI = $_SERVER['REQUEST_URI'];

        $user = new User();

        if (!$user->isLoggedIn()) {
            $navArr = Config::get('navigation');

            $navigation = '
' . PHP_EOL;

            foreach ($navArr as $name => $path) {
                $navigation .= '
' . $name . '
' . PHP_EOL;
            }

            $navigation .= '
' . PHP_EOL . PHP_EOL;
        } else {
            //logged off navigation
        }

        return $navigation;
    }
}


texts:
I've been learning Haskell recently and I decided I needed to work on a (somewhat) realistic problem.

What I'm most interested in getting feedback on is how well I've used the tools in Haskell to accomplish the goal of converting Roman numerals to Arabic values. I suspect that my approach is more verbose than it needs to be, so thoughts on how I could remove unneeded code would be quite welcome.

Lastly, thoughts on how to address Haskell bad practices or similar errors would be appreciated.

-- file: roman.hs
import Data.Char

-- Application startup.
main :: IO ()
main = do
    putStrLn "Enter a Roman numeral. The numerical value will be returned."
    putStrLn "For example MMI -> 2001."
    putStrLn "Enter 'finis' to exit."
    process
    putStrLn "vale! :-)"

-- Main loop.
process :: IO ()
process = do
    putStrLn "Numeral: "
    line <- getLine
    if line == "finis"
        then return ()
        else do
            let nums = readNumerals(line)
                in if errorNum `elem` nums
                    then putStrLn (line ++ "is not a valid Roman numeral.")
                    else putStrLn ("   The Roman numeral " ++ line ++ " is equal to " ++ show(getValue(nums)))
            process

data Numeral = Numeral {
    numeralValue :: Int,
    numeralSymbol :: Char,
    subRule :: [Char]}
    deriving (Show, Eq)

-- This is the Numeral error type. used to check if the input was valid.
errorNum = Numeral 0 'E' []

-- Turn a string into a list of numerals.
readNumerals :: String -> [Numeral]
readNumerals (x:xs) = readNumeral (toUpper(x)) : [] ++ readNumerals xs -- First cons the Char to an empty list, then recur.
readNumerals "" = []

-- Parse each char into the corresponding numeral.
readNumeral :: Char -> Numeral
readNumeral 'I' = Numeral 1 'I' ['V', 'X']
readNumeral 'V' = Numeral 5 'V' []
readNumeral 'X' = Numeral 10 'X' ['L', 'C']
readNumeral 'L' = Numeral 50 'L' []
readNumeral 'C' = Numeral 100 'C' ['D', 'M']
readNumeral 'D' = Numeral 500 'D' []
readNumeral 'M' = Numeral 1000 'M' []
readNumeral _ = errorNum

-- Turn a list of Roman numerals into their corresponding Arabic number.
getValue :: [Numeral] -> Int
getValue [] = 0
getValue (x:xs) =
                if subRuler (subRule x) xs
                then negate (numeralValue x) + getValue xs
                else numeralValue x + getValue xs
                -- if x has a non-empty subRule and the next x is in the list, then flip the sign for x

-- Take the subRule from x and xs, if x of xs is in subRule, return true, otherwise false.
-- What this really means is see if the next element in the list of Numerals is one of the elements in subRule.
subRuler :: [Char] -> [Numeral] -> Bool
subRuler [] _ = False
subRuler _ [] = False
subRuler a b = numeralSymbol (head b) `elem` a

{-
Subtractive Rules, from Wikipedia
I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)
-}


texts:
I'm working on a program to program the bisection method:
https://www.calculushowto.com/bisection-method/
I know there's questions similar to this one but I want to see if my own one works.
double func(double x) {
    return x * x - 3 * x - 1;
}

double bisect(double (*f)(double), double a, double b, double e) {
    double mid = (a + b) / 2;
    while (abs(mid) > e) {
        if (f(mid) < 0) {
            mid = a;
        } else {
            mid = b;
        }
    }

    return mid;
}

func() is the function I'm using to test the bisection method. In the other function, a is the left point, b is the right point and e is the error bound.
Any mistakes that I didn't catch?


texts:
During a discussion in a development chat, a user suggested to another (in the context of C# originally),

UserA: Challenge: Create an implementation of RPS, and then show how it can be extended to include an unlockable option Bomb (blows up paper and rock, but scissors cuts the fuse - basically Paper+; AI that has Bomb uses it instead of Paper) with a minimum of fuss.
UserA: Bonus: Make it so the game can be thus modified changing only data (constants, serialized fields, whatever).
UserB: how would one unlock the Bomb?
UserA: Basically "elsewhere" however you want. Could be an external property, could be an Interface or Serialized Field or parameter or whatever.

and since I'm interested in learning F# I decided to pick up the exercise. Along with that, I also tried to clean up the code for I/O handling, such that I could potentially swap a "player vs computer" game to "player vs player" or even "computer vs computer". I have published the script in GitHub, but please find it pasted below too for convenience:
open System

type MatchResult =
    | Won
    | Lost
    | Draw

type Element =
    | Rock
    | Paper
    | Scissors
    | Bomb

type Player = {
    Pick: Element[] -> Element;
    AnnounceResult: MatchResult -> unit;
}

let victoriesOf element =
    match element with
    | Rock -> [Scissors]
    | Paper -> [Rock]
    | Scissors -> [Paper; Bomb]
    | Bomb -> [Rock; Paper]

let (!) (result: MatchResult) =
    match result with
    | Won -> Lost
    | Lost -> Won
    | x -> x

let evaluate player rival =
    let winsOver a b =
        victoriesOf a
        |> List.contains b
    match (winsOver player rival, winsOver rival player) with
    | (true, false) -> Won
    | (false, true) -> Lost
    | _ -> Draw

let parse options move =
    let cleanup (input: string) = input.ToLowerInvariant().Trim()
    let compare =
        string
        >> cleanup
        >> (=) move
    Seq.tryFind compare options

let runRound (a: Player) (b: Player) options =
    let aChoice = a.Pick options
    let bChoice = b.Pick options
    let result = evaluate aChoice bChoice
    a.AnnounceResult result
    b.AnnounceResult !result

let player = {
    Pick = fun options ->
        printfn "Choose one of %s:" (String.Join(", ", options))
        match parse options (Console.ReadLine()) with
        | Some(x) -> x
        | None -> failwith "Unknown choice!";
    AnnounceResult = fun result ->
        match result with
        | Won -> printfn "You won!"
        | Lost -> printfn "You lost!"
        | Draw -> printfn "It's a draw!"
}

let computer =
    let rng = Random()
    {
        Pick = fun options ->
            let choice = Array.item (rng.Next(options.Length)) options
            printfn "Computer chose %A" choice
            choice;
        AnnounceResult = fun _ -> ();
    }

[<EntryPoint>]
let main argv =
    let validMoves = [|Rock; Paper; Scissors; Bomb|]

    while true do
        runRound player computer validMoves
    0

Since I'm new to ML-like languages, I'm looking for feedback on how I could better use the F# libraries, better model my state and data, and even how to make it more point-free. And if there are more idiomatic ways of writing any piece of code, please tell!


texts:
I'm working on a little django quiz taking app. Currently I'm making it's models. So far I've got Quiz, Question, Answer, and Response designed as follows:

from django.db import models
from npage.mixins import TranslatedModelMixin
from django.contrib.auth.models import User

# Create your models here.

class Quiz(models.Model):

    title = models.CharField(max_length=60,blank=False,)

    # show_feedback = models.BooleanField(blank=False,default=True,help_text="Correct answer is shown after question.",)

    class Meta:
        verbose_name = "Quiz"
        verbose_name_plural = "Quizzes"

    def __unicode__(self):
        return self.title

class Question(models.Model, TranslatedModelMixin):

    quiz = models.ManyToManyField(Quiz, blank=True, )

    content = models.CharField(max_length=1000, blank=False, help_text="Enter the question text that you want displayed",verbose_name='Question',)
    es_content = models.CharField(max_length=1000, blank=True, help_text="Enter the question text that you want displayed",verbose_name='Question',)

    type = models.CharField(max_length=8, choices=TYPES, default='radio')
    is_scoreable = models.BooleanField(default=True, help_text="Will the answer to this question be scored?")

    # idea
    # tags = models.CharField(max_length=1000, blank=False, help_text="Enter some text to help you find this question to add it to quizzes later on.",verbose_name='Question',)

    feedback = models.TextField(max_length=2000,blank=True,help_text="Explanation to be shown after the question has been answered.",verbose_name='Explanation',)
    es_feedback = models.TextField(max_length=2000,blank=True,help_text="Explanation to be shown after the question has been answered.",verbose_name='Explanation',)

    TYPES = (
        ('radio', 'radio'),
        ('checkbox', 'checkbox'),
        ('text', 'text'),
    )

    language_code = 'en'
    translated_fields = ['content', 'feedback']

    class Meta:
        verbose_name = "Question"
        verbose_name_plural = "Questions"
        #ordering = ['category']

    def __unicode__(self):
        return self.content

class Answer(models.Model, TranslatedModelMixin):
    question = models.ForeignKey(Question)

    content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that you want displayed",)
    es_content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that you want displayed",)

    correct = models.BooleanField(blank=False, default=False,help_text="Is this a correct answer?")

    language_code = 'en'
    translated_fields = ['content']

    def __unicode__(self):
        return self.content

class Response(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)

    # Could have either an FK to an answer OR some free response text.
    answer = models.ForeignKey(Answer)
    free_response = models.TextField(max_length=2000,blank=True)

    def __unicode__(self):
        if self.answer:
            return self.answer
        else:
            return free_response

I am especially concerned with the elegance of my Response model. The idea here is a question might be multiple choice (radio group or checkbox group) OR free response (text) so a response could either be a foreign key to an answer (which may or may not be correct) OR just some plain text (probably not both). Is this a good design? What can I do to improve my models


texts:
I have this code, which is working correctly, but I am sure that it allows SQL injection attacks.

@app.route('/private/')
def private():
    login = request.args.get('login', default=None, type=str)

    if login is None:
        return jsonify(data='Incorrect URL')

    try:
        c, conn = cursor_connection()
        c = conn.cursor()
        c.execute("SELECT uid "
                  "FROM logins_passwords "
                  "WHERE login='{}' "
                  "".format(login)
                  )

        id = c.fetchall()
        if not id:
            return jsonify(data='Incorrect login')

        c.execute("SELECT mc_address "
                  "FROM boxes_id "
                  "WHERE uid='{}' "
                  "".format(id[0][0])
                  )
        mc_address = c.fetchall()[0][0]

        c.close()
        conn.close()
    except Exception as e:
        return str(e)

    return render_template(
        "private.html",
        id=mc_address
    )

Access is available by URL request. How can I protect it against SQL injection? If I'm right, I think that changing access method to POST can solve all problems with security here?

As far as I understand, in cases of only POST requests allowed, the attacker will have no ability to inject SQL request through a URL. How can it be possible to execute SQL requests than?


texts: Most occuring digit in an array of numbers

texts:
I stumbled upon this exercise , and I am wondering if there is a more efficient way of writing this. It is written from high school level knowledge.

  Find the most occuring number of an array of numbers, with each number only counting one per number. For example in 2222 the 2 only counts ONCE. If you have 2 or more digits with the same amount of occurrences write out a random one. For example X[3] = {20; 21; 30}, either write out 0 or 2.

I could've used dynamic arrays, but that's not what I'm interested in here.

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

struct numbers
{
int number;
int howmany;
};

int main()
{
int X[20], Z[9], sizex, i, j, temp, howmany_found = 0, howmany_elem = 0, max = 0;
numbers Y[10];
bool found;

srand(time(NULL));

cout << "Array size: " ;
cin >> sizex;

for (i = 0; i < sizex; i++)
{
    cout << i + 1 << " element: " << " " ;
    cin >> X[i];
}

for (i = 0; i <= 9; i++)
{
    Y[i].number = i;
}

for (i = 0; i <= 9; i++)
{
    for (j = 0; j < sizex; j++)
    {
    found = false;
    temp = X[j];

    while (found != true && temp >= 1)
    {
        if (temp % 10 == i)
        {
            found = true;
            howmany_found++;

        }
        temp /= 10;
    }
    }
    Y[i].howmany = howmany_found;
    howmany_found = 0;
}

for (i = 0; i <= 9; i++)
{
    if (Y[i].howmany > max)
        max = Y[i].howmany;

    if (Y[i].howmany > 0)
    cout << "(" << Y[i].number << "," << Y[i].howmany << ")" ;
}

for (i = 0; i <=9; i++)
{
    if (Y[i].howmany == max)
    {
        Z[howmany_elem] = Y[i].number;
        howmany_elem++;
    }
}

if (howmany_elem > 1)
{
int RandIndex = rand() % howmany_elem ;
cout << endl;
cout << Z[RandIndex] ;
}
else
{
    cout << endl;
    cout << Z[0] ;
}

return 0;
}


texts:
The code generates all combinations of filename with underscore _:

def filename_generator(name, path=''):
    names = []

    for i in range(len(name)):
        p = '_'.join([x for x in name[i:]]) + path

        names.append(name[:i] + p)
        names += filename_generator(name[:i], p)

    return sorted(list(set(names)))

for e in filename_generator('longlonglonglonglonglongname'):
    print(e)

Example:

Input:

name

Output:

n_a_m_e
n_a_me
n_am_e
n_ame
na_m_e
na_me
nam_e
name

My code works well, but very slowly. How can I optimize the algorithm?


texts: Equivalent binary trees (structure & values)

texts:
I am following the Golang tour and I have been asked to build a couple of functions to manipulate binary trees.

My code runs as expected, but I would like to know if I could further improve my code. I'm looking for improvements regarding the algorithm and mainly the use of go routines. As the point of this exercise is to mainly work with go routines I would like to know if I could further add more go routines and to improve the concurrent design of this app.

You can try it in the go playground.

package main

import (
    "fmt"
    "code.google.com/p/go-tour/tree"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int){
    if(t == nil){
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right,ch)

}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    t1Slice := make([]int,1)
    t1ch := make(chan int)
    t2Slice := make([]int,1)
    t2ch := make(chan int)
    go func(){
        Walk(t1,t1ch)
        close(t1ch)
    }()
    go func(){
        Walk(t2,t2ch)
        close(t2ch)
    }()
    for j := range t1ch{
        h := append(t1Slice, j)
        t1Slice = h
    }
    for i:= range t2ch{
        o := append(t2Slice,i)
        t2Slice = o
    }
    for z := 0; z < len(t1Slice); z++ {
        if t1Slice[z] != t2Slice[z] {
            return false
        }
    }
    return true

}

func main() {
    ch := make(chan int, 5)
    go func() {
        Walk(tree.New(1),ch)
        close(ch)
    }()
    for j := range ch {
        fmt.Println(j)
    }

    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))

}


texts: Rock paper scissors in C# using more efficient choice comparison

texts:
I decided to create a rock, paper, scissors game in C#.
I realised early on that standard if-else evaluation in rock-paper-scissors would take up a lot of code. So I decided to use more efficient choice comparison in my game as you will see below.
Is this an efficient choice comparison? Or should I stick to 'if else'. How could I improve this code? Maybe I am not doing something right?
I am looking for any sort of feedback.
namespace RockPaperScissors
{
    public class Weapon
    {
        public string Name { get; set; }
        public string WeakTo { get; set; }
        public string StrongTo { get; set; }
    }
    public static class AvailableOptions
    {
        public static Weapon[] Options => new Weapon[]
        {
             new Weapon()
             {
                 Name = "Rock",
                 WeakTo = "Paper",
                 StrongTo = "Scissors"
             },
             new Weapon()
             {
                Name = "Paper",
                WeakTo = "Scissors",
                StrongTo = "Rock"
             },
             new Weapon()
             {
                Name = "Scissors",
                WeakTo = "Rock",
                StrongTo = "Paper"
             },
        };
    }
    public class RockPaperScissors
    {
        public string[] PossibleValues = new string[] { "Rock", "Paper", "Scissors" };
        public int Rounds { get; set; }
        public void StartGame()
        {
            int roundsCompleted = 0;

            while (Rounds > roundsCompleted)
            {
                Console.WriteLine("Rock");
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("Paper");
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("Scissors");
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("Shoot!");

                Ask();

                roundsCompleted++;
            }
        }
        private void Ask()
        {
            Console.WriteLine("----------------------------------");

            string input = Console.ReadLine();

            Random rnd = new Random();

            string consoleInput = PossibleValues[rnd.Next(0, PossibleValues.Length)];

            Console.WriteLine(consoleInput);

            Console.WriteLine("----------------------------------");

            Evaluate(consoleInput, input);
        }
        private void Evaluate(string ConsoleInput, string UserInput)
        {
            foreach (Weapon w in AvailableOptions.Options)
            {
                switch (UserInput)
                {
                    case var _ when UserInput.Trim().ToLower() == w.Name.Trim().ToLower():
                        switch (w)
                        {
                            case var _ when (w.StrongTo == ConsoleInput):
                                Console.WriteLine("You won");
                                break;

                            case var _  when (w.WeakTo == ConsoleInput):
                                Console.WriteLine("You lost");
                                break;

                            default:
                                Console.WriteLine("Tie");
                                break;
                        }
                        break;
                }
            }
            Thread.Sleep(2000);
            Console.Clear();
        }
        class Program
        {
            static void Main(string[] args)
            {
                RockPaperScissors rockPaperScissors = new RockPaperScissors()
                {
                    Rounds = 5,
                };
                rockPaperScissors.StartGame();

                Console.ReadLine();

            }
        }
    }
}

Thank you CodeReview StackExchange,


texts: Simulating pod racing over a 2D map : am I implementing OOP in a GO-like fashion?

texts:
I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be.

I used an OOP design. Is it correctly implemented in GO ?

In my main, I will call the method pod.playTurn(target, speed)

package main

import (
    "fmt"
    "math"
    "os"
    "strconv"
)
// Dot is king
type Dot struct {
    x, y int
}
// Pod is life
type Pod struct {
    position                Dot
    vx, vy, angle, nextCpID int
    hasShieldOn             bool
}

func squaredDist(a, b Dot) int {
    return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)
}
func distance(a, b Dot) float64 {
    return math.Sqrt(float64(squaredDist(a, b)))
}

func (pod Pod) getAngle(p Dot) float64 {
    d := distance(p, pod.position)
    dx := float64(p.x-pod.position.x) / d
    dy := float64(p.y-pod.position.y) / d
    a := math.Acos(dx) * 180.0 / math.Pi

    // If the point I want is below me, I have to shift the angle for it to be correct
    if dy < 0 {
        a = 360.0 - a
    }
    return a
}

func (pod Pod) diffAngle(p Dot) float64 {
    a := pod.getAngle(p)
    pangle := float64(pod.angle)

    right := 0.0
    if pangle <= a {
        right = a - pangle
    } else {
        right = 360.0 - pangle + a
    }

    left := 0.0
    if pangle >= a {
        left = pangle - a
    } else {
        left = pangle + 360.0 - a
    }

    if right < left {
        return right
    }
    return -left
}

func (pod Pod) rotate(p Dot) int {
    a := pod.diffAngle(p)

    // Can't turn more than 18° in one turn !
    if a > 18.0 {
        a = 18.0
    } else if a < -18.0 {
        a = -18.0
    }

    pod.angle += int(math.Round(a))

    if pod.angle >= 360.0 {
        pod.angle = pod.angle - 360.0
    } else if pod.angle < 0.0 {
        pod.angle += 360.0
    }
    return pod.angle
}

func (pod Pod) boost(t int) (int, int) {
    if pod.hasShieldOn {
        return pod.vx, pod.vy
    }
    pangle := float64(pod.angle)
    pod.vx += int(math.Round(math.Cos(pangle) * float64(t)))
    pod.vy += int(math.Round(math.Sin(pangle) * float64(t)))
    return pod.vx, pod.vy
}

// t shoud become a float later on
func (pod Pod) move(t int) (int, int) {
    pod.position.x += pod.vx * t
    pod.position.y += pod.vy * t
    return pod.position.x, pod.position.y
}

func (pod Pod) endTurn() (int, int) {
    // todo rounding position if needed
    pod.vx = int(float64(pod.vx) * 0.85)
    pod.vy = int(float64(pod.vy) * 0.85)
    return pod.vx, pod.vy
}

func (pod Pod) playTurn(p Dot, t int) {
    pod.angle = pod.rotate(p)
    pod.vx, pod.vy = pod.boost(t)
    pod.position.x, pod.position.y = pod.move(1)
    pod.vx, pod.vy = pod.endTurn()
    fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ")
    fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy)
}

Am I using struct correctly ? Is it acceptable object oriented code ?


texts:
I'm new to React.js and this code came from 30 Days of React - Day 7. However the given code example wasn't working so I rewrote it myself. My biggest issue here is how to make the component work without function getTime() using both setState and return. Any other suggestions are appreciated.

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {currentTime: this.getTime()};
    }

    getTime() {
        const currentTime = new Date(),
        hours = currentTime.getHours(),
        minutes = currentTime.getMinutes(),
        seconds = currentTime.getSeconds(),
        ampm = hours >= 12 ? 'pm' : 'am';
        this.setState({currentTime: {hours, minutes, seconds, ampm}});
        return {hours, minutes, seconds, ampm};
    }

    componentDidMount() {
        const intervalId = setInterval(this.getTime.bind(this), 1000);
        this.setState({intervalId: intervalId});
    }

    componentWillDisMount() {
        clearInterval(this.state.intervalId);
    }

    render() {
        const {hours, minutes, seconds, ampm} = this.state.currentTime;
        return (

                {hours == 0 ? 12 : (hours > 12) ? hours - 12 : hours}:
                {minutes > 9 ? minutes : `0${minutes}`}:
                {seconds > 9 ? seconds : `0${seconds}`} {ampm}

        )
    }
}

ReactDOM.render(<Clock />, document.querySelector("#app"));


texts: Filtering of maximum value by ID and category sum

texts:
I have a task that is quite simple: I need to get the sum of values in the categories of each ID, and keep the category with the highest sum:
id    category   value
1       A         10
1       A         15
1       B         13
2       A         80

So, in this case the sum of value for each category-id pair would be:
id    category   value
1       A         25
1       B         13
2       A         80

And then the maximum for id == 1 is 25 and for the other is 80, so the final dataframe is:
id    category   value
1       A         25
2       A         80

I achieved this like this:
(df.groupby(['id', 'category'])['value']
 .sum().reset_index().sort_values(by=['id', 'value'])
 .drop_duplicates(['id'], keep='last'))

I feel this can be done in lesser steps, maybe with some transform, but I can't find a better way. Any ideas?
Thanks


texts: Nearest Neighbour classification algorithm

texts:
The following code is from a university assignment of mine to write a classification algorithm (using nearest neighbour) to classify whether or not a given feature set (each feature is the frequency of words in an email) is spam or not.

We are given a CSV file (the training data) with the frequencies, and an integer (1 or 0) at the end of the row indicating whether or not it is spam.
So in this form:

X1,X2,...,Xn,SPAM

The test data is also in this form (including the SPAM column, so we can verify the accuracy).

My question is, how can I make this code more idiomatic, and what speedups can I make to this code? For example, is there a way to write getMostCommon, without having to groupBy and then run a maximumBy again?

import Text.CSV
import Data.List

data SpamType = Spam | NotSpam
    deriving (Show, Eq)

type FeatureSet = [Float]

toSpam :: Int -> SpamType
toSpam 0 = NotSpam
toSpam 1 = Spam
toSpam a = NotSpam

parseClassifiedRecord :: Record -> (FeatureSet, SpamType)
parseClassifiedRecord x = (init converted, toSpam (truncate (last converted)))
    where
        converted = map (\val -> read val :: Float) x

-- returns the euclidean distance between two feature sets
difference :: FeatureSet -> FeatureSet -> Float
difference first second = sqrt (sum (zipWith (\x y -> (x - y)^2) first second))

-- finds the SpamType of the k nearest 'nodes' in the training set
findKNearest :: [(FeatureSet, SpamType)] -> FeatureSet -> Int -> [SpamType]
findKNearest trainingSet toMatch k = take k (map snd (sortBy (\x y -> (compare (fst x)  (fst y))) [(difference (fst x) toMatch, snd x) | x <- trainingSet]))

-- returns item which occurs most often in the list
getMostCommon :: (Eq a) => [a] -> a
getMostCommon list = head (maximumBy (\x y -> (compare (length x) (length y))) (groupBy (\x y -> (x == y)) list))

-- given a feature set, returns an ordered (i.e. same order as input)
-- list of whether or not feature is spam or not spam
-- looks at the closest k neighbours
classify :: [(FeatureSet, SpamType)] -> FeatureSet -> Int -> SpamType
classify trainingSet toClassify k = getMostCommon (findKNearest trainingSet toClassify k)

-- gives a value for the accuracy of expected vs actual for spam classification
-- i.e. num classified correctly / num total
accuracy :: [(SpamType, SpamType)] -> Float
accuracy classifications = (fromIntegral $ length (filter (\x -> (fst x) == (snd x)) classifications)) / (fromIntegral $ length classifications)

main = do
    packed <- parseCSVFromFile "spam-train.csv"
    packedtest <- parseCSVFromFile "spam-test.csv"
    let (Right trainingSet) = packed
    let (Right testSet) = packedtest
    let classifiedTrainingSet = map parseClassifiedRecord (tail (init trainingSet))
    let unclassified = map parseClassifiedRecord (tail (init testSet))
    let classified = map (\x -> (classify classifiedTrainingSet (fst x) 1, snd x)) unclassified
    putStrLn (show (accuracy classified))


texts: Pandas - 3 iterations per second on simple conditional

texts:
The function removes rows from a pandas df if that row doesn't have the value of important_1 inside of important_2. For example if important_1 is "blue" and important_2 is "M" then that row would be removed, but if important_2 were "redbluegreen" then the row would be kept.

On my ~125mb files this code runs really slow. Only about 3 iterations a second. In this example it runs faster maybe because it is a much smaller csv.
How can I speed this up?

import pandas as pd
import numpy as np
from io import StringIO

df = """
valid,important_1,important_2,unrelated_1,unrelated_2
2015-07-10 01:47:00,blue,,blabla,foobar56
2015-07-10 01:51:00,blue,M,blabla,foobar32
2015-07-10 02:37:00,blue,M,blab004la,foobar
2015-07-10 02:51:00,blue,M,blabla,foobar343
2015-07-10 03:19:00,blue,blue green,blabla,foobar
2015-07-10 03:51:00,blue,,blabla1,foobar6543
2015-07-10 04:11:00,blue,green red,blabla,foobar
2015-07-10 04:51:00,blue,red,blabla,foobar2466
2015-07-10 05:51:00,blue,blue,blabla,foobar
2015-07-10 06:27:00,blue,,blabla4,foobar
2015-07-10 06:51:00,blue,,blab605la3,foobar6543
2015-07-10 07:27:00,blue,M,blabla,foobar
2015-07-10 07:51:00,blue,M,blab445la2,foobar2334
2015-07-10 08:51:00,blue,blue green red,blabla,foobar7666
2015-07-10 09:51:00,blue,blue green,blabla,foobar
"""
df = StringIO(df)
df = pd.read_csv(df)

def remove_rows_that_dont_have_important_1_in_important_2(df):
    """
    Removes all rows of the dataframe that do not have important_1 inside of important_2.
    Note: All rows have the same value for important_1.
    Note: Every row can have a different value for important_2.
    Note: There are unrelated columns in the df that cannot be dropped from the df. But rows still can.
    """
    important_1 = df.at[0, 'important_1']  # get the icao fro the df from the first ob
    important_2_column_index = df.columns.get_loc('important_2')  # column order won't always be the same, so find the right column first
    iter_index = len(df)  # the start point of the loop

    while iter_index > 0:  # start from the end of the df and work forwards
        print(iter_index)  # DEBUG printing
        iter_index -= 1  # every loop move forward one item. This is at the top of the loop because that way every loop we ensure to move down one (or up a row depending on how you look at it).

        value_of_important_2_for_this_row = df.iat[iter_index, important_2_column_index]  # the value of important_2 for the row we are currently on

        # check for np.NaN first because it is cheaper then checking str in str
        if value_of_important_2_for_this_row is np.NaN:  # if the value of important_2 is np.NaN then there is now way important_1 can be in it
            pass

        # str in str check
        elif important_1 not in value_of_important_2_for_this_row:  # safe to assume the important_2 is off type str
            pass

        else:  # safe to assume that important_1 is indeed in important_2
            continue  # skip deletion because important_1 is in important_2 Yay!

        df.drop([iter_index], inplace=True)  # delete the row

    return df  # reset the index before returning the df

df = remove_rows_that_dont_have_important_1_in_important_2(df=df)
print(df)

OUTPUT

                  valid important_1     important_2 unrelated_1 unrelated_2
4   2015-07-10 03:19:00        blue      blue green      blabla      foobar
8   2015-07-10 05:51:00        blue            blue      blabla      foobar
13  2015-07-10 08:51:00        blue  blue green red      blabla  foobar7666
14  2015-07-10 09:51:00        blue      blue green      blabla      foobar


texts:
I'm trying to generate N prime numbers where my N = 200,000.

The method that I think I wrote is -

  Start with first prime of 2
  Increment possible prime number by 1
  See if possible prime is divisible by any found prime (if yes exit to 2)
  Stop testing when next found prime is more than half of the possible prime (exit to 2)
  Add it to the list

It works, but it is taking 1 minute 8 seconds which seems really long. Is my algorithm not doing what I think or is it just implemented incorrectly? Or should I not be using these arrays?

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Module PrimeNumberGenerator
     Sub Main()
        Static start_time As DateTime
        Static end_time As DateTime
        Dim elapsed_time As TimeSpan
        start_time = DateTime.Now
        Dim targetPrimes(199999) As Integer
        targetPrimes = GetPrimes(targetPrimes.Length)
        end_time = DateTime.Now
        elapsed_time = end_time - start_time
        Debug.Print(elapsed_time.ToString)
        Debug.Print((targetPrimes(500)).ToString)
    End Sub

    Private Function GetPrimes(ByVal countOfPrimes As Integer) As Integer()
        Dim myPrimes(countOfPrimes - 1) As Integer
        Dim primeIndex As Integer = 0
        Dim testIndex As Integer = 0
        Dim possiblePrime As Integer = 2
        myPrimes(primeIndex) = possiblePrime
        Do Until primeIndex = countOfPrimes - 1
            possiblePrime += 1
            For testIndex = 0 To primeIndex
                If possiblePrime Mod myPrimes(testIndex) = 0 Then
                    Continue Do
                ElseIf myPrimes(testIndex + 1) * 2 > possiblePrime Then
                    Exit For
                End If
            Next
            primeIndex += 1
            myPrimes(primeIndex) = possiblePrime
        Loop
        Return myPrimes
    End Function
End Module


texts: Displaying information about a ticket purchase

texts:
My code works perfectly, however, I know my approach isn't best practice practice. I would appreciate the effort of anyone who tries to explain in details on how I could refactor this code using either(presenters, decorators or poros) - I have no deep understanding of either yet.
Here is the code below:

In my events controller, I have a method called tickets_report defined as such

def tickets_report
  @all_bookings = @event.bookings
  @ticket_types = @event.ticket_types
  @attendees = @event.attendees
end

then, I use the @ticket_types instance variable in my views to plot a table as follows:

<% grand_quantity = ticket_left = quantity_sold = total_price = total_amount = 0 %>
<% @tickets.each_with_index do |ticket, index| %>
    <% remains = ticket.quantity.to_i - ticket.user_tickets.count.to_i
       amount = ticket.price.to_f * ticket.user_tickets.count.to_i
       grand_quantity += ticket.quantity
       ticket_left += remains
       quantity_sold += ticket.user_tickets.count
       total_price += ticket.price.to_f
       total_amount += amount
    %>

            <%= index + 1%>
            <%= ticket.name %>
            <%= ticket.quantity %>
            <%= remains %>
            <%= ticket.user_tickets.count %>
            <%= number_to_currency(ticket.price)%>
            <%= number_to_currency(amount)%>

<% end %>

    Grand Total
    <%= grand_quantity %>
    <%= ticket_left %>
    <%= quantity_sold %>
    <%= number_to_currency(total_price)%>
    <%= number_to_currency(total_amount)%>

My problem is this calculations done in the view is really not a good thing, and this is how far I have gone trying to fix this myself

module Events
  class Ticket
    def initialize(ticket)
      @ticket = ticket
    end

    def name
      @ticket.name
    end

    def quantity
      @ticket.quantity
    end

    def price
      @ticket.price.to_f
    end

    def user_count
      @ticket.user_tickets.count.to_i
    end

    def remains
      @ticket.quantity.to_i - user_count
    end

    def amount
      price  * user_count
    end
  end

  class TicketReportPresenter < Ticket
    @@grand_quantity = @@ticket_left = @@quantity_sold = 0
    @@total_price = @@total_amount = 0

    def initialize(ticket)
      @ticket = Ticket.new(ticket)
      @@grand_quantity += @ticket.quantity.to_i
      @@ticket_left += @ticket.remains
      @@quantity_sold += @ticket.user_count
      @@total_price += @ticket.price
      @@total_amount ++ @ticket.amount
    end

    class << self

      def grand_quantity
        @@grand_quantity
      end

      def ticket_left
        @@ticket_left
      end

      def quantity_sold
        @@quantity_sold
      end

      def total_price
        @@total_price
      end

      def total_amount
        @@total_amount
      end
    end
  end
end

The new tickets_report method in my controller

def tickets_report
  @all_bookings = @event.bookings
  @ticket_types = Events::TicketReportPresenter.new(@event.ticket_types.first)
  @attendees = @event.attendees
end

However, things don't seem to be going right at this point. For instance I cannot call ActiveRecord relationships on the tickets object I defined. What is the best approach to refactor the logic present in the view, a detailed description and source code will suffice plus links to other resources.


texts: Updating Google Sheets table efficiently

texts:
Program description:

A program accepts a list (uTable). The list consists of at least 4 different lists (rows), each with 7 elements (cells). Check whether the value in [7] is zero and assign a new random variable to it on the basis of what [3] is: 1, 2, 3, 4 or 5. A chance should be used to calculate the chance of the assigning operation. A cell should be updated using sheet_store.update_cell(i, k, value). A check for admin permissions should be included ( if adminId in admins:).

My solution:
 if adminId in admins:
        uTable = sheet_store.get_all_values()
        for i in range(len(uTable)):
            row = uTable[i]
            if (row[7] == '0'):
                chance = random.uniform(0, 1)
                if (row[3] == '5'):
                    if chance <= 0.05:
                        print('5 EXECUTED!')
                        sheet_store.update_cell(i+1, 8, 1)
                elif (row[3] == '4'):
                    random_1 = randint(1, 3)
                    if chance <= 0.1:
                        print('4 EXECUTED!')
                        sheet_store.update_cell(i+1, 8, random_1)
                elif (row[3] == '3'):
                    random_2 = randint(1, 5)
                    if chance <= 0.4:
                        print('3 EXECUTED!')
                        sheet_store.update_cell(i+1, 8, random_2)
                elif (row[3] == '2'):
                    random_3 = randint(1, 10)
                    if chance <= 0.6:
                        print('2 EXECUTED!')
                        sheet_store.update_cell(i+1, 8, random_3)
                elif (row[3] == '1'):
                    random_4 = randint(1, 20)
                    if chance <= 1:
                        print('1 EXECUTED!')
                        sheet_store.update_cell(i+1, 8, random_4)
        return True
    else:
        return False

Input: (TABLE IS TRANSFERRED AS LIST) (Row and column with index 0 are not included)
0    1              2   3       4          5           6          7
1 артифак           0   5   незвестен   a_1.jpg 07/08/20/15/30    0
2 Съедобный предмет 1   3   бафф        a_2.jpg                   0
3 описание          2   4   неизвестен  a_3.jpg время обновления  1
4 Отличный компан   3   2   компаньон                             7

Runtime:
1 EXECUTED!
2 EXECUTED!

success
0.5s

Is there any way to improve the code and make the program run faster? Thank you in advance.


texts: C program to read a file containing numbers, and then print ones divisible by 3 to another file

texts:
The program reads a file containing a list of numbers, and then writes the ones divisible by 3 to another file, and prints the remaining ones (non-divisible) to a third file.

Declaring, opening, and closing the files is alone over 50% of the code, is there anyway to make it more compact?

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

int main(void){
    FILE *in_file; /*input file*/
    FILE *out_file_divis; /*FIle that contains numbers divisible by 3*/
    FILE *out_file_remain; /*File that contains the rest of the numbers*/

    if((in_file = fopen("total", "r")) == NULL){
        perror("total");
        exit(EXIT_FAILURE);
    }

    if((out_file_divis = fopen("divis", "w")) == NULL){
        perror("divis");
        exit(EXIT_FAILURE);
    }

    if((out_file_remain = fopen("remain", "w")) == NULL){
        perror("remain");
        exit(EXIT_FAILURE);
    }

    int number;

    while(fscanf(in_file, "%i", &number) == 1){
        if(number%3 == 0){
            fprintf(out_file_divis, "%i\n", number);
        }

        else{
            fprintf(out_file_remain, "%i\n", number);
        }
    }

    fclose(in_file);
    fclose(out_file_divis);
    fclose(out_file_remain);

    return 0;
}


texts: Structuring a HTML5 game without a framework

texts:
After trying a couple different HTML5 frameworks, I've always found pure JS the most appealing. However, I am uncertain about the way I'm structuring it.

var titlescreen = new Titlescreen();
var fps = new FPSTracker();
var input = new Input();
var background = new Background();
var shops = new Shops();
var chunkhandler = new ChunkHandler();
var explosionhandler = new ExplosionHandler();
var ui = new UI();
var world = new World();
var player = new Player();
var joystick = new Joystick();

var old_time = 0;
var dt = 0;

load();

function init(){    // called once resources loaded
    // ...
    requestAnimationFrame(loop);
}

function update(){
    player.update();
}

function draw(){
    background.draw();
    world.draw();
    shops.draw();
    player.draw();
    chunkhandler.draw();
    explosionhandler.draw();
    ui.draw();
    fps.draw();
}

function loop(time){
    dt = Math.min(0.04, (time - old_time) / 1000);

    if(!game_paused){
        update();
        draw();
    }

    old_time = time;
    requestAnimationFrame(loop);
}

Some objects listed here must communicate information between each other. For example, the Player class accesses some of world's functions by simply stating world.functionINeedToUse();, using the global variable's name. Coming from a Java background, this gives me a very bad vibe as it depends on the declaration of this global variable with the specific name. Though I've found JS to be a more forgiving language, this still does not feel right.


texts:
I started to learn programming just a few days ago. And I've written code for a simple original game for practice, using some knowledge of JavaScript that I have gained so far.

Is the following code properly written? I'm especially concerned about the use of "Math.floor", "Math.random", "function", and "if / else".

Incidentally, "Metal King" is the name of a monster in the game, and "Angelo" is a character.

alert("Metal Kings (A, B, and C) have appeared!");

// Which Metal King (A, B, or C) will Angelo decide to attack? \
// 33% probability for each.

var MetalKingABC = 1 + Math.floor(Math.random() * 3);

if (MetalKingABC === 1) {
    MetalKingABC = "Metal King A";
}
else if (MetalKingABC === 2) {
    MetalKingABC = "Metal King B";
}
else {
    MetalKingABC = "Metal King C";
}

var WhichOneToAttack = function(MonsterName) {

    alert("Angelo is about to attack " + MonsterName + ".");

    // Metal King has a 50% chance of fleeing the battle.

    var FleeOrFight = 1 + Math.floor(Math.random() * 2);

    if (FleeOrFight === 1) {
        alert(MonsterName + " flees like lightning!");
        // The battle ends here before Angelo attacks.
    }

    else // Metal King stays, and Angelo attacks.
    {
        // 70% chance of MISS, 20% of ONE damage, 10% of Critical.

        var MissOneCritical = 1 + Math.floor(Math.random() * 10);

        if (MissOneCritical <= 7) {
            alert(MonsterName + " swiftly evades Angelo's attack.");
        }

        else if (MissOneCritical <= 9) {
            alert("Angelo inflicts 1 point of damage on " + MonsterName + ".");
        }

        else {
            // The damage dealt by a critical hit can range from 197 to 256 points.

            var CriticalRange = 197 + Math.floor(Math.random() * 60);

            alert("Angelo lands a critical hit on " + MonsterName + ", dealing massive \
            damage of " + CriticalRange + " points! Angelo defeats " + MonsterName + ".");

            // When defeated, Metal King drops a shield with an 80% probability.

            var ShieldDrop = 1 + Math.floor(Math.random() * 10);

            if (ShieldDrop <= 8) {
                alert(MonsterName + " drops a shield. Angelo obtains a Diamond Shield!");
            }
            else {
            // No code is written in this else portion, since Metal King didn't drop \
            // any item.
            }
        }
    }
};

// Finally, call the function.

WhichOneToAttack(MetalKingABC);


texts: Design to separate client API from internal API in Kotlin for a chess engine

texts:
This is a follow-up from my previous review on this site. To be clear, the code is stand-alone, and does not depend on the previous review.

As before my goal is to come up with a design for a chess engine in Kotlin that hides implementation details, and that ensures that the implementation cannot accidentally become spaghetti.

Example client code

package chessapp

import chessapp.api.internal.createBoard
import chessapp.api.internal.createSearchEngine

fun main() {
    val board = createBoard("1R/1p w")
    val searchEngine = createSearchEngine()
    val move = searchEngine.findBestMove(board)
    println(move)
}

Client facing public API

package chessapp.api

enum class PieceColor { BLACK, WHITE }
enum class PieceType { PAWN, ROOK}
data class ColoredPiece(val pieceColor: PieceColor, val pieceType: PieceType)
interface Board {
    val pieces: List<ColoredPiece>
}
interface SearchEngine {
    fun findBestMove(board: Board): String
}

Intended to be clean and easy to understand, but bad for performance.

Inward facing API

package chessapp.api.internal

import chessapp.api.Board

internal const val BLACK_PAWN: Byte = (0x00 + 0x01).toByte()
internal const val WHITE_ROOK: Byte = (0x08 + 0x05).toByte()
internal interface InternalBoard: Board {
    val bytePieces: ByteArray
    fun doInternalMove(from: Int, to: Int)
}

Intended to be optimized for performance and potentially hard to understand.
Additionally, the interface is likely volatile and can change quickly, which should not affect the public API.

Implementation that supports both public and internal API

package chessapp.api.internal

import chessapp.api.Board
import chessapp.api.ColoredPiece
import chessapp.api.PieceColor
import chessapp.api.PieceType

fun createBoard(fen: String): Board = InternalBoardImpl(fen)
internal fun createInternalBoard(board: Board): InternalBoard = InternalBoardImpl(board as InternalBoardImpl)

internal class InternalBoardImpl(override val bytePieces: ByteArray) : InternalBoard {
    constructor(fen: String) : this(byteArrayOf(BLACK_PAWN, WHITE_ROOK)) {}
    constructor(rhs: InternalBoardImpl) : this(rhs.bytePieces.copyOf()) {}

    override val pieces: List<ColoredPiece>
        get() = bytePieces.map { it.toColoredPiece() }

    override fun doInternalMove(from: Int, to: Int) {}
}

internal fun Byte.toColoredPiece() = when (this) {
    BLACK_PAWN -> ColoredPiece(PieceColor.BLACK, PieceType.PAWN)
    WHITE_ROOK -> ColoredPiece(PieceColor.WHITE, PieceType.ROOK)
    else -> null
}!!

As you may notice, there is a hidden assumption that a Board will always be  an InternalBoard, and even more, implemented as an InternalBoardImpl. As yet I haven't figured out how to do that better without sacrificing the separation of the public and internal interface. So please feel free to comment.

Search engine implementation that uses only the internal interface

package chessapp.api.internal

import chessapp.api.Board
import chessapp.api.SearchEngine

fun createSearchEngine(): SearchEngine = OptimizedSearchEngine()

internal class OptimizedSearchEngine: SearchEngine {
    override fun findBestMove(board: Board): String {
        // Intended to be badly readable code just because it is supposed to be optimized for speed
        return listOf(Pair(7, 8), Pair(7, 15)).map {
            val newInternalBoard = createInternalBoard(board)
            newInternalBoard.doInternalMove(it.first, it.second)
            Pair(evaluate(newInternalBoard), it)
        }.maxBy { it.first }?.second.toString()
    }
    private fun evaluate(internalBoard: InternalBoard) = 42
}

Final words

I'd appreciate any thoughts you may have how this example design code can be improved.

To be honest, I'm not pleased with the hidden assumption that a Board has to be an InternalBoard, which in turn has to be an InternalBoardImpl. It goes against the OO concept that an interface should be able to have different implementations.


texts: Fuzzy Humanize date using Moment.js for datatable searching

texts:
In my JS project, I am using datatable plugin to show data where I have a date column which users can filter/search.

In order to help users to search using a logical string such as today,  thismonth , lastweek I am writting a fucntion which uses MomentJs.

I am looking at the most efficient way of writing this fuzzyDate function.

function fuzzyDate(mydate){
  var fuzzy1 = ''; var fuzzy2 = ''; var fuzzy3 = '';

  var todaydt = moment(moment().format('YYYY-MM-DD'));
  var daydiff = mydate.diff(todaydt,'day');
  if (daydiff==-1){fuzzy1='Yesterday'}
  if (daydiff==0){fuzzy1='Today'}
  if (daydiff==1){fuzzy1='Tomorrow'}

  var weekdiff = mydate.diff(todaydt,'week');
  if (weekdiff==-1){fuzzy2='LastWeek'}
  if (weekdiff==0){fuzzy2='ThisWeek'}
  if (weekdiff==1){fuzzy2='NextWeek'}

  var monthdiff = mydate.diff(todaydt,'month');
  if (monthdiff==-1){fuzzy3='LastMonth'}
  if (monthdiff==0){fuzzy3='ThisMonth'}
  if (monthdiff==1){fuzzy3='NextMonth'}

  return fuzzy1 + ' ' + fuzzy2 + ' ' + fuzzy3;
}

console.log( '2018-06-01 - ', fuzzyDate(moment('2018-06-01','YYYY-MM-DD')) ) ;
console.log( '2018-07-01 - ', fuzzyDate(moment('2018-07-01','YYYY-MM-DD')) ) ;
console.log( '2018-07-07 - ', fuzzyDate(moment('2018-07-07','YYYY-MM-DD')) ) ;
console.log( '2018-07-10 - ', fuzzyDate(moment('2018-07-10','YYYY-MM-DD')) ) ;
console.log( '2018-07-11 - ', fuzzyDate(moment('2018-07-11','YYYY-MM-DD')) ) ;
console.log( '2018-07-12 - ', fuzzyDate(moment('2018-07-12','YYYY-MM-DD')) ) ;
console.log( '2018-07-13 - ', fuzzyDate(moment('2018-07-13','YYYY-MM-DD')) ) ;
console.log( '2018-07-15 - ', fuzzyDate(moment('2018-07-15','YYYY-MM-DD')) ) ;
console.log( '2018-07-30 - ', fuzzyDate(moment('2018-07-30','YYYY-MM-DD')) ) ;
console.log( '2018-08-30 - ', fuzzyDate(moment('2018-08-30','YYYY-MM-DD')) ) ;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Output of the above function

2018-06-01 - LastMonth
2018-07-01 - LastWeek ThisMonth
2018-07-07 - ThisWeek ThisMonth
2018-07-10 - ThisWeek ThisMonth
2018-07-11 - Yesterday ThisWeek ThisMonth
2018-07-12 - Today ThisWeek ThisMonth
2018-07-13 - Tomorrow ThisWeek ThisMonth
2018-07-15 - ThisWeek ThisMonth
2018-07-30 - ThisMonth
2018-08-30 - NextMonth


texts: Elegant way for parsing birthday from rodne cislo (czech republic ID)

texts:
How can I refactor it to elegant way? This code is about parse birthday from Rodne Cislo string. I don't know how to do it clever and add more clean code style details

public static void extractBirthdayFromRodneCislo(String rodneCislo) {
    rodneCislo = rodneCislo.replace("/", "=");

    int year;
    int month;
    int day;

    if (rodneCislo.length() < 10) {
        year = Integer.parseInt("19" + rodneCislo.charAt(0) + rodneCislo.charAt(1));
    } else {
        String century = Integer.parseInt(String.valueOf(rodneCislo.charAt(0)) + String.valueOf(rodneCislo.charAt(1))) < 53 ? "20" : "19";
        year = Integer.parseInt(century + rodneCislo.charAt(0) + rodneCislo.charAt(1));
    }

    month = Integer.parseInt(String.valueOf(rodneCislo.charAt(2)) + String.valueOf(rodneCislo.charAt(3)));

    if (month > 12) {
        month -= 50;
    }
    day = Integer.parseInt(String.valueOf(rodneCislo.charAt(4)) + rodneCislo.charAt(5));

    System.out.println(year + " " + month + " " + day);
}

The form is YYXXDD/SSSC, where XX=MM (month of birth) for male (numbers 01-12) and XX=MM+50 for female (numbers 51-62), SSS is a serial number separating persons born on the same date and C is a check digit, but for people born before 1 January 1954 the form is without the check digit - YYXXDD/SSS. This enables the system to work until the year 2054. The whole number must be divisible by 11.


texts:
Can you please share your thoughts on the following simple httphelper in Go? Thanks in advance.
I mainly would like to know whether returning a channel of a custom type seems like a good idea and if so , how could I improve it for only receive chans.
package services

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "time"
)

type HHResult struct {
    Result     string
    StatusCode int
    Error      error
}

type IHttpHelper interface {
    Request(method string, url string, headers map[string][]string, payload interface{}) chan HHResult
    RequestWithOptions(method string, url string, headers map[string][]string, payload interface{}) chan HHResult
}

var singleton IHttpHelper

type HttpHelper struct{}

func (h *HttpHelper) Request(method string, url string, headers map[string][]string, payload interface{}) chan HHResult {
    var result chan HHResult = make(chan HHResult)
    go func(output chan HHResult) {
        payl, err := json.Marshal(payload)
        if err != nil {
            result <- HHResult{
                Result:     "",
                StatusCode: 0,
                Error:      err,
            }
        }
        req, err := http.NewRequest(method, url, bytes.NewReader(payl))
        client := http.Client{
            Timeout: time.Second * 30,
        }
        resp, err := client.Do(req)
        if err != nil {
            result <- HHResult{
                Result:     "",
                StatusCode: 0,
                Error:      err,
            }
        }
        respbytes, err := ioutil.ReadAll(resp.Body)
        defer resp.Body.Close()
        result <- HHResult{
            Result:     string(respbytes),
            StatusCode: resp.StatusCode,
            Error:      nil,
        }

    }(result)
    return result
}

func (h *HttpHelper) RequestWithOptions(method string, url string, headers map[string][]string, payload interface{}, timeout int) chan HHResult {
    var result chan HHResult = make(chan HHResult)
    go func(output chan<- HHResult) {
        payl, err := json.Marshal(payload)
        if err != nil {
            result <- HHResult{
                Result:     "",
                StatusCode: 0,
                Error:      err,
            }
        }
        req, err := http.NewRequest(method, url, bytes.NewReader(payl))
        client := http.Client{
            Timeout: time.Second * timeout,
        }
        resp, err := client.Do(req)
        if err != nil {
            result <- HHResult{
                Result:     "",
                StatusCode: 0,
                Error:      err,
            }
        }
        respbytes, err := ioutil.ReadAll(resp.Body)
        defer resp.Body.Close()
        result <- HHResult{
            Result:     string(respbytes),
            StatusCode: resp.StatusCode,
            Error:      nil,
        }

    }(result)
    return result
}

func NewHttpHelper() IHttpHelper {
    if singleton == nil {
        singleton = &HttpHelper{}
    }
    return singleton
}

Example of usage
func main() {
  helper := services.NewHttpHelper()
  res := <-helper.Request("GET", "https://jsonplaceholder.typicode.com/users/1", nil, nil)

  if res.Error != nil {
      fmt.Println(res.Error.Error())
      return
  }
  fmt.Println(res.StatusCode)
  fmt.Println(res.Result)
}


texts: Data transformation using Lodash in a more readable way

texts:
I don't like how transforming the data requires a bunch of nested functions. It's not very readable. Is there a more readable way to do the same transformations in Lodash?

var templates = {
  "fullRenderV80": {
    "stuff": "stuff",
    "screenshots": [
      {
        "device": "iPhone 6",
        "position": 1
      },
      {
        "device": "Watch",
        "position": 2
      }
    ]
  },
  "fullRenderV70": {
    "stuff": "stuff",
    "screenshots": [
      {
        "device": "iPhone 6",
        "position": 1
      },
      {
        "device": "iPad",
        "position": 2
      }
    ]
  }
}

var transformedData = _.groupBy(_.map(templates, 'screenshots'), function(screenshotsArray) {
  return _.reduce(screenshotsArray, function(templateDevicesName, screenshot) {
    return templateDevicesName.concat(screenshot.device)
  }, []).join(' + ')
})

// transformedData is this:
//{
//  "iPhone 6 + Watch": [
//    [
//      {
//        "device": "iPhone 6",
//        "position": 1
//      },
//      {
//        "device": "Watch",
//        "position": 2
//      }
//    ]
//  ],
//  "iPhone 6 + iPad": [
//    [
//      {
//        "device": "iPhone 6",
//        "position": 1
//      },
//      {
//        "device": "iPad",
//        "position": 2
//      }
//    ]
//  ]
//}


texts: Finding the frequency of an element in a sorted list of integers

texts:
Input: Array of sorted integers and an element to check the frequency for

Output: Frequency of the element

public class FrequencyElement {
public static void main(String args[]){
    //System.out.println("Enter Input string");

    int input_array []= {2,3,4,25,99,99,19000};
    int element = 99;

    System.out.println(checkFreq(input_array,element));
}
static int checkFreq(int a[],int n){
    //returns the frequency of n in a

    int indexOfElement=elementExists(a,n);

    if(indexOfElement!=-1){
        int count =0;
        while(a[indexOfElement]==n){
            count++;
            indexOfElement++;
        }
        return count;
    }
    else
        return 0;

}
static int elementExists(int input[], int element){
    int lo=0;
    int high = input.length-1;

    while(lo<high){
        int mid = (lo + high )/2;
        if(element >input[mid] ){
            lo = mid+1;
        }
        else if(element < input[mid]){
            high= mid-1;
        }
        else if (lo !=mid)
            high = mid;
        else {
            System.out.println("Mid is: " + mid);
            return mid;
        }
    }
    return -1;
}
}


texts: Scraping websites for presence of particular words

texts:
Im new to Python and Scrapy and Im trying to write a code that would find if a website contains a specific word in it. I need to scrapy many websites with different layouts so the search is a general one. I would appreciate if you could comment do you see a more efficient way on how to perform this task. Here is my solution:
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from .lists_loop import * #used to import list of 'word_to_find'
import re

word_to_find = 'pharmacy'

class TestSpider(CrawlSpider):
    name = 'test'
    # these are lists of a lot of domains
    allowed_domains = strip_url
    start_urls = merch_url
rules = (
    Rule(LinkExtractor(), callback='parse_item', follow=True),
)

def parse_item(self, response):
    # Here I clean up the parsed text not to include /n or whitespace.
    words = response.xpath("//a//text()").getall()
    cleaned_words = [word.strip() for word in words]
    cleaned_words = [word.lower() for word in cleaned_words if len(word) > 0]

    # Then I loop through the cleaned_words in order to find a match
    for single_word in cleaned_words:
        re.search(r'\b%s\b' % word_to_find, single_word)
        yield{
            'Matching': 'Found the word {} in {}'.format(word_to_find, response.url)
        }
    else:
        pass

I am stripping the found //a//text() and hence in the end searching each word separately if it matches any of my word_to_find list of words (In this case I just added 1 word for simplicity). Maybe its better to search the whole text string but the problem I encountered is that a lot of times it includes a lot of whitespaces /n symbols etc.
Any advice would be appreciated.


texts: Where best to declare a counter variable to track number of guesses?

texts:
An exercise asks that we extend the below random number generator app to print to the console how many times the user guessed before guessing the correct random number.

I first declared what I call a counter variable numberOfGuesses inside the keepPlaying while loop and then inside the continueGuessing while loop I increment this number by 1 before I check the user's guess against the random number generated. This works, but then I tried declaring numberOfGuesses at the top of the program and commented out the former placement, as you can see below, and this also worked.

My question is, which is the better way of these two to solve this, and is there another even better way to solve this problem by using another loop perhaps or would that be silly/overkill/not workable?

var randomNumber = 1
var numberOfGuesses = 0
var continueGuessing = true
var keepPlaying = true
var input = ""

while keepPlaying {
    //get a random number between 0 - 100
    randomNumber = Int(arc4random_uniform(101))
    print("The random number to guess is: \(randomNumber)")

    //var numberOfGuesses = 0 //can go here, or in global variables up top!

    while continueGuessing { //
        print("Pick a number between 0 and 100.")
        //get keyboard input, and trim the new line
        input = String(bytes: FileHandle.standardInput.availableData, encoding: .utf8)!
        input = input.trimmingCharacters(in: .whitespacesAndNewlines)

        if let userGuess = Int(input) {
            numberOfGuesses += 1
            if userGuess == randomNumber {
                continueGuessing = false //terminator for this while loop
                print("Correct number!")
                print("You have made this number of attempts to get it right: \(numberOfGuesses)")
            } else if userGuess > randomNumber {
                //user guessed too high
                print("Your guess is too high!")
            } else {
                //no reason to check if userGuess < randomNumber. It has to be.
                print("Your guess is too low!")
            }
        } else {
            print("Invalid guess, please try again.")
        }
}

print("Play again? Y or N")
    input = String(bytes: FileHandle.standardInput.availableData,encoding: .utf8)!
    input = input.trimmingCharacters(in: .whitespacesAndNewlines)

    if input == "N" || input == "n" {
        keepPlaying = false //a way to exit while loop
        print("You have played the game this number of times: \(numberOfGuesses)")

    }
    continueGuessing = true
}


texts:
I am making a GUI application for a class. I have made the form layout (make_form()) using both Frame and grid, but I am not exactly sure that one should be mixing those two together. What is the best way to make a layout, using grid to incorporate not just the labels and Entry fields, but also the buttons?

import tkinter as tk

fields = "Dimensions", "Parent population size", "Children populatoin size", \
            "Recombination population size", "Maximum iterations", "Low boundary domain", \
            "High boundary domain", "Parameter size"

def quit():
    root.destroy()

def clear_initial_conditions(initial_conditions):
    for ic in initial_conditions:
        ic[1].delete(0, "end")

def get_initial_conditions(initial_conditions):
    for ic in initial_conditions:
        field = ic[0]
        text = ic[1].get()
        if text.isdigit():
            print("%s: %s" % (field, text))
        else:
            print("Field \"%s\" does not have a valid number, correct to integer" % field)

def make_form(root, fields):
    initial_conditions = []
    for field in fields:
        row = tk.Frame(root)
        row.pack(side = tk.TOP, fill = tk.X, padx = 10, pady = 10)
        lab = tk.Label(row, width = 30, text = field, anchor = tk.W)
        lab.grid(row = 0, column = 0)
        ent = tk.Entry(row)
        ent.grid(row = 0, column = 1, sticky = tk.W)
        initial_conditions.append((field, ent))
    return initial_conditions

if __name__ == "__main__":
    root = tk.Tk()
    root.option_add('*font', ('verdana', 8))
    root.title("Pack - Example 12")
    ents = make_form(root, fields)

    root.bind("<Return>", (lambda event, e = ents: get_initial_conditions(e)))
    b1 = tk.Button(root, text = "Find minimum", command = (lambda e = ents: get_initial_conditions(e)))
    b1.pack(side = tk.LEFT, padx = 10, pady = 10)
    b2 = tk.Button(root, text = "Clear", command = (lambda e = ents: clear_initial_conditions(e)))
    b2.pack(side = tk.LEFT, padx = 10, pady = 10)

    root.mainloop()


texts: Which is the more preferable font size reset?

texts:
Up until now, I've been using a 14-pixel reset in my theme's main CSS file, but after looking online, I see that a lot of web developers prefer a 10-pixel reset;

Here is what I'm currently using:

/* reset.css */
* { font-size: 1em; }

/* dark-theme.css */
body { font-size: 0.875em; } /* 14 pixels equals 1.0em */

Here is what I've seen preferred by others:

/* reset.css */
* { font-size: 1em; }

/* dark-theme.css */
body { font-size: 0.625em; } /* Now, 14 pixels equals 1.4em; easy! */

With a simple decimal calculation, I can see the latter method being easier to work with.  Other than that, is there any real upside to the 10px method, or any downside to my 14px method?

I use 14 pixels because I find that Tahoma and Segoe UI are both at optimum reading size for the majority of users, with text resize options available if required. A 16-pixel font size looks too cluttered for my personal taste.


texts: Simple bash script creates apache2 virtualhost config for subdomain

texts:
Simple bash script to create apache2 virtualhost for localhost. Can be used for public subdomains on developer server with changes - "replace .localhost".

Tested on Ubuntu, but should work where dependency met.

Not for production, for development purposes only.

Use zenity for gui and pkexec for root permissions, so can be run without terminal, however some terminal output persist.

/etc/hosts file looks like: (so allowing add any subdomain)

127.0.0.1 localhost *.localhost

Note the wildcard, script doesn't create domains.

I'm not very experienced at bash scripting. Review and improve security, compatibility, maybe also some features with domains.

It's also on GitHub:(Updated) https://github.com/LeonidMew/CreateVirtualHost

#!/bin/bash

WEBROOT="/home/leonid/Web/" # root folder where subfolders for virtualhosts created
APACHEHOST="/etc/apache2/sites-available/050-" # prefix for virtualhost config file
A2ENSITE="050-" # short prefix for virtualhost config file
TMPHOST="/tmp/a2host-" # tmp prefix for virtualhost config while editing or rejecting

if ((`which zenity|wc -w` == 0)) # check dependency
then
    echo "Error: zenity not installed."
    exit
fi

if [ "$USER" == "root" ]
then
    zenity --error --text="You should not run this script as root but as user going to edit web files."
    exit
fi

HOST=`zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)'`
words=$( wc -w <<<"$HOST" )

if (($words == "0" || $words > 1)) # this not check for fully qualified sub domain name. ".localhost" added
then
    zenity --error --text="More then one word for sub domain or empty"
    exit
fi

HOSTFILE="$APACHEHOST$HOST"
HOSTFILE=$HOSTFILE".conf"   # apache virtualhost config file
DIR="$WEBROOT$HOST"         # folder used as document root for virtualhost

# virtualhost template
cat >$TMPHOST$HOST <<EOF
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot $DIR
    ServerName  $HOST.localhost
    ServerAlias $HOST.localhost
    <Directory "$DIR">
        AllowOverride All
        Require local
    </Directory>
    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    LogLevel warn
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF

# edit virtualhost config
TEXT=`zenity --text-info --filename=$TMPHOST$HOST --editable`
words=$( wc -w <<<"$TEXT" )
if (($words == 0))
then
    echo "Cancel"
    rm $TMPHOST$HOST
    exit
fi
echo "$TEXT" > $TMPHOST$HOST

A2ENSITE=$A2A2ENSITE$HOST".conf" # params for a2ensite

echo "execute root tools with pkexec to create virtualhost"
[ -d "$DIR" ] || mkdir -p "$DIR"
pkexec /bin/bash <<EOF
chgrp www-data "$DIR"
chmod u=rwX,g=rX,o= "$DIR"
mv $TMPHOST$HOST $HOSTFILE
chown root:root $HOSTFILE
chmod u=rw,g=r,o=r $HOSTFILE
a2ensite $A2ENSITE
EOF


texts: Load JSON file into model using Javascript / jQuery (deferred, asynchronous)

texts:
As a beginner I am always determined to improve myself. I've got written the following Code using jQuery that is working fine. However, I am sure that there are cleaner ways for achieving the same.

Right now, I am struggling with the this keyword and the asynchronous loading of the JSON file. Moreover, I am not sure whether you should call an function for initialization the way I did.

Do you have any suggestions for improvements?

$(function(){

    function Model() {
        this.data = null;
        this.init();
    };

    Model.prototype = {

        deferred: $.Deferred(),

        config: {
            jsonFile: 'dump.json'
        },

        init: function() {
            this.loadJson();
        },

        loadJson: function() {
            var self = this;
            jQuery.getJSON(
                this.config.jsonFile,
                function(data) {
                    self.data = data;
                    self.deferred.resolve();
                }
            )
            .fail(function() {
                console.error("Loading JSON file failed");
            })
            .always(function() {});
        },

        getData: function(callback) {
            console.log("getData")
            var self = this;

            $.when(this.deferred)
            .done(function() {
                callback(self.data)
            })
        },
    };

    var model = new Model();
    model.getData(function(data) {
        console.log(data)
    });

});

(duplicate of https://stackoverflow.com/q/23142089/3546614)

Update 1

I've just updated my code (and truncated unimportant stuff) taking @jgillich's advices into account. For the moment I feel better reading the JSON file when the object is generated which is why I outsourced the operation into separate function.

$(function(){
    function Model() {
        this.loadJson();
    };

    Model.prototype = {

        deferred: $.Deferred(),
        jsonFile: 'dump.json',

        loadJson: function() {
            $.getJSON(this.jsonFile)
                .done(function (data) {
                    this.data = data;
                    this.deferred.resolve(data);
                }.bind(this))
                .fail(this.deferred.reject);
        },

        getData: function() {
            return this.deferred.promise();
        },
    };

    var model = new Model();
    model.getData().done(function(data) {
        console.log('done')
        console.log(data)
    });
});


texts: Use only necessary fields in an object for URL params

texts:
I'm trying to cleanly grab some fields I need from an object.

The scenario is this:

I've got an object that is stored with certain 'extra' properties that exist because of the way we've set up our store in Redux. It'll look something like this:

var formData = {
  account_name: 'SomeAccountName',
  custom_domain_name: '',
  id: 152
};

I'm trying to grab the fields I need from this object, which in this case are only popup: true and account_name, since custom_domain_name is empty. I'll be adding the necessary fields as params to the end of the URL.

What I've got so far works, but seems clunky to me. I was hoping I could do something with object destructuring, such as:

var fields = ['account_name']
var necessaryFields = { ...fields } = formData

But of course that doesn't work. This is what I've got instead:

//this turns an array of field objects into just the name of the field
const fieldNames = fields.map(field => field.key);

//so here I just grab the field name if it's not an empty string
//and stick it in the new object. `popup: true` is not a required
//field, but it is necessary for the URL.
let necessaryFields = fieldNames.reduce(
  (newFormObject, fieldName) => {
    if (formData[fieldName]){
      newFormObject[fieldName] = formData[fieldName];
    }
    return newFormObject;
  }, { popup: true });

After this code runs, I just run the object through an existing addParamsToUrl function (that unfortunately does not account for empty fields) that pretty much just does field_name=field_value& with each key-value pair.

Is there a nicer way to do this? I'm also always looking to make my code as functional as possible (and that's possibly why this irks me).


texts: PHP array with array value into multiple arrays with same key

texts:
Very difficult to explain in a sentence sorry so here is example.
I have this array:
$setParams = [
    'repeat_delay' => [23, 1],
    'repeat_type' => ['Hour', 'Day'],
];

that I want to turn into this
$wanted = [
    [
        'repeat_delay' => 23,
        'repeat_type' => 'Hour'
    ],
    [
        'repeat_delay' => 1,
        'repeat_type' => 'Day'
    ]
];

I have it working but wanting to know if there is a cleaner way, or even another way.
$newArray = [];
$setKeys = array_keys($setParams);
$setValues = array_values($setParams);

$isSetValueArray = array_filter($setValues,
    static function ($setValue) {
        return is_array($setValue);
    });

if (!empty($isSetValueArray)) {
    foreach ($setKeys as $keyCount => $key) {
        foreach ($setValues as $valueCount => $value) {
            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    if ($keyCount === $valueCount) {
                        $newArray[$k][$key] = $v;
                    }
                }
            }
        }
    }
}

Some more information to help others. I am sorry I didn't provide sooner as I know context is everything.
Here is a link to my snippet with more info and complete example.
https://gitlab.mrwilde.solutions/-/snippets/18


texts:
I'm using this function to replace UTF-8 characters representing numbers in text with 'normal' digits.

I'm wondering if this is optimized code since this is using two str_replace()s.

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $arabic = array('٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    $num = range(0, 9);
    return str_replace($arabic, $num, str_replace($persian, $num, $string));
}


texts:
DESCRIPTION:
  [Inspired by Chandler's GameOfCups with Joey in "Friends"].
     Program gets 5-digit zipcode from user.  (Assume user won't make a
         mistake, and will enter exactly 5 digits).
     Program awards points based on a series of rules, and reports the total
         points earned at the end.
     The 8 rules are embedded as comments in the code.
     For each rule, besides adding points (or not) to the total, rule displays
         "Rule _ got _ points, so total is now _"
         (It prints this even if rule added 0 points to total).

"""
RULES
    +5 when first and last digit match
    +6 when second digit is twice the first AND third digit is greater than second or fourth digit
    +7 if any 7 is in the zipcode
    +8 when there's no "13" in MIDDLE the zipcode
    +9 when all three middle digits match
    +10 when third and fourth digits match
    +11 when zipcode is palindrome (12121 == 12121, while 12345 != 54321)
"""

Here is my solution to the challenge above:

zipcode = input("Enter your zipcode: ")
total_points = 0

#Rule 1

points = 5 if zipcode[0] == zipcode[-1] else 0
total_points += points
print(f"Rule 1 got {points} points, so total is now {total_points}")

#Rule 2

points = 6 if (int(zipcode[1]) * 2) > int(zipcode[0]) and (int(zipcode[2]) > int(zipcode[1]) or int(zipcode[2]) > int(zipcode[3])) else 0
total_points += points
print(f"Rule 2 got {points} points, so total is now {total_points}")

#Rule 3

points = 7 if "7" in zipcode else 0
total_points += points
print(f"Rule 3 got {points} points, so total is now {total_points}")

#Rule 4

points = 8 if "13" not in zipcode[1:-1] else 0
total_points += points
print(f"Rule 4 got {points} points, so total is now {total_points}")

#Rule 5

points = 9 if zipcode[1] == zipcode[2] == zipcode[3] else 0
total_points += points
print(f"Rule 5 got {points} points, so total is now {total_points}")

#Rule 6

points = 10 if zipcode[2] == zipcode[3] else 0
total_points += points
print(f"Rule 6 got {points} points, so total is now {total_points}")

#Rule 7

points = 11 if zipcode == reversed(zipcode) else 0
total_points += points
print(f"Rule 7 got {points} points, so total is now {total_points}")

print(f"{zipcode} got {total_points} points!")

I feel like there is a much better way to do this. The print statements are repetitious, and reassigning points each time I check the zip code feels weird. Any suggestions are helpful and appreciated.


texts: Critique my JSON-optimizing Python script

texts:
Here's a Python script to optimize JSON documents:

#!/usr/bin/python3

"""jopo - Optimize JSON documents."""

from collections import defaultdict

def optimize(data):
    """Optimize a JSON-like data structure."""
    if isinstance(data, list):
        if len(data) == 1:
            return optimize(data[0])
        digest = defaultdict(lambda: defaultdict(set))
        for element in data:
            if not isinstance(element, dict) or len(element) != 2:
                break
            for key, value in element.items():
                digest[key][type(value)].add(repr(value))
        else:
            if len(digest) == 2:
                pool = {k for k in digest if len(digest[k][str]) == len(data)}
                if pool:
                    if len(pool) > 1:
                        meta = input("Which key (%s)? " % "|".join(pool))
                    else:
                        meta = next(iter(pool))
                    infra = (digest.keys() - {meta}).pop()
                    return {d[meta]: optimize(d[infra]) for d in data}
        return [optimize(x) for x in data]
    if isinstance(data, dict):
        if len(data) == 1:
            return optimize(next(iter(data.values())))
        else:
            return {k: optimize(v) for k, v in data.items()}
    return data

if __name__ == "__main__":
    import json
    import sys
    for arg in sys.argv[1:]:
        with open(arg) as f:
            doc = json.load(f)
        print(json.dumps(optimize(doc), indent=2))

... which, given a JSON document recipes.json like this:

{
  "recipes": [
    {
      "name": "pizza",
      "ingredients": [
        {
          "quantity": "100g",
          "ingredient": "cheese"
        },
        {
          "quantity": "200g",
          "ingredient": "tomato"
        }
      ]
    },
    {
      "name": "pizza 2",
      "ingredients": [
        {
          "quantity": "300g",
          "ingredient": "ham"
        },
        {
          "quantity": "300g",
          "ingredient": "pineapple"
        }
      ]
    }
  ]
}

... is used like this:

$ ./jopo.py recipes.json
Which key (ingredient|quantity)? ingredient
{
  "pizza 2": {
    "ham": "300g",
    "pineapple": "300g"
  },
  "pizza": {
    "tomato": "200g",
    "cheese": "100g"
  }
}

It does two things:

Collapse 1-item objects and arrays.
Reduce arrays of congruent 2-item objects to a single object, if possible.

I think the optimize() function is both too long and too hard to follow.

Obviously I could separate out the if isinstance(data, <type>): # ... blocks into separate functions, but even then, an optimize_list() function along those lines is still going to be quite long and, IMO, somewhat impenetrable.

How can I improve the legibility of this code?


texts:
Can the following complete program be improved? I have been using the Python For Absolute Beginners book and recently made my own version of the Python Word Jumble game.

The Areas I am particularly interested in improving:

The while word Loop Block
Python Standards
Simplifying the overall program
Commenting

# Word Jumble Game. Using Mac0S (Latest). Python V 3.4.3

import random

# Initialize Variables
WORD = ('python', 'programming', 'mug', 'glass','phone') # Constant Variable
word = random.choice(WORD)
correct = word
jumble = ''
guess = ''

print('\t\tWelcome to Word Jumble!')
print('\n')
print('\tUnscramble the letters to make a word.')

while word:
    position = random.randrange(len(word))
    jumble += word[position] # Jumble process 1
    word = word[:position] + word[(position + 1):] #Jumble process 2

print('\n')
print('The Jumble is:', jumble)

guess = input('Your Guess: ')
while guess != correct:
    print('Sorry, that\'s not it')
    guess = input('Your Guess: ')

if guess == correct:
    print('\n')
    print('That\'s it! You guessed it!')
    print('\n')
    print('Thanks for playing')

exit() # User has the correct answer


texts: Generate CSV from multiple files on Regex Python Output

texts:
I have written a python script using regex to extrapolate a poorly formatted text file data table into an actual data table. I am currently printing the output using . C:\my file location\file.csv in the command prompt. Is there a better way to cause my script to run for an entire directory of files and programmatically output each to a .csv file?

Here is the code:

import re

data = open('C:\file.txt', 'rU')

output = [['DEALER CODE', 'DEALER NAME', 'DEALER PHONE', 'DATE', 'CHG DESCRIPTION', 'VIN', 'CURRENT', 'OVER 30-DAYS', 'OVER 60-DAYS', 'OVER 90-DAYS', 'OVER 120-DAYS', 'AGE']]

for line in data:
    dealer_code = re.search(r'(\w\d\d\d\d\d  )', line)
    dealer_code_phone_search = re.search(r'(\d\d\d-\d\d\d-\d\d\d\d)', line)

    if dealer_code and "/" not in line:
        line = line.replace('\n','')
        dealer_code_number = line.split()[0]
        if dealer_code_phone_search:
            dealer_code_phone = dealer_code_phone_search.group(0)
            dealer_name = ''.join(line.split(dealer_code_number)[1:]).strip().split(dealer_code_phone)[0].strip()
        else:
            dealer_code_phone = ''
            dealer_name = ''.join(line.split(dealer_code_number)[1:]).strip()

    elif "/" in line:
        line = line.replace('\n','')
        vin = re.search(r'(\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w)', line)
        if vin:
            date = line.split(vin.group(0))[0].split()[0]
            descp = ' '.join(line.split(vin.group(0))[0].split()[1:])
            rest = line.split(vin.group(0))[1].split()
            vin = vin.group(0)

            new_line = [dealer_code_number, dealer_name, dealer_code_phone, date, descp, vin]
            for i in rest:
                new_line.append(i)

            output.append(new_line)

for line in output:
    print(','.join(line))


texts:
So, I have the boundaries of every states in the US, from the google map KML file.

This KML file is actually a XML file.

I'm converting this file to a JS file compatible with google map in order to draw polygons on my map.

Here is an excerpt from the file with all the coordinates:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
  <Placemark>
    <name>WA</name>
    <description><![CDATA[]]></description>
    <styleUrl>#style37</styleUrl>
    <Polygon>
      <outerBoundaryIs>
        <LinearRing>
          <tessellate>1</tessellate>
          <coordinates>
            -122.402015585862,48.2252165511906
            -122.368333031748,48.1281417374007
            -122.216991980112,48.0074395523983
            -122.230120864997,47.9691133009971
            -122.302922293019,47.9502148146411
            -122.394492319816,47.7741760704507
            -122.414815251142,47.6641799154458
            -122.382220450337,47.5954090424224
            -122.392633724016,47.510242430349
            -122.319738644767,47.3901148739843
            -122.325376306437,47.3443234291417
            -122.420837154063,47.3188444009071
            <!-- etc., 243 points altogether for WA state -->
          </coordinates>
        </LinearRing>
      </outerBoundaryIs>
    </Polygon>
  </Placemark>

Here is my code to convert the KML file to the JS file.

require 'rubygems'
require 'xmlsimple'

def read_xmlfile(file_name)
  file = File.open(file_name, "r")
  data = file.read
  file.close
  return data
end

target  = "states.js"

xml_data = read_xmlfile('Stateborders.xml')

data = XmlSimple.xml_in(xml_data, 'KeyToSymbol' => true)

content = "var stateBorders = {\n"
data[:document][0].each_with_index do |item, index|
  states = item[1]
  states.each_with_index do |state, index|
      name = state[:name][0]
      coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip.gsub(/[\n]/,") ,new google.maps.LatLng(").gsub(" ) ,", "), ");
      coord = state[:polygon][0][:outerboundaryis][0][:linearring][0][:coordinates][0].tr("\t", "").strip
      coord2 = ""
      coord.split("\n").each do |ll|
        ll = ll.split(",")
        lat = ll[1].to_s.strip
        lat = lat.to_f.round(6).to_s
        lon = ll[0].to_s.strip
        lon = lon.to_f.round(6).to_s
        coord2 << "new google.maps.LatLng("+lat+", "+lon+"), "
      end
      statecoord = "'#{name}' : [#{coord2}],".gsub(", ],","],")
      content << statecoord+"\n"
  end
end
content << "};"

File.open(target, "w+") do |f|
  f.write(content)
end

The code itself is fast enough but i'm sure can be much simpler/cleaner. Also for the last state I have ], instead of ].


texts: Fast Prime Sieve (Python Implementation)

texts:
A modified version of the prime sieve. I actually doubt it could be implemented any faster, but I might be wrong:

from math import sqrt

def sieve(n):
    """
        *   A fast implementation of the prime sieve algorithm. Finds all prime numbers up to a given upper bound.

        *   Params:
            *   n: The upper bound.
        *   Return:
            *   A list of all prime numbers in [0, n].
        *   Implementation:
            *   Implements the sieve of Erasthotenes with a few optimisations for speed.
            *   We only delete multiples of numbers up to `int(sqrt(n))`. This suffices to find all prime numbers.
            *   We manipulate a list of boolean values, indexed by the number itself with the values denoting its primality. This is much faster than deleting elements in the list.
    """
    if n < 2:   return []
    prime = [True]*(n + 1)      #Initialise the list.
    rt = int(sqrt(n))+1
    for x in range(2, rt):      #We only need to seive multiples of numbers <= to `n`.
        if prime[x]:
            for c in range(x*x, n + 1, x):      prime[c] = False
    return [idx for idx, p in enumerate(prime) if p][2:]


texts: One-line initialisation for a constant list with all entries except one from another list

texts:
I'm looking to simplify the initialisation of the second constant, preferably to just one line. Any ideas? Anything from Guava or JDK (up to 1.6) is ok to use.

enum Box {
    PROMO_HEADER,
    FREEMIUM,
    EXTRA_STORIES,
    TOP_STORIES,
    TOP_CHARACTERS,
    TOP_THEMES,
    TOP_ARTISTS,
    TOP_ISSUES
    // several more ...
}

final static List<Box> FREEMIUM_BOXES = ImmutableList.copyOf(Box.values());
final static List<Box> DEFAULT_BOXES = initDefaultBoxes(); // All except FREEMIUM

static List<Box> initDefaultBoxes() {
    List<Box> boxes = Lists.newArrayList(FREEMIUM_BOXES);
    boxes.remove(Box.FREEMIUM);
    return ImmutableList.copyOf(boxes);
}

Granted, it's not that bad, but still I'd like to get rid of the init method. :-) (Static initialiser wouldn't be any better.)

NB: I want to define the order of boxes only once, in the enum definition itself, so ImmutableList.of(PROMO_HEADER, EXTRA_STORIES, ...) is not considered a good solution for the purposes of this refactoring.

A single-statement Guava solution would be this, using filter() and a Predicate, but arguably this is less clean than the original, because this kind of stuff is verbose in Java...

final static List<Box> DEFAULT_BOXES =
    ImmutableList.copyOf(Iterables.filter(FREEMIUM_BOXES, new Predicate<Box>() {
        @Override
        public boolean apply(Box box) {
            return box != Box.FREEMIUM;
        }
    }));

Resolution

Went with this, which is the cleanest option considering I indeed need the constants defined as Lists:

final static List<Box> FREEMIUM_BOXES = ImmutableList.copyOf(Box.values());
final static List<Box> DEFAULT_BOXES =
    Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM))).asList();

Props to Xaerxess!


texts: How can I improve performance of my selecting code

texts:
I have a page with a list of items. Items have several actions assigned to them. (see screenshot).

One may choose to directly click on an icon next to each row or check a checkbox on the left hand side and click action above the list.

The issue is that after clicking an item OR checking a checkbox of several items and then clicking an action there is a lag (a second or so). Imagine having 100 rows or more.

Script:

 $("a.action:not(.remove)").click(function (e) { // .remove => do not execute on download tasks page
            var selected = new Array(); // array to hold selections or clicks
            var obj = $(this), objData = obj.data();
            e.preventDefault();
            if (!obj.hasClass('disablelink')) {
                if (objData.ajaxMachineid) {
                    selected.push(objData.ajaxMachineid);
                } else {
                    $("input.checkbox:checkbox:checked:not(.checkall)").each(function () {
                        var checkbox = $(this), machineId = checkbox.val(), packageId = objData.ajaxPackageid.removeSpecialChars().toUpperCase(), operation = objData.ajaxType;
                        var $row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase());
                        if ($row.length) {
                            $row.has("a[data-ajax-type=" + operation + "]:not(.hide)").length ? selected.push(machineId) : $(this).attr('checked', false);
                        }
                    });
                }
                if (selected.length > 0) {
                    // do something more here blah blah blah
                };
            }
            $("input.checkall").attr("checked", false);
        });

Sample HTML of one row:

<input type="checkbox" value="1960" class="checkbox">

GD009000246

PCGames
Up

10.48.1.236

   View
Install
   Remove


texts:
Used classes to make this simple tic tac toe game.

Any improvements?

from itertools import chain

class Field:
    def __init__(self, sequence):
        self.sequence = sequence
        self.rows = [[sequence[i] for i in range(j, j + 3)] for j in range(0, 9, 3)]
        self.columns = [[row[i] for row in self.rows] for i in range(3)]
        self.first_diagonal = self.rows[0][0] + self.rows[1][1] + self.rows[2][2]
        self.second_diagonal = self.rows[0][2] + self.rows[1][1] + self.rows[2][0]
        self.diagonals = [self.first_diagonal, self.second_diagonal]

    def __str__(self):
        return '''\
---------
| {} {} {} |
| {} {} {} |
| {} {} {} |
---------\
'''.format(*self.sequence)

    def get_value(self, x, y):
        return self.rows[x][y]

    def set_value(self, x, y, value):
        self.rows[x][y] = value
        sequence = ''.join(list(chain.from_iterable(self.rows)))

        self.__init__(sequence)  # Reinitializing attributes.

    def get_state(self):

        num_x = self.sequence.lower().count('x')
        num_o = self.sequence.lower().count('o')

        if abs(num_x - num_o) not in {0, 1}:
            return 'Impossible'

        winners = []
        for sequence in chain(self.rows, self.columns, self.diagonals):
            if len(set(sequence)) == 1:
                if sequence[0] not in winners and sequence[0].lower() in ['x', 'o']:
                    winners.append(sequence[0])

        if len(winners) > 1:
            return 'Impossible'
        elif winners:

            return f'{winners[0]} wins'

        # No winner
        else:
            if '_' in self.sequence or ' ' in self.sequence:
                return 'Game not finished'
            else:
                return 'Draw'

def convert_index(x, y):
    x, y = abs(y - 3), x - 1

    return x, y

def make_move(field, move, value):
    try:
        x, y = move.split()
    except ValueError:
        print('You should enter numbers!')
        return False

    if x.isnumeric() and y.isnumeric():
        x, y = int(x), int(y)
        if x in {1, 2, 3} and y in {1, 2, 3}:
            x, y = convert_index(x, y)
            if field.get_value(x, y).lower() not in ['x', 'o']:
                field.set_value(x, y, value)
                return True
            else:
                print('This cell is occupied! Choose another one!')
        else:
            print('Coordinates should be from 1 to 3!')
    else:
        print('You should enter numbers!')

    return False

field = Field('_' * 9)  # Empty field.

i = 1

while True:
    print(field)

    player = 'X' if i % 2 == 1 else 'O'

    ordinates = input()

    if make_move(field, ordinates, player):  # Only change player if a move was successful
        i += 1

    if field.get_state() not in ['Game not finished', 'Impossible']:
        print(field)
        print(field.get_state())
        break

```