texts: Computing intersections of a Polyline and a line

texts:
I wrote a script to compute / interpolate the nodes of a Polyline at a given latitude, input_lat. It works for my purpose but I am wondering if there is a better, more optimized way of doing this.

The idea is to first check if there is any exact match, i.e. if there are nodes at the exact given latitude so I subtract the input latitude to the list of nodes (the latitudes list) and if there are any zeros, I can just read the longitude of these.

Most of the time the crossing will be between 2 consecutive nodes, with one being below (or above) and the next one being on the other side of the input_lat (the node above will retain a positive value after subtracting input_lat and the node below a negative value) so in my latitudes list I detect that by checking for a change of sign between two consecutive elements, so I multiply each element with the next: if the result is negative, there is a change of sign.
I do this with np.multiply(latitudes[1:], latitudes[:-1]) but I wonder if there is a better way.

The script is meant to run from within QGIS so all the qgis.* libraries that are imported and the Qgs commands are specific to QGIS.

"""Script to compute coordinates of a Polyline at a given Latitude"""

#import QGIS specific libraries
from qgis.core import *
from qgis.gui import *
import qgis.utils

#import numpy
import numpy as np

"""Assuming the following :
- a Line/Polyline Layer is selected"""

#the latitude we want to compute intersections with
input_lat = 28.54456111
ray = [0, input_lat]
longitudes = []

def getIntersectLon(a, b, lat):
    """Compute the Longitude of the intersection between two nodes"""
    return a[0] - (a[1] - lat) * (a[0] - b[0]) / (a[1] - b[1])

layer = qgis.utils.iface.activeLayer()
if layer is None:
    iface.messageBar().pushMessage("Select a Layer", level=QgsMessageBar.CRITICAL, duration=2)
else:
    for feature in layer.getFeatures():
        geom = feature.geometry()
        if geom.type() == QGis.Line:
            # get the nodes coordinates in an array :
            #   geom.asPolyline() will produce an array of tuples
            #   that we will convert to an array of arrays so we
            #   can mutate the values
            nodes = np.asarray(geom.asPolyline())
            #
            # THIS IS THE CORE ROUTINE
            #
            # get the list of the difference between latitudes and the input
            latitudes = (nodes - ray)[:,1]
            # if there are zeros, we have points at the exact given latitude
            exact = np.where(latitudes == 0)[0]
            for e in exact:
                longitudes.append(nodes[e][0])
            # where line crosses between nodes, there will be a change of sign
            # one node being below, and the next above the input
            xing = np.multiply(latitudes[1:], latitudes[:-1])
            # get the indexes of the sign changes
            crossing = np.where(xing < 0)[0]
            for c in crossing:
                longitudes.append(getIntersectLon(nodes[c], nodes[c+1], input_lat))
            #
            # THIS IS THE END OF THE CORE ROUTINE
            #
            # we will now create points the found latitudes (if any)
            #   that we will load into a new Point layer for display
            #
            if longitudes:
                #create a Point layer to store the intersections found
                newlayer =  QgsVectorLayer("Point", "Intersections", "memory")
                pr = newlayer.dataProvider()
                feat = QgsFeature()
                for lon in longitudes:
                    feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(lon, input_lat)))
                    pr.addFeatures( [ feat ] )
                    print lon
                QgsMapLayerRegistry.instance().addMapLayers([newlayer])
            qgis.utils.iface.mapCanvas().refresh()
        else:
             iface.messageBar().pushMessage("Select a Line layer", level=QgsMessageBar.CRITICAL, duration=2)


texts: React Native FlatList with Scroll-To-load data

texts:
I am creating an application that interacts with spotify. A part of my app is a FlatList screen displaying a list of songs and song controls.

I am under the impression that my FlatList is very poorly optimized, leading to slow load times as you scroll down.
The main issue I want to resolve is this performance issue.
First, the authentication wrapper
import {
  setAccessToken,
  setRefreshToken,
} from '_redux/features/authenticationSlice'
import authHandler from '_utils/authenticationHandler'

async function updateReduxWithValidAccessToken({
  accessToken,
  accessExpiration,
  refreshToken,
}) {
  if (accessToken === null || new Date() > new Date(accessExpiration)) {
    console.log('Access Token is Invalid, Refreshing...')
    console.log('refreshToken=', refreshToken)
    const response = await authHandler.refreshLogin(refreshToken)
    accessToken = response.accessToken
    setAccessToken({
      accessToken,
      accessExpiration: response.accessTokenExpirationDate,
    })
    setRefreshToken({
      refreshToken: response.refreshToken,
    })
  }
  return accessToken
}

Next, the song fetching code. This lives within the component
  const [songs, setSongs] = useState([])
  const [songsToFetch, setSongsToFetch] = useState(100)
  const [page, setPage] = useState(0)

  const getSongsOfPlaylist = async (aToken, aPlaylist, aPage, aLimit) => {
    const response = await authHandler.get(
      `/playlists/${aPlaylist}/tracks`,
      aToken,
      {
        offset: 100 * aPage,
        limit: aLimit,
        fields:
          'total,items(track(preview_url, id, name, duration_ms, artists, album(!available_markets)))',
      },
    )
    if (response) {
      const remainingSongs =
        response.data.total - songs.length - response.data.items.length
      setSongsToFetch(Math.min(100, remainingSongs))
      setSongs([...songs, ...response.data.items])
    }
  }

Then all the functions related to rendering the list:
  useEffect(() => {
    console.log('Loading page #', page)
    setLoading(true)
    updateReduxWithValidAccessToken(authentication)
      .then((token) => getSongsOfPlaylist(token, playlistID, page))
      .then(() => {
        setLoading(false)
      })
  }, [page])

  async function loadMore() {
    if (!loading && songsToFetch > 1) {
      setPage(page + 1)
    }
  }

  function renderFooter() {
    if (!loading) {
      return null
    }
    return <ActivityIndicator animating />
  }
  function renderSeparator() {
    return <SeparatorLine />
  }

Finally, the flatlist code:
      <MySongList
        data={songs}
        renderItem={renderListItem}
        keyExtractor={(_, index) => index.toString()}
        ItemSeparatorComponent={renderSeparator}
        ListFooterComponent={renderFooter}
        onEndReached={loadMore}
        onEndReachedThreshold={0.1} />

All this code (except for the authentication wrapper) lives inside a wrapper component, PlaylistDetailScreen.
function PlaylistDetailScreen({ route, navigation, authentication, ...props }) {
  // All code above
  return loading && page === 0 ? (
    <MyText> Loading... </MyText>
  ) : (
    <ContainerView>
      <MySongList />
    <ContainerView />
  )

From my efforts, it appears that the list is rerendering multiple times. Why would this be?


texts:
I've tried as best I can, to implement HMAC as specified in the RFC 2104. This is also my first Rust project, so the chances that rookie mistakes have been made are high. Since I'm fairly new to the language, I'm looking for feedback in general.

use functions;
use ring::{digest, test};

// Set blocksizes
pub const BLOCKSIZE_256: usize = 64;
pub const BLOCKSIZE_512: usize = 128;

/// Return either a SHA256 or SHA512 digest of byte vector
fn hash(variant: i32, mut data: Vec<u8>) -> Vec<u8> {
    if variant == 256 {
        data = (digest::digest(&digest::SHA256, &data).as_ref()).to_vec();
    } else if variant == 512 {
        data = (digest::digest(&digest::SHA512, &data).as_ref()).to_vec();
    } else {
        panic!("Invalid variant. Valid variants are 256 and 512.");
    }
    return data;
}

/// Return a key k that has been padded to fit the selected blocksize
fn key_deriv(variant: i32, mut k: Vec<u8>) -> Vec<u8> {
    if variant == 256 {
        // If key k is bigger than blocksize, it should be hashed and then padded with zeroes
        // to fit blocksize
        if k.len() > BLOCKSIZE_256 {
            k = hash(variant, k);
        }
        while k.len() < BLOCKSIZE_256 {
            k.push(0x00);
        }
        return k;
    } else if variant == 512 {
        if k.len() > BLOCKSIZE_512 {
            k = hash(variant, k);
        }
        while k.len() < BLOCKSIZE_512 {
            k.push(0x00);
        }
        return k;
    } else {
        panic!("Invalid variant. Valid variants are 256 and 512.");
    }
}

/// Returns an HMAC from message m and key k
pub fn hmac(variant: i32, mut k: Vec<u8>, mut m: Vec<u8>) -> Vec<u8> {
    // Initialize vectors that will hold the ipad and opad
    let mut ipad = vec![];
    let mut opad = vec![];
    // Pad the key
    k = key_deriv(variant, k);

    for count in 0..k.len() {
        ipad.push(k[count] ^ 0x36);
        opad.push(k[count] ^ 0x5C);
    }

    ipad.append(&mut m);
    ipad = hash(variant, ipad);
    opad.append(&mut ipad);
    opad = hash(variant, opad);

    return opad;
}

A possible improvement I'm considering is to change the zero padding of k in key_deriv(). Right now it operates on a while loop, but I noticed that an approach like below, was slightly faster. Though I suspected it might be a little more memory intensive because of the vector allocation and I'm not sure which of the two to choose.

let len = k.len();
if len < BLOCKSIZE_256 {
    k.append(&mut vec![0x00; (BLOCKSIZE_256-len)]);
}


texts:
I want to get version from Cargo.toml and use the value inside my app. Here is a function I wrote:

use std::fs;

pub fn get_version() -> &'static str {
    let text = fs::read_to_string("Cargo.toml").unwrap();
    for line in text.split("\n") {
        if line.starts_with("version") {
            let start = line.find('"').unwrap() + 1;
            let end = line.rfind('"').unwrap();
            let version = &line[start..end];
            return Box::leak(version.to_string().into_boxed_str());
        }
    }

    panic!("failed parsing version from Cagro.toml");
}

Writting the function, I had some questions. So I'd like to get help from others.

How can I replace for and if nested blocks with iterator methods?
To return value as static lifetime, I used Box::leak(version.to_string().into_boxed_str()) which is too complicated (&str -> String -> Box<str> just for avoiding compile errors). How can I return &'static str or &'a str simply without getting cannot return value referencing local variable ... error in this case?
Can I make the code simpler? (ex: parsing the version value)


texts: Secret Santa pair allocator in JavaScript

texts:
I have a Secret-Santa gift swap with my family and we always forget who we had last year and never find time to do it so I wanted to create a simple web app to manage the whole thing. What I'm looking for is a critique on my code. Could it use more built-in JavaScript functions? How's my style?

//get people from database
var people = [{name: 'TestName', spouse: 'TestNameSpouse', current: '', past: ['Dad']},
  { name: 'TestNameSpouse', spouse: 'TestName', current: '', past: ['Mom']},
  { name: 'Mom', spouse: 'Dad', current: '', past: ['TestName']},
  {name: 'Dad',spouse: 'Mom',current: '',past: ['SisterInLaw']},
  {name: 'Brother',spouse: 'SisterInLaw',current: '',past: ['TestNameSpouse']},
  {name: 'SisterInLaw',spouse: 'Brother',current: '',past: ['Dad']}
];

const setCurrentToBlank = (people) => people.forEach((person) => person.current = '');
const verifyGiftPartners = (people) => people.every((person) => person.current);

//Knuth shuffle
var shuffle = function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue,
    randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
};
var assignGiftPartners = function(people) {
  var peopleLeftToAssign = people.map(person => person.name);

  people.forEach(function(person) {
    var choices = peopleLeftToAssign.filter(function(personToAssign) {
      return (
        personToAssign != person.name &&
        personToAssign != person.spouse &&
        person.past.indexOf(personToAssign) === -1
      );
    });
    shuffle(choices);
    person.current = choices[0];
    var index = peopleLeftToAssign.indexOf(choices[0]);
    peopleLeftToAssign.splice(index, 1);
  });
};

var allAssigned = false;
var loopCount = 0;
while (!allAssigned) {
  assignGiftPartners(people);
  allAssigned = verifyGiftPartners(people);
  //exit loop if going too long
  if (loopCount > 50) {
    throw 'Something went wrong with the assignment';
  }
  if (!allAssigned) {
    setCurrentToBlank(people);
  }
}

//save choices into database
console.log(people);

Also, I realize that in a year or so we'd have to repeat people, so would it be good to limit the past size to family size - 1?


texts: Add multiples of 3 or 5 below 1000, Can this code be optimised. Project Euler #1

texts:
I have seen some solution here for the same problem, this and this I have found better ways to solve this problem. I just want to know how good or bad my code and way of approaching this problem is.

using System;

public class Program
{
    public static void Main()
    {
        int sum = 0;
        for (int i = 0; 3 * i < 1000; i++)
        {
            sum += 3 * i;

            if (5 * i < 1000 && (5 * i) % 3 != 0)
            {
                sum += 5 * i;
            }
        }
        Console.WriteLine(sum );
    }


texts: Initial attempt at node.js automatic redirection

texts:
I'm working on a Node.js HTTP server on my iPhone:

var fs = require("fs");
var http = require('http');
const port = 8080;
var readFile = function(name, response) {
    var read = function(err, dat) {
        var rv = null;
        var nope = "./redirect.html";
        if (err) {
            if (name == nope)
                rv = "INTERNET!";
            else {
                rv = readFile(nope, response);
                return;
            }
        }
        else rv = dat;
        response.end(rv);
    }
    fs.readFile(name, "utf-8", read);
}
var client = function(request, response) {
    path = "." + request.url;
    file = readFile(path, response);
}
var server = http.createServer(client);
server.listen(port);

redirect.html:

<script language = "javascript">
window.location = "/index.html";
</script>
Bad request.


texts: Clojure performance for solving Project Euler 72 (counting proper reduced fractions)

texts:
Challenge

This is a solution of Project Euler 72 in Java.

  How may proper reduced fractions \$\dfrac{n}{d}\$ are there, where \$n
 < d \le 10^6\$?

Code

public long solve() {
  int limit = 1000000;
  int[] phi = IntStream.range(0, limit + 1).toArray();
  long result = 0;
  for (int i = 2; i <= limit; i++) {
    if (phi[i] == i) {
      for (int j = i; j <= limit; j += i) {
        phi[j] = phi[j] / i * (i - 1);
      }
    }
    result += phi[i];
  }
  return result;
}

The algorithm is explained in detail here. When I run the above code on my machine, it takes 150ms to get the answer.

I translated this code into Clojure like the below.

(defn solve []
  (let [limit 1000000
        phi (int-array (range (inc limit)))]
    (loop [i 2 acc 0]
      (if (= i (aget phi i))
        (loop [j i]
          (if (<= j limit)
            (do (aset phi j (/ (* (aget phi j) (dec i)) i))
                (recur (+ j i))))))
      (if (< i limit)
        (recur (inc i) (+ acc (aget phi i)))
        acc))))

This code uses Java array and mutate the value within the array. The algorithm is logically the same. However, when I run this code in repl, it takes over 25 seconds, which is a huge difference from the Java solution.

I expected that the Clojure code slightly slower than Java. But this is not a slight difference. Why is the Clojure code is slow like this. Did I miss something? Or is there other way to do this better?


texts:
Ruby's built-in sorts are unstable.  The stable_sort gem monkey-patches Ruby's built-in library to have stable sorts which include nearly all the functionality of the built-in sorts, but with the addition of stability.

The built-in sort method can take a block:

a.sort do |x, y|
  x.length <=> y.length
end

However, the gem's #stable_sort_by method cannot take a block (as of version 1.1).  I am adding that capability.  By simply replacing "sort" with "stable_sort", the above sort would become stable:

a.stable_sort do |x, y|
  x.length <=> y.length
end

The code that needs improvement

My implementation is ugly, and not performant: It creates a temporary array of the same size as the original.  Here is the monkey-patch that adds Enumerable#stable_sort:

module Enumerable

  def stable_sort_by
    return to_enum(:stable_sort_by) if !block_given?
    sort_by.with_index{ |e, index| [yield(e), index] }
  end

  def stable_sort
    if block_given?
      # Add indices
      a = map.with_index do |e, i|
        [e, i]
      end
      # Use built-in sort.  When two elements compare the same,
      # compare the indices to break the tie
      a.sort! do |(a, i), (b, j)|
        result = yield(a, b)
        if result == 0
          i <=> j
        else
          result
        end
      end
      # Remove the indices
      a.map(&:first)
    else
      stable_sort_by { |x| x }
    end
  end

end

Supporting code

The rspec test:

describe Enumerable do

  KeyValue = Struct.new(:key, :value) do
    def <=> (other)
      self.key <=> other.key
    end
  end

  let (:array) { [KeyValue.new(1, 1), KeyValue.new(1, 2), KeyValue.new(1, 3), KeyValue.new(1, 4), KeyValue.new(0, 10)] }
  let (:expectation) { [KeyValue.new(0, 10), KeyValue.new(1, 1), KeyValue.new(1, 2), KeyValue.new(1, 3), KeyValue.new(1, 4)] }

  describe "#stable_sort (Array)" do
    it 'sorts stably' do
      expect(array.stable_sort.to_s).to eq expectation.to_s
    end
  end

  describe "#stable_sort (Array) (with block)" do
    it 'sorts stably' do
      array = ['a', 'c', 'bd', 'fe', 'b']
      sorted = array.stable_sort do |a, b|
        a.length <=> b.length
      end
      expect(sorted).to eq ['a', 'c', 'b', 'bd', 'fe']
    end
  end

end

The benchmark:

require "benchmark"

def iterate
  100.times { yield }
end

Benchmark.bm(16) do |x|
  Random.srand(0)
  a = Array.new(10000) { rand(100) }
  x.report("sort") do
    iterate { a.sort }
  end
  x.report("sort {}") do
    iterate { a.sort { |a, b| a <=> b } }
  end
  x.report("stable_sort") do
    iterate { a.stable_sort }
  end
  x.report("stable_sort {}") do
    iterate { a.stable_sort { |a, b| a <=> b } }
  end
end

And benchmark results:

                       user     system      total        real
sort               0.110000   0.010000   0.120000 (  0.119809)
sort {}            0.800000   0.000000   0.800000 (  0.798593)
stable_sort        2.800000   0.000000   2.800000 (  2.801303)
stable_sort {}     2.060000   0.010000   2.070000 (  2.062832) <---

The question

Can stable_sort (benchmark "stable_sort {}") be made more more performant?
  Can it be made cleaner?

Copyright notice

Portions of the above code are derived from the stable_sort gem which is is Copyright (c) 2013 by Naoyoshi Aikawa and released under the MIT License.


texts:
I am busy on a protected page with login and I want know if there is more protection needed. It is a very simple system without database etc...

authentication.php

<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $account = array (
        'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
        'bert' => '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
    );

    if(array_key_exists($_POST['user'], $account)){
        if(password_verify($_POST['password'], $account[$_POST['user']])){
                session_regenerate_id();
                $_SESSION['username'] = $_POST["user"];
                $_SESSION["loggedin"]) = true;
                header("location: protected_page.php");
        }else{
            echo 'Something wrong';
        }
    }else{
        echo 'Something wrong';
    }
}
?>

protected.php

<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo 'welcome';
}else{
    header("location: login.php");
    exit;
}
?>

Please let me know and give me any feedback for a better secure system without database.


texts: Recognise numbers 1 to 6 in various notations

texts:
I'm embarrassed I spent so much time on this seemingly simple but tricky coding exercise.
The task is this: input is various strings - digits, characters, non-English characters, e.g. some could be Cyrillic. The input must be split into words and then each word must be interpreted numerically if possible.
It should handle actual digits from 1 to 6 as valid numbers. All others should be printed as is.
Valid input includes positive, int or float type numbers 1 to 6, such as the following:

1,2,3,4,5,6
+1, +2, ... , +6
1.0, 2.0,... 6.0
any scientific notation that represent numbers 1 to 6.

if number is 1 - print "rule1" , 2- "rule2" etc.
Special case is if input number can be interpreted as 0, or any other variation of 0: .0 , 0.0000 or 0.e00. It prints all 6 - "rule1, rule2,.... rule6".
Invalid input includes negative numbers, they should be printed as-is:
-1 prints '-1', -2 prints -2.

any digits in scientific notation that are not in [1 .. 6] should be printed as is.
any single char or string, English and non-English (like dot) is printed as-is; 'nine' is printed 'nine' and "ывъхзъх" is printed "ывъхзъх".

Sample input:
1.0  03

 +5

 2.0e0
+.4e1
6.E+00
20e-1 2e1 2ва . 1e-307

expected output:
rule1
rule3
rule5
rule2
rule4
rule6
rule2
2e1
2ва
.
1e-307

Here is my code.  I'm looking to make it more elegant.
from math import modf
import fileinput

rule1 = 'rule1'
rule2 = 'rule2'
rule3 = 'rule3'
rule4 = 'rule4'
rule5 = 'rule5'
rule6 = 'rule6'

def print_rule(n):
    if n == 1:
        print(rule1)
    elif n == 2:
        print(rule2)
    elif n == 3:
        print(rule3)
    elif n == 4:
        print(rule4)
    elif n == 5:
        print(rule5)
    elif n == 6:
        print(rule6)

def print_all():
    print(rule1)
    print(rule2)
    print(rule3)
    print(rule4)
    print(rule5)
    print(rule6)

def get_num(s):
    try:
        s = int(s)

        if s == 0:
            print_all()

        elif s in [1, 2, 3, 4, 5, 6]:
            print_rule(s)
        elif s < 1 or s > 6:
            print(s)
    except ValueError:
        try:
            saved = s
            s = float(s)
            if s == 0:
                print_all()
            elif s < 1 or s > 6:
                print(saved)

            else:
                s = float(s)
                s = check_float(s)
                if s == 0:
                    print_all()
                elif s in [1, 2, 3, 4, 5, 6]:
                    print_rule(s)
                else:
                    print(s)

        except ValueError:
            print(s)

def check_float(n):
    frac, _ = modf(n)
    if frac != 0:
        return n
    else:
        return n

def test2():

    for line in fileinput.input():
        line = line.strip().split()

        for item in line:
            get_num(item)

if __name__ == "__main__":

    test2()


texts:
I created a load balancing server at work and have to keep track of which server it adds the user to, so I wrote a little Ruby script that will do just that.

I'm looking for any critique of my work, can I do anything better at all.

Source(user information, directory information, and server information changed for security):

#!/local/usr/bin/ruby

require 'net/ssh'

@username = 'user'
@password =  nil
@host     = 'server_to_run_command_on'

def loadbalance_server_data(user)
  check = Net::SSH.start(@host, @username, :password => @password)
  cmd = "finduser #{user}" #<= Custom command that finds user info
  res = check.exec!(cmd)
  data = res
  write_data(data)
end

def write_data(data)
  File.open("path/to/log.txt", "a+"){ |s| s.puts(data) }
end

user_list = %w(user user user).each do |user|
  loadbalance_server_data(user)
end

Example of log:

Querying: servers..

Server usage report for user
        server_name:
        server_name:
        server_name:
        server_name:
        server_name:
        server_name:
        server_name:  dbus-daemon gvfsd thunderbird #<= These programs always run on this server no matter what server they are logged in on
        server_name:
        server_name:
        server_name:  dbus-daemon dbus-launch do_4000_clone_u execrulz gam_server gnome-screensav gnome-settings- gnome-vfs-daemo newphp openbox openbox-session qccm soffice soffice.bin tint2 umessage #<= The server the user is logged in on
        server_name:


texts: php swiftmailer two message instances with one mailer instance?

texts:
I created a simple function for swiftmailer to send two different messages for support and client. Not sure i did it the rigth way as I am using two different instances for message and one mailer instance. Everything works just fine but am I doing it the right way or I have to create separate mailer instance for each message? Here is my code, if someone could point out if it is ok or could be done better:

<?php

if ((isset($_POST['email'])) && (strlen(trim($_POST['email'])) > 0)) {
    $email = stripslashes(strip_tags($_POST['email']));
} else {$email = 'No data';}

require_once '/home/sitename/public_html/inc/swift/lib/swift_required.php';

function send_email($info){

    $transport = Swift_MailTransport::newInstance();

    $mailer = Swift_Mailer::newInstance($transport);

    //Create the message for support
    $message = Swift_Message::newInstance()
        ->setSubject('Subject 1')
        ->setFrom(array('info@domain.com' => 'Info'))
        ->setTo(array(
            'name1@domain.com',
            'name2@domain.com',
        ))
        ->setBody($info['message_support'],'text/html');

    //Create the message for client
    $message2 = Swift_Message::newInstance()
        ->setSubject('Subject 2')
        ->setFrom(array('info@domain.com' => 'Info'))
        ->setTo(array(
            $info['email']
        ))
        ->setBody($info['message_client'],'text/html');

    if ($mailer->send($message) && $mailer->send($message2))
        return true;
    else
        return false;
}

$info = array(
    'email' => $email,
    'message_support' => '
Dear Support

Hello World
',
    'message_client' => '
Dear Client

Hello World
'
);

if (send_email($info))
{
  header("Location:/thank-you");
}
else
{
  header("Location:/error");
}

?>


texts: Page Object Model class structure in Selenium

texts:
I am automating a webform, and this is what I've coded so far. I am curious if you find the code good and readable. But most important to me is to get some feedback for learning purposes.

The remove account page:

public class RemoveAccountsPage extends Page {

    private Boolean accountsToRemove() {
        by = By.className("zero-results-filter");
        return ((elementExists(by)) ? true : false);
    }

    private void selectAllAccounts() {
        by = By.id("accounts-select-all");
        element = waitForPresenceOfElement(by);
        element.click();
    }

    private void clickRemoveButton() {
        by = By.id("account-delete");
        element = waitForPresenceOfElement(by);
        element.click();
    }

    private void confirmRemovingAccounts() {
        by = By.id("confirm");
        element = waitForPresenceOfElement(by);
        element.click();
        //driver.findElement(By.id("NO_DEAL_VIA_MP")).click()
    }

    public void removeAccounts() throws Exception {
        String request = Page.URL + "/hu/accounts/index.html";
        goToWebPage(request);

        Boolean result = accountsToRemove();
        if(result == false) {
            selectAllAccounts();
            clickRemoveButton();
            confirmRemovingAccounts();
        }

        Thread.sleep(1000);
    }
}

Main class:

public class AccountManager {
    public static void main(String args[]) throws Exception {
        Bot bot = new Bot();
        bot.setUp();

        ........

        RemoveAccountsPage removeAccountsPage = new
        RemoveAccountsPage();
        removeAccountsPage.removeAccounts();

        ........

        bot.tearDown();

    }
}


texts:
I have a FactoryGirl page that generates same data but in two different languages. The variable names are the same. How do I write it in the smartest way possible without having to write a huge bunch of code?

    FactoryGirl.define do
      factory :static_page do
        language ""

        trait :purchase_loan do
          page_name "Purchase Loan Wizard"
          titlebar_text "Home Loan Wizard -Compare and find the best home loan in Indonesia"
         language "en"
        end

        trait :refinance_loan do
          page_name "Purchase Loan Wizard"
          titlebar_text "Rumah Kita Wizard -Dah Bayar rumah Best di Indonesia"
          language "ms"
        end

      end
    end


texts:
I've a created a simple generic numeric input component with input mask which must only valid decimal numbers as input. Please check the code for any improvements.

import React, { useState } from 'react';
import PatternConstants from '../Constants/PatternConstants.js';

const NumericInput = (props) => {

   const pattern = props.pattern ?? PatternConstants.NUMERIC_INPUT_PATTERN;
   const regexPattern = new RegExp(pattern);
   const initValue = regexPattern.test(props.value) ? props.value : '';
   const [inputValue, updateInputValue] = useState(initValue);

   const onInputChange = (event) => {
        const value = event.target.value;

        if (value.charAt(value.length - 1) === '.' && value.match(PatternConstants.NUMERIC_INPUT_LAST_DOT_PATTERN)?.length < 2) {
            updateInputValue(value);
        }

        if (value === '' || regexPattern.test(value)) {
            updateInputValue(value);
        }
    }

    return (
            <input type="text"
                placeholder="Test"
                value={inputValue}
                onChange={(event) => onInputChange(event)} />
    )
}

export default NumericInput;

PatternConstants

const PatternConstants = {
     NUMERIC_INPUT_PATTERN: /^[0-9]+(\.[0-9]+)?$/,
     NUMERIC_INPUT_LAST_DOT_PATTERN: /^[0-9]+(\.)$/,
}

export default PatternConstants;


texts:
This Code is old and I am trying to figure out how to improve it. I am considering running the distance function in MySQL, but it is a ***** to figure out for me due to my experience with arithmetic in MySQL.

$id = $_GET['id'];
    $data = $_SESSION[$id];
    $airline = $data['airline'];
    $hub = $data['hub'];
    $ident = $data['originAirport'];
    $type = $data['type'];

//Query for Origin Airport Details
$query_org = $db->prepare("SELECT `ident`, `name`, `latitude_deg`, `longitude_deg`, `elevation_ft` FROM `airports` WHERE `ident` = :ident");
$query_org->bindParam(":ident", $ident);
$query_org->execute();
$originDetails = $query_org->fetch(PDO::FETCH_ASSOC);
$query_des = $db->prepare("SELECT `ident`, `type`, `name`, `latitude_deg`, `longitude_deg`, `elevation_ft` FROM `airports` WHERE `type` = :type");
$query_des->bindParam(":type", $type);
$query_des->execute();
$num = 0;
while ($destinDetails = $query_des->fetch(PDO::FETCH_ASSOC)) {
    $distance = distance($originDetails['latitude_deg'], $originDetails['longitude_deg'], $destinDetails['latitude_deg'], $destinDetails['longitude_deg'], "N");
    if ($distance >= $data['dismin'] && $distance <= $data['dismax']) {
        $a[$num] = array(
            'ident'         => $destinDetails['ident'],
            'type'          => $destinDetails['type'],
            'name'          => $destinDetails['name'],
            'elevation_ft'  => $destinDetails['elevation_ft'],
            'distance'      => $distance
        );
        $num++;
    }
}

$num = null;
$num = 0;

foreach ($a as $z) {
    $i = $z['ident'];
    $query_run = $db->prepare("SELECT `length_ft` FROM `runways` WHERE `airport_ident` = :ident");
    $query_run->bindParam(":ident", $i);
    $query_run->execute();
    $result = $query_run->fetch(PDO::FETCH_ASSOC);
    $length = $result['length_ft'];
    if ($length >= $data['minrunlen'] && $length <= $data['maxrunlen']) {
        $b[$num] = array(
            'icao' => $z['ident'],
            'name' => $z['name'],
            'distance' => $z['distance']
            );
        $num++;
    }

}

$count = count($b);

$int = rand(0, $count);

//Query for Flight_ID
$queryc = $db->prepare("SELECT `fid` FROM `dispatches` ORDER BY `id` DESC");
$queryc->execute();
$flight_id = $queryc->fetch(PDO::FETCH_NUM);
if ($flight_id[0] !== 1000) {
    $flight_id = (int)$flight_id[0];
    $flight_id++;
} else {
    $flight_id = 1000;
}
$dispatch = array(
    'airline'       => strtoupper($data['airline']),
    'hub'           => strtoupper($data['hub']),
    'pid'           => $data['pid'],
    'pilot'         => $data['fname'].' '.$data['lname'],
    'email'         => $data['email'],
    'fid'           => $flight_id,
    'airframe'      => $data['airframe'],
    'datetime'      => date("Y-m-d H:i:s"),
    'connumb'       => md5(rand(0,9999999999)),
    'originICAO'    => $originDetails['ident'],
    'originName'    => utf8_encode($originDetails['name']),
    'destinICAO'    => $b[$int]['icao'],
    'destinName'    => utf8_encode($b[$int]['name']),
    'distance'      => $b[$int]['distance']."nm"
);
//Query for runway information
$destinICAO = $dispatch['destinICAO'];
$queryd = $db->prepare("SELECT `length_ft`, `width_ft`, `lighted`, `closed`, `le_ident`, `le_latitude_deg`, `le_longitude_deg`, `le_elevation_ft`, `le_heading_degT`, `le_displaced_threshold_ft`, `he_ident`, `he_latitude_deg`, `he_longitude_deg`, `he_elevation_ft`, `he_heading_degT`, `he_displaced_threshold_ft` FROM `runways` WHERE `airport_ident` = :ident");
$queryd->bindParam(":ident", $destinICAO);
$queryd->execute();

Any suggestions are helpful. I am not looking for anybody to rewrite the code. That is my job, but guidance is more what I am looking for.


texts: How to replace plain URLs with links, in javascript?

texts:
I've nearly got this working.  I wanted to know if there is a much better way.  One problem is that no matter what there will be cases where a URL is incorrectly identified and as such the end result will be dependent on requirements.  My requirements are lackadaisy, I just want something that works most of the time.  However some of the URLs in my fiddle are not being detected correctly and I'd like advice on the regex part of this for overcome these.  The main issue here is that the overall design is in question, the should be a simpler method.

Root problem

Fiddle

function replaceURLWithHTMLLinks(text) {
    text = text.replace(/a/g, "--ucsps--");
    text = text.replace(/b/g, "--uspds--");
    var arrRegex = [
        /(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|])(.?\))/ig,
        /()(\b(?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])(.?\b)/ig];
    for (i = 0; i < arrRegex.length; i++) {
        text = text.replace(arrRegex[i], "$1a$2b$3");
    }
    text = text.replace(/a([^b]*)b/g, "$1");
    text = text.replace(/--ucsps--/g, "a");
    text = text.replace(/--uspds--/g, "b");
    return text;
}
var elm = document.getElementById('trythis');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);

Any thoughts?


texts:
I have multiple forms that send an email. As of this moment I have 3 forms that send mail and vary only by the number of inputs:

One requires just an email
Another requires a name and email
Another requires name, email, and a comment

Instead of making 3 separate functions to mail the inputs away, I figured I could consolidate them into 1. The issue here is a lot of if statements. The code all works, but spans around 30 lines, which seems like too much.

function sendMail()
{
$comment = null;
$to =  "destination@mail.com";
$copy = "mymail@mail.com";
$subject = "Email..";
if (isset($_POST["contactSubscribe"]) || isset($_POST["questionSubmit"]) || isset($_POST["submit"])) {
  foreach ($_POST as $field => $value) {
    if ($field == "contactName") {
      $contactName = $value;
    }
    if ($field == "email") {
      $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    }
    if ($field == "comment") {
      $comment = $value;
    }
  }
}
if (!is_null($contactName) && is_null($comment) ) {
  $message = "Name: $contactName Email: $email";
}
if (is_null($comment) && is_null($contactName)) {
  $message = "inputname=i_" . $email;
}
if (!is_null($contactName) && !is_null($comment) ) {
  $message = "Name: $contactName Email: $email Message: $comment";
}
mail($to, $subject, $message);
mail($copy, $subject, $message);
}


texts:
Can someone look over this Sieve of Eratosthenes implementation? It seems almost too easy.

Rather than maintaining a seperate bit[] to track prime/not prime, I'm just removing the noncandidates from the collection completely on each iteration.

Pseudocode

LIST = 2...n

set M = 1
while M < sqrt(n)
   set M = next number in LIST > M
   remove all multiples of M (excluding M itself) from LIST

C#

int cur = 1, total = 1000;
var pc = Enumerable.Range(2, total).ToList();

while(cur <= Math.Sqrt(total))
{
    cur = pc.First(i => i > cur);
    pc.RemoveAll(i => i != cur && i % cur == 0);
}

Console.WriteLine(pc.Max());

It just seems a bit too easy. Results seem right though. In LINQPad 4

Runs total = 100000; in 0.008 secs
Runs total = 1000000; in 0.141 secs
Runs total = 10000000; in 2.973 secs


texts: Tweeting NASA's Astronomy Pic of the Day

texts:
I want to know how I can make this old code faster, cleaner and compact. It may look like bad code because I did it when I first started with Python.

# -*- coding: utf-8 -*-

import urllib
import time
import os
from twython import Twython
from bs4 import BeautifulSoup as bs

class Alfred():

    def __init__(self):
        self.url = "http://apod.nasa.gov/apod/astropix.html"
        self.time = time.localtime()
        self.app_key = "XXX"
        self.app_sec = "XXX"
        self.token_key = "XXX"
        self.token_sec = "XXX"
        self.img_path = "static/img/"

    def start(self):

        tw = Twython(self.app_key, self.app_sec, self.token_key, self.token_sec)

        while True:

            if self.time[3] < 5:
                web = urllib.urlopen(self.url)
                soup = bs(web, "html.parser")
                img = soup.find("img")
                img_src = img.get("src")
                img_name = img_src[11:]

                if os.path.isfile(self.img_path + img_name):

                    pass

                else:

                    img_list = os.listdir(self.img_path)

                    for file_name in img_list:
                        os.remove(self.img_path + file_name)

                    img_url = "http://apod.nasa.gov/apod/" + img_src
                    urllib.urlretrieve(img_url, 'static/img/' + img_name)
                    photo = open(self.img_path + img_name, 'rb')
                    response = tw.upload_media(media=photo)
                    tw.update_status(status="Imagen astronómica del día. (vía: NASA). ~Alfred", media_ids=[response['media_id']])

            else:

                pass

a = Alfred()
a.start()


texts: Selecting three tables with relationship

texts:
I've been working on improving my website code.  I've noticed that querying from a table inside a PHP while function, where while loop is also querying another table:

while($row = mysql_fetch_assoc($table1)){
$table2 = mysql_query(select);
mysql_fetch_assoc($table2);
}

It might be slowing down the performance, depending on the fact that we're querying the second table for each row of the first table.

So I've decided to select both of the tables from the same query.  I came up with this code to accomplish what I think is more sufficient.

Now I have few questions:

Am I correct for what I've said about the way my old code is slow?
Would using PHP functions to query from each table individually be more sufficient?
Is there anything that I need to add or change in my code, that I've made?

Code:

SELECT posts.*, users.username, SUM(IF(rates.hash = posts.hash, (rates.likes - rates.dislikes), 0)) AS rate
FROM posts,users,rates WHERE posts.position = posts.submitter AND users.username = posts.submitter GROUP BY posts.hash ORDER BY posts.ID DESC LIMIT 5


texts:
This checker works perfectly but I have a strong feeling that I could make this script much more compliant with the "Zen of Python", especially having read a book about it recently. There is no doubt that I made this script much longer than needed, so if you see something I can shorten, please say so.

#!/usr/bin/env python

myPhrase = "The quick brown fox jumps over the lazy dog"

def is_pangram(phrase):
    c = 0
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    phraseLetters = ""
    for char in phrase:
        for letter in alphabet:
            if char == letter and char not in phraseLetters:
                phraseLetters += char
    for char in phraseLetters:
        for letter in alphabet:
            if char == letter:
                c += 1
    if c == 26:
        return True
    else:
        print phraseLetters, alphabet
        return False

print is_pangram(myPhrase)


texts: Averaging a list of intersecting rectangles

texts:
I have a list of rectangles as tuples (x, y, w, h).  I need to find which ones intersect and if they do, average all the intersecting rectangles into a new rectangle. I also track the resultant averaged rectangle "weight" (the number of intersecting rectangles) as an addition member in the new tuple. (x, y, w, h, weight)

The final return is resultant list of averaged sorted by weight.

I am looking for feedback on how to improve performance and make it even more pythonic.  Or, as I have discovered many times in python, there may a completely different and better way to approach the problem (such as with NumPy).

I pass a list of rect tuples to ordered_average_intersecting_rects:

import numpy as np

def rects_intersect(r1, r2):
    hoverlaps = (r1[0] <= r2[0] + r2[2]) and (r1[0] + r1[2] >= r2[0])
    voverlaps = (r1[1] <= r2[1] + r2[3]) and (r1[1] + r1[3] >= r2[1])

    return hoverlaps and voverlaps

def average_rects(rects):
    x = np.average([coord[0] for coord in rects])
    y = np.average([coord[1] for coord in rects])
    w = np.average([coord[2] for coord in rects])
    h = np.average([coord[3] for coord in rects])

    return x, y, w, h, len(rects)

def ordered_average_intersecting_rects(rects):
    intersecting_rect_clusters = []

    while rects:  # modified from `while len(rect) > 0:` (janos feedback)
        r1 = rects[0]
        rect_cluster = [r1]

        for r2 in rects[1:]:
            if rects_intersect(r1, r2):
                rect_cluster.append(r2)
                rects.remove(r2)

        rects.remove(r1)
        intersecting_rect_clusters.append(rect_cluster)

    averaged_rects = [average_rects(cluster) for cluster in intersecting_rect_clusters]
    averaged_rects.sort(key=lambda w: w[4], reverse=True)

    return averaged_rects

Here is my unit test to help understand how the code is being used:

def test_ordered_average_intersecting_rects(self):

    # Arrange
    rects = [(150, 55, 40, 20, 0),
             (160, 40, 20, 20, 0),
             (100, 120, 20, 20, 0),
             (45, 10, 15, 30, 0),
             (50, 25, 25, 20, 0),
             (35, 35, 20, 30, 0)]

    # Act
    with test_helpers.Timer('average_intersecting_rects') as t:
        result = ordered_average_intersecting_rects(rects)

    # Assert
    assert len(result) == 3

    cluster1 = result[0]
    assert cluster1[4] == 3
    assert int(cluster1[0]) == 43
    assert int(cluster1[1]) == 23
    assert int(cluster1[2]) == 20
    assert int(cluster1[3]) == 26

    cluster2 = result[1]
    assert cluster2[4] == 2
    assert cluster2[0] == 155
    assert cluster2[1] == 47.5
    assert cluster2[2] == 30
    assert cluster2[3] == 20

    cluster3 = result[2]
    assert cluster3[4] == 1
    assert cluster3[0] == 100
    assert cluster3[1] == 120
    assert cluster3[2] == 20
    assert cluster3[3] == 20


texts: Display students of specific age using struct

texts:
My task for uni is to create a program using structures. In this program I have to make an entry of students, their name, birth date and group (a random number). And I have to search the students according to the input age.

Please note that I am still learning :)

#include <iostream>
#include <cstring>

using namespace std;

struct student
{
char name[50];
int year;
int group;

};

int main( )
{
int N;
int age;

cout<<"Enter how many entries:";
cin>>N;
struct student student1[N];

for (int i=0;i<N;i++)
{
cout<<"enter the student's name:";
cin>>student1[i].name;
cout<<"enter the birth year:";
cin>>student1[i].year;
cout<<"enter the group:";
cin>>student1[i].group;
}
cout<<"enter the student's age:";
cin>>age;

if (age==2016-student1[N].year)
{
    cout<<"The student with the age "<<age<<" is:";
    cout<<student1[N].name;
    cout<<student1[N].group;
}
else
{
    cout<<"the student wasn't found.";
}
return 0;
}


texts: FizzBuzz Solution Rags to Different Rags

texts:
I took some code and reviewed it, but it got me thinking, so I re wrote the code a little bit and would like to ask what you think of it and why it's bad to do this, even though it works.

public class FizzBuzz{
    public static void main(String[] args){
        for(int i = 1 ; i < 101; i++)
            if(i % (5*3) == 0)
                System.out.println("FizzBuzz");
            else if(i % 3 == 0)
                System.out.println("Fizz");
            else if(i % 5 == 0)
                System.out.println("Buzz");
            else
                System.out.println(i);
    }
}

I removed braces because these are all essentially one-line statements and don't need them, so what does this say about my Java coding style?


texts:
I'm kinda new at this jQuery stuff and I've gathered up this much to make my code functional, but I would really want to shorten it. I've already tried $('#Monday','#Tuesday'....) to group them, but with no success.

$('#Monday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Tuesday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Wednesday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Thursday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Friday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Saturday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
$('#Sunday').click(function() {
    if ($(this).hasClass("active")){
        $(this).switchClass( "active", "inactive", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', true);
    } else {
        $(this).switchClass( "inactive", "active", 200, "easeInOutQuad" );
        $(this).parent().find('.miniTime').prop('disabled', false);
    }
    $(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});


texts: ActiveRecord object for billing and shipping addresses

texts:
I have an Order object that belongs_to a BillingAddress and a ShippingAddress. I want to present my user with only ShippingAddress fields and a checked checkbox indicating that the billing address matches the shipping address. If the user unchecks the box, the BillingAddress fields appear.
This design proved painful to implement, and my Order object has a lot of callbacks I would rather not have.
class Order < ActiveRecord::Base
  attr_accessor :bill_to_shipping_address

  belongs_to :billing_address,  class_name: 'Address'
  belongs_to :shipping_address, class_name: 'Address'

  accepts_nested_attributes_for :billing_address, :shipping_address

  after_initialize  :set_billing_to_shipping_address
  before_validation :set_billing_address
  after_validation  :clear_billing_address_errors

  # Init the object with option checked
  def set_billing_to_shipping_address
    self.bill_to_shipping_address ||= '1'
  end

  # Copy shipping address attrs to billing address
  def set_billing_address
    self.billing_address = self.shipping_address if bill_to_shipping_address?
  end

  def bill_to_shipping_address?
    bill_to_shipping_address == '1'
  end

  # If shipping address matches billing, we copy the attrs, and thus duplicate errors too.
  # We only need to show the user one set of errors if addresses are the same, so remove them for billing address.
  def clear_billing_address_errors
    if bill_to_shipping_address?
      self.errors.messages.each { |k,v| self.errors.messages.delete(k) if k.to_s.split('.')[0] == 'billing_address' }
    end
  end
end

This feels smelly, and I have four methods along with three registered callbacks  to satisfy this need. I have no logic in the controller and the form is relatively simple.
= form_for @order do |f|
    # ...
    = f.label :bill_to_shipping_address, class: 'checkbox' do
      #{f.check_box :bill_to_shipping_address} Use my shipping address as my billing address.

This doesn't feel right. I'm also hacking around the error messages.
Questions:

How can I improve my design?

Would switching the relationships help?
Order has_one :billing_address and has_one :shipping_address instead of belongs_to. Nested forms will feel more natural; in that, a parent creates children, not the other way around.

I'm reading a fair bit of refactoring books, but I can never map their examples to my own object design. I'm not that experienced I guess.


texts:
To find neighbors of a vector and return array of Vectors which are neighbors of a Vector:
vector<XY> neighboursOf(XY coord){
    short x = coord.x;
    short y = coord.y;

    vector<XY> neighbours;
    neighbours.reserve(9);

    neighbours.push_back(XY(x-1, y));
    neighbours.push_back(XY(x-1, y-1));
    neighbours.push_back(XY(x-1, y+1));

    neighbours.push_back(XY(x+1, y));
    neighbours.push_back(XY(x+1, y-1));
    neighbours.push_back(XY(x+1, y+1));
    neighbours.push_back(XY(x+1, y-1));

    neighbours.push_back(XY(x, y-1));
    neighbours.push_back(XY(x, y+1));

    return neighbours;
}
}

XY is a class which has members x and y:
class XY{
    public:
    XY(short x=0, short y=0);
    short x;
    short y;
};

XY::XY(short x, short y) {
    this->x = x;
    this->y = y;
}

The param is Vector of the yellow square, the neighbor array is supposed to be the black squares


texts:
I have been working on the following kata from CodeWars. It's basically a Caesar Cipher — see the test cases below my solution code.

Any comments/feedback appreciated!

def encryptor(key, message):
    new = ""
    for letter in message:
        if letter.isalpha():
            id = ord(letter)
            shift = id+key
            if 97 <= id <= 122:
                while shift>122:
                    shift -= 26
                while shift<97:
                    shift += 26
                letter = chr(shift)
            if 65 <= id <= 90:
                while shift>90:
                    shift -= 26
                while shift<65:
                    shift += 26
                letter = chr(shift)
        new = new + letter
    return new

And here are test cases that give you an idea of what is being looked for:

test.assert_equals(encryptor(13, ''), '')
test.assert_equals(encryptor(13, 'Caesar Cipher'), 'Pnrfne Pvcure')
test.assert_equals(encryptor(-5, 'Hello World!'), 'Czggj Rjmgy!')
test.assert_equals(encryptor(27, 'Whoopi Goldberg'), 'Xippqj Hpmecfsh')


texts: First Python program: Tic-Tac-Toe (Followup)

texts:
I am unsure if I followed the the suggestions on my previous post.
I have only been working on programming for about 3 weeks so any more suggestions or insight would be more than welcomed.

import sys
from textwrap import dedent
import os
import random

os.system('CLS')

# board number setup
board = [0, 1, 2,
         3, 4, 5,
         6, 7, 8]

# Defines the board layout printed to the console
def board_layout():
    print(dedent(f'''
    *************
    * {board[0]} | {board[1]} | {board[2]} *
    *-----------*
    * {board[3]} | {board[4]} | {board[5]} *
    *-----------*
    * {board[6]} | {board[7]} | {board[8]} *
    *************
    '''))

def main():
    players = ('Player','NPC')
    turn = 'Player'
    change_turn = 0
    for moves in range(9):
        if turn == 'Player':
            while True:
                try:
                    board_layout()
                    player_move = int(input('Please select a spot: '))
                    if board[player_move] != 'x' and board[player_move] != 'o':
                        board[player_move] = 'x'
                        check_winner()
                        break
                except IndexError:
                    print('please select valid spot')
        if turn == 'NPC':
             # npc move, chooses a random spot that is not taken
            while True:
                npc = random.randint(0, 8)
                if board[npc] != 'o' and board[npc] != 'x':
                    board[npc] = 'o'
                    print('Computer chooses spot ', npc)
                    check_winner()
                    break
        try:
            change_turn += 1
            turn = players[change_turn]
        except:
            change_turn = 0
            turn = players[change_turn]
    else:
       print('You Tied')
       end()

def end():
        print('Thank you for playing')
        answer = input('Would you like to play again?: Y/N')

        if answer.lower() == 'n':
            quit()
        elif answer.lower() == 'y':
                    clear_board()
                    main()
        else:
            print('Please choose a valid option')
            end()

def clear_board():
    for i in range(9):
        board[i] = i

# checks for a winner when called at end of each turn
def check_winner():

            # list of lists with all the winning combinations for from the tic tac toe board
            winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
                            [board[6], board[7], board[8]], [board[0], board[4], board[8]],
                            [board[2], board[4], board[6]],
                            [board[0], board[3], board[6]], [board[1], board[4], board[7]],
                            [board[2], board[5], board[8]]]

            # iterates over the lists in winning_list
            for i, j, k in winning_list:
                # looks at the lists in winning_list to determine if a list has all x's for a win
                if i == 'x' and j == 'x' and k == 'x':
                    print('X wins')
                    end()
                # looks at the lists in winning_list to determine if a list has all o's for a win
                elif i == 'o' and j == 'o' and k == 'o':
                    print('O wins')
                    end()

if __name__ == "__main__":
    main()


texts: Finding the upper and lower bound using binary search

texts:
I am trying to solve this InterviewBit question
https://www.interviewbit.com/problems/search-for-a-range/.

My code for this seems to be working properly and it does give me the correct answers on my IDE and on all the sample test cases online but it gives me a TLE on the online judge. It runs in O(log n) time, just a variation of simple binary search.

I am trying to understand what aspect of my code could be made more efficient and faster.

Here's my code:

int findBound(vector<int> a, int b, bool lower){
int low=0, high=a.size()-1, mid;
while(low<=high){
    mid=low+(high-low)/2;
    if(a[mid]==b){
        if(lower){
            if((mid != (a.size()-1)) && a[mid+1]==b)
                low=mid+1;
            else
                return mid;
        }
        else{
            if(mid != 0 && a[mid-1]==b)
                high=mid-1;
            else
                return mid;
        }
    }
    else if(a[mid]>b)
        high=mid-1;
    else if(a[mid]<b)
        low=mid+1;
}
return -1;
}

vector<int> Solution::searchRange(const vector<int> &A, int B) {
    vector<int> ans(2);
    ans[0]=findBound(A, B, true);
    ans[1]=findBound(A, B, false);
    return ans;
}


texts: Take a number and sum its digits raised to the consecutive powers

texts:
I am new to Scala have to solve this problem:

  If you have number "xy" should equal  sum of  consecutive powers of its digits

  xy = x^1 + y^2

  For example, take the number 89 and you should have:

  89 = 8^1+ 9^2

  And if we have a list we should filter with the matched numbers based on the above role.

  For example:

  Consider these range of numbers:

  (1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

  (90, 100) == []

This code works fine, but is this a pure functional programming style or are there some best practices in terms of performance and functionality?

def myFun(str: String):Double ={

   val myDigits=str.toList.map(_.asDigit)

   (myDigits.indices zip myDigits).toMap.map({case(x , y) =>  pow(y,x+1)}).reduce(_+_)

}

(1 to 100 ) .toList.filter({ case(x) => x == myFun(x.toString) })


texts:
I would like a code review on the coding I did for my assignment. The reason I have asked here is because my lecturer has no intention of going through (Don't ask me why, I asked before and he said no..) and I have no idea if I am doing it right or not.. All my other classmates seems to have different answers too, some have deck class, shuffle function etc..

Anyway the question is asking the user to design and implement a class that represent a playing card in which it can be used to play card games. Consider what information you needs to be stored in a card and what you man want to do with a card (accessors/mutators).

In this assignment, only 2 files are required - 1 header and 1 implementation file.
Kindly see the following:

Header file

#ifndef  CARD_H
#define  CARD_H
#include<string>

using namespace std;

class card
{
    private:
        string cardSuit;
        string cardValue;

    public:
        // Constructor
        string displayCard(string, string);

        // Member Functions
        string getSuit();
        string getValue();

        // Default
        card();

};
#endif

Implementation File

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "card.h"

using namespace std;

card::card()
{
    srand(time(0));
    cardSuit = getSuit();
    cardValue = getValue();
}

string card::displayCard(string suit, string value)
{
    return cardSuit + " of " + cardValue;
}

string card::getSuit()
{

    string arrSuits[] = {"HEARTS", "DIAMONDS", "CLUBS", "SPADES"};

    // 1 out of 4 suits is choose randomly
    int randSuits = rand() % 4;
    return arrSuits[randSuits];
}

string card::getValue()
{
    string arrValues[] = {"ACE", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING"};

    // 1 out of 13 values is choose randomly
    int randValues = rand() % 13;

    return arrValues[randValues];
}

As I have only started out in C++, do pardon me if my coding format is wrong etc.


texts:
I need to pull things from lazy source till timeout is reached in this fashion:

var results = lazySource.SelectMany(item =>
{
    //processing goes here
}).Pull(timeout: TimeSpan.FromSeconds(5), times: maxNumberOfIterations);

and I have this solution:

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? times = null)
    {
        if (times == null)
            return enumerable.ToArray();
        else
            return enumerable.Take(times.Value).ToArray();
    }

    public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, TimeSpan timeout, int? times = null)
    {
        var stopwatch = new Stopwatch();

        stopwatch.Start();

        if (times != null) enumerable = enumerable.Take(times.Value);

        using (var iterator = enumerable.GetEnumerator())
        {
            while (stopwatch.Elapsed < timeout && iterator.MoveNext())
                yield return iterator.Current;
        }
    }
}

Am I just reinvented the wheel and it can be done using some external libs? like Rx/Ix maybe ...


texts:
I would like to submit my enhanced concatenating function for your review. Originally, its method signature is:

char *concat (const *char1, const *char2);

but after knowing that the calling code must supply all the arguments when it calls the function, I modified the method signature to:

char *enhconcat (const char *str1, int start_index1, int end_index1, const char *str2, int start_index2, int end_index2);

supplying the necessary positional arguments, so I think the code is more secured and adaptable to future changes.

Please suggest ways to improve this code and make it more secure.

/* enhconcat.c: enhanced concat - for more secured concatenating */

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

char *
enhconcat (const char *str1, int start_index1, int end_index1,
           const char *str2, int start_index2, int end_index2);

int main (void) {

     const char *part1 = "Cuius est solum, ";
     const char *part2 = "eius est usque ad coelum et ad inferos.";
     printf ("%s\n", enhconcat (part1, 0, strlen (part1), part2, 0, strlen (part2)));
     return (EXIT_SUCCESS);
}

char *
enhconcat (const char *str1, int start_index1, int end_index1,
           const char *str2, int start_index2, int end_index2)
{
   int m = end_index1 - start_index1;
   int n = end_index2 - start_index2;
   char *concatstr;
   concatstr = malloc (m + n + 1);
   if (!concatstr) {
      printf ("Unable to allocate memory.\n");
      exit (EXIT_FAILURE);
   }
   char *chrptr;
   chrptr = concatstr; // store address of concatstr
   for (int i = start_index1; i < m; i++) {
      *chrptr = str1[i];
      chrptr++;
   }
   for (int j = start_index2; j < n; j++) {
      *chrptr = str2[j];
      chrptr++;
   }
   *chrptr = '\0';
   return concatstr;
} /* end of enhconcat() */


texts: Monitoring directories for files that are generated by an engineering program

texts:
I have a service that monitors failure and success directories for files that are generated by an engineering program. I want to check the change was in the success or failure folder, and if it was a new file creation. When those criteria are met I need to check if the file type matches one of the keys for a dictionary, and if it does I want to copy that file to a destination as declared in the config file.

I have an if statement that says:

if (NormalizePath(Path.GetDirectoryName(e.FullPath)) == NormalizePath(this.successFolder)
        && e.ChangeType == WatcherChangeTypes.Created)
{
    string fileExtension = Path.GetExtension(e.FullPath);
    try
    {
        //if the file type is desired copy to destinations.
        if( this.successDictionary.ContainsKey(fileExtension) )
        {
            CopyToDestination(this.successDictionary[fileExtension], e);
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}
//if a file was added to the fail folder
else if (NormalizePath(Path.GetDirectoryName(e.FullPath)) == NormalizePath(this.failFolder)
            && e.ChangeType == WatcherChangeTypes.Created)
{
    activeLog.WriteLineToLog(e.FullPath + " has been added to the fail folder.");
    string fileExtension = Path.GetExtension(e.FullPath);
    try
    {
        //if the file type is desired copy to destinations.
        if (this.failDictionary.ContainsKey(fileExtension))
        {
            CopyToDestination(this.failDictionary[fileExtension], e);
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}

Is it better to do it the first way or the second way?

string fileExtension = Path.GetExtension(e.FullPath);
if (NormalizePath(Path.GetDirectoryName(e.FullPath)) == NormalizePath(this.successFolder)
        && e.ChangeType == WatcherChangeTypes.Created)
{
    try
    {
        //if the file type is desired copy to destinations.
        if( this.successDictionary.ContainsKey(fileExtension) )
        {
            CopyToDestination(this.successDictionary[fileExtension], e);
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}
//if a file was added to the fail folder
else if (NormalizePath(Path.GetDirectoryName(e.FullPath)) == NormalizePath(this.failFolder)
            && e.ChangeType == WatcherChangeTypes.Created)
{
    activeLog.WriteLineToLog(e.FullPath + " has been added to the fail folder.");
    try
    {
        //if the file type is desired copy to destinations.
        if (this.failDictionary.ContainsKey(fileExtension))
        {
            CopyToDestination(this.failDictionary[fileExtension], e);
        }
    }
    catch (IOException ioe)
    {
        activeLog.WriteLineToLog("FolderMonitor IOException: " + ioe.Message);
    }
}

It's really just a question of if it is better to sometimes waste a bit of memory, or if it is better to have it more optimized. I understand that in the grand scheme of things it's rather minimal how much memory it uses, but the voices in my head can't decide which one is better.


texts:
Is there anyway to make this piece of code more elegant? It's not a nice view, but I can't really see a way to improve the looks of it or shorten it.

private void Send(CancellationToken CTSSend)
{
    try
    {
        NativeMethods.Rect rc;
        NativeMethods.GetWindowRect(hwnd, out rc);
        IntPtr dc1;
        IntPtr dc2 = NativeMethods.GetWindowDC(hwnd);
        using (tcp = new TcpClient())
        {
            tcp.NoDelay = true;
            while (!tcp.Connected && !CTSSend.IsCancellationRequested)
            {
                try
                {
                    if (!tcp.Connected)
                        tcp.Connect(adress);
                }
                catch (Exception e)
                {
                    if (e is SocketException) { Console.WriteLine(e.Message); }
                    else
                        MessageBox.Show(e.Message + " Tcp Connect : Send");
                }
            }
            using (EncoderParameters JpegParam = new EncoderParameters())
            using (JpegParam.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 50L))
            using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            using (Graphics g = Graphics.FromImage(bmp))
            using (var ms = new MemoryStream())
            using (var tcpStream = tcp.GetStream())
                while (tcp.Connected && !CTSSend.IsCancellationRequested)
                {
                    try
                    {
                        dc1 = g.GetHdc();
                        NativeMethods.BitBlt(dc1, 0, 0, rc.Width, rc.Height, dc2, 0, 0, 13369376);
                        g.ReleaseHdc(dc1);
                        bmp.Save(ms, jpeg, JpegParam);
                        if (bsize != ms.Length)
                        {
                            bsize = ms.Length;
                            tcpStream.Write(BitConverter.GetBytes(bsize), 0, 4);
                            tcpStream.Write(ms.GetBuffer(), 0, (int)bsize);
                        }
                        ms.SetLength(0);
                    }
                    catch (Exception e)
                    {
                        if (e is IOException)
                        {
                            try { connect.Invoke(new Action(() => { connect.Text = "Connect"; })); }
                            catch (InvalidOperationException) { return; }
                            capcon = false;
                        }
                        else
                            MessageBox.Show(e.Message + ": Send Error");
                    }
                }
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message + "SEND");
    }
}

I am trying to find a nice way to put TCP reconnecting in another class, but I found a limitation where I have to call return in the main class.

internal static void TCPReconnect(CancellationToken CTS, TcpClient tcp, IPEndPoint adress)
{
    tcp.NoDelay = true;
    while (!tcp.Connected && !CTS.IsCancellationRequested)
    {
        try
        {
            if (!tcp.Connected)
                tcp.Connect(adress);
        }
        catch (Exception e)
        {
            if (e is SocketException) { Console.WriteLine(e.Message); }
            else
                MessageBox.Show(e.Message + " Tcp Connect : Send");
        }
    }

}

So, when it fails, it goes out of the loop. I can also make it call Return, but it will do the same thing.

In the class Caller I have to use:

FastMethods.TCPReconnect(CTS, tcp, adress);
if (CTS.IsCancellationRequested)
    return;

As you can see, I have to recheck for CTS. Is it possible to have it inside the other class somehow?

If I use:

if (CTS.IsCancellationRequested)
    return;

It will simply return to the main class and continue.


texts: Simple ES6 JavaScript Module “Loader” (semi follow-up)

texts:
I have recently updated my JavaScript Module "Loader" to ES6 and would like
some feedback on the code and how "ES6-y" it is. I previously asked about the
ES5 version of my code here
and I have implemented the feedback from @janos
(thank you!) in the ES6 version.

(() => {
  const definitions = {},
        instances = {};

  const isDefined = (id) => definitions.hasOwnProperty(id);

  const define = (id, definition, asInstance) => {
    if(isDefined(id)) {
      throw new Error('module already defined: ' + id);
    }

    definitions[id] = definition;

    if (typeof(definition) !== 'function' || asInstance) {
      instances[id] = definition;
    }
  };

  const undefine = (id) => {
    if (!isDefined(id)) {
      throw new Error('module not defined: ' + id);
    }

    delete definitions[id];
    delete instances[id];
  };

  const require = (...ids) => {
    if (ids.length === 0) {
      return null;
    }

    const stack = [];

    const internalRequire = (...ids) => {
      var required = ids.map((id) => {
        if(!isDefined(id)) {
          throw new Error('module not defined: ' + id);
        }

        if (stack.indexOf(id) !== -1 && stack.push(id)) {
          throw new Error('cyclic dependency: ' + stack.join(' -> '));
        }

        stack.push(id);

        if (instances.hasOwnProperty(id)) {
          return instances[id];
        }

        return instances[id] = definitions[id].call(null, internalRequire);
      });

      return required.length === 1 ? required[0] : required;
    };

    return internalRequire(...ids);
  };

  window.module = Object.defineProperty({
    define: define,
    undefine: undefine,
    require: require
  }, 'modules', {
    get: Object.keys.bind(Object, definitions)
  });
})();

Amongst the changes made by
@janos I also ended
up changing the following:

Removed the create function and moved all of the code to the top-level
IIFE.
Allowed require to accept multiple identifiers.

And as always, an example of how to use it:

module.define('person', () => {
  return class Person {
    constructor(name) {
      this.name = name;
    }

    speak(text) {
      return this.name + ': ' + text;
    }
  };
});

module.define('group', () => {
  return class Group {
    constructor(...members) {
      this.members = members;
    }

    speak(text) {
      return this.members.map((member) => member.speak(text));
    }
  };
});

module.define('main', (require) => {
  var [Person, Group] = require('person', 'group');

  var jack = new Person('Jack'),
      rocky = new Person('Rocky');

  var developers = new Group(jack, rocky);

  console.log(jack.speak('Hi Rocky!'));
  console.log(rocky.speak('Hi Jack!'));
  console.log(developers.speak('Hello everyone!'));
});

module.require('main');

One other semi-related question: which of these two is "best"?

module.define('without_return', () => class Example {
  doSomething() { }
});

module.define('with_return', () => {
  return class Example {
    doSomething() { }
  };
});

module.define('with_return_later', () => {
  class Example {
    doSomething() { }
  }

  return Example;
});

I'm not to sure on without_return as it's not that obvious that it is a class, however I don't know whether with_return or with_return_later is better, as they're both just as clear as one another.


texts: Possible antipattern: looping until a search condition is met

texts:
Whenever I write a loop, I always use closure if it's appropriate by way of a self-executing anonymous function. I will typically write my searching loops as follows:

var i = 0, length = myArr.length,
    fe = null;

for (; i < length; i++) {
    if ((function (el) {
            if (el.searchCondition) {
                fe = el;
                return true;
            }
        }(myArr[i])) === true) {
        break;
    }
}

return fe;

I thought it was minimal code and pretty clean. I know it's not the easiest to read - but is there any reason why I should not be doing it this way?


texts: Pretty print a tree from minimal data input

texts:
I'm currently working on an uncrafting tool for minecraft and got a neat output working that shows all the materials needed in a tree. I wonder if the code used to print that tree could be improved somehow. I only have the recursion depth as a measurement and the ArrayList gets filled in the same order as seen in the input example below. The output format should also stay the same, I'm quite happy with that. The input format is a bit sketchy though, any ideas on that are appreciated as well.
The Algorithm
    private static void treeprint(ArrayList<Object[]> tree) {

        ArrayList<String> stem = new ArrayList<>();

        for (int i = 0; i < tree.size() - 1; i++) {
            System.out.print(String.join("", stem));
            Object[] o = tree.get(i);
            int cdepth = (int) o[0];
            String cname = (String) o[1];
            int camt = (int) o[2];

            int ndepth = (int) tree.get(i + 1)[0];
            if (ndepth > cdepth) {
                if (isLastOfDepth(tree, cdepth, i + 1)) {
                    System.out.print("\\---");
                    stem.add("    ");
                } else {
                    System.out.print("+---");
                    stem.add("|   ");
                }

            }
            if (ndepth == cdepth) {
                if (isLastOfDepth(tree, cdepth, i + 1)) {
                    System.out.print("\\---");
                } else {
                    System.out.print("+---");
                }

            }
            if (ndepth < cdepth) {
                System.out.print("\\---");
                for (int j = 0; j < cdepth - ndepth; j++) {
                    stem.remove(stem.size() - 1);
                }
            }
            System.out.println(cname + " x " + camt);
        }

        System.out.println(String.join("", stem) + "\\---" + (String) tree.get(tree.size() - 1)[1] + " x "
                + (int) tree.get(tree.size() - 1)[2]);
    }

    private static boolean isLastOfDepth(ArrayList<Object[]> tree, int depth, int start) {

        for (int i = start; i < tree.size(); i++) {
            int cdepth = (int) tree.get(i)[0];
            if (cdepth < depth) {
                return true;
            }
            if (cdepth == depth) {
                return false;
            }
        }
        return true;
    }

Test Input
Format is recuresion depth / item name / item amount
1 component heat vent 1
2 iron bars 4
3 iron 6
2 heat vent 1
3 electric motor 1
4 coil 2
5 copper cable 8
5 iron 1
4 iron 1
4 tin item casing 2
3 iron bars 4
4 iron 6
3 iron plate 4
2 tin plate 4


texts: Gathering IDs to find values from objects

texts:
My HTML has three divs, each id tagged with the logic behind my object (ma/shadow/traps) which contain 10 div each (every icons), also ID-tagged according to the object. On click, I'm gathering the ID and the parent ID to traverse the object and find the value.

It's only possible to raise the value if the pre-requirement is not 0, or if the pre-requirement is false (no pre-req). My problem comes when there are 2 pre-requirements which need to be checked. I check the first one, and if the first meets the pre-req, I check if a second one exists, and check it.

There has to be a better way of checking on variables than this nightmare of ifs. It works, but I don't think it's good code at ALL. I'm not looking for a full copy/paste code here, but more for a more efficient logic on how to do what I'm already doing.

$(function () {
var basemin = 0;
var basemax = 20;
var skill = {
    ma:{
    //sample object
    },
    shadow:{
        clawMastery:{
            base:0,
            preReq:false
        }, psychicHammer:{
            base:0,
            preReq:false
        }, burstOfSpeed:{
            base:0,
            preReq:'clawMastery'
        }, weaponBlock:{
            base:0,
            preReq:'clawMastery'
        }, cloakOfShadows:{
            base:0,
            preReq:'psychicHammer'
        }, fade:{
            base:0,
            preReq:'burstOfSpeed'
        }, shadowWarrior:{
            base:0,
            preReq:'cloakOfShadows',
            preReq2:'weaponBlock'
        }, mindBlast:{
            base:0,
            preReq:'cloakOfShadows'
        }, venom:{
            base:0,
            preReq:'fade'
        }, shadowMaster:{
            base:0,
            preReq:'shadowWarrior'
        }
    },
    traps:{
    //sample object
    }
};
$('#tree div').bind("contextmenu", function (e) {
    e.preventDefault();
});
$('#tree .tab div').mousedown(function (e) {
    var $this = $(this);
    $this.attr('unselectable', 'on').css('UserSelect', 'none').css('MozUserSelect', 'none');
    var $tab = $this.parent().attr("id");
    var $skill = $this.attr("id");
    function checkPreReq(e) {
        var $preReq = skill[$tab][e]['preReq'];
        var $preReq2 = skill[$tab][e]['preReq2'];
        alert($preReq);
        if ($preReq === false) {
            alert('no pre-req');
            return true;
        } else if ($preReq !== false) {
            alert('pre-req1 exists');
            if(skill[$tab][$preReq]['base'] > 0) {
                alert('pre-req1 higher than 0');
                if ($preReq2 === undefined) {
                    alert('no second pre-req, go on');
                    return true;
                } else {
                    alert('check second pre-req value');
                    if (skill[$tab][$preReq2]['base'] > 0) {
                        alert('pre-req2 higher than 0');
                        return true;
                    } else {
                        alert('pre-req2 not met (0)');
                        return false;
                    }
                }
            } else {
                alert('pre-req1 not met (0)');
                return false;
            }
        } else {
            alert('else');
            return false
        }
    }
    if (e.which == 1) {
        //leftclick
        if (skill[$tab][$skill]['base'] < basemax && checkPreReq($skill)) {
            skill[$tab][$skill]['base'] += 1;
            //$rem_skills -= 1;
        }
    } else if (e.which == 3) {
        //rightclick
        if (skill[$tab][$skill]['base'] > basemin) {
            skill[$tab][$skill]['base'] -= 1;
            //$rem_skills += 1;
        }
    }
    $this.find(".lvl").text(skill[$tab][$skill]['base']);
    //$("#output").find(".rem_skills").text($rem_skills);
});
});


texts: Finding the longest Collatz sequence using Go, concurrently

texts:
I am working through this problem on project euler.

Basic purpose of the code:

/*
if n is even n -> n/2
if n is odd n -> 3n + 1
which starting number under 1 million produces the longest sequence?
*/

The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the get_seq_len function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?

package main

import ("fmt";"math";"time")

This function takes a number x and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.

func get_seq_len(x int, c chan int) {
    var count int = 1
    for {
        if x == 1 {
            break
        } else if x%2 == 0 {
            x = x / 2
        } else {
            x = 3 * x + 1
        }
        count++
    }
    // return count + 1
    c <- count + 1
}

Here the main function just step through every number from 1 to whatever the max is and then tests the length of the sequence for that number. I use channel c to pass the sequenced length back to main().

func main() {
    start := time.Now()
    var max int = int(math.Pow(10,6))
    // var max int = int(math.Pow(3,3))
    var max_length int = 0
    var max_num int = 0
    c := make(chan int, 50)

    for i:=1; i<max; i++ {
        // length := get_seq_len(i, c)
        go get_seq_len(i, c)
        length := <-c

        if length > max_length { max_length = length; max_num = i }
    }

    fmt.Println(max_num)
    t := time.Now()
    elapsed := t.Sub(start)
    fmt.Println(elapsed)

}


texts: List querying capabilities in Python 3.x

texts:
Either out of boredom, or my odd fascination with LINQ and SQL, this, thing, was created. Essentially, it provides list querying capabilities. At the moment, you can only query lists based on conditions, and sort them. Here's the source.

py_listq.py

import operator as oper

class QueryableListCondition:
    """
    A class used for conditions in
    QueryableList.where(*conditions).
    """
    def __init__(self, _operator: str, _value):
        self._operator = _operator.lower()
        self._value = _value
        self._operators = {
            "eq": oper.eq,
            "ne": oper.ne,
            "lt": oper.lt,
            "gt": oper.gt,
            "le": oper.le,
            "ge": oper.ge
        }

    def compare(self, value):
        """
        Compares the values, with value
        as the first compared value. Compari-
        sons look something like this:

            value operator self.value
        """
        return self._operators[self._operator](value, self._value)

    def reverse_compare(self, value):
        """
        Compares the values with self.value
        as the second compared value. Compari-
        sons look something like this:

            value operator self.value
        """
        return self._operators[self._operator](self._value, value)

class QueryableList:
    """
    A special class which is like a
    default Python list, except it
    has querying capabilities.
    """
    def __init__(self, _items: list):
        self._items = _items

    def select(self):
        """
        'Select' self._items and return it as
        a list. This is used in QueryableList.
        where as the first argument.
        """
        return self._items

    def where(self, query_list: list, compare_type: str, *conditions: QueryableListCondition):
        """
        Select elements from a QueryableList
        based on conditions.
        """
        result_list = []
        for condition in conditions:
            for item in self._items:
                if compare_type.lower() == "non-reverse":
                    if condition.compare(item) and item not in result_list:
                        result_list.append(item)
                if compare_type.lower() == "reverse":
                    if condition.reverse_compare(item) and item not in result_list:
                        result_list.append(item)
        return result_list

    def order(self, query_list: list, reverse_results=False):
        """
        Returns a sorted version of the list.
        if reverse=True then the list is
        ordererd in reverse.
        """
        return sorted(query_list, reverse=reverse_results)

Also, for reference, here's a simple example program:

test.py

from py_listq import QueryableList, QueryableListCondition

data = QueryableList([6, 2, 7, 1223, 56, 14, 6, 2435, 234, 6, 2134, 124235, 243621, 74, 378, 3, 45])
result = data.order(
    data.where(
        data.select(),
        "non-reverse",
        QueryableListCondition("gt", 1000)
    ),
    reverse_results=True
)

print(result)

I feel like I shouldn't have implemented this in an Object-Oriented way, and it feels, clunky, to use. So if you have any tips on those, they'd be very much appreciated.


texts: Proper way to wait end of a service and singleton design

texts:
My code works fine and I would like to know if I chose the best strategy to implement my code, or if It can written better (more fast, more clear, best use of design pattern, etc).

In my android application WelcomeActivity, in the onCreate method, I start a really simple service that load data from a file:

public class LoadDataService extends IntentService {
    private int result;
    @Override
    protected void onHandleIntent(Intent intent) {
        try
        {
            FileTestSingleton.getInstance(); //this could be long, read from file
            result = Activity.RESULT_OK;
        } catch (Exception e)
        {
            Log.e(LoadDataService.class.getName(), "FILE DATA LOADING ERROR \n" + e);
            result = Activity.RESULT_CANCELED;
        }
        publishResults(result);
    }

    private void publishResults(int result) {
        stopSelf();
    }
}

Some activity after, the user click a button to go to the next step of my APP. The onCreate method of MyNewActivity need the data from the service, otherwise it's ok to freeze the application, because if the data aren't loaded, nothing can be done. For example, I read that to stop the UI thread is a bad thing, but I need to stop it, otherwise my new activity will not have data to show.

So in my onCreate:

while (FileTestSingleton.getState()==Semaphore.LOADING)
{
    Thread.sleep(250);
}
fileTest = FileTestSingleton.getInstance();

Is this a proper way to wait?

Semaphore is a simple enum that I created inside the FileTestSingleton class:

public enum Semaphore
{
    EMPTY,
    LOADING,
    DONE;
}
private static Semaphore semaphore = Semaphore.EMPTY;
private static FileTestSingleton fileTest;
public static FileTestSingleton getInstance() throws Exception
{
    if (fileTest==null && semaphore!=Semaphore.LOADING)
    {
        semaphore = Semaphore.LOADING;
        fileTest = new FileTestSingleton(); //read from file, really slow
        semaphore = Semaphore.DONE;
    }
    return fileTest;
}
public static Semaphore getState()
{
    return semaphore;
}

Why I think that I can't use AsyncTask:
The problem is: I load some txt files on the startup in the WelcomeActivity that is for 2 seconds on the screen. After the app go in the MiddleActivity and the user  in the meantime can choose some options before he starts the final step of the application: FinalActivity. This FinalActivity need that all the txt files are loaded in the singleton.


texts: Select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head

texts:
I've just got into Haskell a few days ago and I love it. I'm looking for some pointers and best practices on how to organise and write Haskell code specifically when it comes to managing errors, which I have done using Maybe.

The following is an implementation of "select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head" which is going to be a sub-routine of a puzzle solver.

How can I improve the succinctness of my function? I notice that the more complex the logic of my code gets, it starts to be somewhat unreadable.

module Seq where

import Data.Maybe

{-
 - Given a 2D list, select a list via 1-based index
 - Transfer the last item  of its immediate non blank
 - left neighbour to its head.
 - @param [[Int]]   input 2D list
 - @param Int       index of target list
 - @return          the input 2D list after operation -}
pull  :: Maybe [[Int]] -> Int -> Maybe [[Int]]

-- CASE : null input
pull Nothing _                = Nothing
-- CASE : nothing left to pull
pull (Just _) 1               = Nothing
pull (Just ([]:xss)) 2        = Nothing
-- CASE : index out of bounds
pull (Just [xs]) n            = Nothing

-- CASE : currently nothing to pull
pull (Just ([]:xs:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just ([] : p'')
  where
    p' = pull (Just (xs:xss)) (n-1)
    p''= fromJust p'

-- CASE : base case; immediate pull
pull (Just (xs:xs2:xss)) 2   = Just ((init xs) : ((last xs):xs2) : xss)

-- CASE : intermediary blank; split results
pull (Just (xs:[]:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just ((head p'') : [] : (tail p''))
  where
    p' = pull (Just (xs:xss)) (n-1)
    p''= fromJust p'

-- CASE : typical recursion to destination
pull (Just (xs:xs2:xss)) n
  | p' == Nothing = Nothing
  | otherwise     = Just (xs : p'')
  where
    p' = pull (Just (xs2:xss)) (n-1)
    p''= fromJust p'

The following are test cases for the function:

-- pull (Just [[1,2],[],[3],[]]) 4 == Just [[1,2],[],[],[3]]
-- pull (Just [[1,2],[],[3],[]]) 3 == Just [[1],[],[2,3],[]]
-- pull (Just [[1,2],[],[3],[]]) 2 == Just [[1],[2],[3],[]]
-- pull (Just [[],[],[1,2,3],[]) 2 == Nothing


texts: Find all the positive divisors of a positive integer

texts:
This came from this question.

Find all the positive divisors of an integer >= 2.

Can stop when i * i >= number.

Please review for speed and style.

public class IntWithDivisors
{
    public override int GetHashCode()
    {
        return Number;
    }
    public override bool Equals(object obj)
    {
        if(obj is IntWithDivisors)
        {
            return ((IntWithDivisors)obj).Number == this.Number;
        }
        return false;
    }
    public override string ToString()
    {
        return $"number {Number}    Devisors " + string.Join(", ", Divisors);
    }

    public List<int> Divisors { get; } = new List<int>();
    public int Count { get { return Divisors.Count(); } }
    public int Number { get; }
    public IntWithDivisors(int number)
    {
        if (number < 2)
        {
            throw new ArgumentOutOfRangeException();
        }
        Number = number;
        Divisors = IntDivisors(number);
    }
}
public static List<int> IntDivisors(int num)
{
    //Debug.WriteLine($"\nIntDevisors  {num}");
    List<int> intDivisors = new List<int>();
    intDivisors.Add(1);
    intDivisors.Add(num);
    int i;
    int incr;
    if(num / 2 * 2 == num)
    {
        i = 2;
        incr = 1;
    }
    else
    {
        i = 3;
        incr = 2;
    }
    for(; i*i < num; i += incr)
    {
        int numOveri = num / i;
        if (numOveri * i == num)
        {
            //Debug.WriteLine(i);
            intDivisors.Add(i);
            intDivisors.Add(numOveri);
        }
    }
    if(i*i == num)
    {
        intDivisors.Add(i);
    }
    intDivisors.Sort();
    return intDivisors;
}


texts: Get Asset Returns for multiple Tickers and Holding Periods

texts:
I've written some code that will take multiple stock tickers and calculate their returns over yearly, monthly, bi-weekly, and weekly holding periods.  The results are written to an xlsx file.

I'm seeking commentary on any general best-practices I've missed, or any possible simplifications.  In particular, I feel like the to_excel function is over-complicated.  Also, I'm unsure whether my application of functions is excessive or incorrect.

Let me know if I can help, and thanks in advance!

import yfinance as yf
import pandas as pd
from openpyxl import load_workbook
import time
import datetime
import os

Tickers = ['MSFT','AMZN']
ReturnPeriods = ['Yearly','Monthly', 'BiWeekly', 'Weekly']

def ticker_hist (Ticker):
    """
    returns pandas dataframe containing yahoo finance history for given ticker
    """
    ticker = yf.Ticker(Ticker)
    df = ticker.history(period="max")
    df.insert(0, 'Ticker', Ticker)

    return df

def derive_columns(df):
    """
    derives columns needed for performance attribution
    """
    df['DateTime'] = pd.to_datetime(df.index)
    df['day_of_week'] = df['DateTime'].dt.day_name()
    df['DivCumSum'] = df.Dividends.cumsum()

    return df

def date_framing(df, window):
    """
    Filters dataframe for date ranges of interest
    """
    if window == 'Weekly':
        df = df[df.day_of_week == 'Thursday']
        df = df.sort_values(by='Date', ascending=False)
    elif window == 'BiWeekly':
        df = df[df.day_of_week == 'Thursday']
        df = df.sort_values(by='Date', ascending=False)
        df = df.loc[::2, :] # only get paid every other Thursday
    elif window == 'Monthly':
        df = df.groupby([df.index.year, df.index.month]).tail(1)
        df = df.sort_values(by='Date', ascending=False)
    elif window == 'Yearly':
        df = df.groupby([df.index.year]).tail(1)
        df = df.sort_values(by='Date', ascending=False)
    else:
        raise ValueError('Enter a valid return period.')

    df.insert(1, 'ReturnPeriod', window)

    return df

def attribution_cols (df):
    """
    Returns performance attribution calcs
    """
    df['PrevClose'] = df['Close'].shift(-1)
    df['DeltaDividend'] = df['DivCumSum'] - df['DivCumSum'].shift(-1)
    df['DeltaPrice'] = df['Close'] - df['PrevClose']
    df['Delta'] = df['DeltaPrice'] + df['DeltaDividend']
    df['Return'] = df['Delta'] / df['PrevClose'] * 100

    return df

def to_excel(df):
    """
    Writes results to spreadsheet
    """
    master_file = "Investments" + time.strftime("%Y%m%d") + ".xlsx"

    if os.path.exists(master_file):
        book = load_workbook(master_file)
        writer = pd.ExcelWriter(master_file, engine='openpyxl')
        writer.book = book
        writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
        startrow = book.worksheets[0].max_row
        df.to_excel(writer, "Return", startrow=startrow, header=False)
    else:
        df.to_excel(master_file, sheet_name="Return")

    return

def main(Ticker, ReturnPeriod):
    df = ticker_hist(Ticker)
    df = derive_columns(df)
    df = date_framing(df, ReturnPeriod)
    df = attribution_cols(df)

    df = df.drop(columns=['Open','Volume','High','Low','day_of_week','Dividends', 'Stock Splits', 'DateTime', 'DivCumSum'])

    to_excel(df)

    return

for Ticker in Tickers:
    for ReturnPeriod in ReturnPeriods:
        main(Ticker, ReturnPeriod)


texts:
this is a function given an array of numbers to find the one that appears an odd number of times.
what I did is:

Sort the array
Check if the array is odd.
If the array length is 1 then return this value.
Assign every two values to a new array, and check if it is a number.
Check if every two values are equals.
If not equals then the result will be the first element on the new array

function findOdd(A) {

  let copA = Array.from(A).sort((a, b) => a - b);
  let res = 0;

  if (copA.length % 2 === 0) return;
  if (copA.length == 1) return res = copA[0];

  let newArr = [];
  for (let i in copA) {
    // if not a integer break
    if (!Number.isInteger(copA[i])) {
      res = 0;
      break;
    };

    newArr.push(copA[i]);
    if(newArr.length == 2) {
      const [a,b] = newArr;
      if (a === b) {
        newArr = [];
      } else {
        res = a;
        newArr[0] = b;
        break;
      }
    } else if (newArr.length == 1) {
        res = newArr[0];
    }
  }
  return res;
}

// test the code
findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]); // 5
findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]); // -1
findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]); // 5
findOdd([10]); // 10
findOdd([1,1,1,1,1,1,10,1,1,1,1]); // 10
findOdd([5,4,3,2,1,5,4,3,2,10,10]); // 1

My code works well, but I looking to improve it.