texts:
I'm a beginner PHP developer and it's my first time using MySQLi. I'm not sure if this is a correct implementation of the connection and query because some people defend this method and some others not. I need a solid implementation for heavy database usage.

Connection:

class bbddConnection {

private $_host = 'localhost';
private $_username = 'username';
private $_password = 'password';
private $_db_name = 'DBNAME';
private $_mysqli = NULL;
private static $_instance = NULL;

private function __construct() {
    $this->connection();
}

public static function get_instance() {
    if (!isset(self::$_instance)) {
        //echo "Creating new instance.\n";
        $class_name = __CLASS__;
        self::$_instance = new $class_name;
    }
    return self::$_instance;
}

private function connection() {
    //echo "Creating new connection.\n";
    try {
        //The mysqli object will be created once and only once
        if (!$this->_mysqli instanceof mysqli) {
            $this->_mysqli = new mysqli($this->_host, $this->_username, $this->_password);
        }
        if ($this->_mysqli->connect_errno) {
            throw new Exception('An error occured: ' . $this->_mysqli->connect_error);
        } else {
            $this->select_db();
        }
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
    }
}

private function select_db() {
    //echo "Selecting database.\n";
    try {
        $this->_mysqli->select_db($this->_db_name) or die('Could not find database');
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
    }
}

public function query($query) {
    if (!isset($query))
        return;
    //echo "Prevent SQL Injection. \n"
    $query = $this->_mysqli->real_escape_string($query);
    return $this->_mysqli->query($query);
}

public function stmt_init() {
    return $this->_mysqli->stmt_init();
}

public function __destruct() {
    if ($this->_mysqli instanceof mysqli) {
        $this->_mysqli->close();
    }
}

 private function __clone() {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
}

  private function __wakeup() {
    trigger_error('Unserializing is not allowed.', E_USER_ERROR);
}
}

Query:

class gestorUsuarios {

private $db;

public function __construct() {
    $this->db = bbddConnection::get_instance();
}
/**
 * Returns the Name of the user according his ID
 * @param int id
 * @return string Nombre, if an error occurred.
 * returns FALSE
 */
function getUserName($id)
{

    $stmt = $this->db->stmt_init();
    if ($stmt->prepare("Select Nombre from usuarios where id = ?")) {
        $name = '';
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->bind_result($name);

        while ($stmt->fetch())
            $nombre = $name;
        $stmt->close();

        return $nombre;
    } else {
          return false;
    }
}
/**
 * Edit the Name of the user according his ID
 * @param String Nombre, int id
 * @return Boolean if an error occurred.
 * returns FALSE, else returns TRUE
 */
function setUserName($nombre, $id)
{

    $stmt = $this->db->stmt_init();
    if ($stmt->prepare("UPDATE usuarios SET Nombre=? WHERE id =?")) {

        $stmt->bind_param('si', $nombre, $id);
        $stmt->execute();
        $stmt->close();

        return true;
    } else {
        return false;
    }
}
}


texts: Wet Chairs problem from Australian Informatics Olympiad

texts:
I'm trying to solve this problem from the Australian Informatics Olympiad here.

(These are past questions which I'm completing for the purpose of revision, if you are worried about the integrity of the competition, and unfortunately the organisation doesn't provide answers).

Basically, when given an input with: a list of "wet" or "dry" chairs, the number of people needed to be seated, and the number of people who will ONLY sit on dry chairs, you must determine the shortest possible distance between the two people on the ends (the shortest possible distance in total taken up by the group from first person to last).

The solution I found looped through each of the chairs, and for each wet chair allocated someone who was not picky, unless there were no more of those - in which case I simply skipped the chair.  For each dry chair I allocated one picky person, or a non-picky person. There's quite a lot of looping - I've tried to refuse to the size of the data with certain conditional statements - however my solution still timed-out on many of the larger inputs (the max time allowed is 1 second for you code to complete), despite getting the correct outputs.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Solution {

    public static void main(String[] args){
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader("chairsin.txt"));
            String[] lineOne = bufferedReader.readLine().split(" ");
            int numberOfChairs = Integer.parseInt(lineOne[0]);
            int totalFriends = Integer.parseInt(lineOne[1]);
            int niceFriends = Integer.parseInt(lineOne[2]);
            int pickyFriends = totalFriends - niceFriends;
            String[] chairs = bufferedReader.readLine().split("");
            int shortestLength = numberOfChairs;

            for(int x = 0; x < (chairs.length - totalFriends); x++){
                int easyFriends = niceFriends;
                int hardFriends = pickyFriends;
                for(int y = x; y < chairs.length; y++){
                    if ((y - x + 1) > shortestLength){
                        break;
                    }
                    if(chairs[y].equalsIgnoreCase("w")){
                        if(easyFriends>0){
                            easyFriends--;
                        }
                        else
                            continue;
                    }
                    else{
                        if(hardFriends>0){
                            hardFriends--;
                        }
                        else if(easyFriends>0){
                            easyFriends--;
                            continue;
                        }
                    }
                    if(hardFriends == 0 && easyFriends == 0){
                        shortestLength = y - x + 1;
                        break;
                    }
                }
            }

            PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter("chairsout.txt")));
            printWriter.print(shortestLength);

            bufferedReader.close();
            printWriter.close();

        }
        catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

Overall, I'm just looking for ways to improve my solution - be it by optimization, or using a completely different method/algorithm to solve this problem.


texts: Is this an efficient merge sort implementation with regards to average time complexity in Big-O notation?

texts:
Is my below merge sort implementation in O(n log n)? I am trying to implement a solution to find k-th largest element in a given integer list with duplicates with O(N*log(N)) average time complexity in Big-O notation, where N is the number of elements in the list.

 public class FindLargest {
        public static void nthLargeNumber(int[] arr, String nthElement) {
            mergeSort_srt(arr, 0, arr.length - 1);
            // remove duplicate elements logic
            int b = 0;
            for (int i = 1; i < arr.length; i++) {
                if (arr[b] != arr[i]) {
                    b++;
                    arr[b] = arr[i];
                }
            }

            int bbb = Integer.parseInt(nthElement) - 1;
            // printing second highest number among given list
            System.out.println("Second highest number is::" + arr[b - bbb]);
        }

        public static void mergeSort_srt(int array[], int lo, int n) {
            int low = lo;
            int high = n;
            if (low >= high) {
                return;
            }

            int middle = (low + high) / 2;
            mergeSort_srt(array, low, middle);
            mergeSort_srt(array, middle + 1, high);
            int end_low = middle;
            int start_high = middle + 1;
            while ((lo <= end_low) && (start_high <= high)) {
                if (array[low] < array[start_high]) {
                    low++;
                } else {
                    int Temp = array[start_high];
                    for (int k = start_high - 1; k >= low; k--) {
                        array[k + 1] = array[k];
                    }
                    array[low] = Temp;
                    low++;
                    end_low++;
                    start_high++;
                }
            }
        }

        public static void main(String... str) {
            String nthElement = "2";
            int[] intArray = { 1, 9, 5, 7, 2, 5 };

            FindLargest.nthLargeNumber(intArray, nthElement);
        }
    }


texts: Reading three rows of six tab-separated numbers

texts:
I've just posted this solution in my review of @adrienlucca's question, which is to read three rows of six tab-separated doubles.

#include <fstream>
#include <iostream>
#include <string.h>
#include <vector>

struct Sexdoublet {
    double x, y, d, m, c, t;

    friend std::istream &operator>>(std::istream &in, Sexdoublet &r) {
        return in >> r.x >> r.y >> r.d >> r.m >> r.c >> r.t;
    }

    friend std::ostream &operator<<(std::ostream &out, const Sexdoublet &r) {
        return out << "[ x = " << r.x
                   << ", y = " << r.y
                   << ", d = " << r.d
                   << ", m = " << r.m
                   << ", c = " << r.c
                   << ", t = " << r.t << " ]";
    }
};

std::vector<Sexdoublet> import(std::istream &in) {
    std::vector<Sexdoublet> data;
    Sexdoublet s;
    do {
        in >> s;
    } while (in && (data.push_back(s), true));
    return data;
}

int main(int argc, char *argv[]) {
    // If the first command-line argument is not "-", treat it as the filename
    // from which to read the input.  Otherwise, read from STDIN.
    const char *filename = (argc >= 2 && 0 != strcmp("-", argv[1])) ?
                                argv[1] : NULL;
    std::ifstream f;
    std::istream &in = filename ? (f.open(filename), f) : std::cin;
    if (!f) {
        std::cerr << "Error opening " << filename << ": "
                  << strerror(errno) << std::endl;
        return 1;
    }

    std::vector<Sexdoublet> data = import(in);
    std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {
        std::cout << s << std::endl;
    });
    return 0;
}

I ended up using the comma operator twice — both times as a "workaround" for the fact that a function I call returns void:

(data.push_back(s), true) — I have to check whether the istream extractions succeeded before adding an element to the result.
(f.open(filename), f) — I like the ternary operator because it expresses the fact that in is going to be assigned to one value or another.  Also, the in reference has to be initialized immediately and irrevocably, right?

It is my impression that the comma operator is rarely used in C and C++.  So, I'd like to ask, are these reasonable uses of the comma operator?  Or too clever?  Or too dumb, because I've missed an entirely better solution?


texts: Find the highest result between two elements in an array using their values and indices

texts:
I got a programming question on an interview where performance was the focus. I couldnt come up with a better solution than the one below which I think has a time complexity of O(n^2 + n) and scored 20/100 on performance.

The question in short was to find the highest result by adding two elements and in an array and the difference between the two indices e.g A[k] + A[j] + (j - k) - (k can be equal to j).

The size of the array = [1...100 000]
The values in the array =[-1000 000 000...1000 000 000]

I know using nested loops usally is a bad idea when It comes to handling larger arrays. So my question is simply how can it be improved to make it faster?

public static int solution(int [] A) {

    Set<Integer> occoured = new HashSet<Integer>();
    int maxAppeal = 0;

    for(int i = 0; i < A.length; i++) {
        if(occoured.add(A[i])) {
            for(int j = i; j < A.length; j++) {
                int appeal = A[i] + A[j] + (j - i);
                if(appeal > maxAppeal)
                    maxAppeal = appeal;
            }
        }
    }
    return maxAppeal;
}


texts: Multiple file creation with sorted input

texts:
Is there a more efficient way to create the three files and write to those files using BufferedOutput and BufferedWiter I/O? The code works, but I thought there has to be a more compact way to accomplish this.

import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;

public class SortStudent
{

    public static void main(String[] args)
    {
       //variables for processing
        Path fileOut1 = Paths.get("Honors_Students.txt");
        Path fileOut2 = Paths.get("Good_Standing.txt");
        Path fileOut3 = Paths.get("Probation_Students.txt");
        String recOut;
        String delimiter = ",";
        Scanner input = new Scanner(System.in);
        final int QUIT = 999;

        //data class record
        Student student = new Student();

        //input.output may generate exceptions
       try
       {
            //Setup the 3 files to be used for output
            OutputStream output1 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut1, CREATE));
            OutputStream output2 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut2, CREATE));
            OutputStream output3 =
                   new BufferedOutputStream(Files.newOutputStream(fileOut3, CREATE));
            BufferedWriter writer1 =
                   new BufferedWriter(new OutputStreamWriter(output1));
            BufferedWriter writer2 =
                   new BufferedWriter(new OutputStreamWriter(output2));
            BufferedWriter writer3 =
                   new BufferedWriter(new OutputStreamWriter(output3));

            BufferedWriter writer = null;

           //initial read for indefinite repetition
           System.out.print("Enter Student's ID number or 999 to quit: ");
           student.setID(input.nextInt());

           //sentinel controlled loop
           while (student.getID() != QUIT)
           {
                //get Student First Name
                System.out.print("Enter Student's First Name: ");
                student.setFirstName(input.next());

                //get Student Last Name
                System.out.print("Enter Student's Last Name: ");
                student.setLastName(input.next());

                //get Student GPA
                System.out.print("Enter Student's Grade Point Average: ");
                student.setgpa(input.nextDouble());

                //if gpa is 3.6 or> write to Honors Student
                if (student.Honors())
                    writer=writer1;

                //if gpa is >=2.0  and >3.5 write to Good Standing Student
                else if (student.Good_Standing())
                        writer=writer2;

                //if gpa is <2.0  write to Probation Student
                else if (student.Probation())
                        writer=writer3;

                //out of range
                else
                    continue;

                //build the record
                recOut = student.getID() + delimiter
                        + student.getFirstName() + delimiter
                        + student.getLastName() + delimiter
                        + student.getgpa();

                //write the record
                writer.write(recOut, 0, recOut.length());
                writer.newLine();

                //subsequent read for indefinite repetition
                System.out.print("Enter a Student's ID number or 999 to quit: ");
                student.setID(input.nextInt());

            }
            //close all files
            writer1.close();
            writer2.close();
            writer3.close();
        }
        catch(Exception e)
        {
            System.out.println("<<An exception has occurred.>> ");
            System.out.println(e.getMessage());
        }
    }
}


texts:
I have written this code to simulate a Turing machine and wonder what could be improved. In particular, the --tape.end() seems a bit dodgy.

#include <array>
#include <iostream>
#include <list>

typedef enum {right, left} Direction;

template<int n>         // n is the number of symbols
struct State {
    std::array<int, n> write;       // Value to write, 0 <= write < n
    std::array<Direction, n> move;  // Direction to move tape
    std::array<State*, n> next;     // Next state, nullptr represents HALT
};

// Some test machines
std::array<State<2>, 5> A = {{
    {{1, 1}, {left, left},   {&A[1],   &A[0]}},
    {{1, 1}, {right, right}, {&A[2],   &A[1]}},
    {{1, 1}, {left, right},  {&A[0],   &A[3]}},
    {{1, 1}, {left, right},  {&A[0],   &A[4]}},
    {{1, 0}, {left, right},  {nullptr, &A[2]}},
}};

std::array<State<2>, 6> B = {{
    {{1, 1}, {left, left},   {&B[1], &B[0]}},
    {{1, 1}, {right, right}, {&B[2], &B[1]}},
    {{0, 1}, {right, right}, {&B[5], &B[3]}},
    {{1, 0}, {left, right},  {&B[0], &B[4]}},
    {{0, 1}, {left, right},  {&B[0], &B[2]}},
    {{1, 1}, {left, left},   {&B[4], nullptr}},
}};

std::array<State<3>, 3> C = {{
    {{1, 1, 2}, {right, left, left},  {&C[1], &C[1], &C[0]}},
    {{1, 1, 2}, {left, right, right}, {&C[0], &C[2], nullptr}},
    {{0, 2, 1}, {left, right, left},  {&C[0], &C[2], &C[2]}},
}};

int main() {
    std::list<int> tape = {0};
    std::list<int>::iterator head = tape.begin();
    State<2>* current_state = &A[0];
    int read;

    unsigned long long int step_count = 0;
    while (true) {
        step_count += 1;
        // Read tape
        read = *head;
        // Write to tape
        *head = current_state->write[read];
        // Move tape head
        if (current_state->move[read] == right) {
            if (head == --tape.end()) {
                tape.push_back(0);
            }
            head++;
        } else if (current_state->move[read] == left) {
            if (head == tape.begin()) {
                tape.push_front(0);
            }
            head--;
        }
        // Change state
        if (current_state->next[read] == nullptr) {
            break;
        } else {
            current_state = current_state->next[read];
        }
    }
    std::cout << "Halted after " << step_count << " steps." << std::endl;
    unsigned int sum = 0;
    for (int it : tape) {
        sum += (it != 0);
    }
    std::cout << "Total non-zeroes: " << sum << std::endl;
    return 0;
}


texts:
Is there some more efficient way to calculate and extract that array that is greater than or equal to 0.8.

I had to use two foreach to do it, which is not very performant.

The idea is to find the most similar expressions comparing this two arrays.

Thanks!

function getNgrams($match, $n = 2) {

            $ngrams = array();
            $len = strlen($match);
            for($i = 0; $i < $len; $i++) {
                    if($i > ($n - 2)) {
                            $ng = '';
                            for($j = $n-1; $j >= 0; $j--) {
                                    $ng .= $match[$i-$j];
                            }
                            $ngrams[] = $ng;
                    }

            }
            return $ngrams;

    }

$question = 'happy birthday';
$rta = array('today', ' tomorrow ', 'monday', 'birthda');

$question_array = explode(' ',($question));
#print_r($question_array);

$ngram_question = array_map("getNgrams",$question_array);
$ngram_rta = array_map("getNgrams",$rta);
#print_r($ngram_rta);

foreach ($rta as &$valor) {

    foreach ($question_array as &$valorq) {

        $ngram_rta = getNgrams($valor);
        $ngram_q = getNgrams($valorq);

        if ((sizeof(array_intersect($ngram_rta,$ngram_q))/sizeof($ngram_rta)) >= 0.8)
            {echo $valor;
             echo "<br>";
            }

    }
}


texts: Changing a sprite depending on variables

texts:
I have code here which will change a sprite depending on the variables called gunUpgrade and moveUpgrade. Any way to make the code simpler or shorter? I'm using Unity 3D.

if (gunUpgrade > 0 && moveUpgrade > 0)
    {
        if (gunUpgrade == 1)
        {
            // For every moveupgrade, set the sprite to array number
            if (moveUpgrade == 1) { currentSprite = playerSprites[8]; }
            else if (moveUpgrade == 2) { currentSprite = playerSprites[9]; }
            else if (moveUpgrade == 3) { currentSprite = playerSprites[10]; }
            else if (moveUpgrade == 4) { currentSprite = playerSprites[11]; }
        }
        if (gunUpgrade == 2)
        {
            if (moveUpgrade == 1) { currentSprite = playerSprites[12]; }
            else if (moveUpgrade == 2) { currentSprite = playerSprites[13]; }
            else if (moveUpgrade == 3) { currentSprite = playerSprites[14]; }
            else if (moveUpgrade == 4) { currentSprite = playerSprites[15]; }
        }
        if (gunUpgrade == 3)
        {
            if (moveUpgrade == 1) { currentSprite = playerSprites[16]; }
            else if (moveUpgrade == 2) { currentSprite = playerSprites[17]; }
            else if (moveUpgrade == 3) { currentSprite = playerSprites[18]; }
            else if (moveUpgrade == 4) { currentSprite = playerSprites[19]; }
        }
    }


texts: Turning numbers into a string of words - challenge

texts:
I just completed this challenge at CodeEval.

  You are given a positive integer number. This represents the sales made that day in your department store. The payables department however, needs this printed out in english. NOTE: The correct spelling of 40 is Forty. (NOT Fourty)

My solution works, and it works pretty well. However I think there has to be an easier way to do this:

import sys

def nums_to_words(number):
    units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    teens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
             'seventeen', 'eighteen', 'nineteen']
    tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
            'eighty', 'ninety']
    thousands = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
                 'quintillion', 'sextillion', 'septillion', 'octillion',
                 'nonillion', 'decillion', 'undecillion', 'duodecillion',
                 'tredecillion', 'quattuordecillion', 'sexdecillion',
                 'septendecillion', 'octodecillion', 'novemdecillion',
                 'vigintillion']
    words = []

    if number == 0:
        words.append("zero")
    else:
        number_string = "%d" % number
        length_of_number_string = len(number_string)
        number_groups = (length_of_number_string + 2) / 3
        new_number_string = number_string.zfill(number_groups * 3)
        for i in range(0, number_groups * 3, 3):
            x, y, z = int(new_number_string[i]), int(new_number_string[i + 1]), int(new_number_string[i + 2])
            w = number_groups - (i / 3 + 1)
            if x >= 1:
                words.append(units[x])
                words.append("hundred")
            if y > 1:
                words.append(tens[y])
                if z >= 1:
                    words.append(units[z])
            elif y == 1:
                if z >= 1:
                    words.append(teens[z])
                else:
                    words.append(tens[y])
            else:
                if z >= 1:
                    words.append(units[z])
            if (w >= 1) and ((x + y + z) > 0):
                words.append(thousands[w])

    name = []

    for word in words:
        name.append(word.title())

    return ''.join(name) + "Dollars"

if __name__ == '__main__':
    with open(sys.argv[1], "r") as numbers:
        for num in numbers.readlines():
            print(nums_to_words(int(num)))

Is there anything that is obviously noticeable that I can do better?


texts:
I'm looking for some general feedback about the layout and structure of my code. Basically just any feedback, as I'm not super happy about this code, but I'm not sure how to improve it further.

'use strict';

/* jshint node: true */

var fs         = require('fs');
var os         = require('os');
var nodemailer = require('nodemailer');
var rimraf     = require('rimraf');
var config     = require('../config');
var dropbox    = require('../lib/dropbox-sync');
var mysql      = require('../lib/mysql-backup');
var tarball    = require('../lib/tarball');
var transport  = nodemailer.createTransport('sendmail');

// This is the FILE name of the backup file
var backupFilename  = config.dropbox.mysql_prefix + 'backup-' + Date.now();

// This is the absolute file path to save the file to on Dropbox
var dropboxFilename = ['', config.server, config.dropbox.mysql_folder, backupFilename].join('/');

// Connect to Dropbox with our credentials
try {
  dropbox.connect({
    key: config.dropbox.key,
    secret: config.dropbox.secret
  });
} catch (err) {
  failWithDropboxError(err);
}

// Connect to MySQL with our credentials
try {
  mysql.connect({
    host: config.mysql.hostname,
    user: config.mysql.username,
    password: config.mysql.password
  });
} catch (err) {
  failWithMySQLError(err);
}

// Generate a MYSQL backup
mysql.backup(backupFilename, function (err, pathname, stats) {
  if (err) {
    return failWithMySQLError(err);
  }

  tarball.create(pathname, '/tmp/' + backupFilename + '.tar.gz', function (code) {
    rimraf.sync(pathname);

    dropbox.send('/tmp/' + backupFilename + '.tar.gz', dropboxFilename, function (err, response) {
      fs.unlinkSync('/tmp/' + backupFilename + '.tar.gz');

      if (err) {
        failWithDropboxError(err);
      } else {
        console.log(response);
        console.log('The MySQL backup has been completed successfully.\n');
        console.log('Backed up %d from %d databases.\n', stats.tables, stats.databases);
        console.log('The backup file has been saved to your Dropbox: %s', '');
      }
    });
  });
});

function failWithMySQLError (err) {
  console.error('The MySQL backup job has encountered a fatal error and could not continue.\n');
  console.error('We were unable to create the MySQL backup.\n');
  console.error(err);

  process.exit(1);
};

function failWithDropboxError (err) {
  console.error('The MySQL backup job has encountered a fatal error and could not continue.\n');
  console.error('We were unable to sync the MySQL backup to Dropbox.\n')
  console.error(err);

  process.exit(1);
};


texts:
I'm building a Mozilla Firefox extension to hide link's formatting and show them as regular text. It consists of a script that runs on web-pages (content.js) that's activated by clicking on the extension (handled with background.js). On activation, a CSS rule is injected to hide link's formatting. Activating it again will shut changes off.
background.js additionally updates the extension's icon (based on links being currently hidden or not) every time the active tab is changed.
I'm new to JavaScript. I'd really appreciate your comments and observations to improve it (best practices, code structure, etc).
Script that runs on web pages (content.js):
'use strict';

// Links formatting state variable
let hideLinks = false;
const hideLinksRule = `
a,
a:hover,
a:focus,
a:active,
a:visited {
    text-decoration: none !important;
    color: inherit !important;
    background-color: inherit !important;
    border-bottom: initial !important;
}`;

let styleSheet = (function () {
    let style = document.createElement('style');
    document.head.appendChild(style);
    return style.sheet;
})();

function handleRequest(request) {

    // Do not modify if request is only a query
    if (request.isQuery) {
        return Promise.resolve({
            hideLinks
        });
    }

    // Toggle hide/show link formatting
    if (hideLinks) {
        styleSheet.deleteRule(0);
        hideLinks = !hideLinks;
    } else {
        styleSheet.insertRule(hideLinksRule, 0);
        hideLinks = !hideLinks;
    }

    // Return links state
    return Promise.resolve({
        hideLinks
    });

}

browser.runtime.onMessage.addListener(handleRequest);

Script to handle the extension on the browser (background.js):
// Icons paths
const showLinksIconPath = {
    path: 'icons/link-icon.png'
};
const hideLinksIconPath = {
    path: 'icons/broken-link-icon.png'
};

function onError(error) {
    browser.browserAction.setIcon(showLinksIconPath);
}

function updateIcon(response) {
    if (response.hideLinks) {
        browser.browserAction.setIcon(hideLinksIconPath);
    } else {
        browser.browserAction.setIcon(showLinksIconPath);
    }
}

function verifyTabStatus(activeInfo) {
    browser.tabs.sendMessage(
        activeInfo.tabId, {
            isQuery: true
        }
    ).then(updateIcon).catch(onError);
}

function activeTabLinkToggle() {
    browser.tabs.query({
        currentWindow: true,
        active: true
    }).then(requestLinkFormatToggle).catch(onError);
}

function requestLinkFormatToggle(tabs) {

    if (!(tabs === undefined || tabs.length == 0)) {
        const activeTab = tabs[0];
        browser.tabs.sendMessage(
            activeTab.id, {
                isQuery: false
            }
        ).then(updateIcon).catch(onError);
    }

}

// Update Icon on tab change
browser.tabs.onActivated.addListener(verifyTabStatus);

// Request toggle link formatting on click
browser.browserAction.onClicked.addListener(activeTabLinkToggle);

Configuration file to put it together (manifest.json):
{

    "manifest_version": 2,
    "name": "No-link",
    "version": "1.0",

    "description": "Hide link formatting.",

    "icons": {
        "48": "icons/link-icon.png"
    },

    "permissions": [
        "tabs"
    ],

    "browser_action": {
        "default_icon": "icons/link-icon.png",
        "default_title": "No-link"
    },

    "background": {
        "scripts": ["background.js"]
    },

    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]

}

You can also get the source code here.
Thank you very much for your time.


texts:
I just want to create masonry vertical layout with two divider .card-lef`` and.card-right`. Anyone have an idea to place #cardTemplate in left or right based on data Odd/Even? Or maybe in my .ts separate odd/even array?

HTML:

<ng-template let-data="data" #cardTemplate>
    <div class="card">
    </div>
</ng-template>


texts:
I have this method in Java:

private static int ConvertToTimestamp(Date value)
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S", Locale.US);
    String text = "1970-01-01 00:00:00.0";
    LocalDateTime localDateTime = LocalDateTime.parse(text, formatter);

    // getTime() returns milliseconds
    int seconds = (int) (value.getTime()/1000) - localDateTime.getSecond();
    return seconds;

}

It returns the number of seconds between the input parameter and 1/1/1970.
Are there any improvements to this or better ways to do it?


texts: Setting new values in array based on query results

texts:
I have some code which uses nested foreach loops to take the results of a query and drill down into the data, reassigning into a main data array at each level of the foreach nesting. The problem is that required reference variables are passed into the loops deeper down the tree, making it difficult to refactor.

I'd like to refactor this into a more functional style. I've looked into array_walk() and array_map() to try and accomplish this but they seem to be more suited to amending the array argument rather than reassigning to an external array.

I'm looking more for general approaches to refactoring out foreach loops in PHP with this sort of context rather than a direct solution to my problem.

foreach($grid_fields as $gridFieldKey => $gridFieldValue) {
    $grid_field_id = $gridFieldValue['field_id'];
    $grid_field_str = 'field_id_' . $grid_field_id;
    $grid_entry = $this->fetchGridEntry($grid_field_id, $data['entry_id']);

    if(sizeOf($grid_entry) > 0) {
        $data[$grid_field_str] = array();
        $data[$grid_field_str]['entry_id'] = $cloned;

        foreach($grid_entry as $gridEntryKey => $gridEntryValue) {
            $grid_row = 'new_row_' . $gridEntryKey;
            $data[$grid_field_str]['rows'][$grid_row] = array();

            foreach($gridEntryValue as $geK => $geV) {
                if(strpos($geK, 'col_id_') !== false || strpos($geK, 'row_id') !== false) {
                    $data[$grid_field_str]['rows'][$grid_row][$geK] = $geV;
                }
            }
        }
    }
}


texts: Letter Combinations of a phone number using a Dictionary

texts:
Problem statement  (online source)

  Given a digit string, 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.

  Input: Digit string "23"

  Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

  Note:

  Although the above answer is in lexicographical order, your answer
  could be in any order you want.

I have seen and read the reviews for the above problem, and made the modifications suggested. I did see the comment on using LINQ, I am learning how to use them and don't fully understand it yet. I successfully submitted my answer to LeetCode, but I would like a review to see what else I can do to improve the code. I noticed the code uses more memory than most submissions on LeetCode and I wonder if I can find out why here.

My code is based on a tutorial I watched. While it was in Java, I typed my code in C#. It recursively calls the method that looks into the objects of a Dictionary and concatenates the data inside them in the desired format. I am new to programming so I looked up stuff online and made some assumptions on equivalent data structures in C#. For example, the original code used a HashMap, and saw a recommendation online to used Dictionary<T, T> in C#.

public class Solution {
public IList<string> LetterCombinations(string digits) {
    List<String> result = new List<String>();
    if (String.IsNullOrEmpty(digits)){
        return result;
        throw new ArgumentNullException(nameof(digits));
    }
    Dictionary<Char, Char[]> lettersMap = new Dictionary<Char, char[]>();
        lettersMap.Add('1', null);
        lettersMap.Add('2', new[] { 'a', 'b', 'c' });
        lettersMap.Add('3', new[] { 'd', 'e', 'f' });
        lettersMap.Add('4', new[] { 'g', 'h', 'i' });
        lettersMap.Add('5', new[] { 'j', 'k', 'l' });
        lettersMap.Add('6', new[] { 'm', 'n', 'o' });
        lettersMap.Add('7', new[] { 'p', 'q', 'r', 's' });
        lettersMap.Add('8', new[] { 't', 'u', 'v' });
        lettersMap.Add('9', new[] { 'w', 'x', 'y', 'z' });
        lettersMap.Add('0', null);
        StringBuilder sb = new StringBuilder();
        int pos = 0;
        LetterCombinationsFunction(digits, sb, lettersMap, result, pos);
    return result;
}
private static List<String> LetterCombinationsFunction(String digits, StringBuilder sb,
                Dictionary<Char, Char[]> lettersMap, List<String> result, int pos)
    {
        if (sb.Length == digits.Count())
        {
            result.Add(sb.ToString());
            return result;
        }
        lettersMap.TryGetValue(digits[pos], out char[] values);
            foreach (var v in values)
            {
                sb.Append(v);
                LetterCombinationsFunction(digits, sb, lettersMap, result, pos+1);
                sb.Remove(sb.Length - 1, 1);
            }
        return result;
    }
}


texts:
We're having a small debate in work about the following piece of code:

private string GetNextFileName(string fileName)
{
    int index = 1;

    string nextName = $"{fileName}_{index}.png";

    while (File.Exists(nextName))
    {
        nextName = $"{fileName}_{++index}.png";
    }

    return nextName;
}

Is there anything particularly dangerous about this piece of code? It sort of feels dodgy having the condition in a while loop.

Would it be better to use a for-loop with a breakout if the number gets too high?

e.g.

private string GetNextFileName(string fileName)
{
    int i = 1;
    string nextName = $"{fileName}_{i}.png";

    for (; i < 100; ++i)
    {
        if (!File.Exists(nextName))
        {
            return nextName;
        }
        nextName = $"{fileName}_{i}.png";
    }

    throw new ApplicationException("Unable to get free filename");
}


texts: Factory object with a dependency on a bean

texts:
My problem is quite straightforward. I want to build a factory, but the kind of object returned depends on a value read from a bean that is somehow a cache. So of course, I can't call the bean's method from the static method in the factory:

public interface FinderService
{
    public String find(String name);
}

public class GeneralFinderService implements FinderService
{
    @Override
    public String find(String name)
    {
        return "general name";
    }
}

public class NorthFinderService implements FinderService
{
    @Override
    public String find(String name)
    {
        return "place in the north";
    }
}

public class SouthFinder implements FinderService
{
    @Override
    public String find(String name)
    {
        return "guy in the south";
    }
}

public class TestFinder
{
    public static void main(String[] args)
    {
        FinderService finderService = FinderFactory.getFinderService("my location");
        finderService.find("some guy");
    }
}

The options I think I have right now are either make the factory a bean, or use AppContext.getBean to get the bean in the factory. I like neither of them.

Option 1: make the factory a bean

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("finderFactory")
public class FinderFactory
{
    @Autowired
    private LocationCache locationCache;

    public FinderService getFinderService(String location)
    {
        if (locationCache.isInNorth(location))
        {
            return new NorthFinderService();
        }
        else if (locationCache.isInSouth(location))
        {
            return new SouthFinder();
        }
        else
        {
            return new GeneralFinderService();
        }
    }
}

Option 2: get the bean from the appcontext

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FinderFactory
{
    private static LocationCache locationCache = (LocationCache) new ClassPathXmlApplicationContext().getBean("locationCache");

    public static FinderService getFinderService(String location)
    {
        if (locationCache.isInNorth(location))
        {
            return new NorthFinderService();
        }
        else if (locationCache.isInSouth(location))
        {
            return new SouthFinder();
        }
        else
        {
            return new GeneralFinderService();
        }
    }
}

Is there a better approach?


texts: Adding an attribute to a class after the documentation comment trivia

texts:
I am trying to turn

namespace DevComponents.WpfEditors.Primitives
{
    /// <summary>
    /// Interaction logic for EditorFreeTextButton.xaml
    /// </summary>
    public partial class EditorFreeTextButton : EditorButton
    {
        public EditorFreeTextButton()
        {
            InitializeComponent();
        }
    }
}

into

namespace DevComponents.WpfEditors.Primitives
{
    /// <summary>
    /// Interaction logic for EditorFreeTextButton.xaml
    /// </summary>
    [System.Reflection.Obfuscation(Exclude = true)]
    public partial class EditorFreeTextButton : EditorButton
    {
        public EditorFreeTextButton()
        {
            InitializeComponent();
        }
    }
}

through Roslyn. I have the following code that works

private static SyntaxNode AddAnnotation(ClassDeclarationSyntax classNode, SyntaxNode rootNode)
{
    var name = SyntaxFactory.ParseName("System.Reflection.Obfuscation");
    var arguments = SyntaxFactory.ParseAttributeArgumentList("(Exclude = true)");
    var attribute = SyntaxFactory.Attribute(name, arguments);
    var leadingTrivia = classNode.GetLeadingTrivia();
    var whitespace = leadingTrivia.LastOrDefault(x => x.Kind() == SyntaxKind.WhitespaceTrivia);

    var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attribute))
        .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
    var newClassNode = classNode.WithoutLeadingTrivia()
        .WithLeadingTrivia(whitespace)
        .AddAttributeLists(attributeList)
        .WithLeadingTrivia(leadingTrivia);

    rootNode = rootNode.ReplaceNode(classNode, newClassNode);
    return rootNode;
}

However I feel like I am coding in circles to get all the leading Trivia right.

Is there a easier way to insert an attribute to be after the SingleLineDocumentationCommentTrivia and be formatted correctly with the correct leading whitespace trivia?


texts: Snakes and Ladders random world generator second implementation

texts:
The following is an implementation of a random world generator for the classic Snakes and Ladders game. This is a follow up to this question, where I reviewed my own original implementation. I am asking for a review of my review.

The world rules are:

The head of a snake can not be on the last square (you'll never win)
The base of a ladder can not be on the last square (you'll have no where to go)
A square can only have one thing, either the head or base of a ladder or a snake

class World
  attr_reader :size, :snakes, :ladders

  def initialize(size, snakes = 10, ladders = 10)
    @size = size
    @snakes, @ladders = {}, {}
    place_snakes(snakes)
    place_ladders(ladders)
  end

  def place_snakes(count)
    count.times do
      start_point = place_point
      end_point_range = habitable_range.begin..(start_point - 1)

      snakes[start_point] = place_point(end_point_range)
    end
  end

  def place_ladders(count)
    count.times do
      start_point = place_point
      end_point_range = (start_point + 1)..habitable_range.end

      ladders[start_point] = place_point(end_point_range)
    end
  end

private

  def place_point(range = habitable_range)
    begin
      point = rand(range)
    end while occupied?(point)
    point
  end

  def occupied?(number)
    [snakes.keys, snakes.values, ladders.keys, ladders.values].flatten.include?(number)
  end

  def habitable_range
    1..(size - 1)
  end
end


texts: Suggested refactorings of this Ruby time-to-string method?

texts:
I have the following code that gets the difference in time between now and when an alarm is supposed to go off (i.e. "alarm goes off in 23 minutes, 56 seconds").

def time_to_alarm_in_words
  #AN EMPTY STRING WE WILL BE ADDING TO
  time_in_words = ''

  #THE TIME TO THE ALARM IN SECONDS
  total_seconds = (time - Time.now).to_i

  #SOME BASIC TIME UNIT VARIABLES
   days = total_seconds / 86400
   hours = (total_seconds / 3600) - (days * 24)
   minutes = (total_seconds / 60) - (hours * 60) - (days * 1440)
   seconds = total_seconds % 60

  #ONLY PROCEED IF THE TIME TO THE ALARM IS POSITIVE(I.E. IN THE FUTURE)
  unless total_seconds <= 0
    #BUILD A HASH WITH THE TIME UNTIL THE ALARM
    time_hash = {"days" => (total_seconds / 86400),
               "hours" => ((total_seconds / 3600) - (days * 24)),
               "minutes" => ((total_seconds / 60) - (hours * 60) - (days * 1440)),
               "seconds" => (total_seconds % 60)}

  #IF THE TIME SEGMENT IS POSITIVE, ADD IT TO THE STRING
  time_hash.each_pair do |time_segment,length|
    if value > 0

      #i.e. add "22 hours," to the empty string
      time_in_words << "#{length} #{time_segment},"
    end
  end

  #CHOP OFF THE TRAILING ','
  time_in_words.chop!

  #RETURN THE RESULT
  return time_in_words + " ago"
end

I have a feeling I could cut this down by half. Any suggestions?!


texts: Date range remove/split within array of date range

texts:
I have date range array and a removeRange object which can split or remove portion of on the date range array. If Range is within the date range it will split the record into 2 range otherwise it can trim portion of the date range or remove entirely the date range.  I've moment js on the date query to check of date is greater than or less than. SnippetLink

var appt = [{
  text: 'appointment 1',
  StartTime: new Date('June 27,2017 08:00:00'),
  EndTime: new Date('June 27,2017 10:00:00'),
  deleted: false
}, {
  text: 'appointment 2',
  StartTime: new Date('June 28,2017 08:00:00'),
  EndTime: new Date('June 28,2017 12:00:00'),
  deleted: false
}, {
  text: 'appointment 3',
  StartTime: new Date('June 28,2017 13:00:00'),
  EndTime: new Date('June 28,2017 17:00:00'),
  deleted: false
}];
console.log(appt);

//NOTE: this will remove appointment 2 and 3
//var removeRange = {
// StartTime: new Date('June 28,2017 05:00:00'),
//EndTime: new Date('June 28,2017 18:00:00')
//}

//NOTE: This will split the appointment 2
//var removeRange = {
//  StartTime: new Date('June 28,2017 09:00:00'),
//  EndTime: new Date('June 28,2017 10:00:00')
//}

//NOTE: This will remove portion of appointment 2 and appointment 3
var removeRange = {
  StartTime: new Date('June 28,2017 09:00:00'),
  EndTime: new Date('June 28,2017 14:00:00')
}

var forAddLater = [];
appt.forEach(function(appointment, index) {
  if (moment(removeRange.StartTime).isSame(moment(appointment.StartTime), 'day')) {
    //console.log('same day', moment(appointment.StartTime));

    if (moment(removeRange.StartTime).isSameOrBefore(moment(appointment.StartTime))) {
      console.log('same or before', moment(removeRange.StartTime));

      if (moment(removeRange.EndTime).isBefore(moment(appointment.EndTime)) &&
        moment(removeRange.EndTime).isAfter(moment(appointment.StartTime))) {
        console.log('removeRange.EndTime is before appt end time');
        console.log('New StartTime is removeRange.EndTime');
        appt[index].StartTime = removeRange.EndTime;
      }

      if(moment(removeRange.EndTime).isSameOrAfter(moment(appointment.EndTime))){
        console.log('For delete the appt');
        appt[index].deleted = true;
      }
      //else {
        //if (moment(removeRange.EndTime).isBefore(moment(appointment.EndTime))) {
        //  appt[index].StartTime = removeRange.EndTime;
        //} else {
        //  console.log('For delete the appt');
        //  appt[index].deleted = true;
        //}

      //}
    } else {
      console.log('inside the range');
            console.log(moment(removeRange.EndTime));
      console.log(moment(appointment.EndTime));
      if (moment(removeRange.EndTime).isBefore(moment(appointment.EndTime))) {
        console.log('split the appointment data and add new');
        forAddLater.push({
          text: appointment.text + '-split',
          StartTime: removeRange.EndTime,
          EndTime: appointment.EndTime,
          deleted: false
        });
        appt[index].EndTime = removeRange.StartTime;
      } else {
        console.log(appointment);
        console.log('remove the end portion only');
        appt[index].EndTime = removeRange.StartTime;
      }
    }

  }
});

appt.push(forAddLater);

appt = appt.filter(function(el) {
  return !el.deleted;
});

console.log(appt);

Is there a better enhancement on this or a little bit simpler way to handle this one? Is there a possible scenario where the code may fail?


texts: Maximum sub-array of non-negative numbers

texts:
This is the "Maximum sub-array" problem from CodeChef:

  Find out the maximum sub-array of non negative numbers from an
  array.

  The sub-array should be continuous. That is, a sub-array
  created by choosing the second and fourth element and skipping the
  third element is invalid.

  Maximum sub-array is defined in terms of the
  sum of the elements in the sub-array. Sub-array A is greater than
  sub-array B if sum(A) > sum(B).

  NOTE 1: If there is a tie then compare the segment length's and return
  segment which has maximum length.

  NOTE 2: If there is still a tie, then return the segment with minimum starting index.

This is my solution:

def maxset(array):
    """Returns maximum sub array of non-negative numbers"""
    max_sum = 0
    current_sum = 0
    start = 0
    stop = 0
    max_array = array[0]
    for i in range(len(array)):
        if array[i] >= 0:

            current_sum +=  array[i]
            stop += 1

            if max_sum < current_sum:
                max_sum = current_sum
                if max_array < array[start:stop]:
                    max_array = array[start:stop]

            elif max_sum == current_sum:
                if len(max_array)< len(array[start:stop]):
                    max_array = array[start:stop]

        else :

            start = i+1
            stop = start
            current_sum = 0

    return max_array

Test cases :

def main():
    print maxset( [ 1, 2, 5, -7, 2, 5 ] )
    print maxset( [ 1,-1, 1, -1, 1, -1])
    print maxset( [ 1, 2, 5, 7, 2, 5 ] )
    print maxset( [ 222])
    print maxset( [ 1, 1])
    print maxset( [  3, -1, 1, 1, 1, -1, 3])
    print maxset( [ 5, -1, 1, 1, 1, 1, -1, 5 ])
    print maxset([ 3, -1, 1, 1, 1, -1, 2 ])
    print maxset([ 3,-3, -1, 1, 1, 1, -1, 2 ])
if __name__ == '__main__':
    main()

How can I improve this code ?


texts:
I am learning spring and am wondering about this service class's method. Is there a way to split this method up? Is there a way to use spring framework to make this method more readable? Should I move any of it to the controller or the DAO or should I split it into more service methods?

// UserBean has fields: username, password, first name, last name, etc.
// The UserBean parameter has 2 non-null fields: username and password.
public UserBean getUserDetails(UserBean bean) {
    UserEntity entity = new UserEntity();
    BeanUtils.copyProperties(bean, entity);

    // Gets user from DB based on UserBean's username and password.
    // Returns null if not found.
    entity = this.userDao.getUser(entity);

    if (entity == null) {
        return null;
    }

    // Fill in the rest of the UserBean's data from the DB
    UserBean userBean = new UserBean();
    BeanUtils.copyProperties(entity, userBean);
    // calculate time since last login based on DB timestamp
    userBean.setTimeSinceLastLogin(this.getSecondsSinceLastLogin(entity.getLastLogin()));

    // update DB with new timestamp
    entity.setLastLogin(new Date());
    this.userDao.updateUser(entity);

    return userBean;
}


texts: Implementing feature hashing using guava

texts:
I am trying to implement feature hashing in Java. For this I am trying to use Hashing functions from guava.

This is how I am doing it now:

//seed is any integer.
HashFunction hf = Hashing.murmur3_32(seed);

//key is the input int and hd is the hashed dimension.
int hash = Hashing.consistentHash(hf.hashInt(key), hd);

I have another method for sign, not shown in this question.

To measure the performance, I am doing something like below:

int min = 0, max = 2000000, sampleSize = 3000000;
int[] hds = { 2000, 5000, 6000, 10000, 20000, 500000, 1000000, 2000000 };

List<Double> guavaCollisons = new ArrayList<>();

UniformIntegerDistribution runif = new UniformIntegerDistribution(min, max);

Arrays.stream(hds)
        .forEach(hd -> {
            int seed = runif.sample();

            HashFunction hf = Hashing.murmur3_32(seed);

            Map<Integer, Set<Integer>> guava = new HashMap<>();

            Arrays.stream(runif.sample(sampleSize))
                    .forEach(key -> {

                        int guavaHash = Hashing.consistentHash(hf.hashInt(key), hd);

                        if (!guava.containsKey(guavaHash))
                            guava.put(guavaHash, new HashSet<Integer>());

                        guava.get(guavaHash).add(key);
                    });

            double guavaCollisionHd = guava.entrySet()
                    .stream()
                    .mapToInt(entry -> entry.getValue()
                            .size())
                    .average()
                    .getAsDouble();

            guavaCollisons.add(guavaCollisionHd);

            System.out.println("Available buckets = " + hd
                + ",  unutilized = " + (hd - guava.keySet().size())
                + ", guava collision = " + guavaCollisionHd);
        });

double guavaCollision = Stats.meanOf(guavaCollisons);
System.out.println("Average collision = " + guavaCollision);

My questions are:

Is this a correct way to implement the 'hash' part of feature hashing?
Is this a correct way to measure the collision rate of the hashing technique?


texts:
Jojo is browsing the internet while suddenly he sees an ad about the new cafe. The promotion is if the price
of an item is N dollars, then you can buy the second item for half the price, the third item for a quarter of the
original price, and so on, but if it becomes less than M dollars, then you have to pay M dollars. He wonders
how much he has to pay if he buys K item.

Format Input

The first line will contain an integer T, the number of test cases.
Each test case will have 3 integers N, M, and K, each denoting the original price, the minimum price, and the
amount Jojo is going to buy.

Format Output

For each test case, print “Case #X: “ (X starts with 1), then followed by the price Jojo has to pay rounded to 3
decimal digits.

Constraints

1 <= T <= 10

1 <= M <= N <= 1,000,000,000

1 <= K <= 1,000,000,000

#include <stdio.h>

    int main()
    {
        int T;
        scanf("%d", &T);

        for (int i = 1; i <= T; i++) {
            int M, K, N;
            scanf("%d %d %d", &N, &M, &K);

            float halfPrice = N;
            float sum = halfPrice;

            for (int j = 0; j < K-1; j++) {
                halfPrice /= 2;
                halfPrice = (halfPrice < M) ? M : halfPrice;
                sum += halfPrice;
            }
            printf("Case #%d: %.3f\n", i, sum);
        }
    }


texts:
I have a method poker defined as below:

def poker(hands):
'''Returns the best hand from a list of hands.

    Parameters:
        hands: list

    Example:
        poker(hands) => hands
'''
    return max(hands, key=hand_rank)

As mentioned in the docstrings, this function returns the best hand from a list of hands.
The issue I am facing is while passing an empty list of hands to this function. Hypothetically and for greater coverage, I want to add such a test case.

Should I raise an error or should I return None object ?

Generally, how do I decide where an error should be raised and where should it not?


texts: Using Python to tokenize a string in a stack-based programming language

texts:
As an avid user of esoteric programming languages, I'm currently designing one, interpreted in Python.

The language will be stack-based and scripts will be a mix of symbols, letters, and digits, like so:

ab123c-43=f54g6!6

This will be read from the file and passed to a new Script object, to tokenize. It needs to be tokenized into a list of strings, where adjacent digits are grouped together and converted into ints, but letters are individual, resulting in this array:

['a', 'b', 123, 'c', '-', 43, '=', 'f', 54, 'g', 6, '!', 6]

Currently, I am doing this using regex, with the following code (get_tokens is the main method):

import re

class Script:
    def __init__(self, text):
        self._tokens = Script.get_tokens(text)

    def get_tokens(text):
        """ Static tokenizer function.
        Uses regex to turn the string into a list of tokens.
        Groups adjacent digits together and converts to integers. """

        tokens = re.findall('\d+|[^\d]', text)

        for i in range(len(tokens)):
            if tokens[i].isdigit():
                tokens[i] = int(tokens[i])

        return tokens

    def run(self):
        raise NotImplementedError()

The resulting tokens can be seen with Script("ab123c-43=f54g6!6")._tokens.

I have a few questions about my method:

Is there any more Pythonic or elegant way to do this? (e.g, an alternative instead of regexing)
Should I really be using a static function like that, or should I move it outside the class?
If the loop is to be kept, should I be using enumerate instead?

for i,t in enumerate(tokens):
    if t.isdigit():
        tokens[i] = int(t)


texts: Optimizing program to output all numbers summing to 100

texts:
I just finished my program which calculates the solutions to this problem:

  Outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100.

Code in question:

package defaultpackage;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class Main {
    static int[] pos_counter = {0,0,0,0,0,0,0,0};

    static Boolean running = true;

    public static void main(String[] args) {
        int counter = 0;

        while(running) {
            increment();
            oobcheck();
            try {
                counter = (int) calculate(printeq());
            } catch (ScriptException e2) {
                e2.printStackTrace();
            }
            if(counter==100) {
                System.out.print(printeq());
                System.out.print("=");
                System.out.println(100);
            }
        }
    }

    public static int[] increment(){
        int stepcounter = 7;
        pos_counter[7]++;
        while(stepcounter>= 0&&running){

            if(pos_counter[stepcounter]==3&&running){
                if(stepcounter-1 == -1){
                    running = false;
                } else{
                    pos_counter[stepcounter-1]++;
                    pos_counter[stepcounter]=0;
                }
            }
            stepcounter--;
        }
        return pos_counter;
    }

    public static double calculate(String s) throws ScriptException{
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        return (double) engine.eval(s);
    }

    public static void readout() {
        int stepcounter = 0;
        while(stepcounter <= 7) {
            System.out.print(pos_counter[stepcounter]);
            stepcounter++;
        }
        System.out.println("");
    }

    public static String printeq() {
        int stepcounter = 0;
        String read = "";
        while(stepcounter <= 7) {
            read = "" + read + (stepcounter+1);
            if(pos_counter[stepcounter] == 0){
            }else if(pos_counter[stepcounter] == 1) {
                read = read + "+";
            }else if(pos_counter[stepcounter] == 2) {
                read = read + "-";
            }
            stepcounter++;
        }
        read = read + "9";
        return read;
    }

    public static void oobcheck(){
        int stepcounter = 0;
        Boolean checker = true;
        while(checker&&stepcounter <= 7) {
            if(pos_counter[stepcounter] == 2) {
                stepcounter++;
                checker = true;
            }else{
                checker = false;
            }
            if(stepcounter==7){
                if(pos_counter[7] == 2) {
                    running = false;
                }
            }
        }
    }
}

My program works fine and spits out all the answers correctly but I'm looking to improve it. I've seen solutions to similar problems and they mostly take up less space or seem more organized.

Concrete questions:

Where can I learn to improve code efficiency or organization?
What could be used specifically to make my code faster and more efficient?


texts:
I just finished studying immutable objects and their advantages so I thought I'd create one of my own. Here is my employee class that extends a person class. It is not mutable since I have getters to my mutable date objects.

package objects.objects;

import java.util.Date;

public class Person {

    private final String name;
    private final Date dateOfBirth;

    Person(String name,Date dateOfBirth){
        this.name=name;
        this.dateOfBirth=dateOfBirth;

    }
    public String getName() {
        return name;
    }
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
}

Employee Class:

package objects.objects;

import java.util.Date;

public final class Employee extends Person{

    private final String empolyeeID;
    private final Designation designation;
    private final double salary;
    private final Date dateOfJoining;

    public Employee(String Name,Date dateOfBirth,String employeeID,Designation designation,double salary,Date dateOfJoining)
    {
        super(Name,dateOfBirth);
        this.empolyeeID=employeeID;
        this.designation=designation;
        this.salary=salary;
        this.dateOfJoining=dateOfJoining;

    }

    public String getEmpolyeeID() {
        return empolyeeID;
    }

    public Designation getDesignation() {
        return designation;
    }

    public double getSalary() {
        return salary;
    }

    public Date getDateOfJoining() {
        return dateOfJoining;
    }
}

The designation enum:

package objects.objects;

public enum Designation {
    ASSOCIATE,SENIOR_ASSOCIATE,MANAGER,SENIOR_MANAGER,DIRECTOR
}

The Oracle Java documentation says:

  Don't share references to the mutable objects. Never store references
  to external, mutable objects passed to the constructor; if necessary,
  create copies, and store references to the copies. Similarly, create
  copies of your internal mutable objects when necessary to avoid
  returning the originals in your methods

Furthermore, the Oracle doc says:

  Don't allow subclasses to override methods. The simplest way to do
  this is to declare the class as final. A more sophisticated approach
  is to make the constructor private and construct instances in factory
  methods.

What if I want my class to be subclassed? What harm is there if I don't make my class final or have a private constructor?

Does it mean I shouldn't use getters or maybe pass a copy (a new Date object in the getter?) or is there some other approach that I am missing?

Also, could you point out apart from the date being mutable object references? Is there any other flaw in my code that violates the mutable policy or any other improvements as such?


texts:
Is the following functions implemented correctly for the set class?
Please let me know if any changes need to be made.

# Implementation of the Set ADT using a Python list.
class Set :
    # Creates an empty set instance.
    def __init__( self, *initElements ):
        self._theElements = list()
        for i in range(len(initElements)) :
            self._theElements.add( initElements )

   # Returns the number of items in the set.
   def __len__( self ):
       return len( self._theElements )

   # Determines if an element is in the set.
   def __contains__( self, element ):
       return element in self._theElements

   # Determines if the set is empty.
   def isEmpty( self ):
       return len(self._theElements) == 0

   # Adds a new unique element to the set.
   def add( self, element ):
       if element not in self :
           self._theElements.append( element )

   # Removes an element from the set.
   def remove( self, element ):
       assert element in self, "The element must be in the set."
       self._theElements.remove( element )

   # Determines if this set is equal to setB.
   def __eq__( self, setB ):
       if len( self ) != len( setB ) :
           return False
       else :
           return self.isSubsetOf( setB )

   # Determines if this set is a subset of setB.
   def isSubsetOf( self, setB ):
    for element in self :
        if element not in setB :
            return False
    return True

  # Determines if this set is a proper subset of setB.
  def isProperSubset( self, setB ):
    for element in self :
        if self != setB :
            return True
    return False

   # Creates a new set from the union of this set and setB.
   def union( self, setB ):
    newSet = Set()
    newSet._theElements.extend( self._theElements )
    for element in setB :
        if element not in self :
            newSet._theElements.append( element )
    return newSet

   # Creates a new set from the intersection: self set and setB.
   def intersect( self, setB ):
    newSet = Set()
    for i in range(self._theElements) :
        for j in range(setB._theElements) :
            if self._theElements[i] == setB._theElements[j] :
                self.theElements.append(setB)
    return newSet

# Creates a new set from the difference: self set and setB.
def difference( self, setB ):
    newSet = Set()
    newSet._theElements.extend( self._theElements )
    for element in setB :
        if element in self :
            newSet._theElements.remove( element )
    return newSet

 # Creates the iterator for the self
def __iter__( self ):
    return iter(self._theElements)


texts: Mutable named tuple with default value and conditional rounding support

texts:
I have following code to create a mutable namedtuple. based my understand I can use dataclass to do it. is there a better way to do it or clean up the code?

@dataclass
class Price:
    """
    This describes how to map default price value for product
    """
    profit: float = 0.5
    cost: float = 0.1
    sale: float = 25.0

    def round(self, n: float):
        if n < 1:
            return round(n, 2)
        elif n < 100:
            n = round(n / 1)
        elif n < 1000:
            n = round(n / 5) * 5
        elif n < 10000:
            n = round(n / 50) * 50
        else:
            n = round(n / 500) * 500
        return n

    def update(self, **kwargs):
        rate = kwargs.get('rate', 1)
        for k, v in asdict(self).items():
            if k != 'sale':
                v = self.round(v * rate)
            v = kwargs.get(k) or v
            setattr(self, k, float(v))

#run test
p = Price()
p.update(rate=1) #p = Price(profit=0.5, cost=0.1, sale=25.0)

p = Price()
p.update(**{sale=450}, **dict(rate=0.9073)) #p = Price(profit=0.45, cost=0.1, sale=450.0)

p = Price()
p.update(**{sale=800}, **dict(rate=301.377)) #p = Price(profit=150.0, cost=0.1, sale=800.0)

p = Price()
p.update(rate=301.377) #p = Price(profit=150.0, cost=0.1, sale=7550.0)

p = Price(0.0, 0.5, 50.0)
p.update(rate=1) #p = Price(profit=0.0, cost=0.5, sale=50.0)

p = Price(0.0, 0.5, 50.0)
p.update(**{sale=600}, **dict(rate=0.9073)) #p = Price(profit=0.0, cost=0.5, sale=600.0)

p = Price(0.0, 0.5, 50.0)
p.update(**{sale=1200}, **dict(rate=301.377)) #p = Price(profit=0.0, cost=0.5, sale=1200.0)

p = Price(0.0, 0.5, 50.0)
p.update(rate=301.377) #p = Price(profit=0.0, cost=0.5, sale=15000.0)


texts: Bash script that checks if font is installed and installs it if necessary

texts:
This checks if a font is installed by using fc-list and grep. If the particular font is not installed, it offers to install it for the user. This snippet is part of a larger script that installs a particular Conky configuration along with all of its dependencies with minimal effort from the user.

Concerns

I have to create the FONT_INSTALLED variable to avoid a "too many arguments" error by placing the code into the if statement, is there a better practice for handling this?
To check if the font is installed, I check if the FONT_INSTALLED variable is a null String or not. Is this considered good practice? I know in languages such as Java a String is normally checked for length/content since the default value is "".
I've seen that placing > /dev/null after a command that would normally have output hides the output. This seems slightly 'hacky' as I know commands such as wget have the -q or --quiet option to hide output. For commands that do not have such an option, what is the preferred method of hiding output?

I realize that I should not place semi-colons after each line as per the advice on my first question first question. I forgot to make the appropriate changes to this code snippet.

FONT_INSTALLED=$(fc-list | grep -i "roboto");
if [ -z "$FONT_INSTALLED" ]; then
    echo "The Roboto font is not currently installed, would you like to install it now? (Y/N)";
    read response
    if [[ "$response" == [yY] ]]; then
        echo "Installing the Roboto font to the ~/.fonts directory...";
        mkdir .fonts/Roboto/ -p && wget --quiet -O ~/.fonts/Roboto/tmp.zip http://www.fontsquirrel.com/fonts/download/roboto &&
        unzip ~/.fonts/Roboto/tmp.zip -d ~/.fonts/Roboto/ > /dev/null && rm ~/.fonts/Roboto/tmp.zip
        fc-cache -fv > /dev/null
        FONT_INSTALLED=$(fc-list | grep -i "roboto");
        if [ -n "$FONT_INSTALLED" ]; then
            echo "The Roboto font was sucessfully installed!";
        else
            echo "Something went wrong while trying to install the Roboto font.";
        fi
    else
        echo "Skipping the installation of the Roboto font...";
        echo "Please note that this Conky configuration will not work without the Roboto font.";
    fi
else
    echo "The Roboto font has already been installed.";
fi


texts:
I have to enable/disable multiple inputs when a select change. It works but I want to do it better. How can I improve my code?

$("#street_type").on("change", function(event){
    if( $(this).val() == 1){
        $("#clase_via").prop('disabled', true);
        $("#nombre_via").prop('disabled', true);
        $("#numero_via").prop('disabled', true);
        ...
        $("#indicaciones").prop('disabled', true);
    }
    if( $(this).val() == 2){
        $("#clase_via").prop('disabled', false);
        $("#nombre_via").prop('disabled', false);
        $("#numero_via").prop('disabled', false);
        ...
        $("#indicaciones").prop('disabled', false);
    }
});


texts:
Please review my program and give some tips . I am a beginner. IT is for those people who sit on computer all day and get unhealthy . This will remind them to do eye exercise , physical exercise and to drink water
import pygame
import time

t = time.ctime(time.time())
# noinspection SpellCheckingInspection
totalbreaks2 = 17
# noinspection SpellCheckingInspection
breakcount2 = 0
# noinspection SpellCheckingInspection
totalbreaks = 16
# noinspection SpellCheckingInspection
breakcount = 0
# noinspection SpellCheckingInspection
totalbreaks1 = 10
# noinspection SpellCheckingInspection
breakcount1 = 0

# noinspection SpellCheckingInspection
def health():
    # global keywords
    global breakcount2
    global breakcount
    global breakcount1
    global totalbreaks1
    global totalbreaks
    global totalbreaks2
    # water program
    if breakcount2 < totalbreaks2:
        pygame.mixer.init()
        pygame.mixer.music.load("water.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you drink water (type drank if yes)?')
        if query == 'drank':
            with open('water.txt', 'r+') as o:
                o.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(120)
            breakcount2 += 1
    # eye program
    if breakcount < totalbreaks:
        pygame.mixer.init()
        pygame.mixer.music.load("eyes.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you do eyes exercise ?(type eydone if yes)')
        if query == 'eydone':
            with open('water.txt', 'r+') as o1:
                o1.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(1080)
            breakcount += 1
    # exercise program
    if breakcount1 < totalbreaks1:
        pygame.mixer.init()
        pygame.mixer.music.load("physical.mp3.mp3")
        pygame.mixer.music.play(-1)
        query = input('Did you do physical exercise (type exdone if yes) ?:')
        if query == 'exdone':
            with open('water.txt', 'r+') as o2:
                o2.write(f'You drank water at {t} ')
            pygame.mixer.music.pause()
            time.sleep(2400)
            breakcount1 += 1
            health()

z = input('Do you want to start the program? (y=yes , n=no):')
if z == 'y':
    health()
elif z == 'n':
    print('ok')
else:
    print('type correct input')


texts: Mongoose schema to store items from Wynncraft's API

texts:
I am making a Schema to store items from Wynncraft's API.

See an example assortment of items here:

https://api.wynncraft.com/public_api.php?action=itemDB&search=a

I have not finished making the Schema because I want to know if there's a better way I should approach it:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

const ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  tier: {
    type: String,
    enum: ['Unique', 'Rare', 'Legendary', 'Mythic', 'Set', 'Normal'],
    required: true
  },
  identified: {
    type: Boolean,
    required: true
  },
  set: {
    type: String,
    required: true
  },
  sockets: {
    type: Number,
    required: true
  },
  accessoryType: {
    type: String,
    required: () => this.category == 'accessory'
  },
  material: {
    type: String
  },
  restrictions: {
    type: String
  },
  damage: {
    type: String
  },
  fireDamage: {
    type: String
  },
  waterDamage: {
    type: String
  },
  airDamage: {
    type: String
  },
  thunderDamage: {
    type: String
  },
  earthDamage: {
    type: String
  },
  attackSpeed: {
    type: String
  },
  type: {
    type: String
  },
  armorType: {
    type: String
  },
  armorColor: {
    type: String
  },
  addedLore: {
    type: String
  },
  dropType: {
    type: String
  },
  health: {
    type: Number
  },
  fireDefense: {
    type: Number
  },
  waterDefense: {
    type: Number
  },
  airDefense: {
    type: Number
  },
  thunderDefense: {
    type: Number
  },
  earthDefense: {
    type: Number
  },
  level: {
    type: Number
  },
  quest: {
    type: String
  },
  classRequirement: {
    type: String
  },
  strength: {
    type: Number
  },
  dexterity: {
    type: Number
  },
  intelligence: {
    type: Number
  },
  agility: {
    type: Number
  },
  defense: {
    type: Number
  },
  healthRegen: {
    type: Number
  },
  manaRegen: {
    type: Number
  },
  spellDamage: {
    type: Number
  },
  damageBonus: {
    type: Number
  },
  lifeSteal: {
    type: Number
  },
  manaSteal: {
    type: Number
  },
  xpBonus: {
    type: Number
  },
  lootBonus: {
    type: Number
  },
  reflection: {
    type: Number
  },
  strengthPoints: {
    type: Number
  },
  dexterityPoints: {
    type: Number
  },
  intelligencePoints: {
    type: Number
  },
  agilityPoints: {
    type: Number
  },
  defensePoints: {
    type: Number
  },
  thorns: {
    type: Number
  },
  exploding: {
    type: Number
  },
  speed: {
    type: Number
  },
  attackSpeedBonus: {
    type: Number
  },
  poison: {
    type: Number
  },
  healthBonus: {
    type: Number
  },
  soulPoints: {
    type: Number
  },
  emeraldStealing: {
    type: Number
  },
  healthRegenRaw: {
    type: Number
  },
  spellDamageRaw: {
    type: Number
  },
  damageBonusRaw: {
    type: Number
  },
  bonusFireDamage: {
    type: Number
  },
  bonusWaterDamage: {
    type: Number
  },
  bonusAirDamage: {
    type: Number
  },
  bonusThunderDamage: {
    type: Number
  },
  bonusEarthDamage: {
    type: Number
  },
  bonusFireDefense: {
    type: Number
  },
  bonusWaterDefense: {
    type: Number
  },
  bonusAirDefense: {
    type: Number
  },
  bonusEarthDefense: {
    type: Number
  },
  category: {
    type: String,
    enum: ['accessory', 'armor', 'weapon'],
    required: true
  },
  // flags will be added as items are moved from Wynncraft's official API
  // into my database. The official API is inconsistent, I will put problems here,
  // e.g. "item.sockets undefined, setting to 0" and things like this.
  flags: {
    type: [String],
    required: true
  }
});

ItemSchema.plugin(uniqueValidator);

module.exports = mongoose.model('Item', ItemSchema);

There's so much repetition and it's just so long, I wonder if this schema can be created in a less verbose way.


texts: Ruby array search, returning either a result with a good score or the last result

texts:
I have an array of hashes, each of which has two attributes: "title" and "Zscore". I want to return either the result of find or the last element. This can be done with:

a = array.select{|i| i["title"] == "some title"}
b = a.find{|i| i["Zscore"].to_f >= 5} || a.last

Is there an elegant way to put the conditional inside the block, something like the following?

array.select{|i| i["title"] == "some title"}.find{|i| i["Zscore"].to_f >= 5 || last}

Any built-in method? Any ideas of one-liner that is nicer than the following?

array.select{|i| i["title"] == "some title"}.find{|i| i["Zscore"].to_f >= 5} ||
array.select{|i| i["title"] == "some title"}.last


texts:
Please critique:

public void printTree(Node head) {
    if (head == null)
        return;
    Queue<Node> q1 = new PriorityQueue<Node>();
    Queue<Node> q2 = new PriorityQueue<Node>();

    q1.add(head);

    do {
        while (q1.size() > 0) {
            Node element = q1.poll();
            System.out.print(element.data + " ");
            if (element.left != null)
                q2.add(element.left);
            if (element.right != null)
                q2.add(element.right);
        }
        System.out.println();
        while (q2.size() > 0) {
            q1.add(q2.poll());
        }
        q2.clear();
    } while (q1.size() > 0);
}


texts: Accepting a positive integer from either a command-line argument or System.in

texts:
I've been doing a lot of programs for classes that require a prompt from the program. I thought it would be much faster for me to rapidly test inputs if I didn't have to execute the program and then type the input once inside the program (as opposed to just hitting ↑ and adjusting the input that way).

My concern is this code seems to have some duplication with the exception handling, and I'm also not sure if it's as efficient as it can be. I'm somewhat of a beginner, but I'm certainly interested in more advanced ideas/solutions as that would point in direction of where to self-study more.

import java.util.Scanner;

/*
 *  This program is to implement testing command line input or reverting to regular prompts if
 *  an argument isn't provided or is invalid. It tests to see if the input is a negative integer,
 *  and displays the result.
 *
 *  Algorithm:
 *  If the console argument is valid, treat it as user input, or otherwise ignore it
 *  Continue to ask for a positive integer until one is given.
 *  Display the integer given and confirm it's negative
 */
public class TestConsoleArgs
{
    public static void main( String[] args )
    {
        String arg;
        Scanner user_input = new Scanner(System.in);
        int num = 0;

        try {
            arg = args[0];
            num = Integer.parseInt(arg);
        } catch (ArrayIndexOutOfBoundsException e) {
            arg = "";
        } catch (NumberFormatException e2) {
            arg = "";
        }

        while (num <= 0)
        {
            System.out.print("Please type in a positive integer.  ");
            arg = user_input.next();

            try {
                num = Integer.parseInt(arg);
            } catch (NumberFormatException e) {
                System.out.print("That's not an integer! ");
                continue;
            }

            if (num <= 0)
            {
                System.out.print("That's a negative number. ");
            }
        }

        System.out.println("Yes, '" + num + "' is a positive integer.");
    }
}


texts:
So I came up with a problem In C. Our compiler is pre c99 and wasn't identifying functions that are never called. So I ended up writing this script and decided to post it up to be critiqued and to help people who might be in the same predicament. The script works great for me and finished the job that I needed it to do. I just felt that it could be done better.

from sys import exit
import re
import os ,fnmatch
#"(static BOOL|BOOL|static void|void)\s+([A-Z a-z]+)(\(.*?\)\;)"
pattern = "(static BOOL|BOOL|static void|void|static BYTE|BYTE|static int|int)\s+([A-Z a-z]+)(\(.*?\)\;)"

compiled = re.compile(pattern)
commentend = re.compile("\*/")
commentbegin = re.compile("/\*.*") #|\}/s/\*.* extra pattern
count = 0
directory =" "

def menu():#menu function
    global directory
    print "what would you like to do"
    print "1. Enter directory of .c and .h files you want searched"
    print "2. Display possibly unused functions" #not used
    print "Any other key exit program"

    selection = raw_input("> ")
    if selection == '1':#this menu starts the search process
        print "you selected search"
        print "what is the file name"
        directory = raw_input("> ")
        openfiles()
    elif selection == '2':#this selection is not currently used
        print "displaying matching functions"
        print count
    else:
        exit(0)

def openfiles(): #gets a list of file names and then passes the name to search for function to open
    for root,dirs,files in os.walk(directory):
        for pat in ['*.c','*.h']:
            for current_file in fnmatch.filter(files,pat):
                searchforfunction(current_file)

def searchforfunction(file_name):
    global directory
    print file_name
    with open(os.path.join(directory,file_name) ,"r" ,1) as f:
        for line in f:
            matchfun(line)

def matchfun(line): #This searches for a function looking for specific definition then checks how many times the function occurs
    global count
    name_func = compiled.match(line)
    if name_func:
        name_func = name_func.group(2)
        count = searchfilesecond(name_func)
        if count <= 2:
            print name_func," was called",count,"times"
        if count == 2:
            writefunc_twice(name_func)
        if count == 1:
            writefunc_one(name_func)
    count = 0

def writefunc_one(name_func):
    with open("occur_once_func.txt", "a") as myfile:
        myfile.write(name_func+" was called 1 time\n")

def writefunc_twice(name_func):
    with open("occur_twice_func.txt", "a") as myfile:
        myfile.write(name_func + " was called 2 times\n")

def searchfilesecond(name_func): #walks the directory again and searches for a match by passing it so secondsearch
    global count
    global directory
    for root,dirs,files in os.walk(directory):
        for pat in ['*.c','*.h']:
            for current_file in fnmatch.filter(files,pat):
                count = secondsearch(name_func,current_file)

    return count

def secondsearch(name_func,current_file): #this function searches for any instances of the function
    global count
    global directory
    in_comment = False
    secondpatern = re.compile(name_func)
    with open(os.path.join(directory,current_file) ,"r" ,1) as f:

        for line in f:
            if commentbegin.search(line):#This statement searches for the /* part of a comment
                in_comment = True
            if commentend.search(line):#This statement searches for the */ part of a comment
                in_comment = False
            elif in_comment == False:
                name_func1 = secondpatern.search(line)
                if name_func1:
                    count += 1
            else:
                pass
    return count

while(1):
    menu()


texts: Create a triangle arrow block dynamically

texts:
I wrote a function to create one of those CSS triangle blocks and insert it right after one of the already created blocks.

function createArrow() {
    var arrowDown = {
        parent: document.querySelector('.landingItem'),
        div: document.createElement('div'),
        initDiv: function() {
            this.div.classList.add('arrow-down');
            this.div.style.borderLeftWidth = parseInt(document.documentElement.clientWidth)/2 + 'px';
            this.div.style.borderRightWidth = parseInt(document.documentElement.clientWidth)/2 + 'px';
            this.parent.appendChild(this.div);
        },
        checkDiv: function () {
            if(this.parent.querySelector('.arrow-down')) {
                this.parent.removeChild(this.parent.querySelector('.arrow-down'));
            }
            this.initDiv();
        }

    };

    arrowDown.checkDiv();
}

createArrow();
window.addEventListener('resize', createArrow);
.arrow-down {
  margin-top: -2px;
  border-top: 60px solid #501a70;
  border-left: 160px solid transparent;
  border-right: 160px solid transparent;
}

What can I improve?


texts:
I want to make figures of a rectangle and a circle.  How can I make the code more elegant?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class r extends JPanel
{
      public int x1,x2,y1,y2;
      public static double SWITCH;
      public r()
      {
          setBackground(Color.WHITE);
          addMouseListener(new MouseAdapter()
          {
               public void mousePressed(MouseEvent m)
               {
               x1=m.getX();
               y1=m.getY();
               repaint();
               }
               public void mouseReleased(MouseEvent m)
               {
               x2=m.getX();
               y2=m.getY();
               repaint();
               }
          });
          addMouseMotionListener(new MouseMotionAdapter()
          {
              public void mouseDragged(MouseEvent m)
              {
                 x2=m.getX();
                 y2=m.getY();
                 repaint();
              }
          });
      }
      public void paintComponent(Graphics g)
      {
          super.paintComponent(g);
          if(SWITCH == 2)
          {
              g.drawRect(x1, y1, x2, y2);
          }
          else if (SWITCH == 3)
          {
              g.drawOval(x1,y1,x2,y2);
          }
          else
          {
              g.drawString("qwe", x1, y1);
          }
      }

  }
  public class q extends JFrame
  {
      public static void main(String[] args)
      {
          q window = new q();
          window.setVisible(true);
          window.setSize(1024, 800);
          window.setDefaultCloseOperation(EXIT_ON_CLOSE);
          Container cont = window.getContentPane();
          cont.setLayout(new GridLayout(2,2));
          r panel = new r();
          JPanel BPanel = new JPanel();
          cont.add(panel);
          cont.add(BPanel);
          BPanel.setBackground(Color.blue);
          JButton button1,button2;
          button1 = new JButton("Rect");
          button2 = new JButton("Oval");
          BPanel.add(button1);
          BPanel.add(button2);
          button1.addActionListener(new ActionListener() {

              public void actionPerformed(ActionEvent e)
              {
                  r.SWITCH = 2;
              }
          });
          button2.addActionListener(new ActionListener() {

              public void actionPerformed(ActionEvent e)
              {
                  r.SWITCH = 3;
              }
          });
      }
  }


texts:
Background

I am a total beginner in Haskell, so after reading the Starting out-chapter of "Learn you a Haskell", I wanted to create my first program that actually does something.

I decided to do the famous Caesar-Cipher.

Code

import Data.Char

encryptChar :: Char -> Int -> Int
encryptChar char shift = if ord char > 64 && ord char < 91    --Only encrypt A...Z
                           then (if ord char + shift > 90     --"Z" with shift 3 becomes "C" and not "]"
                                  then ord char + shift - 26
                                  else ord char + shift)
                         else ord char

decryptChar :: Char -> Int -> Int
decryptChar char shift = if ord char > 64 && ord char < 91
                            then (if ord char - shift < 65
                                   then ord char - shift + 26
                                   else ord char - shift)
                         else ord char

encrypt :: String -> Int -> String
encrypt string shift = [chr (encryptChar (toUpper x) shift) | x <- string]    --"Loop" through string to encrypt char by char

decrypt :: String -> Int -> String
decrypt string shift = [chr (decryptChar (toUpper x) shift) | x <- string]

main = print(decrypt "KHOOR, ZRUOG!" 3)

(The code does work as intended.)

Question(s)

How can this code be improved in general?
Do I follow the style guide of Haskell (indentation, etc.)?
I have a background in imperative languages. Did I do something that is untypical for functional programming languages?

I would appreciate any suggestions.


texts: Find and replace strings in the first column of data

texts:
Not a professional coder, but my current hospital position is allowing me to code some workarounds for our abysmal EHR system. The following is part of my Python project to visualize laboratory data.
The following code snippet works, but I haven't figured out a way with list comprehensions or np.where to streamline it and potentially improve performance. I haven't found any posts yet to answer this, including among those suggested during question submission.
This code tests tuple[0] in a list of tuples (test_and_value) comprising (lab test names, test values), searching for misspelled lab test names and replacing them with standardized lab test names.
Common misspellings and their replacement terms live in another list of tuples (chem_fix) to preserve the order in which they are checked. Some word fragments of misspellings are used in lieu of full words, therefore testing cannot be a simple == statement.
Final product is a list of tuples, test_and_value_f, with correctly spelled lab tests.
Pertinent code excerpts:
chem_fix = [('A/G RATIO', 'A:G RATIO'), ('ALK', 'ALKALINE PHOSPHATASE'), ('ALT', 'ALT'), ('AST', 'AST'), ('BILI', 'BILIRUBIN,TOTAL'), ('BLIL', 'BILIRUBIN,TOTAL'), ('BUN/CREAT', 'BUN/CREAT RATIO'), ('BUN', 'BLOOD UREA NITROGEN'), ('CARBON', 'CO2'), ('GLOB', 'GLOBULIN'), ('RANDOM', 'GLUCOSE'), ('PROTEIN', 'TOTAL PROTEIN')]
fix_terms = [x[0] for x in chem_fix]

test_and_value_f = []
replaced = False
for lab_test, value in test_and_value:
    for count, term_needing_fix in enumerate(fix_terms):
        if term_needing_fix in lab_test:
            test_and_value_f.append((chem_fix[count][1], value))
            replaced = True
            break
    if replaced == False:
        test_and_value_f.append((lab_test, value))
    else:
        replaced = False

Sample test_and_value input: [('GLUCOSE', '77'), ('BUN', '14'), ('CREATININE', '1.4'), ('CALCULATED BUN/CREAT', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CARBON DIOXIDE', '30'), ('CALCIUM', '8.9'), ('PROTEIN, TOTAL', '6.5'), ('ALBUMIN', '3.4'), ('CALCULATED GLOBIN', '3.1'), ('CALCULATED A/G RATIO', '1.1'), ('BILIRUBIN, TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('SGOT (AST)', '3')]
Sample test_and_value_f output: [('GLUCOSE', '77'), ('BLOOD UREA NITROGEN', '14'), ('CREATININE', '1.4'), ('BUN/CREAT RATIO', '10'), ('SODIUM', '142'), ('POTASSIUM', '3.7'), ('CHLORIDE', '100'), ('CO2', '30'), ('CALCIUM', '8.9'), ('TOTAL PROTEIN', '6.5'), ('ALBUMIN', '3.4'), ('GLOBULIN', '3.1'), ('A:G RATIO', '1.1'), ('BILIRUBIN,TOTAL', '0.7'), ('ALKALINE PHOSPHATASE', '59'), ('AST', '3')]
Is there a more efficient way to do this?


texts: Chaining a number of callables into a single function

texts:
How would you name this function (I gave in a name pipe in the example) which constructs combines a chain of functions with a single attribute into a single callable:

# Python
def pipe(*functions):
    """
    pipe(c, b, a)(value) == a(b(c(value)))
    """
    if len (functions) == 1:
        return functions[0]
    def chain(val):
        for func in functions:
            val = func(val)
        return val
    chain.func_name = '__'.join(repr(f) for f in functions)
    return chain


texts:
This is a small program to calculate the CRC for an STM32 program image, compatible with the CRC on the STM32 hardware. It's a word-wise CRC, and the bin file is encoded as a series of 32 bit little endian words.

This is my first serious attempt at Rust and I'm looking for general comments, as well as a few questions:

Is there a better way of writing the repetitive (buff[3] as u32) when building the word?
Where should the T: Read trait bounds go? Should they also go on WordIterator?

use std::fs::File;
use std::io::Read;

struct WordIterator<T> {
    rd: T
}

impl<T: Read> WordIterator<T> {
    fn new(f: T) -> WordIterator<T> {
        WordIterator {rd: f}
    }
}

impl<T: Read> Iterator for WordIterator<T> {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        let mut buf = [0 as u8; 4];
        match self.rd.read(&mut buf) {
            Ok(4) => {
                let v: u32 = (buf[3] as u32) << 24 |
                (buf[2] as u32) << 16 |
                (buf[1] as u32) << 8  |
                (buf[0] as u32) << 0;

                Some( v )
            },
            _ => {
                None
            }
        }
    }
}

struct CrcCalculator {
    lookup_table: [u32; 256]
}

impl CrcCalculator {
    fn new() -> CrcCalculator {
        let mut calc = CrcCalculator {lookup_table: [0; 256]};

        // Calculate the table:
        for v in 0..256 {
            let mut v2: u32 = v << 24;
            for _ in 0..8 {
                if 0 != v2 & 0x80000000 {
                    v2 = (v2 << 1) ^ 0x04C11DB7;
                }
                else {
                    v2 = v2 << 1;
                }
            }

            calc.lookup_table[v as usize] = v2;
        }

        calc
    }

    fn calculate<T: Read>(&self, f: T) -> (u32, u32) {
        let mut crc: u32 = 0xFFFFFFFF;
        let mut count = 0;

        for word in WordIterator::new(f) {
            crc = crc ^ word;
            crc = (crc << 8) ^ self.lookup_table[((crc >> 24) & 0xFF) as usize];
            crc = (crc << 8) ^ self.lookup_table[((crc >> 24) & 0xFF) as usize];
            crc = (crc << 8) ^ self.lookup_table[((crc >> 24) & 0xFF) as usize];
            crc = (crc << 8) ^ self.lookup_table[((crc >> 24) & 0xFF) as usize];

            count += 1;
        }

        (count, crc)
    }
}

fn main() {
    let lt = CrcCalculator::new();

    let f = File::open("Image.bin").unwrap();
    let (count, crc) = lt.calculate(f);

    println!("count=0x{:X} crc=0x{:08X}", count, crc);
}


texts: Clone array elements when multiplying by a scalar

texts:
I am building an array of strings to form the "empty" representation of a puzzle onto which I will overwrite single characters as necessary for debugging purposes. However, building the array using scalar multiplication results in shared string instances among the rows which breaks when I modify them.

> grid = [["... " * 3] * 3, ""].flatten * 3

This produces the desired output

> puts grid * "\n"

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... ... ...

But the array contains only two string instances: nine of "... ... ..." and two of "". To solve this I use map to clone each string:

grid = ([["... " * 3] * 3, ""].flatten * 3).map(&:clone)

Is there a better way?

The main question here is how best to make sure each array element is a separate string instance.


texts: Filtering vector of maps based on a blacklist

texts:
Given a vector of maps:

(def my-list
  [{:a 1 :b 2 :c 3}
    {:a 1 :b 5 :c 6}
    {:a 7 :b 8 :c 12}
    {:a 10 :b 11 :c 12}])

and a blacklist:

(def blacklist
  [{:a 1 :c 3}
    {:a 10 :c 12}])

the expected output is:

[{:a 1 :b 5 :c 6}
  {:a 7 :b 8 :c 12}]

I came up with:

(defn not-excluded?
  [blacklist item]
  (not-any? (fn [exclusion-item]
              (and (= (:a item) (:a exclusion-item))
                   (= (:c item) (:c exclusion-item))))
            blacklist))

(filter (partial not-excluded? blacklist) my-list)

but there is probably a more idiomatic Clojure way.


texts:
I have quickly wrote a Perl script to convert a mediawiki to a dokuwiki. I know there's an existing script to make that, but I would have a simpler usage code and some use of the API from mediawiki. It was also a good occassion to use pQuery module. I know I can improve some things and I'm going to make a generic command and use Moo and MooX::Options for the next version.  I may also write a parser to convert the syntax, but I did make a first version quickly and an easy script some can easily maintain for no Perl programmers.

I would like to know what you think about the code:

#!/usr/bin/env perl

use strict;
use warnings;

use IO::File;

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;

use MediaWiki::API;
use pQuery;
use Text::Unidecode;

sub generate_file_name {
    my $title  = shift;

    $title =~ s/\s/_/g;
    $title =~s/'/_/g;

    return unidecode($title) . '.txt';
}

sub set_content_file {
    my ( $file, $content ) = @_;

    my $fh = IO::File->new($file, "w");
    if ( defined($fh) ) {
        print $fh $content;

        undef $fh;
    }

    return;
}

sub mediawiki_login {
    my $mediawiki = MediaWiki::API->new({
        api_url => 'http://vim-fr.org/api.php'
    });

    $mediawiki->login({
        lgname     => 'login',
        lgpassword => 'mypassword'
    }) || die $mediawiki->{error}->{code} . ': ' . $mediawiki->{error}->{details};

    return $mediawiki;
}

my $mediawiki    = mediawiki_login();
my $all_articles = $mediawiki->list({
    action => 'query',
    list   => 'allpages'
});
my $user_agent = LWP::UserAgent->new();

foreach my $page (@{$all_articles}) {
    my $article = $mediawiki->get_page({
        title => $page->{title}
    });

    my $request   = POST 'http://johbuc6.coconia.net/mediawiki2dokuwiki.php', [ mediawiki => $article->{'*'} ];
    my $response  =  $user_agent->request($request);
    my $file      = generate_file_name($page->{title});

    print 'Export de la page ' . $page->{title} . " dans le fichier $file", "\n";

    pQuery($response->content)
        ->find('textarea[name=dokuwiki]')
        ->each(sub {
            my $count = shift;
            set_content_file($file, pQuery($_)->html());
        });
}

It was a long time ago when I did not use Perl my favorite language AND I'm going to use more. I hope it was not so bad.


texts:
I have written the following program in C# to display an ASCII pyramid.

public static void method1()
{
  int k;
  int kCond = 5;
  int i;
  int inc = 0;
  for (int p = 0; p <=5; p++)
  {
    for(k = 0; k <= kCond; k++)
    {
         Console.Write(" ");
    }
     kCond--;
     for(i=0; i<=inc; i++)
     {
        Console.Write("*")
     }
     inc +=2;
     Console.WriteLine();
  }
}

Output:

         *
        ***
       *****
      *******
     *********
    ***********

My question is, is this good code from a performance point of view, or not? How could I improve it?