texts: Is this a correct use of the std::cout and std::cin basefields/conversions?

texts:
Considering the code that you can find at the bottom of this post, it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?

I'm referring to the use of:

std::hex in the std::istringstream case
the use of std::cout.setf() and std::cout.unsetf() in the "output section"

In short is this correct for both input and output ?

This could possibly lead to some bug of some kind on some platforms ?

I also have a doubt about the use of an unsigned int to input a char, the basefield always cares about that ? I mean if I input f I would like to store 15 in decimals and not 102 from the ascii table.
(because a char is often implemented as an unsigned int)

Thanks.

// trying to determine what is the header available for unsigned ints
#if __cplusplus < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif

#include <cstdlib>
#include <string>
#include <map>
#include <bitset>
#include <iostream>
#include <iomanip>
#include <sstream>

const static uint32_t fieldWidth = 2;

int main(int argc, char **argv) {

  std::map<std::string, uint32_t> bucket;
  bucket["EAX"] = 0x0; // initializing bucket with default values
  bucket["EBX"] = 0x0;
  bucket["ECX"] = 0x0;
  bucket["EDX"] = 0x0;

  if (argc >= 2) {
    switch (argc) {
    case 2:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      break;
    case 3:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      break;
    case 4:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      break;
    case 5:
      std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
      std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
      std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
      std::istringstream(argv[4]) >> std::hex >> bucket["EDX"];
      break;
    default:
      std::cout << "Too many arguments, exiting now\n";
      exit(EXIT_FAILURE);
    }

  } else {
    std::cout << "Not enough arguments, exiting now\n";
    exit(EXIT_FAILURE);
  }

  std::cout.setf(std::ios::hex, std::ios::basefield);
  std::cout.setf(std::ios::showbase);

  std::cout << "\nExecuting with this HEX values :\n\n";
  std::cout << "EAX = " << std::hex << bucket["EAX"] << "\n"
            << "EBX = " << std::hex << bucket["EBX"] << "\n"
            << "ECX = " << std::hex << bucket["ECX"] << "\n"
            << "EDX = " << std::hex << bucket["EDX"] << "\n";

  std::cout.unsetf(std::ios::showbase);
  std::cout.unsetf(std::ios::hex);

  asm volatile("cpuid"
               : "=a"(bucket["EAX"]), "=b"(bucket["EBX"]), "=c"(bucket["ECX"]),
                 "=d"(bucket["EDX"])
               : "a"(bucket["EAX"]), "b"(bucket["EBX"]), "c"(bucket["ECX"]),
                 "d"(bucket["EDX"]));

  std::cout << "\nThe results:\n";
  for (std::map<std::string, uint32_t>::const_iterator k = bucket.begin();
       k != bucket.end(); ++k) {

    std::cout << "\n";
    std::cout << k->first << "\n";

    for (int c = 31; c >= 0; c--) {
      std::cout << std::setfill(' ') << std::setw(fieldWidth) << c;
    }

    std::cout << "\n";

    std::string s(std::bitset<32>(k->second).to_string());

    for (std::string::const_iterator j = s.begin(); j != s.end(); ++j) {
      std::cout << std::setfill(' ') << std::setw(fieldWidth) << *j;
    }

    std::cout << "\n";
  }
  std::cout << "\n";
  return (0);
}

original repository


texts:
I am trying to write for both NT and POSIX (my two usual platforms) and have come up with the code below. The clrs code I refer to is apparently from blender build scripts, I discovered it on this SO post. They called the class bcolors but I wanted to reduce clutter so I renamed it.

But the main class is what I've written that determines the os before printing. Prints are called, for example, via PRN.cyan("some string").

For this to work I import colorama:

from colorama import init, Fore, Back, Style
init()

The PRN class that handles the print calls:

class PRN:
    @staticmethod
    def cyan(p_str):
        """print some text with cyan foreground"""
        if os.name == 'nt':
            # we'll try the Colorama option but if it fails we can
            # change the global variable for colours.
            if coloursOn:
                sys.stdout.write(Fore.CYAN + p_str + Fore.RESET)
            else:
                sys.stdout.write(p_str)
        else:
            # try Deez1.clrs for posix environment
            sys.stdout.write(clrs.cyan + p_str + clrs.ENDC)

If colorama doesn't work on a Windows system for some reason I can change the global boolean coloursOn.

Is this an incredibly klutzy/dumb implementation? From what I've read, so far, cross platform capability for ANSI color printing has only gotten shakier, not simpler.


texts:
I have this class which is used as part of a game. It needs to generate Random Even values, which is done by generating random numbers until the result is even.

Is there a better way to do this?

Also, I currently have the methods implemented as private instance methods, but should I declare generateRandomNumber() and evenNumber(number) as static methods? Will it have any benefits?

public class Game {
    //...

    public void opponentSaysEvenNumber() {
        int number = generateRandomEvenNumber();
        System.out.println("Opponent: " + number);
    }

    private int generateRandomEvenNumber() {
        Random random = new Random();
        int number = random.nextInt();
        while (!evenNumber(number)) {
            number = random.nextInt();
        }
        return number;
    }

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


texts:
I'm trying to solve this problem but am getting a timeout. Can someone help me to improve?

using namespace std;

typedef multimap<int,int> MMap;

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int t;
    cin>>t;
    for(int tcase=0; tcase<t; tcase++) {
        // contains input for each test case
        vector<int> in_vec;
        // array of different teams
        vector<vector<int> > vec_teams;
        int size;
        cin>> size;
        int val;
        int min = size;
        for(int i=0;i<size;++i) {
            cin>>val;
            in_vec.push_back(val);
        }
        if(size==0) {
            cout<<"0"<<endl;
            continue;
        }
        sort(in_vec.begin(),in_vec.end());
        vec_teams.push_back(vector<int>());
        // maintains ordered, key value pair of size and its position(index) in vec_teams
        MMap mmap;
        mmap.clear();
        vec_teams[0].push_back(in_vec[0]);
        mmap.insert(pair<int,int>(vec_teams[0].size(),0));

        for(int id=1; id<in_vec.size(); ++id) {
            bool added = false;
            MMap::iterator it = mmap.begin();
            //inserts the skill level to correct team
            // if not possible to add to any
            // then new team is created after the loop
            for(int i=0; i<vec_teams.size(); ++i,++it) {
                int mpos = (*it).second;
                if (vec_teams[mpos][vec_teams[mpos].size() -1 ] + 1 == in_vec[id]) {
                    pair <MMap::iterator, MMap::iterator> pa= mmap.equal_range(vec_teams[mpos].size());
                    MMap::iterator mmit;
                    for (mmit=pa.first; (*mmit).second!=mpos; ++mmit);
                    mmap.erase(mmit);
                    vec_teams[mpos].push_back(in_vec[id]);
                    mmap.insert(pair<int,int>(vec_teams[mpos].size(),mpos));
                    added = true;
                    break;
                }
            }
            // Since not able to add to existing teams
            // new team is created and added to it
            if(!added) {
                vec_teams.push_back(vector<int>());
                vec_teams[vec_teams.size() -1].push_back(in_vec[id]);
                mmap.insert(pair<int,int>(1,vec_teams.size() -1));
            }
        }
        int ans = (*(mmap.begin())).second;
        cout<<vec_teams[ans].size()<<endl;
    }
    return 0;
}


texts:
I've self-taught myself Python and have recently started learning tkinter. I made a simple stopwatch program and I wanted to know if the code is clean and written in a way that the code works efficiently. I would highly appreciate any suggestions on how to improve my code! Thank you!

from tkinter import *
import time

root = Tk()

numberOfSeconds = 0

def counting():
    global numberOfSeconds
    global stopCounting

    if stopCounting == False:
        numberOfSeconds += 1
        seconds.config(text=str(numberOfSeconds))
        seconds.after(1000, counting)
    elif stopCounting == True:
        stopCounting = False
        numberOfSeconds = 0
        seconds.config(text=str(numberOfSeconds))

def start():
    global stopCounting
    stopCounting = False
    stopButton.config(state=NORMAL)
    seconds.after(1000, counting)

def stop():
    global stopCounting
    stopButton.config(state=DISABLED)
    stopCounting = True

seconds = Label(text=str(numberOfSeconds))
startButton = Button(text="Start", command=start)
stopButton = Button(text="Stop", command=stop, state=DISABLED)

seconds.grid(row=0, column=0, columnspan=2)
startButton.grid(row=1, column=0)
stopButton.grid(row=1, column=1)

root.mainloop()


texts: Generic method for HTTP GET/POST parameter conversion

texts:
I just made a method that should handle GET and POST parameters (primitive types) sent by AJAX requests to the server:

protected T GetParam<T>(string key)
{
    string value = HttpContext.Current.Request[key];

    if (string.IsNullOrEmpty(value))
        return default(T);

    return (T)Convert.ChangeType(value, typeof(T));
}

Do you have any suggestions regarding improvements?


texts: Attempt at the Most dynamic FizzBuzz possible in Java

texts:
I was trying to come up with the most dynamic fizzbuzz answer I could.. and well, this is what I came up with:

public static void main(String[] args) {

    ultraFizzBuzz((Integer arg) -> {
        String retVal = "";
        if(arg % 3 == 0) { retVal += "fizz"; }
        if(arg % 5 == 0) { retVal += "buzz"; }
        return retVal;
    });
}

public static void ultraFizzBuzz(modConditions<Integer> tester) {

    for(int i = 1; i < 100; i++) {
        String result = tester.test(i);
        if(result != "")
            System.out.println(tester.test(i));
        else
            System.out.println(i);
    }
}

In here the modConditions is an interface with a method (test) that returns type String.

What I was basically trying to do is create a super dynamic function that lets you add as many fizzes and buzzes and pops as you wanted.. but I think in the process accidentally made it so you end up writing 90% of the code in a lambda statement everytime you want to call it.

Am I overcomplicating things? Would this be considered bad programming practice?


texts:
start:
try
{
    oleDbDataAdapter1.Fill(myDataTable);
}
catch (Exception ex) {
    DialogResult res = MessageBox.Show("Can't load data:\n" + ex.Message, "Error",
        MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
    if (res == DialogResult.Retry)
    {
        goto start;
    }
}

Is it ok to use goto operators, which lead outside a try/catch block?  What consequences may it lead to?
How can I make this code better?


texts:
I'm creating a web page which has two types of users with very similar permissions: Person and Company. The main difference is in their attributes and probably different billing.

I've created only one UserProfile for both types of users. What do you think? Is it safe? Should I expect some problems later because of this?

The first problem I met is that I can't tell Django that if the user is a person, then username can't be blank and the same with company and company_name.

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile',on_delete=models.CASCADE)

    TYPE_OF_USER_CHOICES = (('company', 'Company'),
                            ('person', 'Person'))

    type_of_user = models.CharField(max_length=40, choices=TYPE_OF_USER_CHOICES)

    IBAN = models.CharField(max_length=80, null=True)

    # PERSON

    username = models.CharField(max_length=20,blank=True,null=True)

    # COMPANY
    company_name = models.CharField(max_length=100,blank=True,null=True)

    ICO = models.CharField(max_length=30, blank=True, null=True, unique=True,
                           help_text=u'Zadajte firemné IČO alebo nechajte prázdne')
    DIC = models.CharField(max_length=30, blank=True, null=True, unique=True,
                           help_text=u'Zadajte firemné DIČ alebo nechajte prázdne')

    @property
    def is_firm(self):
        return self.type_of_user == 'company'

    @property
    def is_person(self):
        return self.type_of_user == 'person'

    def __str__(self):
        if self.is_firm:
            return '{} - Company'.format(self.company_name)
        else:
            return '{} - Person'.format(self.username)


texts: Escaping the prison - finding the shortest way

texts:
I have given an assignment where I have to escape a labyrinth. The goal is to find the shortest way. I have done some research and there seem to be two strategies to solve the problem: the Depth-first search and Breadth-first search, where the first starts at the root (Starting point in maze) and explores as far as possible along each branch before backtracking and the second begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on.

I have implemented both algorithms (non-recursive implementations) that will go on until they find the end:

/**
 * A non-recursive implementation of DFS
 * @param maze
 */
void solveUsingDepthFirst(IMaze maze) {
    Stack<IMazePosition> candidates = new Stack<IMazePosition>();
    //insert start position
    candidates.push(maze.getStartPosition());

    IMazePosition currentPosition;
    IMazePosition nextPosition;
    while (!candidates.empty()) {
        currentPosition = candidates.pop();

        if (maze.isMazeSolved(currentPosition)) break;

        //mark the current position
        maze.markPosition(currentPosition, maze.getPathMark());
      // maze.printMaze();
        // Check for possible ways to go
        nextPosition = currentPosition.north();
        if (maze.canMove(nextPosition)) candidates.push(nextPosition);
        nextPosition = currentPosition.east();
        if (maze.canMove(nextPosition)) candidates.push(nextPosition);
        nextPosition = currentPosition.south();
        if (maze.canMove(nextPosition)) candidates.push(nextPosition);
        nextPosition = currentPosition.west();
        if (maze.canMove(nextPosition)) candidates.push(nextPosition);
    }

    System.out.println(!candidates.empty() ? "Done" : "Sorry, could not do it");
    maze.printMaze();
}

/**
 * A non-recursive implementation of BFS
 * @param maze
 */
void solveUsingBreadthFirst(IMaze maze) {
    LinkedList<IMazePosition> candidates = new LinkedList<IMazePosition>();
    //insert start position
    candidates.add(maze.getStartPosition());

    IMazePosition currentPosition;
    IMazePosition nextPosition;
    while (!candidates.isEmpty()) {
        currentPosition = candidates.removeFirst();

        if (maze.isMazeSolved(currentPosition)) break;

        //markPosition the current position
        maze.markPosition(currentPosition, maze.getPathMark());
     //   maze.printMaze();

        // Check for possible ways to go
        nextPosition = currentPosition.north();
        if (maze.canMove(nextPosition)) candidates.add(nextPosition);
        nextPosition = currentPosition.east();
        if (maze.canMove(nextPosition)) candidates.add(nextPosition);
        nextPosition = currentPosition.south();
        if (maze.canMove(nextPosition)) candidates.add(nextPosition);
        nextPosition = currentPosition.west();
        if (maze.canMove(nextPosition)) candidates.add(nextPosition);
    }

    System.out.println(!candidates.isEmpty() ? "Done" : "Sorry, could not do it");
    maze.printMaze();
}

The map (or the maze) is represented as char[][]. The MazePosition is a representation of coordinates:

public MazePosition(int x, int y) {
    this.x = x;
    this.y = y;
}

Now with that code, I have all the possible paths from start to end that I was able to find until I found the end for the first time - is it fair to assume that the shortest path is amongst them?
Given that I have the possible paths, how would I go with finding the shortest? And, is the code for path generation any good at all? Can I optimize any of the routines I already have.

Also, as far as I know, there are no "holes" in the maze, which means I can always stick to the wall.


texts:
I am learning C# and for an experiment I tried implementing the Caesar Cypher cryptography method which just offsets every character of the string n characters. How can I make this simple program better?

string original = Console.ReadLine();
string encrypted = "";
int key = 1;
foreach (var l in original)
{
    if (!l.Equals(' '))
    {
        if (l.Equals('z'))
        {
            char next = 'a';
            encrypted += next;
        }
        else
        {

            double next = (int)l + key;
            encrypted += (char)next;
        }
    }
    else
    {
        encrypted += ' ';
    }
}
Console.WriteLine(encrypted);


texts:
I would like to plot the following function:

$$
\begin{align}
\Lambda(\delta\tau) &\equiv\ \chi(\delta\tau, 0)
= \frac{1}{T_i} \int_0^{T_i} a(t_0+t')a(t_0+t'+\delta\tau) dt' \\
&= \begin{cases}
   1 - \frac{\left|\delta\tau\right|}{\tau_c}, &\left|\delta\tau\right| \le \tau_c(1+\frac{\tau_c}{T_i}) \\
   -\frac{\tau_c}{T_i}, &\left|\delta\tau\right| \gt \tau_c(1+\frac{\tau_c}{T_i}) \\
   \end{cases}
\end{align}
$$
which represents a simple triangular shape.
There is a conditional statement. My implementation uses a for loop as follows:

def waf_delay(delay_increment):
    for d in delay_increment:
        if np.abs(d) <= delay_chip*(1+delay_chip/integration_time):
            yield 1 - np.abs(d)/delay_chip
        else:
            yield -delay_chip/integration_time;

integration_time = 1e-3 # seconds
delay_chip =  1/1.023e6 # seconds

x=np.arange(-5.0, 5.0, 0.1)
y=list(waf_delay(x))
plt.plot(x, y)
plt.show()

Is there a more correct way to transform an array based on a condition rather than just looping through it? Instead of having something like this:

def f(x_array):
    for x in x_array:
        if np.abs(x) <= 3:
            yield 1 - x/3
        else:
            yield 0

x=np.arange(-5.0, 5.0, 0.1)
y=list(f(x))
plt.plot(x, y)
plt.show()

I would like to write something like this:

def f(x):
        if np.abs(x) <= 3:
            yield 1 - x/3
        else:
            yield 0

x=np.arange(-5.0, 5.0, 0.1)
plt.plot(x, f(x))
plt.show()

that could take an array.


texts:
I have a database (PostgreSQL) from which I want to migrate some data to a MS SQL Server database. I decided to use a code first approach. The question is related to the proper way of feeding my new tables.

Model.cs:

public class Info
{
    [Key]
    public int InfoID { get; set; }
    public int NameID { get; set; }
    public string Name { get; set; }
}

DatabaseInitializer:

  private void SeedInfos(SomeContext context)
    {
        var Infos = new List<Info>();

using (var com = new NpgsqlCommand(PostgresSQLs.GetAllInfos, EstablishedConnection()))
        {
            using (var r = com.ExecuteReader())
            {
                while (r.Read())
                {
                    Infos.Add(new Info { InfoID= Convert.ToInt32(r["infoID"]), NameID = Convert.ToInt32(r["NameId"]), Name = r["Name"].ToString()});
                };
            }
        }
        foreach (var Usr in Users)
            context.Infos.Add(Usr);
    }

One of my concerns is related to the static class PostgreSQL where I store queries which are retrieving the data I need from PostgreSQL. Is it a proper approach? The more complicated query, the more complex code, so it may be hard to maintain later, isn't it? What approach would you use?

Besides, such data feeding may cost a lot of memory in case the table is big. Is there a possibility to avoid memory leaks?


texts:
Both these functions take in a sentence and generate a random string based of the length of sentence.

Mine, the first one, runs 4 times more slowly than the second one (someone else's code), but I don't know why and I'd like to understand what's happening 'under the hood' that makes it this way. If anything I would've expected numpy to be faster, which makes me think it's something else entirely.

Also, is there a way to make the first function even faster?

import random
import numpy as np

def generate_guess(sentence):
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']
    return [np.random.choice(alphabet) for i in range(len(sentence))]

Don't review this one:

def generate_guess(sentence):
  alphabet = 'abcdefghijklmnopqrstuvwxyz '
  res = ''
  for i in range(len(sentence)):
      res = res + alphabet[random.randrange(len(alphabet))]
  return res


texts: Choosing between a Template Wrapping vs. Inheritance Technique

texts:
I wanted to introduce logging to potentially many classes in the future and I am curious about the best techniques. Personally, I would go the AOP way, but within C++, and having my compiler constrained, using a AOP compiler/library is not feasible.
At any rate, I was playing around with some potential approaches and currently have two, an inheritance implementation and a template wrapping implementation. Below is a complete example.
#include <iostream>

/*********************************************
    Inheritance technique
*********************************************/
class Measurements
{
    public:
        void start() { std::cout << "start" << std::endl; }
        void end() { std::cout << "end" << std::endl; }
};

class InheritanceOp: public Measurements
{
    public:
        void myop() { start(); std::cout << "in myop" << std::endl; end(); }
};

/******************************************
    template wrapper technique
*******************************************/
namespace components{
    class Operation
    {
        public:
            void myop() { std::cout << "in myop" << std::endl; }
    };
}
namespace aspects{
    template <class OP>
    class Measurements_Aspect: public OP
    {
        public:
        void start() { std::cout << "start" << std::endl; }
        void end() { std::cout << "end" << std::endl; }

        void myop()
        {
            start();
            OP::myop();
            end();
        }
    };
}
namespace configuration{
    using Operation = aspects::Measurements_Aspect<components::Operation>;
}
using namespace configuration;

int main()
{
    Operation op;
    op.myop();

    InheritanceOp iop;
    iop.myop();
}

I can see some shortcomings of both and I believe it's strongly a case-by-case decision, but I was hoping I could get some opinions on the two techniques, thanks!


texts: Is using beforeFind() event in background to dynamic update SQL queries a good practice?

texts:
I have a Projects table, which I need to ORDER BY code column. But problem is code is not a simple INT, but a VARCHAR specifying multiple level (like 01-15_33/23). So I need to sort by first part, then next, and so on.

One of the option I found is to replace order field everywhere with a complex array

    $orderAsc = [
        "cast(Projects.code as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'_', -1) as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'-', -1) as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'/', -1) as unsigned)",
        "Projects.code"
    ];

This is the other solution I wrote.

public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) {
    $commonOrder = ["Projects.code REGEXP '^[0-9]+' DESC"];

    $orderAsc = [
        "cast(Projects.code as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'_', -1) as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'-', -1) as unsigned)",
        "cast(SUBSTRING_INDEX(Projects.code,'/', -1) as unsigned)",
        "Projects.code"
    ];
    $orderDesc = array_map(function($value) { return $value . ' DESC'; }, $orderAsc);

    $orderAsc = implode(',', array_merge($commonOrder, $orderAsc));
    $orderDesc = implode(',', array_merge($commonOrder, $orderDesc));

    // Order project ascending if no order is specified
    $query->order($orderAsc);

    // Process ['Projects.code' => 'DESC'] and ['Projects.code' => 'ASC'] intelligently
    // Doesn't support other notation like ['Projects.code ASC'] for now
    $query->traverse(function ($conditions, $clause) use ($orderAsc, $orderDesc) {
        if (!empty($conditions)) {
            $conditions->iterateParts(function ($c, &$key) use ($orderAsc, $orderDesc) {
                if ('projects.code=asc' == strtolower("$key=$c")) {
                    $c = $orderAsc;
                    $key = null;
                }
                if ('projects.code=desc' == strtolower("$key=$c")) {
                    $c = $orderDesc;
                    $key = null;
                }
                return $c;
            });
        }
    }, ['order']);
}

It process everything in background. And you don't have to change your code at all anywhere.

One of the other advantage I found is, it works well with Pagination feature which generate ORM query in background. But I feel a developer who is new to this project won't understand what's happening at all.

Any feedback regarding the code I wrote or the thinking behind it is welcomed.


texts: Find the uncommon elements from two sets

texts:
I am trying to find the uncommon elements from two sets in Java. Here is my way:

private void findUnCommon{

    Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
    Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 5, 6));
    // get all elements from set a and set b

    System.out.println("Before..");
    System.out.println("a is : " + a);
    System.out.println("b is : " + b);

    Set<Integer> result = new HashSet<>(a);
    result.removeAll(b);
    System.out.println("result is : " + result);

    Set<Integer> temp = new HashSet<>(b);
    temp.removeAll(a);
    System.out.println("temp is : " + temp);

    result.addAll(temp);
    System.out.println("Uncommon elements of set a and set b is : "
        + result);

    System.out.println("After..");
    System.out.println("a is : " + a);
    System.out.println("b is : " + b);
}

I have declared two extra sets.  Can this be improved?


texts: Readable code with many components (Swing)

texts:
Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?

package newpackage.view;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class UserPanel extends JPanel{

    private JLabel idLbl;
    private JLabel nameLbl;
    private JLabel passwordLbl;
    private JRadioButton adminRad;
    private JRadioButton userRad;
    private JTextField idFld;
    private JTextField nameFld;
    private JPasswordField passwordFld;
    private JButton submitBtn;

    public UserPanel() {
        setLayout(new GridLayout(4,2));
        idLbl = new JLabel("ID");
        nameLbl = new JLabel("Name");
        passwordLbl = new JLabel("Password");
        adminRad = new JRadioButton("Admin");
        userRad = new JRadioButton("User");
        idFld = new JTextField();
        nameFld = new JTextField();
        passwordFld = new JPasswordField();
        submitBtn = new JButton("Submit");
        add(idLbl);
        add(idFld);
        add(nameLbl);
        add(nameFld);
        add(passwordLbl);
        add(passwordFld);
        add(adminRad);
        add(userRad);
        add(submitBtn);
    }
}


texts:
Ok this is the first makefile I've ever written. I it works and that's about it. Things that I was wondering if if I can specify where the object files go. It looks really bad with all the .o files cluttering the working folder. I was thinking a src folder and maybe a obj folder? Is there a better naming convention for Compiler_flags and c_compiler_flags? Also is there other ways of optimizing the makefile? Thanks all help is extremely appreciated.

OBJS = close.o init.o main.o texture.o load_media.o
CC = g++
COMPILER_FLAGS = -w
C_COMPILER_FLAGS = -c -w
LINKER_FLAGS = -lSDL2 -lSDL2_image -lSDL2_mixer -lSDL2_ttf
OBJ_NAME = run

all : exe

debug : COMPILER_FLAGS += -g
debug : C_COMPILER_FLAGS += -g
debug : exe

exe : $(OBJS)
    $(CC) $(OBJS) $(COMPILER_FLAGS) $(LINKER_FLAGS) -o $(OBJ_NAME)

close.o : isolation.h close.cpp
    $(CC) $(C_COMPILER_FLAGS) $(LINKER_FLAGS) close.cpp

init.o : isolation.h init.cpp
    $(CC) $(C_COMPILER_FLAGS) $(LINKER_FLAGS) init.cpp

main.o : isolation.h main.cpp
    $(CC) $(C_COMPILER_FLAGS) $(LINKER_FLAGS) main.cpp

texture.o : isolation.h texture.h texture.cpp
    $(CC) $(C_COMPILER_FLAGS) $(LINKER_FLAGS) texture.cpp

load_media.o : isolation.h load_media.cpp
    $(CC) $(C_COMPILER_FLAGS) $(LINKER_FLAGS) load_media.cpp

clean:
        \rm *.o *~ run


texts: Simulating the martingale betting system with roulette

texts:
I wrote a program that simulates many instances of trying the martingale betting system with roulette in Haskell.

At the answerer's suggestion I opted to leave the IO monad in main and ensure that the functions martingale and martingale', which handled the actual testing, were entirely pure, but the answerer also suggested that I could push my call to newStdGen all the way down into martingale'. I believe this would remove the requirement that my functions even require a StdGen as an argument.

My question then: Is it more natural for functions that compute random variable x to require StdGens as an argument, or for them to create StdGens and perhaps return IO x? Also, is my source code posted below reasonable and could it be improved or made more natural?

-- file: Martingale.hs
-- a program to simulate the martingale doubling system

import System.Random (randomR, newStdGen, StdGen)
import System.Environment (getArgs)
import Control.Monad (replicateM)

red = [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36]

martingale :: StdGen -> Bool
martingale = martingale' 1 0

martingale' :: Real a => a -> a -> StdGen -> Bool
martingale' bet acc gen
  | acc >= 5     = True
  | acc <= -100  = False
  | otherwise    =
    let (randNumber, newGen) = randomR (0,37) gen :: (Int, StdGen)
    in if randNumber `elem` red
       then martingale' 1 (acc + bet) newGen
       else martingale' (bet * 2) (acc - bet) newGen

main :: IO ()
main = do
  args <- getArgs
  let iters = read $ head args
  gens <- replicateM iters newStdGen
  let results = map martingale gens
      countWins = length $ filter (== True) results
      prob = fromIntegral countWins / fromIntegral iters
  print prob


texts: Look up parameters based on a numpy array of input values

texts:
Aim: Write a function that looks up empirical parameters A, B and C for a  solar radiation model. Each parameter has a value for a certain interval of time, represented as the day of the year. For now, I basically translate the four-column (day_of_year-interval, A, B, C) table that I have on paper into the following look up. The function works, but I have a feeling that this is not the most Pythonic way to do it.

Current implementation:

import numpy as np

def lookup_DNI_parameters(day_of_year):
    """Sets parameters A, B, and C for the calculation of direct normal irradiance
    based on day of year-intervals.

    A is in W/m^2
    B and C are dimensionless
    """
    A = np.empty_like(day_of_year)
    B = np.empty_like(day_of_year)
    C = np.empty_like(day_of_year)

    # generate boolean indices for each day_of_year-interval
    interval_1 = np.logical_and(day_of_year >=1, day_of_year < 32)
    interval_2 = np.logical_and(day_of_year >= 32, day_of_year < 60)
    interval_3 = np.logical_and(day_of_year >= 60, day_of_year < 91)
    interval_4 = np.logical_and(day_of_year >= 91, day_of_year < 121)
    interval_5 = np.logical_and(day_of_year >= 121, day_of_year < 152)
    interval_6 = np.logical_and(day_of_year >= 152, day_of_year < 182)
    interval_7 = np.logical_and(day_of_year >= 182, day_of_year < 213)
    interval_8 = np.logical_and(day_of_year >= 213, day_of_year < 244)
    interval_9 = np.logical_and(day_of_year >= 244, day_of_year < 274)
    interval_10 = np.logical_and(day_of_year >= 274, day_of_year < 305)
    interval_11 = np.logical_and(day_of_year >= 305, day_of_year < 335)
    interval_12 = day_of_year >= 335

    # set parameter values based on the interval
    A[interval_1] = 1230.0
    A[interval_2] = 1215.0
    A[interval_3] = 1186.0
    A[interval_4] = 1136.0
    A[interval_5] = 1104.0
    A[interval_6] = 1088.0
    A[interval_7] = 1085.0
    A[interval_8] = 1107.0
    A[interval_9] = 1152.0
    A[interval_10] = 1193.0
    A[interval_11] = 1221.0
    A[interval_12] = 1234.0

    B[interval_1] = 0.142
    B[interval_2] = 0.144
    B[interval_3] = 0.156
    B[interval_4] = 0.180
    B[interval_5] = 0.196
    B[interval_6] = 0.205
    B[interval_7] = 0.207
    B[interval_8] = 0.201
    B[interval_9] = 0.177
    B[interval_10] = 0.160
    B[interval_11] = 0.149
    B[interval_12] = 0.142

    C[interval_1] = 0.058
    C[interval_2] = 0.060
    C[interval_3] = 0.071
    C[interval_4] = 0.097
    C[interval_5] = 0.121
    C[interval_6] = 0.134
    C[interval_7] = 0.136
    C[interval_8] = 0.122
    C[interval_9] = 0.092
    C[interval_10] = 0.073
    C[interval_11] = 0.063
    C[interval_12] = 0.057

    return A, B, C

# test an array of a few sample days for correctness of results
days = np.array([21., 80., 141., 202., 264., 325.])
A, B, C = lookup_DNI_parameters(days)
print A # [1230, 1186, 1104, 1085, 1152, 1221]
print B # [0.142, 0.156, 0.196, 0.207, 0.177, 0.149]
print C # [0.058, 0.060, 0.071, 0.121, 0.136, 0.092, 0.063]


texts: How to deal with interface inheritance and common properties?

texts:
I'm trying to design a generic caching system that takes keyed items and allows either read-only or read-write access to a cached version of it. The read-only backing interface is:

public interface IReadableItem<TKey>
{
  TKey Key { get; }
}

However, I need to be able to dynamically update the key of my writable items. I've come up with two options, but both are unappealing.

I can forgo the inheritance:

public interface IWritableItem<TKey>
{
  TKey Key { get; set; }
}

... but this leaves me in a situation where I have to specify that every class is both an IWritableItem and an IReadableItem in order to allow read-write access.

On the other hand, I can use the new keyword to override the underlying inheritence:

public interface IWritableItem<TKey> : IReadableItem<TKey>
{
  new TKey Key { get; set; }
}

... but this leaves me with a bad code-smell, especially when attempting to explicitly implement the interface at the class level.

Is this a situation where I should just take the lesser of two evils, or is there a Third Way?


texts: Building a better Data Access Layer Class

texts:
Since I am new to MVC and the Entity Framework, I have been struggling to grasp the concept of creating useful Data and Service layers. I have come across a scenario where I believe my code has become very redundant:

Data Access Layer:

public static class DeploymentOrderDataLayer
    {

     public static usr_OrderFulfillment GetScannedItem(string orderNumber, string itemNumber)
        {
            using (TPGContext context = new TPGContext())
            {
                return context.usr_OrderFulfillment.FirstOrDefault(x => x.SOPNUMBE == orderNumber && x.ItemNumber == itemNumber);
            }
        }

    public static void UpdateScannedItem(string orderNumber, string itemNumber, string user, string serialNumber)
        {
            using (TPGContext context = new TPGContext())
            {
                var result = context.usr_OrderFulfillment.FirstOrDefault(x => x.SOPNUMBE == orderNumber && x.ItemNumber == itemNumber);

                result.IsFulfilled = true;
                result.FulfilledBy = user;
                result.DateFulfilled = DateTime.Now;

                if (!string.IsNullOrEmpty(serialNumber))
                {
                    result.SerialNumber = serialNumber;
                }

                context.SaveChanges();
            }
        }
}

I call all of my Data Layers through a BusinessLayer, which handles my business logic:

public class DeploymentOrderBusinessLayer
    {

    public static void UpdateScannedItem(string orderNumber, string itemNumber, string user, string serialNumber = "")
            {

                    var itemInfo = DeploymentOrderDataLayer.GetScannedItem(orderNumber, itemNumber);

                    if (itemInfo == null) throw new BusinessException("Item number not found.");

                    if (itemInfo.IsFulfilled) throw new BusinessException(string.Format("Item already fulfilled by {0}", itemInfo.FulfilledBy));

                DeploymentOrderDataLayer.UpdateScannedItem(orderNumber, itemNumber, user, serialNumber);
            }

   }

The BusinessLayer then gets called from my DeploymentOrder Controller:

 try
        {

          DeploymentOrderBusinessLayer.UpdateScannedItem(orderNumber, itemNumber, User.Identity.Name);

        }
        catch (BusinessException ex)
        {
            ViewBag.AlertMessage = ex.Message;
        }

A couple things that bug me:

I'm calling GetScannedItem in my business layer so that I can do my validation first, before anything gets updated.  When I'm ready to update, I have to re-query the database again, so that I can update my context.  This extra hit to the database seems unnecessary to me, but I'm not sure how to fix it.
The DeploymentOrderDataLayer is fine for my DeploymentOrderController, but useless for any other controllers that might need to access similar data.  I would like my Data Layers to be more dynamic.

Any suggestions are appreciated.


texts: LeetCode 928: Minimize Malware Spread II

texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem
(This problem is the same as Minimize Malware Spread, with the differences bolded.)
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware.  Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware.  This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.
We will remove one node from the initial list, completely removing it and any connections from this node to any other node.  Return the node that if removed, would minimize M(initial).  If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:

Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1

Example 3:

Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1

Note:

\$1 < \text{graph}.\text{length} = \text{graph}[0].\text{length} <= 300\$
\$0 <= \text{graph}[i][j] == \text{graph}[j][i] <= 1\$
\$\text{graph}[i][i] = 1\$
\$1 <= \text{initial}.\text{length} < \text{graph}.\text{length}\$
\$0 <= \text{initial}[i] < \text{graph}.\text{length}\$

Inputs
[[1,1,0],[1,1,0],[0,0,1]]
[0,1]
[[1,1,0],[1,1,1],[0,1,1]]
[0,1]
[[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]]
[0,1]

Outputs
0
1
1

Code
#include <cstdint>
#include <vector>
#include <queue>
#include <unordered_set>
#include <algorithm>

struct Solution {
    using uint16 = std::uint_fast16_t;
    int minMalwareSpread(
        std::vector<std::vector<int>>& graph,
        std::vector<int>& initial
    ) {
        uint16 smallest_node = 0;
        uint16 initial_len = std::size(initial);
        uint16 min_len = std::size(graph);
        std::sort(std::begin(initial), std::end(initial));

        for (const auto init_node : initial) {
            const uint16 curr_len = breadthFirstSearch(graph, initial, init_node);

            if (curr_len < min_len) {
                min_len = curr_len;
                smallest_node = init_node;
            }
        }

        return smallest_node;
    }

private:
    static uint16 breadthFirstSearch(
        const std::vector<std::vector<int>>& graph,
        std::vector<int>& initial,
        uint16 node
    ) {
        std::queue<uint16> nodes_queue;
        std::unordered_set<uint16> nodes_set = {node};
        uint16 count = 0;

        for (const auto init_node : initial) {
            if (init_node != node) {
                nodes_queue.push(init_node);
            }
        }

        while (!nodes_queue.empty()) {
            uint16 curr_node = nodes_queue.front();
            nodes_queue.pop();

            if (nodes_set.count(curr_node)) {
                continue;
            }

            nodes_set.insert(curr_node);
            ++count;

            for (uint16 index = 0; index < std::size(graph); ++index) {
                if (index != curr_node && graph[curr_node][index]) {
                    nodes_queue.push(index);
                }
            }
        }

        return count;
    }
};

References

Problem

Discuss

Solution


texts: Fractional knapsack implementation in Python

texts:
def get_optimal_value(capacity, weights, values):
    value = 0.
    remaining_capacity = capacity
    # compute value per unit
    values_per_unit = [v / float(w) for w, v in zip(weights, values)]
    while remaining_capacity > 0:
        value_and_index = get_max_value_per_unit(values_per_unit)
        replace_max_value(values_per_unit, value_and_index["index"])

        weight = weights[value_and_index["index"]]
        value_per_unit = value_and_index["value"]

        if remaining_capacity >= weight:
            remaining_capacity = remaining_capacity - weight
            value = value + (weight * value_per_unit)
        elif remaining_capacity < weight:
            value = value + (min(remaining_capacity, weight) * value_per_unit)
            acceptable_capacity = min(remaining_capacity, weight)
            remaining_capacity = remaining_capacity - acceptable_capacity
    return value

def get_max_value_per_unit(values_per_unit):
    idx = values_per_unit.index(max(values_per_unit))
    value = values_per_unit[idx]
    return {'value': value, 'index': idx}

def replace_max_value(values_per_unit, idx):
    values_per_unit[idx] = -1

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value))

Input:

5 100
60 20
100 50
120 30
90  10
10  10

Run:

python [filename].py < input.txt

Question:

The goal of the algorithm above, is to make sure the knapsack has the highest value. Can we further improve the implementation above?


texts: Finding the maximum of an array to solve a rope-burning puzzle

texts:
I am trying to get the maximum value out of this array.

There is a long rope of length totalLength at its each unit length some ropes are tied pointing in upper and lower directions with their length given. I am saving them in upper and lower arrays. Question is if we light up the front end how much time it will take to burn the whole rope. The fire spreads at 1m/s.

These two arrays upper and lower they have some value and the I am adding the max of them in each iteration and at the end I am finding the max value.

My idea is the total time taken will be equal to burning the longest part of the rope. I am finding the longest part and displaying it. It seems like this code is not good enough and is not clearing the time limits.

import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {

        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();//total test cases;
        int totalLength = 0;
        int maxSum = 0, maxUL = 0;
        int[] upper;
        int[] lower;
        int[] result;
        while(N-- > 0) {

              maxSum = 0;

              totalLength = scan.nextInt();// total length of a base graph
              upper = new int[totalLength - 1];
              lower = new int[totalLength - 1];
              result = new int[totalLength - 1];
              for(int i = 0; i < totalLength - 1; i++){
                upper[i] = scan.nextInt();
              }

             for(int i = 0; i < totalLength - 1; i++){
                lower[i] = scan.nextInt();
              }

              for(int i = 0; i <= totalLength - 2; i++){
                   maxUL = (upper[i] > lower[i]) ? upper[i]: lower[i];
                   maxSum = i+1 + maxUL;
                   result[i] = maxSum;
              }

              int maxVal = 0;
              for(int i = 0; i < result.length; i++){
                if(maxVal < result[i]){
                    maxVal = result[i];
                }
              }
              System.out.println(maxVal);
        }
    }
}

Sample Input

1 // for the test cases
5 // the totallength of the main rope
1 0 2 2
1 1 1 0

Output

6


texts: City and District class examples for teaching OOP in PHP

texts:
I wrote these two classes for teaching OOP in PHP. Do you think it's breaking some good practices or SOLID principles?

<?php

class City
{
    private $id;
    private $name;
    private $districts = [];

    public function __construct($id, string $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

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

    public function name():string
    {
        return $this->name;
    }

    public function addDistrict(District $district)
    {
        if (!isset($this->districts[$district->id()])) {
            $this->districts[$district->id()] = new District($district->id(), $this, $district->name());
        }
    }

    public function getArray():array
    {
        $districts = [];
        foreach ($this->districts as $district) {
            array_push($districts, $district->getArray());
        }
        return ['id' => $this->id(), 'name' => $this->name(), 'districts' => $districts];
    }

    public function districts():array
    {
        return $this->districts;
    }
}

class District
{
    private $id;
    private $cityId;
    private $name;

    public function __construct($id, City $city, string $name)
    {
        $this->id = $id;
        $this->name = $name;
        $this->cityId = $city->id();
    }

    public function getArray():array
    {
        return ['id' => $this->id, 'name' => $this->name];
    }

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

    public function name():string
    {
        return $this->name;
    }
}


texts: What are the downsides of stateful socket NodeJS server comparing to a regular stateless REST server?

texts:
I've built this NodeJS server architecture 5 years ago. The project was in production all this time, I've been maintaining it actively, adding a lot of new features, and had no troubles with this architecture. So, now I have a budget to refactor it fundamentally. I'm considering if I should keep this architecture or move to the common REST architecture.
The project consists of a mobile app, web app, admin panel (also a web app), and a NodeJS server.
All 3 client-side parts are using Redux under the hood with socket.io sending actions with SOCKET/ prefix right to the server. The server accepts those actions and responds to them as many times as needed at any time.
I know where to improve the code, so, pls don't waste your time reviewing the code quality.
What I'm looking for is a review of this architecture. What are the downsides? Why I should use stateless REST instead of a stateful socket connection? Maybe it
I guess I'll omit the explanation of what are the pro-s of using this architecture for me, as it's not helpful in this context.
Probably, relevant info about this project:

This is enterprise software that will never exceed 2-3 thousand active users.
Vast majority of actions do not require real-time capabilities and would work just fine with question-answer model.
At the moment we have ~600 active users and still using $24/month GCP instance.

Here is the essence:
import http from 'http'
import express from 'express'
import socketIo from 'socket.io'
import EventEmitter from './EventEmitter'
import actions from './actions'

const socket = async (server) => {
  const io = socketIo(server)
  const connectedUsers = new Map()
  io.use(/*authorization middleware*/)
  io.on('connection', async socket => {
    const eventEmitter = new EventEmitter({ socket })
    console.info(`=== v.${config.version} New connection ===`)

    const sessionData = new Map()
    sessionData.set('role', 'notLogedInUser')
    sessionData.set('clientVersion', socket.authorizationData.clientVersion)

    socket.emit('connected')
    const emitAction = (actionType, actionPayload) => socket.emit('action', {
      type: actionType,
      payload: actionPayload
    })

    if (socket.authorizationData.authorized) {
      const user = await db.users.findById(socket.authorizationData.userId)
      sessionData.set('_id', user._id.toString())
      // ...assigne other important user's props to sessionData
      socket.on('action', async (action = {}) => {
        const { type, payload } = action
        if (!actions[type]) {
          return emitAction('SNACK', 'Invalid action type')
        }
        actions[type]({
          payload,
          emitAction,
          sessionData
        })
      })
    } else {
      emitAction('SNACK', 'Unauthorized')
    }

    socket.on('disconnect', () => {
      console.info(`=== ${socket.id} has disconnected ===`)
      connectedUsers.delete(socket.id)
    })
  })
}

let app = express()

app.server = https.createServer(app)

app.server.listen(config.port, '::', () => {
  socket(app.server, config.port, config.hostname)
})

export default app

Thanks


texts:
Several months ago, I asked Program to count vowels, which was asking for a code review of a vowel counting function in implemented in Python.

Since I've been trying to learn Ruby, I decided to reimplement the entire program in it. I'm mainly looking for critiques on:

Naming conventions
Best practices for string iteration
do/end vs {}
Coding standards and best practices

Of course there are some slight changes in how I implemented this in ruby vs Python. The biggest being simply using a Hash since I couldn't find a suitable replacement for Python's tuples. On a unrelated side note, is there a replacement for Python's tuples in ruby?

def count_vowels(string)
    # Create a function that will receive a string. The
    # function will count each vowel in the string and
    # return a count of all the vowels, whether found or not,
    # each being a `key, value` in a Hash.
    vowels = {"a" => 0, "e" => 0, "i" => 0, "o" => 0, "u" => 0}
    string.each_char do |chr|
        if vowels.has_key?(chr)
            vowels[chr] += 1
        end
    end
    return vowels
end


texts: Critique & improve a file reading routine

texts:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun read-sim-file (filename)
  "Reads file.
File is presumed to be the output from a simulation.

Returns lines from the simulation as a list of strings

We throw an error if TRAP ET is detected.

Lines with DBG_INT are ignored."
  (let ((file-text-list (split "\\n"
                   (batteries:read-text-file filename)))
    (return_list '()))

    (loop for line in file-text-list do
     (cond ((scan "DBG_INT" line)
        )  ; intentional newline.
           ((scan "TRAP ET" line)
        (error "Trap ET detected"))
           (t
        ;; There's got to be a cleaner method here.
        (setf return_list (append return_list (list line))))))
    return_list))

This code is ugly.
In particular, the (setf X (append X Y)) idiom feels hideously clunky.

Comments on how to make this more beautiful?

Possibly REMOVE-IF?


texts:
I decided to learn generic programming in C (and take a break from templates in C++) by implementing my first simple data structure in C: the singly linked list.

What I'm looking to gain out of reviews is:

Clarity/quality
Algorithmic correctness
Code style for C
Structure and design
Any bugs or issues you can find

I'm planning to use this as a basis for implementing a hash-map in C that uses chaining.

slist.h

#ifndef C_SLIST_H
#define C_SLIST_H

#include <stdbool.h>
#include <stddef.h>

struct slist_node;
struct slist;

typedef bool (*func_cmp)(const void *a, const void *b);

struct slist *slist_init(func_cmp cmp);

void slist_insert(struct slist *, void *);

void slist_free(struct slist *);

bool slist_empty(const struct slist *);

void *slist_value(const struct slist_node *);

struct slist_node *slist_find(const struct slist *, void *);

void clear(struct slist *);

size_t slist_size(const struct slist *);

void slist_remove(struct slist *, void *);
#endif

slist.c

#include <stdlib.h>
#include "slist.h"

struct slist_node {
    struct slist_node *next;
    void *data;
};

struct slist {
    struct slist_node *head, *tail;
    func_cmp compare;
};

static struct slist_node *create_node(void *value)
{
    struct slist_node *node = calloc(1, sizeof(*node));
    if (!node) { return NULL; }
    node->data = value;
    return node;
}

static bool default_compare(const void *a, const void *b)
{
    return a == b;
}

struct slist *slist_init(func_cmp func)
{
    struct slist *l = calloc(1, sizeof(struct slist));
    l->compare = func ? func : default_compare;
    return l;
}

void slist_insert(struct slist *l, void *value)
{
    if (!l) { return; }

    if (slist_empty(l)) {
        l->head = create_node(value);
        if (!l->head) { return; }
        l->tail = l->head;
        return;
    }

    l->tail->next = create_node(value);
    if (!l->tail->next) { return; }

    if (l->tail->next) {
        l->tail = l->tail->next;
    }
}

void clear(struct slist *l)
{
    if (!l) { return; }

    struct slist_node *copy = l->head;
    while (copy) {
        struct slist_node *after = copy->next;
        free(copy);
        copy = after;
    }

    l->head = NULL;
    l->tail = NULL;
}

void slist_free(struct slist *l)
{
    clear(l);
}

bool slist_empty(const struct slist *l)
{
    return l ? l->head == NULL : true;
}

void *slist_value(const struct slist_node *n)
{
    return n ? n->data : NULL;
}

size_t slist_size(const struct slist *l)
{
    if (!l || slist_empty(l)) { return 0; }

    const struct slist_node *copy = l->head;
    size_t size = 0;
    while (copy) {
        ++size;
        copy = copy->next;
    }
    return size;
}

static struct slist_node *slist_find_ahead(const struct slist *l, void *value)
{
    struct slist_node *copy = l->head;
    while (copy) {
        if ((l->compare)(copy->next->data, value)) {
            return copy;
        } else {
            copy = copy->next;
        }
    }
    return NULL;
}

struct slist_node *slist_find(const struct slist *l, void *value)
{
    if (!l || slist_empty(l)) { return NULL; }

    if ((l->compare)(l->head->data, value)) { return l->head; }

    const struct slist_node *found = slist_find_ahead(l, value);
    return found ? found->next : NULL;
}

void slist_remove(struct slist *l, void *value)
{
    if (!l || slist_empty(l)) { return; }

    if (l->head->data == value) {
        struct slist_node *copy = l->head;
        if (l->tail == l->head) {
            l->tail = copy->next;
        }
        l->head = copy->next;
        free(copy);
        return;
    }

    struct slist_node *ahead = slist_find_ahead(l, value);
    if (!ahead) { return; }

    if (ahead->next == l->tail) {
        l->tail = ahead;
    }
    struct slist_node *to_delete = ahead->next;
    ahead->next = ahead->next->next;
    free(to_delete);
}


texts: Arduino Code for Juggling Machine (Stepper Motors)

texts:
I have built a machine that juggles. An Arduino sends signals to stepper motor drivers that drive NEMA 23 size stepper motors.

Video of the machine: https://youtu.be/-9zD_8erkck
Currently, each arm makes one revolution and then pauses while the other arm makes one revolution. One arm starts before the other arm comes to a complete stop, the amount of overlap is captured by the variable stepover.
I would like to make the machine more consistent and run quieter with less vibration. How can I make it run smoother? Is there a way to do this where the hands will never come to a complete stop?
The stepper motors are running at 800 steps per revolution. I have tried to using more steps/rev for smoother operation, but the accelstepper library will not run the motors fast enough.
I have tried altering the values max_acceleration, max_speed, and stepover. I have not found a way to optimize these values.
#include <AccelStepper.h>
AccelStepper stepper1(AccelStepper::DRIVER, 9, 8);
AccelStepper stepper2(AccelStepper::DRIVER, 4, 3);

int start = 0;
int side = 0;
int max_speed = 6000;
int max_acceleration = 12000;
int stepover = 300;
int step_distance = 800;

void setup()
{
  stepper1.setMaxSpeed(max_speed);
  stepper2.setMaxSpeed(max_speed);
  stepper1.setAcceleration(1234);
  stepper2.setAcceleration(1234);
  stepper1.moveTo(600);
  stepper2.moveTo(-200);
}

void loop()
{
  // This code gets the arms in the right place before startup
  if (start == 0) {
    while (abs(stepper1.distanceToGo()) != 0) {
      stepper1.run();
    }
    while (abs(stepper2.distanceToGo()) != 0) {
      stepper2.run();
    }
    start = 1;
    stepper1.setAcceleration(max_acceleration);
    stepper2.setAcceleration(max_acceleration);
    delay(500);
  }

  // This code moves the left arm
  if (abs(stepper1.distanceToGo()) == 0
      and abs(stepper2.distanceToGo()) < stepover
      and side == 0) {
    stepper1.moveTo(step_distance + stepper1.currentPosition());
    side = 1;
  }

  // This code moves the right arm
  if (abs(stepper2.distanceToGo()) == 0
      and abs(stepper1.distanceToGo()) < stepover
      and side == 1) {
    stepper2.setCurrentPosition(0);
    stepper2.moveTo(step_distance);
    side = 0;
  }

  if (start == 1) {
    stepper2.run();
    stepper1.run();
  }
}


texts: Adding Youtube iframe API at runtime - React Component

texts:
So we created a component where we have a couple of Yotube iframes and we import the Youtube iframe API like this way. It's working and we achieve what we expected. I would appreciate any comments about this code!

componentDidMount() {
   this.init();

   window.onYouTubeIframeAPIReady = e => {
     this.YT = window.YT;

     this.individualsPlayer = new window.YT.Player(this.YTIndividualsRef, {
       events: {
         onStateChange: this.onPlayerStateChange
       }
     });

     this.managersPlayer = new window.YT.Player(this.YTManagersRef, {
       events: {
         onStateChange: this.onPlayerStateChange
       }
     });
   };
}

init() {
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}

onPlayerStateChange = e => {
  switch (e.data) {
    case window.YT.PlayerState.PLAYING:
      console.log('playing');
    break;
  }
}


texts: Python arbitrary objects Serialization and Deserialization

texts:
I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.
import json

Here is the first class
class Foo():
    def __init__(self,x,y,bar):
        self.x =x
        self.y = y
        self.bar = bar #Second class object is here

    def toJson(self):
        return json.dumps(Foo(self.x,self.y,self.bar).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Foo(
            x = data['x'],
            y = data['y'],
            bar = Bar.fromJson(data['bar'])
        )

Here is the second class
class Bar():
    def __init__(self, z):
        self.z = z

    def toJson(self):
        return json.dumps(Bar(self.z).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Bar(
            z = data['z'],
        )

Convert to Json
jsonData = Foo(100,500,Bar(900).toJson()).toJson()

Retrieve the Json and convert to Object
foo = Foo.fromJson(jsonData)

Print the Object attributes
print(foo.bar.z)

It works actually. But is there any memory leakage? Any security issue?


texts: Determine the number of factors of a large numbers efficiently

texts:
I am trying to determine the number of factors of a large number efficiently. I have written this function but how can it be improved upon?

long numOfFactors(long long n)
{
    long i=0,num=0;
    for(i=1;i<=n/2;i++)
    {
        if(n%i==0)
            num++;
    }
    return num;
}


texts:
Link here
I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review Python code. Both solutions share similar logic, so the review will apply to either.

Problem statement

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:
Input: s = ""
Output: 0

Example 4:
Input: s = "(()()()"
Output: 6

Example 5:
Input: s = "((())((((())))"
Output: 8

Both solutions are Oⁿ and pass all test cases including the time limit however, they are taking time more than I expected, specially the c++ version though both share the same logic. I need to improve time as a priority.
longest_parentheses.py
def check_longest(s):
    opened = []
    closed = []
    cum_distance = 0
    max_distance = 0
    for i, ss in enumerate(s):
        if ss == ')':
            if opened:
                closed.append((opened.pop(), i))
        if ss == '(':
            opened.append(i)
    closed = set(sum(closed, ()))
    for j in range(len(s)):
        if j in closed:
            cum_distance += 1
        else:
            cum_distance = 0
        max_distance = max(max_distance, cum_distance)
    return max_distance

if __name__ == '__main__':
    print(check_longest(')((()()()()'))

Stats:
Runtime: 272 ms, faster than 5.14% of Python3 online submissions for Longest Valid Parentheses.
Memory Usage: 15.5 MB, less than 6.57% of Python3 online submissions for Longest Valid Parentheses.

longest_parentheses.h
#ifndef LEETCODE_LONGEST_PARENTHESES_H
#define LEETCODE_LONGEST_PARENTHESES_H

#include <string_view>

int calculate_distance(size_t p_size, const std::vector<size_t> &closed);
int get_longest(const std::string_view &s);

#endif //LEETCODE_LONGEST_PARENTHESES_H

longest_parentheses.cpp
#include "longest_parentheses.h"
#include <vector>
#include <iostream>

int calculate_distance(size_t p_size, const std::vector<size_t> &closed) {
    int cum_distance = 0;
    int max_distance = 0;
    for (size_t i = 0; i < p_size; ++i) {
        if (std::find(closed.begin(), closed.end(), i) != closed.end()) {
            cum_distance++;
        } else {
            cum_distance = 0;
        }
        max_distance = std::max(max_distance, cum_distance);
    }
    return max_distance;
}

int get_longest(const std::string_view &s) {
    std::vector<size_t> opened, closed;
    for (size_t i = 0; i < s.size(); ++i) {
        auto ss = s[i];
        if (ss == ')') {
            if (!opened.empty()) {
                closed.push_back({opened.back()});
                closed.push_back(i);
                opened.pop_back();
            }
        }
        if (ss == '(') {
            opened.push_back(i);
        }
    }
    return calculate_distance(s.size(), closed);
}

int main() {
    std::cout << get_longest(")()())");
}

Stats:
Runtime: 1276 ms, faster than 5.09% of C++ online submissions for Longest Valid Parentheses.
Memory Usage: 9.3 MB, less than 5.04% of C++ online submissions for Longest Valid Parentheses.


texts:
I have just picked up Scala like 2 hours ago, and I am thinking of printing a series like 1 to 10 but in a recursive fashion. I do not understand what is wrong with this:

def printSeries(x:Int):Int = {
  if(x==0) doNothing() else doSomething()

  def doNothing()  = {}

  def doSomething() = {
    println(x)
    printSeries(x-1)
  }

}

Sorry, this might be very basic. Please point out my mistakes or any alternative and simpler implementation. (I do not want to use loops).

Thanks,


texts: Specifying UTC time or current time offset

texts:
What do you think about this helper class to specify UTC time? It should also support an easy way to capture current time offsets. Let's say we expose it in API like this:

interface IApi
{
    void Start(Utc at);
}

Now it should go as:

api.Start(new DateTime(2021, 01, 01)) // starts on 2021-01-01 UTC
api.Start(new TimeSpan(1, 0, 0)) // starts in one hour
api.Start(2000) // starts in 2 seconds

Library code is:

struct Utc
{
    public static Utc Now => 0;

    public static implicit operator Utc(DateTime value) => new Utc(value);
    public static implicit operator Utc(DateTimeOffset value) => value.UtcDateTime;
    public static implicit operator Utc(TimeSpan value) => DateTime.UtcNow + value;
    public static implicit operator Utc(int value) => TimeSpan.FromMilliseconds(value);

    public static implicit operator DateTime(Utc utc) => utc.Time;
    public static implicit operator DateTimeOffset(Utc utc) =>
        new DateTimeOffset(utc, TimeSpan.Zero);

    Utc(DateTime time) => Time = DateTime.SpecifyKind(time, DateTimeKind.Utc);
    DateTime Time { get; }
}


texts: Generating a table based on an array of objects

texts:
I have a React component that generates a table based on an array of objects, which gets populated with data in an object.

I'm trying to learn as much as I can about React.js / JavaScript. Could anyone with more experience in this area show me a way to simplify the code that I have here? Or if there are any other 'fancy' ways of doing what is being done in the code?

App.js

import React, { Component } from 'react';
import Table from './Table';

//Columns defines table headings and properties to be placed into the body
let columns = [
  {
    heading: 'Name',
    property: 'name'
  },
  {
    heading: 'Age',
    property: 'age'
  },
  {
    heading: 'Sex',
    property: 'sex'
  },
  {
    heading: 'Breed',
    property: 'breed'
  },
]

//Data is the array of objects to be placed into the table
let data = [
  {
    name: 'Sabrina',
    age: '6',
    sex: 'Female',
    breed: 'Staffordshire'
  },
  {
    name: 'Max',
    age: '2',
    sex: 'Male',
    breed: 'Boxer'
  }
]

class App extends Component {

  render() {
    return (
      <>

      </>
    );
  }
}

export default App;

Table.js

import React, { Component } from 'react';

class Table extends Component {

  buildTable = (columns, data, key) => {
    let headerRow = [];
    let dataRows = [];

    //Build the table header
    columns.forEach (col => {
      headerRow.push(
        <th key={`header-${col.heading}`}>{col.heading}
      );
    });

    //Build the rows
    data.forEach(item => {
      let dataCells = [];

      //Build cells for this row
      columns.forEach (col => {
        dataCells.push(
          <td key={`${item[key]}-${col.property}`}>{item[col.property]}
        );
      });

      //Push out row
      dataRows.push(
        <tr key={`${item[key]}-row`}>{dataCells}

      )
    });

    return(
      <>

{headerRow}

          {dataRows}

      </>
    );
  };

  render() {
    const {
      columns,
      data,
      propertyAsKey
    } = this.props;

    return (

        {this.buildTable(columns, data, propertyAsKey)}

    );
  }
}

export default Table;


texts: Count number of ways to paint a fence with N posts using K colors

texts:
A friend sent me this question, and I'd love somebody to review this and give his opinion.

  Write an algorithm that counts the number of ways you can paint a
  fence with N posts using K colors such that no more than 2 adjacent
  fence posts are painted with the same color"

Is this algorithm accurate? Could it be implemented in a better way?  Is there anything really un-pythonic that I did there?  I hope I haven't made any embarrassing mistakes.

def find_combinations(n, colours):

combos_list = []

    for i in range(1, n+1):

        #Check if the combos_list is empty (happens when post number == 1)
        if not combos_list:
            #Add all variations for when there's only one post
            for c in colours:
                combos_list.append([c])
        else:
            new_combo_list = []
            for combo in combos_list:
                for c in colours:
                    #Check if last 2 posts are from the same colour, meaning we can't add another one
                    if not combo[len(combo) - 2:] == [c, c]:
                        combo_to_add = combo[:]
                        combo_to_add.append(c)
                        new_combo_list.append(combo_to_add)
            combos_list = new_combo_list[:]

    return combos_list, len(combos_list)

colours = ["black", "white"]
n = 4

print find_combinations(n, colours)

Example of input:

  colours = ["a", "b"]
  n = 3

Output:

  a, a, b
  a, b, a
  a, b, b
  b, a, a
  b, a, b
  b, b, a

Number of combos - 6


texts:
I'm pretty proud of the following, but would welcome any comments from experts:

%% Provide with a Goal and it will iterate towards it.

guess(Goal, Res) :-
    guessIterate(Goal, [], Res).

guessIterate(Goal, Guesses, Res) :-
    makeGuess(Guess),
    check_against_guesses(Guess, Guesses),
    score(Guess, Goal, ThisScore),
    (
        %% if completely correct,...
        ThisScore == [4, 0]
    ->
        Res = Guess
    ;
        write(Guess), write(' '), write(ThisScore),nl,
        NewGuesses = [guess(Guess, ThisScore) | Guesses],
        guessIterate(Goal, NewGuesses, Res)
    ).

/*
If this Guess is correct, it will pedict the right results for previous guesses
*/
check_against_guesses(_, []).
check_against_guesses(Guess, [guess(Code, Score) | TGuesses]) :-
    score(Code, Guess, Score),
    check_against_guesses(Guess, TGuesses).

makeGuess(Guess) :-
    Colours = [red, blue, green, yellow, orange, purple, pink],
    member(G1, Colours),
    member(G2, Colours),
    member(G3, Colours),
    member(G4, Colours),
    Guess = [G1, G2, G3, G4].

/*
Score a guess, [#Black, #White], by first looking for exact matches - black - and then
look for inexaxct matches - white.
It is not possible for a guess of [...red, red...] to match twice with a
single 'red' in the Goal
*/

score(Guess, Goal, Res) :-
    pass1(Guess, Goal, [], Pass1Res),
    pass2(Guess, Pass1Res, Pass2Res),
    countUp(Pass2Res, [0,0], Res).

pass1(_, [], Acc, AccRev) :-
    reverse(Acc, AccRev).

pass1([HGuess | TGuess], [HGoal | TGoal], Acc, Res) :-
    (
        HGuess == HGoal
    ->
        AccNew = [black  | Acc]
    ;
        AccNew = [HGoal | Acc]
    ),
    pass1(TGuess, TGoal, AccNew, Res).

%% check each Guess element with Goal and change Goal element to 'white' if there is a match
pass2([], Goal, GoalRev) :-
    reverse(Goal, GoalRev).

pass2([HGuess | TGuess], Goal, Res) :-
    pass2Helper(HGuess, Goal, [], ModifiedGoal),
    pass2(TGuess, ModifiedGoal, Res).

pass2Helper(_, [], Acc, AccRev) :-
    reverse(Acc, AccRev).

pass2Helper(Guess, [HGoal | TGoal], Acc, Res) :-
    (
        Guess == HGoal
    ->
        reverse(TGoal, TGoalRev),
        %% Res = [white | TGoalRev]
        append(TGoalRev, [white | Acc], Res)
    ;
        AccNew = [HGoal | Acc],
        pass2Helper(Guess, TGoal, AccNew, Res)
    ).

countUp([], Acc, Acc).
countUp([HRes|TRes], [AccB, AccW|_], Res) :-
    (
        HRes == black
    ->
        AccBNew is AccB + 1,
        countUp(TRes, [AccBNew, AccW], Res)
    ;
        (
            HRes == white
        ->
            AccWNew is AccW + 1,
            countUp(TRes, [AccB, AccWNew], Res)
        ;
            countUp(TRes, [AccB, AccW], Res)
        )
    ).


texts: Attaching both mouseenter and mouseleave event handlers using jQuery

texts:
I'm a newbie to javascript, and day after day, I try to write better code with jQuery.

For example, I wrote this code earlier:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
});

What I want to happen with this code is when the mouse enters .foo the h1 gets a new background color or any style applying on class, hover.

Another example:

$$foo= $(".foo");

$$foo.mouseenter(function() {
    $(this).find('h1').addClass("hover");
    $(this).find('input').focus();
});

$$foo.mouseleave(function() {
    $("h1").removeClass("hover");
    $(".foo input").val('');
});

What I want to happen here is when the mouse enters .foo the input gets focus, and when mouse out the input's values are removed.

Both cases are working perfect, but I want to know if there is a better way to do this (mouse enter and mouse out)?


texts:
This was inspired by a Stack Overflow question about getting all the classes of an application and I took it a little too seriously (or perhaps not seriously enough).

It's rather silly to do it this way, but I believe the code below is guaranteed to find every class exposed in the scope it is called from...eventually. (As long as the class name is 255 chars or less.)

I'm looking for improvements on my coding style, hardcore criticism, and anything that would optimize this code.

application:didFinishLaunchingWithOptions

NSString * set = @"_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
NSInteger setLength = 255;
NSLog(@"Here we go!");
[Enumerator enumerateAllStringCombinationsInSet:set toMaximumLength:setLength withBlock:^(NSString *string) {
    Class class = NSClassFromString(string);
    if (class != nil) {
        NSLog(@"Found one! %@", string);
    }
}];

Enumerator.m

@implementation Enumerator

+ (void)enumerateAllStringCombinationsInSet:(NSString*)set toMaximumLength:(NSInteger)maximumLength withBlock:(void(^)(NSString *string))actionBlock {

    const char *charSet = [set UTF8String];

    NSInteger i, j, k;
    NSInteger setLength = [set length];
    NSInteger lastPlace = setLength-1;
    NSInteger activePlace = 0;

    NSInteger *places = calloc(maximumLength, sizeof(NSInteger));

    char lastChar = charSet[lastPlace];
    char *cStrBuffer = calloc(maximumLength, sizeof(char));

    BOOL go = true;

    while (go) {
        // increment active place
        for (j=0; j<setLength; ++j) {
            cStrBuffer[activePlace] = charSet[j];
            places[activePlace] = j;
            actionBlock([NSString stringWithUTF8String:cStrBuffer]);
        }

        for (i=activePlace; i >= 0; --i) {
            // check for carry over / overflow
            if (cStrBuffer[i] == lastChar) {
                // carry over, set to "zero" and defer processing to one place to the left.
                if (i == 0) {
                    if (++activePlace >= maximumLength) {
                        //  maximum size has been reached because all places are maxed out
                        go = false;
                        break;
                    }
                }

                cStrBuffer[i] = charSet[0];
                places[i] = 0;

                // otherwise, check previous char
            } else {

                // safe to increment this char up
                cStrBuffer[i] = charSet[places[i]+1];
                places[i] = places[i]+1;

                if (i<activePlace) {
                    // set all trailing figures to "zero"
                    for (k = i+1; k < activePlace; ++k) {
                        cStrBuffer[k] = charSet[0];
                        places[k] = 0;
                    }
                }
                break;
            }
        }
    }

    NSLog(@"Done!");
}

@end

Output:

Started at 3:07AM

2015-10-05 03:07:38.572 ClassFinder[59704:4595935] Here we go!
2015-10-05 03:09:29.770 ClassFinder[59704:4595935] Found one! NSSet
2015-10-05 03:09:29.774 ClassFinder[59704:4595935] Found one! NSURL
2015-10-05 03:10:27.769 ClassFinder[59704:4595935] Found one! UINib
2015-10-05 03:26:32.810 ClassFinder[59704:4595935] Found one! ALCity

It's now 3:29AM and it has made it all the way to the string AcAeZP.


texts:
I've built the beginnings of a numerology calculator, and would like an experienced javascript developer to review this code.

It works as expected, but I can't help but think there is a better way to write it instead of using multiple for loops.

There are a few calculations that have to be made, so I can't see any way around it. Any direction would be great.

function addNumbers(arr, fn) {
    var arrayTotal = [],
    singleDigits = [];

    for (i = 0; i < arr.length; i++) {
        arrayTotal.push(
            fn(arr[i])
        );
    }

    for (value in arrayTotal) {
        for (num in arrayTotal[value]) {
            singleDigits.push(parseInt(arrayTotal[value][num]));
        }
    }

    for (i = 0, sum = 0; i < singleDigits.length; i++) {
        sum += singleDigits[i];
    }

    for (i = 0, numericValue = 0, sum = fn(sum); i < sum.length; i++) {
        numericValue += parseInt(sum[i]);
    }

    return numericValue;
}

function splitNumbers(item) {
    return item.toString().split('');
}

var value = addNumbers([13, 11, 1938], splitNumbers);
document.body.innerHTML = value;


texts:
I'm new to writing VBA and having spent most of the day writing some code, I have finally got it working but it looks horrible. I'm hoping that someone can help me tidy it up.

The code simply copies certain cells from one sheet into another. If a particular cell in the source sheet contains the word "Accepted". Columns A of the source and destination sheets contain a unique reference and that data is only copied across if the unique reference is not already in the destination data. In addition, my code adds the date at which each entry is made in the destination sheet.

Ideally I need the code to look tidy and professional and probably most importantly be understandable to anyone looking at it, whether that be someone else or me in a years time - when I've forgotten what I did.

Public Sub UpdateAcceptedChangeRequests()

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

On Error GoTo errorHandler:

Dim varAnswer As String
    varAnswer = MsgBox("Are you sure you want to update the Accepted Change Requests List?", vbYesNo, "Update Accepted Change Requests")
        If varAnswer = vbNo Then
            MsgBox ("No changes saved")
                With Application
                    .ScreenUpdating = True
                    .EnableEvents = True
                End With
            Exit Sub
        End If

Dim SourceRange As Range, DestRange As Range
Dim DestSheet As Worksheet, SourceSheet As Worksheet
Dim LastRowDestSheet As Long, i As Long, LastRowSourceSheet As Long
    Set DestSheet = ThisWorkbook.Worksheets("Accepted Change Requests")
    Set SourceSheet = ThisWorkbook.Worksheets("All Change Requests")

        LastRowDestSheet = DestSheet.Cells(DestSheet.Rows.Count, "A").End(xlUp).Row
        LastRowSourceSheet = SourceSheet.Cells(SourceSheet.Rows.Count, "E").End(xlUp).Row

            For i = 2 To LastRowSourceSheet
                If SourceSheet.Range("E" & i).Value = "Accepted" Then
                    If Evaluate("ISERROR(MATCH(A" & i & ",'Accepted Change Requests'!A:A,0))") Then
                        DestSheet.Range("A" & LastRowDestSheet + 1 & ":D" & LastRowDestSheet + 1).Value = _
                            SourceSheet.Range("A" & i & ":D" & i).Value
                            With DestSheet.Range("E" & LastRowDestSheet + 1)
                                .Value = Date
                                .NumberFormat = "dd/mm/yyyy"
                            End With
                        LastRowDestSheet = LastRowDestSheet + 1
                    End If
                End If
            Next i

        With Application
        .ScreenUpdating = True
        .EnableEvents = True
        End With

Exit Sub

errorHandler:
MsgBox ("There was an error adding this Change Request")
Resume Next

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub


texts:
I wanted to write something that would be useful for the indices of a grid where if one walked off the edge of the grid they would re enter on the opposite side. This could in theory help with checking for special cases when checking for neighbours to a certain position on the grid. For example the neighbours of position (0, 0) on a 10 x 10 grid would be (0, 1), (1, 1), (1, 0), (9, 9), (0, 9), (1, 9), (9, 0), (9, 1).

def _adj_index(method):
    def _dec(instance, *args):
        if isinstance(args[0], int):
            index = args[0] % len(instance)
            return method(instance, index, *args[1:])
        return method(instance, args)
    return _dec

class Ring(list):
    """
    Ring datatype.
    """

    def __iter__(self):
        while True:
            for i in xrange(len(self)):
                yield self[i]

    def __getitem__(self, item):
        if isinstance(item, tuple):
            slice = item[0]
            return Ring([
                self[i]
                for i in xrange(slice.start, slice.stop, slice.step)])
        return super(Ring, self).__getitem__(item)

    __getitem__ = _adj_index(__getitem__)
    __setitem__ = _adj_index(list.__setitem__)
    __delitem__ = _adj_index(list.__delitem__)

    def __getslice__(self, i, j):
        return Ring([
            self[x]
            for x in range(i, j)])

I don't like the special case for __getitem__ of having to check if it is an integer or a tuple containing a slice.


texts: Created a DialogBuilder object, but having issues with subscribing/unsubscribing to dialog events

texts:
var WorkflowDialogBuilder = _.once(function () {
    'use strict';
    var workflowDialog = $('#WorkflowDialog');
    var workflowDialogContent = $('#WorkflowDialogContent');

     var events = {
        onApplyChangesSuccess: 'onApplyChangesSuccess',
        onValidationFailed: 'onValidationFailed',
        onDialogOpen: 'onDialogOpen'
    };

    var dialogConfig = {
        autoOpen: false,
        buttons: {
            OK: function () {
                var form = $(this).find('form');

                if (form.valid()) {
                    var self = this;
                    $.ajax({
                        type: "POST",
                        url: 'Form/Save',
                        dataType: 'json',
                        data: form.serialize(),
                        success: function (data) {
                            $(self).dialog('close');
                            $(self).trigger(events.onApplyChangesSuccess, data);
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                } else {
                    $(this).trigger(events.onValidationFailed);
                }
            },
            Cancel: function () {
                $(this).dialog('close');
            }
        },
        open: function () {
            $(this).trigger(events.onDialogOpen);
        }
    };

    workflowDialog.dialog(dialogConfig);

    return {
        onApplyChangesSuccess: function (event) {
            workflowDialog.on(events.onApplyChangesSuccess, event);
        },
        onDialogOpen: function (event) {
            workflowDialog.on(events.onDialogOpen, event);
        },
        onValidationFailed: function (event) {
            workflowDialog.on(events.onValidationFailed, event);
        },
        buildAddTaskDialog: function () {
            workflowDialogContent.load('NewTaskDetails', function () {
                //Load ViewModel client-side helpers and then when its ready, open the dialog.
                $.getScript('../Scripts/Orders/NewTaskDetailsModel.js', function () {
                    workflowDialog.dialog('open');
                });
            });
        },
        buildAddOrderDialog: function () {
            workflowDialogContent.load('NewOrderDetails', function () {
                //Load ViewModel client-side helpers and then when its ready, open the dialog.
                $.getScript('../Scripts/Orders/NewOrderDetailsModel.js', function () {
                    workflowDialog.dialog('open');
                });
            });
        }
    }
}

So, I've made the above builder. It is responsible for initializing a dialog element, opening it, and responding appropriately when the dialog closes.

Now, I was pretty happy with this implementation until I realized that, given the following scenario, events were subscribing and not unsubscribing.

//User calls WorkflowDialogBuilder.buildAddTaskDialog();
//NewTaskDetailsModel.js is loaded.
//NewTaskDetailsModel.js calls the following:

WorkflowDialogBuilder.onValidationFailed(function () {
    console.log("NewTaskDetailsMode.js onValidationFailed fired.");
});

//AddTaskDialog is closed by the user. NewTaskDetailsModel.js has already been loaded.
//AddTaskDialog continues to be subscribed to DialogBuilder's onValidationFailed.

//User calls WorkflowDialogBuilder.buildAddOrderDialog();
//User works with the dialog and clicks 'OK' to apply validation.
//AddTaskDialog's onValidationFailed event runs because WorkflowDialogBuilder triggers an event.

Now, I can think of one very simple solution to this. I could simply respond to the dialog's onClose event and, at that pont in time, unsubscribe all events.

Question: Does that seem like a proper solution? Or, have I gone down a bad path from the getgo and should rethink my architecture? If so, advice on how to restructure?


texts: Finding the minimum in a sorted, rotated array

texts:
Given an array that is first sorted non-decreasing and then rotated
  right by an unspecified number of times, find the index of its minimal
  element efficiently. If multiple such minimal elements exist, return
  the index of any one.

  Idea: Conceptually, divide the array into two parts: the "larger"
  subpart (to the left) which consists of large numbers brought here
  from the extreme right by rotation, and the "smaller" subpart which
  starts with the smallest element. We can always tell in which part we
  are, and move left/right accordingly.

Notes: When the array has multiple minimal elements, the index of the leftmost one in the "right" subpart is returned.

int getMinimIndex (const int *const a, size_t left, size_t right)
{
        assert(left<= right);

        // Special cases:
        // 1 If left & right are same , return
        if (left ==right)
                return left;

        // 2 For an array of size 2, return the index of minimal element
        if (left == right - 1)
                return a[left]<=a[right]?left:right;

        // 3 If the array wasn't rotated at all,
        if (a[left] < a[right])
                return left;

        // General case
        // Go to the middle of the array
        size_t mid = (left + right) >> 1;

        // If we stepped into the "larger" subarray, we came too far,
        // hence search the right subpart
        if (a[left] <= a[mid] )
                return getMinimIndex(a, mid, right);
        else
        // We're still in the "smaller" subarray, hence search left subpart
                return getMinimIndex(a,left, mid);
}

Unit tests:

\#define lastIndex(a)  ((sizeof(a)/sizeof(a[0]))-1)

int main()
{
        int a1[] = {7,8,9,10,11,3};
        int a2[] = {1};
        int a3[] = {2,3,1};
        int a4[] = {2,1};
        int a5[] = {2,2,2,2,2};
        int a6[] = {6,7,7,7,8,8,6,6,6};
        int a7[] = {1,2,3,4};

        printf("\n%d", getMinimIndex(a1,0, lastIndex(a1))); // 5
        printf("\n%d", getMinimIndex(a2,0, lastIndex(a2))); // 0
        printf("\n%d", getMinimIndex(a3,0, lastIndex(a3))); // 2
        printf("\n%d", getMinimIndex(a4,0, lastIndex(a4))); // 1
        printf("\n%d", getMinimIndex(a5,0, lastIndex(a5))); // 3
        printf("\n%d", getMinimIndex(a6,0, lastIndex(a6))); // 6
        printf("\n%d", getMinimIndex(a7,0, lastIndex(a7))); // 0

        return 0;

}


texts:
I've created a simple daily task scheduler but I'd like to change this to a general task scheduler accepting more advanced schedules.

I'd like to have some critiques from other sets of eyes on my current implementation before I continue.

public class ScheduleJob
{
    #region PRIVATE VARIABLES
    private readonly Timer  _timer;
    private Action          _job;
    private int             _setHour;
    private int             _setMin;
    #endregion

    #region CONSTRUCTOR
    public ScheduleJob()
    {
        _timer      = new Timer();
        _setHour    = 0;
        _setMin     = 0;
    }
    #endregion

    #region PUBLIC METHODS
    public void SetTimeofDay(int in_hour, int in_min)
    {
        _setHour = in_hour;
        _setMin = in_min;
    }
    public void SetJob(Action in_task)
    {
        _job = in_task;
    }
    public void Start()
    {
        try
        {
            int PeriodMin = GetHour() * 60 + GetMin(); //minute
            _timer.Interval = PeriodMin * 60 * 1000; //millisecond

            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();
            IsRunning = true;
        }
        catch (Exception)
        {
            IsRunning = false;
        }
    }
    public void Stop()
    {
        if (_timer != null)
            _timer.Stop();

        IsRunning = false;
    }
    #endregion

    #region PRIVATE METHODS
    private void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _timer.Enabled = false;

        _job(); //perform the job

        int PeriodMin = 24 * 60;
        _timer.Interval = PeriodMin * 60 * 1000;
        _timer.Enabled = true;
    }
    private int GetHour()
    {
        int _nowHour = DateTime.Now.Hour;

        if (_nowHour > _setHour)
        {
            return (24 - (_nowHour - _setHour));
        }
        else
        {
            return (_setHour - _nowHour);
        }
    }
    private int GetMin()
    {
        int _nowMin = DateTime.Now.Minute;

        if (GetHour() == 0)
        {
            if ((_setMin - _nowMin) <= 0)
            {
                return (24 * 60) + Math.Abs(_setMin - _nowMin);
            }
        }

        return (_setMin - _nowMin);
    }
    #endregion

    #region PROPERTIES
    public bool IsRunning { get; set; }
    #endregion
}


texts: ToastUtils - helper class for Android SDK Toast

texts:
Using:

ToastUtils.LONG.show(context, R.string.greeting);

Code:

public class ToastUtils {
    public static ToastUtils LONG = new ToastUtils(Toast.LENGTH_LONG);
    public static ToastUtils SHORT = new ToastUtils(Toast.LENGTH_SHORT);

    private final int duration;

    private ToastUtils(int duration) {
        this.duration = duration;
    }

    public Toast makeText(Context context, String text) {
        return Toast.makeText(context, text, duration);
    }

    public void show(Context context, String text) {
        makeText(context, text).show();
    }

    public Toast makeText(Context context, int resId) {
        return Toast.makeText(context, resId, duration);
    }

    public void show(Context context, int resId) {
        makeText(context, resId).show();
    }

}

In my opinion, there are some disadvantages of using Toast class directly:

In Toast class I often miss the call to show()
Parameter length has type int. So a compiler couldn't detect invalid argument value

What do you think? Maybe this class is useless?

Can you suggest any improvements?


texts: Renaming and moving files in a subdirectory with an index and the folder name

texts:
I'm putting together a script to take .mp4 files organized into folders that described the video (eg. cat) and I'd like to do the following:

rename them with the folder name and a number
move the video into a folder named and numbered in the same manner
parse the video into frames using ffmpeg

I'm posting this here to be a reference for others and to ask about how this could be done better.  It works fine but I'm wondering how to make it better.

for dir in /path/to/parent/directory/*; do
cd "$dir" && result=${PWD##*/}
cd video
echo "$result"
a=1
    for i in *.mp4; do
        dafile="$(printf "_%02d.mp4" ${a})"
        dafolder="$(printf "_%02d" ${a})"
        newfolder="$result$dafolder"
        newfile="$result$dafile"
        mkdir "${newfolder}"
        mv "${i}" "${newfolder}/${newfile}"

        cd "${newfolder}"
            ffmpeg -i "${newfile}" -r 30 -f image2 "${newfolder}-\%04d.png"
        cd ..
        let a=a+1
    done

done

I used the following links to figure out a bunch of ideas for the code:

Get current directory name without full path in Bash script
Renaming files in a folder to sequential numbers


texts: Finds the absolute max of the numbers in each file and outputs in specific format

texts:
Inputs:
Files that are named in this scheme:
FAX_99383.txt- (txt files with columns of any width)

==> FAX_99383.txt <== (two rows of 12 numbers)

-93.    -95.    -97.    -96.    -95.    -93.    -91.    -90.    -89.    -88.    -87.    -89.
-99.   -101.   -103.   -102.   -101.    -99.    -97.    -96.    -94.    -93.    -93.    -95.

==> SH1_99383.txt <== (two rows of 12 numbers, like the above)

-2700.  -2677.  -2667.  -2649.  -2619.  -2593.  -2571.  -2552. -2536.  -2523.  -2527.  -2620.
-2788.  -2766.  -2755.  -2738.  -2709.  -2681.  -2659.  -2641.  -2624.  -2610.  -2614.  -2707.

To call

python3.5 maxtxt.py FAX_99383.txt SH1_99383.txt

Output:
MAXES.TXT-

Element    FAX     SH1
   99383   108.0  2923.0

Code works with multiple elements

import numpy as np
import sys

# Retrieve command line txt file entries to process
lis = sys.argv[1:]

# Loop over each txt file and determine the abs max and store in a dictionary
MaxLoads = {}
for file in lis:
    f = open(file, "r")
    X = np.loadtxt(f)
    dof = (file.partition('_'))[0]
    elemid = (file.partition('_'))[2].partition('.')[0]
    if elemid not in MaxLoads:
        MaxLoads.update({
            elemid: {}
        })
    MaxLoads[elemid].update({
        dof: max(X.max(), abs(X.min()))
    })
    f.close()

# Loop over each element and print each max in one line
fw = open("MAXES.TXT", "w")
e = list(MaxLoads.keys())[0]
doflis = sorted(list(MaxLoads[e].keys()))
oline = 'Element    ' + '     '.join(doflis)
fw.write(oline + '\n')
print(oline)
for e in MaxLoads:
    oline = '{:>8}'.format(e)
    for d in doflis:
        oline += '{:>8}'.format(MaxLoads[e][d].__str__())
    print(oline)
    fw.write(oline + '\n')
fw.close()

I'm looking for general feedback on if I am using the best methods to accomplish this goal in Python 3 (both stylistically and effectively). If there is a better language that offers a better solution, those comments are welcome too.  This code is my first operational Python code, goal is to learn Python.


texts:
I wrote FizzBuzz. My aim is to use C# Code Standards correctly, and write flexible code. How can I improve my solution according to code standards? How can it be better in general?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private IEnumerable<int> Sequence(int startPoint, int endPoint)
        {
            return
                Enumerable
                    .Range(Math.Min(startPoint, endPoint), Math.Abs(startPoint - endPoint) + 1);
        }

        private bool IsDivisible(int number, int divisor)
        {
            return (number % divisor).Equals(0);
        }

        private static SortedDictionary<int, string> GetRules()
        {
            var rules = new SortedDictionary<int, string>
            {
                [3] = "Fizz",
                [5] = "Buzz"
            };

            return rules;
        }

        private bool IsInRules(int number)
        {
            return
                GetRules()
                    .Any(rule => IsDivisible(number, rule.Key));
        }

        private string FizzBuzz(int number)
        {
            if (IsInRules(number))
            {
                var result =
                    GetRules()
                        .Where(rule => IsDivisible(number, rule.Key))
                        .Aggregate(new StringBuilder(), (stringBuilder, rule) => stringBuilder.Append(rule.Value));

                return Convert.ToString(result);
            }

            return Convert.ToString(number);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var result =
                Sequence(1, 20)
                    .Select(FizzBuzz);

            listBox1.DataSource = result.ToArray();
        }
    }
}