texts:
I am trying to write a Python script that download an image from a webpage.  On the webpage (I am using NASA's picture of the day page), a new picture is posted everyday, with different file names. After download, set the image as desktop.

My solutions was to parse the HTML using HTMLParser, looking for "jpg", and write the path and file name of the image to an attribute (named as "output", see code below) of the HTML parser object.

The code works, but I am just looking for comments and advice.  I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.

import urllib2
import ctypes
from HTMLParser import HTMLParser

# Grab image url
response = urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html')
html = response.read()

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        # Only parse the 'anchor' tag.
        if tag == "a":
           # Check the list of defined attributes.
           for name, value in attrs:
               # If href is defined, print it.
               if name == "href":
                   if value[len(value)-3:len(value)]=="jpg":
                       #print value
                       self.output=value

parser = MyHTMLParser()
parser.feed(html)
imgurl='http://apod.nasa.gov/apod/'+parser.output
print imgurl

# Save the file
img = urllib2.urlopen(imgurl)
localFile = open('desktop.jpg', 'wb')
localFile.write(img.read())
localFile.close()

# set to desktop(windows method)
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "desktop.jpg" , 0)


texts:
I've posted a few questions about natas a wargame. But I'm stuck at natas29 it has to do with Perl. I've never coded in Perl before.

Thus to help me beat the last few levels, I decided it is time to learn Perl. And what better way to learn it, then with wargames from overthewire. I made a small Perl program that beats the first few levels of bandit (in combination with some bash commands)

I'm specifically looking for answers that provide insights on how certain Perl operation could be abused, but any review is welcome.

#!/usr/bin/perl
use strict;
use warnings;

use Net::SSH::Perl;

my ($hostname, $username, $password, $port, $command) = ("bandit.labs.overthewire.org", "bandit0", "bandit0", "2220", "");

sub next_level {
    my ($user) = @_;
    $user =~ s/(\d+)\z/ $1 + 1 /e;
    return $user;
}

sub bandit_level {
    my ($pass, $user, $c) = @_;
    my $ssh = Net::SSH::Perl->new("$hostname", port=>$port, debug=>0);
    $ssh->login("$user","$pass");
    my ($stdout, $stderr, $exit) = $ssh->cmd("$c");
    my $new_pass = $stdout;
    return $new_pass;
}

sub read_file {
    my %hash;
    open CONFIG, "commands.txt" or die;
    while (my $line = <CONFIG>) {
        chomp $line;
        my ($lvl, $cmd) = split /\:/, $line;
        $hash{$lvl} = $cmd;
    }
    close CONFIG;
    return %hash;
}

my %hash = read_file;
my $bandit_count = scalar(keys %hash);

while ($bandit_count-- > 0)
{
    print "$username:$password\n";
    $command = $hash{$username};
    $password = bandit_level($password, $username, "$command");
    chomp $password;
    $password =~ s/\s//g;
    $username = next_level($username);
}

With commands.txt being this:

bandit0:cat readme
bandit1:cat ./-
bandit2:cat 'spaces in this filename'
bandit3:cat inhere/.hidden
bandit4:cat inhere/./-file07
bandit5:cat inhere/./maybehere07/.file2
bandit6:cat /var/lib/dpkg/info/bandit7.password
bandit7:cat data.txt | grep millionth | sed -e 's/^millionth//'
bandit8:cat data.txt | sort | uniq -u
bandit9:strings data.txt | grep '=' | cut -d '=' -f11 | tail -c 36
bandit10:base64 -d data.txt

Not yet another perl hacker ;)


texts:
This problem:

  The Shallow Alto city council has organized a special committee to review the traffic situation in the city. Despite the fact that there is nothing whatsoever to do in the city, citizens still write complaints about the amount of time it takes them to get from one unexciting location to the next. The committee has been asked to figure out how long it takes someone to travel down the streets of Shallow Alto given the current traffic light programming. To do this, they want you to write an algorithm which, given the speed a car travels down a road and the timing of the traffic lights, returns the amount of time it takes the car to travel down the street. The traffic lights will be in an int[], with each element representing the amount of time in seconds between signal changes. Initially, all traffic lights have just turned green, and are at the beginning of their cycle. The order of the traffic lights in the int[] will be the order in which a car encounters them. The speed you will be given is in meters per second. Assume that the car starts 150 meters before the first traffic light, that there are 150 meters between each traffic light, and that the car stops 150 meters after the last traffic light. Disregard all acceleration and deceleration; a car is either at its given speed or entirely stopped, and it takes no time to go from one state to the other. If a car reaches a traffic light just as it turns red, it immediately stops and waits for it to turn green again (at which point it starts moving immediately). If the light just turned green, there is no wait and the car drives on through. Return the time, in seconds, that it takes the car to travel the entire distance. Round down any fractional parts, (for example 55.5 becomes 55 and 44.9 becomes 44), but do not do this until returning.

But in F# instead of C#:

namespace TrafficFlow

module Traffic =

    let isGreen currentTime switchItme =
        let state = int currentTime / int switchItme
        state % 2 = 0

    let waitTime (currentTime : float) switchTime =
        match (isGreen currentTime switchTime) with
            | false -> if (currentTime % switchTime) < 0.01 then switchTime else currentTime % switchTime
            | _ -> 0.0

    let time distanceBetween speed  (lights : seq<int>) =
        let timeBetween = float distanceBetween / float speed
        (lights |> Seq.fold (fun acc x -> float acc + timeBetween + waitTime acc (float x) ) timeBetween)

open Traffic
open System

module Program =

    [<EntryPoint>]
    let main argv =

        let distance = 150

        printf "0) time: %d\n" (int (time distance 30  [10; 10; 10]))
        printf "1) time: %d\n" (int (time distance 20  [10; 10; 10]))
        printf "2) time: %d\n" (int (time distance 20  [10; 20; 30]))
        printf "3) time: %d\n" (int (time distance 5  [10; 11; 12; 13; 14; 15]))
        printf "4) time: %d\n" (int (time distance 5  [60; 60; 60; 60; 60; 60; 60; 60; 60; 60]))
        printf "5) time: %d\n" (int (time distance 25  [55;29;26;12;19;39;18;20;23;28;56;20;59;48;33;40;30;60;19]))

        Console.ReadLine() |> ignore

        0 // return an integer exit code


texts:
I am using a code similar to the following example to create a table with tkinter using Python 3:

Each cell is individually created as a ttk.Label and displayed using .grid(row, column)

Some of my values get updated while the program is running with tk.StringVar().set()

Each value is unique and has it's own variable name count1 count2

This example seems short, but in my program I have a few more rows being displayed and each row has 2 StringVar() that I need to keep updated. Overall, it's a very large for loop because it has to check if it's in the correct row & column combination (row 1 column 0 or row 2 column 0) before creating a StringVar().

Any suggestions on how to reduce the size of my for loop?
Are there better ways of creating tables that need a few values consistently updated?

Thank you for your time and Happy Holidays!
import time
import tkinter as tk
import tkinter.ttk as ttk
from threading import Thread

gui = tk.Tk()
gui.geometry('360x270')
gui.configure(bg='white')

style = ttk.Style()
style.theme_create('custom', settings={
    'header.TLabel': {'configure': {
        'background': 'white',
        'foreground': 'dark green',
        'font': 'Times 16 bold',
        'padding': (10, 0)}},
    'TLabel': {'configure': {'background': 'white', 'font': 'Times 12'}},
    'TFrame': {'configure': {'background': 'white'}}})
style.theme_use('custom')

table_frame = ttk.Frame(gui)
table_frame.pack(pady=(36, 0))

values = [('Count', 'Date', 'Time', 'Phrase'),
          ('5', '12/12/10', '03:15', 'blue car'),
          ('13', '09/09/98', '16:20', 'red door')]

total_rows = len(values)
total_columns = len(values[0])

for i in range(total_rows):
    for j in range(total_columns):
        if i == 0:
            label = ttk.Label(table_frame, text=values[i][j], style='header.TLabel')
            label.grid(row=i, column=j)
        elif i == 1:
            if j == 0:
                count1 = tk.StringVar()
                count1.set(values[i][j])
                label = ttk.Label(table_frame, textvariable=count1)
                label.grid(row=i, column=j)
            else:
                label = ttk.Label(table_frame, text=values[i][j])
                label.grid(row=i, column=j)
        elif i == 2:
            if j == 0:
                count2 = tk.StringVar()
                count2.set(values[i][j])
                label = ttk.Label(table_frame, textvariable=count2)
                label.grid(row=i, column=j)
            else:
                label = ttk.Label(table_frame, text=values[i][j])
                label.grid(row=i, column=j)

def increment_count():
    increment_count.status = 'run'

    while increment_count.status == 'run':
        new_minute1 = int(count1.get()) + 1
        count1.set(str(new_minute1))

        new_minute2 = int(count2.get()) - 1
        count2.set(str(new_minute2))

        time.sleep(1)

Thread(target=increment_count).start()

gui.mainloop()
increment_count.status = 'exit'


texts: Function for minimum non-zero with multiple additional conditions

texts:
This function works, but seems unnecessarily complicated.  I would like to simplify but performance is vital as it is called many times.

The conditions are:

  1) If either value is negative, then result is -1

  2) If both values are zero, then result is zero

  3) If NeedMax is true, result is largest value

  4) If NeedMax is false, result is smallest non-zero value

CODE:

Public Function SelValue(ValOne As Long, ValTwo As Long, _
                    Optional NeedMax As Boolean = True) As Long

    If ValOne < 0 Or ValTwo < 0 Then
        SelValue = -1
    ElseIf ValOne = 0 And ValTwo = 0 Then
        SelValue = 0
    ElseIf NeedMax Then
        If ValOne > ValTwo _
            Then SelValue = ValOne _
            Else SelValue = ValTwo
    Else
        If ValOne = 0 Then
            SelValue = ValTwo
        ElseIf ValOne > ValTwo And ValTwo <> 0 Then
            SelValue = ValTwo
        Else
            SelValue = ValOne
        End If
    End If

End Function

Can anyone suggest a more direct, and hopefully faster, approach?


texts:
I have a Python function w/ specified functionality, and two proposed approaches - which do you prefer, and why? (performance, simplicity, clarity, etc) (both use import random)

PROBLEM: Need a plain Python function that accepts an arbitrary number of iterables (tuples, lists, dictionaries), and returns them shuffled in the same order:

a = (1, 2, {3: 4}, 5)
b = [(5,6), [7,8], [9,0], [1,2]]
c = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}

x, y, z = magic(a, b, c)
print(x, y, z, sep='\n')
# ({3: 4}, 1, 2)
# [[9, 0], (5, 6), [7, 8]]
# {0: ('x', 2), 'arrow': 5, 'knee': 'guard'}

The function must:

Return iterables shuffled in the same order (see above)
Accept any number of iterables
Preserve iterables types
Support nested iterables of any depth and type
Not shuffle nested elements themselves (eg. [7,8] above doesn't become [8,7])
Return iterables with length of shortest iterable's length w/o raising error (see above)
Return shuffled iterables in the same order they're passed in (see above)

NOTE: requires Python 3.7. Can work with Python 3.6- if excluding dicts, as dicts aren't ordered.

SOLUTION 1:

def ordered_shuffle(*args):
    args_types = [type(arg) for arg in args]                               # [1]
    _args      = [arg if type(arg)!=dict else arg.items() for arg in args] # [2]
    args_split = [arg for arg in zip(*_args)]                              # [3]
    args_shuffled = random.sample(args_split, len(args_split))             # [4]
    args_shuffled = map(tuple, zip(*args_shuffled))                        # [5]
    return [args_types[i](arg) for i, arg in enumerate(args_shuffled)]     # [6]

Explanation: img

SOLUTION 2:

def shuffle_containers(*args):
    min_length = min(map(len, args))
    idx = list(range(min_length))
    random.shuffle(idx)
    results = []
    for arg in args:
        if isinstance(arg, list):
            results.append([arg[i] for i in idx])
        elif isinstance(arg, tuple):
            results.append(tuple(arg[i] for i in idx))
        elif isinstance(arg, dict):
            items = list(arg.items())
            results.append(dict(items[i] for i in idx))
        else:
            raise ValueError(
                "Encountered", type(arg),
                "expecting only list, dict, or tuple"
            )
    return results


texts:
I have this very simple code which is used to parse values:

public class Connections
{
    public List<Integer> getConnections() throws IOException
    {
        byte[] fileBytes;
        File myFile = new File("/proc/net/sockstat");
        if (myFile.exists())
        {
            try
            {
                fileBytes = Files.readAllBytes(myFile.toPath());
            }
            catch (java.nio.file.AccessDeniedException e)
            {
                return null;
            }

            if (fileBytes.length > 0)
            {
                String doc = new String(fileBytes);

                Pattern p = Pattern.compile("-?\\d+");
                Matcher m = p.matcher(doc);

                List<Integer> list = new ArrayList<>();
                while (m.find())
                {
                    list.add(Integer.valueOf(m.group()));
                }

                return list;
            }
        }
        return null;
    }

}

This code works well but it's using too many slow operations to get the values. Is there a way to improve the code? I would like to use Java 8.


texts: Overloading email sender utility class methods take single or array arguments

texts:
I'm writing a simple utility class for sending an email. I'm not sure what's the proper way to present this to a consumer. Should I force them to use an array in send()? Or should I provide an overload so they can pass a single argument?

public class SimpleSender {

    public static void send(String smtpServer, String[] to, String[] cc, String from,
                            String subject, String body, boolean HTML, String fullFilePath) {
        SendEmail(smtpServer, to, cc, from, subject, body, HTML, fullFilePath);
    }
    public static void send(String smtpServer, String[] to, String[] cc, String from,
                            String subject, String body, boolean HTML) {
        SendEmail(smtpServer, to, cc, from, subject, body, HTML, null);
    }

    // Should I provide this overload and similar ones?
    public static void send(String smtpServer, String to, String[] cc, String from,
                            String subject, String body, boolean HTML) {
        SendEmail(smtpServer, new String[] {to}, cc, from, subject, body, HTML, null);
    }
    private static void SendEmail(String smtpServer, String[] to, String[] cc, String from, String subject, String body, boolean HTML, String fullFilePath) {
     .... Send email
    }
}

I know it's a bit of overkill for just a simple email utility, but in general, what's a good practice for these situations?


texts: Generating random numbers and decks of cards

texts:
So I have some code here:
First a simple random # generator and a array-choosing function:

 function Rand(min,max)
 {
 return parseFloat(Math.floor(Math.random()* max-min+1)))+parseFloat(min);
 }

 function Choose(arr)
 {
//Returns an element from an array at random.
return arr[Math.floor(Math.random()*arr.length)];
 }

and second a Card shuffler:

function CardDeck() {
var Cd=["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"];
var H=[];
var S=[];
var D=[];
var C=[];
var Result=[];
var Dk=document.getElementById("Deck Count").value;
for(i=0;i<Cd.length;i++) {
    S[i]=Cd[i]+" of Spades";
    H[i]=Cd[i]+" of Hearts";
    C[i]=Cd[i]+" of Clubs";
    D[i]=Cd[i]+" of Diamonds";}
if (Dk=="4") {P=S.concat(C,D,H);}
else if (Dk=="5") {
    var St=[];
    for(i=0;i<Cd.length;i++) {St[i]=Cd[i]+" of Stars";}
    P=S.concat(C,D,H,St);}
else if (Dk=="6") {
    var Rk=[];
    var Wh=[];
    for(i=0;i<Cd.length;i++) {
        Rk[i]=Cd[i]+" of Rackets";
        Wh[i]=Cd[i]+" of Wheels";}
    P=S.concat(C,D,H,Rk,Wh);}
for(i=0;i<Dk*Cd.length;i++) {
    var Q=Choose(P);
    R=P.indexOf(Q);
    Result[i]=(i+1)+": "+Q;
    P=P.slice(0,R).concat(P.slice(R+1));}
document.getElementById("Cards").innerHTML=Result.join("\n");}

Is there an easy way to make this faster or at least declare the arrays faster instead of just doing a=[],b=[]...

Additionally, is there a way to get a better RNG with a longer period in base JS (no libraries, as this was built on base JS)


texts:
I'm creating a rectangular prism function, whose output looks like this:

I think that this code can be improved by optimizing the use of np.meshgrid with a Python iterator, but I can't wrap my head around it. It might also be possible to do this with fewer plotting calls, but I can't figure that out either. Ideally, I would change the line drawing to use a Line3DCollection and the areas to use a Patch3DCollection for plotting speed, but I'm still not comfortable enough with the 3D api.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
def rect_prism(x_range, y_range, z_range):
    # TODO: refactor this to use an iterator
    xx, yy = np.meshgrid(x_range, y_range)
    ax.plot_wireframe(xx, yy, z_range[0], color="r")
    ax.plot_surface(xx, yy, z_range[0], color="r", alpha=0.2)
    ax.plot_wireframe(xx, yy, z_range[1], color="r")
    ax.plot_surface(xx, yy, z_range[1], color="r", alpha=0.2)

    yy, zz = np.meshgrid(y_range, z_range)
    ax.plot_wireframe(x_range[0], yy, zz, color="r")
    ax.plot_surface(x_range[0], yy, zz, color="r", alpha=0.2)
    ax.plot_wireframe(x_range[1], yy, zz, color="r")
    ax.plot_surface(x_range[1], yy, zz, color="r", alpha=0.2)

    xx, zz = np.meshgrid(x_range, z_range)
    ax.plot_wireframe(xx, y_range[0], zz, color="r")
    ax.plot_surface(xx, y_range[0], zz, color="r", alpha=0.2)
    ax.plot_wireframe(xx, y_range[1], zz, color="r")
    ax.plot_surface(xx, y_range[1], zz, color="r", alpha=0.2)

rect_prism(np.array([-1, 1]), np.array([-1, 1]), np.array([-0.5, 0.5]))
plt.show()


texts: Creating multiple lists of named tuples based on condition

texts:
I have created a function which is used to create a list of named tuples. The tuple which is created is dependent on the format of 'instructions' in which there are 3 different formats. Instructions is just a list of lists. I wanted to improve the readability/maintainability of this function and had 3 ideas in mind but not sure how to implement them.

Should the named tuple declarations live somewhere outside the function and be called in somehow?
Should list comprehensions be used?
Could this be set up using a factory pattern instead of using the if statements? How would that be done?

Ignoring the naming convention as it's just generic... any further feedback would be much appreciated.

instructions = [['1'],['2','bob','MATCH'],['3','alice','55']]

def assign_tuple_lists(instructions):
    """Creates named tuple lists from instructions"""

    Items = namedtuple('Items', 'timestamp, user, action')
    Cars = namedtuple('Cars', 'timestamp, user, reserve')
    Timing = namedtuple('Timing', 'timestamp')

    items = []
    cars = []
    timing = []
    for instruction in instructions:
        if len(instruction) < 2:
            timing.append(Timing._make(instruction))
        elif instruction[2] == 'MATCH':
            cars.append(Cars._make(instruction))
        else:
            items.append(Items._make(instruction))

    return timing, cars, items

Output:

timing = [Timing(timestamp = '1')]
cars = [Cars(timestamp = '2',user = 'bob',reserve = 'MATCH')]
timing = [Item(timestamp = '3',user = 'alice',action = '55')]


texts: PHP login page using prepared statements

texts:
I am new to the concept of prepared statement and i am trying to adjust my "user login" function to be a prepared statement. The part i am really struggling with is the fact i have multiple SQL queries in the one function and the biggest hurdle right now is fetching from a prepared statement.

Here is the code i have written for the function so far, i do apologise its a mess and i understand there is parts that shouldn't be in there, i just left everything in.

function login_member() {

    $connection = mysqli_connect("localhost", "root", "", "ecom_db");
    if(isset($_POST['login_button'])) {

        $email = filter_var($_POST['log_email'], FILTER_SANITIZE_EMAIL);

        $_SESSION['log_email'] = $email;
        $password = $_POST['log_password'];

        $stmt = $connection->prepare("SELECT email AND password FROM users WHERE email=? AND password=? AND com_code IS NULL");
        $stmt->bind_param('ss', $email, $password);
        $stmt->execute();
        $stmt->bind_result($email, $password);
        $stmt->store_result();
        if($stmt->execute()) {

        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {

            //result is in row

            }

        }
        if($stmt->num_rows == 1) {
            if($stmt->fetch()) {
                while (($row = $res->fetch_assoc()))
                   $username = $row['username'];

            $closed = $connection->prepare("SELECT email AND password FROM users WHERE email=? AND user_closed=?");
            $closed->bind_param('ss', $email, "yes");
            $closed->execute();
            $closed->bind_result($email, "yes");
            $closed->store_result();
            $closed_res = $closed->get_result();

            if($closed->num_rows == 1) {
                $open = $connection->prepare("UPDATE users SET user_closed=? WHERE email=?");
                $open->bind_param('ss', "no", $email);
                $open->execute();
                $open->bind_result("no", $email);
                $open->store_result();
            }

            $_SESSION['username'] = $username;
            header("Location: ../public/member/index.php");
            exit();
        }
        else {
            set_message("Email or password was incorrect");
        }
    }
}

I understand that it looks like a complete mess, i have left all my working outs in there. My main issue here is after my initial statement, i want to be able to fetch the results from the returned row and set the "username" a column in that row to the variable $username.

My original, working code (without prepared statements) is as follows.

My original - without prepared satatements is as follows.

function login_new_member() {

    if(isset($_POST['login_button'])) {

        $email = filter_var($_POST['log_email'], FILTER_SANITIZE_EMAIL); //sanitize email

        $_SESSION['log_email'] = $email; //Store email into session variable
        $password = md5($_POST['log_password']); //Get password md5

        $check_database_query = query("SELECT * FROM users WHERE email='$email' AND password='$password' AND com_code IS NULL");
        confirm($check_database_query);
        $check_login_query = mysqli_num_rows($check_database_query);

        if($check_login_query == 1) {
            $row = mysqli_fetch_array($check_database_query);
            $username = $row['username'];

            $user_closed_query = query("SELECT * FROM users WHERE email='$email' AND user_closed='yes'");
            confirm($user_closed_query);
            if(mysqli_num_rows($user_closed_query) == 1) {
                $reopen_account = query("UPDATE users SET user_closed='no' WHERE email='$email'");
                confirm($reopen_account);
            }

            $_SESSION['username'] = $username;
            header("Location: ../public/member/indexhold.php?register_new");
            exit();
        }
        else {
            echo "Email or password was incorrect";
        }

    }

}


texts:
I'm using the Sieve of Eratosthenes to find primes numbers under N. Is there any performance problems you see with my approach? I used the LinkedList<Integer> because of the performance of removing items to the list while looping through it. Also, I'd want to know if I respect the Java conventions with my code.

import java.util.*;
import java.lang.*;
import java.io.*;

public class PrimeFinders
{
    public static void main (String[] args) throws java.lang.Exception
    {
        LinkedList<Integer> naturalNumbers = new LinkedList<Integer>();
        final int maxNumber = 1000; //This is N

        //Add only uneven numbers, as even numbers won't be prime
        for(int i = 3; i <= maxNumber;i+=2){
            naturalNumbers.add(i);
        }

        int primeIndex = 1; //Starting at 1 since we need to count the number 2, not added in the list
        int primeNumber = 2; //First prime number is 2

        while(naturalNumbers.size() > 0){
            primeNumber = naturalNumbers.pop(); //Always a prime since non-prime numbers are removed in the loop.
            System.out.println("Prime " + primeIndex + " : " + primeNumber);
            applyEratosthenesSieve(primeNumber, naturalNumbers);
            primeIndex++;
        }
    }

    private static void applyEratosthenesSieve(int prime, LinkedList<Integer> numbers){
        Iterator<Integer> numbersIterator = numbers.iterator();

        while(numbersIterator.hasNext()){
            int number = numbersIterator.next();
            if(number % prime == 0){ //Remove all multiples of the number.
                numbersIterator.remove();
            }
        }
    }
}


texts:
Here's the Rabin-Karp implementation that I've written in Python:
from functools import lru_cache
from itertools import islice
from typing import List, Optional

BASE = 139
MOD = 2 ** 31 - 1

@lru_cache(maxsize=None)
def char_to_int(c: str) -> int:
    return ord(c) + 1

def calculate_hash(s: str, length: Optional[int] = None) -> int:
    ret_hash = 0
    if length is not None:
        s = islice(s, 0, length)
    power = len(s) - 1 if length is None else length - 1
    for i, c in enumerate(s):
        ret_hash += char_to_int(c) * BASE ** power
        power -= 1
    return ret_hash % MOD

def roll_hash(prev_hash: int, prev_char: int, next_char: str, length: int) -> int:
    new_hash = ((prev_hash - char_to_int(prev_char) * BASE ** (length - 1)) * BASE) % MOD
    new_hash += char_to_int(next_char)
    return new_hash % MOD

def rabin_karp(text: str, pattern: str) -> List[int]:
    """
    Returns a list of indices where each entry corresponds to the starting index of a
    substring of `text` that exactly matches `pattern`
    """
    p_hash = calculate_hash(pattern)
    n = len(pattern)
    curr_hash = calculate_hash(text, n)
    indices = []
    if p_hash == curr_hash:
        indices.append(0)
    for i in range(1, len(text) - n + 1):
        curr_hash = roll_hash(
            curr_hash, text[i - 1], text[i + n - 1], n
        )
        if p_hash == curr_hash:
            indices.append(i)
    return indices

if __name__ == "__main__":
    with open("lorem_ipsum.txt", "r") as f:
        text = f.read()
    pattern = "lorem"
    indices = rabin_karp(text, pattern)
    print(f"indices: {indices}")

I'm trying to optimize the code as much as possible, so I've tried to do some dynamic code analysis to better understand bottlenecks. I used cProfile to understand the function calls and made changes to the code accordingly to arrive at the above code. Here is the final output from cProfile:
Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    60301    0.091    0.000    0.091    0.000 rabin_karp.py:25(roll_hash)
        1    0.035    0.035    0.126    0.126 rabin_karp.py:30(rabin_karp)
       42    0.000    0.000    0.000    0.000 rabin_karp.py:11(char_to_int)
        2    0.000    0.000    0.000    0.000 rabin_karp.py:15(calculate_hash)
       57    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
       42    0.000    0.000    0.000    0.000 {built-in method builtins.ord}
        3    0.000    0.000    0.000    0.000 {built-in method builtins.len}

Are there any other ways I could further optimize the code? Another interesting thing of note is that adding @lru_cache actually increases execution time as measured by timeit despite the caching mechanism reducing the number of functions calls to char_to_int() (from 120612 to 42).


texts: Save 2 related models through a single form

texts:
Here are two models - Property and Developer:

class Property(models.Model):
    property_type = models.CharField(max_length=255, default='Apartment')
    specifications = models.CharField(max_length=255, default='Basic')
    built_up_area = models.FloatField(max_length=6, null=False)
    total_area = models.FloatField(null=False)
    number_of_bedrooms = models.CharField(max_length=3, default=1)
    number_of_bathrooms = models.CharField(max_length=3, default=1)
    number_of_parking_spaces = models.CharField(max_length=2, default=0)
    address_line_one = models.CharField(max_length=255, null=False)
    address_line_two = models.CharField(max_length=255, default=None)
    city = models.CharField(max_length=255, null=False)
    state = models.CharField(max_length=255, null=False)
    pin_code = models.CharField(max_length=20, null=False)
    developer = models.ForeignKey('Developer')

    connectivity = models.CharField(max_length=255, default=None, null=True)
    neighborhood_quality = models.CharField(max_length=255, default=None, null=True)
    comments = models.CharField(max_length=255, default=None, null=True)

    def __unicode__(self):
        return self.property_type

class Developer(models.Model):
    name = models.CharField(max_length=255, null=False)

    def __unicode__(self):
        return self.name

And here is its corresponding form:

class PropertyForm(ModelForm):
    developer = forms.CharField()

    class Meta:
        model = Property
        fields = [
            'built_up_area',
            'total_area',
            'number_of_bedrooms',
            'number_of_bathrooms',
            'number_of_parking_spaces',
            'address_line_one',
            'address_line_two',
            'city',
            'state',
            'pin_code',
        ]
        widgets = {
            'number_of_bedrooms': forms.Select(
                choices=((1, 1,), (2, 2), (3, 3)), ),
            'number_of_bathrooms': forms.Select(
                choices=((1, 1,), (2, 2), (3, 3)), ),
            'number_of_parking_spaces': forms.Select(
                choices=((1, 1,), (2, 2), (3, 3)), ),
            'developer': forms.TextInput(),
        }

    def __init__(self, *args, **kwargs):
        super(PropertyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.fields['address_line_two'].required = False,
        self.helper.layout = Layout(
            AppendedText('built_up_area', 'sq ft'),
            AppendedText('total_area', 'sq ft'),
            'number_of_bedrooms',
            'number_of_bathrooms',
            'number_of_parking_spaces',
            'address_line_one',
            'address_line_two',
            'city',
            'state',
            'pin_code',
            'developer',
            ButtonHolder(
                Submit('Submit', 'submit', css_class='btn-block')
            )
        )

    def save(self, commit=True):
        developer = self.cleaned_data['developer']
        developer, created = Developer.objects.get_or_create(name=developer)
        self.instance.developer = developer

        return super(PropertyForm, self).save()

What could be a better way to save related objects using a single form?


texts: Implementation in js to find if N can be written as X ^Y , N<100

texts:
From past year ,i have been mainly working on Js, and so have started implementing Algo Questions in js .can it be implemented in a better way.

/**
* Implementaion to find if a number can be expressed as x^y
* x is assumed to be >=0
*/

var canBeExpressedAsXraisedToY = function (n) {
if (n == 0 && n == 1) {
    console.log("Supplied 0 or 1");
    return true;
}
else if (n > 1) {
    var x = 2, prod = 1,y = 1;
    while (prod < n) {

        while (prod < n ) {

            prod = Math.pow(x,y);
            console.log('prod:',prod,'y:', y ,'x:',x)
            if (prod == n) {
                console.log('it can be expressed as x:', x, 'in terms of:', y);
                return true;
                break;
            }
          y++;
        }
        x++;
    }

    console.log("the number cannot be expressed as x ^ y ");
    return false;
}
else { // to handle negative cases .
    console.log('the number given is not supported ');
    return false;
}
}

console.log(canBeExpressedAsXraisedToY(4));
console.log(canBeExpressedAsXraisedToY(67));
console.log(canBeExpressedAsXraisedToY(64));


texts:
I'm just curious if this is clear to the average person.

template<typename IteratorType>
inline IteratorType skip_over(
    IteratorType begin,
    IteratorType end,
    typename std::iterator_traits<IteratorType>::value_type skippedCharacter)
{
    typedef typename std::iterator_traits<IteratorType>::value_type value_type;
    return std::find_if(begin, end,
            std::not1(
                 std::bind2nd(std::equal_to<value_type>(), skippedCharacter)
            )
        );
}


texts:
I have a windows forms application which needs customized dll files to be built and for that I am using an online builder using asp.net. I am in no way a asp.net expert not even near a beginner but this is what I have come up with so far:

All the work is done by the Handler:

public void ProcessRequest(HttpContext context)
    {
        var assembly = AssemblyDefinition.ReadAssembly(context.Server.MapPath("D2.dll"));

        var ctor = assembly.MainModule.Types.FirstOrDefault(t => t.FullName.Contains("ClassName") && t.Namespace.Contains("NameSpace"))
            .Methods.FirstOrDefault(m => m.FullName.Contains("ctor"));

        // Update Instructions
        ctor.Body.Instructions[1].Operand = context.Request["A"];
        ctor.Body.Instructions[4].Operand = context.Request["GM"];
        ctor.Body.Instructions[7].Operand = context.Request["GI"];
        ctor.Body.Instructions[10].Operand = context.Request["U"];
        ctor.Body.Instructions[13].Operand = context.Request["CT"];
        ctor.Body.Instructions[16].Operand = context.Request["MT"];
        ctor.Body.Instructions[19].Operand = context.Request["D"];

        // Optimize the Body - Required to allow proper build
        ctor.Body.OptimizeMacros();
        ctor.Body.SimplifyMacros();

        // Write the Assembly to Stream so it can be converted to Byte[]
        var memstream = new MemoryStream();
        assembly.Write(memstream);

        // Clear existing response.
        context.Response.Clear();

        // Write new response.
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", "attachment; filename=Build.dll");
        context.Response.AddHeader("Content-Length", memstream.Length.ToString());
        context.Response.BinaryWrite(memstream.ToArray());
    }

Currently using this approach/model I have a lot of problems mainly debugging and fixing errors.

I want to improve on this but due to my lack of knowledge in web applications I see no clear path to choose. I have looked at SignalR and it seems like a better approach as it can provide features such as Progress Responses from the server. But still I am confused.


texts: How to manipulate directories using Python

texts:
I'm using the following lump of code to manage a 9.4gb dataset.  I had to divide the dataset into multiple github repositories to be able to do this. I've explained what each block of code does.

git_repo_tags = ['AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X']
counter = 1

# Cloning the github repositories
print('Beginning cloning...')
for repo in git_repo_tags:
  git.Git('.').clone('git://github.com/utility-repos/' + repo)
  print('-\nCloning ' + repo)

  #Removing the .git folder from each repo
  shutil.rmtree(repo + '/.git')
  print('--Removing the .git folder ' + str(counter) + '/8')
  counter += 1

# Creating the Food-101/images directory and subdirectory if it doesn't already exist
if not os.path.exists('Food-101/images'):
    os.makedirs('Food-101/images')
    print('Created the Food-101/images')

    # Going through the repo X and moving everything a branch up
    for i in os.listdir('X'):
      shutil.move(os.path.join('X', i), 'Food-101')
      print('Moved important files to an upper branch')

    # Going through the other repos and moving everything to Food-101/images
    for directory in git_repo_tags:
      for subdirectory in os.listdir(directory):
        shutil.move(os.path.join(directory, subdirectory), 'Food-101/images')
        print('Moving ' + subdirectory + ' to Food-101/images')

#After the above code is complete, moves all test images to the Food-101/test folder and renames them
print('\n-Beginning to separate the test dataset...')
if not os.path.exists('Food-101/test'):
    os.makedirs('Food-101/test')

with open('Food-101/meta/test.txt') as test_file:
  for line in test_file:
    name_of_folder = line.split('/')[0]
    name_of_file = line.split('/')[1].rstrip()
    Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/test/' + name_of_folder + '_' + name_of_file + '.jpg')
    print('--Moved Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg to Food-101/test/')

# Moves all training images to the Food-101/images directory and renames them
print('\n-Beginning to separate the training dataset...')
with open('Food-101/meta/train.txt') as train_file:

  for line in train_file:
    name_of_folder = line.split('/')[0]
    name_of_file = line.split('/')[1].rstrip()
    Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/images/' + name_of_folder + '_' + name_of_file + '.jpg')
    print('--Moved Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg to Food-101/train/')

# Removes empty directories inside Food-101/images
with open('Food-101/meta/train.txt') as train_file:
  for folder in train_file:
    name_of_folder = folder.split('/')[0]
    if os.path.exists('Food-101/images/' + name_of_folder):
      shutil.rmtree('Food-101/images/' + name_of_folder)

# Removes empty directories
for dirs in git_repo_tags:
  shutil.rmtree(dirs)

This code works but its a mess and I have too many repeats.  What is a good way to clean this up?


texts:
I have two arrays:

$row
$rowTwo

The only difference between these two arrays are the first two keys have slightly different names due problems out of my control.

I'm wondering if there is a cleaner way to do it. Or would it be simply easier to find a way to rename the arrays to match?

        $needUpdate = false;

        if (strcasecmp( $row['Trelease'] , $rowTwo['release'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['dateTime'] , $rowTwo['date'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['defectID'] , $rowTwo['defectID'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['type'] , $rowTwo['type'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['severity'] , $rowTwo['severity'] ) != 0) {
            $needUpdate = true;
        } else if (strcasecmp( $row['summary'] , $rowTwo['summary'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['status'] , $rowTwo['status'] ) != 0) {
            $needUpdate = true;
        }  else if (strcasecmp( $row['link'] , $rowTwo['link'] ) != 0) {
            $needUpdate = true;
        }


texts: Abstract Data Type: Stack implementation in C++

texts:
While trying to get better at C++ I tried my hand at making a stack implementation. This is the result:

#include<iostream>

template<typename T>
struct Node {
    T data;
    Node *next;
    Node(T data, Node *next) : data(data), next(next) {}
};

template<typename T>
class Stack {
    public:
        Stack() : top(nullptr), level(0), max_size(10) {}
        Stack(int max_size) : top(nullptr), level(0), max_size(max_size) {};
        void push(T data);
        T pop();
        void display();
        bool isEmpty() { return level == 0; }
        bool isFull() { return level == max_size; }
        int geLevel() { return level; }
        int getMaxSize() { return max_size; }

    private:
        Node<T> *top;
        int level, max_size;
};

template<typename T>
void Stack<T>::push(T data) {
    if(!isFull()) {
        Node<T> *newNode = new Node<T>(data, top);
        top = newNode;
        level++;
    } else {
        std::cerr << "stack overflow";
    }

}

template<typename T>
T Stack<T>::pop() {
    if(!isEmpty()) {
        Node<T> *temp = top;
        T data = temp->data;
        top = top->next;
        level--;
        delete temp;
        return data;
    }

    std::cerr << "stack underflow";

}

template<typename T>
void Stack<T>::display() {
    Node<T> *curr = top;
    while(curr != nullptr) {
        std::cout << curr->data << std::endl;
        curr = curr->next;
    }
}

Any help would be appreciated to make this code mor C++'ish.


texts: Insert and Remove Element in Deque using threads in C++

texts:
The following code works fine for inserting and removing an element from a deque using two threads.

I would appreciate any help on how to make it better, especially in terms of thread safety.

#include "stdafx.h"
#include <deque>

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

#define SLEEP_TIME 1

std::deque <int> q;
std::mutex _mu;
std::condition_variable cond;

void function1()
{
    int count = 10;

    while (count > 0)
    {

        std::unique_lock <std::mutex> locker(_mu);
        q.push_front(count);
        locker.unlock();
        cond.notify_one();
        std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME));

        count--;
    }

    return;
}

void function2()
{
    int data = 0;

    while (data != 1)
    {
        std::unique_lock<std::mutex> locker(_mu);
        cond.wait(locker);

        data = q.back();
        q.pop_back();
        locker.unlock(),

        std::cout << "T2 gets " << data << " from T1" << std::endl;
    }

    return;

}

int main() {

    std::thread t2(function1);
    std::thread t1(function2);

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

    std::cout << "Thread Function Executed Successfully" << std::endl;
}


texts:
I'm working on a webapp in ScalaJS and want to create a query url for requesting some JSON.

Right now I'm using a method called urlBuilder to take the query options from an Options case class and return a String that represents a usable query URL. The urlBuilder method, despite my best efforts, has become somewhat ugly.

Am I missing out on any syntactic sugar or language features that could make this a little easier to understand/cleaner looking? Is pattern matching + string interpolation the best strategy here?

case class GameRegions(americas: Boolean, europe: Boolean, asia: Boolean)

case class Options(startRank: Option[Int], endRank: Option[Int], startDate: Option[Date], endDate: Option[Date], startTime: Option[Date], endTime: Option[Date], regions: GameRegions, gameMode: Boolean)

//Builds the URL based on the provided options object
def urlBuilder(baseUrl: String, o: Options): String = {
  baseUrl + "?" + (o.startRank match {
    case Some(x) => s"rank[0]=$x&"
    case None => ""
  }) + (o.endRank match {
    case Some(x) => s"rank[1]=$x&"
    case None => ""
  }) + (o.startDate match {
    case Some(x) => s"added[0]=@${x.getTime / 1000}&"
    case None => ""
  }) + (o.endDate match {
    case Some(x) => s"added[1]=@${x.getTime / 1000}&"
    case None => ""
  }) + (o.startTime match {
    case Some(x) => s"time[0]=@${x.getTime / 1000}&"
    case None => ""
  }) + (o.endTime match {
    case Some(x) => s"time[1]=@${x.getTime / 1000}&"
    case None => ""
  }) + (o.regions match {
    case GameRegions(false, false, false) => ""
    case GameRegions(x, y, z) => {
      var i: Int = -1
      if (x) {
        i = i + 1
        s"region[$i]=Americas&"
      } else {
        ""
      } + (if (y) {
        i = i + 1
        s"region[$i]=Europe&"
      } else {
        ""
      }) + (if (z) {
        i = i + 1
        s"region[$i]=Asia&"
      } else {
        ""
      }) + "&"
    }
  }) + s"format[0]=${if (o.gameMode) "Standard" else "Wild"}"
}


texts:
I want to perform a filter on a DataGridView using 3 different TextBox.
The solution below works, but does not consider very effective and good. Is there a way to improve it?

private void textBoxCod_TextChanged(object sender, EventArgs e)
{
    Filter();
}

private void textBoxArt_TextChanged(object sender, EventArgs e)
{
    Filter();
}

private void textBoxDesc_TextChanged(object sender, EventArgs e)
{
    Filter();
}

private void Filter()
{
    string queryFilter = "1=1"; //With this we avoid to check if there is the AND in the query
    var filterCod = textBoxCod.Text;
    var filterArt = textBoxArt.Text;
    var filterDescr = textBoxDesc.Text();
    if (filterCod != "")
        queryFilter += " AND product_code LIKE '%" + filterCod + "%'";
    if(filterArt != "")
        queryFilter += " AND article LIKE '%" + filterArt + "%'";
    if (filterDescr != "")
        queryFilter += " AND description LIKE '%" + filterDescr + "%'";

    bSource.Filter = queryFilter;
    dataGridView.DataSource = bSource;
}

Before I used the string.Format but I realized that not having optional parameters could not combine several filters.


texts: is there way to make faster to write to a file?

texts:
with open(filepath) as fp:
   #line = fp.readline()
   cnt = 1
   while line:
       line = fp.readline()
       print("Line {}%: {}".format(cnt, line.strip()))

       line = line.replace('\n', '')
       #print('line->',line)
       rst = read_ct[read_ct['user_id']==line]
       #print(rst)
       if rst.shape[0] != 0:
           AI = rst.iloc[0,1]
       else:
           AI ='32'
       index=df2[df2['id']==AI].index[0]

       df['distances'] = cosine_similarity(df, df.iloc[0:index])
       n = 1000 # or however many you want
       n_largest = df['distances'].nlargest(n + 1) # this contains the parent itself as the most similar entry, hence n+1 to get n children

       file.write(line)
       #file.writelines([df2.at[i,'article_id'] for i in list(n_largest.index)])

       for i in list(n_largest.index):
            file.write(" "+df2.at[i,'article_id'])

       file.write('\n')
       #break
       cnt += 1

I'm trying to write some preprocessed data to the file
but it takes too long so want to gather the idea to make it faster

its writing 1000 results for each ID
want to know how to make this code "faster"


texts:
I'm fairly new to Angular 2 and I started off with creating a clock for my app. I tried to stick to the official documentation tutorial.

Folder structure:

The CSS file is still empty and the HTML is not very spectacular:

<p>{{time | date:'HH:mm' }}</p>

The clock component itself looks like this:

import {Component} from "@angular/core";
import {ClockService} from "./clock.service";

@Component({
  selector: 'clock',
  templateUrl: './clock.component.html',
  styleUrls: ['./clock.component.css']
})
export class Clock {

  time: Date;

  constructor(private clockService: ClockService) {
  }

  ngOnInit() {
    this.clockService.getClock().subscribe(time => this.time = time);
  }

}

The most important part, however, is the service, which looks like this:

import {Injectable} from "@angular/core";
import {Observable} from "rxjs";

@Injectable()
export class ClockService {

  private clock: Observable<Date>;

  constructor() {
    this.clock = Observable.interval(1000).map(tick => new Date()).share();
  }

  getClock(): Observable<Date> {
    return this.clock;
  }

}

Basically, I need a general review since this is my very first approach. However, what I'm really curious about is if I get the usage of the Observable right. Is it correct to store it as a private field like shown above? Am I doing the .share() correctly?


texts: Reading words and counting their occurence in Java

texts:
I have very typical problem:

Given big text file, containing text. The task is to calculate occurence of each word and print this info from most occured to less.

Example input:

cat cat cat dog dog mouse

Correct answer:

cat -> 3
dog -> 2
mouse -> 1

First I solved this using Scanner. But this solutions seems to be slow, cause IO was blocking.

After some time and cookie spent I wrote this solution:

final Path path = FileSystems.getDefault().getPath("/tmp/", "file.txt");

Map<String, Long> occ =
  Files
    .lines(path)
    .flatMap(line -> Arrays.stream(line.split(delimRegex)))
    .filter(line -> line.length() > 0)
    .map(String::toLowerCase)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

occ
  .entrySet()
  .stream()
  .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
  .forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));

I think solution is good (but not sure). Is there any other optimization techniques I've ignored?


texts:
I saw this article that proposes a refactoring exercise and thought I'd give it a try.

Spoiler alert: I'm going to show my solution to the Kata below. You might want to attempt the Kata yourself before you look at this code, so this will not influence you in any way.

I ended up with the following three classes:

Person.cs

public class Person
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public bool IsOlderThan(Person person2)
    {
        return BirthDate > person2.BirthDate;
    }
}

Pair.cs

public class Pair
{
    public Person Person1 { get; set; }
    public Person Person2 { get; set; }
    public TimeSpan AgeDifference { get { return Person2.BirthDate - Person1.BirthDate; } }

    public Pair(Person person1, Person person2)
    {
        if (person1.IsOlderThan(person2))
        {
            Person1 = person2;
            Person2 = person1;
        }
        else
        {
            Person1 = person1;
            Person2 = person2;
        }
    }

    public Pair()
    {
        Person1 = Person2 = null;
    }
}

Finder.cs

public class Finder
{
    private readonly List<Person> _person;

    public Finder(List<Person> person)
    {
        _person = person;
    }

    public Pair FindClosestAgeInterval()
    {
        return Find(pairs => pairs.OrderBy(p => p.AgeDifference).FirstOrDefault());
    }

    public Pair FindFurthestAgeInterval()
    {
        return Find(pairs => pairs.OrderByDescending(p => p.AgeDifference).FirstOrDefault());
    }

    public Pair Find(Func<IEnumerable<Pair>, Pair> pairSelectionLambda)
    {
        var availableDistinctPairs = GetDistinctPairs();

        return pairSelectionLambda(availableDistinctPairs) ?? new Pair();
    }

    private IEnumerable<Pair> GetDistinctPairs()
    {
        for (var i = 0; i < _person.Count - 1; i++)
            for (var j = i + 1; j < _person.Count; j++)
                yield return new Pair(_person[i], _person[j]);
    }
}

The test class basically remained the same (except that I have updated it with the new class/method names).

Overall I think this code is OK (it passes the tests and I could easily understand it 6 months from now).

However, I'm interested to hear your critic opinions, to find out how it can get better.


texts:
I started learning C a week ago, and here is my implementation for the split function:

char** my_split(const char* str, char delim, int* size)
{
    int index = 0, start;
    char** results = NULL;
    *size = 0;

    do
    {
        if ((*size) % 10 == 0) //top floor reached
        {
            results = realloc(results, ((*size) + 10) * sizeof(char*)); //extend the space for another 10 pointers
            if (results == NULL) //if failed, return NULL
                return NULL;
        }
        start = index;
        while (str[index] != delim && str[index]) //find the delimeter or end of string
        {
            index++;
        }

        int length = index - start; //length of matching string
        results[*size] = malloc((length + 1) * sizeof(char)); //allocate memory in the size of the string, and another char for '\0'
        if (results[*size] == NULL) //if failed, return NULL
            return NULL;

        strncpy(results[*size], &str[start], length); //copy the matching string to the array
        results[*size][length] = 0; //end the string
        (*size)++; //add 1 to the total size
    } while (str[index++]);

    results = realloc(results, (*size) * sizeof(char*)); //trim unused bytes
    return results;
}

Is there anything I could do better (memory, performance and error handling)? Maybe in the logic of the function?

Also, feel free to criticize my writing style, as I want it to be more readable and "correct".


texts:
I am a Math tutor and I found the site https://www.yksityisopetus.fi/ where one can search pupils. I made a Python parser to find pupils that want Math teaching with at least 25 €/hour. Are there any improvements for this code?
import requests
import tkinter as tk

link = "https://www.yksityisopetus.fi/opiskelijat/matematiikka/min-25-per-tunti/uusin-ensin"
f = requests.get(link)
lista = f.text.split('\n')
ilmot = []
for i in range(len(lista)):
    if "<a href=\"/" in lista[i] and "<a href=\"/opettajat" not in lista[i] and "")
    for j in range(len(f)):
        if f[j] == '\n<br /':
            parsittu.append(f[j+1])
s = ""
parsilmot = []
for i in range(len(parsittu)):
    if parsittu[i].endswith('</div'):
        parsilmot.append(parsittu[i][0:len(parsittu[i])-5])

p = list(set(parsilmot))
quote = ""
for i in p:
    quote += i+"\n"

root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=4, width=100)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
T.insert(tk.END, quote)
tk.mainloop()


texts: Calculating frequency of a note from a string

texts:
I've been working on a solution to Pset3 of CS50 Harvard course for last couple of hours and managed to finish it. Although it works as intended I'm unhappy with how clean this code is, mostly because of use of multiple nested conditionals inside the main switch case. The function takes a string, for example "B#3", and converts it to correct frequency.

If interested here is the Pset and here is the frequency table.

// Calculates frequency (in Hz) of a note
int frequency(string note)
{
    const double a4Frequency = 440;
    char key;
    float numOfSemitones = 0;
    double octave = 0;
    bool flat, sharp;

    // Determine octave and whether key is sharp or flat
    if (note[1] == 'b')
    {
        octave = note[2] - '0';
        flat = true;
    }
    else if(note[1] == '#')
    {
        octave = note[2] - '0';
        sharp = true;
    }
    else
        octave = note[1] - '0';

    key = note[0];

    // Base frequency knowing that A4 is 440 hz
    if(((key == 'A') && (octave == 4)) && ((!flat) && (!sharp)))
        return 440;

    // TODO find alternative way to count distance between keys - there is a pattern
    // Count frequency using distance in semitones from A4
    double frequency = 0.0;
    switch(key)
    {
        case 'B':
            if (flat)
                numOfSemitones = 1;
            else
                numOfSemitones = 2;

            frequency = pow(2, (numOfSemitones / 12))  * a4Frequency;
            break;
        case 'A':
            if (flat){
                numOfSemitones = 1;
                frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            }
            else if (sharp){
                numOfSemitones = 1;
                frequency = pow(2, (numOfSemitones / 12))  * a4Frequency;
            }
            else
                frequency = a4Frequency;

            break;
        case 'G':
            if (flat)
                numOfSemitones = 3;
            else if (sharp)
                numOfSemitones = 1;
            else
                numOfSemitones = 2;

            frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            break;
        case 'F':
            if (sharp)
                numOfSemitones = 3;
            else
                numOfSemitones = 4;

            frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            break;
        case 'E':
            if (flat)
                numOfSemitones = 6;
            else
                numOfSemitones = 5;

            frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            break;
        case 'D':
            if (flat)
                numOfSemitones = 8;
            else if (sharp)
                numOfSemitones = 6;
            else
                numOfSemitones = 7;

            frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            break;
        case 'C':
            if (sharp)
                numOfSemitones = 8;
            else
                numOfSemitones = 9;

            frequency = a4Frequency / pow(2, (numOfSemitones / 12));
            break;
    }

    // Multiply or divide frequency to get note in correct octave
    int final;
    if (octave > 4)
    {
        octave = pow(2, (octave - 4));
        final = round(frequency * octave);
    }
    else if (octave == 4)
    {
        octave = 0.0;
        final = round(frequency);
    }
    else
    {
        octave = pow(2, (4 - octave));
        final = round(frequency / octave);
    }
    return final;
}

I'm trying to focus on writing clean code from start, yet this solutions seems a bit hacked to me. How can I make this code more readable? What's the alternative to nested conditionals? What's "illegal" about this code?


texts:
I have created a small script that:

Creates a lot of random points.
Runs a small brute force search to find a rect that has a low error, that is a good fit for the data.
Runs a linear regression on the rect generated with brute force to further reduce the error.
Prints out information and plots the data.

Down here you can see an example graph: the random points in blue, the brute forced rect, in blue, the 'linear regressed' rect in green.

from __future__ import division
import random
import matplotlib.pyplot as p
import numpy as np

def random_point():
    return (random.random(),random.random())

def list_of_random_points(n):
    return [random_point() for _ in range(n)]

def error_of_point(point,function):
    x,y = point[0],point[1]
    return abs(y - function(x))

def error_of_list_of_points(points,function):
    return sum((error_of_point(point,function) for point in points))

def get_starting_rect(points):
    min_error = 10**10
    for m1 in range(-10,10):
        for q1 in range(-10,10):
            m,q = m1/10,q1/10
            function = lambda x: m*x + q
            if error_of_list_of_points(points,function) < min_error:
                min_error = error_of_list_of_points(points,function)
                best_mq = m,q
    return best_mq

def get_approximate_m(m,q,points,sensibility):
    if error_of_list_of_points(points,lambda x: (m+sensibility)*x+q) < error_of_list_of_points(points,lambda x: m*x + q):
        m += sensibility
    elif error_of_list_of_points(points,lambda x: (m-sensibility)*x+q) < error_of_list_of_points(points,lambda x: m*x + q):
        m -= sensibility
    return m

def get_approximate_q(m,q,points,sensibility):
    if error_of_list_of_points(points,lambda x: (m)*x+q+sensibility) < error_of_list_of_points(points,lambda x: m*x + q):
        q += sensibility
    elif error_of_list_of_points(points,lambda x: (m)*x+q-sensibility) < error_of_list_of_points(points,lambda x: m*x + q):
        q -= sensibility
    return q

def approximate_better_m_and_q(m,q,points,sensibility):
    for _ in range(100):
        m = get_approximate_m(m,q,points,sensibility)
        q = get_approximate_q(m,q,points,sensibility)
    sensibility /= 10
    for _ in range(100):
        m = get_approximate_m(m,q,points,sensibility)
        q = get_approximate_q(m,q,points,sensibility)
    return m,q

def plot_rect(m,q):
    x = np.arange(0,1,0.1)
    y = [i*m + q for  i in x]
    p.plot(x,y)

def plot_rect_and_points(rect,points):
    p.scatter(*zip(*points))
    m,q = rect
    plot_rect(m,q)

def main():
    NUMBER_OF_POINTS = 1000
    points = list_of_random_points(NUMBER_OF_POINTS)

    m,q = get_starting_rect(points)
    plot_rect(m,q)

    print("""The rect generated with brute force of equation y = {}x + {}
has an error of {}""".format(m,q,error_of_list_of_points(points,lambda x: m*x + q)))

    better_rect = approximate_better_m_and_q(m,q,points,0.1)
    m,q = better_rect
    print("""The rect generated with linear regression of equation y = {}x + {}
starting from the rect generated with
brute force has an error of {}""".format(
    m,q,error_of_list_of_points(points,lambda x: m*x + q)))

    plot_rect_and_points((m,q),points)
    p.show()

if __name__ == "__main__":
    main()


texts:
I have this helper method that generates an HTML calendar based on the current day:

module PageHelper
  def calendar(date)
    cal = "

"
    days = %w(Sun Mon Tue Wed Thu Fri Sat)
    days.each do |day|
      cal += "#{day}	"
    end
    cal+= '

'
    #end of table head
    first_day = date.at_beginning_of_month.strftime('%w').to_i
    last_day = date.at_end_of_month.strftime('%d').to_i
    last_day_week = date.at_end_of_month.strftime('%w').to_i
    current_day = date.strftime("%d").to_i
    prev_month_day = (date - 1.month).at_end_of_month.strftime('%d').to_i
    # print first row
    first_day.times do |day|
      num = prev_month_day - first_day + day + 1
      cal += "#{num}	"
    end
    (7-first_day).times do |day|
      if day == current_day -1
        cal += "#{day+1}	"
      else
        cal += "#{day+1}	"
      end
    end
    # print remaining rows
    cal += '
'
    (7-first_day).upto(last_day-1).each_slice(7) do |slice|
      cal += '
'
      slice.each do |day|
        if day == current_day -1
          cal += "#{day+1}</day>"
        else
          cal += "#{day+1}	"
        end
      end
      cal += '
' unless slice.last == last_day -1
    end
    # get remaining number of cells
    rem_cells = 6 - last_day_week
    if rem_cells && rem_cells != 6
      rem_cells.times do |day|
        cal += "#{day+1}	"
      end
    end
    cal += '

'
  end
end

The method is called like this:

<%=  calendar(Date.today).html_safe %>

Here is an example calendar:

However, I think that my code is not very DRY and the method is unnecessarily longer than what it should be.


texts:
Implement a feature for a text editor to find errors in the usage of brackets in the code.

Input: sorted(list(zip(a, b))

Output: False

Input: ([{}, {}])

Output: True

Here's my implementation in Python:

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        """Push item in stack."""
        self.items.append(item)

    def top(self):
        """Return top of the stack."""
        if self.items:
            return self.items[-1]
        raise Exception('Stack empty.')

    def pop(self):
        """Remove and return top of the stack."""
        if self.items:
            return self.items.pop()
        raise Exception('Stack empty.')

    def is_empty(self):
        """Return True if stack is empty."""
        return len(self.items) == 0

    def __len__(self):
        """Return stack length."""
        return len(self.items)

    def __str__(self):
        """Print stack."""
        print(list(reversed(self.items)))

def check_balance(code):
    """Return True if brackets are balanced, False otherwise."""
    valid = {']': '[', ')': '(', '}': '{'}
    lefts = Stack()
    for char in code:
        if char in '[({':
            lefts.push(char)
        if char in '])}' and lefts.is_empty():
            return False
        if char in '])}' and not lefts.is_empty():
            if lefts.top() != valid[char]:
                return False
            lefts.pop()
    if not lefts:
        return True
    return False

if __name__ == '__main__':
    print(check_balance('[(((((({{}}))))))]'))
    print(check_balance('print(list(reversed(self.items))'))
    print(check_balance(' print(list(reversed(self.items))[]'))
    print(check_balance('print(list(reversed(self.items)))'))
    print(check_balance('print(list[(]reversed(self.items))'))
    print(check_balance('print(list(reversed(self.items[0)]))'))
    print(check_balance('print(list(reversed(self.items[7])))'))


texts: Entity management design & smart pointers

texts:
I'd like to get some guidance on whether or not I'm approaching my design the correct way, especially with regards to usage of smart pointers and references.

I've started developing a small game engine which among other things consists of Entities, an EntityManager to 'own' the entities, a Quadtree for 2d entity position lookups which will be regenerated each update and a World to encapsulate manager and tree. Here are the relevant bits:

World:

EntityManager mEntityManager;
Quadtree<Entity&> mTree;

void World::Init() {
    // Add some initial entities
    for( int i=0 ; i < 200; i++ ) {
        std::unique_ptr<Entity> entity( new Entity(*this) );
        mEntityManager.AddEntity(&entity);
    }
}

void World::Update() {
    // Rebuild quadtree and update entities
    mTree.clear();
    for( const auto &i : mEntityManager.getEntities() ) {
        mTree.insert(*i.get(), i->position().x, i->position().z );
    }
    mEntityManager.update();
}

EntityManager:

std::vector<std::unique_ptr<Entity>> mEntities;

const std::vector<std::unique_ptr<Entity>> &getEntities(){ return mEntities; }

void EntityManager::AddEntity(std::unique_ptr<Entity>* entity) {
    mEntities.push_back(std::move(*entity));
}

Entity:

World&      mWorld;

Entity(World& world) : mWorld( world ) { };

void Entity::update() {
    // Call world to retrieve a list of
    for( const auto &i : world.getNearbyEntities( this->position, radius ) ) {
        // etc...
    }
}

All currently seems to works fine, but I'd just like to know if I'm going about this the right way or if I'm lining myself up for problems in the future based on how I'm defining/passing data.

EDIT
Okay, big thanks @Morwenn . How does this look, assuming I want to create a new instance and then perhaps perform some operations on the newly created entity. Anything I've misunderstood?

EntityManager:

template<typename Derived, typename... Args>
Derived& EntityManager::EmplaceEntity(Args&&... args) {
    std::unique_ptr<Entity> ptr( new Derived{std::forward<Args>(args)...} );
    mEntities.push_back(std::move(ptr));
    return dynamic_cast<Derived&>(*(mEntities.back()));
}

World:

for( int i=0 ; i < 200; i++ ) {
    BlueEntity& entity = mEntityManager.EmplaceEntity<BlueEntity>(*this);
    entity.setPosition(x, y);
}


texts: Custom PHP MySQL database queries function - Suggestions for improvement or additions

texts:
For my website needs I made a custom procedural MySQL function in PHP which can INSERT, UPDATE, SELECT or DELETE data from database. I would like a review and any suggestions for improvement or addition of new features.

function mysqli_database_query($sql, $values, $param = NULL, $result_param = NULL) {
    require "dbconn.script.php";
    // String to array conversion
    if (!is_array($values)) {
        $values_array = array($values);
    } else {
        $values_array = $values;
    }
    // Number of values checker and string of parameter types creation
    $number_of_values = count($values_array);
    if ($number_of_values > 1) {
        $param_types = implode("", array_map(function($val) { return gettype($val)[0]; }, $values_array));
    } else {
        $param_types = gettype($values_array[0])[0];
    }
    // SQL query execution
    $stmt = mysqli_stmt_init($conn);
    mysqli_stmt_prepare($stmt, $sql);
    mysqli_stmt_bind_param($stmt, $param_types, ...$values_array);
    mysqli_stmt_execute($stmt);
    // SQL query results management
    if (preg_match("/^SELECT.*/", $sql)) {
        $results = mysqli_stmt_get_result($stmt);
        # RETURN ASSOCIATIVE AND NUMERIC ARRAY COMBINED EVEN IF RESULT PARAMETER IS INVALID
        if ($result_param === NULL || $result_param !== "assoc" || $result_param !== "num" || $result_param !== "row") {
            return mysqli_fetch_array($results, MYSQLI_BOTH);
        # RETURN ASSOCIATIVE ARRAY
        } else if ($result_param === "assoc") {
            return mysqli_fetch_array($results, MYSQLI_ASSOC);
        # RETURN NUMERIC ARRAY
        } else if ($result_param === "num") {
            return mysqli_fetch_array($results, MYSQLI_NUM);
        # RETURN ONE ROW
        } else if ($result_param === "row") {
            if ($param === NULL || $param !== "id") {
                return mysqli_fetch_row($results);
            }
            # RETURN ONE ROW ID
            if ($param === "id") {
                $result = mysqli_fetch_row($results);
                return $result["id"];
            }
        }
    }
    if (preg_match("/^INSERT.*/", $sql)) {
        # RETURN LAST INSERTED ID
        if ($param === "insert_id") {
            return mysqli_insert_id($conn);
        # RETURN NUMBER OF AFFECTED ROWS
        } else if ($param === "affected_rows") {
            return mysqli_affected_rows($conn);
        } else {
            return false;
        }
    }
    if (preg_match("/^UPDATE.*/", $sql)) {
        # RETURN NUMBER OF AFFECTED ROWS
        if ($param === "affected_rows") {
            return mysqli_affected_rows($conn);
        } else {
            return false;
        }
    }
    if (preg_match("/^DELETE.*/", $sql)) {
        # RETURN NUMBER OF AFFECTED ROWS
        if ($param === "affected_rows") {
            return mysqli_affected_rows($conn);
        } else {
            return false;
        }
    }
};


texts: Optimizing code that needs to run through a lot of different numbers for Project Euler

texts:
I have been working on Project Euler problem number 12. I have code that will get me the right answer, however it takes too long. I know the code works because I have tested it multiple times with numbers that are smaller and take much less time to iterate through. I first wrote essentially the same thing in python, but I know C is faster so I gave it a shot in C, but my solution is just not efficient. Here is the code (in C):

#include <stdio.h>

int main(void) {
  int num = 0;
  int i;
  int j;
  int divisors = 0;
  for (i=1; i<10000; i++){
    num += i;

    for (j=1; j<=num; j++) {
      if (num % j == 0) {
        divisors += 1;
      }
    }

    if (divisors > 500) {
      printf("Num is %d\n", num);
      printf("Divs are %d\n", divisors);
    }

    divisors = 0;

  }
}

Project Euler problems are supposed to be solved in under a minute of run-time anyways, so this isn't a great solution even if I let it run until I got an answer.

Any suggestions on ways to do this faster would be much appreciated!


texts: Usage of the ternary "?:" operator with functions listening to click events

texts:
I've recently been doing some mods to some old code I've been maintaining for a couple of years now.

As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set:

addFooListeners = function (panelType) {

    YAHOO.util.Event.addListener("show" + panelType, "click", showFoo, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("hide" + panelType, "click", hideFoo, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("commit" + panelType, "click", commitFoo, eval(ns + ".panel_" + panelType), true);

}

This code is the result of a number of panels/dialogs having near identical behaviour.

For this round of development I've needed to add the ability to do things a little differently from time to time, so I added an object, overrides which allows me to point the show, hide and commit actions elsewhere.  I came up with the following:

addFooListeners = function (panelType, overrides) {

    var handlers = {
        show: ( overrides != null ? ( overrides.show != null ? overrides.show : showFoo ) : showFoo ),
        hide: ( overrides != null ? ( overrides.hide != null ? overrides.hide : hideFoo ) : hideFoo ),
        commit: ( overrides != null ? ( overrides.commit != null ? overrides.commit : commitFoo ) : commitFoo )
    }

    YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, eval(ns + ".panel_" + panelType), true);
    YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, eval(ns + ".panel_" + panelType), true);
}

As you can see I'm enforcing default behaviour unless an appropriate attribute in the overrides object is set with another function (named or anonymous).

Is there a cleaner / more readable way to concisely setup the handlers object?  The nested ternary seems to my eyes to be cluttering things a bit but other approaches like if ( overrides != null ) { ... } seem just as messy.


texts: Graph and minimum spanning tree in Python

texts:
Here is my Graph class that implements a graph and has nice a method to generate its spanning tree using Kruskal's algorithm.

I want to:

Make it pythonic
Improve readability
Improve the abstraction (but not changing the use of outer and inner dicts to represent the graph)

Performance is not a concern.

Code:

class Graph(object):
    def __init__(self):
        self.g = {}

    def add(self, vertex1, vertex2, weight):
        if vertex1 not in self.g:
            self.g[vertex1] = {}

        if vertex2 not in self.g:
            self.g[vertex2] = {}

        self.g[vertex1][vertex2] = weight
        self.g[vertex2][vertex1] = weight

    def has_link(self, v1, v2):
        return v2 in self[v1] or v1 in self[v2]

    def edges(self):
        data = []

        for from_vertex, destinations in self.g.items():
            for to_vertex, weight in destinations.items():
                if (to_vertex, from_vertex, weight) not in data:
                    data.append((from_vertex, to_vertex, weight))

        return data

    def sorted_by_weight(self, desc=False):
        return sorted(self.edges(), key=lambda x: x[2], reverse=desc)

    def spanning_tree(self, minimum=True):
        mst = Graph()
        parent = {}
        rank = {}

        def find_parent(vertex):
            while parent[vertex] != vertex:
                vertex = parent[vertex]

            return vertex

        def union(root1, root2):
            if rank[root1] > rank[root2]:
                parent[root2] = root1
            else:
                parent[root2] = root1

                if rank[root2] == rank[root1]:
                    rank[root2] += 1

        for vertex in self.g:
            parent[vertex] = vertex
            rank[vertex] = 0

        for v1, v2, weight in self.sorted_by_weight(not minimum):
            parent1 = find_parent(v1)
            parent2 = find_parent(v2)

            if parent1 != parent2:
                mst.add(v1, v2, weight)
                union(parent1, parent2)

            if len(self) == len(mst):
                break

        return mst

    def __len__(self):
        return len(self.g.keys())

    def __getitem__(self, node):
        return self.g[node]

    def __iter__(self):
        for edge in self.edges():
            yield edge

    def __str__(self):
        return "\n".join('from %s to %s: %d' % edge for edge in self.edges())

graph = Graph()

graph.add('a', 'b', 2)
graph.add('a', 'd', 3)
graph.add('a', 'c', 3)

graph.add('b', 'a', 2)
graph.add('b', 'c', 4)
graph.add('b', 'e', 3)

graph.add('c', 'a', 3)
graph.add('c', 'b', 4)
graph.add('c', 'd', 5)
graph.add('c', 'e', 1)

graph.add('d', 'a', 3)
graph.add('d', 'c', 5)
graph.add('d', 'f', 7)

graph.add('f', 'd', 7)
graph.add('f', 'e', 8)
graph.add('f', 'g', 9)

print(graph.spanning_tree())
print()
print(graph.spanning_tree(False))


texts:
I'm trying to make a console application to sort and delete duplicate image files. I have a folder with about 20000 images which take up roughly 70GB of space.
I wrote the following script and it seems to work fine, but the issue is that my PC runs out of available RAM memory (it has 16GB) without reaching halfway through.
static void Main(string[] args)
{
    var uniqueData = new HashSet<string>();

    int progress = 0;
    int fileCount = Directory.GetFiles(imageFolderPath).Length;

    foreach (var file in Directory.GetFiles(imageFolderPath))
    {
        string data, year, month;

        using (var image = Image.FromFile(file))
        {

            using (var ms = new MemoryStream())
            {
                image.Save(ms, ImageFormat.Jpeg);
                data = Convert.ToBase64String(ms.ToArray());
            }

            try //try to get image date
            {
                var date = Encoding.UTF8.GetString(image.GetPropertyItem(36867).Value).Split(':');
                year = date[0];
                month = date[1];
            }
            catch
            {
                year = "Unknown";
                month = "Unknown";
            }
        }

        if (!uniqueData.Contains(data))
        {
            uniqueData.Add(data);

            string yearDirectory = Path.Combine(outputFolderPath, year);

            if (!Directory.Exists(yearDirectory))
            {
                Directory.CreateDirectory(yearDirectory);
            }

            string monthDirectory = Path.Combine(yearDirectory, (int.TryParse(month, out int i) && i > 0 && i < 14) ? CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i) : month);

            if (!Directory.Exists(monthDirectory))
            {
                Directory.CreateDirectory(monthDirectory);
            }

            File.Move(file, Path.Combine(monthDirectory, Path.GetFileName(file)));
        }
        else
        {
            File.Delete(file);
        }

        progress++;
        Console.WriteLine($"{progress} / {fileCount}");
    }
}


texts:
I am new to Ruby and would like some help with re-factoring my code.

class Beam
def initialize
    puts "Please specify span of beam"
    @span = gets.chomp.to_f
    puts "How many number of point loads do you want?"
    @pointLoadNos = gets.chomp.to_i
    @pointLoad = Array.new(@pointLoadNos)
    @pointLoadDistFromLeft = Array.new(@pointLoadNos)
    @pointLoadDistFromRight = Array.new(@pointLoadNos)
    @magnitude = Array.new(@pointLoadNos)
    @reaction = Array.new(2,0)
end
def setValues
    count = 0
    while count < @pointLoadNos
        puts "At what dist should point load #{count+1} be placed from left?"
        @pointLoadDistFromLeft[count] = gets.chomp.to_f
        if @pointLoadDistFromLeft[count] > @span
            puts "Dist of Point Load #{count+1} From Left should be less than span length of beam"
        else
            puts "Magnitude of point load #{count+1} should be?"
            @magnitude[count] = gets.chomp.to_f
            @pointLoadDistFromRight[count] = (@span - @pointLoadDistFromLeft[count])
            count += 1
        end
    end
end
def calReactions
    i = 0
    while i < @pointLoadNos
        @reaction[0] += (@pointLoadDistFromLeft[i]*@magnitude[i])/@span
        @reaction[1] += (@pointLoadDistFromRight[i]*@magnitude[i])/@span
        i += 1
    end
    puts "Reaction at Left: #{@reaction[0]}"
    puts "Reaction at Left: #{@reaction[1]}"
end
end

beam = Beam.new
beam.setValues
beam.calReactions


texts:
I have been solving this problem of Hackerrank recently .. https://www.hackerrank.com/challenges/maximum-element
A little bit about the problem

You have an empty sequence, and you will be given N queries. Each query is one of these three types:
1 x  -Push the element x into the stack.
2    -Delete the element present at the top of the stack.
3    -Print the maximum element in the stack.

And my code is here - which passes the first 12 test cases.
import java.util.*;

public class Stackers {

    public static Stack<Integer> stack;
    public static String output = "";

    public static void main(String[] args) {

        stack = new Stack<>();
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        for(int i = 0 ; i < n + 1; i++){

            String op = sc.nextLine();
            performOperation(op);

        }

        sc.close();
        if(!output.isEmpty()){
            System.out.println(output);

        }

    }

    public static void performOperation(String op) {

        if (op.startsWith("1")){

            String remains = op.split(" ")[1];
            int rem = Integer.valueOf(remains);
            stack.push(rem);

        }else if(op.equalsIgnoreCase("2")){

            stack.pop();

        }else if(op.equals("3")){

            int max = (int) Collections.max(stack);
            output += (max + "\n");

        }

    }

}

But fails with "timeout" from the 13th test case. Most of the times, logic will be wrong, so I ran the 13th test case locally in my computer . I got the output in 1.3- 1.6 minutes tho:)
How can I improve my code. Please guide me or if it is the wrong stack exchange community, please advise me.


texts:
Hello today after few weeks of learning I tried some form validation.
I am wondering how I could improve my code and what things I missed.
Here is a preview hosted on github + repository.
And here is my code :
HTML
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="main.css">
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <title>Form validation</title>

    <form action="#" class="form">

Contact with us

          <input type="text" name="name" class='input-name' id='input' placeholder="First name *" required>

          <input type="text" name="surname" class='input-surname' id='input' placeholder="Surname">

          <input type="text" name="email" class='input-email' id='input' placeholder="E-mail *" required>

          <input type="text" name="phone" class='input-phone' id='input' placeholder="Phone number">

        <textarea name="message" rows="8" cols="80" class='input-message' id='input' placeholder="Message *" required></textarea>
        <button href="#" class="btn">Submit</button>

    </form>

JS
'use strict';

const submit = document.querySelector('.btn');
const name = document.querySelector('.input-name');
const surname = document.querySelector('.input-surname');
const email = document.querySelector('.input-email');
const phone = document.querySelector('.input-phone');
const items = document.querySelectorAll('#input');

const isValid = function(item) {
  for (let i = 0; i < item.length; i++) {
    if (item[i].value){ // Check if contains value

      let error = document.getElementById(`${item[i].className}-p`);
      const letters = /^[A-Za-z]+$/;
      const numbers = /^\d+$/;
      let inputLength = item[i].value.length;

      switch (item[i].className){
        case 'input-name':
        case 'input-surname':
          if(!letters.test(item[i].value)){ // Invalid input
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;

        case 'input-email':
          if(!item[i].value.includes('.') || !item[i].value.includes('@') || !letters.test(item[i].value[inputLength-1])  ){ // check if includes (@ or .) and check if the last index is a letter
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;
        case 'input-phone':
          if(!numbers.test(item[i].value) ||  inputLength<5){  // Invalid input
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;
      }

    }
  }
}

for (let i = 0; i < items.length; i++) {
    items[i].addEventListener('click',function(){
      // Check if the input is valid
      isValid(items);
    });
}


texts: NullPointer Exception handling in the code

texts:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class FileOperations<T> implements Operations<T> {

    private ObjectMapper objectMapper;
    //this is going to come from the property file.
    private String filePath = "C:\\Users\\phyadavi\\workspace\\ConfigurationService\\src\\main\\resources\\seed.txt" ;
    private File file;

    public FileOperations() {
        this.objectMapper = new ObjectMapper();
        this.file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.getMessage();
            }
        }
    }

    private void saveImpl(Object serializableObject) throws IOException {
        String jsonData = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serializableObject);
        BufferedWriter br = new BufferedWriter(new FileWriter(file));
        br.write(jsonData);
        br.close();
    }

    @Override
    public void save(List<T> serializableObjects) throws IOException {
        saveImpl(serializableObjects);
    }

    @Override
    public void save(T serializableObject) throws IOException {
        saveImpl(serializableObject);
    }

    @Override
    public List<T> get() throws IOException {
        List<T> list = objectMapper.readValue(file, new TypeReference<List<T>>() {
        });

        return list;
    }

}

import java.io.IOException;
import java.util.List;

import com.cisco.daas.configservice.entities.User;
import com.cisco.daas.configservice.utilities.FileOperations;
import com.cisco.daas.configservice.utilities.Operations;

public class Data {

    private static final Operations<User> operations = new FileOperations<User>();

    private static List<User> users;

    public static List<User> getUsers() {
        try {
            users = operations.get();
        } catch (IOException e) {
            e.getMessage();
        }
        return users;
    }
}

The above code reads json data from a text file using the Jacksons ObjectMapper API.

The public List<T> get() method reads the data from the files and converts the data into a list of objects of type T.

The public void save(T serializableObject) and public void save(List<T> serializableObjects) both saves the json data to the file.

The Data creates a static list objects which is meant for performing operations in-memory.

Now, I would like someone to review the exception handling in the code. I need some idea on how to handle exceptions like NullPointer and FileNotFound exceptions in the above code.


texts: Best way to do unknown number of nested v-for loops, or how to do while loops in VueJs (is there a "v-while"?)

texts:
I want to recursively use a Vue component for each item in a multidimensional array, which is a list of topics. For example, Topic 1 can have subtopics 1.1, 1.1.1 and 1.1.2, but topic 2 might have no subtopics at all. (My working code is presented at the bottom)
My Array in Vue's app data is something like:
[
  ['Topic 1', [
    'Topic 1.1', [
       ['Topic 1.1.1', []],
       ['Topic 1.1.2', []]
    ]
  ],
  ['Topic 2', []],
  ['Topic 3', [
    ['Topic 3.1', []],
    ['Topic 3.2', []],
    ['Topic 3.3', []],
    ]
  ]
]

Supposing my component is just a details tag, this is my expected HTML output (borders were added just for clarity):

details > details {
  margin-left: 2em;
  border: 1px solid black;
}

Topic 1
  Topic 1.1
    Topic 1.1.1

    Topic 1.1.2

Topic 2

Topic 3
  Topic 3.1

  Topic 3.2

  Topic 3.3

etc.

I can't anticipate all v-for loops I'll use, because I don't know the depth of each topic (i.e., I don't know how many subtopics there are, it depends on each topic and there can be dozens or none at all).
My solution was to use a v-if to check if there are subarrays inside the current array; if there are, a component is created for the subarrays too (and the component's template includes in the end this div with a v-if, so it works recursively).
This works, but looks clunky. So my question is: what is the best way to run a while-loop with Vue (for the cases where I don't know how many for-loops I need to run)? Or is my solution already the best way to approach this?
(I first thought of creating a method, and calling this method in the end to check if there are subarrays and then create components for them basically via JavaScript, but this seems worse than using v-if and adding a v-for for adding components to the subarray items)

Here's my working code:

Vue.component('details-component', {
  template: ` {{ arritem[0] }}

`,
  props: {
    arritem: {
      type: Array,
      required: true
    }
  }
});

const app = new Vue({
  el: "#root",
  data: {
    arr: [
      ['Topic 1', [
        ['Topic 1.1', [
          ['Topic 1.1.1', []],
          ['Topic 1.1.2', []]
          ]
        ]
      ]],
      ['Topic 2', []],
      ['Topic 3', [
        ['Topic 3.1', []],
        ['Topic 3.2', []],
        ['Topic 3.3', []],
      ]]
    ]
  }
});
details details {
  margin-left: 2em;
}


texts:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Feel like I went about this the wrong way, but my gut said to check if a number divided evenly by each number up to 20 and when it did, return it.

function isDivisible(number) {
    for (d = 1; d <=20; d++) {
        if (number % d === 0) {
            continue;
        } else {
            return false;
        }
    }
    return true;
}

var number = 1;
do {
    number++;
} while (! isDivisible(number));

console.log(number);


texts: Code to join filesystem path strings in PHP

texts:
Following code has some issues:

$args = func_get_args();
$paths = array();
foreach ($args as $arg) {
    $paths = array_merge($paths, (array)$arg);
}

$paths = array_map(create_function('$p', 'return trim($p, DIRECTORY_SEPARATOR);'), $paths);
$paths = array_filter($paths);
return DIRECTORY_SEPARATOR . join(DIRECTORY_SEPARATOR, $paths);

Unnecessary array_merge usage
Using depecated create_function function

Would using modern PHP 5.6+ features (anonymous functions etc.. ) help to improve the code?


texts:
I'm actually creating an AI for the online contest Vindinium. The fact is that's also an exam for my school because I'm going to have a note with that work.

I created an AI based on ants pheromones with a recursive function. The bot is working but only on small maps. I need to send my answer turn after turn (which movement my bot is going to make) in only one second. But one of my functions: to apply all ant pheromones on the map is taking too long.

At each turn, if my bot has got a new objectif, he is going to spreads pheromones on the map with some value on each squares of the map. An on each square the value can propagate to to all neighbors until the square of the final destination.

public function appliCoeff($x, $y, $sx, $sy, $value)
{

    // Optimisation du code
    $newval = $value+1;

    if( /* Special condition */ )
        $this->setReccurence($x, $y-1, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->setReccurence($x-1, $y, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->setReccurence($x+1, $y, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->setReccurence($x, $y+1, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->appliCoeff($x, $y-1, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->appliCoeff($x-1, $y, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->appliCoeff($x+1, $y, $sx, $sy, $newval);

    if( /* Special condition */ )
        $this->appliCoeff($x, $y+1, $sx, $sy, $newval);

}

Do you have any idea to optimize it? Do you think threads are a good idea? I never used them and I don't know if it's such a good idea to parallelize treatments?


texts: Javascript run length encoding algorithm

texts:
I have implemented a custom run length encoding algorithm that converts an m x n array into an p x (n+1) array. The extra column is to record counts. Probably easier to show through examples:

encode = (array) => {
  // crude array equality function
  arrayEquals = (...arr) => {
    return arr[0].map(x => {
      return JSON.stringify(x);
    }).every((x, _, a) => {
      return x === a[0];
    });
  };

  let result = [],
    count = -1,
    len = array.length;

  array.reduce((acc, val, i) => {
    if (!arrayEquals([acc, val])) {
      // if current value differs from last
      if (i !== len - 1) {
        // push the count and data to the result
        result.push([++count, acc]);
        count = 0; // reset the count
      } else { // last iteration
        // push the (n - 1)th  value
        result.push([++count, acc]);
        // now push the nth value
        result.push([1, val]);
      }
    } else {
      // if current value equals the last, increment counter and continue
      count++;
      if (i === len - 1) { // last iteration
        // push regardless
        count === 1 ? result.push([++count, val]) : result.push([count, val]);
      }
    }
    return val;
  }, array[0]);

  return result;
};

console.log(encode([1, 1, 2, 2, 3, 3, 4]));
console.log(encode([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [10, 11, 12]
]));
console.log(encode([
  [1, 2, 3],
  [1, 2, 3],
  [4, 5, 6]
]));
console.log(encode([
  [0],
  [0],
  [1],
  [2, 3],
  [4, 5, 6],
  [],
  []
]));

I think I've tried the full range of common test cases and it has worked so far for all of them but I feel there must be a better way to implement this. The logic was awkward to write given the need to have knowledge of previous iterations and the current. I used reduce as it seemed to lend itself to this but even so, keeping track of when to increment was very difficult and doesn't make for the most readable code. My hunch is that there's a neat solution where one adds dummy elements to the beginning or end of the initial array and then can do away with the need for the (if (i === len - 1) logic)?

Any improvements would be much appreciated.