texts:
I've made an implementation of a doubly-linked list, I spend quite some time trying to get it right. I used both gdb and valgrind to make sure there was no memory leaks or errors. There's not a lot of comments in there, so sorry about that. There's still some things that bothers me in the code, like checking if 'head->prev' is null before appending to it. I'm sure there's must be a better way to implement that, like keeping a pointer to the first node. Also, I've got a list_init() function because I thought it was easier and more clean, but I may be wrong. I may be wrong a lot, so correct me if I am. I'm still not done with the implementation as I still want to add more functions to it, like a list_sort() or reverse_list(), but I'll wait for more input, just to see that I'm on the right track. Thanks!

list.c

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

#include "list.h"

node *list_init()
{
    node *node_t = calloc(1, sizeof(node));
    if (!node_t) {
        fprintf(stderr, "Allocation failed on list_init().\n");
        return NULL;
    }
    return node_t;
}

void list_append(node *node_t, char *data)
{
    /*
     * If there's no previous entry, then we're at the first item of the list.
     */
    if (!node_t->prev) {
        node_t->data = malloc(strlen(data) + 1);
        if (!node_t->data) {
            fprintf(stderr, "Allocation failed on list_add().\n");
        }
        strncpy(node_t->data, data, strlen(data) + 1);
        node_t->prev = node_t;
        return;
    }
    while (node_t->next) {
        node_t = node_t->next;
    }
    node_t->next = malloc(sizeof(node));
    if (!node_t->next) {
        fprintf(stderr, "Allocation failed on list_add().\n");
        return;
    }
    (node_t->next)->prev = node_t;
    node_t->next->data = malloc(strlen(data) + 1);
    if (!node_t->next->data) {
        fprintf(stderr, "Allocation failed on list_add().\n");
        return;
    }
    strncpy(node_t->next->data, data, strlen(data) + 1);
    node_t->next->next = NULL;
}

void list_print(node *node_t)
{
    while (node_t) {
        printf("Value: %s\n", node_t->data);
        node_t = node_t->next;
    }
}

void list_remove_last(node *node_t)
{
    if (!node_t->next) {
        free(node_t);
        node_t->data = NULL;
        return;
    }
    while (node_t->next->next) {
        node_t = node_t->next;
    }
    free(node_t->next->data);
    free(node_t->next);
    node_t->next = NULL;
}

bool list_find(node *node_t, char *data)
{
    while (node_t) {
        if (!strcmp(node_t->data, data)) {
            return true;
        }
        node_t = node_t->next;
    }
    return false;
}

void list_destroy(node *node_t)
{
    node *current = NULL;
    while ((current = node_t)) {
        node_t = node_t->next;
        free(current->data);
        free(current);
    }
}

list.h

#ifndef __LIST_H__
#define __LIST_H__

#include <stdbool.h>

typedef struct node {
    char *data;
    struct node *prev, *next;
} node;

node *list_init();
void list_append(node *head, char *data);
void list_print(node *head);
void list_remove_last(node *head);
bool list_find(node *head, char *data);
void list_destroy(node *head);

#endif /* __LIST_H__  */


texts:
I am interested in finding the average spacing between objects on a directional basis. I did my best to minimally implement this in Python and to conform to PEP8.

I try to explain what I'm doing in the code comments. The problem I want to solve is to find the average spacing between circles of known radius and locations (in my application, these locations are irregular) on a directional basis. For example, what is the average spacing between these circles in the x, diagonal, and y directions?

import numpy as np

# I have a set of x and y coordinates describing the
# locations of objects
px = np.array([0, 0, 0, 10, 10, 10, 20, 20, 20])
py = np.array([0, 10, 20, 0, 10, 20, 0, 10, 20])

# Each object is a circle with known radius size
point_diameter = 2

# I'll put my answers here
spacing = {}

# The challenge is to calculate the average spacing per point on a directional
#  basis, e.g., what is the average distance between points in the direction
#  of 45 degrees?

# To do this, I define a function to check if points are alligned in a
#  direction
def check_alligned(direction, p1x, p1y, p2x, p2y):

    # Since the points have some wisdth, I need to check the "edge cases"
    # as well as the centerlines.
    tolerance = 0.2
    pr = point_diameter / 2
    for offsetx1 in [-1, 0, 1]:
        for offsetx2 in [-1, 0, 1]:
            for offsety1 in [-1, 0, 1]:
                for offsety2 in [-1, 0, 1]:

                    # The scheme is to check if the direction leads to the object x or y location.
                    # I chose or to handle cases where the x or y difference is zero.
                    distance = distance_between([p1x + pr*offsetx1,
                                                     p1y + pr*offsety1],
                                                    [p2x + pr*offsetx2,
                                                     p2y + pr*offsety2])
                    if abs(p1x + distance * np.cos(np.radians(direction)) - p2x) <= tolerance or abs(p1y + distance * np.sin(np.radians(direction)) - p2y) <= tolerance:
                         return True
    return False

def distance_between(v1, v2):
    return np.sqrt( (v1[0] - v2[0])**2 + (v1[1] - v2[1])**2)

# Initial Smallest Spacing - use to find if we get to a spacing in the loop
# and record the smallest one
ISP = 9e4

# Iterate through directions to calculate average distance in each direction.
# Directions go counterclockwise and x points in the direction of 0 degrees.
for direction in [0, 60, 45, 90]:

    # These are a running sum and counter of 1st nearest neighbor spacings
    # that are less than an initial smallest spacing value. They are used
    # to calculate the average spacing in each direction.
    total_spacing = 0.
    space_count = 0

    # Look through every point
    for ii in range(px.size):

        smallest_spacing = ISP
        # and every other point except ones we've already checked
        for jj in range(px.size - ii - 1):

            # If the jj point is not in the same line as the
            # ii point along this diretion, skip it
            idx2 = ii + jj + 1

            if check_alligned(direction, px[ii], py[ii], px[idx2], py[idx2]):
                space = np.sqrt((px[ii]-px[idx2])**2 +
                                          (py[ii] - py[idx2])**2)
                if space < smallest_spacing:
                    smallest_spacing = space

        # Record a distance if it is less than the initial
        # smallest spacing
        if smallest_spacing != ISP:
            total_spacing += smallest_spacing
            space_count += 1

    # record the average spacing in this direction
    if space_count:
        spacing[direction] = total_spacing / space_count
    else:
        spacing[direction] = 0.

print spacing


texts: Simple application to look up items in a list

texts:
I'm very new to the programming world and have been working exclusively with console window applications in C# thus far. I've created a program which took me way too long to produce but I'm very proud to have completed it exactly as I set out to make it. It does what I wanted it to do, however the code is separated into many different methods. Again, being a newbie, I don't know a lot about formatting my code for readability's sake, so I'd love to have some outside opinions about what you would change, if anything, about the text so that I may be pointed in the right direction for future applications I create.

class Program
{

    public static string Name { get; set; }

    public static void Main()
    {
        Console.Write("Please Enter Your Name: ");
        Name = Console.ReadLine();
        SearchBarStart(Name);
    }

    public static void SearchBarStart(string searchName)
    {
        Console.WriteLine("Welcome, {0}", searchName);
        Thread.Sleep(1000);

        SearchChecker();

    }

    public static void SearchBar(string searchName)
    {
        Console.Clear();
        Console.WriteLine("Welcome back, {0}", searchName);
        Thread.Sleep(1000);

        SearchChecker();
    }

    public static void SearchChecker()
    {
        Item Ball = new Item() { Name = "Ball", Price = 100.001F, Popularity = 1 };
        Item Book = new Item() { Name = "Book", Price = 210.1F, Popularity = 5 };
        Item Bag = new Item() { Name = "Bag", Price = 300F, Popularity = 4 };

        List<Item> items = new List<Item>();
        items.Add(Ball);
        items.Add(Book);
        items.Add(Bag);

        string userChoice = string.Empty;

        do
        {
            Console.Write("Please enter which item would you like to view: ");
            userChoice = Console.ReadLine();

            Item resultItem = items.Find(item => item.Name == userChoice);

            if (resultItem == null)
            {
                Console.WriteLine("Item name not valid");
                SearchChecker();
            }
            else
            {
                Console.WriteLine("Item Name: {0}\n" +
                    "Item Price: {1:C}\n" +
                    "Item Popularity Hits: {2}\n",
                    resultItem.Name, resultItem.Price, resultItem.Popularity);
            }
            Console.WriteLine("Would you like to continue? (yes/no)");
            userChoice = Console.ReadLine();
        }
        while (userChoice == "yes");

        Exit();
    }

    public static void Exit()
    {
        Console.WriteLine("Are you sure? (yes/no)");
        string answer = Console.ReadLine();

        if (answer == "yes")
        {
            Console.WriteLine("Press enter again to exit");
            Console.ReadLine();
        }
        else if (answer == "no")
        {
            SearchBar(Name);
        }
        else
        {
            Console.WriteLine("Sorry, I don't recognize {0}\n", answer);
            Exit();
        }

    }
}

class Item
{
    public string Name { get; set; }
    public float Price { get; set; }
    public int Popularity { get; set; }
}


texts: Dependency injection/dependency injection containers in MVC web app

texts:
I just learned about dependency injection/dependency injection containers, and I realize that the controller in my MVC web application is hard to test.

My original controller class:

class Controller
{
    protected $db;
    private $article;
    private $nav;

    public function __construct($db)
    {
        $this->db = $db;
        $this->article = new Article($this->db);
        $this->nav = new Nav($this->db);
    }

    public function render($template)
    {
        var_dump($this->article->getRow());
        var_dump($this->nav->getRows());
    }

}

This is my test using DI/DIC in my MVC app:

Controller

class Controller
{
    private $container;

    public function __construct()
    {
    }

    public function render($container,$template)
    {
        $this->container = $container;
        var_dump($this->container->getArticle($url = 'home'));
        var_dump($this->container->getNav());
    }

}

Container: holds all objects which generate data from the database

class Container
{
    protected $db;
    private $article;
    private $nav;

    public function __construct($db)
    {
       $this->db = $db;
    }

    public function setArticle()
    {
        if (is_null($this->article))
        {
            $this->article = new Article($this->db);
        }
        return $this->article;
    }

    public function setNav()
    {
        if (is_null($this->nav))
        {
            $this->nav = new Nav($this->db);
        }
        return $this->nav;
    }

    public function getArticle($url)
    {
        return $this->setArticle()->getRow($url);
    }

    public function getNav()
    {
        return $this->setNav()->getRows();
    }
}

Models

class Article
{
    public function __construct($db)
    {

    }

    public function getRow($url)
    {
        return "row 1";
    }
}

class nav
{
    public function __construct($db)
    {

    }

    public function getRows()
    {
        return "rows nav";
    }
}

Usage

$db = 'pdo connection';
$template = 'template.phtml';
$container = new Container($db);
$controller = new Controller();
$controller->render($container,$template);

Questions:

Am I doing it correctly or not?
Do the improved Controller and Container above make sense to you if you were a developer going to pick up  this application's development?
Do I need any interfaces or traits as part of the app? If so, why?


texts: Counting the number of occurrences of chars in one string, in another string

texts:
This program counts the total number of times any character from the source string can be found in the target string.

E.g Source String - "Hello World"
Target String - "llo"
Output = 5 (as there are 3 l's and 2 o's)

Source String - "Hello World"
Target String - "ooood"
Output = 3 (as there are 2 o's and 1 d)

Is there any better way of write the below program?

public class CountOccurence {
public static int countChars(String target, String source){
    char a[] = source.toCharArray();

    int loc = 0, count = 0;
    boolean charRepeat = false;

    for (loc = 0; loc < source.length(); loc++) {
        charRepeat = false;
        for (int z = 0; z < loc; z++) {
            if (a[loc] == a[z]) {
                charRepeat = true;
                break;
            }
        }

        if (charRepeat == false) {
            int i = 0;
            while ((i = target.indexOf(a[loc], i)) != -1) {
                count++;
                i++;
            }
        }
    }
    return count;
}

public static void main(String[] args) {
    String target = "Hello World";
    String source = "oood";

    int count = countChars(target, source);
    System.out.println(count);

    source = "lld";
    count = countChars(target, source);
    System.out.println(count);

}

}


texts: 4 distinct integers, whose reciprocals sum up to 1

texts:
I wrote the following short python program to solve a math puzzle, which asked for all the 4-tuples of distinct natural numbers whose reciprocals sum up to 1.

from fractions import Fraction

results = []

def solve(length, terms):
  previous = terms[-1] if len(terms) > 0 else 0
  sum_needed = 1 - sum([Fraction(1,x) for x in terms])
  if length == len(terms) + 1:
    rest = int(Fraction(1,sum_needed))
    if Fraction(1,rest) == sum_needed and rest >= previous + 1:
      results.append(terms + [rest])
  else:
    next_min = max(previous, int(Fraction(1,sum_needed))) + 1
    next_max = int(Fraction(length,sum_needed))
    for next in range(next_min, next_max+1):
      solve(length, terms + [next])

solve(4,[])
print results

The basic idea is to go through the possible range of the smallest number first, and then based on its value, find the other three numbers.
It all works fine, the output is as desired:

[[2, 3, 7, 42], [2, 3, 8, 24], [2, 3, 9, 18], [2, 3, 10, 15], [2, 4, 5, 20], [2, 4, 6, 12]]

This was a 10-minute project, and not production code, so I don't really worry about readability or maintainability, but still there are a few things which I don't like in my implementation, mostly originating from the recursive approach used.

I've used the itertools module in other tiny hobby-projects, mostly to answer combinatorics-related questions, but I'm not really experienced with other uses of it.
I wonder if changing the approach from recursion to iteration is possible for a problem of this kind, and if itertools has some functions which could help me achieving that.

Any other comments on bad practises in the code above and some pythonic ideas that could have been used in it are also very welcome. Thanks in advance!

I also include an iterative solution:

from fractions import Fraction

result = []

a_min = max(1, int(Fraction(1,(1-sum([Fraction(1,i) for i in []])))+1))
a_max = int(Fraction(4,1-sum([Fraction(1,i) for i in []])))
for a in range(a_min,a_max+1):
  b_min = max(a+1, int(Fraction(1,(1-sum([Fraction(1,i) for i in [a]])))+1))
  b_max = int(Fraction(3,1-sum([Fraction(1,i) for i in [a]])))
  for b in range(b_min,b_max+1):
    c_min = max(b+1, int(Fraction(1,(1-sum([Fraction(1,i) for i in [a,b]])))+1))
    c_max = int(Fraction(2,1-sum([Fraction(1,i) for i in [a,b]])))
    for c in range(c_min,c_max+1):
      d = int(Fraction(1,1-sum([Fraction(1,i) for i in [a,b,c]])))
      if d>c and 1-sum([Fraction(1,i) for i in [a,b,c,d]])==0:
        result.append([a,b,c,d])

print result

Of course this has the big disadvantage of being non-generic: unlike the recursive solution, this (without modification) cannot be used to find 5-tuples with the same reciprocal sum of 1.
I tried to write it in a way that emphasizes the repetitive pattern in it: the loop for a and b variables are very similar, so maybe that's the part which can be replaced by a well-chosen function from itertools.
Any ideas?


texts: Aggregation on list forEach and maps improvals

texts:
I am using a function in a SpringBoot @RestController, with Lombok

This function is an intermediate result that permit me to do an aggregation between two classes.

This 2 classes are:

@Data
public class AchMatiereCmdCptAggDto implements Serializable {

    private static final long serialVersionUID = 4022154955808447185L;
    private String codService;
    private String codSociete;
    private String numCompte;
    private String codCommande;
    private Double mntCommandeHTLCY;
    private Double mntLivreHTLCY;
    private Double mntFactureHTLCY;
}

@Getter
@Setter
public class AchMatiereCompteCommandeAggFullDto extends AchMatiereCmdCptAggDto implements Serializable {

    private static final long serialVersionUID = 6357406952790844723L;
    private Date dateCommande;
    private String codFournisseur;
    private String libFournisseur;
    private Boolean booFournisseurIntragroupe;
    private Long idCommandeEtat;

}

public static String stringConcat(String ... elements) {
    return new StringBuilder().append(elements).toString();
}

I use them that way, and I want to improve forEach part, and any other improvable piece of code:

 public List<AchMatiereCompteCommandeAggFullDto> mergeAchat(List<AchMatiereCompteCommandeAggFullDto> achats,

List<AchMatiereCmdCptAggDto> achats2) {

    Set<AchMatiereCmdCptAggDto> setAchats = new HashSet<>(achats2);
    Map<String, AchMatiereCmdCptAggDto> map = setAchats.stream()
            .collect(Collectors.toMap(
                    p -> stringConcat(p.getNumCompte(), p.getCodCommande()),
                    p -> p, (ach1, ach2) -> ach2
            ));

    achats.stream().forEach(achat -> {
        String k = stringConcat(achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());

        if (map.containsKey(k)) {
            achat.setMntFactureHTLCY(map.get(k).getMntFactureHTLCY());
        }
    });
    return achats;
}

I was thinking about using a StringBuilder for the concatenation of attributes.

I would also like to avoid forEach, and use a Map or something like this.

Thanks for your help.


texts:
How could I improve this code?

public class DALUser
    {
        SqlConnection conn;
        SqlCommand cmd;

        public void ExecuteSp(string Spname, Dictionary<dynamic, dynamic> Params)
        {
            try
            {
                initialize();
                cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = Spname;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd = GetParam(Params, cmd);
                cmd.ExecuteNonQuery();
            }
            finally
            {
                DeIntialize();
            }
        }

        public  DataTable ExecuteAdapter(string Spname, Dictionary<dynamic, dynamic> Params)
        {
            try
            {
                initialize();
                cmd = new SqlCommand();
                cmd.Connection = conn;
                DataTable dt = new DataTable();
                cmd.CommandText = Spname;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd = GetParam(Params, cmd);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt);
                return dt;
            }

            finally
            {
                DeIntialize();
            }
        }

        SqlCommand GetParam(Dictionary<dynamic, dynamic> Params, SqlCommand cmd)
        {
            foreach (var objparam in Params)
            {
                cmd.Parameters.AddWithValue(Const.sParamPrefix + objparam.Key, objparam.Value);
            }
            return cmd;
        }

        #region SqlConnection Side

        void initialize()
        {
            if (CheckConnection())
            {
                conn = new SqlConnection(Const.ConnectionString);
                conn.Open();
            }
        }

        bool CheckConnection()
        {
            if (conn == null)
                return true;
            return false;
        }

        void DeIntialize()
        {
            if (!CheckConnection())
            {
                conn.Close();
                conn.Dispose();
            }
        }

        #endregion

    }


texts:
This is a simple implementation of a generic binary tree that holds elements of type T. I was wondering if there was something that could be done better (especially in the EnumerateNodes methods).

using System.Collections.Generic;

namespace DataStructures.Node
{
    /// <summary>
    /// Implements a generic binary tree.
    /// </summary>
    /// <typeparam name="T">The type of the nodes</typeparam>
    public class Node<T>
    {
        #region Private attributes
        private T _node = default(T);
        private Node<T> _leftChild = default(Node<T>);
        private Node<T> _rightChild = default(Node<T>);
        #endregion

        #region Constructor
        public Node()
        {
            _node = default(T);
            _leftChild = null;
            _rightChild = null;
        }

        public Node(T node)
        {
            _node = node;
            _leftChild = null;
            _rightChild = null;
        }
        #endregion

        #region Accessors
        public T Value
        {
            get { return _node; }
            set { _node = value; }
        }

        public Node<T> LeftChild
        {
            get { return _leftChild; }
            set { _leftChild = value; }
        }

        public Node<T> RightChild
        {
            get { return _rightChild; }
            set { _rightChild = value; }
        }

        /// <summary>
        /// Returns the total number of elements in the tree.
        /// </summary>
        public int Count
        {
            get { return count(); }
        }
        #endregion

        #region Private methods

        private int count()
        {
            if (_leftChild == null && _rightChild == null)
                return 1;
            if (_leftChild == null)
                return 1 + _rightChild.count();
            if (_rightChild == null)
                return 1 + _leftChild.count();
            else
                return 1 + _leftChild.count() + _rightChild.count();
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Adds the element on the right branch of the node.
        /// </summary>
        /// <param name="rightBranch">Node to add on the right side of the node.</param>
        public void AddRight(Node<T> rightBranch)
        {
            _rightChild = rightBranch;
        }

        /// <summary>
        /// Adds the element on the left branch of the node.
        /// </summary>
        /// <param name="leftBranch">Node to add on the left side of the node.</param>
        public void AddLeft(Node<T> leftBranch)
        {
            _leftChild = leftBranch;
        }

        public IEnumerable<T> EnumerateNodes()
        {
            yield return _node;
            if (_leftChild != null)
                foreach (T child in _leftChild.EnumerateNodes())
                    yield return child;
            if (_rightChild != null)
                foreach (T child in _rightChild.EnumerateNodes())
                    yield return child;
        }

        #endregion
    }
}


texts: Async function with slow web reference(web service) slowing down webpage

texts:
Is there a way to make a threading/async post with a web reference not slow down the whole website just because the web reference takes a long time to return a response?

I have a send email function that gets posted async with a threading system that basically looks like this. This whole .cs file is called Mail.cs (that's where the Mail. name comes from).

public static bool SendMail(var alotOfVariablesHere)
{
    MailParameters param = new MailParameters(alotOfVariablesHere);
    Thread thread = new Thread(Mail.QueueSendMailAsyc);
    thread.Start(param);
    return true;

}

static Object locker = new object();
public static void QueueSendMailAsyc(object Objparam)
{
    lock (locker)
    {
        SendMailAsyc(Objparam);
    }
}

Inside SendMailAsyc() we run our web reference:

WebReference.Service1 Converter = new WebReference.Service1();
Converter.Timeout = 3 * 60 * 1000;

byte[] file = Converter.ConvertFunction(File.ReadAllBytes(attachfilepath), fileName);

The only thing the WebReference does is receiving a byte array and a file name and then returns a new byte array.

Pretty simple and it all works fine.

But recently the server were the web reference is sitting on (a totally different server from the webpage) has started getting really slow.
This means that the web reference takes a long time to respond (it does respond and it does return everything like the way we want it. just that it's now a lot slower)

And this has started causing a lot of issues, like:
The webpage also get really slowed down, it takes ages to navigate through the pages and so on.

Plus the fact that this one single web reference threading/async post takes so long time means that there is plenty of time to put up even more threading/async posts meaning it'll put an even bigger pressure on the server, causing it to slow down a lot.

This issue is primary that the web reference has gotten really slow lately, and that our webpage server cannot handle the pressure of too many threads/async posts.

I can't do much about the server the web reference is sitting on has started getting really slow recently.

But is there anything I can do code-wise to make my system handle this really slow web reference better?


texts:
I made a program that converts a decimal number given from the user, and converts it to a binary number. For example, if I entered 2, it would return 10. It then, counts the amount of ones and zeros in the binary conversion. Please tell me any way my code can be either, more efficient, or if there is an error with my code. If there are any bad practices used, please tell me. Indentation is also important to me.

package Conversions;
import java.util.Scanner;

public class BinaryChallenge {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
    int number;

    Scanner scan = new Scanner(System.in);
    int oneCount = 0;
    int zeroCount = 0;
    System.out.println("Enter a positive integer");
    number = scan.nextInt();
    String binary = "";
    if (number < 0) {
        System.out.println("Error: Not a positive integer");
    } else {
        while(number > 0) {
            int mod = (number % 2);
            number /= 2;
            binary = Integer.toString(mod) + binary;
        }
        System.out.println("The binary representation of your integer is: " + binary + ".");
    }

    for (int i = 0; i < binary.length(); i++) {
        if (binary.charAt(i) == '1') {
            oneCount++;
        } else if(binary.charAt(i) == '0') {
            zeroCount++;
        }
    }
    System.out.println("The binary representation of your integer has: " + oneCount + " ones.");
    System.out.println("The binary representation of your integer has: " + zeroCount + " zeros.");
    System.out.println("The binary representation of your integer has 0 twos... duh.");
}
}


texts: Finding the last ten digits of \$\sum_{n=1}^{1000} n^n\$

texts:
This is my solution to Project Euler Problem 48.

Problem:

  The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$ .

  Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.

I would like feedback/advice to possibly increase efficiency and/or correct incorrect practices.

public static void main(String[] args) {
    BigInteger start, sum = BigInteger.valueOf(0);

    for (int i = 1; i <= 1000; i++) {
        start = BigInteger.valueOf(i);
        sum = sum.add(start.pow(i));
    }
    String sumStr = sum.toString();
    System.out.println(sumStr.substring(sumStr.length() - 10));
}


texts:
Gives advice to the user on which trains to take to reach a destination

 public class TripAdvisor {
        private Station source;
        private Station destination;
        private double cost;
        /**
         *
         * @param path the shortest path returned by the shortestPath method implementation
         */
        TripAdvisor(ArrayList<Station> path)
        {
            Lane color=null;
            ArrayList<Station> changeStation =new ArrayList<Station>();//used to identify when the user needs to change lines
            ArrayList<Object> trains=new ArrayList<>();//list of trains the user need to take to reach a station
            for(int i=0;i<(path.size()-1);i++)
            {

                Station current=path.get(i);
                Station next=path.get(i+1);
                for (Connection e : current.adjacencies)
                {
                    if(e.getTarget().equals(next))
                    {
                        Lane train=e.getLaneColor();
                        trains.add(train);
                        if(!e.getLaneColor().equals(color)&&(color!=null))
                        {
                            changeStation.add(current);
                        }
                    }
                    color=e.getLaneColor();
                }
            }

            System.out.println("trains"+ "$" +trains);
            if(trains.size()==1)
            {
                int q;
                System.out.println("Take a "+ trains.get(0) +"liner from" + path.get(0) +"to reach" + path.get( q=path.size()));
            }
            else
            {
                System.out.println("Take a "+ trains.get(0) +"liner from" + path.get(0)+ "Get down at" + changeStation.get(0));

            }
        }

    }
    /**
     *
     * @author PrasannaAarthiB
     * This has all the lines in the metro.They are represented by different colors
     */
    public enum Lane{
        RED,BLUE,GREEN,YELLOW,BLACK
    }


texts:
This is a challenge question from codeeval.com:

  Write a program which reads a file and prints to stdout the specified
  number of the longest lines that are sorted based on their length in
  descending order. Input sample:

  Your program should accept a path to a file as its first argument. The
  file contains multiple lines. The first line indicates the number of
  lines you should output, the other lines are of different length and
  are presented randomly. You may assume that the input file is
  formatted correctly and the number in the first line is a valid
  positive integer.

  For Example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

  Output sample:

  Print out the longest lines limited by specified number and sorted by
  their length in descending order.

  For example:

San Francisco
Hello World

Please let me know how I can improve this implementation.

#include<iostream>
#include<map>
#include<fstream>
#include<string>
#include<chrono>

class fixed_hash{
public:
        fixed_hash( int pSize )
        {
            size = pSize;
        }
        void push( std::string & record )
        {

            if( hash_table.size() < size )
            {
                hash_table.emplace( std::make_pair( record.size(), record ) );
            }
            else if( record.size() > hash_table.rbegin()->second.size() )
            {
                hash_table.erase( hash_table.begin() );
                hash_table.emplace( std::make_pair( record.size(), record ) );
            }
        }
        void print()
        {
            auto end = std::rend(hash_table);
            for( auto it = std::rbegin( hash_table ); it != end ; ++it )
            {
                std::cout << it->second << "\n";
            }
        }

 private:
        std::map<int,std::string> hash_table;
        int size;
};

void readInputFile( std::string fileName )
{
    std::ifstream infile( fileName );
    std::string record;
    int output_nbr = 0;
    infile >> output_nbr;
    fixed_hash output_string_list( output_nbr );
    while( std::getline( infile, record ) )
    {
        output_string_list.push( record );
    }

    output_string_list.print();
    infile.close();
}

int main( int argc, char* argv[] )
{
    auto start = std::chrono::steady_clock::now();
    if( argc < 2 )
    {
        std::cout << "Error: input file is missing " << "\n";
        exit( 0 );
    }

    std::ios_base::sync_with_stdio( false );
    readInputFile( argv[ 1 ]);

    auto end      = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
    std::cout<< duration.count() << "\n";
    return 0;
}


texts: Class/model hierarchy for a school-management application

texts:
Please find how I would model a system that had teachers, students, classes and parents. Instead of creating a model for each user type, I created only two models, User and Profile. Each user can have multiple profiles and each profile can have a unique profile_type.

I would love to get some feedback on my proposed architecture.

class User < ActiveRecord::Base
  has_many :profiles
  has_many :user_klasses
  has_many :klasses, through: :user_klasses

  def get_student_classes
    student_profile = profiles.select { |p| p.profile_type == 'student' }.first
    return [] if student_profile.nil?

    return klasses.select { |k| k.profile_id == student_profile.id }
  end

  def get_teacher_classes
    teacher_profile = profiles.select { |p| p.profile_type == 'teacher'}.first
    return [] if teacher_profile.nil?

    return klasses.select { |k| k.profile_id == teacher_profile.id }
  end

end

class Klass < ActiveRecord::Base
  has_many :user_klasses
  has_many :users, through: :user_klasses
  belongs_to :teacher, class_name: 'Profile', -> { where profile_type: 'teacher' },
                        dependent: :destroy
end

class UserKlasses < ActiveRecord::Base
  belongs_to :user
  belongs_to :klass
end

class Profile < ActiveRecord::Base
  belongs_to :user
end


texts:
I recently found adventofcode, but when I solved Day 3 in Python, I noticed that my code isn't looking very nice. The challenge is about navigating a hypothetical memory laid out in a square spiral:

  You come across an experimental new kind of memory stored on an infinite two-dimensional grid.

  Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:

17  16  15  14  13
18   5   4   3  12
19   6   1   2  11
20   7   8   9  10
21  22  23---> ...

  Given an input, the program should print:

  The Manhattan distance of the cell with that address to the cell with address 1 (justified by the only access port being at address 1)

  For example:

  Data from square 1 is carried 0 steps, since it's at the access port.
  Data from square 12 is carried 3 steps, such as: down, left, left.
  Data from square 23 is carried only 2 steps: up twice.
  Data from square 1024 must be carried 31 steps.

  The first value written to memory larger than the input during a "stress test".

  As a stress test on the system, the programs here clear the grid and then store the value 1 in square 1. Then, in the same allocation order as shown above, they store the sum of the values in all adjacent squares, including diagonals.

  Square 1 starts with the value 1.
  Square 2 has only one adjacent filled square (with value 1), so it also stores 1.
  Square 3 has both of the above squares as neighbors and stores the sum of their values, 2.
  Square 4 has all three of the aforementioned squares as neighbors and stores the sum of their values, 4.
  Square 5 only has the first and fourth squares as neighbors, so it gets the value 5.

47  142  133  122   59
304    5    4    2   57
330   10    1    1   54
351   11   23   25   26
362  747  806--->   ...

I'm particularly looking for tips on reducing the code repetition in the coords function. Should I use list comprehension to sum the values? It seems quite long. Finally, is there a more Pythonic way to include a special case when a key isn't found?

from math import sqrt, floor
import itertools

# Given an address in the spiral memory, return the coordinates of that memory cell,
# where x grows when moving right, and y grows when moving down.

def coords(address):
# For a spiral of side length n, the bottom right element will have an address of n^2
# Starting from that element, the spiral goes one cell right, and then n cells up,
# n+1 cells left, n+1 cells down and n+2 cells right

# Start in the bottom right corner of the largest spiral that does not contain
# the address we are looking for.
    n = floor(sqrt(address))

    if n % 2 == 0:
        n -= 1

# r - the radius of the spiral of side length n
    r = (n - 1) // 2
    address -= n ** 2

    if address == 0:
        return r, r
    address -= 1

    if address < n:
        return r + 1, r - address
    address -= n

    if address < n + 1:
        return r + 1 - address, r - n
    address -= n + 1

    if address < n + 1:
        return r - n, r - n + address
    address -= n + 1

    if address < n + 2:
        return r - n + address, r + 1
    raise Exception("This shouldn't ever happen")

def distance(x, y):
    return abs(x) + abs(y)

inp = int(input())
print(distance(*coords(inp)))

spiral = { (0, 0): 1 }
for address in itertools.count(2):
    x, y = coords(address)
    value = sum([spiral[(x + dx, y + dy)] for dx, dy in itertools.product([-1, 0, 1],
      repeat = 2) if (x + dx, y + dy) in spiral])

    spiral[(x, y)] = value

    if value > inp:
        print(value)
        break

Note: I had to add the blockquotes in an edit because SE considers heuristics about how well an answer is formatted an absolute truth... I think something should be done about it. If I am going as far as figuring out how to unbind an event listener that doesn't let me post, it should be clear that I am certain about my formatting.


texts: Sieve of Eratosthenes and twin prime finder

texts:
I made this program to find primes and twin pairs. I'd like feedback on anything from formatting to content to technique. In short: how would this be different if it was written by an experienced professional?

The program runs five methods:

getMax asks for an integer input which is the maximum number below which to find primes and twin prime pairs. It also has an error message to catch unacceptable input and ask again.
sieve checks every number between 0 and max and returns a boolean array which says whether each index is prime or not.
primesCount counts many primes there are, and prints it.
primesList creates an integer array of all primes, and prints it.
pairsCount counts how many twin prime pairs there are, and prints it.
pairsList creates a string array of all twin prime pairs, and prints it.

Code:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int max = getMax(in);

    boolean[] primesSieve = sieve(max);
    int primesCount = primesCount(primesSieve);
    int[] primesList = primesList(primesSieve, primesCount);
    int pairsCount = pairsCount(primesList);
    pairsList(primesList, pairsCount);

}

// User input for maximum number to sieve
public static int getMax(Scanner in) {
    System.out.print("Maximum number to sieve: ");
    while (!in.hasNextInt()) {
        String input = in.next();
        System.out.println("Error: \"" + input + "\" is not a number. Try again.");
        System.out.print("Maximum number to sieve: ");
    }
    int max = in.nextInt();
    return max;
}

// Create boolean array of prime status of integers less than max
public static boolean[] sieve(int max) {

    // Create initial array and assume all are primes
    boolean[] arePrimes = new boolean[max];
    for (int i = 0; i<max; i++) {
        arePrimes[i] = true;
    }

    // Mark multiples of each prime as non-prime
    for (int i = 2; i<max; i++) {
        if (arePrimes[i]) {
            for (int m = 2; i * m < max; m++) {
                arePrimes[i*m] = false;
            }
        }
    }
    return arePrimes;
}

// Count and print how many primes are less than max
public static int primesCount(boolean[] primes) {
    int count = 0;
    for (boolean prime : primes) {
        if (prime) {
            count++;
        }
    }
    System.out.println("Number of primes: " + count);
    return count;
}

// Create and print array listing all primes less than max
public static int[] primesList(boolean[] sievedPrimes, int numberOfPrimes) {
    int[] listPrimes = new int[numberOfPrimes-2];
    int n = 0;

    for (int i=2; i<sievedPrimes.length; i++) {
        if (sievedPrimes[i]) {
            listPrimes[n] = i;
            n++;
        }
    }
    System.out.println("List of primes: " + Arrays.toString(listPrimes));
    return listPrimes;
}

// Count and print the number of twin prime pairs
public static int pairsCount(int[] listOfPrimes) {
    int pairsCount = 0;
    for (int i=0; i<listOfPrimes.length-1; i++) {
        if (listOfPrimes[i+1] - listOfPrimes[i] == 2) {
            pairsCount++;
        }
    }
    System.out.println("Number of twin prime pairs: " + pairsCount);
    return pairsCount;
}

// Create and print array listing all pairs of twin primes less than max
public static String[] pairsList(int[] listOfPrimes, int pairsCount) {
    String[] twinPrimes = new String[pairsCount];
    int n = 0;
    for (int i=0; i<listOfPrimes.length-1; i++) {
        if (listOfPrimes[i+1] - listOfPrimes[i] == 2) {
            twinPrimes[n] = listOfPrimes[i] + " and " + listOfPrimes[i+1];
            n++;
        }
    }
    System.out.println("List of twin prime pairs: " + Arrays.toString(twinPrimes));
    return twinPrimes;
}


texts: Competition - Qualifications - E - Matrix distance

texts:
2 types of query:

add value to x y
output the sum of \$value*(|a - x|+|b-y|)\$ for every pair(a, b, v).

In the start you are given \$n\$ (number of querys), \$m\$ (maximal dimension for square matrix).

In the next \$n\$ lines you are given either:

1 x y v, you should add value v to x y coordinate, or
2 x y calculate the \$distance * value\$ between every \$a\$ and \$b\$ that have some values (distance is being calculated: \$|a- x| + |b - y|\$). So the formula for one spot in matrix would be \$v * (|a - x| + |b - y|)\$ for a given \$a\$ and \$b\$.

My code works, but it is too slow.

Constraints:
\$n <= 250'000\$
\$m <= 10^9\$
\$X_i\$ and \$Y_i <= m\$
\$V_i\$ <= \$10^4\$

time limit: 2.5s

My code:

for (int i = 0; i < n; ++i){

    int el;
    cin >> el;

    if (el == 1){
        int a, b, c;
        cin >> a >> b >> c;

        x.push_back(a);
        y.push_back(b);
        v.push_back(c);
    }

    if (el == 2){
        int a, b;
        cin >> a >> b;

        ll sol = 0;
        for (int j = 0; j < x.size(); ++j){
            sol += v[j] * (abs(a - x[j]) + abs(b - y[j]));
        }
        cout << sol << "\n";

    }

}


texts:
It occurred to me that if SHA2 can be used to derive keys from passwords, then it might as well be good enough to generate random data that can be xored with a plaintext to encrypt and the other way around.

These are my assumptions:

SHA-512 produces a random-looking output that is impossible to guess
The result of SHA-512 can be fed back into it appended to a 256-bit key and produce an output with the same quality as given for a random input

If those assumptions hold, then it should provide privacy. It's much faster than AES-256-CBC.

At first I thought there must be something I'm missing, but no one has pointed out an attack that can be carried out against this construction. So what I would like to know is how secure this algorithm is and specific ways to break it.

Here's the code:

mad.h

#ifndef _MAD_H_
#define _MAD_H_

typedef struct {
  unsigned char state[64];
  unsigned char key[32];
} MadCtx;

void mad_ctx_init(MadCtx* mad, unsigned char const* key,
                  unsigned char const* iv);

void mad_encrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,
                 unsigned char* out);

void mad_decrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,
                 unsigned char* out);

#endif

mad.c

#include "mad.h"
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <openssl/sha.h>

// Private
static void _xor64(uint64_t* dest, uint64_t const* a, uint64_t* b)
{
  for(int i = 0; i < 8; ++i)
    *dest++ = *a++ ^ *b++;
}

// Public
void mad_ctx_init(MadCtx* mad, unsigned char const* key,
                  unsigned char const* iv)
{
  memcpy(mad->state, iv, 64);
  memcpy(mad->key, key, 32);
}

void mad_encrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,
                 unsigned char* out)
{
  assert(0 == in_size % 64);

  int n = in_size >> 6; // in_size / 64
  while(n){
    uint64_t x[8];
    SHA512((unsigned char const*)mad, 96, (unsigned char*)x);
    _xor64((uint64_t*)out, (uint64_t const*)in, x);
    memcpy(mad->state, out, 64);
    in += 64;
    out += 64;
    --n;
  }
}

void mad_decrypt(MadCtx* mad, unsigned char const* in, unsigned int in_size,
                 unsigned char* out)
{
  assert(0 == in_size % 64);

  int n = in_size >> 6; // in_size / 64
  while(n){
    uint64_t x[8];
    SHA512((unsigned char const*)mad, 96, (unsigned char*)x);
    memcpy(mad->state, in, 64);
    _xor64((uint64_t*)out, (uint64_t const*)in, x);
    in += 64;
    out += 64;
    --n;
  }
}

and some test code

#include "mad.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void phex(void const* data, size_t size)
{
  char const* table = "0123456789abcdef";
  unsigned char const* in = data;
  while(size--){
    int c;
    c = table[*in >> 4];
    putchar(c);

    c = table[*in & 0xf];
    putchar(c);
    ++in;
  }
}

void read_or_die(FILE* file, void* dest, size_t size)
{
  if(size != fread(dest, 1, size, file)){
    perror("fread()");
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char* argv[])
{
  FILE* urandom = fopen("/dev/urandom", "r");
  unsigned char iv[64];
  unsigned char key[32];
  unsigned char plain[128];
  unsigned char cipher[128];
  unsigned char decrypted[128];

  read_or_die(urandom, iv, 64);
  read_or_die(urandom, key, 32);
  memset(plain, 0xdd, 128);

  puts("plain text is:");
  for(int i = 0; i != 128; i += 32){
    phex(plain + i, 32);
    putchar('\n');
  }
  putchar('\n');

  MadCtx ctx;
  mad_ctx_init(&ctx, key, iv);
  mad_encrypt(&ctx, plain, 128, cipher);

  puts("cipher text is:");
  for(int i = 0; i != 128; i += 32){
    phex(cipher + i, 32);
    putchar('\n');
  }
  putchar('\n');

  assert(0 != memcmp(plain, cipher, 128));

  mad_ctx_init(&ctx, key, iv);
  mad_decrypt(&ctx, cipher, 128, decrypted);

  puts("decrypted text is:");
  for(int i = 0; i != 128; i += 32){
    phex(decrypted + i, 32);
    putchar('\n');
  }
  putchar('\n');

  assert(0 == memcmp(plain, decrypted, 128));
}


texts: Multiple isset block going from more specific to more generic

texts:
I have a data structure that allows for inheritance of properties, in such a way that if a property is not defined within a context, the second most specific context is checked until said property is found. Simplified it's basically the following:

function getCarPartColor($carData, $owner, $brand, $part) {
    $color = false;

    if(isset($carData->{$owner}->{$brand}->{$part})) {
        $color = $carData->{$owner}->{$brand}->{$part};

    } else if(isset($carData->{$owner}->{$brand}->allparts)) {
        $color = $carData->{$owner}->{$brand}->allparts;

    } else if(isset($carData->{$owner}->allbrands->allparts)) {
        $color = $carData->{$owner}->allbrands->allparts;

    } else if(isset($carData->allowners->allbrands->allparts)) {
        $color = $carData->allowners->allbrands->allparts;
    }

    return $color;
}

Where $carData is the data structure and the rest are the querying variables. If I were to call:

getCarPartColor($carData, "AnthonyNewel", "opel", "engine");

But I hadn't defined any color for $carData->AnthonyNewel->opel->engine, then it checks if a color is set on $caraData->AnthonyNewel->opel->allparts, and fetches this one instead if it exists. If it's not there, it then checks if it's defined for allbrands, and it goes on.

While the code above works, one can't help but notice the repetition. Is there a less verbose way to write this while still being maintanable (i.e. not a long ternary operator)?


texts: What percentage of down votes are users responsible for?

texts:
I put together this simple query to calculate the percentage of downvotes each user is responsible for and displaying them in order of downvote percentage. It's generating the desired results, but I am uncertain about style and best practices.

WITH DownVoteCount AS (
SELECT DownVoteCount = CAST(SUM(DownVotes) AS float)
FROM Users
), DownVoteWeight AS (
SELECT DisplayName, UpVotes, DownVoteWeight = ROUND(DownVotes / (SELECT DownVoteCount from DownVoteCount) * 100, 4)
FROM Users
Where Users.DownVotes > 0
)

SELECT DisplayName, DownVoteWeight
FROM DownVoteWeight

ORDER BY DownVoteWeight DESC, UpVotes

I read about the capitalization of keywords, and decided it would be useful in case of working with SQL inside strings, where syntax highlighting wouldn't be available.


texts:
I've made a program to find the missing element (if there's one) in a sequential list:

Program criteria:
Returns -1 if a list is sequential, otherwise the missing element in a non-sequential list is returned.
To perform binary search, we need a key to half the problem size. Here the key is to find the distance between the index (low, high) and their corresponding values.
Compilation procedure:
gcc -Wall -g testList.c -o testList

./testList

#include<stdio.h>
int bSearch(int array[], int low, int high){

  int mid = (low + high) / 2;

  if(high == low + 1){
    if(array[high] > array[low] +1){
      return array[low] +1;
    }else{
      return -1;
    }
  }

  if(array[mid] - array[low] == mid - low){
    return bSearch(array, mid, high);
  }else if(array[mid] -  array[low] > mid - low){
    return bSearch(array, low, mid);
  }else{
    return -1;
  }
}

int main(void){

  int array [] = {22, 23, 24, 25, 26, 27, 28, 30};
  int upperBound = (sizeof(array)/sizeof(array[0]))-1;
  printf("%d\n", bSearch(array, 0,  upperBound));
  return 0;
}

My questions:

Why does removing the else{} case cause the compiler to give a warning for it?

Can the base case look more elegant?

For code elegance and optimization, can this code be improved?


texts:
I am asking about the right way to make a component that holds some state.  This includes a Jbutton that saves a color in it, or a list item that saves a certain object. So when those GUI components fire an event, I can use the saved states to do something with it.

My way is like this:

Make a subclass of the required component, like a subclass from Jbutton.
Make a Listener for this new subclass: in the listener check, if the event source is the subclass, convert it and then use the stored data.

class ColorButton extends JButton
{
    static class Listener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            Object source = actionEvent.getSource();
            if( source.getClass() == ColorButton.class)
            {
                ColorButton t = (ColorButton) source;
                t.getComponent().setBackground(t.getColor());
            }
        }
    }

    //states i want to be saved
    private Color c;
    private Component comp;

    ColorButton(Component comp, Color c) {
        setColorChanger(comp, c);
    }

    /*   ......
         ......
         rest of constructors added with those additions
         ......
    */
    private void  setColorChanger(Component comp, Color c)
    {
        this.comp = comp;
        this.c = c;
    }

    Color getColor() {
        return c;
    }

    Component getComponent() {
        return comp;
    }

}

And I use it this way:

JPanel panel = new JPanel();
ColorButton.Listener l = new ColorButton.Listener();
JButton b = new ColorButton("Blue", panel, Color.BLUE);
JButton r = new ColorButton("Red", panel, Color.RED);
r.addActionListener(l);
b.addActionListener(l);
panel.add(b);
panel.add(r);
add(panel);

I am wondering: is this way okay?  I feel it is very boring to make this for every component that should hold a certain state.  Is there a better way?


texts: Constructing a class from a line in a parameter file

texts:
I've got a problem where I need to parse a line in a parameter file of the form

PotentialName [... variable number of parameters]

I've got code which works however it seems like it will be horrendous to maintain when I add more than a few options here.

What would be the best design pattern to avoid the long chain of else ifs and what looks like (to my eyes) quite a bit of boilerplate for each option I add.

std::shared_ptr<Potential> construct_potential( std::istringstream& iss )
{
    std::string pot_type;
    iss >> pot_type;

    if( pot_type == "NFW" ) {
        double rho0, rs;
        iss >> rho0 >> rs;
        return std::make_shared<NFW>(rho0, rs);
    }
    else if( pot_type == "MiyamotoNagai" ) {
        double m, a, b;
        if( iss >> m >> a >> b ) {
            return std::make_shared<MiyamotoNagai>(m, a, b);
        } else {
            throw ParseError("Expected 3 parameters for " + pot_type + " potential");
        }
    }
    else if( pot_type == "Kepler" ) {
        double m;
        if( iss >> m ) {
            return std::make_shared<Kepler>(m);
        } else {
            throw ParseError("Expected 1 parameter for " + pot_type + " potential");
        }
    }
    else {
        throw ParseError("Unknown Potential: " + pot_type);
    }
}

How can I improve this?


texts:
I believe any data structure can be converted to RDF, and I wrote the
subroutine below which sort of does this, at least for arbitrarily
complex hashes.

However, I'm unhappy with it because:

$hash2rdf_count should not be global. I don't see an easy fix for this.
Where I comment "hopefully it's referring to a scalar at this
point!", I'm not actually convinced. Are there better ways to check?
@triplets should not be global. I think I can fix this by passing
it as a parameter, but is there an easier way?

Other notes:

In my specific use case, I'm using JSON::from_json($data) to
convert JSON data to a hash, which I then feed to the subroutine
below. I then print out @triplets and create an SQLite3 DB out of it. So it's really: JSON2hash, hash2rdf, rdf2sql. The entire program: https://github.com/barrycarter/bcapps/blob/master/bc-get-discogs.pl
JSON::GRDDL failed with an out-of-memory error on my data. My
subroutine doesn't. Is there another "prepackaged" solution I could
use?
I realize what I'm doing is a very minimal form of RDF.

=item hash2rdf($ref,$name="")

Given a scalar/array/hash reference $ref, returns RDF triplets recursively.

If $name is given, assigns name $name to $ref. Otherwise, creates a name

Pretty much does what var_dump() does, only in RDF

=cut

sub hash2rdf {
  my($ref,$name) = @_;
  my($type) = ref($ref);

  # if no type at all, just return self (after cleanup)
  unless ($type) {
    $ref=~s/\n/\r/isg;
    $ref=~s/\"/\\"/isg;
    return $ref;
  }

  # name I will give $ref if not given
  unless ($name) {$name = "REF".++$hash2rdf_count;}
  # TODO: making $hash2rdf_count global is bad
  # TODO: making @triplets global is unacceptably bad (but just testing now)
  # my(@triplets);

  if ($type eq "ARRAY") {
    # interim var
    my(@l) = @{$ref};
    # push triplets for my children
    for $i (0..$#l) {push(@triplets, [$name, $i, hash2rdf($l[$i])]);}
    # return the name I gave myself
    return $name;
  }

  if ($type eq "HASH") {
    # interim var
    my(%h) = %$ref;
    for $i (keys %h) {push(@triplets, [$name, $i, hash2rdf($h{$i})]);}
    return $name;
  }

  # hopefully it's referring to a scalar at this point!
  return $$ref;
}


texts: "Largest power of two less than N" in Python

texts:
def floor_log(num, base):
    if num < 0:
       raise ValueError("Non-negative number only.")
    exponent = 0
    while num > 1:
        num >>= 1
        exponent += 1
    return base << (exponent - 1)

print floor_log(3, 2) #2
print floor_log(4, 2) #4
print floor_log(5, 2) #4
print floor_log(6, 2) #4

I frequently miss the edge cases like while num or while num > 1. What is good strategy to avoiding these mistakes? apart from this the function seems fine to me. Comments are most welcome.


texts:
The code snippet below, receives data from a form, formats and inserts into the database.
This code snippet is located in a controller and the insertion is done in a 'repository' to manipulate data that entity laravel in my project.
Wonder if there are improvements to be made in this code for a great process of receiving, formatting, and data persistence.
- The method HelperRS :: date, gets a date in Brazil and format for timestamp formats.
- The method HelperRS :: real, gets a value in Brazil and format to format float.

// Formats data for inserting budget (orcamento)
$data['idCliente']          = $cliente->id_cliente;
$data['dataIni']            = ($data['dataIni']) ? HelperRS::data($data['dataIni'], 'ts') : NULL;
$data['dataFim']            = ($data['dataFim']) ? HelperRS::data($data['dataFim'], 'ts') : NULL;
$data['elaboradoPor']       = strtoupper(Auth::user()->nome);
$data['loginUsuario']       = Auth::user()->usuario;
$data['dataUltMudanca']     = ($data['dataUltMudanca']) ? HelperRS::data($data['dataUltMudanca'], 'ts') : NULL;
$data['descontoRecibo']     = ($data['descontoRecibo']) ? HelperRS::real($data['descontoRecibo'], 'fl') : NULL;
$data['total']              = ($data['total']) ? HelperRS::real($data['total'], 'fl') : NULL;
$data['totalSemDesconto']   = ($data['totalSemDesconto']) ? HelperRS::real($data['totalSemDesconto'], 'fl') : NULL;
$data['lembrar']            = ($data['lembrar']) ? HelperRS::data($data['lembrar'], 'ts') : NULL;;
$id_orcamento = $this->orcamentos->insert($data);


texts:
BFS and DFS in Java. Please give suggestions!!

Class Main {
    public void bfs()
    {
        // BFS uses Queue data structure
        Queue queue = new LinkedList();
        queue.add(this.rootNode);
        printNode(this.rootNode);
        rootNode.visited = true;
        while(!queue.isEmpty()) {
            Node node = (Node)queue.remove();
            Node child=null;
            while((child=getUnvisitedChildNode(node))!=null) {
                child.visited=true;
                printNode(child);
                queue.add(child);
            }
        }
        // Clear visited property of nodes
        clearNodes();
    }

    public void dfs() {
        // DFS uses Stack data structure
        Stack stack = new Stack();
        stack.push(this.rootNode);
        rootNode.visited=true;
        printNode(rootNode);
        while(!stack.isEmpty()) {
            Node node = (Node)s.peek();
            Node child = getUnvisitedChildNode(n);
            if(child != null) {
                child.visited = true;
                printNode(child);
                s.push(child);
            }
            else {
                s.pop();
            }
        }
        // Clear visited property of nodes
        clearNodes();
    }
}

Class Node {
   Char data;
   Public Node(char c) {
      this.data=c;
   }
}


texts: Can this simple percentage calculator be further optimized?

texts:
public double getValueWithPercentage(double number, double percentage)
{
    return number + ((percentage / 100.0) * number);
}

Are there any tricks to optimize this simple code?


texts: Merging client names into orders using RxJS

texts:
I have an API which I can't modify. I have to use data as it is.

I want to join data from two separate requests where the second request is based on data from the first one.

I have a working solution already but the code quality, in my opinion, is low so I want to know your opinion (and if you can provide: better, more reactive solution).

So, I have an order API that's receiving data:

/orders response:

[
  {
    id: 1,
    clientId: 201,
    // other data
  },
  {
    id: 2,
    clientId: 201,
  },
  {
    id: 3,
    clientId: 11,
  }
]

In this response, I don't have data about the client name, so I have a second API where I can pass IDs of clients and then I got back:

/clientsData?ids=201,11 response:

[
  {
    id:201,
    name: "Jon Doe"
  },
  {
    id: 11,
    name: "Jack Sparrow"
  }
]

So, now I have a working code but as mentioned, in the beginning, I'm feeling it can be done in a better way. Please, note that the request should be done in the correct order because I need clients IDs before I make a second API call.

Also, want to avoid making multiple (more than two [orders+clients]) requests to check client data.

Working code:

// API Call to get orders:
const result$ = this.http.get('/orders').pipe(
  mergeMap(
    orders => {
      const ids = orders
        .map(item => item.clientId)
        .filter((v, i, a) => a.indexOf(v) === i) // remove duplicates
        .join(','); // get client ids into one string

      // Client IDs: 1,2,99,201
      // API call to check IDs:
      return this.http.get(`/clientsData?ids=${ids}`).pipe(
        mergeMap(clientsData => {
          // map over each client
          clientsData.forEach(client => {
            // then map over each order
            orders.forEach(order => {
              // and assign client name to order
              if (order.clientId === client.id) {
                order.clientName = client.name;
              }
            });
          });

          return of(orders); // observable
        })
      );
    }
  )
);

result$.subscribe(console.log);

I expect to get back Observable with merged data:

[
  {
    id: 1,
    clientId: 201,
    name: "Jon Doe"
    // other data
  },
  {
    id: 2,
    clientId: 201,
    name: "Jon Doe"
  },
  {
    id: 3,
    clientId: 11,
    name: "Jack Sparrow"
  }
]

I want to avoid nested subscriptions and achieve the result in a reactive way.


texts: Recursively displaying json data on website

texts:
I am displaying the data from a json file onto a website, with recursive and iterative tables side by side. i have the iterative code working, but I have no idea on how to make it recursive.
Here is the code:
    $dataArray = json_decode($data, true);
            if(is_array($dataArray)){ //first level
                $result = "
";
                    foreach($dataArray as $key=>$val){ //second level
                        $result.="
".$key.": 	";
                        if(gettype($val)=="array"){
                            $result .= "
";
                            foreach($val as $subkey=>$subval){ //third level
                                $result.="
".$subkey.": 	";
                                if(gettype($subval)=="array"){
                                    $result .= "
";
                                    foreach($subval as $lowkey=>$lowval){ //fourth level
                                        $result.="
".$lowkey.": 	";
                                        if(gettype($lowval)!="array"){
                                            $result.=$lowval."
";
                                        }else{
                                            $result.="
";
                                        }
                                    }
                                    $result.="
";
                                }else{
                                    $result.=$subval."
";
                                }
                            }
                            $result.="
";
                        }else{
                        $result.=$val."
";
                        }
                    }
                $result.= "
";
            }else{
                echo "Not a valid format!";
            }
            return $result;


texts:
I previously posted a question for codereview:
Python Autoclicker
And I received some great feedback and changes to do in the code.
I have done many of the changes mentioned in the answers and here is the final code:
from pynput.keyboard import Controller
from time import sleep

def auto_click(key: str, n_clicks: int, delay: float):
    keyboard = Controller()

    for _ in range(n_clicks):
        keyboard.tap(key)
        sleep(delay)

def main():
    key = input("Key to be autopressed: ")

    try:
        n_clicks = int(input("Number of autopresses (integer): "))
    except ValueError:
        print("\n The number of autopresses should be an integer value, defaulting to 1. \n")
        n_clicks = 1

    try:
        delay = float(input("Delay between each autopress in seconds (integer/float): "))
    except ValueError:
        print("\n The delay between each autoclick should be an integer or a decimal value, defaulting to 1 (second). \n")
        delay = 1

    auto_click(key, n_clicks, delay)

if __name__ == '__main__':
    main()

What is it that you think should be made better in this code? Any feedback and suggestions would be much appreciated.
Here's the github repo:
https://github.com/SannanOfficial/AutoKeyPython


texts: Making a reservation using Selenium/PhantomJS

texts:
I have this small script that needs to make a reservation at a DMV office.

The problem is that the reservation window opens only every few hours for a few minutes (it might show up in one of these months: December, January, February or March of next year). My code is too slow to even "catch" the "open day".

Any ideas on how I can speed up the whole process? Maybe a different approach?

from selenium import webdriver
import time

firstName = "John"
lastName = "Smith"
yob = "1929"
email = "john.smith29@yolol.com"
phone = "555-123-4567"

browser = webdriver.PhantomJS()
browser.get("https://page/page2/ACFCustom/Se.aspx")

def check_date_avaialbility():
    # Choose a service
    browser.find_element_by_name("ct$cphBy$rS$ctl$btn1").click()
    # Choose an office
    browser.find_element_by_name("cphBy_rpt_btn1").click()

    # Loop through the next 4 months and search for an open window (The day will be highlighted in green)
    for i in range(1, 5):
        try:
            print("Searching for available day... ")
            browser.find_element_by_xpath("//*[contains(@style, 'background-color:#4A0889;')]").click()
            browser.find_element_by_xpath("//*[@id='cphBy_rblAT']").click()
            browser.find_element_by_id("cphBy_Nt").click()
            form_data()
        except:
            print("There are no available dates. Next page... \n")
            browser.find_element_by_name("ctl_cphBy_rdcAD_NN").click()
            time.sleep(1)

    # If you couldn't find anything three. Go back to the "home" page
    browser.find_element_by_name("cphBy_lnkbnK").click()
    time.sleep(1)
    # Start going through all the next 4 months all over again
    check_date_avaialbility()

def form_data():
    print("Filling up the form...")
    browser.find_element_by_id("cphBy_txbFN").send_keys(firstName)
    browser.find_element_by_id("cphBy_txbLN").send_keys(lastName)
    browser.find_element_by_id("cphBy_txbYB").send_keys(yob)
    browser.find_element_by_id("cphBy_txbE").send_keys(email)
    browser.find_element_by_id("cphBy_txbPN").send_keys(phone)
    browser.find_element_by_id("cphBy_S").click()

check_date_avaialbility()


texts: Merge all text files in a directory and save a temp file

texts:
I've coded this function where you read all text file in a directory and you save in a temporary file all values. The text files are x, y and z format. The function returns

the name of the temporary file
the bounding box
the origin (top-left corner)
and the bottom (bottom-right corner).

I wish for some comments or suggestion on how to improve my working code.

import os
import tempfile
import glob

class LaserException(Exception):
    """Laser exception, indicates a laser-related error."""
    pass

sepType = {
        "space": ' ',
        "tab": '\t',
        "comma": ',',
        "colon": ':',
        "semicolon": ';',
        "hyphen": '-',
        "dot": '.'
        }

def tempfile_merge(path,separator,wildcard= '*.txt'):
    file_temp = tempfile.NamedTemporaryFile(delete=False,dir=path)
    name = file_temp.name
    minx = float('+inf')
    maxx = float('-inf')
    miny = float('+inf')
    maxy = float('-inf')
    for file in glob.glob(os.path.join(path,wildcard)):
        for line in open(file, "r"):
            element = line.split(sepType[separator])
            if len(element) < 3:
                raise TypeError("not enough arguments: %s has only %s columns" % (inFile_name_suffix,len(element)))
            try:
                maxx = max(maxx, float(element[0]))
                minx = min(minx, float(element[0]))
                maxy = max(maxy, float(element[1]))
                miny = min(miny, float(element[1]))
            except ValueError:
                raise LaserException("x,y,z are not float-values")
            newelement = " ".join([str(e) for e in element])+ "\n"
            file_temp.write(newelement)
    file_temp.close()
    return(name, ((minx,maxy),(maxx,maxy),(maxx,miny),(minx,miny)),(minx,maxy),(maxx,miny))


texts:
I'm new to jQuery, and am using it to dynamically construct chunks of a page.

The created HTML is what I want, but I'm not sure if the way I'm generating it is sensible or idiomatic.

function setupIndex()
{
  $(document.body).append($("<img/>", {src : 'logo.png'}));
  var div = $("<div/>", {"class" : "content"}).appendTo(document.body);

  div.append("<h2/>", { text :'My Panels'});
  div.append($("<table/>", {id : 'maintable'}));
}

function addPanel(name, desc)
{
  if (!$("#maintable"))
    setupIndex();

  var row = $("<tr/>",{"class":"panels"}).appendTo("#maintable");

  var div = $("<td/>").appendTo(row);
  div.append($("<h3/>").append($("<a/>", { text : name, href : name + "/index.html"})));
  div.append(document.createTextNode(desc));

  div = $("<td/>").appendTo(row);

  var anc = div.append($("<a/>", {href: name + "/index.html"}));
  anc.append($("<img/>", { css : {width : "200px", height : "auto"}, src : name + "/thumbnail.png"}));
}


texts: Performing a regex search and saving results to CSV

texts:
I am a Python beginner, and I wrote a simple Python program, which does the following:

search the pattern in the lines of a file (contains messages)
pick the information from the lines and save it to disk
remove the messages which matches with the regex (regular expression)
saves remaining messages to another file,

Regexps are not available, so I pick one message -> create regex for it -> remove the matching messages and repeat the same with remaining messages.

# coding: utf-8

# In[50]:

import re
import csv

# ### Run this part only once in the starting. From here

# In[2]:

# ### Change the directory to working folder and give the right filename (hdfcbk),
# ### if unsure what to do go to your folder and right click and copy the filen here, it will look like /home/XYZ/.../Your_folder_name/hdfcbk
smsFile = open('hdfcbk', 'r')
data = smsFile.read()
data = data.split('\n')
main_data = data
regex_list = []
regl = []

# In[3]:
def regex_search(pattern, file_name):
   remove_arr = []
   res = []
   remain_sms = []
   for sms in file_name:
       j= re.match(pattern,sms)
       if j != None:
           res.append(j.groupdict())
           remove_arr.append(sms)
       else:
           remain_sms.append(sms)
   return res, remove_arr, remain_sms

# In[4]:

def write_to_csv(result,csv_name):
    keys = result[0][0].keys()
    with open(csv_name, 'wb') as output_file:
        dict_writer = csv.DictWriter(output_file, keys, dialect='excel')
        dict_writer.writeheader()
        dict_writer.writerows(result[0])

# In[12]:

# ### To here, now the repetitive run start

# ### Update this pattern file

# In[1]:

pat1 = 'INR (?P<Amount>(.*)) deposited to A\/c No (?P<AccountNo>(.*)) towards (?P<Towards>(.*)) Val (?P<Date>(.*)). Clr Bal is INR (?P<Balance>(.*)) subject to clearing.'

# In[8]:

A = regex_search(pat1,main_data)

# ### Updating main_data to remaining messages

# In[11]:

main_data = A[2]

# ### Writing remaining sms to a file, you don't need to change the file name as it will be updated everything as you run the script. Just look at the remaining sms and make new regex

# In[21]:

with open('remaining_sms.txt', 'w') as fp:
    fp.write('\n'.join('%s' % x for x in main_data))

# ### Update the csv file

# In[ ]:

write_to_csv(A, 'hdfc_test_3.csv')

# ### Keeping all the regexes in one list, update the index number in [i,pat1]

# In[52]:

regl.append([1,pat1])

# ### Wrting the regex index to csv, run this part in the end, or if you're unsure that you will make the mistake run this part and keep changing the output file name

# In[53]:

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(regl)

I commented everything in the code. Now the thing is, I need to send this task to some people, who does not know anything in coding. That's why I commented so much.

Can you please review my code and suggest what else I can do to improve the code so that people can run the code without any hassle?


texts: Nested template variable access in Meteor

texts:
I'm a brand new JavaScript guy (currently playing with Meteor) and would love some critique of the following:

The goal:  I've got two collections

Buckets
Widgets.

I'm displaying a select for each bucket, populated with an option for each widget.

The goal is simply to mark the appropriate option as selected if the bucket currently contains that widget.

I wrestled with this a bit and came up with what feels hack-ey

-- I'm explicitly passing the bucket's contents as a Handlebars variable.  I feel like there's a better way, but not sure how to get 'er done.

Is there a way to get access to the parent template instance's context from a nested template instance?  #each widget is being called from within #each bucket but this only gives me access to the child context.

(This works, I'm just trying to learn here).

HTML:

<template name="choices">
  {{#each bucket}}
    <label for='{{bucket_name}}'>{{bucket_description}}</label>
    <select id='{{bucket_name}}'>
      {{#each widget}}
        <option value="{{widget_name}}" {{selected ../bucket_contains}}>{{widget_description}}</option>
      {{/each}}
    </select>
  {{/each}}
</template>

JS:

if (Meteor.isClient) {
  Template.choices.bucket = function () {
    return Buckets.find({});
  };

  Template.choices.widget = function () {
    return Widgets.find({});
  };

  Template.choices.selected = function (parent) {
    return (this.widget_name === parent) ? 'selected' : '';
  };

  Template.choices.events({
    'change select': function (event) {
      Buckets.update({bucket_name: event.target.id}, {$set: {bucket_contains: event.target.value}});
    }
  });
}


texts:
// names are unique within a function, any valid variable name
// a jump table try, allowing return values to determine the exception thrown(index in a jump table, -1 being success for example)
// you only need to put in what you need, not all exceptions, or total exception count
#define GTRY(name, exc) void* __jt_##name[exc];int __jtix_##name = 0;
// register an exception in the jump table. you don't need to do them all
#define GTEX(name, exception) __jtix_##name;__jt_##name[__jtix_##name++] = &&__tr_##exception##name;
// resets the jump table index to a given value, useful for overwriting exceptions without a new try.
#define GTRST(name, index) __jtix_##name = index;
// a standard try, doesn't actually add anything, but for cleanliness.
#define TRY(name) ;
// throw an exception by name
#define THROW(name, exception) goto __tr_##exception##name;
// throws an exception by jump table index
#define GTHROW(name, exn) goto *__jt_##name[exn];
// begins a catch block
#define CATCH(name, exception) goto __trend_##name;__tr_##exception##name:;
// signifies where the try ends
#define ENDTRY(name) __trend_##name:;
// 'finally' blocks need only be put after an end try.

Usage Example:

int main(int argc, char* argv[]) {
    TRY(magic)
    THROW(magic, EOF)
    CATCH(magic, EOF)
    printf("eof!\n");
    ENDTRY(magic)
    printf("complete\n");
    GTRY(fagic, 2)
    int eof = GTEX(fagic, EOF)
    int rst = GTEX(fagic, RST)
    GTHROW(fagic, rst)
    CATCH(fagic, EOF)
    printf("eof2!\n");
    CATCH(fagic, RST)
    printf("rst\n");
    ENDTRY(fagic);
    //
    TRY(nest) {
        THROW(nest, EOF);
    } CATCH(nest, EOF) {
        printf("eof3!\n");
    }
    ENDTRY(nest)
    printf("complete3\n");
    return 0;
}

My purpose was to create a macro-based exception system that can run on embedded devices with ease(magic is done compile-time). There is a potential performance malice if CPUs don't support labels as values and GTRY is used.


texts:
I have a view model that I'm migrating to RxUI. It exposes a collection of brokers along with a bool indicating whether there is a market (ie. at least one broker). In addition, it has a property for the currently selected broker (the user can choose a broker via a drop-down):

private IReactiveCollection<SourceViewModel> brokers;
public IReactiveCollection<SourceViewModel> Brokers
{
    get { return this.brokers; }
    private set { this.RaiseAndSetIfChanged(x => x.Brokers, ref this.brokers, value); }
}

private ObservableAsPropertyHelper<bool> isMarket;
public bool IsMarket
{
    get { return this.isMarket.Value; }
}

private SourceViewModel selectedBroker;
public SourceViewModel SelectedBroker
{
    get { return this.selectedBroker; }
    set { this.RaiseAndSetIfChanged(x => x.SelectedBroker, ref this.selectedBroker, value); }
}

I have these pieces hooked up and working, but I am not convinced I've done this in the most reactive-friendly fashion:

this.WhenAny(x => x.Volatilities, x => x.Value)
    .StartWith((ItemObservableCollection<VolatilityViewModel>)null)
    .Subscribe(x =>
        {
            if (x == null)
            {
                // no volatilities, so definitely no market
                this.Brokers = null;
                this.SelectedBroker = null;
                this.isMarket = Observable.Return(false).ToProperty(this, y => y.IsMarket);
            }
            else
            {
                // we have volatilities, so potentially we have a market

                // TODO: is there a better means of doing this?
                this.Brokers = x.CreateDerivedCollection(y => y.Source);

                // TODO: is there a cleaner way to do this?
                this.Brokers.Changed
                    .Select(y => true)
                    .StartWith(true)
                    .Subscribe(y =>
                        {
                            var volatility = x.FirstOrDefault();
                            this.SelectedBroker = volatility == null ? null : volatility.Source;
                        });

                // TODO: is there a cleaner way to do this?
                this.isMarket = this.Brokers.CollectionCountChanged.Select(y => y > 0).StartWith(x.Count > 0).ToProperty(this, y => y.IsMarket);
            }
        });

My Volatilities property is set when the user interacts with a specific set of vols. Everything hinges off of it. It's currently an ItemObservableCollection, but I may change it later to be a reactive collection. I don't believe that's relevant here, but I could be wrong.

The parts I'm concerned about have TODOs in the code, but to summarize:

when my Volatilities property changes, so too do the available brokers. I currently create a new derived collection each time Volatilities changes. I couldn't come up with any way to avoid this or implement it more cleanly.
when I recreate my brokers collection, I immediately set up a Changed observer so that any changes result in the first broker being selected. The reasoning is that the first broker will (once I do sorting) be the preferred broker, so any changes in the market should instigate the selection of the preferred broker. I couldn't think of a way to make this logic cleaner and simpler.
in addition, I also recreate my isMarket member, which is true whenever there is at least one broker in the brokers collection. Again, I'm not sure that this is the best approach to achieving this.

Can anyone weigh in with their thoughts on this?


texts: Can I shorten this assembly code to test if a number is even?

texts:
Here is MIPS code to return 1 if a number is even, 0 otherwise:
isEven:
  andi $t0, $a0, 1
  li   $t1, 1
  sub  $v0, $t1, $t0
  jr   $ra

My question is whether this can be done in fewer instructions. I could implement isOdd in two instructions (by eliminating the li and sub), but I don't see a single-instruction way to invert just the bottom bit of $t0 into $v0.


texts: Socket server with consumer-producer design to handle concurrent connections

texts:
The usual way is to implement socket server to handle concurrent requests by creating new thread for each request.

Instead of this approach i tried to create a server using consumer-producer design, as follows.

Main thread

//holds socket instances
ConcurrentLinkedQueue<Socket> queue = new ConcurrentLinkedQueue<>();

//create producer thread
Thread producer = new Thread(new RequestProducer(queue));
//create consumer thread
Thread consumer = new Thread(new RequestConsumer(queue));

producer.start();
consumer.start();

RequestProducer thread

//this holds queue instance coming from main thread
ConcurrentLinkedQueue<Socket> queue

//constructor, initiate queue
public RequestProducer(
    ConcurrentLinkedQueue<Socket> queue
) {
    this.queue = queue;
}

public void run() {
    try {
        //create serversocket instance on port 19029
        ServerSocket serverSocket = new ServerSocket(19029);
        while (true) {
            try {
                //keep accept connections
                Socket socket = serverSocket.accept();
                //add socket to queue
                queue.offer(socket);
            } catch (ConnectException ce) {//handle exception
            } catch (SocketException e) {//handle exception
            }
        }
    } catch (IOException ex) {//handle exception}
}

RequestConsumer thread

//this holds queue instance coming from main thread, same as requestproducer
ConcurrentLinkedQueue<Socket> queue

//constructor, initiate queue
public RequestConsumer(
    ConcurrentLinkedQueue<Socket> queue
) {
    this.queue = queue;
}

public void run() {
    try {
        Socket socket = null;
        while (true) {
            //get head of the queue (socket instance)
            socket = queue.poll();
            if (null != socket) {
                //process data stream
                String in = DataStreamUtil.parseUtfSockStream(socket.getInputStream());
                //close socket conection
                socket.close();
                //excecute database insert of processed data
                excecuteDbInsert(in);
            }
        }
    } catch (IOException | ParseException ex) {//handle exceptions}
}

Note: no need to send response back to the client
Also, i haven't tested this yet in concurrent environment.

My questions are,

what are the pros and cons of this approach ?
how can i improve this ?
any other suggestions are highly appreciated.


texts:
The task:

  Write a function that rotates a list by k elements. For example, [1,
  2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2]. Try solving
  this without creating a copy of the list. How many swap or move
  operations do you need?

const lst = [1, 2, 3, 4, 5, 6];
const rotateBy = 2;

The functional solution takes 2 operations (slice twice)?:

// I guess a slice is technically not a "copy of the list" but rather it's sub-elements, so it's allowed?

const rotate = (lst, rotateBy) => [...lst.slice(rotateBy % lst.length), ...lst.slice(0, rotateBy % lst.length)];

console.log(rotate(lst, rotateBy));

console.log(rotate(lst, rotateBy));

The imperative solution takes as many operations as there are elements:

function rotate(lst, rotateBy) {
  const res = [];
  for (let i = rotateBy % lst.length, len = lst.length; res.length < len; i = ++i % len) {
    res.push(lst[i]);
  }
  return res;
}
console.log(rotate(lst, rotateBy));


texts:
I just started to learn Java and had to write a "guess the number" game.

Could you please review and give me some feedback?

public static void main(String[] args) {

    System.out.println("Welcome to the guess the number game!\n");
    System.out.println("Please specify the configuration of the game:\n");

    Scanner input = new Scanner(System.in);

    System.out.println("Range start number (inclusively):");
    int startRange;
    startRange = nextValidInt(input);

    System.out.println("Range end (inclusively):");
    int endRange;
    endRange = nextValidInt(input);

    System.out.println("Maximum number of attemps:");
    int maxAttemp;
    maxAttemp = nextValidInt(input);

    System.out.println("Your Task is to guess the random number between "
            + startRange + " and " + endRange);

    Random randGenerator = new Random();
    int randNumber = randGenerator.nextInt((endRange - startRange + 1)
            + startRange);
    int numberOfTries = 0;

    System.out
            .println("You may exit the game by typing; exit - you may now start to guess:");

    for (numberOfTries = 0; numberOfTries <= maxAttemp - 1; numberOfTries++) {

        int guess;
        guess = nextValidInt(input);

        if (guess == randNumber) {
            System.out.println("Congratz - you have made it!!");
            System.out.println("Goodbye");
            break;
        } else if (guess > randNumber) {
            System.out.println("The number is smaller");
        } else if (guess < randNumber) {
            System.out.println("The number is higher");
        }

    }

    if (numberOfTries >= maxAttemp) {
        System.out.println("You reached the max Number of attempts :-/");
    }

}

public static int nextValidInt(Scanner s) {
    while (!s.hasNextInt() && s.hasNext()) {
        System.out.println("Please provide a valid integer value!");
        s.next();
    }
    return s.nextInt();

}


texts: Check if string can be rearranged into a palindrome

texts:
I created a function to test whether a single word string can be a rearranged into a palindrome (doesn't have to be a real word). My logic was if the string has an even number of letters, then each letter must occur twice. If the string has an odd number of letters, each letter must occur twice except for one.

function checkPalindrome(str) {
    var letters = str.split(''),
        unique = [],
        match = {},
        single = [];

    var findUnique = function(arr, letter) {
        for (var k = 0; k < arr.length; k++) {
            if (arr[k].match(letter) && !unique.join('').match(letter)) {
                unique.push(arr[k]);
            }
        }
    }

    var sortLetters = function(arr, letter) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === letter) {
                if (match[letter] === undefined) {
                    match[letter] = 1;
                } else {
                    match[letter]++;
                }
            }
        }
    }

    for (var j = 0; j < letters.length; j++) {
        findUnique(letters, letters[j]);
    }

    for (var m = 0; m < unique.length; m++) {
        sortLetters(letters, unique[m]);
    }

    for (var key in match) {
        if (match[key] % 2 !== 0) {
            single.push(match[key])
        }
    }

    if (letters.length % 2 === 0) {
        if (single.length === 0) {
            return true;
        } else {
            return false;
        }
    } else {
        if (single.length === 1) {
            return true;
        } else {
            return false;
        }
    }
}

Any tips on how to improve this function in terms of efficiency ?


texts:
I have a small node.js app (MY FIRST)

I have models using mongoose, controllers for each and a seperate route, I feel like this is pretty good seperation but something about the number of route files i would have to create seems not route, basically every section of the restful api would have a route, model and controller, this keeps everything nice and tidy but I had a few question or wishes for recommendations

The complete code can be found here
https://github.com/ninjatalent/starternodejs

however i will detail out one specific area i have questions below

in my app.js i have

app.use('/api/issue', issueWebsiteRouter);
app.use('/api/project', projectRouter);

This is because i can specify a router to handle /issue or /project, but this means that I will create a router for each of this.  Is this fairly common?  Good architecture?  Let me show you an example of a router

var express = require('express');

var route = function(Issue){

var issueWebsiteController = require('../controllers/issueWebsiteController')(Issue)  // putting elements in controllers to make it easier for unit testing etc, inject mongoose Issue model
var appRouter = express.Router();
appRouter.route('/')
    .post(issueWebsiteController.post)
    .get(issueWebsiteController.get);

// this is some middleware we are injecting when we are looking at an id we see if there is a book, we add it to request and next moves us to the next method
appRouter.use('/:id', function(req,res,next){
    Issue.findById(req.params.id, function(error,issue){
        if(error)
        {
            res.status(500).send(error);
        }
        else if(issue)
        {
            req.issue = issue;
            next();

        }
        else
        {
            res.status(404).send('no book found');
        }
    });
});
appRouter.route('/:id')

    .get(function(req,res){

        res.json(req.issue);// we wont get here if there is a 404 from above

    })
    .put(function(req,res){

        req.issue.url = req.body.url;
        req.issue.reporter = req.body.reporter;
        req.issue.title = req.body.title;
        req.issue.description = req.body.description;
        req.issue.browser = req.body.browser;
        req.issue.device = req.body.device;
        req.issue.save(function(error){ // on saving if error display error otherwise send back saved element
            if(error)
            {
                res.status(500).send(error);
            }
            else
            {
                res.json(req.issue);
            }
        });

    })
    .patch(function(req,res){
        if(req.body._id)
        {
            delete req.body._id;
        }
        for(var p in req.body) // for every key in req.body
        {
            req.issue[p] = req.body[p]; // we are assigning everything in req.issue to req.body
        }
        req.issue.save(function(error){ // on saving if error display error otherwise send back saved element
            if(error){
                res.status(500).send(error);
            }
            else
            {
                res.json(req.issue);
            }
        });
    })
    .delete(function(req,res){
       req.issue.remove(function(error){
           if(error)
           {
               res.status(500).send(error);
           }
           else
           {
               res.status(204).send('Removed'); // 204 means removed
           }
       }); // take whatever is found in middleware and remove it
    });
return appRouter;
};

module.exports = route;

Since the put delete etc for each of these is potentially going to be different it feels like I have to have a seperate route, again suggestions please


texts:
This is a simple C++ code with a function mult to multiply matrices. This can easily be generalized for any \$n \times n\$ matrix by replacing 4 with any positive number greater than 1.

The multiplication is done by iterating over the rows, and iterating (nested in the rows iteration) over the columns. While inside the columns iteration, the multiplication is performed, which is a dot product (again using a new iteration).

The simple demo shows the multiplication of \$A \times A\$.

I wonder if there are better ways in writing this.

Code:

#include <iostream>
#include <string>

using namespace std;

int mult(int A[4][4], int B[4][4]){

int C[4][4], num;

for (int i=0; i<4; i++){
     for(int j=0; j<4; j++){
        num = 0;
        for(int k=0; k<4; k++){
          num += A[i][k]*B[k][j];
}
      C[i][j]=num;
      cout << num << " ";
}
     cout << endl;
}

return 0;

}

int main(){

   int A[4][4], ind=0;
cout << "Default Matrix A: \n \n";

   for (int i=0; i<4; i++){
     for(int j=0; j<4; j++){
      A[i][j]=ind; ind++;
      cout<< A[i][j]<< " ";
}
     cout << endl;

}
    cout << "\nMultiplication of A^2: \n \n";
mult(A,A);
return 0;

}

Output:

Default Matrix A:

    0 1 2 3
    4 5 6 7
    8 9 10 11
    12 13 14 15

Multiplication of A^2:

56 62 68 74
152 174 196 218
248 286 324 362
344 398 452 506


texts: Is this a secure way to hash a password?

texts:
I'm implementing a login system on app engine (I have to, so please don't tell me to use the User service, or an other way to delegate authentication), and I'm wondering whether this setup is secure.

from pbkdf2 import PBKDF2
import os

salt = os.urandom(8)
password = PBKDF2(passphrase, salt).read(32).encode("hex")

Would this be a secure way to store passwords?


texts: Polyglot function to sum all the numbers in an array in Javascript and PHP

texts:
This, again, is a very simple code.

This is my 2nd polyglot question and this time I've tried to do something that I miss sometimes in Javascript.

PHP has the array_sum() function, but Javascript has no direct equivalent.

So, I decided to make one that works with both languages!

Here is the code:

function sum_array()
{
    if( $javascript = '\0' == "\0" )
    {
        $vars = new Object();
        $vars['args'] = arguments;
        $vars['l'] = arguments.length;
    }
    else
    {
        $vars = Array();
        $vars['args'] = func_get_args();
        $vars['l'] = func_num_args();
    }

    for( $vars['sum'] = $vars['i'] = 0; $vars['i'] < $vars['l']; $vars['i']++ )
    {
        $vars['m'] = $javascript ? $vars['args'][$vars['i']].length : count($vars['args'][$vars['i']]);

        for( $vars['j'] = 0; $vars['j'] < $vars['m']; $vars['j']++ )
        {
            $vars['sum'] += ( $vars['args'][$vars['i']][$vars['j']] / 1 ? $vars['args'][$vars['i']][$vars['j']] : 0 );
        }
    }

    return $vars['sum'];
}

Usability is really easy:

Simply pass multiple arrays as arguments. In PHP, it is required to be an array with only numeric keys. This is due to the limitations of Javascript.

Example of usage:

sum_array([1,2,3,4,5],[15]); //should return 30 in Javascript and PHP 5.4+

To avoid 'poisoning' the window object, I only created 2 variables and use one of them as an array (The other is just to save if we are running in Javascript or PHP).

Was this a good decision?

What else can I improve on my code?


texts:
I made a solution to this problem from HackerRank :

  You are given a list of N people who are attending ACM-ICPC World
  Finals. Each of them are either well versed in a topic or they are
  not. Find out the maximum number of topics a 2-person team can know.
  And also find out how many teams can know that maximum number of
  topics.

  Note Suppose a, b, and c are three different people, then (a,b) and
  (b,c) are counted as two different teams.

  Input Format

  The first line contains two integers, N and M, separated by a single
  space, where N represents the number of people, and M represents the
  number of topics. N lines follow. Each line contains a binary string
  of length M. If the ith line's jth character is 1, then the ith person
  knows the jth topic; otherwise, he doesn't know the topic.

My code is considered too slow (I think I am allowed 10 seconds, the code below takes more than 20 seconds when N and M are both 500):

import random
import itertools
import time

# n number of people
# m number of topics

n = 500
m = 500

"""
binary_string(n) and random_list(n_people, n_topic) just help
to generate test cases, irrelevant otherwise.
"""

def binary_string(n):
    my_string = "".join(str(random.randint(0, 1)) for _ in range(n))
    return my_string

def random_list(n_people, n_topic):
    my_list = [binary_string(n_topic) for _ in range(n_people)]
    return my_list

"""
the essential part is item_value(e1, e2)
and find_couples(comb_list)
"""

def item_value(e1, e2):
    c = bin(int(e1, 2) | int(e2, 2))
    return sum(int(i) for i in c[2:])

def find_couples(comb_list):
    max_value = 0
    counter = 0

    for pair in itertools.combinations(comb_list, 2):
        value = item_value(pair[0], pair[1])
        if value == max_value:
            counter += 1
        elif value > max_value:
            max_value = value
            counter = 1

    print(max_value)
    print(counter)
    return

topic = random_list(n, m)

print(topic)

start = time.time()
find_couples(topic)
end = time.time()
print(end - start)

In the context of the above algorithm, in what ways can I make it more efficient?
Is there a better algorithm?


texts:
Is there anything specifically bad here, or anything that I could improve? Wasted lines of code, things done in a more memory intensive way than it could be, etc.

from random import*
b = 10
a = randint(1,b)
point = 1
x = 1
while x < 2:
    print("Guess a number between 1 and ", b)
    svar = int (input())
    if svar == a:
            b+=5
            point= point+point
            a = randint (1,b)
            print("You have ", point, "points!")
    elif svar < a:
            print("Higher")
    else:
            print("Lower")