texts:
I'm posting my C++ code for LeetCode's Evaluate Division. If you have time and would like to review, please do so. Thank you!
Problem

Equations are given in the format A / B = k, where A and B are
variables represented as strings, and k is a real number (floating
point number). Given some queries, return the answers. If the answer
does not exist, return -1.0.
Example: Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a
= ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector&
values, vector<pair<string, string>> queries , where equations.size()
== values.size(), and the values are positive. This represents the equations. Return vector.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries =
[ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries
will result in no division by zero and there is no contradiction.

Accepted C++
class Solution {
public:
    std::vector<double> calcEquation(std::vector<vector<string>> equations, std::vector<double> values, std::vector<vector<string>> const& queries) {
        generate_graph(equations, values);
        std::vector<double> evaluates;

        for (auto& query : queries) {
            std::set<string> visited;
            double accumulated = 1.0;
            bool evaluate = solve_equation(query[0], query[1], accumulated, visited);

            if (evaluate) {
                evaluates.push_back(accumulated);

            } else {
                evaluates.push_back(-1);
            }
        }

        return evaluates;
    }

protected:
    struct Node {
        Node(std::string const parameter, double const evaluate) {
            this -> parameter = parameter;
            this -> evaluate = evaluate;
        }

        std::string parameter;
        double evaluate;
    };

    map<string, vector<Node>> graph;

    void generate_graph(std::vector<vector<string>>& equations, std::vector<double>& values) {
        for (auto const& equation : equations) {
            vector<Node> children;
            graph[equation[0]] = children;
        }

        for (int equation = 0; equation < equations.size(); equation++) {
            Node node(equations[equation][1], values[equation]);
            graph[equations[equation][0]].push_back(node);

            Node node_reverse(equations[equation][0], 1 / values[equation]);
            graph[equations[equation][1]].push_back(node_reverse);
        }
    }

    bool solve_equation(std::string const nominator, std::string const denominator, double& accumulated, std::set<string>& visited) {
        if (nominator == denominator && graph.find(nominator) != graph.end()) {
            return true;
        }

        if (graph.find(nominator) == graph.end() || graph.find(denominator) == graph.end()) {
            return false;
        }

        visited.insert(nominator);

        for (auto& child : graph[nominator]) {
            if (visited.find(child.parameter) == visited.end()) {
                accumulated *= child.evaluate;

                if (child.parameter == denominator) {
                    return true;
                }

                if (solve_equation(child.parameter, denominator, accumulated, visited)) {
                    return true;

                } else {
                    accumulated /= child.evaluate;
                }
            }
        }

        return false;
    }

};

Reference
On LeetCode, there is an instance usually named Solution with one or more public functions which we are not allowed to rename those.

Question
Discussion


texts:
I use this code to get values from SharedPreferences.

public static String getSharedPreferenceValue(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(
    Utility.PREFERENCES_NAME, Context.MODE_PRIVATE);
    String value = sp.getString(key, Utility.EMPTY_STRING);
    return value;
}

Will this static method keep context (Activity) all time and are there memory leaks?

Is there a better way to get values from SharedPreferences?
I'm looking for the best way to do this.


texts: Multiplying corresponding integers using streams

texts:
While reviewing Multiplying Lists, I got the impression that the problem was naturally suited to Java 8 streams.  Unfortunately, since there is no convenient way to zip two streams, the solution ended up being uglier than I expected.

The task is to take lines of input, in the form a0 a1 a2 … an | b0 b1 b2 … bn, where the ai and bi are integers, and output the products a0b0 a1b1 a2b2 … anbn.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;

public class StreamMultiplier {
    public static IntStream multiply(IntStream aStream, IntStream bStream) {
        PrimitiveIterator.OfInt a = aStream.iterator(),
                                b = bStream.iterator();
        PrimitiveIterator.OfInt product = new PrimitiveIterator.OfInt() {
            public boolean hasNext() { return a.hasNext() && b.hasNext(); }
            public int nextInt() { return a.next() * b.next(); }
        };
        return StreamSupport.intStream(
            Spliterators.spliteratorUnknownSize(product, Spliterator.ORDERED),
            false
        );
    }

    public static IntStream toIntStream(String spaceDelimitedInts) {
        return Arrays.stream(spaceDelimitedInts.trim().split("\\s+"))
                     .mapToInt(Integer::parseInt);
    }

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = (args.length > 0) ? new Scanner(new File(args[0]))
                                          : new Scanner(System.in);

        while (input.hasNextLine()) {
            String[] halves = input.nextLine().split("\\|", 2);
            System.out.println(
                multiply(toIntStream(halves[0]), toIntStream(halves[1]))
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(" "))
            );
        }
    }
}

Is this use of Spliterators correct, and can it be improved?


texts: Mongoose and Hapi/Express promise handling in controllers

texts:
I'm switching my code to promises - mostly as delivered by Mongoose. I use Hapi though I think something similar would apply to Express.

In my models/services I perform queries such as:

var sampleMethod = function(id, status) {
  return Model.findById(id).exec().then(function(item) {
    if(!item) return Boom.notFound(); //404

    item.status = status;
    return Mode.somethingElseThatPromises();
  }, function(err) {
    return Boom.badImplementation() // 500
  }
}

Then in a controller:

handler: function(request, reply) {
  Model.sampleMethod(request.query.id, 'pending').then(function(res) {
    reply(res).code(204); // return 404 on not found else 204 and empty
  }, function(err) {
    reply(err);
  }
}

Alternatively I have tried this to let Hapi catch the 500

handler: function(request, reply) {
  Model.sampleMethod(request.query.id, 'pending').then(function(res) {
    reply(res);
  }).end();
}

I feel the above are not optimized and may be extra redundant and/or not handle all cases. I am looking for suggestions on a better controller syntax. I am not super familiar with Mongoose's promise implementation either so might be missing something.

I should add that my ultimate goal is extra lean controllers with a nice Boom usage. I generally just throw a 500 when the database does something weird (Hapi does catch these) so open to suggestions in general.


texts:
Please can someone confirm if this code is the best way to build the following tree

           0
         /   \
        1      1
       / \    / \
      3  8    4  7

class Node():
    def __init__(self, value, right = None, left= None):
        self.value = value
        self.right = right
        self.left = left
    def addNode (self, list_parent_nodes, child_value):
        if self.value >=0:
            if len(list_parent_nodes) > 1:
                if list_parent_nodes[0] == 0:
                    self.left.addNode (list_parent_nodes[1:], child_value)
                else:
                    self.right.addNode (list_parent_nodes[1:], child_value)
            else:
                if list_parent_nodes[0] == 0:
                    self.left = Node(child_value)
                else:
                    self.right = Node(child_value)
    def printTree(self,level=0):
        if self.value >=0:
            output = self.value
            print("  "*level + str(output))
            if self.left: self.left.printTree(level+1)
            if self.right: self.right.printTree(level+1)

g = Node(0)
g.addNode ([0], 1)
g.addNode ([1], 1)
"""Graph looks like
   0
  / \
 1   1
 """

g.addNode ([0,0], 3)
g.addNode ([0,1], 8)
g.addNode ([1,0], 4)
g.addNode ([1,1], 7)
"""Graph looks like
           0
         /   \
        1      1
       / \    / \
      3  8    4  7
"""
g.printTree()

```


texts: First Rust program - squares which are sum of squares

texts:
I've been programming in C++ for over a decade and am thinking of learning Rust. Finding a number whose square is the sum of three different positive squares in at least two disjoint ways, which I used in test code in a C++ program, I wrote a Rust program to find out what other numbers' squares can be written as the sum of three different positive squares. Here's the program; how can it be improved?
fn main()
{
  for a in 1..101
  {
    let mut b=1;
    while a*a-b*b>=0
    {
      let mut c=1;
      while a*a-b*b-c*c>=0 && c<b
      {
        let mut d=1;
        while a*a-b*b-c*c-d*d>=0 && d<c
        {
          if a*a-b*b-c*c-d*d==0
          {
            println!("{}²={}²+{}²+{}²",a,b,c,d);
          }
          d+=1;
        }
        c+=1;
      }
      b+=1;
    }
  }
}


texts: Insert new row to a QTableView by double-clicking the last row

texts:
Recently I was experimenting with QTableViews and I wanted to create something where I can add a new row to a table without having any additional button/menu item outside the table. I achieved this by adding a single item to the view's model and set that not editable. Then if a double-click happens on the table I check if it was on the last item. IF that is true I just add a new item before the last so my special item will be the last row every time.

Here is a minimal example which works:

#include <QApplication>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTableView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTableView tableView;
    QStandardItemModel model{ 0, 1 };
    QStandardItem insertRow{ "<Click to add new item>" };
    insertRow.setEditable(false);

    tableView.setModel(&model);
    model.insertRow(0, &insertRow);

    QApplication::connect(&tableView, &QTableView::doubleClicked,
            [&model](const QModelIndex index)
    {
        int rowCount = model.rowCount();
        if (index.row() == rowCount - 1)
            model.insertRow(rowCount - 1, new QStandardItem{ "New item" });
    });

    tableView.show();

    return a.exec();
}

Is there a more proper way to implement this? Am I doing it right or this functionality is built into the Qt framework and I completely missed?


texts:
We have to reverse char[] using recursion.

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

package codeMonk;

public class RevereseString {

    public  char[] reverseStr(char[] reversedString, int startIndex , int lastIndex, int midIndex) {

        // Base Condition
        if(startIndex > midIndex || midIndex >= lastIndex){
            return reversedString;
        } else {
            char storeChar = reversedString[startIndex];
            reversedString[startIndex] = reversedString[lastIndex -1];
            reversedString[lastIndex -1 ] = storeChar;
            return reverseStr(reversedString, ++startIndex , --lastIndex, midIndex);
        }
    }

    public static void main(String[] args) {
        char[] oldArray = {'A',' ','m','a','n',',',' ','a',' ','p','l','a','n',',',' ','a',' ','c','a','n','a','l',':',' ','P','a','n','a','m','a'};
        int midIndex = 0 + (oldArray.length - 0)/2 ;
        RevereseString reverseStr = new RevereseString();
        char [] newArray = reverseStr.reverseStr(oldArray, 0 , oldArray.length, midIndex);
        for(char ch : newArray) {
            System.out.print(ch +" ");
        }
    }

}

This code works fine, but how can I improve it and reduce the lines of code?


texts: Streaming scheduled TV shows according to a CSV playlist

texts:
I'm very new to Python, and I've made a small program/script that will allow me to stream specific files at a given time.

My idea is that I have a .csv file for each day, with one row for each movie/tv show i want to watch and a cron job that checks every 30 minutes (at :00 and :30). If the job finds any row that matches the current time, then it will play the file given in the row.

As it is now, it has been configured to my installation of Mac OS High Sierra, using VLC as player. Since i've split the config out to a seperate file, I'm hoping it will be easy to setup on another environment (e.g. a Raspberry Pi)

I've split things into three seperate files (all located in the same folder), one of the files being a config file.

cron.py is the file, that is executed by the cron job.

import tvshow
import config

tvShowFile = tvshow.getTodaysFilename()
time = tvshow.getTime()
print ("Scanning file %s for %s" % (tvShowFile, time))
row = tvshow.scanFileForTime(tvShowFile, time)

if(row):
    urlColIndex = config.csvIndexes['url']
    streamUrl = row[urlColIndex]
    print("Executing app:" + config.apppath)
    print("URL:" + streamUrl)
    try:
        tvshow.show(streamUrl)
    except Exception as e:
        print ("Something went wrong:" + str(e))
else:
    print("No show at time %s" % time)

tvshow.py is the file with all the actual stuff

from datetime import datetime
import config
import csv
import config
from subprocess import call

def getTodaysFilename():
    filename = datetime.now().strftime(config.fileTimeFormat)
    return config.filepath + "/" + filename + "." + config.extension

def getTime():
    return datetime.now().strftime(config.hourMinuteFormat)

def getFileContent(filename):
    lines = []
    with open(filename) as csvfile:
        csvContent = csv.reader(csvfile, delimiter = ',')
        for row in csvContent:
            lines.append(row)
    return lines

def scanFileForTime(filename, time):
    timeColIndex = config.csvIndexes['time']
    content = getFileContent(filename)
    for row in content:
        if(row[timeColIndex] == time):
            return row

def compileArguments(streamUrl):
    arguments = []
    arguments.append(config.apppath)
    arguments.append(streamUrl)
    for item in config.appArguments:
        arguments.append(item)
    return arguments

def show(streamUrl):
    arguments = compileArguments(streamUrl)
    call(arguments)

config.py is the configuration

apppath = '/Applications/VLC.app/Contents/MacOS/VLC'
filepath = '/Users/Shared/tvshow'
fileTimeFormat = "%Y_%m_%d"
hourMinuteFormat = "%H:%M"
extension = 'csv'
csvIndexes = dict(
    time = 0,
    title = 1,
    url = 2
)
appArguments = [
    '--fullscreen',
    '--no-loop',
    '--play-and-exit'
]

Tv show listings sample file - The "title" is not used for anything and could be left out.

"19:47","Big Buck Bunny","http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4"

Any feedback on the code would be appreciated.


texts:
I have come up with a solution to the equilibrium index problem with help from the answers off here:

val in = Stream(-7, 1, 5, 2, -4, 3, 0)
val sum = in.scan(0)(_ + _)
val hash = (in zip sum) map { case (e, lsum) => 2*lsum + e }
val target = sum.last
hash.zipWithIndex.collect { case (e, i) if e == target => i }

It's unfortunate that I have to traverse through the whole stream again to get target.

Are there any possible improvements?


texts:
Can this insertion sort program be improved in any way? Please suggest something in terms of efficiency and lines of code as well.

def insort(lst):
    for i in range(len(lst)-1):
        l = i + 1
        for j in range(l, -1, -1):
            print(j)
            if j == 0:
                break
            if lst[j] < lst[j-1]:
                lst[j], lst[j-1] = lst[j-1], lst[j]
    return lst

data = input("Enter the numbers separated by spaces: ")

print(insort(list(map(int, data.split()))))


texts: Grouping, merging and mapping with a timetable

texts:
I want to create a "timetable" for some shop. It should look like, "days - hours".

I get response from the server in this way:

var array = [{
  days : ["Mo", "Tu", "We", "Th", "Sa"],
  dayIndexes: [1,2,3,4, 6],
  time: "9am - 3pm"
}, {
  days : ["Mo", "Tu", "We", "Th", "Sa"],
  dayIndexes: [1,2,3,4,6],
  time: "5pm - 9pm"
}, {
  days : ["Fr", "Su"],
  dayIndexes: [5,7],
  time: "9am - 2pm"
}];

It is like one object contains days for which shop has the same work hours. Duplicates by property days can happen because it is how the server implement "breaks" for a shop.

I've added my working sample, which returns exactly what I need, but I think it can be made simpler.

jsFiddle

var array = [{
     days: ["Mo", "Tu", "We", "Th", "Sa"],
     dayIndexes: [1, 2, 3, 4, 6],
     time: "9am - 3pm"
 }, {
     days: ["Mo", "Tu", "We", "Th", "Sa"],
     dayIndexes: [1, 2, 3, 4, 6],
     time: "5pm - 9pm"
 }, {
     days: ["Fr", "Su"],
     dayIndexes: [5, 7],
     time: "9am - 2pm"
 }];
 var convertToRanges = function(arr) {
     console.log(arr);
     if (arr.length > 0) {
         var ranges = [
                 [arr[0], arr[0]]
             ],
             lastIndex = 0;

         for (var i = 1; i < arr.length; i++) {
             if (arr[i] - ranges[lastIndex][1] === 1) {
                 ranges[lastIndex][1] = arr[i];
             } else {
                 ranges[++lastIndex] = [arr[i], arr[i]];
             }
         }

         var res = ranges.map((item) => {
             if (item[0] !== item[item.length - 1]) {
                 return moment.weekdaysShort(item[0]) + '-' + moment.weekdaysShort(item[item.length - 1]);
             } else {
                 return moment.weekdaysShort(item[0]);
             }
         });
     } else {
         res = moment.weekdaysShort(arr[0]);
     }

     return res.join(', ');
 }

 var result = _(array)
     .groupBy('dayIndexes')
     .map(function(days) {
         return _.mergeWith.apply(_, [{}].concat(days).concat([
             function(obj, src, key) {
                 if (key === 'time' && obj && src) {
                     return [obj, src].join(', ');
                 }
             }
         ]));
     })
     .values()
     .value()
     .map(d => {
         d.days = convertToRanges(d.dayIndexes);
         return d;
     });

 console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>


texts:
145 is a curious number, as \$1! + 4! + 5! = 1 + 24 + 120 = 145\$.

  Find the sum of all numbers which are equal to the sum of the
  factorial of their digits.

  Note: as \$1! = 1\$ and \$2! = 2\$ are not sums they are not included.

I can't figure out a fair way to optimize the upper bound from the information given in the question. I went on the PE forum and found many people setting the upper bound to 50000 because they knew that would be large enough after testing. This doesn't seem fair to me; I want to set the bound based on the information in the question. Right now it runs in around 20 seconds.

EDIT: I'm not looking for a mathematical algorithm. I'm looking for ways to make this code faster.

from math import factorial as fact
from timeit import default_timer as timer

start = timer()
def findFactorialSum():
    factorials = [fact(x) for x in range(0, 10)] # pre-calculate products
    total_sum = 0
    for k in range(10, fact(9) * 7): # 9999999 is way more than its fact-sum
        if sum([factorials[int(x)] for x in str(k)]) == k:
            total_sum += k

    return total_sum

ans = findFactorialSum()
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I'm currently developing a simple 2D game engine and I was just wondering, what are some things that I can do to improve my service locator class, at the moment it's very basic.

For example, should I be checking for null objects, if so, what exceptions should I throw?

Here's the code, thatnks in advance!

using System;
using System.Collections.Generic;

namespace GameEngine.Core
{
    public sealed class ServiceLocator
    {
        private static ServiceLocator instance;

        private Dictionary<Type, object> services;

        public ServiceLocator()
        {
            this.services = new Dictionary<Type, object>();
        }

        public void AddService(Type serviceType, object serviceObject)
        {
            this.services.Add(serviceType, serviceObject);
        }

        public void RemoveService(Type serviceType)
        {
            this.services.Remove(serviceType);
        }

        public object GetService(Type serviceType)
        {
            return this.services[serviceType];
        }

        public static ServiceLocator Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ServiceLocator();
                }

                return instance;
            }
        }
    }
}


texts: Checking for JSON or YAML file with promises

texts:
I'm using bluebird promises. I'm converting fs.exists to existsAsync (here's how) and fs.readFile (here's how) to promises.

existsAsync(o.inputFilePathJSON).then(function(exists) {
  debug("%s exists %s", o.inputFilePathJSON, exists);
  if (exists) return fs.readFile(o.inputFilePathJSON).then(JSON.parse);
  return existsAsync(o.inputFilePathYML).then(function(exists) {
    debug("%s exists %s", o.inputFilePathYML, exists);
    if (exists) return fs.readFile(o.inputFilePathYML).then(yaml.load);
  });
})

This will check if the JSON version exists, and if it doesn't check for the YML version.

I was wondering how good this code is as promise code.

In this case I'm switching to YML from JSON. I'd love to build my YML files and check if both the JSON and YML are the same. I can't do that with this code because both of the promises don't run independently.

Here's another version of the code:

var json = existsAsync(o.inputFilePathJSON).then(function(exists) {
  debug("%s exists %s", o.inputFilePathJSON, exists);
  if (exists) return fs.readFile(o.inputFilePathJSON).then(JSON.parse);
  return false;
})

var yml = existsAsync(o.inputFilePathYML).then(function(exists) {
  debug("%s exists %s", o.inputFilePathYML, exists);
  if (exists) return fs.readFile(o.inputFilePathYML).then(yaml.load);
  return false;
});

json.then(function(json) {
  yml.then(function(yml) {
    if (yml) return yml;
    if (json) return json;
    return false;
  });
});

What about error reporting when it comes to building these small promises? Should the errors be caught separately for each, or can they be caught in the conjoined version?

My two questions are:

How should this promise code be written?
Where should the errors be caught?


texts:
I'm building a small web app primarily for mobile use. I have some widgets that need to handle tap gestures in the expected way, and I don't feel this one feature is reason enough to include JQuery mobile.

I've written the following function for making an element respond to "tap" events:

function bind_tap(el, cb) {
  (function(){
    var touchStarted = false;
    el.addEventListener("click", cb, false);
    el.addEventListener("touchstart", function(){
      touchStarted = true;
    }, false);
    el.addEventListener("touchcancel", function(){
      touchStarted = false;
    }, false);
    el.addEventListener("touchleave", function(){
      touchStarted = false;
    }, false);
    el.addEventListener("touchend", function(){
      touchStarted = false;
      if (touchStarted) cb();
    }, false);
  })();
};

It seems to work fine, but I'm wondering if it could/should be improved in any way, either in that parts of it are redundant (I'm not sure what touchcancel really means) or to handle some edge case I haven't thought of.

Solution so far:

function bindTap(element, callback, useCapture) {
  var touchStarted = false, touchFinished = null;
  useCapture = !!useCapture;
  function startTap() {
      touchStarted = true;
      touchFinished = false;
  }
  function cancelTap() {
      touchStarted = false;
  }
  function completeTap() {
      if (touchStarted && !touchFinished) {
          callback.apply(this, arguments);
          touchFinished = true;
      }
  }
  function handleClick() {
      touchStarted = true;
      completeTap.apply(this, arguments);
  }
  element.addEventListener("click", handleClick, useCapture);
  element.addEventListener("touchstart", startTap, useCapture);
  element.addEventListener("touchcancel", cancelTap, useCapture);
  element.addEventListener("touchleave", cancelTap, useCapture);
  element.addEventListener("touchend", completeTap, useCapture);
}


texts:
I am totally new to PHP. I just wrote a PHP script for google oauth to pull the data and insert into my database. I don't know if my code is vulnerable to SQL injection. Should I have used prepared statements and should I rewrite the code?

index.php

 <?php ini_set('display_errors', 1);
    error_reporting(E_ALL ^ E_NOTICE); ?>

    <?php

    include_once("config.php");
    include_once("includes/functions.php");

    //print_r($_GET);die;

    if(isset($_REQUEST['code'])){
      $gClient->authenticate();
      $_SESSION['token'] = $gClient->getAccessToken();
      header('Location: ' . filter_var($redirect_url, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['token'])) {
      $gClient->setAccessToken($_SESSION['token']);
    }

    if ($gClient->getAccessToken()) {
      $userProfile = $google_oauthV2->userinfo->get();
      //DB Insert
      //$gUser->setApprovalPrompt ("auto");

      $gUser = new Users();
      // As of PHP 5.3.0

      $gUser->checkUser('google',$userProfile['id'],$userProfile['given_name'],$userProfile['family_name'],$userProfile['email'],$userProfile['gender'],$userProfile['locale'],$userProfile['link'],$userProfile['picture'],$username);
      $_SESSION['google_data'] = $userProfile; // Storing Google User Data in Session
      header("location: feed.php");

      $_SESSION['token'] = $gClient->getAccessToken();
    } else {
      $authUrl = $gClient->createAuthUrl();
    }

      $email  = $_SESSION['google_data']['email'];
      $user = strstr($email, '@', true);
      $username = $user;
?>

functions.php

 <?php ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE); ?>

<?php
 session_start();
class Users {
    public $tableName = 'users';

 function __construct(){
        //database configuration
        $dbServer = 'localhost'; //Define database server host
        $dbUsername = 'root'; //Define database username
        $dbPassword = ''; //Define database password
        $dbName = 'livelor'; //Define database name

        //connect databse
        $con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
        if(mysqli_connect_errno()){
            die("Failed to connect with MySQL: ".mysqli_connect_error());
        }else{
            $this->connect = $con;
        }
    }

    function checkUser($oauth_provider,$oauth_uid,$fname,$lname,$email,$gender,$locale,$link,$picture,$username){
        $prevQuery = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        if(mysqli_num_rows($prevQuery) > 0){
            $update = mysqli_query($this->connect,"UPDATE $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."' ,fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        }else{
            $insert = mysqli_query($this->connect,"INSERT INTO $this->tableName SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$oauth_uid."', fname = '".$fname."', lname = '".$lname."', email = '".$email."', gender = '".$gender."', locale = '".$locale."', picture = '".$picture."', gpluslink = '".$link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."' ,  username='".$username."' ") or die(mysqli_error($this->connect));
        }

        $query = mysqli_query($this->connect,"SELECT * FROM $this->tableName WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$oauth_uid."'") or die(mysqli_error($this->connect));
        $result = mysqli_fetch_array($query);
        return $result;

    }
}


texts: Creating a menu for widgets with editable settings

texts:
I'm trying to create a menu for widgets with editable settings.  As of now I'm setting these settings per object by coding them in like you can see below.

How could I make this shorter / programmatically create those objects with settings (settings are stored in a MySQL database)?

    var widgetArray = new Array();
var objectArray = {
    jira_users: function(){
        this.StartUID = 1;
        this.length = 4;
    },
    calls_per_day: function(){
        this.length = 5;
    },
    calls_per_week: function(){
        this.length = 5;
    },
    calls_per_week_day: function(){
        this.length = 5;
    },
    check_servers: function(){
        this.length = 4;
    }
}

objectArray.jira_users.prototype = {
    constructor: objectArray.jira_users,
    UpdateStartUID: function(newid){
        this.StartUID = newid;
    },
    Update: function($form){
        this.UpdateStartUID($form.find("#user_id_input").val());
    }
}

objectArray.calls_per_day.prototype = {
    constructor: objectArray.calls_per_day,
    UpdateLength: function(newLength){
        this.length = newLength;
    },
    Update: function($form){
        this.UpdateLength($form.find("#display_length").val());
    }
}

objectArray.calls_per_week.prototype = {
    constructor: objectArray.calls_per_week,
    UpdateLength: function(newLength){
        this.length = newLength;
    },
    Update: function($form){
        this.UpdateLength($form.find("#display_length").val());
    }
}

objectArray.calls_per_week_day.prototype = {
    constructor: objectArray.calls_per_week_day,
    UpdateLength: function(newLength){
        this.length = newLength;
    },
    Update: function($form){
        this.UpdateLength($form.find("#display_length").val());
    }
}


texts: Adding Length dimension to a Crate Object

texts:
Consider Crate::addLength() in the following code:

class Crate
{
    protected $length, $width, $height;

    function __construct(float $length, float $width, float $height)
    {
        $this->length = $length;
        $this->width = $width;
        $this->height = $height;
    }

    function addLength(float $length): Crate
    {
        return new self($this->length + $length, $this->width, $this->height);
    }
}

I am concerned that Crate object creating a Crate object is a violation of Single Responsibility Principle (SRP).  Crate object duties is to keep dimensions of the crate.  Creating another crate object seems like introducing extra responsibilities to a class that already has responsibilities.

With that in mind, how to I make the code better?

The directions I think I can go are

1)  Is it better to just instead increase the length of the Crate?

function addLength(float $length): void
{
    $this->length += $length;
}

When doing so however, my crate becomes 'stretchy', which is typically not done in real life.  Instead, a new crate is constructed with given measurements.

Thus,

2) Is it better to instead delegate object creation to a separate class?

class CrateService
{

    function addLength(Crate $crate, float $length): Crate
    {
        return new Crate($crate->GetLength() + $length, $crate->getWidth(), $crate->getHeight());
    }
}

That seems to work, even if a little cumbersome - we basically call every crate's dimension individually and add the adder length, and create a new crate.


texts: Looping over a list, checking a boolean and return value

texts:
There are a number of different ways to do this. What do people prefer and why?

public boolean checkNameStartsWith(List<Foo> foos) {
    for (Foo foo : foos) {
        if (!(foo.getName().startsWith("bar"))) {
            return Boolean.FALSE;
        }
    }
    return Boolean.TRUE;
}


texts:
I have a class which takes a string representing a grid from Conway's game of life (along with its size, only accepting square grids) and returns the next grid in string format. Can it be improved?

Please note that this purely does the computation, and none of the displaying or editing. Also, it is internal so it will not have detection or prevention for errors.

The code:

public class GameOfLifeComputer
{
    #region Fields

    private int _up;
    private int _down;
    private int _left;
    private int _right;
    private int _currentIndex;
    private int _cellCount;
    private string _outputGrid;

    #endregion

    #region Methods

    /// <summary>
    /// Returns a string for the next grid state.
    /// </summary>
    /// <param name="inputGrid">The current grid state.</param>
    /// <param name="gridSize">Side length of the grid in cells.</param>
    /// <returns>The next grid state.</returns>
    public string CalculateNextGrid(string inputGrid, int gridSize)
    {
        _outputGrid = "";
        _currentIndex = 0;

        foreach (char currentCell in inputGrid)
        {
            _cellCount = CountCells(_currentIndex, inputGrid, gridSize);

            if (currentCell == '1')
            {
                if (_cellCount < 2 || _cellCount > 3)
                {
                    _outputGrid += "0";
                }
                else
                {
                    _outputGrid += "1";
                }
            }
            else
            {
                if (_cellCount == 3)
                {
                    _outputGrid += "1";
                }
                else
                {
                    _outputGrid += "0";
                }
            }
        }

        return _outputGrid;
    }

    /// <summary>
    /// Returns how many adjacent cells are alive.
    /// </summary>
    /// <param name="currentIndex">Position of the cell.</param>
    /// <param name="inputGrid">State of the grid as a string.</param>
    /// <param name="gridSize">Side length of the grid in cells.</param>
    /// <returns></returns>
    private int CountCells(int currentIndex, string inputGrid, int gridSize)
    {
        var count = 0;

        // Define where the adjacent cells are in terms of relative index position.
        _up = -gridSize;
        _down = gridSize;

        // Up and down must cycle to the top or bottom of the grid if the cell is on the edge.
        if (currentIndex < gridSize)
        {
            _up = inputGrid.Length - gridSize;
        }
        else if (currentIndex > inputGrid.Length - gridSize)
        {
            _down = gridSize - inputGrid.Length;
        }

        // Left and right must cycle to the opposite side on the same row if the cell is on the edge.
        if (currentIndex % gridSize == 0)
        {
            _left = gridSize - 1;
            _right = 1;
        }
        else
        {
            _left = -1;
            _right = 1 - gridSize;
        }

        // Count how many adjacent cells are alive.
        if (inputGrid[currentIndex + _up    + _right]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _up            ]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _up    + _left ]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _left          ]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _down  + _left ]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _down          ]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _down  + _right]   == '1') { count += 1; }
        if (inputGrid[currentIndex + _right         ]   == '1') { count += 1; }

        return count;
    }

    #endregion
}


texts:
I'm working on a script that will be able to press the login button on any site for an app I'm working on. I have it working (still a few edge cases to work out such as multiple submit buttons and iFrames and I'm going to rewrite it to make it prettier once I figure them out).

Can you think of any ways I could improve it or make it more robust?

Some notes:

form.submit() doesn't work consistently since many sites don't allow it to be executed via a script.
Three types of login buttons I see consistently are 'a', 'button', and 'input'.

var buttonElements = document.getElementsByTagName('button');
var inputElements = document.getElementsByTagName('input');
var linkElements = document.getElementsByTagName('a');
var loginElement = null;
// For Button/Input
if (buttonElements != null){
    loginElement = getSubmitElement(buttonElements);
}
if (loginElement != null){
    console.log(loginElement);
    loginElement.click();
}
else{
    if (inputElements != null){
        loginElement = getSubmitElement(inputElements);
    }
    if (loginElement != null){
        console.log(loginElement);
        loginElement.click();
    }
    else{
        if (linkElements != null){
            loginElement = getLinkElement(linkElements);
        }
        if (loginElement != null){
            console.log(loginElement);
            loginElement.click();
        }
    }
}
// Used for link elements (<a/>)
function getLinkElement(elements){
    for (i=0;i < elements.length; i++){
        // Is a submit button
        // Check ID class
        if (isLoginElement(elements[i],'id')){
            return elements[i];
        }
    }
    for (i=0;i < elements.length; i++) {
        if(isLoginElement(elements[i], 'name')){
            return elements[i];
        }
        else if(isLoginElement(elements[i],'class')){
            return elements[i];
        }
    }
    return null;
}

// Use for Button or Input - Checks the id/name/class attributes
function getSubmitElement(elements){
    for (i=0;i < elements.length; i++){
        var type = elements[i].getAttribute('type');
        if (type != null){
            if (type.toLowerCase() == 'submit' || type.toLowerCase() == 'image'){
                // Is a submit button
                // Check ID class
                if (isLoginElement(elements[i],'id')){
                    return elements[i];
                }
                else if(isLoginElement(elements[i], 'name')){
                    return elements[i];
                }
                else if(isLoginElement(elements[i],'class')){
                    return elements[i];
                }
            }
        }

    }
    return null;
}

// Checks if a specific attribute value contains our preset login strings
function isLoginElement(element, attribute){
    var attr;
    if (attribute != 'content'){
        attr = element.getAttribute(attribute);
    }
    else{
        attr = element.textContent;
    }
    if (attr != null){
        if (hasLogin(attr)){
            return true;
        }
    }
    return false;
}

// Checks that an attribute's value contains login, sign, or submit
function hasLogin(str){
    var substrings = ['login', 'sign', 'submit', 'continue'];
    if (new RegExp(substrings.join("|")).test(str.toLowerCase())) {
        console.log('Match Found - ' + str);
        return true;
    }
    return false;
}


texts: Finding all possible letter combinations from an inputted phone number

texts:
Prompt:

  Given a string containing digits from 2-9 inclusive, return all
  possible letter combinations that the number could represent.

  A mapping of digit to letters (just like on the telephone buttons) is
  given below. Note that 1 does not map to any letters.

I'm a relatively new LeetCoder and I feel pretty good about solving this problem. What are some obvious improvements that I could be making to improve the runtime or approach towards this problem or other problems in general?

public IList<string> LetterCombinations(string digits)
{
    string[] ph = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    List<string> result = new List<string>();
    if (digits == null || digits.Length == 0) return result;
    int len = ph[digits[0] - '0'].Length;
    for (int i = 0; i < len; i++)
    {
        GetCombos(digits, "", i, ref result, digits.Length);
    }

    return result;
}

public void GetCombos(string inputDigits, string curVariation, int charIndex, ref List<string> resultList, int length)
{
    string[] phone = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    if (curVariation.Length != length)
    {
        char ch = phone[inputDigits[0] - '0'][charIndex];
        curVariation += ch;
    }
    if (curVariation.Length == length)
    {
        resultList.Add(curVariation);
        return;
    }

    string newInput = inputDigits.Substring(1, inputDigits.Length - 1);
    if (newInput == "") return;
    int numChars = phone[newInput[0] - '0'].Length;
    for (int i = 0; i < numChars; i++)
    {
        GetCombos(newInput, curVariation, i, ref resultList, length);
    }
}


texts:
For my current job, I've been told that soon I'm going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I've been learning as much about Cython as I can. I've decided that tackling the Fibonacci sequence would be a good start. I've implemented a Cython + Iterative version of the Fibonacci sequence. Are there any more performance upgrades I can squeeze out of this? Thanks!
fibonacci.pyx
cpdef fib(int n):
    return fib_c(n)

cdef int fib_c(int n):
    cdef int a = 0
    cdef int b = 1
    cdef int c = n
    while n > 1:
        c = a + b
        a = b
        b = c
        n -= 1
    return c

And how I test this code:
testing.py
import pyximport ; pyximport.install() # So I can run .pyx without needing a setup.py file #
import time

from fibonacci import fib

start = time.time()
for i in range(100_000):
    fib(i)
end = time.time()
print(f"Finonacci Sequence: {(end - start):0.10f}s (i=100,000)") # ~2.2s for 100k iterations


texts: Creating folders even if already exist or removing removing their content

texts:
I have a project where, every time I run it, I have to:

test if some folders exist, and create them if they don't exists.
remove their content if the folders already exist.

This is the code that I developed to do this:

import os
import pathlib

def clean_Folders(directory):
    folders = ['preprocessed', 'results', 'tmp']
    for folder in folders:
        if not os.path.exists(os.path.join(directory, folder)):
            os.makedirs(os.path.join(directory, folder))
    for filepath in pathlib.Path(directory).glob('**/*'):
        try:
            os.remove(filepath.absolute())

        except:
            print('something went wrong')

I had another idea which is creating the folders every time I run my project (without doing the existence test nor caring about what the already contain).
Here is the code:

import os
import shutil

def clean_Folders(directory):
    folders = ['preprocessed', 'results', 'tmp']
    for folder in folders:
        try:
            if os.path.exists(os.path.join(directory, folder)):
                    shutil.rmtree(os.path.join(directory, folder))
            os.makedirs(os.path.join(directory, folder))
        except:
            print('something went wrong')

Which one of the solutions is more optimized and more professional?
Thank you.


texts:
I have written an algorithm intended to find prefixes and suffixes in arrays of strings.

I would like to get opinions/suggestions/reviews on the code I wrote (specially cases in which my code would fail), but also, I would like to know if this algorithm can be rewritten in a more optimal way since I will be running this code against lots of entries.

Finding preffixes

function findPrefix(strings){
    if(!strings || strings.length === 0){
        return null;
    }

    var prefix = '',
        characters = strings[0].split(''),
        i, j;

    for(i = 0; i < characters.length; i++){
        var isPrefix = true,
            character = characters[i];

        for(j = 0; j < strings.length; j++) {
            var string = strings[j];

            isPrefix = isPrefix &&
                (string.length >= i + 1 && string[i] === character);
        }

        if(isPrefix) {
            prefix += character;
        } else {
            return prefix;
        }
    }
}

Finding suffixes

function reverse(string){
    return string.split('').reverse().join('');
}

function findSuffix(strings){
    if(!strings || strings.length === 0){
        return null;
    }

    return reverse(findPrefix(strings.map(reverse)));
}

A running example can be found here: http://jsbin.com/razuta/2/edit (click JavaScript and console to see the results)


texts: Student Class in C++ using sstream for format

texts:
Based on my previous review, I'm posting another Hackerrank Class solution.

  Problem Statement

  We can store details related to a student in a class consisting of his
  age (int), first_name (string), last_name (string) and standard (int).

  You have to create a class, named Student, representing the student's
  details, as mentioned above, and store the data of a student. Create
  setter and getter functions for each element; that is, the class
  should at least have following functions:

  get_age set_age
  get_first_name, set_first_name
  get_last_name,set_last_name
  get_standard, set_standard

  Also, you have to create another method to_string() which returns the
  string consisting of the above elements, separated by a comma(,). You
  can refer to stringstream for this.
   NB: I didn't implement the to_string() as I felt I could use sstream in   the main().

  Input Format

  Input will consist of four lines.  The first line will contain an
  integer, representing the age. The second line will contain a string,
  consisting of lower-case Latin characters ('a'-'z'), representing the
  first_name of a student.  The third line will contain another string,
  consisting of lower-case Latin characters ('a'-'z'), representing the
  last_name of a student.  The fourth line will contain an integer,
  representing the standard of student.

  Note: The number of characters in first_name and last_name will not
  exceed 50.

  Output Format

  The code provided by HackerRank will use your class members to set and
  then get the elements of the Student class.

  Sample Input

15
john
carmack
10

  Sample Output

15
carmack, john
10

15,john,carmack,10

Here is my code:

#include <iostream>
#include <sstream>
using namespace std;

/*
Enter code for class Student here.
Read statement for specification.
*/
class Student{

    int age;
    string first_name;
    string last_name;
    int standard;

    public:
          int get_age(){
              return age;
          }
          void set_age(int age1){
              age = age1;
          }
           string get_first_name(){
              return first_name;
          }
          void set_first_name(string first_name1){
              first_name = first_name1;
          }
          string get_last_name(){
              return last_name;
          }
          void set_last_name(string last_name1){
              last_name = last_name1;
          }
           int get_standard(){
              return standard;
          }
          void set_standard(int standard1){
              standard = standard1;
          }

};

int main() {
    int age, standard;
    string first_name, last_name;
    stringstream ss;

    cin >> age >> first_name >> last_name >> standard;

    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);

    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";

    ss << st.get_age() <<","<<st.get_first_name() <<","<<st.get_last_name()<<","<< st.get_standard();
    cout<<ss.str()<<endl;

    return 0;
}

Final thoughts:

Have I used sstream correctly? Have I used it to its full capacity?
What could have been done better, such as style-wise?


texts: Prim's Algorithm - Minimum Spanning Tree

texts:
I have implemented Prim's Algorithm from Introduction to Algorithms. I have observed that the code is similar to Dijkstra's Algorithm, so I have used my Dijkstra's Algorithm implementation.

Please review this code and suggest improvements.

To compile on Linux: g++ -std=c++14 prims.cpp

#include <iostream>
#include <map>
#include <limits>
#include <list>
#include <queue>

class Graph
{

    struct Vertex
    {
        std::size_t id;
        int distance = std::numeric_limits<int>::max();
        Vertex * parent = nullptr;

        Vertex(std::size_t id) : id(id) {}
    };

    using pair_ = std::pair<std::size_t, int>;
    std::vector<Vertex> vertices = {};

    //adjacency list , store src, dest, and weight
    std::vector< std::vector< pair_> > adj_list;
    //to store unprocessed vertex min-priority queue
    std::priority_queue< pair_, std::vector<pair_>,
                         std::greater<pair_> > unprocessed;

  public:
    Graph(std::size_t size);
    void add_edge(std::size_t src, std::size_t dest, int weight);
    void prim(std::size_t vertex);
    std::size_t  minimum_cost() ;
};

Graph::Graph(std::size_t size)
{
    vertices.reserve(size);
    adj_list.resize(size);
    for (int i = 0; i < size; i++)
    {
        vertices.emplace_back(i);
    }
}

void Graph::add_edge(std::size_t src , std::size_t dest, int weight)
{
    if(weight >= 0)
    {
        if (src == dest)
        {
            throw std::logic_error("Source and destination vertices are same");
        }

        if (src < 0 || vertices.size() <= src)
        {
            throw std::out_of_range("Enter correct source vertex");
        }

        if (dest < 0 || vertices.size() <= dest)
        {
            throw std::out_of_range("Enter correct destination vertex");
        }

        int flag = 0, i = src;
        for (auto& it : adj_list[i])
        {
            if (it.first == dest)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
        {
            adj_list[src].push_back( {dest, weight} );
        }
        else
        {
            throw std::logic_error("Existing edge");
        }

    }
    else
    {
        std::cerr << "Negative weight\n";
    }
}

void Graph::prim(std::size_t vertex)
{
    vertices[vertex].distance = 0;
    vertices[vertex].parent = &vertices[vertex];

    unprocessed.push( std::make_pair(vertices[vertex].distance, vertex) );
     while (!unprocessed.empty())
     {
         int curr_vertex_dist = unprocessed.top().first;
         std::size_t curr_vertex = unprocessed.top().second;
         unprocessed.pop();

        for (auto& ver: adj_list[curr_vertex])
        {
            auto& next_dist = vertices[ver.first].distance;
            const auto curr_dist = ver.second;
            if (curr_dist < next_dist)
            {
                next_dist = curr_dist;
                //make src vertex parent of dest vertex
                vertices[ver.first].parent = &vertices[curr_vertex];
                unprocessed.push( std::make_pair(next_dist, ver.first));
            }
        }
    }
}

std::size_t  Graph::minimum_cost()
{
    std::size_t cost = 0;
    for (auto vertex: vertices)
    {
        cost = cost + vertex.distance;
    }
    return cost;
}

int main()
{
    Graph grp(9);
    grp.add_edge(0, 1, 4);
    grp.add_edge(0, 2, 8);
    grp.add_edge(1, 2, 11);
    grp.add_edge(1, 3, 8);
    grp.add_edge(3, 4, 2);
    grp.add_edge(4, 2, 7);
    grp.add_edge(2, 5, 1);
    grp.add_edge(5, 4, 6);
    grp.add_edge(3, 6, 7);
    grp.add_edge(3, 8, 4);
    grp.add_edge(5, 8, 2);
    grp.add_edge(6, 7, 9);
    grp.add_edge(6, 8, 14);
    grp.add_edge(7, 8, 10);
    grp.prim(0);
    std::cout << "The total cost is : " << grp.minimum_cost() << "\n";
}


texts: Find all pairs of unique indices in a list such that the concatenation of the two words is a palindrome

texts:
The task

  Given a list of words, find all pairs of unique indices such that the
  concatenation of the two words is a palindrome.

  For example, given the list ["code", "edoc", "da", "d"], return
  [(0, 1), (1, 0), (2, 3)].

const lst = ["code", "edoc", "da", "d"];

My functional solution

const findPalindromePairs = lst => {
  const isPalindrome = str => str === [...str].reverse().join("");
  return lst.reduce((pairs, w1, i) => {
    return [...pairs, ...lst.reduce((match, w2, j) => {
      if (i !== j && isPalindrome(`${w1}${w2}`)) { match.push([i,j]); }
      return match;
    }, [])];
  }, []);
};

console.log(findPalindromePairs(lst));

My imperative solution

function findPalindromePairs2 (lst) {
  const len = lst.length;
  const pairs = [];

  const isPalindrome = str => str === [...str].reverse().join("");
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      if (i !== j && isPalindrome(lst[i] + lst[j])) { pairs.push([i,j]); }
    }
  }
  return pairs;
}

console.log(findPalindromePairs2(lst));


texts: Creating ShortCut (RightClick) Menus in Access

texts:
I'm writing a tool to create shortcut menus for an application that I maintain built on the Access runtime. I compile this app into an *.accde file, so much to my chagrin, all right click menus are disabled.

After some research, I've been able to develop this tool to add the menus to the database. This code is called during development, not at runtime.

I'm already seeing a lot of duplication, and am not sure what to do about it. So, I figured I'd stop and get some feedback before I started building all of the various menus that I'm going to need.

Note: There is not a built in Enumeration of all of the different button types. There are thousands of them and I'm adding them to a self defined enum as I need them.

Option Explicit

Private Enum ButtonControls
    bcCopy = 19
    bcCut = 21
    bcPaste = 22
    bcSortSmallToLarge = 210
    bcSortSortLargeToSmall = 211
    bcDelete = 478
    bcNewRecord = 539
    bcRowHeight = 541
    bcDeleteRecord = 644
End Enum

Private Sub CreateFormDatasheetClipboard()
    Dim menu As Office.CommandBar
    Set menu = CommandBars.Add("FrmDsClipboard", msoBarPopup, False)

    With menu.Controls
        .Add msoControlButton, bcCut
        .Add msoControlButton, bcCopy
        .Add msoControlButton, bcPaste
    End With
    Set menu = Nothing
End Sub

Private Sub CreateFormDataSheetCopyOnly()
    Dim menu As Office.CommandBar
    Set menu = CommandBars.Add("FrmDsCopyOnly", msoBarPopup, False)

    menu.Controls.Add msoControlButton, bcCopy

    Set menu = Nothing
End Sub

Private Sub CreateFormDataSheetRow()
    Dim menu As Office.CommandBar
    Set menu = CommandBars.Add("FrmDsRow", msoBarPopup, False)

    With menu.Controls
        .Add msoControlButton, bcNewRecord
        .Add msoControlButton, bcDeleteRecord
        .Add msoControlButton, bcCut
        .Add msoControlButton, bcCopy
        .Add msoControlButton, bcPaste
        .Add msoControlButton, bcRowHeight
    End With

    Set menu = Nothing
End Sub

Private Sub CreateFormDataSheetRowClipboardOnly()
    Dim menu As Office.CommandBar
    Set menu = CommandBars.Add("FrmDsRowClipboardOnly", msoBarPopup, False)

    With menu.Controls
        .Add msoControlButton, bcCut
        .Add msoControlButton, bcCopy
        .Add msoControlButton, bcPaste
    End With

    Set menu = Nothing
End Sub

Private Sub RemoveAllCustomMenus()
    Dim cbar As CommandBar
    For Each cbar In CommandBars
        If Not cbar.BuiltIn Then
            cbar.Delete
        End If
    Next
End Sub

Private Sub CreateAllCustomMenus()
    RemoveAllCustomMenus
    CreateFormDatasheetClipboard
    CreateFormDataSheetCopyOnly
    CreateFormDataSheetRow
    CreateFormDataSheetRowClipboardOnly
End Sub


texts: Monitor a web page for when a desired price is met

texts:
I have a code that keeps checking a webpage with a price on it and when the price meets a number I set it to, the thing is purchased. I am looking for ways to increase the speed of it.

I have added multiprocessing and its performance may have improved, but I don't know if its the best-case scenario for this code and there probably are better methods for speed and efficiency.

from multiprocessing.dummy import Pool
from functools import partial

session = requests.session()
session.cookies["cookie"] = ""

login = session.get("https://www.example.com")
if login.status_code == 200:
    print("logged in")
else:
    raise ValueError("Invalid Cookie")

crsf_token = ""

def token():
    while True:
        global crsf_token
        crsf_token = re.search(r"<script>XsrfToken.setToken\('(.*?)'\);</script>", session.get('https://www.example.com').text).group(1)
        time.sleep(5)

def _cthread():
    with Pool() as pool:
        while True:
            try:
                req = session.get(f"https://www.example.com")
                if req.status_code == 429:
                    time.sleep(5)
                    continue

                allposts = [f'https://www.example.com&Price={i["Price"]}'
                        for i in req.json()["data"]["Sellers"] if i["Price"] <= 10]
                if allposts:
                    pool.map(partial(session.post, headers={"X-CSRF-TOKEN": crsf_token}), allposts)
            except requests.urllib3.exceptions.ConnectTimeoutError as E:
                pass

threading.Thread(target=_cthread).start()
threading.Thread(target=token).start()


texts: Prepared statement inside function that then return results

texts:
I've created a function that makes a query of a database table and managed to use the results in another page where the function is called.

Is this approach good?

function cart_list($db, $user){
    $stmt = $db->prepare("
SELECT
    o.username,
    o.quantity,
    p.description,
    p.product_name,
FROM
    orders as o
INNER JOIN
    products as p
ON
    p.product_id = o.product_id
INNER JOIN
    users as u
ON
    o.username = u.username
WHERE
    o.username ='$user'
AND
    o.checkout ='0'");
return $stmt;
}

In the file where I called the function, I used:

$stmt = cart_list($db, $user);
$stmt->bind_result(
    $username,
    $quantity,
    $description,
    $product_name);
$stmt->execute();

while($stmt->fetch()){
echo $product_name;
}


texts:
I have several json models which represent same logic model. e.g:
{"title":"title1","years":"31"} and {"name":"title1","age":31}

at the moment I make 2 different classes which implement same interface

 public class NameModel implements Person {

  @SerializedName("name") private String name;
  @SerializedName("age") private int age;

  public String getName() {
    return name;
  }

  public int getAge() {
    return age;
  }
}
public class TitleModel implements Person {

  @SerializedName("title") private String title;
  @SerializedName("years") private int years;

  public String getName() {
    return title;
  }

  public int getAge() {
    return years;
  }
}
public interface Person {
  String getName();
  int getAge();
}

Is this a correct approach to unify different models to one if they are essentially same, but with different field names?


texts: Python class which chains Google translations back and forth between two languages

texts:
I created a class which creates chained translations (for example, Japanese translated to English, then back to Japanese, then to English).

Some concerns:

Is my usage of recursion good?
Is the class pythonic? Is there anything else to make it more pythonic?
I used instantiated Translator twice in my code. Is there any way to only use it once?

Code:

from googletrans import Translator

word_list = []

class Translate:

    def __init__(self, word, target_language='en'):
        translator = Translator()

        self.target_language = target_language
        self.original_language = translator.detect(word).lang
        self.chained_translation = self.repeat_translation(word, target_language)

    def __getitem__(self, item):
        return self.chained_translation[item]

    def __len__(self):
        return len(self.chained_translation)

    def repeat_translation(self, word, target, count=0):
        translator = Translator()
        translated_text = translator.translate(word, dest=target).text
        word_list.append(translated_text)
        count += 1
        # When recursive count is odd.
        if count % 2 == 1:
            return self.repeat_translation(translated_text, self.original_language, count)
        # When recursive count is even and under 10.
        if count < 10:
            return self.repeat_translation(translated_text, self.target_language, count)
        # When recursive ends.
        else:
            return word_list

Example usage:

test = Translate('は忙しい。彼は多忙な人間だ。勉強をしたい')
print(test.chained_translation)
print(test[9])
print(test[8])
print(len(test))

['I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい', 'I am busy. He is a busy man. I want to learn', '私は忙しいです。彼は忙しい人だ。学びたい']
私は忙しいです。彼は忙しい人だ。学びたい
I am busy. He is a busy man. I want to learn
10


texts:
I've written a program:

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Mohammad Faisal
 */
public class FileContentMatcher {

public static void main(String[] args) throws IOException {

    String textToMatch = "Quick Styles gallery on";
    ArrayList<String> paths = new ArrayList<String>();
    String content;
    int found = 0;
    int notFound = 0;
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };

    File path = new File("E:\\anchit\\temp");
    File[] listOfFiles = path.listFiles(filter);
    for (File file : listOfFiles) {
        content = FileUtils.readFileToString(file);
        if (content.contains(textToMatch)) {
            //System.out.println("Found in: " + file.getAbsolutePath());
            paths.add(file.getAbsolutePath());
            found++;
        } else {
            //System.out.println("No found\n" + content);
            notFound++;
        }
    }
    for (String pth : paths) {
        System.out.println(pth);
    }
    System.out.println("Found in " + found + " files.\nNot found in " + notFound + " files.");
}
}

In which I've used Apache Commons IO api.
My actual requirement is to list all the files in the given directory which contains the search phrase textToMatch in minimum amount of time about 4-5 seconds, where number of files could be upto 100000. But this program takes much more time than that.
So I need to optimize this code but not getting how?
Is there any API which can help me? I've heard of Lucene but not getting how to work with it.


texts: When push data to array decide which key need to use

texts:
Sometimes I need to push data to the array, but I have one different key (here I have key color and key name) and another part of the object is the same. I use IF/else to check this, but i wonder is there any better and cleanest way to handle this?
  getData(passedData, dataControl: string) {
    const data = [];

    for (const value of passedData) {
      if (dataControl === 'color') {
        data.push({
          color: value,   ---> diff
          username: this.userForm.value.username,
          test: this.userForm.value.test
        }
        );
        this.userForm.controls['data1'].setValue(data);     ---> diff

      } else {
        data.push({
          name: value,     ---> diff
          username: this.userForm.value.username,
          test: this.userForm.value.test
        }
        );
        this.userForm.controls['data2'].setValue(data);       ---> diff

      }
    }
  }

Thank you


texts: Vertex cover approximation in JavaScript

texts:
I believe this runs in \$O(V+E)\$ but I wouldn't be able to explain the reasons why. I was looking for some general code review and any help on understanding the runtime.

var Graph = function() {
    this.adj = {};
}

Graph.prototype.addEdge = function(v, w) {
    if (!Array.isArray(this.adj[v])) this.adj[v] = [];
    if (!Array.isArray(this.adj[w])) this.adj[w] = [];

    this.adj[v].push(w);
    this.adj[w].push(v);
}

var vertexCover = function(G) {
    var visited = {};
    var cover = [];

    var u;
    for (var v in G) {
        if (!visited[v]) {
            for (var i = 0; i < G[v].length; i++) {
                u = G[v][i];
                if (!visited[u]) {
                    visited[u] = true;
                    visited[v] = true;
                }
            }
        }
    }

    for (var x in visited) {
        cover.push(x);
    }
    return cover;
}

var ex = new Graph();
ex.addEdge(0, 1);
ex.addEdge(0, 2);
ex.addEdge(1, 3);
ex.addEdge(3, 4);
ex.addEdge(4, 5);
ex.addEdge(5, 6);
console.log('graph', ex.adj);

console.log(vertexCover(ex.adj));


texts: Using goto to wait on the result of a database query to change

texts:
This is a small personal project where most non-sensitive data is distributed to some globally hosted CDN servers, which store the JSON. Now one problem we've seen during testing is a few deadlocks during spike loading of Ajax resources at the precise time that the cache is being distributed to the cache servers. So I came up with this locking scheme. Basically it will loop until the cache-lock value from one of the slave db servers responds with a value of 1, where 1 represents readable and 0 represents a locked state.

Is this ok to put into production? The environment is a REST server written in Slim Framework. I'm not smart enough to know why goto is considered evil so I would like a different opinion. I'm also curious if I should choose an alternative to sleep(1).

public function wait_lock()
{
    $steps = 0;
    restart:
    if(! $this->is_enabled('cache-lock') ){
        if($steps > 4){
            // the following method is a short cut for throwing an exception.
            $this->e('cache error. wait a few moments and try again. if the problem persists, contact the administrator.');
        }else{
            sleep(1);
            $steps++;
            goto restart;
        }
    }
}


texts:
As a senior in Computer Science, have a long way to go towards improving myself. I'd appreciate any and all criticism.

Problem Set

Write a program that can draw a scalable checkered grid (like a chessboard) to any dimension.

#include <iostream>
using std::cout;
using std::cin;

void printSmallSquares(int SquareSize, int width, bool cond) {
bool stars = cond;
    printf("%s", "\n*");
    for (int i = 0; i < width; i++) {
        for (int i = 0; i < SquareSize; i++)
        {
            printf("%s", (stars ? "*" : " "));
        }
    stars = !stars;
}
printf("%s", "*");
}

int main() {
int Height = 8;
int Width = 16;
int SquareSize = 6;

for (int j = 0; j < Height; j++) {
    for (int i = 0; i < Width * SquareSize + 2; i++) {
        printf("%s", "*");
    }

    for (int i = 0; i < SquareSize; i++) {
        (j % 2 == 0 ? printSmallSquares(SquareSize, Width, true) : printSmallSquares(SquareSize, Width, false));
    }
    printf("%s", "\n");
}
for (int i = 0; i < Width * SquareSize + 2; i++) {
    printf("%s", "*");
}
cin >> Width;

}


texts: Inter Thread Communication Even Odd Example

texts:
I have implemented a simple example for inter thread communication which have 2 threads to print even and odd numbers in sequence.

I am looking for a feedback and points for improving the example.

My code looks like:

public class InterThreadCommunicationEvenOddExample
{
    public static void main(String[] args)
    {
        NumberResource numberResource = new NumberResource();
        new EvenThread(numberResource);
        new OddThread(numberResource);
    }
}

class EvenThread implements Runnable
{

    NumberResource numberResource;

    EvenThread(final NumberResource numberResource)
    {
        this.numberResource = numberResource;
        new Thread(this, "Even").start();
    }

    public void run()
    {
        while (true)
        {
            System.out.println("Even Thread::" + this.numberResource.getNextEven());
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {

            }
        }
    }

}

class OddThread implements Runnable
{

    NumberResource numberResource;

    OddThread(final NumberResource numberResource)
    {
        this.numberResource = numberResource;
        new Thread(this, "Odd").start();
    }

    public void run()
    {
        while (true)
        {
            System.out.println("Odd Thread::" + this.numberResource.getNextOdd());
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {

            }
        }
    }
}

class NumberResource
{

    private int number = 0;

    public synchronized int getNextEven()
    {
        while (isEven(number))
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {

            }

        }
        number++;
        notify();
        return number;
    }

    public synchronized int getNextOdd()
    {
        while (!isEven(number))
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {

            }

        }
        number++;
        notify();
        return number;
    }

    private boolean isEven(int number)
    {
        return number % 2 == 0;
    }

}


texts:
I was looking for a way to write this code shorter and still get the same result. Can this be achieved?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if indexPath.row == 0 {
        print("connection status pressed")

        print("get")

        let connectionStatusSelectorViewController = ConnectionStatusSelector()
        //profileEditor.user = self.user
        navigationController?.pushViewController(connectionStatusSelectorViewController, animated: true)

    }else{
        if indexPath.row == 1 {
            print("account type pressed")

            let AccountSelectorViewController = AccountTypeSelector()

            navigationController?.pushViewController(AccountSelectorViewController, animated: true)

        }else{
            if indexPath.row == 2 {
                print("gender type pressed")

                let GenderSelectorViewController = GenderTypeSelector()
                navigationController?.pushViewController(GenderSelectorViewController, animated: true)

            }else{
                if indexPath.row == 3 {
                    print("service type pressed")

                    let serviceSelectorViewController = ServiceTypeSelector()
                    navigationController?.pushViewController(serviceSelectorViewController, animated: true)

                }else{
                    if indexPath.row == 4 {
                        print("distance pressed")

                    }else{
        print("nothing")
}
}
}
}
}
}


texts:
I'm working on a random number guessing game.  I'm done with the code and it's working, but there is a part that I want to make better.  I declared an instance of a Guess class I created, and now how to make this part more efficient.

int counter = 0;
do
{
    myGuess.UserGuess = GetUserGuess(); //read user guess
    if (myGuess.Compair() == "match")
    {
        Console.WriteLine("\n\t Correct!You WIN !");
    }

    else if (myGuess.Compair() == "high")
    {
        if (counter < 3)
            Console.WriteLine("\n\tTry a lower number,");
        else
            Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);

        counter++;
    }

    else if (myGuess.Compair() == "low")
    {
        if (counter < 3)
            Console.WriteLine("\n\tTry a higher number,");
        else
            Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
        counter++;
    }

} while (myGuess.Compair() != "match" && counter < 4);

For example, I used the same message the same condition twice, which I think is not the best way.  Any way to loop better than that?


texts: Statistical queries on a list of customers

texts:
I have been given a list of simple Customer objects to work with. This would be an example of a customer list:

customers = [
    Customer(active=True, age=38, gender='F'),
    Customer(active=False, age=18, gender='M'),
    None,
    Customer(active=False, gender='F'),
    None,
    Customer(age=64),
    Customer(active=True, age=23),
    None,
    Customer(age=23, gender='M'),
    None,
]

The list contains None values for customers that have been deleted and active, gender and age are not required properties of Customer and so they can be un-set.

To find the number of active customers:

def number_of_active_customers(customers):
    # Assumption: A customer is only active if active=True is set
    return len([customer for customer in customers if customer is not None and customer.active is True])

To find the number of inactive customers:

def number_of_inactive_customers(customers):
    # Assumption: Deleted customers also count as inactive
    return len([customer for customer in customers if customer is None or customer.active in (False, None)])

To find out if the list of customers has any None values:

def list_has_none_values(customers):
    # any() won't work here since a list of None's always evaluates to False. We don't need to know the length
    # of the list so we can simply loop over each element and return True when we encounter the first None value
    for customer in customers:
        if customer is None:
            return True
    return False

To find out if the list has any customers with active=None:

def list_has_active_equals_none_customers(customers):
    # any() works here because we can stop processing at the first True value in the list
    return any([customer for customer in customers if customer is not None and customer.active is None])

To find the average age of male customers:

def average_age_of_male_customers(customers):
    try:
        # Round average to 1 digit
        return round(
            mean(
                (customer.age for customer in customers if customer is not None
                 and customer.gender == 'M' and isinstance(customer.age, int))
            ),
            1)
    except StatisticsError:
        # Return 0 when there are no male customers
        return 0

My code should be as pythonic and efficient as possible. I'm fairly sure I got it, I'm just second-guessing myself a little. This is not a school assignment and I am allowed to ask for help.


texts:
Any advice would be great. I watched a few videos over the last 3 weeks and made a program up; what do you think?

The program is a business ideal for a few computers in a shop, some computers with training and the rest of the computers without. (for gaming, etc.)

import java.util.Scanner;

public class n_com {

    public static void main (String args []){

        Scanner input = new Scanner (System.in);

    double training,p_h,computer_training,computers,open;

    double max,two,thre,four,five;
    double two2,thre3,four4,five5,p;

    System.out.print("please enter cost of training people up on the computer p/h £ ");
        training =input.nextDouble();

    System.out.print("please enter cost to use the pc p/h for general use £");
             p_h=input.nextDouble();

    System.out.print("please enter number of computer in the shop for training :");
             computer_training =input.nextInt();

    System.out.print("please enter number of computer in the shop for general use :");
            computers =input.nextInt();

    System.out.print("please enter hours open per week :");
             open=input.nextDouble();

    training = training * computer_training * open; //max income per week w/training
       p_h = p_h * computers * open;  //max income per week (gamers ect)

    max = training + p_h;

            two  =0.2 * max;    // 20%  max total
            thre =0.3 * max;    // 30%  max total
            four =0.4 * max;
            five =0.5 * max;

            p = 0.45;  // % of shop taking paid per week as wages

            two2  = p * two;  // 45% of the estimated shop taking (two = 0.20% of max)
            thre3 = p * thre;
            four4 = p * four;
            five5 = p * five;

            max = (max * 52 / 12);
            System.out.println();

       System.out.println ("maxim monthly income from the computers £ "+ max);

            System.out.println();

       System.out.println ("total income estimated over the next 2 years");

       System.out.println();

       System.out.println("estimated monthly income at mouth 1-3 \t:"+ two );
       System.out.println("estimated monthly income at mouth 3-6 \t:"+ thre);
       System.out.println("estimated monthly income at mouth 6-12\t:"+ four);
       System.out.println("estimated monthly income at year  1-2 \t:"+ five);

            System.out.println();

        System.out.println("wages will be 45% of total income at the end of each mouth" );

            System.out.println();

       System.out.println("estimated monthly wages for mouth 1 - 3  £ "+ two2  );
       System.out.println("estimated monthly wages for mouth 4 - 6  £ "+ thre3 );
       System.out.println("estimated monthly wages for mouth 7 - 12 £ "+ four4 );
      System.out.println("estimated monthly wages after the first year £"+five5);
     }
 }


texts:
Problem statement:

Write a function which returns the total number of combinations whose difference is k.
For example, 4 8 15 16 23 42 and the difference 7 has 2 pairs, 8, 15 and 16, 23.

I liked the Finding number of number pairs with given difference question so much (despite its brokenness) that not only did I review it, but I also decided to write up my own implementation of it (following the approach I described in my review). I was intrigued by this comment:

You need the handle the case of elements being equal too, though. That means an array with 2x duplicates such as 4 4 8 8 15 15 16 16 23 23 42 42 should return 4x the number of combinations as without duplicates. - JS1

When a pair is found, I count how many numbers are matching at lowIndex and highIndex respectively, and then calculating how many pairs there are.
NumberPairsDiff.java
public class NumberPairsDiff {

    public static int pairsWithDifference(int[] input, long difference) {
        int[] sorted = Arrays.copyOf(input, input.length);
        Arrays.sort(sorted);

        int pairsFound = 0;

        int lowIndex = 0;
        int highIndex = 0;

        while (lowIndex < sorted.length && highIndex < sorted.length) {
            long current = (long) sorted[highIndex] - sorted[lowIndex];
            if (current < difference) {
                highIndex++;
            } else if (current > difference) {
                lowIndex++;
            } else {
                // Find out how many values are equal at `highIndex`
                int highMatching = findEqual(sorted, highIndex);
                highIndex += highMatching;

                if (difference == 0) {
                    // 1+2+3+4+5+...+n = 0.5x^2 + 0.5x
                    int add = (int)(0.5f * highMatching * highMatching + 0.5 * highMatching);
                    pairsFound += add;
                    lowIndex += highMatching;
                } else {
                    // Find out how many values are equal at `lowIndex`
                    int lowMatching = findEqual(sorted, lowIndex);
                    lowIndex += lowMatching;
                    pairsFound += lowMatching * highMatching;
                }
            }
        }

        return pairsFound;
    }

    private static int findEqual(int[] sorted, int index) {
        int matching = 1;
        while (index < sorted.length - 1 && sorted[index] == sorted[index + 1]) {
            index++;
            matching++;
        }
        return matching;
    }

}

Obligatory parametrized unit test, NumberPairsDiffTest.java:
@RunWith(Parameterized.class)
public class NumberPairsDiffTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {new int[]{ 4, 4, 8, 8, 15, 15, 16, 16, 23, 23, 42, 42 }, 4, 4},
                {new int[]{ 4, 4, 8, 8, 15, 15, 16, 16, 23, 23, 42, 42 }, 7, 8},
                {new int[]{ 4, 4, 8, 8, 15, 15, 16, 16, 23, 23, 42, 42 }, 0, 18},
                {new int[]{ 1 }, 0, 1},
                {new int[]{ 2, 2 }, 0, 3},
                {new int[]{ 3, 3, 3 }, 0, 6},
                {new int[]{ 4, 4, 4, 4 }, 0, 10},
                {new int[]{ 2, 2, 4 }, 0, 4},
                {new int[]{ 1, 4, 7, 11, 14, 17 }, -3, 4},
                {new int[]{ 1, 4, 7, 11, 14, 17 }, 5, 0},
                {new int[]{ Integer.MIN_VALUE, Integer.MAX_VALUE }, (long)(Integer.MAX_VALUE) * 2L + 1L, 1},
        });
    }

    @Parameterized.Parameter(value = 0)
    public int[] input;

    @Parameterized.Parameter(value = 1)
    public long diff;

    @Parameterized.Parameter(value = 2)
    public int expected;

    @Test
    public void test() {
        String string = String.format("Array %s with diff %d", Arrays.toString(input), diff);
        assertEquals(string, expected, NumberPairsDiff.pairsWithDifference(input, diff));
    }

}

Primary concerns

Readable, understandable code?
Missed edge-cases?
Better approaches?


texts:
technical interview question i got from daily interview pro
A palindrome is a sequence of characters that reads the same backwards and forwards. Given a string, s, find the longest palindromic substring in s.
Example:

Input: "banana"
Output: "anana"

Input: "million"
Output: "illi"

i was wondering if there is any way to optimize the code more
Also is using built in functions such as join(),index() and so on not preferred for a coding interview ?Because by using it it makes it so much easier in python compared to languages like java
class Solution:

    def checkOddChars(self,lst):
        ls = []
        for i in lst:
            if lst.count(i) == 1:
                ls.append(i)
        return ls

    def checkPalindrome(self,lst):
        return lst[:] == lst[::-1]

    def longestPalindrome(self, s):
      lst = list(s)

      while lst:
        if self.checkPalindrome(lst) :
            return(''.join(lst))

        oddChars = self.checkOddChars(lst)

        if lst[0] in oddChars:
            del lst[0]
        if lst[len(lst)-1] in oddChars:
            del lst[len(lst)-1]

      return('List is empty')

# Test program
s = "tracecars"
print(str(Solution().longestPalindrome(s)))
# racecar
```


texts:
Riddle Description:

  \$N\$ doors are closed. In the first pass, I open all of them. In the
  second pass, I toggle every second door. In the third pass, I toggle
  every third door. I continue this until I have completed the \$N\$th
  pass. Find all the doors that will remain open after \$N\$ passes.

public static void printDoorsOpened(int passes)
{
        HashMap<Integer, Boolean> doors=new HashMap<Integer, Boolean>();
        int i = 0;
        //Close all doors as default in the start
        while(i < passes)
        {
            doors.put(i, false);
            i++;
        }

        for(int j = 1; j <= passes; j++)
        {
            for(int k = j - 1; k < passes; k += j)
                doors.put(k, !(doors.get(k)));
        }

        for(int l = 0; l < passes; l++)
        {
            System.out.println("The door number "+(l + 1)+" is "+(doors.get(l) == true ? "Opened" : "Closed"));
        }
}

Please feel free to review it based on best practices, style and any other efficient solution, but please refrain from solely style-based reviews.


texts:
As an introduction, I would like to have my inputs validated with the built-in validation HTML5 attributes, e.g. use pattern for text input. So this is my sample code that implements that.

Is it considered best practice while handling event, to access event.target, which is the original DOM, and do something with it, rather than dealing with React virtual DOM?

Please let me know if there are more improvements can be made. I'm using React.js 0.14.7. Thanks.

NodeList.prototype.forEach = Array.prototype.forEach;

class InputSet extends React.Component {
    render() {
        return (
            <div>
                <input type="text" defaultValue={this.props.firstName} data-field="firstName" required/>
                <input type="text" defaultValue={this.props.lastName} data-field="lastName" required/>
            </div>
        );
    }
}

class FormWithValidation extends React.Component {
    handleSubmit(event) {
        event.preventDefault();
        console.log(event.target);

        let childNodes = Array.prototype.slice.call(event.target.childNodes);
        childNodes = childNodes.filter((elm) => elm.tagName === 'DIV');
        const values = childNodes.map((div) => {
            const value = {};
            div.childNodes.forEach((input) => {
                const field = input.getAttribute("data-field");
                value[field] = input.value
            })
            return value;
        });

        // Do something with values.
        console.log(values);
    }

    render() {
        const inputSets = [
            {firstName: "Donald", lastName: "Duck"},
            {firstName: "Bill", lastName: "Williams"}
        ]

        return (
            <form action="" onSubmit={this.handleSubmit} >
                {inputSets.map((obj, index) => {
                    return <InputSet {...obj} key={index} />
                })}
                <input type="submit" value="Save"/>
            </form>
        );
  }
}

ReactDOM.render(<FormWithValidation/>, document.getElementById('container'))


texts: Are there any open vulnerabilities in this mailer script?

texts:
I made a PHP mailer script does the basic validation of fields, return errors, else submit if all is good. But it also has a honeypot field that is not required to be filled in (I'm assuming by hiding it using CSS a spambot will fill in the field anyway).  If the field is not empty, it opens a text file and writes/appends the attempt on it, and it also sends an email alert of the attempt.

<?php
//print_r($_POST);
$error['name'] ="";
$error['company']="";
$error['email'] ="";
$error['subject'] ="";
$error['message'] ="";
$error['website'] ="";
$success = "";
$thistime = time();
$current_date = date('m/d/Y/T ==> H:i:s');

if(isset($_POST['_save'])) {
    $name = stripslashes($_POST['name']);
    $email = stripslashes($_POST['email']);
    $company = stripslashes($_POST['company']);
    $message = stripslashes($_POST['message']);
    $subject = stripslashes($_POST['subject']);
    $website = stripslashes($_POST['website']);

    if (empty($name) || empty($email) || empty($subject) || empty($message) ||
            !empty($website)) {
    if (empty($name))
       $error['name'] = "Please enter your Full Name";
    if (empty($email))
       $error['email'] = "Please enter a valid Email Address";
    if (empty($company))
       $error['company'] = "Please enter Your Company Name";
    if (empty($subject))
       $error['subject'] = "Please Write a Subject";
    if (empty($message))
       $error['message'] = "Please write a message, inquiries or
               other concerns above";
    if (!empty($website)) // this is the honeypot
       $error['subject'] = "Opps looks like you're a spambot. You
              just filled in a not required field.;
      $myFile = "botlog.txt";
      $fh = fopen($myFile, 'a') or die("can't open file");
      $stringData = "bot trapped" . " " . "-"  . " " . $website . " " . "-
                    " . " " . $current_date . "\r\n";
      fwrite($fh, $stringData);
      fclose($fh);
      $donot="donotreply@example.com";
      $headers="From: {$email}\r\nReply-To: {$donot}"; //create headers
      mail('opps@example.com',$headers,$stringData);
    }
    else { //if not empty
    stripslashes($headers);
    $headers="From: {$email}\r\nReply-To: {$email}"; //create headers
    $content="Name: ".$name."\r\n\r\nCompany: "
               .$company."\r\n\r\nSubject: ".$subject."\r\n\r\nMessage: ".$message;
    mail('opps@example.com',$subject,$content,$headers); //mails it
    $success = "Thank you! You're email has been sent.";
    #done;
    }
}
?>

Am I doing it right? Does this open any vulnerabilities? I'm open to any suggestions and improvements.


texts: Writing C#'s analog of setTimeout, setInterval and clearInterval

texts:
I got tired of starting timer every time I need to do something simple as running some function 5 seconds after something in my code happens. So I tried to write a function (actually, 3 of them: setTimeout, setInterval and clearInterval) to write one line of code when I need it instead of, say, five.

It is working, at least for the cases I tested.

I understand that maybe something in that code is not right, maybe I forgot about something. Should I improve anything in my approach?

using System;
using System.Windows.Forms;

namespace timeouts_test
{
    public partial class Form1 : Form
    {
        private Timer[] timerList = new Timer[100];
        private int timerMaxIndex = -1;
        public Form1()
        {
            InitializeComponent();
            int aInterval = SetInterval(500, a);
            int bInterval = SetInterval(500, b);
            int cInterval = SetInterval(500, c);

            SetTimeout(3500, () =>
            {
                ClearInterval(aInterval);
            });

            SetTimeout(7000, () =>
            {
                ClearInterval(bInterval);
            });

            SetTimeout(10500, () =>
            {
                ClearInterval(cInterval);
            });
        }

        public void a()
        {
            label1.Text += "a";
        }

        public void b()
        {
            label1.Text += "b";
        }

        public void c()
        {
            label1.Text += "c";
        }

        public int SetInterval(int time, Action function)
        {
            Timer tmr = new Timer();
            tmr.Interval = time;
            tmr.Tick += new EventHandler(delegate (object s, EventArgs ev)
            {
                function();
            });
            tmr.Start();

            timerMaxIndex++;
            var index = timerMaxIndex;
            timerList[timerMaxIndex] = tmr;
            return index;
        }

        public int SetTimeout(int time, Action function)
        {
            Timer tmr = new Timer();
            tmr.Interval = time;
            tmr.Tick += new EventHandler(delegate (object s, EventArgs ev)
            {
                function();
                tmr.Stop();
            });
            tmr.Start();

            timerMaxIndex++;
            var index = timerMaxIndex;
            timerList[timerMaxIndex] = tmr;
            return index;
        }

        public void ClearInterval(int interval)
        {
            if (timerList[interval] == null)
                return;

            timerList[interval].Stop();
            timerList[interval] = null;
            if (interval == timerMaxIndex)
                timerMaxIndex--;
        }
    }
}

(Functions a, b and c were made just to test this.)


texts:
The following code takes in an point array and removes all of the nearby points whilst averaging them based on the conditions past in.

The variable _nCornerTolerance is an int that is calculated prior in the class. Typically it is around 5;

private Point[] AverageNearbyPoints(Point[] points, bool averageLeft, bool averageHigh)
{
    List<Point> plAveragedPoints = new List<Point>();
    for (int pi = 0, pc = points.Length; pi < pc; ++pi)
    {
        Point[] paNearbyPoints = points.Where(p => (Math.Abs(p.X - points[pi].X) <= _nCornerTolerance)
                                                && (Math.Abs(p.Y - points[pi].Y) <= _nCornerTolerance))
                                        .ToArray();
        if (paNearbyPoints.Length > 1)
        {
            int nX = averageLeft ? (int)Math.Floor(paNearbyPoints.Sum(p => p.X) / (float)paNearbyPoints.Length)
                                    : (int)Math.Ceiling(paNearbyPoints.Sum(p => p.X) / (float)paNearbyPoints.Length);

            int nY = averageHigh ? (int)Math.Floor(paNearbyPoints.Sum(p => p.Y) / (float)paNearbyPoints.Length)
                                    : (int)Math.Ceiling(paNearbyPoints.Sum(p => p.Y) / (float)paNearbyPoints.Length);

            if (!plAveragedPoints.Any(p => p.X == nX && p.Y == nY))
            {
                plAveragedPoints.Add(new Point(nX, nY));
            }
        }
        else
        {
            if (!plAveragedPoints.Any(p => p.X == points[pi].X && p.Y == points[pi].Y))
            {
                plAveragedPoints.Add(points[pi]);
            }
        }
    }

    return plAveragedPoints.ToArray();
}

Is there anyway I can rewrite the int nX = ... and int nY = ... parts better so I don't need the conditional?

A full review of this code would also be helpful, although the main part I am asking about is the above.


texts:
I just read this article on how to write a standard-like algorithm and wanted to try it myself by writing (as suggested in the article) an algorithm to test if a sequence given by two bidirectional iterators is a palindrome.

Here is my code with two different ways of calling the algorithm (is_palindrome and alt_is_palindrome):

#include <cctype>       // std::tolower
#include <functional>   // std::equal_to
#include <iostream>     // std::cout
#include <iterator>     // std::iterator_traits<T>::value_type
#include <string>
#include <vector>

template<typename Iterator>
using ItVType  = typename std::iterator_traits<Iterator>::value_type;

template<typename Iterator>
using StdEqual= typename std::equal_to<ItVType<Iterator>>;

template<typename BidirectionalIterator, typename Compare=StdEqual<BidirectionalIterator>>
bool is_palindrome(BidirectionalIterator first, BidirectionalIterator last, Compare comp=Compare())
{
    for(; first != last && first != --last; ++first)
        if(not comp(*first,*last))
            return false;

    return true;
}

template<typename BidirectionalIterator, typename Compare>
bool alt_is_palindrome(BidirectionalIterator first, BidirectionalIterator last, Compare comp)
{
    for(; first != last && first != --last; ++first)
        if(not comp(*first,*last))
            return false;

    return true;
}

template<typename BidirectionalIterator>
inline bool alt_is_palindrome(BidirectionalIterator first, BidirectionalIterator last)
{
    return alt_is_palindrome(first, last, StdEqual<BidirectionalIterator>());
}

int main()
{
    std::vector<std::string> vs = { "", "palindrome", "abba", "abcBA"};

    std::cout << "case sensitive:" << std::endl;
    for(auto const& s : vs)
        std::cout << s << " is "
            << ( is_palindrome(begin(s),end(s)) ? "" : "not " )
            << "a palindrome." << std::endl;
    std::cout << std::endl;

    auto my_comp = [](auto const& lhs, auto const& rhs)
    {
        return tolower(lhs) == std::tolower(rhs);
    };

    std::cout << "case insensitive:" << std::endl;
    for(auto const& s : vs)
        std::cout << s << " is "
            << ( is_palindrome(begin(s),end(s), my_comp) ? "" : "not " )
            << "a palindrome." << std::endl;
}

So first: I like the style of is_palindrome better with the default arguments, but I haven't seen it used in that way before (maybe I just haven't seen enough code...).
Is there a preferred way to declare this?
If so, is it 'just' a convention or are there actual benefits (performance, security,...) to it?

The second thing I am not sure about are my range-based for-loops and the lambda function int the main function.
As you see I took their respective variables by auto const&. I have sometimes seen people take them as auto&&, but I am not quite sure about he implications of this. Is this way preferred?

If you note anything else that isn't quite right or nice (e.g. the kind of type aliases I use), please let me know, too.


texts: Find existing player to update or create new one

texts:
I'm making a game in Java 7, and I have this block of logic when handling an update from the server.

public void handleNewPlayer(Player newPlayer, Player[] otherPlayers) {
    boolean done = false;
    for (Player otherPlayer : otherPlayers) {
        if (newPlayer.id == otherPlayer.id) {
            updatePlayer(otherPlayer);
            done = true;
            break;
        }
    }

    if (!done) {
        createPlayer(newPlayer);
    }
}

The client has a list of players, and gets a player object from the server. If the client already has that player (one with the same id), it updates that existing one, otherwise it creates a new one.

This code looks ugly though. The done flag is really getting under my skin. Is there a better way to organize this to avoid that? Are there any other problems with this code?

Sidenote: createPlayer() and updatePlayer() do very different things, and need to be seperate methods.