texts: Avoid calling init method on each return method

texts:
I'm implementing a module system into one of mine ASP.NET MVC applications and I am currently writing a module helper which all the modules can use to get some basic information about itself.

I'm using the namespace of the caller to identify the module and search it up in the database and retrieve the information.

Now I want to make everything static, so I don't have to instantiate it each time.

   public static class ModuleHelper
{
     private static  ModuleInstallations _module;

     static ModuleHelper()
     {
         Init();
     }

    private static void Init()
    {
         var stackTrace = new StackTrace();
         MethodBase method = stackTrace.GetFrame(2).GetMethod();
         var calledNamespace = method.ReflectedType.Assembly.GetName().Name;

        if (_module == null || calledNamespace != _module.Namespace)
        {
            LoadModuleInfo(calledNamespace);
        }
    }

    private static void LoadModuleInfo(string moduleNamespace)
    {
        var moduleService = new ModulesService();
        _module = moduleService.GetByNameSpace(moduleNamespace);
    }

    public static string GetPathModule(this Controller controller, string pathFile)
    {
        Init();

        return string.Format("/Modules/{0}/{1}", _module.AreaName, pathFile);
    }

    public static string GetModuleAreaName(this Controller controller)
    {
        Init();

        return _module.AreaName;
    }

    public static int GetModuleId(this Controller controller)
    {
        Init();

        return _module.Id;
    }
}

The problem is that a previous module could get stored into the class and I have to check on each method if it's another module. If it's another module I have to retrieve the information of it.

What would be a good solution for this problem?


texts: Find the kth-to-last element of a singly linked list

texts:
I wrote this code for finding the \$k\$th-to-last element in a singly linked list.

class Node:
  def __init__(self, v = None, next = None):
    self.v = v
    self.next = next

a = Node("Australian Sheperd")
b = Node("Beagle")
c = Node("Cairne Terrier")
d = Node("Dobermann")
e = Node("English Mastiff")

a.next = b
b.next = c
c.next = d
d.next = e

count = 1

def kthToLastNode(k, root):
  global count
  if root.next:
    count = kthToLastNode(k, root.next)
  if count == k:
    print(root.v)
  return count + 1

For example:

>>> kthToLastNode(3,a)
Cairne Terrier
6

When called on a list with \$n\$ nodes, the code goes all the way through the list, recursing \$n\$ times, using \$\Theta(n)\$ stack space, and returning \$n\$ times. Is there a way to improve the space performance of the function?


texts:
I've written a simple JavaScript function based off some existing code that takes a specific UNIX time string (in the snippet: 1491685200). It shows an alert if the specified time is still in the future. When that date has passed, it shows the elapsed days, hours and minutes whenever the function is called in-page.

I'm don't have much JavaScript object experience so it works just fine as-is, but I think it can be optimized further before I migrate my other stuff over to ES6.

function ElapsedTime () {
  var nTotalDiff = Math.round((new Date()).getTime() / 1000) - 1491685200;
  if (nTotalDiff >= 0) {
    var oDiff = {};
    oDiff.days = Math.floor(nTotalDiff / 86400);
    nTotalDiff -= oDiff.days * 86400;
    oDiff.hours = Math.floor(nTotalDiff / 3600);
    nTotalDiff -= oDiff.hours * 3600;
    oDiff.minutes = Math.floor(nTotalDiff / 60);
    nTotalDiff -= oDiff.minutes * 60;
    oDiff.seconds = Math.floor(nTotalDiff);
    return oDiff;
  } else {
    alert('nTotalDiff still not >=0, so must be before the specified date');
  }
}

function TimePassed() {
  oDiff = ElapsedTime();
  if(oDiff) {
    alert(oDiff.days + 'd ' + oDiff.hours + 'h ' + oDiff.minutes + 'm ');
  }
}

//   document.getElementById('counter').addEventListener('click', TimePassed, false);


texts: Computing huge Fibonacci numbers in Java

texts:
I have this small Java program for computing particurly large Fibonacci numbers (10000th Fibonacci number is computed in about 220 milliseconds). The key idea here is to use lists of digits, which is exactly what is done in java.math.BigInteger, yet I wanted to implement a simple digit list addition on my own.

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static String fibonacci(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("n = " + n);
        }

        switch (n) {
            case 0:
                return "0";

            case 1:
                return "1";
        }

        List<Character> listA = new ArrayList<>();
        List<Character> listB = new ArrayList<>();

        listA.add('0');
        listB.add('1');

        boolean fromAtoB = true;

        for (int i = 0; i < n; ++i, fromAtoB = !fromAtoB) {
            if (fromAtoB) {
                add(listA, listB);
            } else {
                add(listB, listA);
            }
        }

        StringBuilder sb;

        if (fromAtoB) {
            // It looks like the result is in the listB. However, as the boolean
            // fromAtoB was flipped after the last add(list1, list2), the result
            // is actually in list A.
            sb = new StringBuilder(listA.size());

            // For efficiency, we grow the digit string such that the least
            // significant digits are in the lowest array positions. That way
            // we make sure that adding a new (most significant digit) always
            // runs in amortized constant time.
            for (int i = listA.size() - 1; i >= 0; --i) {
                sb.append(listA.get(i));
            }
        } else {
            // Result is in listB.
            sb = new StringBuilder(listB.size());

            for (int i = listB.size() - 1; i >= 0; --i) {
                sb.append(listB.get(i));
            }
        }

        return sb.toString();
    }

    // Adds the number represented by digit list 'from' to the number
    // represented by digit list 'to'.
    private static void add(List<Character> from, List<Character> to) {
        // The carry flag.
        boolean carry = false;

        if (to.size() < from.size()) {
            // Extend the target digit list so that it can accommodate most of
            // the digits of the sum of the two Fibonacci numbers.
            to.add('0');
        }

        for (int i = 0; i < from.size(); ++i) {
            int digit = charToInt(from.get(i)) +
                        charToInt(to.get(i)) +
                        (carry ? 1 : 0);

            if (digit > 9) {
                digit -= 10;
                carry = true;
            } else {
                carry = false;
            }

            to.set(i, intToChar(digit));
        }

        if (carry) {
            to.add('1');
        }
    }

    private static int charToInt(char c) {
        return (int)(c - '0');
    }

    private static char intToChar(int i) {
        return (char)(i + '0');
    }

    public static void main(String[] args) {
        Integer i = -1;

        if (args.length > 0) {
            try {
                i = Integer.parseInt(args[0]);
            } catch (NumberFormatException ex) {

            }
        }

        long startTime = System.currentTimeMillis();
        String number = fibonacci(i >= 0 ? i : 10);
        long endTime = System.currentTimeMillis();

        System.out.println(number);
        System.out.println((endTime - startTime) + " milliseconds.");
    }
}

So what do you think?


texts: Generating the largest decent number of given number of digits

texts:
The Sherlock and the Beast challenge from HackerRank asks to generate the following number with \$n\$ digits for \$T\$ test cases:

  A Decent Number has the following properties: its digits can only be 3's and/or 5's. The number of 3's it contains is divisible by 5. The number of 5's it contains is divisible by 3. If there are more than one such number, we pick the largest one.

My code may not be very optimal. Can you please point out which test cases it may fail, as I may have missed a few conditions? Any suggestions to optimize the code?

using namespace std;
#include<iostream>

int main() {
    int T;
    cin >> T;

    while (T >= 1) {
        int n, flag;
        cin >> n;
        int z = n;

        if(n%5==0){
            for(int r=1;r<=n;r++){
                cout<<"3";
            }cout<<"\n";
        }

        else if(n%5!=0){
        for (int i = 3; i <= n; i += 3) {
            if ((z - i) % 5 == 0) {
                flag = i;
                break;
            }
        }

        if (flag == 0|| (n-flag)%5!=0) {
            cout << "-1"<<"\n";
        }

        else {
            for (int x = 1; x <= flag; x++) {
                cout << "5";
            }
            for (int y = 1; y <= (n - flag); y++) {
                cout << "3";
            }
            cout<<"\n";
        }
        }
        T--;
    }
}


texts:
I'm currently working on my own game engine for learning purposes, so I've implemented the first iteration of an entity component system using Java 8.

For my approach, I decided to not use any entity class for the system as an entity only holds data and so there is no class required to list all the components itself. This also means that I've got a Component which holds the data and a System which can have access to multiple components (for example a movement system which required data from the position and velocity component).

My systems also have a render method available (thought render systems are the only one who uses them), because the frame rate is not the same as the ticks.

In my ExitSystem, the InputMultiplexer is just for testing purpose there.

How can I improve the code and mainly the system I've got?

The EntityManager:

public class EntityManager {

private ArrayList<Integer> entities = new ArrayList<>();
private ArrayList<ISystem> componentSystems = new ArrayList<>();

public void addEntity(int ID, ISystem... system) {
    this.entities.add(ID);
    this.componentSystems.addAll(Arrays.asList(system));
}

public void init() {
    for(ISystem system : this.componentSystems)
        system.init();
}

public void update() {
    for(ISystem system : this.componentSystems)
        system.update();
}

public void render() {
    for(ISystem system : this.componentSystems)
        system.render();
}

public void dispose() {
    for(ISystem system : this.componentSystems)
        system.dispose();
}

public int getEntity(int id) {
    return this.entities.get(id);
}
}

The IEntityComponent:

public interface IEntityComponent {

}

The ISystem:

public interface ISystem {

public void init();

public void update();

public void render();

public void dispose();

public IEntityComponent[] get();
}

The ExitData:

public class ExitData implements IEntityComponent {

public int exit = GLFW_KEY_ESCAPE;
public int action = GLFW_REPEAT;
}

The ExitSystem:

public class ExitSystem implements ISystem {

@Override
public void init() {
    InputMultiplexer.getInput().addComponent(new InputComponent.InputKeyComponent() {

        @Override
        public boolean onKeyPress(int key, int action) {
            if(key == ((ExitData)get()[0]).exit && action == ((ExitData)get()[0]).action)
                Game.windowShouldClose();
            return true;
        }
    });
}

@Override
public void update() {

}

@Override
public void render() {

}

@Override
public void dispose() {

}

@Override
public IEntityComponent[] get() {
    return new IEntityComponent[] {new ExitData()};
}
}


texts: Random permutation of int[] and ArrayList

texts:
I wrote a simple program using int[] and ArrayList<Integer> which aims to get a random permutation output between 1 to 10, where each number will not be repeated in each line of output (each line of output will have number 1 until 10 in a different order). Both classes work nicely with the desire output. Is there any other possible way to shorten my code?

Random arrays using brute force:

  3 5 2 9 7 8 10 1 4 6
  4 10 5 2 3 9 6 1 7 8
  7 9 1 10 3 8 5 4 2 6
  5 3 8 9 10 2 6 7 1 4
  8 5 9 7 10 6 4 2 1 3
  4 10 2 9 8 6 3 7 5 1
  8 9 10 2 5 4 6 7 3 1
  7 2 4 9 5 10 6 8 1 3
  9 2 8 1 10 7 6 4 5 3
  8 1 10 3 9 7 4 2 5 6

This is my BrutePermutationGenerator file:

import java.util.Random;

public class BrutePermutationGenerator
{

  public int[] getRandomPermutation()
  {
  Random rand = new Random();
  int[] array = new int[10];

  int r = 0;
  int count = 0;
  boolean fill;

  int low = 1;
  int high = 10;
  int range = high - low + 1;

  do
  {
    fill = true;
    r = rand.nextInt(10) + 1;

     for (int i = 0; i < array.length; i++)//loop for random number between 1 to 10
     {
        if (array[i] == r)
        {
           fill = false;
        }
     }

     if (fill == true)
     {
        array[count] = r;
        count++;
     }
   }
   while (count < 10);
      for (int i = 0; i < array.length; i++)//loop for element in array
      {
         System.out.print(array[i] + " ");
      }
   return array;
  }

public void nextPermutation()
 {
   for (int i = 0; i < 10; i++) //loop for permutation 10 times
   {
      getRandomPermutation();
      System.out.println();
   }
  }
}

This is my SmartPermutationGenerator file:

import java.util.ArrayList;
import java.util.Random;

public class SmartPermutationGenerator
{
   private int size;
   private Random rand = new Random();

   public SmartPermutationGenerator()
   {
      this.size = 10;
   }

   public ArrayList<Integer> getRandomPermutation()
   {
      ArrayList<Integer> unused = new ArrayList<>();

      for (int i = 0; i < size; i++) // loop for element in array
      {
         unused.add(i + 1);
      }

      ArrayList<Integer> perm = new ArrayList<>();

      for (int k = 0; k < size; k++)  //loop for random number between 1 to 10
     {
         int pos = rand.nextInt(unused.size());
         perm.add(unused.get(pos));
         unused.remove(pos);
     }

    return perm;
    }

public void nextPermutation()
{
   for(int i = 0; i < size; i++) //loop for permutation 10 times
   {
       for(Integer item : getRandomPermutation())
       {
           System.out.print(item + " ");
       }
    System.out.println();
   }
 }
}

This is my PermutationGeneratorViewer file:

public class PermutationGeneratorViewer
{
   public static void main(String[] args)
   {
      BrutePermutationGenerator brute = new BrutePermutationGenerator();
      SmartPermutationGenerator smart = new SmartPermutationGenerator();

      System.out.println("\n" + "Random arrays using Brute Force: ");
      brute.nextPermutation();

      System.out.println("\n" + "Random arrays using Smart Force: ");
      smart.nextPermutation();
   }
}


texts: Find common preamble of a list of strings

texts:
Think of a set of text lines starting with a common string, e.g. indented code.

my $preamble = reduce {
    my $len = min(length $a, length $b);
    --$len while substr($a, 0, $len) ne substr($b, 0, $len);
    return substr($a, 0, $len);
} @lines;

Note that after the first invocation chances are high that $a already has the final result.

I'm wondering if there is a better approach in comparing the two strings in the reduce block. The while loop does not seem to be the best approach. It's also less readable since it does not convey the intent of the code (find common preamble of $a and $b).

Update:
After feedback from amon here is an alternative:

my $preamble = reduce {
    my $len = min(length $a, length $b);
    my ($current_prefix, $string) = (substr($a, 0, $len), substr($b, 0, $len));

    while($current_prefix ne $string) {
        chop $current_prefix;
        chop $string;
    }

    return $current_prefix;
} @lines;

I think this is an improvement in both performance and readability.


texts:
I am working on a C++ project for solving a class of optimization problems. The project will be header-only, and for now, I would like to stay with C++11 (so, not fold-expressions).

To be able to support some basic logging functionality, I have started writing the below logger class. Any comment/feedback is welcome. However, I would like to ask specifically about your suggestions on how to restructure the code, if at all, to make it more efficient.

#ifndef LOGGER_HPP_
#define LOGGER_HPP_

#include <chrono>
#include <cstdint>
#include <type_traits>
#include <vector>

namespace utility {
namespace logger {

template <class float_t, bool log_x_v, bool log_g_v> struct logger_t {
  template <class InputIt1, class InputIt2>
  void operator()(const std::size_t k, const float_t fval, InputIt1 xbegin,
                  InputIt1 xend, InputIt2 gbegin, InputIt2 gend) {
    tend = std::chrono::high_resolution_clock::now();
    const auto telapsed =
        std::chrono::duration<float_t, std::chrono::milliseconds::period>(
            tend - tstart);
    iterations.push_back(k);
    times.push_back(telapsed.count());
    fvalues.push_back(fval);
    log_x(xbegin, xend, std::integral_constant<bool, log_x_v>{});
    log_g(gbegin, gend, std::integral_constant<bool, log_g_v>{});
    tstart = std::chrono::high_resolution_clock::now();
  }

private:
  template <class InputIt>
  void log_x(InputIt xbegin, InputIt xend, std::true_type) {
    xvalues.emplace_back(xbegin, xend);
  }
  template <class InputIt> void log_x(InputIt, InputIt, std::false_type) {}
  template <class InputIt>
  void log_g(InputIt gbegin, InputIt gend, std::true_type) {
    gvalues.emplace_back(gbegin, gend);
  }
  template <class InputIt> void log_g(InputIt, InputIt, std::false_type) {}

  std::vector<std::size_t> iterations;
  std::vector<float_t> times;
  std::vector<float_t> fvalues;
  std::vector<std::vector<float_t>> xvalues, gvalues;
  std::chrono::time_point<std::chrono::high_resolution_clock> tstart{
      std::chrono::high_resolution_clock::now()},
      tend;
};

template <class float_t> using value = logger_t<float_t, false, false>;
template <class float_t> using decision = logger_t<float_t, true, false>;
template <class float_t> using gradient = logger_t<float_t, false, true>;
template <class float_t> using full = logger_t<float_t, true, true>;

} // namespace logger
} // namespace utility

#endif

Basically, the class is not complete, yet. I will be adding iterator support, read/write csv/binary functionality and some locking mechanism, later on, to be able to support thread-safe logging of values inside the logger.

Specifically, what I would like to ask is if I need to have some level of abstraction to make the unused private member variables disappear. The tag dispatch on log_x and log_g member functions seem to be OK when it comes to optimizing out the empty function calls, I hope. But then, when there is no logging needed for x and g, private member variables xvalues and gvalues are redundant. Should I care about them, or should I leave it as is for the sake of maintainability and ease of reading the code?


texts: Simple shell script to backup to Amazon over iSCSI

texts:
The script works but I know that it can be improved. Please note that my scripting skills are very basic :) (as it can be seen in my Frankenstein script – I took bits and pieces of the code from different tutorials).

I would appreciated if someone could review this script and identify some major flaws.

Some other questions that I have:

After the backup is complete is it necessary/better to logout from the amazon and unmount the volume?
Is it better to check if the volume is mounted based on the UUID?

#!/bin/bash
##
## VARIABLES
##
BACKUP_FROM="/folder/"
BACKUP_TO="/folder/"
LOG_FILE="/var/log/backup.log"
SCSI="/sbin/iscsiadm"
VOL="ghrryhfd-56655565-456456-3453-dfhthjtrrgg"
##
## SCRIPT
##
# Check that the log file exists
if [ ! -e "$LOG_FILE" ]; then
    touch "$LOG_FILE"
fi

# Check if the volume is mounted if not login to amazon and mount
if mountpoint -q /mount_folder; then
echo "$(date "+%Y-%m-%d %k:%M:%S") - Volume mounted" >> "$LOG_FILE"
else
echo "$(date "+%Y-%m-%d %k:%M:%S") - Mounting!" >> "$LOG_FILE"
$SCSI --mode node --targetname abc.222-99.com.amazon:volume_name --portal 1.1.1.1:9999 --login
sleep 10
mount -U "$VOL" /mount_folder
sleep 8
fi

# Start entry in the log
echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync started." >> "$LOG_FILE"

# Start sync
if rsync -a -v "$BACKUP_FROM" "$BACKUP_TO" &>> "$LOG_FILE"; then
    echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync completed succesfully." >> "$LOG_FILE"
else
    echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: rsync-command failed." >> "$LOG_FILE"
    echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
    echo "" >> "$LOG_FILE"
    exit 1
fi

# End entry in the log
echo "" >> "$LOG_FILE"
exit 0


texts: Pythonic way to convert XML attribute to float, or else get None

texts:
My Python code is converting XML attributes in an ElementTree to appropriate values. How do I best convert a value in this dict to a float() if it exists, or else get None?

Best I have now is:

attr = etree_elem.attrib
self.radius = float(attr['radius']) if 'radius' in attr else None
...
if self.radius:
  # do stuff using radius

I dislike this because it's not DRY (repeats both 'radius' and attr). I had code like this:

self.radius = float(attr.get('radius', -1))
...
if self.radius >= 0:
  # do stuff using radius

But (a) that only works when I know that a particular attribute value is otherwise invalid, and (b) it's not as "clean" to me as using None to properly signify that no radius was passed.


texts: Is this a good way to handle Web API UriTemplates?

texts:
I want to be able to do /contacts/Matt%20Phillips and /contacts/1 and have both of them return a contact. The way I did that was to try and parse an int from the captured parameter and call the Id method instead of the byName method like so:

    [WebGet(UriTemplate="{param}"]
    public Contact SingleParam(string param)
    {
        int x;
        if (int.TryParse(param, out x))
        {
            return GetContactById(x);
        }
        else
        {
            return GetContactByName(param);
        }
    }

    private Contact GetContactByName(string param)
    {
        var contact = from c in contacts
                      where c.Name.Equals(param)
                      select c;
        if (!contact.Any())
        {
            return null;
        }
        return contact.Single();
    }

    public Contact GetContactById(int id)
    {
        var contact = from c in contacts
                      where c.ContactId == id
                      select c;
        if (!contact.Any())
        {
            return null;
        }
        return contact.Single();
    }

But it seems clunky to me. Anyone have suggestions for a better way to do this?


texts:
I have the following 'custom' tree data structure.  This concept was to be thought of as, if given ("abb", 20) and ("abc", 30), then

Tree['a']['b']['b'] == 20

Tree['a']['b']['c'] == 30

Or

a
 \
  b
 / \
b   c

With b == 30, and c == 20.

Therefore taking up very limited space, and a very fast search.
However, as depth increases, the number of bytes for a fully explored tree was exponential. In the above case, 4 * 256 bytes were required for valid indexing to occur.  This was not good.

It now works in the following way; for each branch, compare its value against the n character; i.e. introducing a worst case O(256) character comparison for each depth. This is not ideal, and what I want to attempt to change.

The other question was (and still is), what is it? I couldn't quite classify it as anything but a Tree; nor relate it to any std:: containers for comparison. It is very good at what it does though, out-performing a std::map with small strings and very large strings (sizes ~20, ~500 respectively); past 600, the data structure begins to get too heavy.

Obviously, this code is a bit sketchy in how it handles the templates at the moment.  A number of things could go wrong, but my interest (other than classification) is on improving this data structure.

template <class K, class V>
class Tree {
    unsigned int depth;
    Tree* parent;

    std::vector<Tree> branches;
public:
    K key;
    V val;

    int n_trees;
    Tree(K key = 0, int depth = 0, Tree* parent = 0) : depth(depth), parent(parent), key(key) {
        val = 0;
        n_trees = 0;
        inc();
    }

    void inc() {
        if (parent) parent->inc();
        n_trees++;
    }

    void add(const K* search, const unsigned int length, const V value) {
        const int index = search[depth];

        if (length <= depth) {
            val = value;
            return;
        }

        for (unsigned int i = 0; i < branches.size(); ++i) {
            if (branches[i].key == index) {
                branches[i].add(search, length, value);
                return;
            }
        }
        branches.push_back(
            Tree(index, depth + 1, this)
        );
        branches.back().add(search, length, value);
    }
    V find(const K* search, const unsigned int length) {
        const int index = search[depth];

        if (length <= depth) {
            return val;
        }

        for (unsigned int i = 0; i < branches.size(); ++i) {
            if (branches[i].key == index) {
                return branches[i].find(search,length);
            }
        }
        return 0; // won't work for all types lol
    }
};


texts: The Login Authentication Model Class for ApiController

texts:
This class accepts input parameters (Login and Password) from ApiController via POST method, and do the following:

Trims the white spaces.
Checks for not null and Not Empty.
Checks the length of the input string to ensure it hasn't exceeded (only if the item 2 exceeds).

But, I think the class is violating the DRY Principle.

using FluentValidation;
using FluentValidation.Attributes;

namespace BusinessService.Auth.Models
{
    [Validator(typeof(AuthModelValidator))]
    public sealed class AuthPostModel
    {
        string _username;
        public string Username
        {
            get { return _username; }
            set { _username = value.Trim(); }
        }

        string _password;
        public string Password
        {
            get { return _password; }
            set { _password = value.Trim(); }
        }
    }
    class AuthModelValidator : AbstractValidator<AuthPostModel>
    {
        public AuthModelValidator()
        {
            RuleFor(x => x.Username).NotEmpty();
            RuleFor(x => x.Username).Length(1, 256)
                .When(x => !string.IsNullOrEmpty(x.Username));

            RuleFor(x => x.Password).NotEmpty();
            RuleFor(x => x.Password).Length(1, 32)
                .When(x => !string.IsNullOrEmpty(x.Password));
        }
    }
}


texts: Calculator with multiple inputs to add up

texts:
Can someone look over my code and clean it up?
I am trying to make a calculator with multiple inputs to add up. This is a snippet of the code that just needs to be cleaned up and shortened and I am relatively new to python so if anyone wants to clean this up thank you.
#functions
def x():
    #needed for the the loop later
    x.x = int(input("Type how many numbers you would like to add up: "))
    x.xCON = int(input("Please confirm by typing the same number: "))

#welcome to the code
print("Would you like to add up lots of numbers?")
print("If so you came to the right place")

#neaten up
print("________________________________________________")

#run function
x()

#cheack if the numbers are the same if not they have to retype them
if x.x == x.xCON:
    #neaten up
    print("____________________________________")
    #setting veriables for the loops and the list of the numbers
    i = 0
    nums = []
    #while i is not = to the input number(x.x) do the loop
    while i != x.x:
        #asks for the numbers to be added up
        INTnum = float(input("Write the numbers to be added up: "))
        #adds the numbers to the list
        nums.append(INTnum)
        #updates the veriable cheacking how many times the code has been ran
        i+=1
    #creating new veriables for the next loop
    index = 0
    ans = 0
    #while indxex is not = to the amount to numbers in the list run the code
    while index != len(nums):
        #veriable nums is now set as the lists index of the veriable index
        num = nums[index]
        #the ans veriable is eqal to itself + the number that was recorded from the idex
        ans = ans + num
        #moves the number along one everytime the code is run
        index+=1
    #gives the rueult of the sum
    print("\nThe sum of the numbers is", ans)
    #neaten up
    print("____________________________________________________")

#what happens if the numbers are not the same sending the bacn to the x() function
else:
    print("The numbers were not the same.")
    x()

#end of the code
print("\nThank you for using the calculator")


texts:
I am dealing constantly with the following code.

The thing is that literally it makes no sense for me to have all the spacing and divisions in the if-else when the code is so small that can be a block by itself.

When I read a line within line breaks I expect something difficult to understand or something that should be paid special care to be read about. Not just a line break after each function or if definition by default.

if (branchInfo.name === BRANCHNAMES.MASTER) {

    branchInfo.isMaster = true;

} else if (
    branchInfo.name === BRANCHNAMES.RELEASE ||
    branchInfo.name === BRANCHNAMES.HOTFIX
) {

    branchInfo.isDev = true;

}

Given that the line doesn't exceed the 120 characters and that they are small truthy statements that don't deserve to get a function, I want to remove that unnecessary split in the else if because it doesn't seem necessary, almost like the other line breaks and in my opinion it just leads into weird code.

if (branchInfo.name === BRANCHNAMES.MASTER) {
    branchInfo.isMaster = true;
} else if (branchInfo.name === BRANCHNAMES.RELEASE || branchInfo.name === BRANCHNAMES.HOTFIX) {
    branchInfo.isDev = true;
}

Am I being over paranoid about it? Is this actually a good practice?

PS: I know a good practice is to keep into a coding style and always keep it as it is, but really, I can't stand some things that just make code look weird. Sometimes too many line breaks also lead into unreadable code, don't you think so?


texts:
$('pre').each(function(index) {
    var c = $(this).attr("class");
    if (!c) {
        return true;
    }
    // Match only Javascript code snippets
    if (!c.match(/brush: js; class-name: 'jsbox'/)) {
        return true;
    }
    var code = $(this).text();
    $(this).after($("<button>Run example</button>").click(function() {
        run(code);
    }));

I noticed if I didn't have if (!c) { then the loop could abrubtly halt if it found a <pre> element without a class.

I wonder how to write this more succinctly. I'm also wondering about my matching options, since I've noticed different ways people match / compare strings in Javascript and I wondered what was "de rigueur".


texts:
I am currently using this code, but I am pretty sure there is a better way of doing it:

private string ReturnEmployeeName(string userName)
{
    try
    {
        // Username coming is     RandomDomain\RandomLengthUsername.whatever
        string[] sAMAccountName = userName.Split('\\');
        return sAMAccountName[1];

How can I make this faster?  I am not sure if my try block will catch any exceptions that may arise because of this line.


texts: Python program that takes input and runs queries on a mySQL database on it

texts:
I've been slowly learning Python so I want to know what the most Python-esque way of doing things are.

The scenario is that I'm connected to a database with a Customer and a SalesRep table in a database called sports2000. I also have a flat file containing a list of customer id's and salesrep names. My end goal is to update these customers to have these corresponding salesreps assigned to them. I want to do three things:

Display information about all the customers in this list.
Display information about the customers in the list in Massachusetts.
Update the customers to have their new sales representatives.

Any ideas or better ways to make this code more Python-esque would be great as I'm trying to write code that looks like it was written by a competent Python developer.

import MySQLdb as mdb

class PrimeCustomer:
    id = 0
    newRep = ""

with open('input.txt', 'r') as f:
    lines = f.readlines()

primeCustomers = []

for line in lines:
    words = line.split()

    tt = PrimeCustomer()

    tt.id = int(words[0])
    tt.newRep = words[1]

    primeCustomers.append(tt)

try:
    db = mdb.connect('localhost', 'root', '', 'sports2000')
    cur = db.cursor()

    # Create a string to use for the SQL IN operator
    customerNumbers = '('
    for prime in primeCustomers:
        customerNumbers += str(prime.id)
        customerNumbers += ', '

    # Remove the trailing comma and space and add ending parenthesis
    customerNumbers = customerNumbers[:-2]
    customerNumbers += ')'

    cur.execute("SELECT Name, custNum from customers where custNum in {}".format(customerNumbers))

    row = cur.fetchone()
    while row is not None:
        print ", ".join([str(c) for c in row])
        row = cur.fetchone()

    # Get a list of all the new salesReps for Massachusetts customers
    cur.execute("SELECT Name, custNum from customers where State = 'MA'")

    row = cur.fetchone()
    while row is not None:
        for prime in primeCustomers:
            if row[1] == prime.id:
                print row[0], prime.newRep

        row = cur.fetchone()

    # Go through each customer and assign them the sales rep
    # with the given name
    for prime in primeCustomers:
        cur.execute("UPDATE customer " +  \
                    "SET salesRep = " + \
                    "(SELECT salesRep FROM SalesRep WHERE repName = '{}' LIMIT 1) ".format(prime.newRep) + \
                    "WHERE customerNumber = {}".format(prime.id))

    db.commit()
except Exception as e:
    db.rollback()
    print e
finally:
    if cur:
        cur.close()
    if db:
        db.close()


texts: Modifying database using POSTed variables in PHP

texts:
I am writing PHP code to update a database, but this code is extremely repetitive and thus error prone. I am effectively typing the variable names six times each! Can this be improved without loosing functionality? I am certain there must be better way!

First, the definition of the demandArrayValue function:

function demandArrayValue($array, $key) {
  $value = isset($array[$key]) ? $array[$key] : null;
  if (is_null($value)) {
    throw new Exception("Failed to get value for '".$key."'.");
  }
  return $value;
}

Next an example of my extremely repetitive code:

try{
  if ($_POST) {
    $var1 = demandArrayValue($_POST, "Var1");
    $var2 = demandArrayValue($_POST, "Var2");
    $var3 = demandArrayValue($_POST, "Var3");
    [ ... and so on. ]

    $query = "UPDATE Table SET Var1 = :var1, Var2 = :var2, Var3 = :var3, [...] WHERE VarX = :varX";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':var1', $Var1);
    $stmt->bindParam(':var2', $Var2);
    $stmt->bindParam(':var3', $Var3);
    [ ... and so on. ]
    $stmt->execute();
  }
}
catch [ ... ]

Can a better PHP programmer than I am help me out please? Many many thanks in advance!

Disclaimer: I asked this same question on stackoverflow and was pointed to this site as a potentially better location.  I have no idea how you move a question from one site to another, so I am sorry to duplicate this.


texts:
I have view and it works correct, but very slow

class Reading(models.Model):
    meter = models.ForeignKey(Meter, verbose_name=_('meter'))
    reading = models.FloatField(verbose_name=_('reading'))
    code = models.ForeignKey(ReadingCode, verbose_name=_('code'))
    date = models.DateTimeField(verbose_name=_('date'))

    class Meta:
        get_latest_by = 'date'
        ordering = ['-date', ]

    def __unicode__(self):
        return u'%s' % (self.date,)

    @property
    def consumption(self):
        try:
            end = self.get_next_by_date(code=self.code, meter=self.meter)
            return (end.reading - self.reading) / (end.date - self.date).days
        except:
            return 0.0

    @property
    def middle_consumption(self):
        data = []
        current_year = self.date.year
        for year in range(current_year - 3, current_year):
            date = datetime.date(year, self.date.month, self.date.day)
            try:
                data.append(Reading.objects.get(
                    date = date,
                    meter = self.meter,
                    code = self.code
                ).consumption)
            except:
                data.append(0.0)
            for i in data:
                if not i:
                    data.pop(0)
        return sum(data) / len(data)

class DataForDayChart(TemplateView):
    def get(self, request, *args, **kwargs):
        output = []
        meter = Meter.objects.get(slug=kwargs['slug'])
        # TODO: Make it faster
        for reading in meter.readings_for_period().order_by('date'):
            output.append({
                "label": reading.date.strftime("%d.%m.%Y"),
                "reading": reading.reading,
                "value": reading.consumption / 1000,
                "middle": reading.middle_consumption / 1000
            })
        return HttpResponse(output, mimetype='application/json')

What should I change to make it faster?


texts:
I have a java component that was using a lot of string literals that I need to make comparisons on and return booleans based on these comparisons.

In order to make the code more robust I externalized these strings first as class constants, then after other classes started to use these constants I had to separate them to decrease the dependency between the classes.

Knowing that the best practice is not to use variable-classes dedicated for string for many reasons, and since I am using Java 6, I decided to go for enums. below is the implementation that I had in mind

public enum SecurityClassification {
    SENSITIVE("Sensitive"), HIGHLY_SENSITIVE("Highly Sensitive"), PUBLIC("Public"), INTERNAL("Internal");

    private String value;

    private SecurityClassification(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public boolean hasValue(String param) {
        return value.equalsIgnoreCase(param);
    }

    public static SecurityClassification enumForValue(String param){
        for (SecurityClassification securityClassification : SecurityClassification.values()) {
            if(securityClassification.getValue().equals(param)){
                return securityClassification;
            }
        }
        return null;
    }
}

I was wondering specifically about the enumForValue method, is this an optimal solution? is there any other better way?


texts: User model with validation, delegates, and carrierwave upload mounter

texts:
I've refactored this model about 50 times according to codeclimate, trying to get the code smell down. With all of the associations, I feel like this is as bare bones as I can get it while still keeping the necessary associations. I wanted to throw it up on here and see what people thought or if anyone had any suggestions on what I could do differently. It's pretty basic, has some custom validators for email and passwords, delegates, carrierwave upload mounter and some concerns included.

class User < ActiveRecord::Base
  self.table_name = "users_standard"

  include Scopeable::Clientable, Searchable, Auditable
  attr_accessor :password, :password_confirmation

  belongs_to :role
  has_many :discussion_posts, dependent: :destroy
  has_many :passtokens
  has_many :attendees
  has_many :authorized_ipads
  has_many :bookjobs
  with_options foreign_key: "user_id" do |user|
    user.has_and_belongs_to_many :questions,    join_table: "questions_users"
    user.has_and_belongs_to_many :chatposts,    join_table: "chatusers"
    user.has_and_belongs_to_many :permissions,  join_table: "permissions_users"
    user.has_and_belongs_to_many :committees,   join_table: "committees_users"
    user.has_and_belongs_to_many :bookfolders,  join_table: "bookfolders_users"
    user.has_and_belongs_to_many :efolders,     join_table: "efolders_users"
    user.has_and_belongs_to_many :surveys,      join_table: "surveys_users"
    user.has_and_belongs_to_many :tasks,        join_table: "tasks_users"
  end

  with_options uniqueness: { scope: :client_id } do |user|
    user.validates :email, email: true, allow_blank: true
    user.validates :companyemail, email: true, allow_blank: true
    user.validates :login, presence: true
  end
  validates :firstname, :lastname, presence: true
  validates :password, presence: true, confirmation: { message: "does not match" }, password: true, allow_blank: true

  before_save do |u|
    if u.password.present?
      self.password_hash = SecurePasswordService.new(self.password).secure
      self.p2            = true
    end
  end

  accepts_nested_attributes_for :permissions, allow_destroy: true

  delegate :title, :hostname, :forge_email_sender, :email_from, :email_new_account, :profile_update_email, :remove_email_footer, :disclaimer, :disclaimer_expiration_period, :password_change_days, :ftlogin, :user_lockout, to: :client, prefix: true

  mount_uploader :photo, UserPhotoUploader

  def self.active
    where('active = 1 and (system = 0 or system is null) and global_spawn != 1').order('lastname asc')
  end

  def self.private_directory_list(user)
    joins(:committees).where('committees.id in (?)', user.committees.map(&:id))
  end

  def endpoint_safe
    { user: self.attributes.with_indifferent_access.except!(:client_id) }
  end

  def is_committee_member?(committee)
    (committee.is_a?(Committee) && self.committees.include?(committee)) or (!committee.is_a?(Committee) && committee.map{ |c| self.committees.include?(c) })
  end
end


texts:
I need my string-to-int converter to handle all exceptions without throwing any errors. I also have a use case where I need the default value to be less than zero if the TryParse is false.

Is there a built-in way of doing this?
Should I make any changes to the method?

public int ToInt32OrDefault(string value, int defaultValue = 0)
{
    int result;
    if (Int32.TryParse(value, out result) == false)
        result = defaultValue;

    return result;
}


texts: Find the smallest regular number that is not less than N (Python)

texts:
This is from an answer to my own StackOverflow question on how to efficiently find a regular number that is greater than or equal to a given value.

I originally implemented this in C# but translated it to Python because I guessed (correctly) that it would be shorter and would eliminate a third-party library dependency.

I am a Python newbie though - This is the longest Python program I have ever written.  So I would like to know:

Is there a convention for indicating what version of the language you are targeting (like require <version> in perl?)  This program only works in 2.6.
Instead of the priority queue, is there a better way to generate the odd regular numbers?  I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?
Any other idioms/naming conventions I am missing?

from itertools import ifilter, takewhile
from Queue import PriorityQueue

def nextPowerOf2(n):
    p = max(1, n)
    while p != (p & -p):
        p += p & -p
    return p

# Generate multiples of powers of 3, 5
def oddRegulars():
    q = PriorityQueue()
    q.put(1)
    prev = None
    while not q.empty():
        n = q.get()
        if n != prev:
            prev = n
            yield n
            if n % 3 == 0:
                q.put(n // 3 * 5)
            q.put(n * 3)

# Generate regular numbers with the same number of bits as n
def regularsCloseTo(n):
    p = nextPowerOf2(n)
    numBits = len(bin(n))
    for i in takewhile(lambda x: x <= p, oddRegulars()):
        yield i << max(0, numBits - len(bin(i)))

def nextRegular(n):
    bigEnough = ifilter(lambda x: x >= n, regularsCloseTo(n))
    return min(bigEnough)


texts: FFmpeg command line for showing two videos side by side

texts:
Here is command line for playing two videos side by side in sync in FFmpeg (ffplay). It can be useful for comaring videos, for example.

ffplay -v warning -f rawvideo -s 800x400 -i /dev/zero -vf 'movie=video1.mkv,scale=400x400 [mv2] ; movie=video2.mkv,scale=400x400 [mv1]; [in][mv1] overlay=0:0 [tmp]; [tmp][mv2] overlay=400:0'

Is there some better way, in particular:

Without using fake video input;
More easily extendible, without inventing names for [tmp];
Maybe with automatic geometry calculation, without manual coordinates;
Input video filenames should be more easily visible and together?


texts:
This is a basic spell checking program that I wrote earlier today. It accomplishes the tasks that I had in mind, but was curious about improving my coding style and improving efficiency of my program. Any advice is appreciated. I have read through the PEP-8 style guide and some others as background information. The hard-coded wordlist.txt is a text file containing some 60 odd thousand English words that are spelled correctly.

#---------------------------------------------------------
# The "spellCheck" function determines whether the input
# from the inputFile is a correctly spelled word, and if not
# it will return the word and later be written to a file
# containing misspelled words
#---------------------------------------------------------
def spell_check(word, english):
    if word in english:
        return None
    else:
        return word

#---------------------------------------------------------
# The main function will include all of the code that will
# perform actions that are not contained within our other
# functions, and will generally call on those other functions
# to perform required tasks
#---------------------------------------------------------
def main():
    # Grabbing user input
    inputFile = input('Enter the name of the file to input from: ')
    outputFile = input('Enter the name of the file to output to: ')
    english = {}  # Will contain all available correctly spelled words.
    wrong = []  # Will contain all incorrectly spelled words.
    num = 0  # Used for line counter.

    # Opening, Closing, and adding words to spell check dictionary
    with open('wordlist.txt', 'r') as c:
        for line in c:
            (key) = line.strip()
            english[key] = ''

    # Opening, Closing, Checking words, and adding wrong ones to wrong list
    with open(inputFile, 'r') as i:
        for line in i:
            line = line.strip()
            fun = spell_check(line, english)
            if fun is not None:
                wrong.append(fun)

    # Opening, Closing, and Writing to output file
    with open(outputFile, 'w') as o:
        for i in wrong:
            o.write('%d %s\n' % (num, i))
            num += 1

main()


texts:
I am creating what strives to be a truly random number generator. As of right now, the implementation uses a mix of mainly nonsense system data and some pseudo-random numbers to generate numbers that are different and use the last half of the number (which, statistically, I believe is sufficiently random). The advice I would like:

Obviously, a general "review", as always.
How can I optimize this code to be faster? Currently, generating ten 1000 digit numbers takes two seconds, ten 10000 digit numbers takes 35-37 seconds, and ten 100000 digit numbers is exponentially slower.
How practical is this? Currently the generator uses some methods which may be considered "hacky"; ergo, using the last half of a number, or including pseudo-random numbers in the algorithm. Is this OK? I believe it should be, as long as the numbers generated are indeed random, but I would like other's opinions on this.

Another thing to note is that when testing some sample batches with this online tester, I got p-values around 0.24, which I believe is the optimal range. If you answer, don't feel pressured to answer all three questions.

import os, re, time, random
from functools import reduce

def rand_num(digits=3):
  nums = []
  strs = []
  rand = []
  add = True
  all_info = re.sub('(.*?: *)','',os.popen("cat /proc/meminfo").read()).replace('kB','').splitlines()+list(filter(None,re.findall(r'(\w*)',os.popen('ps').read())))
  all_info = list(x.strip() for x in all_info)
  nums.append(random.sample(range(digits*70), digits*35))
  nums = nums[0]
  for x in all_info:
    if x.isdigit():
      nums.append(int(x))
    else:
      strs.append(x)
  jugglenum = 0
  for x in nums:
    if add == True:
      jugglenum += x
      add = False
    else:
      jugglenum -= x
      add = True
  jugglenum = abs(jugglenum)
  for i in range(digits):
    rand.append(int(time.time()*(os.getpid()%jugglenum)))
  for i, x in enumerate(rand):
    rand[i] = ''.join(random.sample(str(x), len(str(x))))
  rand = [int(x)//10 for x in rand]
  largenum = str(reduce(lambda x, y: x*y, rand))[:digits]
  return ''.join(random.sample(random.sample(largenum,len(largenum)),len(largenum)))

An executable program on repl.it.

Yes, I know, this is similar to random.SystemRandom or os.urandom. This program I am developing now is really my first look into this concept and I don't plan for this to be my final program by any means. This is just something that I thought I would play around with for the time being.

So before you go and tell me that this is pointless and could have no application, I know. This is just my own personal experiment so I can get better at this sort of program.


texts:
Trying to return the below values from an RSS feed. I have sorted out the RSS feed side of things but I am not sure if what I am doing is the best way to extract the data that I need.  I have looked at beautifulsoup and regex's, re.search but not sure what is the best way to do this.

Values that I need; (both of these values change daily obviously)

4 Nov 2013

LOW-MODERATE

This is the cut down version of the full body of text that has the data i need to get from rss feed;

Fire Danger Ratings
Bureau of Meteorology forecast issued at: Mon, 4 Nov 2013 05:30 AM

Central: LOW-MODERATE

My code to extract the rss feed and data at the moment;

import feedparser #https://wiki.python.org/moin/RssLibraries

cfa_rss_url = "http://www.cfa.vic.gov.au/restrictions/central-firedistrict_rss.xml"

d = feedparser.parse( cfa_rss_url )

#get the data from the first item only, as it is only updated daily.
data = d.entries[0].description
print (data)
print('---------')

getdate = re.compile('forecast issued at: (.*?)
')
getrating = re.compile('
Central: (.*?)
')

m = getdate.search(data)
n = getrating.search(data)

print(m.group(1))
print(n.group(1))

This is the FULL data that is returned;

Total Fire Ban Status
Today, Mon, 4 Nov 2013 is not currently a day of Total Fire Ban in the Central (includes Melbourne and Geelong) fire district.

Fire Danger Ratings
Bureau of Meteorology forecast issued at: Mon, 4 Nov 2013 05:30 AM

Central: LOW-MODERATE

 Displays when Total Fire Ban in force
Restrictions may apply

---------
Mon, 4 Nov 2013 05:30 AM
LOW-MODERATE

As you can see my code returns the correct values atm but is this the most efficient way of doing this or should I be using another command?


texts:
I am creating an investment/betting simulation; since is the first I create , I am sure it can be done better, both from a coding and a simulation point of view.

I would like to ask you what you think and if you can share your experience.

There are 5 main variables that the user has to input:

z --> it is my average winning percentage. As discuss later, a random number between 0 and 100 will be generate. If the generated number (x) is greater than (z), then the trade is loss; if x < z, is a win.
invest --> how much money invested per trade, es. 10$. In case of a win, the return is always the 70%. i.e. bet 10$, win 7$ (plus the bet)
days --> how many days I trade. there is fixed amount of trade per day, which is between 9 and 33
simulazioni --> the number of simulations
varianza --> is the shifting probability. If varianza is 5% and my percentage (z) is 50%, my actual variance could be either 45% or 55%. This is calculated randomly for each trade.

As you can see from the code at the bottom, the simulation is based on "for loops". The main one is the simulations, second one are the days and the last one calculates if the trading is positive or negative.

There are also dictionaries that I use to collect data from daily profit and total profit (i.e. "datatot"; these dictionaries are used to plot data later on (this bit is not included in the code).

import random
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np

data=[]
data2=[]
datatot = []
portafoliotot = 0
portafolio = 0
pos= 0
neg= 0

#input variables
z= input("Percentuale: ")
invest = input("Investimento:")
days = input ("Giorni:")
simulazioni = input("Simulazioni:")
varianza = input("Varianza:")

for simulazione in range(0,int(simulazioni)):

    for giorno in range(0,int(days)):

        portafoliotot = 0 #simulation portfolio
        portafolio = 0 #daily portfolio
        pos = 0 #n of positive trades
        neg = 0 #n of negative trades

        for trade in range(0,int(random.randint(9,33))):

            x=random.randint(0,100) #random number to see if the trade is pos or neg

            calcvarianza = 2 * np.random.rand() - 1 # calculation of (varianza). if positive, is going to be added to (z), otherwise subtracted. this is done for each trade.

            if calcvarianza > 0:
                varianza = - int(varianza)

            if x<(int(z)+int(varianza)): #checking if the trade is pos or neg

                portafolio += (int(invest)/100)*70
                pos +=1
            else:
                portafolio += -int(invest)
                neg +=1

        portafoliotot += portafolio
        data.append(portafoliotot)
        data2.append(portafoliotot)

    datatot.append(sum(data2))
    data2 = []


texts: Create all combinations of length N from a given alphabet

texts:
I have some (very limited) experience in Java 6 and decided to revisit the language. To do so I wrote a solution for the following challenge:

You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in alphabetical order.
The first argument will be the path to the input filename containing the test data. Each line in this file is a separate test case. Each line is in the format: N,S i.e. a positive integer, followed by a string (comma separated). E.g.
Print all of the possible ways to write a string of length N from the characters in string S comma delimited in alphabetical order, with no duplicates.

Input sample:
1,aa
2,ab
3,pop

Output sample:
a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp

The code works but performance is pretty bad and it feels like this can be improved.
Please point out anything that is wrong with this. I'm especially interested to know if this could be written in an entirely different way using features of Java 8.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.HashSet;
import java.lang.String;
import java.lang.Integer;

public class Main
{
    public static List<String> create_combinations(List<Character> alphabet, int word_length)
    {
        List<Integer> index = new ArrayList<Integer>(word_length);
        for (int i = 0; i < word_length; ++i)
        {
            index.add(0);
        }
        List<String> results = new ArrayList<String>();

        for (;;)
        {
            StringBuilder word = new StringBuilder();
            for (int i = 0; i < index.size(); ++i)
            {
                word.append(alphabet.get(index.get(i)));
            }
            results.add(word.toString());

            for (int i = index.size() - 1; ; --i)
            {
                if (i < 0)
                {
                    return results;
                }

                index.set(i, index.get(i) + 1);

                if (index.get(i) == alphabet.size())
                {
                    index.set(i, 0);
                }
                else
                {
                    break;
                }
            }
        }
    }

    public static void main (String[] args) throws IOException
    {
        BufferedReader buffer = new BufferedReader(new FileReader(new File(args[0])));
        String line;
        while ((line = buffer.readLine()) != null)
        {
            int word_length = Integer.parseInt(line.substring(0, line.indexOf(',')));
            String letters = line.substring(line.indexOf(',') + 1);

            Set<Character> unique_letters = new HashSet<Character>();
            for (char c : letters.toCharArray())
            {
                unique_letters.add(c);
            }
            List<Character> alphabet = new ArrayList<Character>();
            alphabet.addAll(unique_letters);
            Collections.sort(alphabet);

            System.out.println(String.join(",", create_combinations(alphabet, word_length)));
        }
    }
}


texts: Python script to update a cPanel zone record with my public IP

texts:
This is my first attempt at using Python to send http requests.  I want to keep a zone record on cPanel pointed at my home network's public IP.  I'm just looking for some general feedback/suggestions.  Is there an easier way to do this?  Is there a more Pythonic way?  My intent is to run this as a cronjob to stay ahead of my ISP's DHCP.

This file generates the http request containing the cPanel JSON API call.

#!/usr/bin/python3

from http import client
from base64 import b64encode
from sys import argv
from netutils import PollIP

class ZoneUpdate:

    def __init__ (self):

        pass

    def updateIP (self, passedIP):

        newIP = passedIP

        conn = client.HTTPSConnection('mydomain.com', 2083)

        myAuth = b64encode(b'username:thepassword').decode('ascii')

        authHeader = {'Authorization':'Basic ' + myAuth}

        conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + newIP, headers=authHeader)

        myResponse = conn.getresponse()

        print(myResponse.getcode())

        data = myResponse.read()

        if myResponse.getcode() != 200:
        print('did not succeed')

        print (data)

############################################

if __name__ == "__main__":

    app = ZoneUpdate()

    if len(argv) > 1:
        newIP = argv[1]
        print(argv[1])
    else:
        getIP = PollIP()
        newIP = getIP.publicIP()

    app.updateIP(newIP)

This module (imported by the preceding) will use the dyndns website to obtain my public IP address.

#!/usr/bin/python3

from urllib import request
from re import compile

class PollIP:

    def __init__(self):
        pass

    #Use the dyndns web-site to poll my public IP address
    def publicIP(self):

        myReq = request.urlopen('http://checkip.dyndns.com')

        html = str(myReq.read())

        myReg = compile('[\d.]+')

        myMatch = myReg.search(html)

        print(myMatch.group())

        return myMatch.group()


texts: Most efficient JavaScript countdown timer implementation

texts:
I have this timer working already(jsbin):

HTML:

  <input id="m" type="number" value="0" min="0" max="59"/>
  <input id="s" type="number" value="2" min="0" max="59"/>
  <input id="start" type="button" value="Start!" />
  <output>00:00</output>

JavaScript:

var o = document.querySelector('output'),
m = document.querySelector('#m')
s = document.querySelector('#s'),
start = document.querySelector('#start');

start.addEventListener('click', function(){
    var mm = parseInt(m.value),
        ss = parseInt(s.value);
    timer = function(){
        if(mm>0){
            if(ss>0){
                ss--;
            }
            else{
                mm--;
                ss = 59;
            }
            setTimeout("timer()", 1000);
            o.value = (mm<10 ? '0' + mm : mm) + ":" + (ss<10 ? '0' + ss : ss);
        }
        else{
            if(ss>0){
                ss--;
                o.value = "00:" + (ss<10 ? '0' + ss : ss);
                setTimeout("timer()", 1000);
            }
        }
    }

    timer();
}, false);

It seems a lot of code for just a timer. Is it possible to implement this with less code? Maybe with loops, Date object or something else?

This code have problem and that is number of items in call stack when the time is big enough. I tried to write same code with while or for but I couldn't get a good result.

MY QUESTION is how to write this countdown with for or while?


texts:
I have an optimization issue and I'm not sure if I can improve the overall speed of my function.

The function draw_w is my actual implementation that gives me the right update for my vector w. You can see that the code is running for 1000 iterations in 9s.
I had a first implementation (draw_w_fw) that was quiet good because, well-vectorized, that is an order of magnitude quicker by 0.8s. Unfortunately, this implementation is wrong because the cache[0] is not updated correctly.

I would like to know if someone knows a way to speed up draw_w from what I've wrote.

import scipy.sparse as sps
import numpy as np
import timeit

def draw_w(X, w, cache):

    X = X.tocsr()

    for i in xrange(w.shape[0]):
        x_li = X.getrow(i)
        Y = w[i] * x_li
        Y.data -= np.take(cache[0], Y.indices)
        h = x_li.multiply(-Y)

        w_mean = h.sum()
        w_sigma_sqr = (x_li.multiply(x_li)).sum()

        w_sigma_sqr = 1.0 / w_sigma_sqr
        w_mean = - w_sigma_sqr * w_mean

        # update w:
        w_old = np.copy(w[i])

        if np.isinf(w[i]):
            w[i] = 0
        elif np.isnan(w[i]):
            w[i] = 0
        else:
            w[i] = w_mean

        # update error:
        cache[0] -= (w_old - w[i]) * x_li

    #print 'draw_w', w
    #True result w [ 2.34125626  2.37726446  4.00792293  3.71059779  4.00792293  0.11100713
    # -0.28899287 -0.04393113  0.21429929]

####################

def draw_w_fw(X, w, cache):

    x_li = X.tocsr()
    nnz_per_row = np.diff(x_li.indptr)
    Y = sps.csr_matrix((x_li.data * np.repeat(w, nnz_per_row), x_li.indices, x_li.indptr), shape=x_li.shape)
    Y.data -= np.take(cache[0], Y.indices)   #not good because cache[0] is updated...
    h = x_li.multiply(-Y)

    w_mean = np.asarray(h.sum(axis=1).transpose())[0]
    w_sigma_sqr = np.asarray(( x_li.multiply(x_li) ).sum(axis=1).transpose())[0]

    w_sigma_sqr = 1.0 / w_sigma_sqr
    w_mean = - w_sigma_sqr * w_mean

    # update w:
    w_old = np.copy(w)

    w[~np.isnan(w) & ~np.isinf(w)] = w_mean[~np.isnan(w) & ~np.isinf(w)]

    w[np.isinf(w)] = 0.0
    w[np.isnan(w)] = 0.0

    # update error:
    cache[0] -= (w_old - w) * x_li

    #print 'draw_w_fw', w

##########################

def test():

    data = [ 1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]
    cols = [ 0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14]
    rows = [0,5,1,5,2,5,3,5,4,5,0,6,1,6,2,6,3,6,4,6,1,7,3,7,0,8,2,8,4,8]

    X = sps.coo_matrix((data, (rows, cols)), shape = (9,15))
    X = X.tocsr()

    w = np.array([ 0.16243454, -0.06117564, -0.05281718, -0.10729686,  0.08654076, -0.23015387,  0.17448118, -0.07612069,  0.03190391])

    cache = np.zeros((2, 15))
    cache[0] =  np.asarray([-5.06771933, -5.29132951, -4.28297104, -1.33745073, -2.14361311, -0.66308429,
     -0.88669446, -2.878336,  -4.93281569, -4.73897806, -1.13729633, -5.18341755,
     -0.80566155, -5.02091327, -4.88155533])
    #draw_w(X, w, cache)
    draw_w_fw(X, w, cache)

if __name__ == '__main__':
    print(timeit.timeit("test()", setup="from __main__ import test", number=1000))
    #draw_w:    9.26 for 1000 iterations
    #draw_w_fw: 0.80 for 1000 iterations


texts:
I have already asked similar question here, but I figured this place might be better on getting some actual implementation feedback.

I tried to implement a simple SOM. You can see the training implementation function here.

The main part of the code is the seqTrain function:

seqTrain <- function(somWeights, X, gridSize, trainLen, alphaInit, radiusPar, neighbFunc) {
    # calculate map unit distances
    # first we need to calculate map units coordinates on map grid
    mapUnitCoord <- getUnitCoords(gridSize)
    mapUnitDists <- getUnitDistances(mapUnitCoord)
    dataLen <- nrow(X)
    message("Kicking off ", trainLen, " training iterations")
    # initialize quant Error vector
    qErr <- c()
    # perform the actual SOM training
    for (i in 1:trainLen){
            # pick a sample vector from input data
            xIn <- X[sample(dataLen,1),]
            # calculate the distance matrix
            deltaX <- sweep(-somWeights, 2, xIn, "+")
            distX  <- deltaX^2
            # find the bmu
            bmu <- which.min(rowSums(distX))
            # calculate learning rate, radius and neighbourhood
            a <- alpha(alphaInit = alphaInit, trainLen, i)
            r <- radius(radiusPar, trainLen, i)
            n <- neighbFunc(mapUnitDists, bmu, r)
            # update the SOM weights - vector n is multiplying each column of deltaX
            somWeights <- somWeights + a*sweep(deltaX, 1, n, "*")
            # calcuate quantization error
            qErr[i] <- mapErr(X, somWeights)
    }
    list("model" = somWeights, "qerr" = qErr)

}

There is something strange I'm noticing and I'm not really sure why it's happening. I'm sure I'm missing something fundamental or subtle. I'm using the iris data set to both train and validate the SOM parameters. The data set contains data for 3 different kinds of flowers i.e. it contains 3 different groups/clusters of data.

Once I have trained the SOM I try to validate the model using the trained parameters. I expect to see that the SOM really does cluster the Iris data to three groups - each per flower type.

However I'm seeing something different when validating the SOM parameters. When I normalize the input data and then try to verify/validate the trained SOM parameters using the original non-normalized iris data, the validation seems to cluster the data into the same best matching unit (BMU). That is, if I normalize the input for learning and don't normalize the data for validation, I get 1 cluster instead of expected 3 clusters.

However, when I normalize both the input and the validation data set (like I said validation data is the same data set as the one used for training the SOM - iris data set), I do get the expected result - i.e. the data does cluster into 3 [clearly identifiable] clusters.

Equally, when I don't normalize either of the data sets I get the expected validation results.

What would be the potential cause of the first case be: ie. training the model on normalized data and getting incorrect results when validating the model using the exact same data as validation data, but not non-normalized?

I would expect that normalizing the data to train the SOM model should have no effect on validation i.e. that once you have the model parameters, you should be able to classify non-normalized data.

I'm guessing that this could be because of using the same data set for training and validation.


texts: Converting a 12 hour time string to a 24 hour time string

texts:
Input - Standard input - HH:MM:SS[AM|PM] format.

Examples:

12:00:00AM
12:00:00PM
01:00:10AM
01:00:10PM

The program reads one line per instance.

Output - military format (24 hour format):

00:00:00
12:00:00
01:00:10
13:00:10

using System;

class Solution {
    static void Main(String[] args) {
        var time = Console.ReadLine().Trim();
        MilitaryTime mt = new MilitaryTime(time);
        Console.WriteLine(mt);
    }

    class MilitaryTime{
        string newTime = null;
        string originalTime = null;

        string correctHour(string time){
            var ampmLen = 2;
            var ampm = time.Substring(time.Length-ampmLen, ampmLen);
            var hourIndex = 0;
            var hour = time.Split(':')[hourIndex];
            var h = hour;
            if(ampm.Equals("PM")){
                h = (int.Parse(hour) + 12).ToString();
            }
            if(hour.Equals("12") || hour.Equals("24")){
                if(ampm.Equals("AM")){
                    h = "00";
                } else if(ampm.Equals("PM")){
                    h = "12";
                }
            }
            return h;
        }
        string minutesAndSeconds(string time){
            var ampmLen = 2;
            var hourLen = 2;
            var startIndex = hourLen; // since we are taking after hour HH:MM:SS
            return time.Substring(startIndex, time.Length - ampmLen - hourLen);
        }
        public MilitaryTime(string time){
            originalTime = time;
        }
        public override string ToString(){
            if(string.IsNullOrEmpty(newTime)){
                newTime = correctHour(originalTime) + minutesAndSeconds(originalTime);
            }
            return newTime;
        }
    }
}

Is this code smelly?
I re-factored code to this state, but did I miss anything?
Is there a better way to solve this problem, using .net classes and features I might have missed?
Does it look like that it's written by someone junior or new to programming? If yes, then how would an experienced programmer write it?


texts:
I am trying to implement linklist data structure in java. Following is my implementation:

// A singly Linked List
class Node{

int value;
Node next;

Node(int n){
   this.value = n;
   this.next = null;
}

public void printNode(){
   System.out.println("Value: " + value);
}

}

class LinkList{

 private Node first;
 private Node last;

 public LinkList(){
  first = null;
  last = null;
}

public boolean isEmpty(){
   return first == null;
}

public void insertFirst(int n){

 Node node = new Node(n);

 if(first == null){
    System.out.println("1. Vlaue of n: "+n);
    first = node;
    last = node;
 }else{
    System.out.println("2. Vlaue of n: "+ n);
    Node tmp = first;
    first = node;
    node.next = tmp;

  }

 }

 public void deleteFirst(){
   if (!isEmpty()){
      Node tmp = first;
      first = tmp.next;
  }
}

public void deleteLast(){

 if(!isEmpty()){

    Node tmp = first;
    Node oneBeforeLast = null;

    while (tmp.next != null){
        oneBeforeLast = tmp;
        tmp = tmp.next;
    }

    oneBeforeLast.next = null;

   }
 }

 public void deleteNode(int value){

  if (!isEmpty()) {

    Node tmp = first;
    Node oneBeforeLast = first;

    while (tmp.next != null) {

        if (tmp.value == value) {

            if (oneBeforeLast == first) {
                first = tmp.next;
            } else
                oneBeforeLast.next = tmp.next;
        }
        oneBeforeLast = tmp;
        tmp = tmp.next;
        System.out.println("Btmp: " + oneBeforeLast.value + " tmp:
        " + tmp.value);
    }

     if (tmp.next == null && tmp.value == value) {
        oneBeforeLast.next = null;
     }
    }
 }

public void printList(){

  Node tmp = first;

  System.out.println("\nPrinting List:");

  while(tmp != null){
     tmp.printNode();
     tmp = tmp.next;
   }
 }
}

public class LinkListTest {

 public static void main(String[] args) {

 // TODO Auto-generated method stub
 LinkList linklist = new LinkList();
   linklist.insertFirst(1);
   linklist.insertFirst(2);
   linklist.insertFirst(3);
   //linklist.insertFirst(3);
   linklist.insertFirst(4);

   linklist.printList();

   //linklist.deleteFirst();
   //linklist.printList();

  //linklist.deleteLast();
  //linklist.printList();

   linklist.deleteNode(1);
  linklist.printList();
 }

}

I would like to improve it further and check its efficiency for large inputs. Can anyone give some pointers on these two pointers, please?


texts: Calling functions with different variable types

texts:
I need to call the function that will get the value of a datatable cell with the ColIndex, either a text (column name) or an integer (columnindex).

To avoid writing two functions that, I wrote this code:

Public Function DTableCellValue(ByRef RowData As DataRow, _
                                    ByVal ColIndex As Object, _
                                    Optional ByVal DefaultVal As String = "") As Object
        Try
            Dim ret As Object = RowData.Item(ColIndex)

            If IsDBNull(ret) Then
                Return DefaultVal
            Else
                Return ret
            End If
        Catch ex As Exception
            Throw
        End Try
    End Function

Can you tell me if it uses bad coding practices or is potentially problematic?


texts:
Good Morning

This is a builder design pattern .. the builder problem is duplication so

I want to know from an expert with explanation which is better on quality on this code:

(1)

public class Animal {

    private String animalName;
    private int animalAge;

    public static class Builder {
        private Animal animal;

        public Builder() {
            animal = new Animal();
        }

        public Builder getName(String animalName) {
            animal.animalName = animalName;
            return this;
        }

        public Builder getAge(int animalAge) {
            animal.animalAge = animalAge;
            return this;
        }

        public Animal build(){
            animal.build(this);
            return animal;
        }
    }

    public Animal(){ }

    public void build(Builder builder) {
        this.animalName = builder.animal.animalName;
        this.animalAge = builder.animal.animalAge;
    }

    public String getAnimalName() {
        return animalName;
    }

    public int getAnimalAge() {
        return animalAge;
    }
}

(2)

public class Animal {

    private String animalName;
    private int animalAge;

    public static class Builder{

        private String animalName;
        private int animalAge;

        public Builder getName(String animalName){
            this.animalName = animalName;
            return this;
        }

        public Builder getAge(int animalAge){
            this.animalAge = animalAge;
            return this;
        }

        public Animal build(){
            return new Animal(this);
        }

    }

    public Animal(Builder builder) {
        this.animalName = builder.animalName;
        this.animalAge = builder.animalAge;
    }

    public String getAnimalName() {
        return animalName;
    }

    public int getAnimalAge() {
        return animalAge;
    }
}

in first model i pass animal object and create an instance and then the builder fill the data and build the animal again .

in second model i duplicate all the animal instance variables

which is true ? and which not broke builder rules ?


texts:
I have written a program to find all the possible permutations of a given list of items. This precisely means that my program prints all possible P(n,r) values for r=0 to n.

package com.algorithm;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Permutations<T> {
    public static void main(String args[]) {
        Permutations<Integer> obj = new Permutations<Integer>();
        Collection<Integer> input = new ArrayList<Integer>();
        input.add(1);
        input.add(2);
        input.add(3);

        Collection<List<Integer>> output = obj.permute(input);
        int k = 0;
        Set<List<Integer>> pnr = null;
        for (int i = 0; i <= input.size(); i++) {
            pnr = new HashSet<List<Integer>>();
            for(List<Integer> integers : output){
            pnr.add(integers.subList(i, integers.size()));
            }
            k = input.size()- i;
            System.out.println("P("+input.size()+","+k+") :"+
            "Count ("+pnr.size()+") :- "+pnr);
        }
    }
    public Collection<List<T>> permute(Collection<T> input) {
        Collection<List<T>> output = new ArrayList<List<T>>();
        if (input.isEmpty()) {
            output.add(new ArrayList<T>());
            return output;
        }
        List<T> list = new ArrayList<T>(input);
        T head = list.get(0);
        List<T> rest = list.subList(1, list.size());
        for (List<T> permutations : permute(rest)) {
            List<List<T>> subLists = new ArrayList<List<T>>();
            for (int i = 0; i <= permutations.size(); i++) {
                List<T> subList = new ArrayList<T>();
                subList.addAll(permutations);
                subList.add(i, head);
                subLists.add(subList);
            }
            output.addAll(subLists);
        }
        return output;
    }
}

output:
P(3,3) : Count (6) :- [[1, 2, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2], [2, 1, 3], [1, 3,
2]]
P(3,2) : Count (6) :- [[3, 1], [2, 1], [3, 2], [1, 3], [2, 3], [1, 2]]
P(3,1) : Count (3) :- [[3], [1], [2]]
P(3,0) : Count (1) :- [[]]

My problem is increasing the numbers in the input list. Running time increases, and after 11 numbers in the input list, the program almost dies. Takes around 2 GB memory to run.

I am running this on a machine having 8GB RAM and i5 processor, so the speed and space is not a problem.

I would appreciate it if anyone can help me write more efficient code.


texts: Update only specific field of specific item (data) in List from YAML

texts:
I don't like the logic to update [Repository] list here because I need to map whole list to change only specific field of specific node,  I especially don't like that I need to provide all other fields in changing node alike (location x) etc... Major trouble there is that if I will edit data model I will be forced to edit a lot of code where I use it like this.

hashupdate :: String -> String -> IO ()
hashupdate hash rep =
  withConfig $ \ymlx ->
    let ymlprocess = ifSo $ do
        rsdata <- yDecode ymlx :: IO [Repository]
        let ed = map enR rsdata
                        where enR x = if rep == (location x)
                                            then (Repository (location x)
                                                             (branches x)
                                                             (upstream x)
                                                             (enabled x)
                                                             (clean x)
                                                             (post_rebuild x)
                                                             (syncGroup x)
                                                             (Just hash))
                                            else x
        yEncode ymlx ed
    in doesFileExist ymlx >>= ymlprocess

The other definitions used there is here:

data Repository = Repository { location      :: String
                             , branches      :: [String]
                             , upstream      :: String
                             , enabled       :: Maybe Bool
                             , clean         :: Maybe Bool
                             , post_rebuild  :: Maybe [String]
                             , syncGroup     :: Maybe String
                             , hash          :: Maybe String
                             } deriving (Show, Eq)

yEncode :: ToJSON iToJSONable => FilePath -> iToJSONable -> IO()
yEncode fnm dat = do
  let bs = Data.Yaml.encode dat
  BS.writeFile fnm bs


texts: Is there a condensed way of adding multiple event listeners each with different functions to the same group of elements?

texts:
I would ideally like to add event listeners to a single group of elements, topLevelDesktopNavDropdownItems , in some kind of object syntax like {event: function, event: function}. Or is there another way to do this? Here is my current code:
topLevelDesktopNavDropdownItems.forEach(
    element => element.addEventListener('mouseenter', topLevelNavItemMouseOver)
);

topLevelDesktopNavDropdownItems.forEach(
    element => element.addEventListener('mouseleave', topLevelNavItemMouseOut)
);

topLevelDesktopNavDropdownItems.forEach(
    element => element.addEventListener('keydown', topLevelNavItemLinkKeyDown)
);


texts:
I somewhat recently asked a question on here for advice on a PDO function that I had written. I got some good advice from a user, and went with it. I had used that function for about 3 months which is also about how long I have been using PDO in general, until someone mentioned to me that they would have made it a class.

I have never worked with classes before in PHP, and I wanted to give it a shot. So I did.

Now, since this is my first class, I wanted to get some advice on it and some constructive criticism. I want my code to keep on improving, and I want to know the best way to do some things. I don't know if my class is written well, and knowing how I can improve it will definitely help me out.

I've hosted the project on my GitHub.  The project is being developed there, and everyone is welcome to contribute to it.

class GrumpyPdo {

    private $host, $user, $pass, $db, $charset;
    private $dsn, $databaseObject;

    private $killOnError = true;
    private $echoOnError = false;

    //these options can obviously be changed but not "on the fly" (yet).
    private $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    function __construct($host, $user, $pass, $db, $charset = "utf8") {

        $this->setData([
            "host" => $host,
            "user" => $user,
            "pass" => $pass,
            "db" => $db,
            "charset" => $charset,
        ]);

        $this->createDBObject();

    }

    function query($query, $values = []) {
        if(!empty($values)) {
            $stmt = $this->databaseObject->prepare($query);
            $stmt->execute($values);
        } else {
            $stmt = $this->databaseObject->query($query);
        }
        return $stmt;
    }

    function setData($data) {
        if(!is_array($data)) {
            $this->handleError("GrumpyPDO: Error Code SD13; The setData method requires an array with \$key => \$value pairs.");
        }
        foreach($data as $k => $v) {
            $this->{$k} = $v;
        }
        return true;
    }

    function createDBObject() {
        $this->dsn = "mysql:host={$this->host};dbname={$this->db};charset={$this->charset}";
        $this->databaseObject = new PDO($this->dsn, $this->user, $this->pass, $this->opt);
    }

    function handleError($error) {
        error_log($error);
        if($this->echoOnError) echo $error;
        if($this->killOnError) die($error);
    }

}


texts:
I have made this small text-based dice rolling game in C++. How could I improve it? Be as picky as you'd like.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void mainGame(int &numDice);

int main()
{
    srand (time(NULL));

    int gameRunning = true;
    int numDice;

    while (gameRunning == true)
    {
        system("cls");
        cout << "\n How many dice would you like to use? (1-4)" << endl;
        cout << "\n Enter '0' to exit." << endl;
        cout << "\n> ";
        cin >> numDice;

        if (numDice == 1 || numDice == 2 || numDice == 3 || numDice == 4)
        {
            mainGame(numDice);
        }

        else if (numDice == 0)
        {
            return 0;
        }

        else {
            system("cls");
            cout << "\n That was invalid input!" << endl;
            cout << "\n ";
            system("pause");
        }
    }
}

void mainGame(int &numDice)
{
    bool goAgain = true;
    int dice[4];
    int input;

    while (goAgain == true)
    {
        for (int x = 0; x != numDice; x++)
        {
            dice[x] = (rand() % 6) + 1;

            cout << "\n Dice " << x + 1 << " shows a " << dice[x] << "!" << endl;
            cout << "\n ";
            system("pause");
        }

        system("cls");
        cout << "\n Would you like to go again with " << numDice << " dice?" << endl;
        cout << "\n Enter '1' for yes or '2' for no." << endl;
        cout << "\n> ";
        cin >> input;
        switch (input)
        {
            case 1:
                break;

            case 2:
                goAgain = false;
        }
    }
}


texts:
Find ceiling and floor in the BinarySearchTree. Looking for code-review, optmizations and best practices.

public class FloorCeiling {

    private TreeNode root;

    public FloorCeiling(List<Integer> items) {
        create(items);
    }

    private void create (List<Integer> items) {
        if (items.isEmpty())  {
            throw new NullPointerException("The items array is empty.");
        }

        root = new TreeNode(items.get(0));

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode {
        private TreeNode left;
        private int item;
        private TreeNode right;

        TreeNode(int item) {
            this.item = item;
        }
    }

    private static class IntegerObj {
        Integer obj = null;
    }

    public int ceiling (int val) {
        IntegerObj iobj = new IntegerObj();
        recurseCeiling(root, iobj, val);
        return iobj.obj;
    }

    public int floor (int val) {
        IntegerObj iobj = new IntegerObj();
        recurseFloor(root, iobj, val);
        return iobj.obj;
    }

    private void recurseCeiling (TreeNode node,  IntegerObj iobj, int value) {
        if (node == null) {
            return;
        }
        if (value <= node.item) {
            iobj.obj = node.item;
            recurseCeiling(node.left, iobj, value);
        } else {
            recurseCeiling(node.right, iobj, value);
        }
    }

    private void recurseFloor (TreeNode node, IntegerObj iobj, int value) {
        if (node == null) {
            return;
        }
        if (value < node.item) {
            recurseFloor (node.left, iobj, value);
        } else {
            iobj.obj = node.item;
            recurseFloor (node.right, iobj, value);
        }
    }
}

public class FloorCeilingTest {

    @Test
    public void test1() {
        FloorCeiling fc1 = new FloorCeiling(Arrays.asList(100, 50, 150, 25, 75, 125, 175));
        assertEquals(25,  fc1.ceiling(20));
        assertEquals(50,  fc1.ceiling(30));
        assertEquals(75,  fc1.ceiling(70));
        assertEquals(100, fc1.ceiling(90));
        assertEquals(125, fc1.ceiling(120));
        assertEquals(150, fc1.ceiling(145));
        assertEquals(175, fc1.ceiling(160));
    }

    @Test
    public void test2() {
        FloorCeiling fc2 = new FloorCeiling(Arrays.asList(100, 50, 150, 25, 75, 125, 175));
        assertEquals(25,  fc2.floor(27));
        assertEquals(50,  fc2.floor(55));
        assertEquals(75,  fc2.floor(78));
        assertEquals(100, fc2.floor(110));
        assertEquals(125, fc2.floor(128));
        assertEquals(150, fc2.floor(160));
        assertEquals(175, fc2.floor(180));
    }

}


texts:
I am taking a helper stack, which is used during dequeue. Kindly suggest improvement or some solution with less complexity.

import java.util.ArrayDeque;
import java.util.Deque;

public class MyQueueUsingTwoStack {

    Deque<Integer> mainStack = new ArrayDeque<>();
    Deque<Integer> helperStack = new ArrayDeque<>();

    public void enqueue(int x) {
        mainStack.push(x);
    }

    //popping up all the object from mainStack to helper stack(except the last one) and then putting all object
    //from helper stack to mainStack
    public int dequeue() {
        while(!mainStack.isEmpty()) {
            helperStack.push(mainStack.pop());
        }

        int pop = helperStack.pop();

        while(!helperStack.isEmpty()) {
            mainStack.push(helperStack.poll());
        }

        return pop;

    }

    public boolean isEmpty() {
        return mainStack.isEmpty();
    }

}


texts:
I need a way to store and retrieve callbacks in Ruby, so I made a Callbacks class. Any suggestions would be greatly appreciated.

class Callbacks
  def initialize
    # name: name of callback
    # event: event of which it belongs
    # callback: block to call
    @callbacks = []
  end

  def add name, event, &block
    if block_given?
      @callbacks << {
        name: name,
        event: event,
        callback: block
      }
    end
  end

  def get options={}
    name = options[:name]
    event = options[:event]

    @callbacks.each do |h|
      if name and event
        return h if h[:name] == name and h[:event] == event
      else
        return h if h[:name] == name or h[:event] == event
      end
    end
    nil
  end
end


texts:
This code consumes a lot of CPU. Could you tell me where it is possible to improve the code or change the way rendering?

Or it is possible to reduce the overhead of calculations? If you are using only 1 point when drawing the load on the CPU is not changed! Load 50-60%

Ubuntu 15.04 / intel® Core ™ i5-3230M CPU @ 2.60GHz × 4

Run the code without rendering lines - 20-30% load. So they are quite costly...

Demo: http://codepen.io/jonfint/full/VLYMMW

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext('2d'),
    points = [],
    r = 0;

var a = 50; // количество точек
var b = 1; // скорость поворота
var d = 20; // увеличение радиуса*
var minDist = 200; // ??
var dist; // ??

canvas.width = 500;    // Originally window.innerWidth, changed for Stack Snippet
canvas.height = 600;   // Originally window.innerHeight, changed for Stack Snippet

for (var i = 0; i < a; i++) {
    var rand = Math.random() * canvas.height;

    points.push({
        cy: rand,
        cx: rand * 0.3 + 300,
        r: 360 / a * i,
        p: {x: null, y: null},
        d: Math.random() * (d + 5) + 50,
        s: (Math.random() - 0.5) * 0.7,
        size: Math.random() * 3 + 1,
    })
}

function render(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = '#202020';
    for (var i=0, len = points.length; i < len; i++) {
        var p = points[i];

        for (var j = i + 1; j < points.length; j++) {
            var p2 = points[j];
            distance(p.p.x, p.p.y, p2.p.x, p2.p.y);
        }

        p.r += p.s;

        var vel = {
            x: p.d * Math.cos(p.r * Math.PI / 180),
            y: p.d * Math.sin(p.r * Math.PI / 180) / 2
        };

        var centx, centy;
        centx = p.p.x - p.size * 0.5;
        centy = p.p.y - p.size * 0.5;
        ctx.beginPath();
        ctx.rect(centx, centy, p.size, p.size);
        ctx.fill();
        ctx.closePath();

        p.p.x = p.cx + vel.x;
        p.p.y = p.cy + vel.y;
    }
}

function distance(p1x, p1y, p2x, p2y) {
    var dx = p1x - p2x;
    var dy = p1y - p2y;
    dist = Math.sqrt(dx*dx + dy*dy);
      // Нарисовать линию, если расстояние меньше, чем minDistance
    if (dist <= minDist) {
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(200, 200, 200,'+ (1.0-dist/minDist) +')';
        ctx.moveTo(p1x, p1y);
        ctx.lineTo(p2x, p2y);
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.closePath();
    }
}

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame   ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
    function(callback) {
        window.setTimeout(callback, 1000 / 30);
    };
})();

(function animloop() {
    requestAnimFrame(animloop);
    render();
})();
<canvas id="canvas"></canvas>


texts: Correct implementation of encryption function

texts:
I wrote a simple encryption function that uses argon2d as the KDF and XChaCha20-Poly1305 as the AEAD. Since it is very easy to not get things right when dealing with encryption, I would appreciate if someone could review my script and tell me if it has any vulnerabilities and could be used in the real world to encrypt real data.
import argon2
from Cryptodome.Cipher import ChaCha20_Poly1305
import secrets

def encrypt(password, data):
    salt = secrets.token_bytes(32)
    nonce = secrets.token_bytes(24)

    key = argon2.low_level.hash_secret_raw(secret=password, salt=salt, time_cost=3, memory_cost=1000000, parallelism=4, hash_len=32, type=argon2.low_level.Type.D, version=19)

    cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)

    ciphertext, tag = cipher.encrypt_and_digest(data)

    return salt + nonce + ciphertext + tag


texts: Python script to delete sections of text

texts:
I've been writing a python script to help me clear up some files that contain outdated code, while also serving as a way to learn python. These files have sections of code surrounded with tags on their own lines, I need it to remove both the tags and everything within. While this largely applies to XML documents I am also using this script for several other file types, so XML specific solutions aren't suitable.

I have a working script already but it doesn't look like the most elegant or efficient solution by far, so I would like to see how I can improve it.

Script is called as python cleanup.py startDeleteTag stopDeleteTag where the last two arguments are the locations where the code should be deleted and stop being deleted respectfully.

import os, sys

def clearFile(path, beginDelete, stopDelete):

  path = os.path.join(path, "fileName.xml")
  input = open(path, "r")
  lines = input.readlines()
  input.close()

  currentFlag = False
  nextFlag = False

  output = open(path, "w")

  for line in lines:
    if nextFlag == True:
      nextFlag = False
      deleteFlag = False

    if beginDelete in line:
      deleteFlag = True
    elif stopDelete in line:
      nextFlag = True

    if deleteFlag == False:
      output.write(line)

thisDirectory = os.getcwd()
for start, dirs, files in os.walk(thisDirectory):
  for f in files:
    if f == "fileName.xml":
      clearFile(thisDirectory, sys.argv[1], sys.argv[2])

This is the part of the script that checks each line for the start of the section to be deleted (beginDelete to stopDelete). Because this would leave the end tag in the file I have to use a couple of booleans to specify when the current line needs to be removed but the next line shouldn't be. As an extra, is there a way to improve this to further check for tags that may be on the same line as body of the code? This isn't currently an issue but I'm curious how I would do it if I needed to in future.

As requested, and example file input would look like this:

<good>
  keep this
</good>

<bad>
  delete this
</bad>

<good>
  keep this
  <bad>
    delete this
  </bad>
</good>

And this would produce the output:

<good>
  keep this
</good>

<good>
  keep this

</good>


texts: Project Euler #5 in Ruby with Prime class

texts:
Question:

  Smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

I tackle the problem with reference to how I solved #3, which is using the prime_division method in the Prime class. I have created an array of prime_divisions for 2..20.

The array looks like this:

[[2, 1], [3, 1], [2, 2], [5, 1], [2, 1], [3, 1], [7, 1], [2, 3], [3, 2], [2, 1], [5, 1], [11, 1], [2, 2], [3, 1], [13, 1], [2, 1], [7, 1], [3, 1], [5, 1], [2, 4], [17, 1], [2, 1], [3, 2], [19, 1], [2, 2], [5, 1]]

And after using the .uniq method and sorting it, it shortens to the following:

[[2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [5, 1], [7, 1], [11, 1], [13, 1], [17, 1], [19, 1]]

which is then easy, I just multiply the highest index for each factor:

\$2^4 \times 3^2  \times 5  \times 7  \times 11  \times 13  \times 17  \times 19 = 232792560\$

At this last stage, the right thing to do would be to multiply the highest power of each factor. I couldn't figure out how to do that in an elegant way.  However, I realised that coincidentally, the number of occurrences of each factor in array b always equals to the highest power. But I would welcome a more elegant solution to this.

require 'prime'

a=[]
c= 1

# Get all prime factors from 2 to 20
(2..20).each do |n|
    a = a.concat(Prime.prime_division(n))
end

# Select only the unique elements and extract the factor, multiply them all
b = a.uniq
b.each do |n|
    if n[0] != 0 || !n[0].nil?
        c = c * n[0]
    end
end

puts c


texts: Printing a pattern through the use of a dictionary

texts:
We had to port a c program to python.  The code works but uses a dictionary to solve the problem.  This doesn't feel like the right use of a dictionary.  Is there a better way?

#!/usr/bin/env python3

def main():
    while True:
        height = input("Height: ")
        try:
            height = int(height)
            if height >= 0:
                break
        except:
            pass

    mtn={}
    space_mtn(height,mtn)
    hashs_mtn(height,mtn)
    print_mtn(height,mtn)

def space_mtn(height,mtn):

    for i in range(height):
        for j in range(2*height+2):
            mtn[i,j]=" "
    return

def hashs_mtn(height,mtn):

    for i in range(height):
        for  j in range(height-1,height-i-2,-1):
            mtn[i,j] = '#'

    for i in range(height):
        for j in range(height+2,height+i+3):
            mtn[i,j] = '#'
    return

def print_mtn(height,mtn):

    for i in range(height):
        for j in range(height+3+i):
            print("{}".format(mtn[i,j]),end="")
        print("")
    return

if __name__ == "__main__":
    main()