texts: Project Euler 19 (count Sundays in the 20th Century) with a while loop

texts:
I'm working on Project Euler problem 19, which reads as follows:

  You are given the following information, but you may prefer to do some research for yourself.

  1 Jan 1900 was a Monday.
     Thirty days has September,
     April, June and November.
     All the rest have thirty-one,
     Saving February alone,
     Which has twenty-eight, rain or shine.
     And on leap years, twenty-nine.
     A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

  How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

Note that my title is slightly misleading because this isn't counting all of the Sundays in the 20th Century, just the ones that fall on the first day of the month.

Here's my code:

public int HowManySundays()
    {
        // Have an array with the number of days in each month. For example, month 0 is January,
        // which has 31 days.
        int[] daysInEachMonth = new int[]
        {
            31,
            28,
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31
        };

        int currentYear = 1900;

        // First year in 1900
        // We could calculate the first Sunday in 1901 to save a little time
        // but that's not all *that* much of an optimization so it's not terribly important
        int currentDay = 7;

        int currentMonth = 0;

        int numberOfSundays = 0;

        while (currentYear < 2001)
        {
            // Add 7 each time so that we know that it's another Sunday
            currentDay += 7;

            // I don't particularly like the special reasoning for February for leap-year detection
            // We don't actually have to do separate logic for centuries because the only century we
            // care about is the year 2000, which we already know is evenly divisible by 400
            int daysInMonth =
                currentMonth == 1 ?
                    ((currentYear % 4 == 0) ? 29 : 28) :
                    daysInEachMonth[currentMonth];

            if (daysInEachMonth[currentMonth] < currentDay)
            {
                currentDay -= daysInEachMonth[currentMonth];
                currentMonth++;

                // Months are 0 - 11
                // See if we've wrapped around to a new year
                if (currentMonth >= 12)
                {
                    currentMonth = 0;
                    currentYear++;
                }

                // If day == 1, then it must be a Sunday on the first day of the month
                if (currentDay == 1 && currentYear > 1900)
                {
                    numberOfSundays++;
                }
            }
        }

        return numberOfSundays;
    }

I have a trivial unit test (not included here) proving that my method does, in fact, return the correct answer (171).

Does anyone have feedback on this (especially on its readability)? Is this decently efficient, or did I miss some optimizations?


texts:
I've written a script in python using "threading" module to scrape two sites simultaneously. It parses the two sites flawlessly. Any insight as to how I can improve this script will be appreciated.

Here is what I did:

import requests ; from lxml import html
import threading ; import time

Yp_link = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA&page=2"
Tuts_link = "http://www.wiseowl.co.uk/videos/"

def create_links(url):
    response = requests.get(url).text
    tree = html.fromstring(response)
    for title in tree.cssselect("div.info"):
        name = title.cssselect("a.business-name span[itemprop=name]")[0].text
        street = title.cssselect("span.street-address")[0].text
        phone = title.cssselect("div[itemprop=telephone]")[0].text if title.cssselect("div[itemprop=telephone]") else ""
        time.sleep(1)
        print(name, street, phone)

def process_links(link):
    response = requests.get(link).text
    tree = html.fromstring(response)
    for titles in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
        title = titles.xpath('.//a')[0]
        time.sleep(1)
        print(title.text, title.attrib['href'])

th1 = threading.Thread(target=create_links, args=(Yp_link,))
th2 = threading.Thread(target=process_links, args=(Tuts_link,))

th1.start()
th2.start()

th1.join()
th2.join()


texts:
Deleting folders programmatically is extremely dangerous. It is enough for somebody else to change a configuration file or constant variable including the target folder's name to, say C:\, and that's it: the workstation is paralyzed!

The following suggested methods are to prevent such a situation. Their aim is to wrap the low level, possibly recursive file system operation with the necessary validation and clear facade - look twice, delete once.

Delete temporary directory created by current user (non recursive!)

/// <summary>
/// carefully remove directory and its files
/// verify the directory is located under the %temp%
/// and it is not e.g. C:\
/// </summary>
/// <param name="dir"></param>
public static void DeleteTempDirShallow(string dir)
{
    // check if it is an invalid directory path,
    // e.g. a disk drive or just a bad string
    if (! Directory.Exists(dir)) return;

    DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath());
    DirectoryInfo dirInfo = new DirectoryInfo(dir);

    if (dirInfo.FullName.Contains(userTempDirInfo.FullName))
    {
        foreach (FileInfo file in dirInfo.GetFiles())
            file.Delete();

        dirInfo.Delete(); // just clean up the empty dir
    }
}

Delete temporary directory created by current user (recursive!)

public static void DeleteTempDirRecursive(string dir)
{
    // check if it is an invalid directory path,
    // e.g. a disk drive or just a bad string
    if (! Directory.Exists(dir)) return;

    DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath());
    DirectoryInfo dirInfo = new DirectoryInfo(dir);

    if (dirInfo.FullName.Contains(userTempDirInfo.FullName))
    {
        dirInfo.Delete(recursive: true);
    }
}

Do I try to delete any root or system folder?

static List<string> systemDirs = new List<string>
{
    Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles),
    Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86),
    Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
    Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu),
    Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup),
    Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
    Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts),
    Environment.GetFolderPath(Environment.SpecialFolder.PrinterShortcuts),
    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
    Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
    Environment.GetFolderPath(Environment.SpecialFolder.Resources),
    Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),
    Environment.GetFolderPath(Environment.SpecialFolder.Startup),
    Environment.GetFolderPath(Environment.SpecialFolder.System),
    Environment.GetFolderPath(Environment.SpecialFolder.SystemX86),
    Environment.GetFolderPath(Environment.SpecialFolder.Templates),
    Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
    Environment.GetFolderPath(Environment.SpecialFolder.Windows),
};

/// <summary>
/// check if the argument dir is adisk drive,
/// is a system (sub-)folder
/// and should not be erased
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public static bool IsSystemOrRootDir(string dir)
{
    // check if it is an invalid directory path,
    // or just a bad string
    if (! Directory.Exists(dir)) return true;

    DirectoryInfo dirInfo = new DirectoryInfo(dir);

    // is it a root (disk drive)?
    if (dirInfo.Parent == null) return true;

    bool result = false;
    systemDirs.ForEach(sysDir => { result = result ||
                                   dirInfo.FullName.Contains(sysDir); } );
    return result;
}

References

How to check if directory 1 is a subdirectory of dir2 and vice versa
How to delete all files and folders in a directory?


texts: One method for changing one of the properties

texts:
I have a few resources set in my class – coins, diamonds, hearts, enum of these resources names, and method for increasing specified resource. I want to make single "Increase" method for all resources that wouldn't have switch statement. Sort of single-line not overloaded "generic" method independently on which property to increase. Below is the best what I achieved so far. Please advice on best approach to be taken for the described Increase method.

public enum ResourceType { Coins, Diamond, Hearts };

private static int Coins { get { return resourceBox[ResourceType.Coins]; } }
private static int Diamonds { get { return resourceBox[ResourceType.Diamonds]; } }
private static int Hearts { get { return resourceBox[ResourceType.Hearts]; } }
private static Dictionary<ResourceType, int> resourceBox = new Dictionary<ResourceType, int>();

private void Init()
{
    resourceBox.Add(ResourceType.Coins, 0);
    resourceBox.Add(ResourceType.Diamond, 0);
    resourceBox.Add(ResourceType.Hearts, 0);
}

public static void Increase(ResourceType _res, int _income)
{
resourceBox[_res] += _income;
}

However this leads to situation where Dictionary is a primary resource storage, which may not be desired in future.
I wonder what could be another (not obligatory dictionary) way to create Increase method as described above.


texts: Make sure the user enters a valid floating-point number in C

texts:
I would like to know if this is a good way to make sure the user enters a valid number.

#include <stdio.h>
#include <ctype.h>

void clear_stream(FILE *in)
{
   int ch;
   clearerr(in);

   do
      ch = getc(in);
   while (ch != '\n' && ch != EOF);

   clearerr(in);
}

float retreive_input()
{
    float input = 0;
    fflush(stdout);
    while (scanf_s("%f", &input) != 1)
    {
        clear_stream(stdin);
        printf("Invalid number. Please try again: ");
        fflush(stdout);
    }

    return input;
}

int main()
{
    float input = 0;
    printf("ENTER A NUMBER: ");
    input = retreive_input();
    printf("YOUR INPUT: %f", input);

    getchar();
    return 0;
}


texts:
I'm trying to implement Dijkstra's algorithm to find the shortest path. This is from a challenge on CodeWars.

In this scenario there is a map:

[
  [1,2,3],
  [4,8,2],
  [1,5,3],
]

We start at the position 0, 0 and we can only move right or down. Our goal is to reach the position x, y passed to the function and get the sum of the shortest path. In this case the result would be 1+2+3+2+3 = 11 (for x and y pointing to the end of the square.

I implemented this code as an attempt to solve the challenge, but it times out. (It is safe to run, the part that timeout is commented).

const minPath = (grid, x, y) => {
  const maxWidth = x;
  const maxHeight = y;

  let next = [{ x: 0, y: 0, weight: grid[0][0] }];
  let arr = next;

  do {
    arr = next;
    next = [];

    for (let i = 0; i < arr.length; ++i) {
      let node = arr[i];

      if (node.x < maxWidth) {
        next.push({
          x: node.x + 1,
          y: node.y,
          weight: node.weight + grid[node.y][node.x + 1]
        });
      }

      if (node.y < maxHeight) {
        next.push({
          x: node.x,
          y: node.y + 1,
          weight: node.weight + grid[node.y + 1][node.x]
        });
      }
    }
  } while (next.length);

  return Math.min(...arr.map(o => o.weight));
};

const smallSquare = [
  [1,2,3],
  [4,8,2],
  [1,5,3],
];

console.time('small');
console.log(minPath(smallSquare, smallSquare.length - 1, smallSquare.length - 1));
console.timeEnd('small');

// just an example, values can be generated at random
const bigSquare = [[29,24,84,67,8,9,52,47,68,58,33,58,69,80,26],[95,98,94,47,20,70,46,87,80,82,96,28,4,52,10],[9,70,31,22,87,71,46,33,79,28,26,56,26,7,73],[35,2,88,70,20,41,39,85,35,35,19,1,41,85,63],[59,87,27,33,60,65,12,5,17,60,10,26,11,10,8],[6,15,49,32,54,39,93,28,32,32,51,52,13,92,44],[6,58,26,88,78,73,71,60,77,20,49,43,35,27,38],[59,73,86,52,27,85,74,67,85,72,92,55,31,76,43],[25,60,14,92,49,23,51,93,8,21,94,35,63,33,33],[34,33,18,99,67,38,36,80,5,6,82,87,33,97,3],[54,88,53,82,31,36,69,83,73,92,89,0,19,48,12],[6,89,54,88,35,13,1,33,38,31,59,93,29,72,55],[3,94,94,6,41,19,19,4,31,71,0,64,76,12,85],[96,20,58,69,65,79,40,25,58,52,79,17,97,32,42],[12,86,40,49,63,98,65,8,14,90,15,8,53,57,65]];

// This will break the page if run here
// console.time('bigSquare');
// console.log(minPath(bigSquare, bigSquare.length - 1, bigSquare.length - 1));
// console.timeEnd('bigSquare');

It seems to work pretty well, however, my solution is timing out all the time (12s+).

The first big test passes the position 29,29 (see grid here)

I wonder if I'm implementing it right. Is there something wrong? Is there a way to improve performance so it can work for really big maps?


texts:
I'm trying to solve Project Euler problem #3, which asks:

  The prime factors of 13195 are 5, 7, 13 and 29.
  What is the largest prime factor of the number 600851475143 ?

Can you please review the code and suggests improvements?

namespace FullPractice
{
  public class PrimeFactorFinder
  {
    private readonly HashSet<int> _myPrimeFactors = new HashSet<int>();
    private long _myNumber;

    public void PrimeFactors(long number)
    {
        _myNumber = number;
        FindPrimeFactors();
        DisplayAllPrimeFactors();
        ShowLargestPrimeFactor();
    }

    private void ShowLargestPrimeFactor()
    {
        Console.WriteLine("\nLargest Prime Factor = {0}",_myPrimeFactors.Last());
    }

    private void FindPrimeFactors()
    {
        long temp = _myNumber;
        int primeNumber = 2;
        while (temp != 1)
        {
            if (temp%primeNumber == 0)
            {
                _myPrimeFactors.Add(primeNumber);
                temp = temp/primeNumber;
            }
            else
            {
                primeNumber = GetPrimeNumberAfter(primeNumber);
            }
        }
    }

    private void DisplayAllPrimeFactors()
    {
        Console.WriteLine("All prime factors of {0} are : ", _myNumber);
        foreach (var primeFactor in _myPrimeFactors)
        {
            Console.Write("{0},", primeFactor);
        }
    }

    private int GetPrimeNumberAfter(int primeNumber)
    {
        var next = primeNumber + 1;
        while (true)
        {
            if (IsPrime(next))
            {
                return next;
            }
            next++;
        }
    }

    private bool IsPrime(int number)
    {
        if (number%2 == 0)
        {
            return false;
        }
        var sqaureRoot = (int)Math.Sqrt(number);
        for (int divisor = 3; divisor < sqaureRoot; divisor += 2)
        {
            if (number%divisor == 0)
            {
                return false;
            }
        }
        return true;
    }
}
}


texts:
As a learning exercise I wrote a short C program that changes the instructions of a function at runtime in order to execute a shell. It's obviously dependent on x86_64 architecture and Linux (for the syscall number). Indeed, it does start a shell when I run it. I was told to post it here by someone on StackOverflow so what I'm wondering is if there is anything that I'm overlooking in the overall concept or if anything can be improved?

For the sake of brevity, below is only the final product. I wrote up a much longer explanation of the whole process on my blog, but I'm only concerned about the code below, not my long explanation of it.

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>

void foo(void);
int change_page_permissions_of_address(void *addr);

int main(void) {
    void *foo_addr = (void*)foo;

    // Change the permissions of the page that contains foo() to read, write, and execute
    // This assumes that foo() is fully contained by a single page
    if(change_page_permissions_of_address(foo_addr) == -1) {
        fprintf(stderr, "Error while changing page permissions of foo(): %s\n", strerror(errno));
        return 1;
    }

    puts("Calling foo");
    foo();

    char shellcode[] =
        "\x48\x31\xd2"                              // xor    %rdx, %rdx
        "\x48\x31\xc0"                              // xor    %rax, %rax
        "\x48\xbb\x2f\x62\x69\x6e\x2f\x73\x68\x00"  // mov    $0x68732f6e69622f2f, %rbx
        "\x53"                                      // push   %rbx
        "\x48\x89\xe7"                              // mov    %rsp, %rdi
        "\x50"                                      // push   %rax
        "\x57"                                      // push   %rdi
        "\x48\x89\xe6"                              // mov    %rsp, %rsi
        "\xb0\x3b"                                  // mov    $0x3b, %al
        "\x0f\x05";                                 // syscall

    // Careful with the length of the shellcode here depending on what is after foo
    memcpy(foo_addr, shellcode, sizeof(shellcode));

    puts("Calling foo");
    foo();

    return 0;
}

void foo(void) {
    int i=0;
    i++;
    printf("i: %d\n", i);
}

int change_page_permissions_of_address(void *addr) {
    // Move the pointer to the page boundary
    int page_size = getpagesize();
    addr -= (unsigned long)addr % page_size;

    if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
        return -1;
    }

    return 0;
}


texts: File loop and logic in controller of view header

texts:
I have the following in the header.php file which is included in all of my views:

$dh = opendir(Vs.get_class($this).'/js') ;
while($script = readdir($dh)) {
    if(!is_dir($script))
    {
        echo '<script type="text/javascript" src="js/'.$script.'"></script>' ;
    }
}

$dh = opendir(Vs.get_class($this).'/css') ;
while($css = readdir($dh)) {
    if(!is_dir($css))
    {
        echo '<link type="text/css" href="css/'.$css.'" rel="stylesheet"/>' ;
    }
}

It's purpose is to autoload all the CSS and JS files for a particular view (which has the same name as the controller, hence get_class).

Should all this be a part of the associated controller or is how I have done it fine?


texts:
Is this code pythonic, easy to read, stable, or missing something?

# -*- coding: utf-8 -*-
""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs
from unicodedata import normalize

def flatten_unicode_keys(dic):
    '''pass unicode keywords to **kwargs '''
    for key in dic.keys():
        if isinstance(key, unicode):
            value = dic[key]
            del dic[key]
            dic[normalize('NFKD',key).encode('ascii','ignore')] = value

def entry2html(**kwargs):
    """ Format feedparser entry """
    flatten_unicode_keys(kwargs)
    title = kwargs['title']
    link = kwargs['link']
    description = kwargs['description']
    template = u"""

{title}

    {title}
    {description}
    """
    return template.format(title=title, link=link, description=description).encode('utf-8')

def convert_feed(**kwargs):
    """ Main loop """
    flatten_unicode_keys(kwargs)
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

save_file('http://stackoverflow.com/feeds', 'index.html')


texts: Is there a shorter way to write the following if statements?

texts:
I have the following code which uses four if statements to check the value in four different combo boxes.

if (!String.IsNullOrEmpty(tx_cmb_Circuits1.Text.Trim()))
    emp.CircuitEmail_Group_Rels.Add(
        new Circuit_Email_Group_Rel
        {
            Circuits = (Circuits) tx_cmb_Circuits1.SelectedItem,
            Group = emp
        });
if (!String.IsNullOrEmpty(tx_cmb_Circuits2.Text.Trim()))
    emp.CircuitEmail_Group_Rels.Add(
        new Circuit_Email_Group_Rel
        {
            Circuits = (Circuits) tx_cmb_Circuits2.SelectedItem,
            Group = emp
        });
if (!String.IsNullOrEmpty(tx_cmb_Circuits3.Text.Trim()))
    emp.CircuitEmail_Group_Rels.Add(
        new Circuit_Email_Group_Rel
        {
            Circuits = (Circuits) tx_cmb_Circuits3.SelectedItem,
            Group = emp
        });
if (!String.IsNullOrEmpty(tx_cmb_Circuits4.Text.Trim()))
    emp.CircuitEmail_Group_Rels.Add(
        new Circuit_Email_Group_Rel
        {
            Circuits = (Circuits) tx_cmb_Circuits4.SelectedItem,
            Group = emp
        });

Is there are shorter way to do the same. Please review my code.


texts: Finding the largest jacobian in a finite element mesh

texts:
So I'm trying to implement the following problem in a couple of different languages to get a rough idea of how different languages work & feel. I'm completely new to C, and this is the first code I've cobbled together using the C reference and Google/SO.

The problem is this:

Generate a list of n random doubles in (0, 1) and sort it
Create n "nodes" or points, so a Node is just a type with three doubles x,y,z
set x of each node to the corresponding entry in the list
generate a list of "elements", called a "mesh", where each element has two nodes
compute the Jacobian for each element (see jacobian below)
print the largest Jacobian of all elements

The following code works, I think. Since I have no experience in C, I want to know:

How can the code be made more idiomatic?
How can the code be made more performant?

#include <stdlib.h>
#include <math.h>
#include <stdio.h>

struct Node
{
    double x, y, z;
};

struct Element
{
    struct Node node1, node2;
};

struct Mesh
{
    struct Element* elements;
    int num_elements;
};

int compare_doubles(const void* a, const void* b)
{
    double arg1 = *(const double*)a;
    double arg2 = *(const double*)b;

    if (arg1 < arg2) return -1;
    if (arg1 > arg2) return 1;
    return 0;
}

double* generate_coordinates(int num_nodes)
{
    double* coordinates = malloc(num_nodes * sizeof(double));
    for (int i=0; i < num_nodes; i++)
    {
        coordinates[i] = (double) rand() / RAND_MAX;
    }

    qsort(coordinates, num_nodes, sizeof(double), compare_doubles);

    return coordinates;
}

struct Mesh generate_mesh(double* coordinates, int num_nodes, int num_elements)
{
    struct Node* nodes = malloc(num_nodes * sizeof *nodes);
    for (int i=0; i < num_nodes; i++)
    {
        nodes[i].x = coordinates[i];
        nodes[i].y = 0.0;
        nodes[i].z = 0.0;
    }

    struct Element* elements = malloc(num_elements * sizeof *elements);
    for (int i=0; i < num_nodes; i++)
    {
        elements[i].node1 = nodes[i];
        elements[i].node2 = nodes[i+1];
    }

    struct Mesh mesh;
    mesh.elements = elements;
    mesh.num_elements = num_elements;

    return mesh;
}

double jacobian(struct Element elem)
{
    double dx = elem.node2.x - elem.node1.x;
    double dy = elem.node2.y - elem.node1.y;
    double dz = elem.node2.z - elem.node1.z;
    return 0.5 * sqrt(dx*dx + dy*dy + dz*dz);
}

double find_max_jacobian(struct Mesh mesh)
{
    double max = 0.0;
    for (int i=0; i < mesh.num_elements; i++)
    {
        double jac = jacobian(mesh.elements[i]);
        if (jac > max)
            max = jac;
    }

    return max;
}

int main()
{
    int num_elements = 5000000;
    int num_nodes = num_elements + 1;

    double* coordinates = generate_coordinates(num_nodes);
    struct Mesh mesh = generate_mesh(coordinates, num_nodes, num_elements);

    printf("Max jacobian: %e\n", find_max_jacobian(mesh));
    return 0;
}

Edit: I just realised that I'm storing the nodes twice (right?). So I've made the nodes in the element just pointers, and modified the access in jacobian, so

struct Element
{
    struct Node *node1, *node2;
};
// ...
    elements[i].node1 = &nodes[i];
    elements[i].node2 = &nodes[i+1];
// ...
    double dx = elem.node2->x - elem.node1->x;


texts:
I am studying algorithms and I did this "Union Find Like" algorithm.
I have one array of objects with a reference and I make the union pointing to the same reference instead of have two int[] with numbers and weights.

Its not necessary to initialize the array.
You will have a maximum of N/2 extra objects ( if you do a union in pairs ), but in an array with a lot of unions you will have just a few objects (only the R roots) with only references pointing to the same object.
It's a linear time.

Can I have some feedback about this idea?
Thanks.
public class UnionFind {

    public static class Pointer {
        Pointer pointerForJoin;
    }

    // number of elements in array
    private static final int N = 10;
    private static Pointer[] connection = new Pointer[N];

    private static void union(int a, int b) {
        if(connection[a] != null && connection[b] != null) {
            if(connection[a].pointerForJoin != connection[b].pointerForJoin )
                connection[a].pointerForJoin = connection[b].pointerForJoin = connection[a];
        } else if(connection[a] != null) {
            connection[b] = connection[a];
        } else if(connection[b] != null) {
            connection[a] = connection[b];
        } else {
            connection[a] = connection[b] = new Pointer();
            connection[a].pointerForJoin = connection[b].pointerForJoin = connection[a];
        }
    }

    private static boolean isConnected(int a, int b) {
        if (a == b) return true;
        if(connection[a] == null || connection[b] == null) return false;
        return connection[a].pointerForJoin == connection[b].pointerForJoin;
    }

    public static void main(String[] args) {
        union(1,2);
        union(2,3);
        union(5,6);
        union(8,9);
        union(8,2);

        System.out.println(isConnected(8,3)); //true
        System.out.println(isConnected(8,2)); //true
        System.out.println(isConnected(9,1)); //true
        System.out.println(isConnected(1,6)); //false
        System.out.println(isConnected(1,7)); //false
        System.out.println(isConnected(0,0)); //true
    }
}
```


texts: Memory management with password retrieval

texts:
Questions:

Is this code secure? (I think that it is, but I'm a newbie so I want to be sure.)
Is the get_pass function correct with passing the arguments to the free_memory function?
Do I have to delete the pass' buffer with memset?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>

void get_pass(char **host, char **user, char **pass);
void free_memory(char *h, char *u, char *p);

int main(){

    char *host, *user, *pass;

    host = (char *) calloc(64, sizeof(char)); /* spazio per max 64 caratteri e inizializzo a 0 (maggior sicurezza) */
    if(!host){
        fprintf(stdout, "\nErrore di allocazione della memoria\n");
        exit(EXIT_FAILURE);
    };

    user = (char *) calloc(64, sizeof(char));
    if(!user){
        fprintf(stdout, "\nErrore di allocazione della memoria\n");
        exit(EXIT_FAILURE);
    };

    pass = (char *) calloc(64, sizeof(char));
    if(!pass){
        fprintf(stdout, "\nErrore di allocazione della memoria\n");
        exit(EXIT_FAILURE);
    };

    /* Immissione di hostname, username e password.
     * Controllo inoltre i 'return code' dei vari fscanf e, se non sono 0, esco.
     * Per evitare buffer overflow imposto limite massimo a 64 caratteri
     */
    fprintf(stdout,"--> Inserisci hostname (max 64 caratteri): ");
    if(fscanf(stdin, "%63s", host) == EOF){
        fprintf(stdout, "\nErrore, impossibile leggere i dati\n");
        free_memory(host,user,pass);
        exit(EXIT_FAILURE);
    }
    fprintf(stdout,"\n--> Inserisci username (max 64 caratteri): ");
    if(fscanf(stdin, "%63s", user) == EOF){
        fprintf(stdout, "\nErrore, impossibile leggere i dati\n");
        free_memory(host,user,pass);
        exit(EXIT_FAILURE);
    };
    fprintf(stdout, "\n--> Inserisci password (max 64 caratteri): ");
    get_pass(&host,&user,&pass);

    /* Stampo a video le informazioni immesse */
    fprintf(stdout, "\n\nHost: %s\nUser: %s\nPass: %s\n\n", host,user,pass);

    free_memory(host,user,pass);

    return EXIT_SUCCESS;
}

void get_pass(char **host, char **user, char **pass){
    /* Grazie a termios.h posso disabilitare l'echoing del terminale (password nascosta) */
    struct termios term, term_orig;
    tcgetattr(STDIN_FILENO, &term);
        term_orig = term;
        term.c_lflag &= ~ECHO;
        tcsetattr(STDIN_FILENO, TCSANOW, &term);
        /* Leggo la password e controllo il 'return code' di fscanf */
        if(fscanf(stdin, "%63s", *pass) == EOF){
        fprintf(stdout, "\nErrore, impossibile leggere i dati\n");
        tcsetattr(STDIN_FILENO, TCSANOW, &term_orig);
        free_memory(*host, *user, *pass);
        exit(EXIT_FAILURE);
    };
        /* Reimposto il terminale allo stato originale */
        tcsetattr(STDIN_FILENO, TCSANOW, &term_orig);
}

void free_memory(char *h, char *u, char *p){
    /* Libero la memoria occupata */
    free(h);
    free(u);
    free(p);
}


texts:
I am writing a brute-force method to search for a word. Please review my code and tell me how I can improve it.

public class Searcher {

  private static String filepath = null;
  private static final String defaultPath = "//sample_text";

  private Searcher() {
    this.filepath = defaultPath;
  }

  private Searcher(String dir) {
    if (dir.isEmpty()) {
      this.filepath = defaultPath;
    } else {
      this.filepath = dir;
    }
  }

  public static void main(String[] args) throws IOException {
    Searcher search = new Searcher();

    String folderToSearch = search.filepath;

    File folder = new File(folderToSearch);
    Set<File> list = new HashSet<File>();
    search.getFiles(folder, list);

    String toSearch = "The";
    for (File file : list) {
     BruteForceSearch bSerch = new BruteForceSearch(file);
     bSerch.search(toSearch);
    }
  }

  private void getFiles(File folder, Set<File> list) {

    folder.setReadOnly();
    File[] files = folder.listFiles();
    for (int j = 0; j < files.length; j++) {
      list.add(files[j]);
      if (files[j].isDirectory())
        getFiles(files[j], list);
    }
  }

}

public class BruteForceSearch implements WordSearch{

  private final String fileName;
  private Map<String, Integer> result =  new HashMap<String, Integer>();
  private File file;
  private int count =0;

  public BruteForceSearch(File file) throws IOException {
    this.file =  file;
    this.fileName = file.getName();
    this.count = 0;
  }

  private void searchBruteForce(String toSearch) throws IOException {

      FileInputStream fstream = new FileInputStream(file);
      BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
      String readLine = "";
      while ((readLine = in.readLine()) != null) {
        String[] words = readLine.split("\\W");
        for (String text : words) {
          if (text.equalsIgnoreCase(toSearch)) {
            count++;
          }
        }
      }
      in.close();
  }

  public String getFile() {
    return fileName;
  }

  public int getCount(String word) {
    return count;
  }

  public void search(String toSearch) throws IOException {
    searchBruteForce(toSearch);
    if (getCount(toSearch) != 0) {
        System.out.println(getFile() + " - " + getCount(toSearch) + " matches ");
    }
  }
}
public interface WordSearch {

  String getFile();
  int getCount(String term);
}

Here the interface is used for other search methods as well (like using regex, using index based). Brute-force is one such implementation.


texts:
I created a function that will tell me how many times a number is divisible by another number and what the remainder of it is:

 <?php
function divisible_times($number, $divider) {
    $count = 0;
    $remainder = $number % $divider;
    $num_array = range($number, 1);
    foreach($num_array as $num) {
        if($num % $divider == 0){
            $count++;
        }
    }

    $arr[$number.':'.$divider]['divisions_no'] = $count;
    $arr[$number.':'.$divider]['remainder'] = $remainder;
    return $arr;
}
print_r(divisible_times(4, 3)); // Returns Array ( [4:3] => Array ( [divisions_no] => 1 [remainder] => 1 ) )
print_r(divisible_times(14, 3)); // Returns Array ( [14:3] => Array ( [divisions_no] => 4 [remainder] => 2 ) )
print_r(divisible_times(13, 3)); // Returns Array ( [13:3] => Array ( [divisions_no] => 4 [remainder] => 1 ) )
print_r(divisible_times(12, 3)); // Returns Array ( [12:3] => Array ( [divisions_no] => 4 [remainder] => 0 ) )

Can this code be optimized somehow? I tried to use $number directly, but couldn't find out the count that way. The only thing I could think is to create am array of numbers and go through each one.

I mean this does the trick, but optimization is important, and I was wondering if there is any other way of doing it?


texts: Simplify multiple jQuery click functions

texts:
How can I simplify this jQuery code? I feel like I should be able to do this with one click function.

jQuery

$('.btn').eq(0).click(function () { $('.carousel').css({ 'left': '0%' }); });
$('.btn').eq(1).click(function () { $('.carousel').css({ 'left': '-100%' }); });
$('.btn').eq(2).click(function () { $('.carousel').css({ 'left': '-200%' }); });
$('.btn').eq(3).click(function () { $('.carousel').css({ 'left': '-300%' }); });

HTML

Button 1

Button 2

Button 3

Button 4


texts: jQuery form builder for parsing email array into single input

texts:
I have the following in script in my web app which contains a lot of duplication. How can I cut down on this duplication and generally improve my code?

$('a#newAuthority').on("click", function() {
    var $newAuthorityContainer = $(".new-authority-container");

    var $row = $('
', {
        class: 'row'
    }).appendTo($newAuthorityContainer);

    var $large11 = $('
', {
        class: 'large-11 columns'
    }).appendTo($row);

    var $input = $('<input>', {
        type: 'text',
        placeholder: 'email@domain.com',
        class: 'authority-email'
    }).appendTo($large11);

    var $large1 = $('
', {
        class: 'large-1 columns'
    }).appendTo($row);

    var $removeContainer = $('
', {
        class: 'remove-container'
    }).appendTo($large1);

    var $remove = $('', {
        href: '#',
        class: 'remove'
    }).html('').appendTo(
        $removeContainer);
    return false;
});
$('a#newMember').on("click", function() {
    var $newMemberContainer = $(".new-member-container");

    var $row = $('
', {
        class: 'row'
    }).appendTo($newMemberContainer);

    var $large11 = $('
', {
        class: 'large-11 columns'
    }).appendTo($row);

    var $input = $('<input>', {
        type: 'text',
        placeholder: 'email@domain.com',
        class: 'authority-email'
    }).appendTo($large11);

    var $large1 = $('
', {
        class: 'large-1 columns'
    }).appendTo($row);

    var $removeContainer = $('
', {
        class: 'remove-container'
    }).appendTo($large1);

    var $remove = $('', {
        href: '#',
        class: 'remove'
    }).html('').appendTo(
        $removeContainer);
    return false;
});

$('input.button').on("click", function() {

    var $authorityInputs = $('.authority-email');

    var authortyEmails = [].map.call($authorityInputs, function(
        $authorityInputs) {
        return $authorityInputs.value;
    }).join(',');

    if ($('body.teamsnew').length) {
        $('input#team_authority_emails').val(authortyEmails);
    }

    if ($('body.teamsedit').length) {
        $('input#team_authority_emails').val('{' + authortyEmails + '}');
    }

    var $memberInputs = $('.member-email');

    var memberEmails = [].map.call($memberInputs, function(
        $memberInputs) {
        return $memberInputs.value;
    }).join(',');

    if ($('body.teamsnew').length) {
        $('input#team_member_emails').val(memberEmails);
    }

    if ($('body.teamsedit').length) {
        $('input#team_member_emails').val('{' + memberEmails + '}');
    }
});

$(document).on('click', '.remove', function() {
    $(this).closest('.row').remove();
    return false;
});


texts:
I'm new to Scala and I'm trying to write a generic function to convert from Int to any scalar.

For example:

val res: Float = convertInt[Float](12)
val res: Double = convertInt[Double](12)
//etc

I've achieved the following code:

  trait FromIntConverter[T]{
    def apply(int: Int): T
  }

  def convertInt[T](int: Int)(implicit converter: FromIntConverter[T]): T = converter(int)

  implicit val IntToIntConverter = new FromIntConverter[Int]{
    def apply(int: Int) = int
  }

  implicit val IntToFloatConverter = new FromIntConverter[Float]{
    def apply(int: Int) = int.toFloat
  }

  implicit val IntToDoubleConverter = new FromIntConverter[Double]{
    def apply(int: Int) = int.toDouble
  }
  //etc

Is it ok in regards to readability/brevity/performance?


texts: Solving the max-subarray problem from CLRS in C++

texts:
I'm working through Algorithms Cormen et al to learn more about algorithms and modern C++.  I've implemented the maximum subarray problem and would like some feedback.  I'd really like to use the modern additions to C++ effectively, so please let me know where things can be improved.

One of my concerns was using std::numeric_limits::infinity in the code.  Would this be used in production code?  How would one handle something like infinity otherwise?  I often see Dijkstra's algorithm described in pseudocode this way (using infinity), but is there something smarter/more standard to use?

Another concern was using tuples to return multiple values from a function.  I find that I then have to use std::get quite a lot to access the individual elements of the tuple.  Is this acceptable?

#include <iostream>
#include <tuple>
#include <vector>
#include <limits>
#include <math.h>

std::tuple <int,int,double> max_crossing_subarray(std::vector<double> A, int low, int mid, int high);
std::tuple<int,int,double> max_subarray(std::vector<double> A, int low, int high);

int main(){

    std::vector<double> A = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
    //std::vector<double> A = {1, -1, 9};

    std::tuple<int,int,double> answer = max_subarray(A,0,A.size()-1);

    std::cout << std::get<0>(answer) << '\n' << std::get<1>(answer) << '\n' << std::get<2>(answer) << std::endl;

    return 0;

}

std::tuple<int,int,double> max_subarray(std::vector<double> A, int low, int high){

    std::tuple<int,int,double> ans;
    std::tuple<int,int,double> left_sub;
    std::tuple<int,int,double> right_sub;
    std::tuple<int,int,double> crossing_sub;

    if(high==low){
        ans = {low,high,A[low]};
        return ans;
    }
    else{
        int mid = floor((low+high)/2);
        left_sub = max_subarray(A, low, mid);
        right_sub = max_subarray(A, mid+1, high);
        crossing_sub = max_crossing_subarray(A, low, mid, high);
    }

    // is my left subarray the largest?
    if(std::get<2>(left_sub)>std::get<2>(right_sub) & std::get<2>(left_sub)>std::get<2>(crossing_sub)){
        ans = left_sub;
    }
    //is my right subarray largest?
    else if (std::get<2>(right_sub)>std::get<2>(left_sub) & std::get<2>(right_sub)>std::get<2>(crossing_sub)){
        ans = right_sub;
    }
    // my crossing subarray is largest
    else{
        ans = crossing_sub;
    }

    return ans;

}

std::tuple <int,int,double> max_crossing_subarray(std::vector<double> A, int low, int mid, int high){

    double inf = std::numeric_limits<double>::infinity();  // is this wise?
    double sum = 0;

    int max_left = 0;
    double left_sum = -inf;
    for(int i=mid; i>=low; i--){
        sum += A[i];
        if(sum>left_sum){
            left_sum = sum;
            max_left = i;
        }
    }

    int max_right = 0;
    double right_sum = -inf;
    sum = 0;
    for(int j=mid+1; j<=high; j++){
        sum += A[j];
        if(sum > right_sum){
            right_sum = sum;
            max_right = j;
        }

    }

    std::tuple<int,int,double> out = {max_left, max_right, left_sum+right_sum};

    return out;

}


texts:
This code has several functions and procedures for the program to generate cards like '5 of diamond'. I would like to shorten the code.

def random(one,two):
    import random
    number = random.randint(one,two)
    return number

def suit():
    suitnumber = random(1,4)
    if suitnumber == 1:
        suitb = 'Spade'
    elif suitnumber == 2:
        suitb = 'Hearts'
    elif suitnumber == 3:
        suitb = 'Diamonds'
    elif suitnumber == 4:
        suitb = 'Clubs'

    return suitb

def number():
    number = random(1,13)
    if number == 13:
        value = 'Ace'
    elif number == 12:
        value = 'King'
    elif number == 11:
        value = 'Queen'
    elif number == 10:
        value = 'Jack'
    elif number < 10:
        value = number

    return value

def card():
    cardnumber = number()
    cardsuit = suit()
    card = cardsuit,cardnumber
    return card

def store10Cards():
    tenCards = [card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card(),
               card()]
    return tenCards

def yourCards():
    cards = store10Cards()
    counter = 1
    choice = int(input('Which of your cards would you want to see? You have 10 cards : '))
    if choice == 1:
        print('Your chosen card is',cards[0])
    elif choice == 2:
        print('Your chosen card is',cards[1])
    elif choice == 3:
        print('Your chosen card is',cards[2])
    elif choice == 4:
        print('Your chosen card is',cards[3])
    elif choice == 5:
        print('Your chosen card is',cards[4])
    elif choice == 6:
        print('Your chosen card is',cards[5])
    elif choice == 7:
        print('Your chosen card is',cards[6])
    elif choice == 8:
        print('Your chosen card is',cards[7])
    elif choice == 9:
        print('Your chosen card is',cards[8])
    elif choice == 10:
        print('Your chosen card is',cards[9])

        import time
        time.sleep(5)

    return cards

print('Hi')
import time
time.sleep(2)
print('You have 10 cards')
time.sleep(2)
choice = input('Would you like to see them? Y/N  : ')
choice = choice.title()
if choice == 'Y':
    yourCards()
elif choice == 'N':
    print('Too bad')
    time.sleep(1)
    import sys
    sys.exit(0)


texts: 3 selects on a page and 2 of them need to be observed for changes

texts:
There are 3 selects on a page: 2 selects are populated and 3rd empty. Onload takes both populated selects and combines them into 3rd select with groupings.

An external event is simulated with button on page, which adds an option to one of the populated selects.

I am using DOMSubtreeModified event to observe any changes in the 2 populated selects. When modified event occurs it should update the 3rd select with new option.

Is there another way to do this, or does this look ok?

$(function () {
    LoadSelects();

    $('#btn1').click(function () {
        $('#selMain').unbind('change');
        $('#s1').append('<option value="five">Five</option>');
        AddObserver();
    });
});

function LoadSelects() {
   InitSelects([
        {id:"s1",tbl:"src One",grp:"Group 1"}, {id:"s2",tbl:"src Two",grp:"Group 2"}]);
}

function AddObserver() {
    $('#observe_this').one('DOMSubtreeModified', function () {
        $('#selMain').html('<option value="-1"></option>');
        LoadSelects();
    });
}

function InitSelects(aryObj) {
    $.each(aryObj, function (index, item) {
        var arygrp = $('select[name="' + item.tbl + '"]');
        arygrp.attr('id', item.id);
        if ($('#' + item.id + ' option[value="0"]').length == 0) {
            arygrp.prepend('<option value="0"></option>');
        }
        var optgrp = $('<optgroup label="' + item.grp + '"></optgroup>');

        $(arygrp).find('option').each(function () {
            if ($(this).val() != '0') {
                var opt = $(this).clone();
                $(opt).data('source-meta', {
                    id: item.id,
                    craycray: $(this).val()
                });
                $(opt).val(item.id + $(this).val());
                $(optgrp).append(opt);
            }
        });
        $('#selMain').append(optgrp);
    });

    //Add main select change event below
    $('#selMain').change(function(){
        alert(this.value);
    });
} //end function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selMain">
  <option value="-1"></option>
</select>
<div id="observe_this">
  <select name="src One">
    <option value="one">One</option>
    <option value="two">Two</option>
  </select>
  <select name="src Two">
    <option value="three">Three</option>
    <option value="four">Four</option>
  </select>
</div>
<input id="btn1" type="button" value="External event" />


texts:
In Encrypt PDF-Files I provided a Python program to encrypt PDF-Files in a folder.

This program here does the oposite. Giving a password and path all PDFs which are encrypted are decrypted in the supplied path. If the password is wrong a message is displayed.

pdf_decrypter.py

"""
Decrypts all files in a folder and sub folder with provided password
"""

import os
import argparse
from typing import Tuple
from getpass import getpass
from pathlib import Path
import PyPDF2

def get_password_from_user() -> str:
    """Asks the user to enter a password"""
    while True:
        password: str = getpass(promt="Enter password: ")
        if password:
            return password

def get_path_from_user() -> str:
    """Asks for a path from the User"""
    while True:
        #input_string = "E:/Python Projekte\ATBS\CH13_EX1_pdf_decrypter\CH13_EX1_pdf_decrypter\CH13_EX1_pdf_decrypter\\testfolder"
        path = Path(input("Enter absolute Path:"))
        if os.path.exists(path):
            return path
        print("Path doesn't exist\n")

def get_path_and_password() -> Tuple[str, str]:
    """
    Gets path and password from command line or
    if not available from the user
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--path", help="provide root folder to look for PDFs to encrypt",
        type=str)
    parser.add_argument(
        "--password", help="password to encrypt PDFs with", type=str)
    args = parser.parse_args()
    if args.path and args.password:
        return Path(args.path), args.password
    return get_path_from_user(), get_password_from_user()

def is_encrypted(filename: str) -> bool:
    """Checks if file is encrypted"""
    with open(filename, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        return pdf_reader.isEncrypted

def decrypt(filename: str, password: str) -> bool:
    """
    Try to decrypt a file. If not successful a false is returned.
    If the file passed is not encrypted also a false is passed
    """
    with open(filename, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        pdf_reader.decrypt(password)
        pdf_writer = PyPDF2.PdfFileWriter()

        try:
            for page_number in range(pdf_reader.numPages):
                pdf_writer.addPage(pdf_reader.getPage(page_number))
        except PyPDF2.utils.PdfReadError:
            return False

        filename_decrypted = filename.strip('.pdf') + "_decrypted.pdf"

        with open(filename_decrypted, 'wb') as pdf_file_decrypted:
            pdf_writer.write(pdf_file_decrypted)
    return True

def pdf_decrypter():
    """
    Main routine:
    Giving a password and path all PDFs which are encrypted get
    decrypted in the supplied path.
    If the password is wrong a message is displayed.
    """
    path, password = get_path_and_password()
    for folder_name, _, filenames in os.walk(path):
        for filename in filenames:
            if not filename.endswith('.pdf'):
                continue

            if not is_encrypted(os.path.join(folder_name, filename)):
                continue

            if decrypt(os.path.join(folder_name, filename), password):
                os.remove(filename)
            else:
                print(filename + " could not be decrypted (wrong password)")

if __name__ == "__main__":
    pdf_decrypter()

I already incorporated improvements suggested in the encrypter review in Encrypt PDF-Files

What else can be improved in the code?

Let me know.


texts: Await all HTTP request body chunks before moving on

texts:
I'm developing a man-in-the-middle proxy that will let the user see and modify HTTP and HTTPS requests before they leave the client and responses before they arrive at the client. The code I'm working on is working, but I don't know if it's the right or beast way to achieve this behaviour. I'm waiting for all request and response chunks before moving on the the next step.

Browsing with the proxy on is clearly slower, although this is not a problem to the application I'll use this proxy on. Below is the code I'm using to wait for all body chunks before performing the next step.

let requestBody: Buffer

    try {
      requestBody = await this.collectMessageBody(req)
    } catch (error) {
      req.destroy(new ProxyError('Error while fetching request body', ErrorType.unknown, error))
      return
    }

    let modifiedRequest: any

    try {
      // Send the intercepted request to the client before forwarding to its destination
      modifiedRequest = await this.interceptHandler('request', request, response)
    } catch (error) {
      req.destroy(new ProxyError('Request dropped by the client', ErrorType.denied, error))
      return
    }
    // Handle the response from the forwarded request. The logic is similar to above but can be ignored to this question scope
    const responseHandler = async (serverResponse: http.IncomingMessage) => this.receiveResponse(request, response, serverResponse, res)
    // Creates the request that will be sent to the final destination using http.request(...)
    const forwardedRequest = Router.forward(modifiedRequest, responseHandler)
    forwardedRequest.on('error', error => this.emit('error', error))

    // Write the original request body to the forwarded one
    forwardedRequest.write(requestBody)
    // Send the request
    forwardedRequest.end()

private collectMessageBody(incomingMessage: http.IncomingMessage): Promise<Buffer> {
    return new Promise<Buffer>((resolve, reject) => {
      let bodyBuffers: Buffer[] = []

      incomingMessage.on('data', chunk => bodyBuffers.push(chunk))
      incomingMessage.on('end', () => resolve(Buffer.concat(bodyBuffers)))
      incomingMessage.on('error', error => reject(error))
    })
  }
```


texts: Function to generate an Int from a series of bits

texts:
I wrote the following function in order to handle some data from a QR code:

func genInt(fromBitArray array: [Int]) -> Int {
    var n = 0
    for i in 0...array.count - 1 {
        n += array[i] << ((array.count - 1) - i)
    }
    return n
}

genInt(fromBitArray: [1, 1, 0]) would return 6.

Is there a better/more efficient way to do this?


texts: Constant Time implementation of String Uniqueness Algorithm

texts:
I've written what I think is a constant time implementation of a uniqueness check. I've seen many algorithms online, which run in linear time, but was wondering whether my conclusion that this runs in constant time was correct.

I've seen many linear versions of this algorithm, but I haven't seen any that run in O(1).

Any feedback on style, flaws in the code, or how to improve the algorithm would be greatly appreciated.

from string import printable

def is_unique(string):
    """Checks whether a string is unique or not.

    Big O:

      O(S * C) - Constant Time

      Where:

        `S` is the characters of the string being checked for uniqueness
        `C` is a set of all ASCII characters (not including the extended set)

    """
    if len(string) == 1:
        # A single character is always going to be unique
        return True

    if len(string) > len(printable):
        # If there are more characters than the ASCII character set,
        # then we know there are duplicates
        return False

    found_character = bytearray(len(printable))

    for character in string:
        for index, ascii_value in enumerate(printable):
            if character == ascii_value:
                if found_character[index] == True:
                    return False

                # Set the index of the ASCII value in our bytearray to True
                found_character[index] = 1
                break

    return True

is_unique(string='abc')


texts:
The application I'm currently working on have two main user types, let's say user and reviewer. I need to create a functionality to track changes made by both user and reviewer (for post) and show them in the frontend. I have given specific messages to show in the frontend for each change.
ex:- user submits a post. This post must be reviewed by reviewer
In user dashboard
Post submitted   -> Pending review
In reviwer dashboard
Pending review    -> You have a new post to review before 01/07/2019
My approach
Make a language file to store all the status given.
lang/en/status.php
<?php

return [

    'post_accepted' => [

        'user' => [

            'from' => 'Pending review',
            'to' => 'Post accepted',

        ],

        'reviewer' => [

            'from' => 'Pending review',
            'from' => 'You have a new post to review before [DATE]',

        ]

    ]

];

Then I have formatted each status and saved to the database with user's id.
ex:- For reviewer,
$reviewer= $post->reviewer;

$status_from = __('status.post_accepted.reviewer.from');
$status_to = str_replace('[DATE]', '01/07/2019', __('status.post_accepted.reviewer.to'));

// Helper function for save log
add_log(
     $post,              // Post
     'post_submitted',   // unique slug for each status
     $status_from,       // from status
     $status_to,         // to status
     $reviewer->id       // reviewer id (The message should be shown to)
);

This is a hard approach to maintain code, not cleaner and I have to write a lot if code for each status.
Is there a cleaner way to achieve this with laravel?


texts: Isolate URLs from other text around it and put each on own line (with sed)

texts:
I have a small shell script that uses sed to take an input file of URLs with hand-written notes around them and strips the notes and puts each URL on its own line.  For example:

INPUT:

note: http://www.example.com/Beat-Poetry + ??? http://www.example.com/beat+poetry
http://www.example.com/17th+cent. + http://www.example.com/17th+century + http://www.example.com/17th+c.
http://www.example.com/18th+century
https://www.example.com/C19th-C20th + http://www.example.com/19th-20th+century (note)
note:
http://www.example.com/18th+cent. note http://www.example.com/18th+century

Note: the URLs will always either have leading/trailing space or start or end the line.

DESIRED OUTPUT:

http://www.example.com/Beat-Poetry
http://www.example.com/beat+poetry
http://www.example.com/17th+cent.
http://www.example.com/17th+century
http://www.example.com/17th+c.
http://www.example.com/18th+century
http://www.example.com/C19th-C20th
http://www.example.com/19th-20th+century
http://www.example.com/18th+cent.
http://www.example.com/18th+century

I have this code, which does the job by adding some delimiters around each URL and removing stuff based on where the delimiters are found, but I am a newbie with this stuff, and it doesn't quite feel right.  If nothing else, it's not robust enough to withstand potential usage of á and é characters in the "notes".

#!/bin/bash

  # squash out all the extra text that isn't URL (notes to self) and put each URL on a new line
  # hackish steps to achieve this:
  # - change urls from http://url to áhttp://urlé
  # - put each one on a new line
  # - remove leading space/words
  # - remove trailing space/words
  # - change any https to http

sed -re 's/(https?:[^ ]*)( |$)/á\1é /g' \
     -e 's/é[^á]*á/\n/g' \
     -e 's/(^[^á]*)(á[^é]*é)/\2/g' \
     -e 's/é[^á]*$//' \
     -e 's/https:/http:/g' $1 |
tr -d 'áé\r' |
sed -rn 's/(http:\/\/www.example.com\/.*)$/\1/p'

I assume that there is a more proper way to do this? (Again, the URLs will always have whitespace or ^ or $ around them.)  I'd appreciate any improvement suggestions. Thanks.


texts: Writing a more Pythonic solution to the min triangle path

texts:
The problem I'm referring to is available here. In quick summary, the problem gives a list of lists such as [[2],[3,4],[6,5,7],[4,1,8,3]] and we must find the minimum path sum: 2 + 3 + 5 + 1 = 11. I took the obvious DP approach:

def minimumTotal(self, triangle):
    # make a memo with n rows and i columns
    # where i is the number of elements in the last row
    n, i = len(triangle), len(triangle[-1])
    memo = [[0] * i for _ in range(n)]
    # add the base case
    memo[0][0] = triangle[0][0]
    for m in range(1, n):
        for k in range(m + 1):
            if (k == 0):
                memo[m][k] = triangle[m][k] + (memo[m-1][0] if m - 1 >= 0 else float("inf"))
            elif (m == k):
                memo[m][k] = triangle[m][k] + (memo[m-1][k-1] if m - 1 >= k - 1 else float("inf"))
            else:
                memo[m][k] = triangle[m][k] + min(memo[m-1][k-1] if m - 1 >= k - 1 else float("inf"), memo[m-1][k] if m - 1 >= k else float("inf"))
    # now loop through the last row and choose the min
    answer = memo[-1][0]
    for l in range(1,i):
        if (memo[-1][l] < answer):
            answer = memo[-1][l]
    return answer

This code is faster than 95% of the other submission times so I'm satisfied with run time. However, what I am interested in is how to (a.) make this code more "Pythonic" and (b.) how to improve the memory usage. This code is more memory efficient than only 8% of submissions so I'm curious on how to better improve this.


texts: Generic classes with inheritance/equals/comparison operators

texts:
I would like to greatly reduce verbosity of following code fragment.

What I'd like to do:

Reduce number of occurrences of MaterialRangedParam<Value> and MaterialParam<Value>. C++ has typedef. C# doesn't. Is there keyword for own type of a class?
Remove operator !=, operator ==, GetHashCode and Equals and make compiler generate them for me (the way C++ would do it).

How can I do that?

Additional info:

I'm already aware that clone method offers functionality similar to ICloneable. I have no need to support ICLoneable at the moment.

Usage pattern:
    Those items are going to be stuffed into several lists, arrays and hashtables, compared to each other, assign is going to be called often.

Advice?

public class MaterialParam<Value> where Value: System.IEquatable<Value>{
    public string name = "";
    public string shaderValueName = "";
    public Value value;// = Value();
    public void assignFrom(MaterialParam<Value> other){
        name = other.name;
        shaderValueName = other.shaderValueName;
        value = other.value;
    }

    public MaterialParam<Value> clone(){
        var result = new MaterialParam<Value>();
        result.assignFrom(this);
        return result;
    }

    public override bool Equals(object obj){
        if(!(obj is MaterialParam<Value>))
            return false;

        MaterialParam<Value> other = (MaterialParam<Value>)obj;
        if((System.Object)other == null){
            return false;
        }

        return (this.name == other.name) &&
            (this.shaderValueName == other.shaderValueName) &&
                (this.value.Equals(other.value));
    }

    public override int GetHashCode(){
        return name.GetHashCode() ^ shaderValueName.GetHashCode()
            ^ value.GetHashCode();
    }

    public static bool operator !=(MaterialParam<Value> a, MaterialParam<Value> b){
        return !(a == b);
    }

    public static bool operator ==(MaterialParam<Value> a, MaterialParam<Value> b){
        return a.Equals(b);
    }
};

public class MaterialRangedParam<Value>: MaterialParam<Value> where Value: System.IEquatable<Value>{
    public Value minValue;// = Value();
    public Value maxValue;// = Value();
    public void assignFrom(MaterialRangedParam<Value> other){
        base.assignFrom(other);
        minValue = other.minValue;
        maxValue = other.maxValue;
    }

    new public MaterialRangedParam<Value> clone(){
        var result = new MaterialRangedParam<Value>();
        result.assignFrom(this);
        return result;
    }

    public override bool Equals(object obj){
        if (!base.Equals(obj))
            return false;

        if(!(obj is MaterialRangedParam<Value>))
            return false;

        MaterialRangedParam<Value> other = (MaterialRangedParam<Value>)obj;
        if((System.Object)other == null){
            return false;
        }

        return (minValue.Equals(other.minValue)) && (maxValue.Equals(other.maxValue));
    }

    public override int GetHashCode(){
        return base.GetHashCode() ^ minValue.GetHashCode() ^ maxValue.GetHashCode();
    }

    public static bool operator !=(MaterialRangedParam<Value> a, MaterialRangedParam<Value> b){
        return !(a == b);
    }

    public static bool operator ==(MaterialRangedParam<Value> a, MaterialRangedParam<Value> b){
        return a.Equals(b);
    }
}


texts: Clojure solution to HackerRank Challenge 'Restaurant' under Number Theory

texts:
My main concern is how messy the min-number-of-slices function is.  I would appreciate help finding good ways to clean that up since it has a lot of nesting/scope.

This is my first ever Clojure program, so I know this is probably not idiomatic Clojure, nor is it neat, nor probably fast, either.  Please give as much feedback as you would like on my code (especially regarding stuff that's bad about it).

The challenge is, given a list of 2D dimensions for pieces of bread, find the minimum number of perfect squares you could cut out of each piece without wasting any bread.
https://www.hackerrank.com/challenges/restaurant

(ns clojure-solution.core)
(require '[clojure.string :as string])

(defn parse-int [s]
  (Integer. s))

(defn parse-line [s]
  (map parse-int (string/split s #" ")))

(defn get-loaf-dimensions []
  (let [numLoaves (parse-int (read-line))]
    (map #(%1) (repeat numLoaves (comp parse-line read-line)))))

(def squares (map #(* % %) (range 1 1001)))

(defn min-number-of-slices [dims]
  (let [l              (first dims)
        b              (second dims)
        area           (* l b)]
    (letfn [(perfect-slice-dimension? [slice-area]
              (= 0 (+ (mod area slice-area)
                      (mod b (int (Math/sqrt slice-area)))
                      (mod l (int (Math/sqrt slice-area))))))]
      (let [largest-square (last (filter perfect-slice-dimension? (take (min l b) squares)))]
        (int (/ area largest-square))))))

(defn -main [& args] (dorun (map println (map min-number-of-slices (get-loaf-dimensions)))))


texts:
This is a function I made for a timer that counts down and performs a callback at the end. It seems to work fine, but I think the code is not very clean and has some unnecessary bits; also I would like some notes on readability. The code:

//timer object function
function Timer (element, callback) {

 var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000, self = this, timeLeftToNextSecond = 1000, running = false;

 this.set = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;

  this.print();
 }

 this.add = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
  finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;

  this.print();
 }

 this.subtract = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
  if(finalTimeInSeconds < 0) {callback()}
  finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;
  this.print();
 }

 this.reset = function() {

  this.set(0,0);
 }

 this.print = function() {

  displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
  displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.

  $(element).text(displayMinutes + ":" + displaySeconds);
 }

 this.run = function() {

  if (running == false) {
   running = true;

   var _f = function() {
    secondStarted = new Date;
    self.subtract(0, 1);
    interval = 1000;

    var theColorIs = $(element).css("color");
    ac = setTimeout(_f,interval);

   }
   ac = setTimeout(_f, interval);

  }
 }

 this.stop = function() {

  if (running == true) {
   running = false;
   console.log(this + "(" + element + ") was stopped");
   stopped = new Date;
   interval = 1000 - (stopped - secondStarted);
   clearTimeout(ac);
  }
 }

 this.getTotalTimeInSeconds = function() {

  return finalTimeInSeconds;
 }

 this.reset();

}


texts: Python persistant cache for non-pythonic objects

texts:
I am trying to implement a cache which can be persisted. Also, some of the functions that I am trying to cache takes arguments that are not python objects (external library objects). But they seem to have a hash value. My first try was to use lru_cache but it didn't have an option to persist across sessions. Then I stumbled upon this answer which explained a way to create a custom decorator to cache the function results. I made some minor changes to it and came up with this decorator (which can take arguments) now.
def cached(maxsize=None, hashkey=True, persist=False):
    """Decorator method to cache an expensive function

    Args:
        maxsize (int): The maximum number of cached results to store
            if None, the size is indefinite.
        hashkey (bool): If the arguments of the function are objects
            which cannot be pickled, use the hashkey option which will
            hash the arguments.
        persist (bool): Write the cached results to the disk so that
            it can be read in even after the session has ended.

    Returns:
        Decorator function
    """

    def outer(func):
        func.cache = {}
        func.cache_file = f"{func.__name__}.cache"

        @wraps(func)
        def wrapper(*args):
            if hashkey:
                key = hash(args)
            else:
                key = args
            try:
                return func.cache[key]
            except KeyError:
                try:
                    if persist:
                        with open(func.cache_file, "rb") as cachefile:
                            func.cache = pickle.load(cachefile)
                    return func.cache[key]
                except (KeyError, FileNotFound):
                    func.cache[key] = result = func(*args)
                    if maxsize and len(func.cache) > maxsize:
                        func.cache.pop(next(iter(func.cache))) # removes the first item
                    if persist:
                        with open(func.cache_file, "wb") as cachefile:
                            pickle.dump(func.cache, cachefile)
                    return result

        return wrapper

    return outer

The functions that I am planning to cache may be called at most 10000 times with a given cache file.
Here are my questions:

Is there anything obviously wrong with this code?
Is hashing the arguments a bad idea?
Are there any obvious places where I can store the cache file?


texts: Find all distinct palindromic sub-strings for a given string

texts:
I was solving a question where I had to find all possible unique palindromes of size greater than 1 for a string.

I was able to come up with the solution shown below. If I am not mistaken it is an \$O(n^2)\$ solution. I'd like feedback on improving the code and if my understanding of its time complexity is correct.

def check_palin(word):
    for i in xrange(len(word)/2):
        if word[i] != word[-1*(i+1)]:
            return False
    return True

def all_palindromes(string):

    left,right=0,len(string)
    j=right
    results=[]

    while left < right-1:
        temp = string[left:j] #Time complexity O(k)
        j-=1

        if check_palin(temp):
            results.append(temp)

        if j<left+2:
            left+=1
            j=right

    return list(set(results))

print all_palindromes("racecarenterelephantmalayalam")

Output:

['aceca', 'layal', 'cec', 'alayala', 'racecar', 'ele', 'ere', 'aya', 'malayalam', 'ala']


texts: Python implementation of multidimensional power spectral density with Welch method

texts:
I have done my best to write Welch method implementation for python for multidimensional time series and still in the case of one dimensional time series I am getting inconsistent response compared to original Welch method. I have added comments and tried to be clear. Can anybody guide me about the mistake that I might have in implementation?

from scipy.fftpack import fft,fftfreq
import numpy as np
from math import ceil,floor
import sys
from scipy.signal import welch,get_window
from matplotlib import pyplot as plt
import warnings
from scipy.lib.six import string_types

def win_sig(x,nperseg):
    """A function just to cut a multidimensional time series into pieces of specific length (nperseg) """

    #checking whether the size of time series are smaller than the window lenght
    if nperseg >= x.shape[-1]:
        N = nperseg
        win_num = 1
    elif nperseg/2 == nperseg/2.:
        N = nperseg/2+1
        win_num = ceil(x.shape[-1]/float(N-1))
    else:
        N = nperseg/2
        win_num = ceil(x.shape[-1]/float(N))

    #index set manipulation for generating the splitted version of the signals faster
    idx_temp=np.indices((win_num,nperseg))
    idx_temp=np.tile((idx_temp[0]*N+idx_temp[1]).T,x.shape[0]).T.reshape((x.shape[0],win_num,-1))

    #padding zeros for the last window when the last window is longer than the remaining of signal
    pad_len=(win_num-1)*N+nperseg-x.shape[-1]
    idx_mat=np.arange(0,x.shape[0])[...,None,None]*(idx_temp.flatten()[-1]+1)+idx_temp
    pad_mat=np.zeros((x.shape[0],pad_len))
    x=np.concatenate((x,pad_mat),axis=-1)

    return x.flatten()[idx_mat].reshape((x.shape[0],win_num,-1))

def ndim_welch(x,nperseg,window = 'hanning',scaling = 'density',fs = 1.0,axis = -1):
    if x.shape[-1] < nperseg:
        warnings.warn('nperseg = %d, is greater than x.shape[%d] = %d, using '
                    'nperseg = x.shape[%d]'
                    % (nperseg, axis, x.shape[axis], axis))
        nperseg = x.shape[-1]

    #setting the window as is done in original scipy.signal
    if isinstance(window, string_types) or type(window) is tuple:
            win = get_window(window, nperseg)
    else:
        win = np.asarray(window)
        if len(win.shape) != 1:
            raise ValueError('window must be 1-D')
        if win.shape[0] > x.shape[-1]:
            raise ValueError('window is longer than x.')
        nperseg = win.shape[0]

    #setting the scale as is done in original scipy.signal
    if scaling == 'density':
        scale = 1.0 / (fs * (win*win).sum())
    elif scaling == 'spectrum':
        scale = 1.0 / win.sum()**2
    else:
        raise ValueError('Unknown scaling: %r' % scaling)

    #turning the multidimensional time series into multiple time series of windowed sections using the function 'win_seg'
    windowed_sig = win_sig(x,nperseg)
    windowed_sig = np.multiply(win,windowed_sig)

    #calculating the fourier transform
    windowed_seg_fft = fft(windowed_sig)
    windowed_fft = np.mean(windowed_seg_fft,axis=1).T

    #returning the spectral density with calcualting outerproducts to get the crossspectrum matrix and also returning the frequenct set
    spec_density = np.einsum('...i,...j->...ij',windowed_fft,windowed_fft.conjugate())
    spec_density *= scale
    spec_freq = fftfreq(nperseg)
    return spec_freq,np.squeeze(spec_density)
b=np.random.randn(5)
segment = 5
a = (b)[None,...]
print ndim_welch(a,nperseg=segment)[1].real,welch(b,nperseg=segment)[1]


texts:
I am writing a TCP client app using netty

NettyConnectionManager.scala:

class NettyConnectionManager(val config : NettyConfig) extends ConnectionManager {
  @volatile private var connection: Option[Connected] = None

  def get() = {
    if(isConnected) {
      connection.get
    } else {
      synchronized {
        if(isConnected) {
          connection.get
        } else {
          val newConnection = new NettyConnection(config)
          newConnection.connect()
          connection = Some(newConnection)
          connection.get
        }
      }
    }
  }

  private def isConnected = {
    (for(c <- connection if c.isConnected) yield true).getOrElse(false)
  }

  def close() {
    synchronized {
      if(isConnected) {
        connection.foreach(_.close())
      }
    }
  }
}

NettyConnection:

class NettyConnection(val config: NettyConfig) extends Connection {

  @volatile
  private var channel = None: Option[Channel]

  def connect() = {
    val channelFuture = bootstrap().connect(new java.net.InetSocketAddress(config.hostname, config.port))
    channelFuture.awaitUninterruptibly
    channel = Some(channelFuture.getChannel)
  }

  def isConnected = channel.map(_.isOpen).getOrElse(false)
  ...

I am trying to do auto-reconnect in NettyConnectionManager.

Now I have three questions:

Is channel.isOpen method reflect the channel states immediately?
Is NettyConnectionManager thread safe? (get method never return a closed connection more than one time).
Is there a better way doing such reconnect job?


texts:
I've written an image resizer / uploader, that takes an incoming image, resizes it, and uploads it to the server, under the /usericons/ folder.

However, the code is sloppy. Can somebody suggest a better method / improvements?

define ("MAX_SIZE","400");

$errors = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $image = $_FILES["icon"]["name"];
  $uploadedfile = $_FILES['icon']['tmp_name'];
  if ($image) {
        $filename = stripslashes($_FILES['icon']['name']);
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
              echo ' Unknown Image extension ';
              $errors = 1;
        } else {
              $size=filesize($_FILES['icon']['tmp_name']);
              if ($size > MAX_SIZE*1024) {
                    echo "You have exceeded the size limit";
                    $errors = 1;
              }
              if ($extension == "jpg" || $extension == "jpeg" ) {
                    $uploadedfile = $_FILES['icon']['tmp_name'];
                    $src = imagecreatefromjpeg($uploadedfile);
              } else if($extension=="png") {
                    $uploadedfile = $_FILES['icon']['tmp_name'];
                    $src = imagecreatefrompng($uploadedfile);
              } else {
                    $src = imagecreatefromgif($uploadedfile);
              }
              list($width,$height)=getimagesize($uploadedfile);
              $newwidth = 500;
              $newheight = ($height/$width)*$newwidth;
              $tmp = imagecreatetruecolor($newwidth,$newheight);
              $newwidth1 = 300;
              $newheight1 = ($height/$width)*$newwidth1;
              $tmp1 = imagecreatetruecolor($newwidth1,$newheight1);
              imagecopyresampled($tmp, $src, 0,0,0,0, $newwidth, $newheight, $width, $height);
              imagecopyresampled($tmp1, $src, 0,0,0,0, $newwidth1, $newheight1, $width, $height);
              $filename = "usericons/500-". $_SESSION['username'] . '.png';
              $filename1 = "usericons/300-". $_SESSION['username'] . '.png';
              imagejpeg($tmp,$filename,100);
              imagejpeg($tmp1,$filename1,100);
              hasIcon($_SESSION['username']);
              imagedestroy($src);
              imagedestroy($tmp);
              imagedestroy($tmp1);
              echo '<script>window.location = "/Users/";</script>';
        }
  }
}
 //If no errors registred, print the success message

if (isset($_POST['Submit']) && !$errors) {
   echo "Image Upload Fail!";
}
function getExtension($str) {

     $i = strrpos($str,".");
     if (!$i) { return ""; }
     $l = strlen($str) - $i;
     $ext = substr($str,$i+1,$l);
     return $ext;
 }


texts:
I was assigned to write a piece of Haskell code that makes an infinite list containing increasing numbers of 'a's.

My first thought was to write it as a list comprehension like this:

aStar = [replicate n 'a' | n <- [0..]]

But when I asked my professor he said I should use explicit recursion so I came up with this:

aStar :: [String]
--repeats a string from 0
aStar = repeat' 0 'a'

repeat' :: Int -> Char -> [String]
repeat' n x = [cycle' x n] ++ repeat' (n + 1) x
    where cycle' _ 0 = ""
          cycle' y z = [y] ++ cycle' y (z - 1)

Is there a shorter way to do it?


texts: Building a table from the result of an AJAX call

texts:
I am looping through content coming from the database using an ajax call. Then I'm building a table using a for loop. Is there a faster way to build the table using the data from the database or is this way efficient enough?

var getPages = '

Page Num	Type	Month	Name	Reg No.	Rrc District

';

for(var i=0; i<getPagesResponse.length; i++) {
    getPages += '
' + getPagesResponse["PageNum"][i] + '	' + getPagesResponse["PageType"][i] + '	' + getPagesResponse["ReportingMonth"][i] + '	' + getPagesResponse["FilerName"][i] + '	' + getPagesResponse["FilerRegNo"][i] + '	' + getPagesResponse["RrcDistrict"][i] + '
';
}
getPages += '

';
//add table to div
$("#pagesTable").html(getPages);


texts: Django model with methods to register various kinds of events

texts:
Is there any better way to define the function in the class which shares most of the same parameters like functools.partial?

from django.db import models

class RegisterUserAction(models.Manager):
    def register_adhoc_created(self, **kwargs):
        return self.create(action_type="ADHOC_CREATED", **kwargs)

    def register_adhoc_deleted(self, *args, **kwargs):
        return self.create(action_type="ADHOC_DELETED", **kwargs)

    def register_broadcast_created(self, **kwargs):
        return self.create(action_type="BROADCAST_CREATED", **kwargs)


texts: AES encryption/decryption using pure .NET and streams

texts:
I'm trying my hand at simple encryption and decryption.  Ideally I'd like to be doing it the 'right' way, ie something secure without doing it in a way that will have a serious hole.  I'd prefer to do this using just the standard .NET libraries, rather than utilising an external library.  If what I'm doing is horrendously wrong, and simply isn't possible without a third-party library, please let me know!

Anyway, I've done a bit of research online, found various different examples (including on Stackoverflow), and found myself confused as to the best way to go about doing things.

I want to take advantage of streams if possible, ie CryptoStream, etc.  This way I can then take say, a FileStream or a MemoryStream and encrypt/decrypt them as desired.

This code is intended mainly 'proof of concept and how I should go about doing things'.  It's got a generated key, a generated iv, and it seems to work with the example string I have there.

It's all one simple application.  However, in theory, rather than encrypting a string, I'd be encrypting a file that is on some webserver, and sending the encrypted file over a web-service, and decrypting it client-side.  That's the idea.

I've read that it's good practice to generate a random key.  If I do that, then both the server and the client would need to know the same key.  I assume this would then mean that I'd need to transmit the key in the call to the web-service from the client.  Is that correct?  Is that secure?  I'd assume that the call to it would be done via HTTPS, but is there anything else I'd need to be aware of in that scenario?

The code I've provided is in VB.NET, and is below.  Be brutal!  If there is need of any further information, ask in the comments and I will try to provide it!

Module Module1

    Sub Main()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create()

            Dim unencryptedValue As String = "My test string"
            Console.WriteLine("Unencrypted: " & unencryptedValue)

            Dim encryptedData As Byte() = Encrypt(aes.Key, System.Text.UTF8Encoding.UTF8.GetBytes(unencryptedValue))
            Dim decryptedData As Byte() = Decrypt(aes.Key, encryptedData)
            Dim decryptedValue As String = System.Text.UTF8Encoding.UTF8.GetString(decryptedData)

            Console.WriteLine("Decrypted: " & decryptedValue)
            Console.ReadKey()
        End Using
    End Sub

    Public Function Encrypt(key As Byte(), unencryptedData As Byte()) As Byte()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
                ms_unencrypted As New IO.MemoryStream(unencryptedData),
                ms_encrypted As New IO.MemoryStream()

            Using cs As New Security.Cryptography.CryptoStream(ms_encrypted, aes.CreateEncryptor(key, aes.IV), Security.Cryptography.CryptoStreamMode.Write)
                ms_encrypted.Write(aes.IV, 0, aes.IV.Length)
                ms_unencrypted.CopyTo(cs)
            End Using

            Return ms_encrypted.ToArray()
        End Using
    End Function

    Public Function Decrypt(key As Byte(), encryptedData As Byte()) As Byte()
        Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
                ms_encrypted As New IO.MemoryStream(encryptedData, 0, encryptedData.Length, False, True),
                ms_decrypted As New IO.MemoryStream()

            Dim iv(15) As Byte
            ms_encrypted.Read(iv, 0, 16)

            Using cs As New Security.Cryptography.CryptoStream(ms_encrypted, aes.CreateDecryptor(key, iv), Security.Cryptography.CryptoStreamMode.Read)
                cs.CopyTo(ms_decrypted)

            End Using

            Return ms_decrypted.ToArray()

        End Using
    End Function

End Module


texts: Processing keyboard input for player movement in a game

texts:
The following code is part of a game I am making using the Phaser framework; the game is in the style of a top-down RPG, with the player moving their character in four possible directions using the arrow keys. This code appears in my update() method.

I like the user experience provided by this code a lot: the character moves on the screen exactly how I intend. However, I can't help but notice that there's a lot of repetition here and I'd like to explore ways of writing this more efficiently and avoiding repetition. I have already investigated case statements vs if/else statements and have found that a lot of repetition still occurs. I tend to encounter these same repetition issues whenever I need to process keyboard input, regardless of the programming language.

NB. I've come across this Code Review question which seems to be close to what I am looking for, but haven't been able to successfully apply the concept to my own project (ie. my version of that code isn't 'working', so isn't appropriate for Code Review).

   if(!this.inputBlocked) {
        if(this.cursors.left.isDown) {
            this.playerInputDirection = 'W';
            this.player.body.velocity.x = -this.PLAYER_SPEED;
        }
        if(this.cursors.right.isDown) {
            this.playerInputDirection = 'E';
            this.player.body.velocity.x = this.PLAYER_SPEED;
        }
        if(this.cursors.up.isDown) {
            this.playerInputDirection = 'N';
            this.player.body.velocity.y = -this.PLAYER_SPEED;
        }
        if(this.cursors.down.isDown) {
            this.playerInputDirection = 'S';
            this.player.body.velocity.y = this.PLAYER_SPEED;
        }
    }

    //control player walking animation
    if(this.player.body.velocity.x != 0 || this.player.body.velocity.y != 0) {
        // check for direction, play appropriate animation
        if (this.playerInputDirection == 'W'){
            this.player.play('walkLeft');
        }
        if (this.playerInputDirection == 'E'){
            this.player.play('walkRight');
        }
        if (this.playerInputDirection == 'N'){
            this.player.play('walkUp');
        }
        if (this.playerInputDirection == 'S'){
            this.player.play('walkDown');
        }
    } else {
    // stop all animation
        this.player.animations.stop();

    // determine the correct sprite frame,
    // so player stops while facing appropriate direction
        if (this.playerInputDirection == 'W'){
            this.player.frame = 4;
        }
        if (this.playerInputDirection == 'E'){
            this.player.frame = 12;
        }
        if (this.playerInputDirection == 'N'){
            this.player.frame = 8;
        }
        if (this.playerInputDirection == 'S'){
            this.player.frame = 0;
        }
    }


texts: To calculate the total CPU usage as a percentage

texts:
I have been developing the below method to calculate the CPU usage of a Linux system at a point in time, as a percentage of the total number of cores available in the system.

#!/bin/bash

# Get number of cores from proc cpuinfo
CORECOUNT=`grep -c ^processor /proc/cpuinfo`
# Use top, skip the first 7 rows, count the sum of the values in column 9 - the CPU column, do some simple rounding at the end.
CPUUSAGE=`top -bn 1 | awk 'NR>7{s+=$9} END {print s/'$CORECOUNT'}' | awk '{print int($1+0.5)}'`
printf "$CPUUSAGE\n"

Would this be considered a reasonably accurate way of doing this? Any suggestions to increase efficiency/accuracy would be greatly appreciated.


texts:
This is my solution to the common 'Array Rotation' algorithm. As I am currently practicing for coding interviews, I want to make sure that my code in fact valid for coding interview scenarios. Would I lose points for using JavaScript's built-in shift and push array methods?

function main() {
var n_temp = readLine().split(' ');
var arrLength = parseInt(n_temp[0]);
var rotations = parseInt(n_temp[1]);
var frontNum;
a = readLine().split(' ');
a = a.map(Number);

for (var i = 0; i < rotations; i++) {
    frontNum = a.shift();
    a.push(frontNum);
}
 console.log(a.join(' '));
}


texts: Should I differentiate object types by calling methods via variables?

texts:
I have three JavaScript objects. The first one serves merely as a prototype. The other two are implementation of a specific type.

var MainPrototype = {};
var SpecificType = $.extend(Object.create(MainPrototype));
var OtherSpecificType = $.extend(Object.create(MainPrototype));

I am missing the option of a parent-method and am trying to implement some specifics for each specific type.

I started of by comparing the types within the main prototype object, yet I found the nesting if-else clausing worrysome and in case that new types would be introduced, I guess the code will get ugly fast. I also does not feel right to put the specifics into the main function.

var MainPrototype = {
    function: bind() {
        //generic stuff

        if (this.type === SpecificType.type) {
          // specifics for this type
        } else if (this.type === OtherSpecificType.type) {
          // specifics for other type
        }
    }
}

That's why I thought I could call a specific function dynamically.

var MainPrototype = {
    bind: function() {
        //generic stuff
        var specificBindMethod = this.type + "Bind";
        if (typeof(this[bindMethod]) === "function") {
            this[categoryBindMethod]();
        }
    }
};

var SpecificType = $.extend(Object.create(MainPrototype, {
  type: 'specific',
  specificBind: function() {
    // doSpecifics
  }
});
var OtherSpecificType = $.extend(Object.create(MainPrototype, {
  function: 'other',
  otherBind: function() {
    // doSpecifics
  }
})

Now I can define the specific function within its proper object and only if they exist they will get called getting rid of the nesting.

I am wondering if this approach is better in terms of maintainability and extensibility or if I should have stayed with the if-else-approach or if there is anything better to solve my current use case.


texts:
I have a 2D array of fixed size and I've implemented a FIFO function. So, the array will always be full before it reaches the FIFO function, then the FIFO will remove the oldest array, move all of the arrays up by one and then add the newest array to the other end. Basically a queue. Now, this code will actually be running on a microcontroller, an array will come from an ADC and then I store the ADC array in a 2D array. To design the FIFO algorithm in simple C first, I have written a program that generates random numbers and then stores them into a 2D buffer. The program then asks the user what new values should be stored, user puts in the latest array of values and then the program removes the oldest array, shuffles all the remaining arrays up by one and then the latest user numbers get added to the end. The program does this 10 times. This is designed to simulate what is happening in the microcontroller code. The 2D array is already full with values and then the ADC adds the latest set of values to the array, and the oldest set are forgotten.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int fixed_number[5] = { 0 };
uint16_t big_array[10][5] = { 0 };
uint16_t big_array_copy[10][5] = { 0 };
uint16_t small_array_1[5] = { 0 };
uint16_t k[1] = { 0 };
uint8_t count = 0;
int main()
{
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array[j][i] = rand() % 255;
        }
    }
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            big_array_copy[j][i] = big_array[j][i];
        }
    }
    printf("These are the original numbers in the big array:\n");
    for (int j = 0; j < 10; j++)
    {
        for (int i = 0; i < 5; i++)
        {
            k[0] = big_array[j][i];
            printf("%d,", k[0]);
                    }
        printf("\n");
            }
    while (count < 10)
    {
        printf("Please enter values for queue:\n");
        for (int i = 0; i < 5; i++)
        {
            scanf_s("%d", &fixed_number[i]);
        }
           printf("\n\n");
        printf("Array values have been swapped:\n ");
        for (int k = 0; k < 5; k++)
        {
            big_array_copy[10 - 1][k] = 0;
        }
                for (int j = 9; j > 0; j--)
        {

            for (int i = 0; i < 5; i++)
            {
                //small_array_1[i] = big_array[j + 1][i];
                big_array_copy[j][i] = big_array[j - 1][i];
            }
        }
        for (int i = 0; i < 5; i++)
        {
            big_array_copy[0][i] = fixed_number[i];
        }
        for (int j = 0; j < 10; j++)
        {
            for (int i = 0; i < 5; i++)
            {
                k[0] = big_array_copy[j][i];
                printf("%d,", k[0]);
            }
            printf("\n");
        }
        for (int j = 0; j < 10; j++)
        {
            for (int i = 0; i < 5; i++)
            {
                big_array[j][i] = big_array_copy[j][i];
            }
        }
        count++;
    }
}

Now this code works perfectly fine, but there is a lot of loops and it also requires twice the memory space as the buffer, big_array[][] must be copied in to big_array_copy[][]. In the real application, the buffer is uint16_t somebuffer[100][45] which is 4.5kb. I've got 512kb of SRAM to use, but I'd rather use as little as I can.
The above method can be implemented on my target platform (STM32F767 for those wondering) but is there a more simple method to implementing the above, that uses fairly portable c with no special functions, that could reduce the memory required and the processing time required?
thanks


texts:
I'm not sure how to title this post as I'm a bit confuse here. My code updates a field in line. It's done in two separate functions. It works well but I wonder if it's possible to handle it in only one function?

Here is the HTML code. The form is shown on hover only and value is updated on change.

<form class='editable' action="{% url "dashboard_staff:ajax_prestation_length_update" uuid=prestation.uuid %}" method="post">
    {% csrf_token %}
    <input type="text" class="collapse" name="length" value="{{ prestation.length }}">
    <span>{{ prestation.d_length }}</span>
</form>

And the javascript:

// Editable in line fields

$('.editable').hover(function () {
    var el_text = this.lastElementChild;
    var el_input = this[1];
    $(el_text).toggleClass('collapse');
    $(el_input).toggleClass('collapse');
});

$('.editable').change(function () {
    event.preventDefault();
    var el_text = this.lastElementChild;
    var action = this.action;
    var method = this.method;
    var data = $(this).serialize();

    $.ajax({
        url: action,
        type: method,
        data: data,
    }).done(function (resp) {
        el_text.textContent = resp.data
    });
});

I'm not sure it is correct to add multiple functions to a same class as well.


texts: Getting products by category, price, etc

texts:
I have the following concerns:

Is Set a good choice for getting products? What are drawbacks of Set for this purpose?
Is it better to do something like common.retainAll() or to get products through a request with WHERE to the database. For now I do three requests in: getProductsByCategory, getProductsByManufacturer, getProductsByPrice. So maybe it would be better to make just one?

@RequestMapping("/{category}/{price}")
public String filterProducts(@PathVariable("category") String productCategory,
        @MatrixVariable(pathVar = "price") Map<String, List<String>> priceParams,
        @RequestParam("manufacturer") String manufacturer, Model model) {

    Set<Product> productsByCategory = service.getProductsByCategory(productCategory);
    Set<Product> productsByManufacturer = service.getProductsByManufacturer(manufacturer);

    BigDecimal low;
    BigDecimal high;

    low = new BigDecimal(priceParams.get("low").get(0));
    System.out.println(low);
    high = new BigDecimal(priceParams.get("high").get(0));
    System.out.println(high);

    Set<Product> productsByPrice = service.getProductsByPrice(low, high);

    Set<Product> common = new HashSet<Product>(productsByCategory);

    common.retainAll(productsByManufacturer);
    common.retainAll(productsByPrice);

    model.addAttribute("products", common);

    return "products";

}


texts:
I am modeling an infectious disease with a fixed incubation period. I chose a queue to keep track of when people become symptomatic. I imagined using some operations like so:

queue' = enqueue numberOfPeopleWhoJustGotInfected queue
(numberOfPeopleWhoJustBecameSymptomatic,queue'') = dequeue queue

Since enqueue and dequeue would always be atomic and the queue length would be fixed, I wrote a fixed length queue data structure. endequeue models the atomic enqueue & dequeue sequence. I hope that it will be more efficient than the library Data.Queue.

I'd like feedback on:

Efficiency. Can it be improved?
Typeclasses. Did I use them correctly? Am I missing others which are applicable?
Test Cases. Are there other logical properties I could add?

Haskell Code:

module FixedLengthQueue
 ( endequeue
 , fromList
 , length
 , peek
 ) where

import Prelude hiding (foldl,foldl1,foldr,foldr1,length)
import Control.Applicative ((<$>),(<*>))
import Data.Array
import Data.Foldable
import Data.Functor
import Data.Maybe  (fromJust)
import Data.Monoid

type Pointer = Int
type Length  = Int

data FixedLengthQueue a = FLQ Length Pointer (Array Int a)
  deriving (Eq) -- I need to manually define, see tests

instance (Show a) => Show (FixedLengthQueue a) where
  show = ("fromList "++) . show . toList

instance Functor FixedLengthQueue where
  fmap f =  fromJust . fromList . fmap f . toList

instance Foldable FixedLengthQueue where
  foldMap f (FLQ n p arr)
    =  f (arr ! p) <> g (succMod p n)
    where
      g z
        | z /= p    = f (arr ! z) <> g (succMod z n)
        | otherwise = mempty

fromList :: [a] -> Maybe (FixedLengthQueue a)
fromList [] = Nothing -- Nonsensical empty fixed length queue
fromList xs
  = Just
  . FLQ len 0
  . array (0, len-1)
  $ zip   [0..len-1] xs
  where
    len = foldl' inc 0 xs
    inc = flip (const succ)

length :: FixedLengthQueue a -> Int
length (FLQ n _ _) = n

peek :: FixedLengthQueue a -> a
peek (FLQ _ p arr) = arr ! p

endequeue :: a -> FixedLengthQueue a -> (a,FixedLengthQueue a)
endequeue e (FLQ n p arr)
  = ( arr ! p
    , FLQ n (succMod p n) $ arr // [(p,e)]
    )

succMod n m
  | n' >= m   = n' - m
  | otherwise = n'
  where n' = succ n

Basic Tests:

module Main where

import Prelude hiding (mapM_)
import Data.Foldable
import FixedLengthQueue
import Test.QuickCheck
import Safe

main ::  IO ()
main =
  mapM_ quickCheck
  ([ \x -> fmap peek                                        (fromList x) == headMay x
   , \x -> fmap (fst . endequeue undefined)                 (fromList x) == headMay x
   , \x -> fmap (init . toList . snd . endequeue undefined) (fromList x) == tailMay x
   , \x -> let mxs = (replicate 2) <$> (headMay x) >>= fromList
           in (snd . (endequeue <$> peek <*> id) <$> mxs)                == mxs
   ] :: [[Int] -> Bool])