texts: Spectrum Analysis with Discrete Fourier Transform

texts:
Here is a simple implementation of the Discrete Fourier Transform:

myFourierTransform.m

function [ft] = myFourierTransform (X, n)
% Objective:
%   Apply the Discrete Fourier Transform on X.
% Input:
%   X - 1xM - complex vector - data points (signal discretisation).
%   n - 1x1 - integer scalar - number of discrete frequencies (spectrum discretisation).
% Output:
%   ft - 1xn - complex vector - "quantity of" i-th frequency in X.
% Complexity: O(n * M).
% Author:
% Date:

  ft = zeros(1, n);
  freq = @(point_index, freq_index, total_freqs)...
  exp( -2 .* pi .* j  .*(point_index - 1) .* (freq_index - 1) / total_freqs );

  for i = 1 : n

    f_i = freq(1: numel(X), i, n);

    ft(i) = dot(X, f_i);

  end

end

Here is a script file applying the above and comparing it to the built-in function fft(X, n):

applyMyFourierTransform.m

clc; clear; close all;

% Signal parameters
A = 1;                                 % signal amplitude.
f = 10;                                % frequency of the signal 10 Hz.
theta = 0.25 * pi;                     % initial phase of the signal.
measurement_rate = f * 30;             % Nyquist-Shannon Th.-rate of measurement >=2*f.

nPeriods = 7;                          % number of periods to be displayed.
tBeg = 0;
tEnd = nPeriods * 1 / f;
tStep = 1 / measurement_rate ;

t = tBeg : tStep : tEnd;
x = A * sin(2 * pi * f * t + theta);   % sine wave A= 1 V,f= 10 Hz, phi_0= pi/4 rad.
P = A^2 / 2;                           % signal power=\frac{1}{T}\int_0^T {x{^2}(t)dt}.
point_num = numel(x);

% Plot the test signal.
subplot(3, 1, 1)
plot(t, x);
xlabel('Time [sec]');
ylabel('Amplitude');
title('Test Signal.');
legend( sprintf( 'f = %.2f [Hz] \n A = %.2f [V]', f, A ) );

% Apply FFT and obtain spectrum of test signal.
freq_num = 2^10;                       % Discretise the spectrum in 1024 frequencies.
bfft = fft(x, freq_num);               % built-in Discrete Fourier Transform.

bfft = fftshift(bfft);                 % shift f(0) at the middle of the vector.

% Calculate signal power \frac{X_k * X_k^{*}}{Frequency_Discretisation * Data_size}.
power = bfft .* conj(bfft) / (freq_num * point_num);

% Frequency axis starts at: -f/2 ends at: f/2 and includes: n frequencies.
frequencies = measurement_rate * (-freq_num / 2 : freq_num/ 2 -1) / freq_num;

subplot(3, 1, 2)
plot(frequencies, power);
xlabel('Frequency [Hz]');
axis([-10*f 10*f])
set(gca, 'XTick', [-10*f : f : 10*f]);
ylabel('Power [Watt]');
title('Power Spectral Density.')
legend( sprintf( 'f = %.2f [Hz]\n P = %.2f [W].', f ,P ) )

% Apply custom implementation of Discrete Fourier Transform.
cdft = myFourierTransform(x, freq_num);
cdft = fftshift(cdft);
cpower = cdft .* conj(cdft) / (freq_num * point_num);

subplot(3, 1, 3)
plot(frequencies, cpower);
xlabel('Frequency [Hz]');
axis([-10*f 10*f])
set(gca, 'XTick', [-10*f : f : 10*f]);
ylabel('Power [Watt]');
title('Power Spectral Density.')
legend( sprintf( 'f = %.2f [Hz]\n P = %.2f [W].', f, P ) )

error = abs( sum(cdft) - sum(bfft) )

Command Line:

>> applyMyFourierTransform

Result:

>> error =   1.7346e-011

Questions

How can I estimate the validity of the values produced by the custom implementation? Is this a reasonable estimate?

error = abs( sum(cdft) - sum(bfft) )


texts:
I'm a total noob to OpenGL just following the tutorial at learnopengl.com. Anyway, I'm trying to build a GUI that involves rectangles that have border radiuses. I figured I could do this using the fragment shader. Essentially, I'm masking each corner with a circle that is r units away from each wall for that corner. I then check if the point is between the circle's center and the corner. If the point is between those two, then I check if it's outside of the circle's radius. If so, I discard the point.
#version 330 core

// the xy position of the fragment (in world coordinates?)
in vec2 xy;

// the bottom left corner of the rectangle
uniform vec2 u_position;

// the width and height of the rectangle
uniform vec2 u_dimensions;

// the border radius (how far the mask circle's center we be from either wall of the corner)
uniform float u_radius;

out vec4 FragColor;

void main(void) {
    // xy = test point coordinates
    // rc = rectangle corner
    // ec = ellipse center
    // uv = test point coordinates relative to ellipse center
    if (xy.x - u_position.x < u_dimensions.x / 2) {
        if (xy.y - u_position.y < u_dimensions.y / 2) {
            // bottom left
            vec2 rc = u_position;
            vec2 ec = rc + vec2(u_radius, u_radius);
            vec2 uv = xy - ec;
            if (uv.x < 0 && uv.y < 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
                discard;
            }
        } else {
            // top left
            vec2 rc = u_position + vec2(0, u_dimensions.y);
            vec2 ec = rc + vec2(u_radius, -u_radius);
            vec2 uv = xy - ec;
            if (uv.x < 0 && uv.y > 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
                discard;
            }
        }
    } else {
        if (xy.y - u_position.y < u_dimensions.y / 2) {
            // bottom right
            vec2 rc = u_position + vec2(u_dimensions.x, 0);
            vec2 ec = rc + vec2(-u_radius, u_radius);
            vec2 uv = xy - ec;
            if (uv.x > 0 && uv.y < 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
                discard;
            }
        } else {
            // top right
            vec2 rc = u_position + vec2(u_dimensions.x, u_dimensions.y);
            vec2 ec = rc + vec2(-u_radius, -u_radius);
            vec2 uv = xy - ec;
            if (uv.x > 0 && uv.y > 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
                discard;
            }
        }
    }
    FragColor = vec4(0.0f, 0.0f, 0.0f, 1.0f);
}

The result looks like this (the corners are really jagged):


texts: Promise.all, but with enforced limit on concurrent promises

texts:
I'm trying to implement parallelLimit() to limit the number of parallel tasks that can be performed at any time. Personally, I'm using this function for limiting the parallel uploads from my code.

const _ = require('lodash');

async function _parallelLimit(tasks, limit) {
  const _tasks = Object.assign([], _.zip(tasks, _.range(tasks.length)));
  const results = [];
  const awaitWorker = async () => {
    while (_tasks.length > 0) {
      const [task, idx] = _tasks.pop();
      results[idx] = await task();
    }
  };
  await Promise.all(_.range(0, limit).map(awaitWorker));
  return results;
}


texts: Applying random luck scores to instances of people

texts:
I'm trying to do a simulation on the role of luck in human achievement.
Here is what I intend to do with my code:

Create 20000 instances of people with randomly generated scores for skill, experience and hard-work(0 to 99), and a luck value(0 to 100).
Create a total score for each person, with 95% of the average of the skill, experience and hard-work, and 5% of their luck value.
Select the top 10 persons and record their luck value.
Iterate the procedure a specified amount of times and find the total average luck of all the people who came top ten in all of the iterations.

Please review the code and tell me if my code is correctly written for the above purpose. I'm skeptical about the pseudo-randomness random library interfering with the results.
import random
class candidate :
    def __init__(self):
        self.skill = random.uniform(0,99)
        self.exp = random.uniform(0,99)
        self.work = random.uniform(0,99)
        self.luck = random.uniform(0,100)
        self.total_score = ((self.skill+self.exp+self.work)/3)*.95+self.luck*0.05

candidate_list = []
candidate_selected_lucks = []
def select():
    for i in range (0,20000):
        candidate_list.append(candidate())
    for m in range(0,10):
        _max = 0.0
        for j in range (0,len(candidate_list)):
            if (candidate_list[j].total_score > _max):
                _max = candidate_list[j].total_score
                index = j
        candidate_selected_lucks .append(candidate_list[index].luck)
        print(m,"."," Score : ", candidate_list[index].total_score, " Luck : ", candidate_list[index].luck,"\n")
        candidate_list.pop(index)

def find_avg(candidate_selected_lucks):
    return sum(candidate_selected_lucks)/len(candidate_selected_lucks)

def simulate(N):
    for k in range(0,N):
        print ("Iteration ",str(k+1),". ")
        select()
        candidate_list.clear()
    print ("average luck is", find_avg(candidate_selected_lucks),"\n")

count = int(input("Enter no of simulations\n"))
simulate(count)


texts:
Which method below should I use to generate a "random letter by frequency" using Javascript?

From https://gist.github.com/furf/2413792

var randomAtoZ = (function (lookup) {
    return function () {
        var random = Math.random() * 100000,
                letter;
        for (letter in lookup) {
            if (random < lookup[letter]) {
                return letter;
            }
        }
    }
})({
    // Ranges calculated from data found at
    // http://en.wikipedia.org/wiki/Letter_frequency
    a: 8167,  b: 9659,  c: 12441, d: 16694,
    e: 29396, f: 31624, g: 33639, h: 39733,
    i: 46699, j: 46852, k: 47624, l: 51649,
    m: 54055, n: 60804, o: 68311, p: 70240,
    q: 70335, r: 76322, s: 82649, t: 91705,
    u: 94463, v: 95441, w: 97801, x: 97951,
    y: 99925, z: 100000
});

My re-write

function randomAtoZ() {
    // Ranges calculated from data found at
    // http://en.wikipedia.org/wiki/Letter_frequency
    var lookup = {
        a: 8167,  b: 9659,  c: 12441, d: 16694,
        e: 29396, f: 31624, g: 33639, h: 39733,
        i: 46699, j: 46852, k: 47624, l: 51649,
        m: 54055, n: 60804, o: 68311, p: 70240,
        q: 70335, r: 76322, s: 82649, t: 91705,
        u: 94463, v: 95441, w: 97801, x: 97951,
        y: 99925, z: 100000
    };

    var random = Math.random() * 100000;

    for (letter in lookup) {
        if (lookup[letter] > random) {
            return letter;
        }
    }
}


texts:
I'm trying to make a card game, using OOP style. I decided to make suit a class rather than an enum as I would first have done. How am I doing so far? Am I over-complicating things by making it a class?

namespace Cards
{
class Suit
{
public:
    Suit();
    ~Suit();

    std::string GetName(bool plural, bool capital) const;
    bool IsRed() const;
    bool IsBlack() const;
    bool IsDifferentColour(const Suit& other) const;
    bool IsSameColour(const Suit& other) const;
    bool operator == (const Suit& other) const;
    bool operator != (const Suit& other) const;
    bool operator < (const Suit& other) const;

    static const Suit hearts, diamonds, clubs, spades;

private:
    enum Type
    {
        Type_Null,
        Type_Hearts,
        Type_Diamonds,
        Type_Clubs,
        Type_Spades
    } type;

    explicit Suit(Type type);
};
}

const Cards::Suit Cards::Suit::hearts(Type_Hearts);
const Cards::Suit Cards::Suit::diamonds(Type_Diamonds);
const Cards::Suit Cards::Suit::clubs(Type_Clubs);
const Cards::Suit Cards::Suit::spades(Type_Spades);

Cards::Suit::Suit()
    : type(Type_Null)
{}

Cards::Suit::Suit(Type type)
    : type(type)
{}

Cards::Suit::~Suit()
{}

std::string Cards::Suit::GetName(bool plural, bool capital) const
{
    std::string name;

    switch (type)
    {
    case Type_Hearts:
        {
             name = "Heart";
        }
        break;

    case Type_Diamonds:
        {
            name = "Diamond";
        }
        break;

    case Type_Clubs:
        {
            name = "Club";
        }
        break;

    case Type_Spades:
        {
            name = "Spade";
        }
        break;

    default:
        {
            assert(false);
        }
        break;
    }

    if (! capital)
    {
        name[0] = static_cast<std::string::value_type>(::tolower(name[0]));
    }

    if (plural)
    {
        name += "s";
    }

    return name;
}

bool Cards::Suit::IsRed() const
{
    bool red;

    switch (type)
    {
        case Type_Hearts:
        {
             red = true;
        }
        break;

    case Type_Diamonds:
        {
            red = true;
        }
        break;

    case Type_Clubs:
        {
            red = false;
        }
        break;

    case Type_Spades:
        {
            red = false;
        }
        break;

    default:
        {
            assert(false);
            // prevent compiler warning
            red = false;
        }
    }

    return red;
}

bool Cards::Suit::IsBlack() const
{
    return ! IsRed();
}

bool Cards::Suit::IsDifferentColour(const Suit& other) const
{
    return this->IsRed() != other.IsRed();
}

bool Cards::Suit::IsSameColour(const Suit& other) const
{
    return this->IsRed() == other.IsRed();
}

bool Cards::Suit::operator == (const Cards::Suit& other) const
{
    return this->type == other.type;
}

bool Cards::Suit::operator != (const Cards::Suit& other) const
{
    return ! (*this == other);
}

bool Cards::Suit::operator < (const Cards::Suit& other) const
{
    return this->type < other.type;
}


texts:
I am trying to implement ugly number sequence generation in Scala.

Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence  1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15...

I have implemented using var keyword like java implementation and it is working fine. Here is the ideone link of complete code.

Can someone suggest better of implementing it using Scala idioms and without using mutable values?

/**
 * Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
 * 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
 * shows the first 11 ugly numbers. By convention, 1 is included.
 * Write a program to find and print the 150th ugly number.
 *
 */
object UglyNumbers extends App {
  var uglyNumbers = List(1)
  val n = 11

  var i2 = 0;
  var i3 = 0;
  var i5 = 0;

  // initialize three choices for the next ugly numbers
  var next_multiple_2 = uglyNumbers(i2) * 2;
  var next_multiple_3 = uglyNumbers(i3) * 3;
  var next_multiple_5 = uglyNumbers(i5) * 5;

  for (i <- 0 to n) {
    val nextUglyNumber = min(next_multiple_2, next_multiple_3, next_multiple_5)
    uglyNumbers = uglyNumbers :+ nextUglyNumber

    if (nextUglyNumber == next_multiple_2) {
      i2 = i2 + 1
      next_multiple_2 = uglyNumbers(i2) * 2
    }

    if (nextUglyNumber == next_multiple_3) {
      i3 = i3 + 1
      next_multiple_3 = uglyNumbers(i3) * 3
    }

    if (nextUglyNumber == next_multiple_5) {
      i5 = i5 + 1
      next_multiple_5 = uglyNumbers(i5) * 5
    }
  }

  for (uglyNumber <- uglyNumbers)
    print(uglyNumber + "   ")

  def min(a: Int, b: Int, c: Int): Int = (a, b, c) match {
    case _ if (a <= b && a <= c) => a
    case _ if (b <= a && b <= c) => b
    case _ => c
  }
}


texts: Print path (leaf to root) with max sum in a binary tree

texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

public class MaxSumPath {

    private TreeNode root;

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

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    private static class TreeInfo {
        TreeNode node;
        int maxCount;

        TreeInfo (TreeNode node, int maxCount) {
            this.node = node;
            this.maxCount = maxCount;
        }
    }

    public void maxSumPath () {
        final TreeInfo treeInfo = new TreeInfo(null, 0);
        fetchMaxSumPath(root, treeInfo, root.item);
        printPath (root, treeInfo);
    }

    private void fetchMaxSumPath (TreeNode node, TreeInfo treeInfo, int sumSoFar) {
        if (node == null) return;

        sumSoFar = sumSoFar + node.item;

        if (node.right == null && node.left == null) {
            if (sumSoFar > treeInfo.maxCount) {
                treeInfo.maxCount = sumSoFar;
                treeInfo.node = node;
            }
            return;
        }

        fetchMaxSumPath(node.left, treeInfo, sumSoFar);
        fetchMaxSumPath(node.right, treeInfo, sumSoFar);
    }

    private boolean printPath (TreeNode node, TreeInfo treeInfo) {
        if (node != null &&  (node == treeInfo.node || printPath(node.left, treeInfo) || printPath(node.right, treeInfo))) {
            System.out.print(node.item + ", ");
            return true;
        }
        return false;
    }
}

Also considering additional storage (TreeInfo), is it right to say that the space complexity is \$O(1)\$?


texts:
Okay, so just having a little fun I thought I'd see if I could write an algorithm to find all of the prime factors of a number. The solution I came up with is as follows:

class Program
{
    static void Main(string[] args)
    {
        var subject = long.MaxValue;
        var factors = new List<long>();
        var maxFactor = 0;

        Console.WriteLine("Factoring {0} ...", subject);

        var sw = new Stopwatch();
        sw.Start();

        while (subject > 1)
        {
            var nextFactor = 2;
            if (subject % nextFactor > 0)
            {
                nextFactor = 3;
                do
                {
                    if (subject % nextFactor == 0)
                    {
                        break;
                    }

                    nextFactor += 2;
                } while (nextFactor < subject);
            }

            subject /= nextFactor;
            factors.Add(nextFactor);
            if (nextFactor > maxFactor)
            {
                maxFactor = nextFactor;
            }
        }

        sw.Stop();

        var factorAnswer = 1L;
        factors.ForEach(f => factorAnswer *= f);

        Console.WriteLine("Factors: {0} = {1}",
            string.Join(" * ",
                factors.Select(i => i.ToString()).ToArray()),
            factorAnswer);
        Console.WriteLine("Max Factor: {0}", maxFactor);
        Console.WriteLine("Elapsed Time: {0}ms", sw.ElapsedMilliseconds);
    }
}

and its output is:

Factoring 9223372036854775807 ...
Factors: 7 * 7 * 73 * 127 * 337 * 92737 * 649657 = 9223372036854775807
Max Factor: 649657
Elapsed Time: 3ms

It works, and IMO awfully fast, but it's a little brute force. Is there a better way of doing it?


texts:
I have written a solution to a DM::OJ exercise to find the next Prime Number after a given number (input).  I'm seeking to optimize it so that it will run for any number up to 1000000000 in 2 seconds or less.

Here is my code:

from functools import reduce

num = int(input())

def factors(n):
  return set(reduce(list.__add__,
  ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

f = (factors(num))

if (len(f) != 2):
  while (len(f) != 2):
    num += 1
    f = factors(num)
  print (num)
else:
  print (num)

Just as a side note, I also found another way to execute this exact same thing, but that one is slower, so I wouldn't mind bothering with that way. However, just for reference though, I'm still adding the slow one anyways:

num = int(input())

def factors(x):
  a = []
  for i in range(1, x + 1):
      if x % i == 0:
          a.append(i)
  return a

f = (factors(num))

if (len(f) != 2):
  while (len(f) != 2):
    num += 1
    f = factors(num)
  print (num)
else:
  print (num)


texts: Interactive Discord bot for tabletop RPG

texts:
I'm new to Python, but have experience in a variety of other languages. I've learnt that a code review early on would make sure I don't start with bad habits. Which are more difficult to get out the longer you keep them.

This is a Discord bot for one of my hobby projects.

import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
token = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='!')

@bot.command(name='ability', aliases=['a', 'ab'], help='Roll an ability check. Parameters: ability [no. of heroic dice].')
async def ability(ctx, ability:int, heroic:int=0):
    if ability < -5 or ability > 5:
        await ctx.send('Invalid ability value "{}". Must be between -5 and +5'.format(ability))
        return
    if heroic < 0 or heroic > 5:
        await ctx.send('Invalid heroic dice amount "{}". Must be between 0 and 5 (3 + 2 ritual dice)'.format(heroic))
        return

    dice = 2 + abs(ability) + heroic
    keep_dice = 2 + heroic
    if (ability < 0):
        keep = 'lowest'
    else:
        keep = 'highest'

    roll = []
    for x in range(0, dice):
        roll.append(roll_die())

    result = sorted(roll)
    if keep == 'highest':
        result.reverse()
    outcome = result[:keep_dice]

    # check for critical success (a pair) or failure (all 1s)
    last = -1
    critical = False
    fail = True
    for d in outcome:
        if d != 1:
            fail = False
        if d == last and d != 1:
            critical = True
        last = d

    if critical:
        # critical success - add the next highest/lowest die as well
        if keep_dice == dice:
            # roll an additional die
            outcome.append(roll_die())
            outcome.sort()
        else:
            outcome = result[:keep_dice+1]
    elif fail:
        outcome = []
        for x in range(0, keep_dice):
            outcome.append(0)

    # now sum up all our dice for the total
    sum = 0
    for d in outcome:
        sum += d

    embed = discord.Embed(title='**Dragon Eye** Ability Test for {}'.format(ctx.author.name),
                          description='Rolling {}d10, keep {} {}'.format(dice, keep, keep_dice),
                          color=0x22a7f0)
    embed.add_field(name='Roll', value=format(roll), inline=False)
    embed.add_field(name='Outcome', value=format(outcome), inline=True)
    embed.add_field(name='Total', value=format(sum), inline=True)
    if critical:
        embed.add_field(name='Additional Info', value='**Critical Success**', inline=True)
    elif fail:
        embed.add_field(name='Additional Info', value='**Critical Fail**', inline=True)

    await ctx.send(embed=embed)

def roll_die(sides=10):
    die = random.randint(1, sides)
    return die

bot.run(token)


texts:
I implemented this peak finder for practice. I have tested it. Everything looks pretty good to me. Please let me know if there is any improvement I can make.

  Peak Finder

  Let input be an array. input[i] is a peak if input[i] >= input[i + 1] and input[i] >= input[i - 1].

  Implement a recursive algorithm of time complexity \$O(\log{n})\$ to find a peak.

class PeakFinder <E extends Comparable<? super E>>{
  private E[] array;

  public PeakFinder(E[] array){
    if(array == null || array.length == 0)
      throw new IllegalArgumentException("array cannot be null or 0");
    this.array = array;
  }

  public E find(){
    return findUtil(0, array.length - 1);
  }

  private E findUtil(int left, int right){
      int mid = (right - left)/2 + left;
      int newLeft = mid + 1;
      int newRight = mid - 1;

      if(newLeft <= right && array[newLeft].compareTo(array[mid]) > 0)
        return findUtil(newLeft, right);
      else if(newRight >= left && array[newRight].compareTo(array[mid]) > 0)
        return findUtil(left, newRight);
      else
        return array[mid];
  }
}

An array always has at least one peak if it is not null or empty.

Special cases:

input[i] is a peak if input[i] >= input[i+1] when input[i] is the first element in the array.
input[i] is a peak if input[i] >= input[i-1] when input[i] is the last element in the array.
input[i] is a peak if input[i] is the only element in the array.


texts: Implementation of unix utility tail in C

texts:
I've written a simple implementation of tail as part of reading The C Programming Language by Kernighan & Ritchie.

The question states to write tail, which prints the last n lines of its input. By default, n is 10 but should be able to be specified by writing:
tail -n to print the last n lines. I don't think the program has to open and read files, as that hasn't been covered in the book as of yet.

I chose to take input as tail -n <number> and wrote the code for parsing the arguments in (hopefully) that would allow for addition of more arguments at a later date easier using the switch statement. However right now, if there were more arguments (say x and z) one could write tail -xzn 10 which would be valid, printing the last 10 lines of input - which maybe could be viewed as a problem.

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

#define MAXLEN 1000

int tail(char *buffer[], int n);
int read_line(char *line, int max);
void print_lines(char* buffer[], int n);

static int lines_read = 0;

int main(int argc, char* argv[]) {
  int number_of_lines = 10;
  char c;

  while(--argc > 0 && (*++argv)[0] == '-') {
    while((c = *++argv[0])) {
      switch(c) {
        case 'n':
          if(argc-1 > 0)
            number_of_lines = atoi(*(argv+1));
          break;
      }
    }
  }

  char *line_buffer[number_of_lines];

  if(tail(line_buffer, number_of_lines) < 0) {
    printf("ERROR: failed to allocate memory for a line.\n");
    return -1;
  }

  printf("Output:\n");
  print_lines(line_buffer, number_of_lines);

  return 0;
}

int tail(char *buffer[], int n) {
  int characters_read = 0;
  char *p, line[MAXLEN];

  while((characters_read = read_line(line, MAXLEN)) > 0) {
    if((p = malloc(sizeof(char)*characters_read)) == NULL) {
      return -1;
    }
    strcpy(p, line);
    buffer[lines_read++ % n] = p;
  }

  return 0;
}

int read_line(char *line, int max) {
  int c, chars_read = 0;

  while((c = getchar()) != EOF && c != '\n' &&  ++chars_read < max-1)
    *line++ = c;

  *line = '\0';

  return chars_read;
}

void print_lines(char *buffer[], int n) {
  for(int i=0; i < (lines_read > n ? n : lines_read); i++)
    printf("%s\n", buffer[lines_read > n ? lines_read++ % n : i]);
}


texts: Function to calculate "Persistence Rate" by group with a logical argument to determine whether to include overall persistence

texts:
The Function

"Persistence Rate" is also sometimes referred to as "retention rate". It is the number of ID's in a given term/period that are also found in the next term/period. (e.g., I have 10 customers in October but only 3 of those customers return in November. My persistence rate is then 30%.)

I have written a function to calculate persistence from a dataframe containing a list of ID's and the rank of the term/period (e.g., October is ranked 10 out of all the 12 months). The function uses tidyeval. It has all of the necessary arguments -- data, id, and rank. I also included a period argument so that the output is easily interpreted. (e.g., output "October" instead of 10). I also included a grouping argument (...) (e.g., persistence rates by gender). The rmax assignment is so I can filter out the last term, since you wouldn't be able to calculate the last terms persistence rate. All of this fits pretty neatly into one dplyr chain.

But I wanted to add an "overall" argument. The overall argument would be a logical argument, indicating whether or not to include the entire population's persistence rate (not considering the term or grouping variables).

Here is what I came up with:

  persist_sum <- function(df, id, period, rank, ..., overall = FALSE){

  rmax <- max(df[deparse(substitute(rank))])

  enq_period <- enquo(period)
  enq_id <- enquo(id)
  enq_rank <- enquo(rank)
  enq_group_var <- quos(...)

   out <- df %>%
          group_by(UQ(enq_id)) %>%
          arrange(UQ(enq_rank)) %>%
          mutate(nextrank = lead(UQ(enq_rank))) %>%
          group_by(UQS(enq_group_var), UQ(enq_period), UQ(enq_rank)) %>%
          summarize(persistence_rate=sum(nextrank == UQ(enq_rank) + 1, na.rm = TRUE)/n()) %>%
          filter(!! enq_rank != rmax) %>%
          select(- UQ(enq_rank))

   if(overall == TRUE){
    total <- df %>%
              group_by(UQ(enq_id)) %>%
              arrange(UQ(enq_rank)) %>%
              mutate(nextrank = lead(UQ(enq_rank))) %>%
              ungroup()%>%
              filter(UQ(enq_rank)!= rmax)%>%
              summarize(persistence_rate=sum(nextrank == (UQ(enq_rank) + 1), na.rm = TRUE)/n())%>%
              as.numeric()

    out <- out %>%
            mutate(overall = total)
     }

  return(out)
}

The Problem/Question

Any suggestions for how to improve this code would be welcome, but my main concern is that calculating the overall persistence rate using the if() statement uses a lot of code. I feel like I should be able to more efficiently incorporate the logical argument into my dplyr chain.

Any recommendations for reducing the amount of text in this code? Also looking for best practices when it comes to incorporating arguments into the code.

Practice Data

Here is the practice data that I have been using to test this function. It also works on the real data that it is intended for.

dataFrame <- data.frame(id = as.character(c(1, 2, 3, 4, 1, 2)),
                        period = c("A", "A", "A", "A", "B", "B"),
                        rank = c(1, 1, 1, 1, 2, 2),
                        group = c(1, 2, 1, 2, 1, 2),
                        stringsAsFactors = FALSE)


texts:
I'm implementing the closed form of Fibonacci numbers.
I figure using a custom data type I can do so without leaving Integer.
It isn't more efficient than the "standard" approach as I couldn't figure an efficient way to calculate the power of my custom number type.

But sticking to this algorithm I would be interested in best practices to write this.
In particular I'm uncertain about the use of Num for my FibNum and the use of fromJust.

module Fibo
    (
     fibo
    ) where

import Data.Maybe (fromJust)

-- use a data type similar to complex numbers.
-- The only irrational number are multiples of sqrt 5
-- which will cancel away in the closed form.
data FibNum = FibNum { int::Integer, sq5::Integer }
  deriving (Show)

instance Num FibNum where
  (+) (FibNum a1 b1) (FibNum a2 b2) = FibNum (a1+a2) (b1 + b2)
  (*) (FibNum a1 b1) (FibNum a2 b2) = FibNum intSide rootSide
    where intSide = a1*a2 + 5 * b1 * b2
          rootSide = a1*b2 + b1*a2
  negate (FibNum a b) = FibNum (negate a) (negate b)
  fromInteger n = FibNum (fromInteger n) 0
  -- no need for abs and sign for now
  abs _ = undefined
  signum _ = undefined

funit = FibNum 1 0
-- actual phi and psi are (1 + sqrt 5)/2 and (1 - sqrt 5)/2
-- I would prefer to avoid fractions so I divide at the end
fphi = FibNum 1 1
fpsi = FibNum 1 (negate 1)

-- was originally planning to calculate the binomial coefficients
-- but seeing that I just need n relatively simple multiplications
-- that seem like unnecessary complication
pow :: FibNum -> Integer -> FibNum
pow _ 0 = funit
pow x 1 = x
pow x n = x * pow x (n-1)

-- in the closed form the integer part is always 0
divR5 :: FibNum -> Maybe Integer
divR5 (FibNum 0 n) = Just n
divR5 _ = Nothing

fibo :: Integer -> Integer
fibo n = flip div p2 . fromJust $ divR5 nom
  where nom = pow fphi n - pow fpsi n
        p2 = 2^n

addendum
Thanks a lot for the useful comments.
If it's interesting I put my code in following repo https://github.com/bdcaf/haskell-fibonacci


texts:
This is my second jQuery script: a universal tooltip for my entire web page. It took me a couple of days to research and make it work.

Now, I need help from the experts to optimize my newbie code.

This is one of the ways I can show the tooltip:

My tooltip

jQuery:

$('.tooltip').hover(function(){
    var text = $(this).attr('data-tooltip');

    // get coordinates (top, left) of clicked element
    var offset = $(this).offset();

    // append tooltip to body, hide it, insert text
    // center the tooltip to the clicked element and display it 3 pixels above the clicked element
    $('

')
    .hide()
    .text(text)
    .appendTo('body')
    .css("left", offset.left - (($(".tooltipbox").outerWidth() - $(this).width()) / 2 )) // center the tooltip
    .css("top", offset.top - $(".tooltipbox").outerHeight() - 3)
    .fadeIn(200);
}, function() {
    // hover out the tooltip box
    $('.tooltipbox').remove();
});

Something simple that works ok. Any way to improve my second jQuery script?


texts:
I'm trying to learn some Haskell by working my way through the CodeAbbey problems. I really struggled to find a nice functional (but still efficient) way to solve problem #21: Array Counters.

The problem is, given a list of M numbers between 1 and N (an input parameter), to count the number of occurrences of each number. The question strongly suggests the imperative approach of using an array of counters and incrementing the counter at the relevant index.

Example:

Input:
10 3
3 2 1 2 3 1 1 1 1 3

Expected output:
5 2 3

My code:

count :: Int -> [Int] -> [Int]
count n = go (replicate n 0)
  where
    go cs []       = cs
    go cs (x : xs) = go (incList x cs) xs

incList :: Int -> [Int] -> [Int]
incList x cs = (take (x - 1) cs) ++ [cs!!(x - 1) + 1] ++ (drop x cs)

main :: IO ()
main = do line <- getLine
          let [m, n] = map (read :: String -> Int) $ words line
          line <- getLine
          let list = map (read :: String -> Int) $ words line
          putStrLn $ unwords $ map show $ count n list


texts: HackerRank Regex Challenge: Detect HTML Tags

texts:
Problem Statement

  In this problem you will use regular expressions to help you detect
  the various Tags used in an HTML document.

  Here are a few examples of tags:

  The "p" tag for paragraphs:

This is a paragraph

  It is also okay to have one or more spaces before or after the tag
  name:

This is also a paragraph

  Then, there is also something called a void or an empty tag such as:

  Some tags can also have attributes. For example, here we see the "a"
  tag which is used for adding links to a document.

[Google](http://www.google.com)

  In the above case, "a" is the tag and "href" is an attribute, the
  value of which is http://www.google.com. Ignore any attributes. Your
  task is to find out all the tags present in the given document.

  There are also tags such as this which haven't been split into an
  opening and closing tag (i.e, self-closing tags): '
'

  Input Format

  The first line will contain N, the number of lines in the fragment. A
  valid HTML document or fragment.Leading and trailing spaces and
  indentation will be removed from the HTML lines.

  Output Format

  A list of all the tags present in the document, in lexicographical
  order, with semi-colons ";" between them. If a tag occurs multiple
  times, you just need to list it out once.

  Sample Input

2

[Example Link](http://www.quackit.com/html/tutorial/html_links.cfm)

 class="more-info">[More Link Examples...](http://www.quackit.com/html/examples/html_links_examples.cfm)

  Sample Output

a;div;p

I have used TreeSet to sort the tags lexicographically:

public class Detect_HTML_Tags {

    public static void main(String[] args) throws NumberFormatException, IOException {

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int N=Integer.parseInt(br.readLine().trim());
        String s="";

        for(int i=0;i<N;i++)
        {
            s+=br.readLine().trim();

        }
        TreeSet<String> tree=count_html_tags(s);
        int i=0;
        String s1="";
        for(String t:tree){
            s1=t;
            if(i==tree.size()-1)
                break;
            System.out.print(t+";");
            i++;
        }
        System.out.print(s1);
    }

    private static TreeSet<String> count_html_tags(String s) {
        String pat="\\s*(?:<([a-z][a-z0-9]*)|([\\[]))\\s*";
        Pattern p=Pattern.compile(pat);
        Matcher m=p.matcher(s);
        TreeSet<String> set=new TreeSet<>();
        while(m.find())
        {
            String tag=m.group(0).trim();
            //System.out.println(tag);
            if(tag.equals("["))
                set.add("a");
            else
                set.add(m.group(1));

        }
        return set;

    }
}

My code passes all the test cases. How can this solution be improved? Is the regex efficient enough or can it be improved further?


texts: Small method for saving student attendance

texts:
var studentRepo = new StudentRepository();
int gradeParaleloId = Convert.ToInt32(cmbGradeParalelo.SelectedValue);
var students = studentRepo.FindAllStudentsFromGradeParalelo(gradeParaleloId);

int year = DateTime.Now.Year;
int month = Convert.ToInt32(cmbMes.SelectedIndex) + 1;
AttendanceRepository attendanceRepo = new AttendanceRepository();

for (int i = 0; i < students.Count; i++)
{
    for (int j = 1; j < dataGridView1.Columns.Count; j++)
    {
        DateTime date = new DateTime(year, month, j);

        var student = students[i];
        var attendance = attendanceRepo.FindAttendance(student.StudentId, date);

        if (attendance == null)
        {
            attendance = new Data.Repositories.Attendance();
            attendanceRepo.Add(attendance);
        }

        attendance.StudentId = student.StudentId;
        attendance.DateOfAttendance = date;
        attendance.Attended = dataGridView1[j, i].Value.ToString();
    }
}

attendanceRepo.SaveChanges();

My main thorn in the side is that for each day in the month, I have to query the database, and see if a record already exists in the DB for that day and student.

The upside is that I'm putting each attendance in the datacontext and only pushing the save at the very end as a transaction of sorts.

So I'm not inserting on every day for every student. Imagine for a class of 40 students. That's an easy \$40 * 30 = 1200\$ queries on the spot.

Is there some way for me to streamline this? I'm more concerned about this line:

var attendance = attendanceRepo.FindAttendance(student.StudentId, date);


texts: Regular Expressions - finding two or more vowels with a consonant before and after it, includes overlapping

texts:
Is there a way to make my code more compact or efficient?

Testcase example 1 : rabcdeefgyYhFjkIoomnpOeorteeeeet
output:
ee
Ioo
Oeo
eeeee

Testcase example 2 : baabooteen
output:
aa
oo
ee

import re
def find_two_or_more_vowels(string: str):
    match_obj = list(re.finditer(r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE))
    if len(list(match_obj)) != 0:
        for match in match_obj:
            print(match.group())
    else:
        print(-1)

find_two_or_more_vowels(input())


texts: CROSS JOIN solution for records "missing" from a link table

texts:
Use case: We have a simple two tables plus a link table setup using some modern RDBMS.

For example:

Hospital table (id, name, ...)

Physician table (id, name, ...)

Visiting_Privilege table (hospital_id, physician_id, ...)

Our goal is to find records that are "missing" (absent) from the link table.

Using our example: List physicians and hospitals where they are not authorized to see patients.

The proposed solution: Create a full Cartesian Product between the two main tables,  JOIN it with the link table, filter records with either of the IDs as NULL.

SELECT p.name, h.name
FROM Physicians p
CROSS JOIN Hospitals h
LEFT OUTER JOIN Visiting_Privilege v ON p.id = v.physician_id AND h.id = v.hospital_id
WHERE v.physician_id IS NULL OR v.hospital_id IS NULL;

We assume that tables are properly indexed and the SQL engine provides reasonable query optimization.

Would it be a right way to attack the problem?
Is there a better solution that avoids the cost of a full Cartesian Product?


texts: function to check if word matches search word

texts:
I have the following which works but was wondering if there's a better way. Better meaning more efficient and or more compact.
The function checks a trie to see if the word is in the trie.
typedef struct nodeWords
{
    char * word;
    int    index;
    struct nodeWords *left;
    struct nodeWords *right;
} nodeWords;

nodeWords ** nodeArray;

/* nodeArray is a pointer to an array of pointers. nodeArray[nodeIdx] is
   a pointer to the middle nodeWords strut where word comes from a sorted
   list. Basic divide and conquer routine. */

bool check(const char *word)
{
    int nodeIdx = hash(word);
    if (nodeIdx < 0)return false;

    nodeWords * searchNode;
    searchNode = nodeArray[nodeIdx];  //nodeArray is global
    bool whileFlag = true, returnFlag = false;

    do
    {
        if (strcmp(word,searchNode->word) == 0 )
        {
            whileFlag = false;
            returnFlag = true;
        }
        else if (strcmp(word,searchNode->word) < 0 )
        {
            if(searchNode->left == NULL)
            {
                whileFlag = false;
            }else{
                searchNode = searchNode->left;
            }
        }else{
            if(searchNode->right == NULL)
            {
                whileFlag = false;
            }else{
                searchNode = searchNode->right;
            }
        }
    }while (whileFlag);

    return returnFlag;
}

for instance, we could rewrite the function this way:
bool check(const char *word)
{
    int nodeIdx = hash(word);
    if (nodeIdx < 0)return false;

    nodeWords * searchNode;
    searchNode = nodeArray[nodeIdx];
    bool returnFlag = false;

    do
    {
        if (strcmp(word,searchNode->word) == 0 )returnFlag = true;
        else if (strcmp(word,searchNode->word) < 0 && searchNode->left  != NULL) searchNode = searchNode->left;
        else if (strcmp(word,searchNode->word) > 0 && searchNode->right != NULL) searchNode = searchNode->right;
    }while (searchNode->left != NULL || searchNode->right != NULL || strcmp(word,searchNode->word) == 0);

    return returnFlag;
}

I notice that the second function is actually not going to work as it's not quite the same as the first but we could change the while loop condition


texts:
I would like to give it a try and ask about my codes on here from now on to see if there are improvement for'em

this code is supposed to combine two sql tables into one.

SELECT * FROM (SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5) t1 JOIN (SELECT username, firstname, lastname, avatar FROM users) t2 ON t1.submitter = t2.username

I was thinking that there might be a better way doing it using union or anything faster, if I'm even right about what I'm saying.


texts: Finding the predominant number in an array

texts:
My program has to read an array and say whether there is a predominant number or not in the array. A predominant number is the one with frequency bigger than number of elements of the array divided by 2. I did it, but the site I am learning on is dissatisfied with the program's speed so I do not have the maximum score. Not for that score I am asking this.

int main()
{
    int number, i, j, currentElAp = 1, maxAp = 0, maxApNumber = -1, remainingElements;
    scanf("%d", &number);
    int ar[number];
    for(i = 0; i < number; i++)
        scanf("%d", &ar[i]);

    for(i = 0; i < number / 2; i++){
        remainingElements = number - i - 1;
        if(ar[i] != maxApNumber){
            for(j = i + 1; j < number && (remainingElements + currentElAp > number / 2); j++){
                if(ar[i] == ar[j])
                    currentElAp++;
            }
        }
        if(currentElAp > maxAp){
            maxAp = currentElAp;
            maxApNumber = ar[i];
        }
        currentElAp = 1;
    }
    if(maxAp > number / 2)
        printf("Yes %d %d", maxApNumber, maxAp);
    else
        printf("No");
    return 0;
}

Restrictions:

1 ≤ number ≤ 100.000
Each element of the array is smaller than 1.000.000.000

How could my code be improved to be faster or how would you write a faster solution?


texts:
I'm working on a tile-based game, and am looking to improve the efficiency of my code to slightly improve framerate. I call this method on every tile, every frame, so it is very performance critical. What optimizations can be made?

public bool OnScreen(Vector2 point)
{
    Rectangle rect = this.Rectangle;
    return ((((rect.X <= point.X) && (point.X < (rect.X + rect.Width))) && (rect.Y <= point.Y)) && (point.Y < (rect.Y + rect.Height)));
}

public bool OnScreen(Vector2 topLeft, Vector2 size)
{
    // Check if each corner is inside of the camera rectangle
    return (
        OnScreen(topLeft) // Top-left
        || OnScreen(topLeft + new Vector2(0, size.Y)) // Bottom-left
        || OnScreen(topLeft + new Vector2(size.X, 0)) // Top-right
        || OnScreen(topLeft + size) // Bottom-right
    );
}

I am doing this so that I can pool the objects that actually render my tiles, since only a maximum of about 800 can be on screen at any one time. These methods are called as so:

// Assign renderers to any tiles in range of the camera.
foreach (var tile in _tiles)
{
    if (tile.IsInRange(camera))
    {
        if (tile.Renderer == null)
        {
            tile.Renderer = _pool.Get();
        }
    }
    else
    {
        tile.Renderer = null;
    }
}


texts: Insert JSON data into rendered template after AJAX call

texts:
I have an already rendered template and I want to update it with some JSON data I obtain via AJAX.

The template as it is before rendering looks like this (using jinja2 template engine):

     Time
     Destination
     Bus number

{% for bus in buses %}

     bus[0]
     bus[1]
     bus[2]

{% endfor %}

And I want to send AJAX requests to update the buses var with new values. The way I do it is deleting the tbody content when new data arrives, and rendering everything again with the new data.

function executeQuery() {
    $.ajax({
        method: 'get',
        url: '/data/json',
        data: { bus_id : {{ bus_id }} },
        success: function(data) {
            data = JSON.parse(data);
            $('#table-body').html('');
            for (i in data){
                $('#table-body').append(
                    "
" +
                    "" + data[i][0] + "	" +
                    "" + data[i][1] + "	" +
                    "" + data[i][2] + "	" +
                    "
");
                };
        }
      });

How can I improve this code? (FWIW I'm using Flask)


texts: Hackerrank Day 8: Dictionaries and Maps solution in C++

texts:
This is a solution for the Day 8 hackerrank.com challenge. The basic idea of the challenge is to create a mapping of names to phone numbers based on the the given input, and later look up the phone numbers for certain names. If the entry exists, print it and its number. If it doesn't, print out "Not found".

Here's my solution in C++:

#include<iostream>
#include<map>
using namespace std;
int main()
{
    int i, n;
    cin>>n;
    string name, number, key;
    map<string, string> phone_dir;
    for(i=0; i<n; i++)
    {
        cin>>name>>number;
        phone_dir.insert(pair <string, string> (name, number));
    }
    while(cin>>key)
    {
        if (phone_dir.find(key) != phone_dir.end())
        {
             cout<<key<<"="<<phone_dir.find(key)->second<< endl;
        }
        else cout<< "Not found"<<endl;
    }

    return 0;

}

Is there a more efficient solution in C++ for this problem?


texts:
I'm currently trying to display a list of movies with this pill-like elements. The code below works but I guess there is a better way or a way to use elements from the twitter Bootstrap. It also bothers me that the date in the brackets isn't centered with the heading.

Please give me feedback how you like my code. I'm always open for any improvements or ideas :)

.pillLink > h {
 display: inline-block;
}

.pillLink {
 display: inline-block;
 padding-left: 20px;
}

.pill > #cover {
 height: 100px;
 outline: 2px solid white;
}

.pill {

 padding: 7px;
 margin: 10px;
 width: 500px;
 background-color: silver;
 -webkit-border-radius: 7px!important;
 -moz-border-radius: 7px!important;
 border-radius: 7px!important;
 border: 1px solid grey
}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="pills_style.css">

Interstellar

   (2014)


texts:
I've been working with web services recently, and I keep copying the same stuff to set up Unity for dependency injection, so I thought I'd extract the common stuff into a library. Here's the main class:

public static class UnityConfig
{
    public static IUnityContainer Register(System.Web.Http.HttpConfiguration config, params Action<IUnityContainer>[] registrations)
    {
        // Defensive programming
        if (config == null) throw new ArgumentNullException(nameof(config));

        // Set up Unity dependency injection.
        var container = new UnityContainer();
        foreach (var register in registrations) register(container);

        // Switch some of the plumbing to our new Unity setup.
        System.Web.Mvc.DependencyResolver.SetResolver(new Microsoft.Practices.Unity.Mvc.UnityDependencyResolver(container));
        config.DependencyResolver = new Microsoft.Practices.Unity.WebApi.UnityDependencyResolver(container);
        Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

        // Grease Web API's inner workings with Unity.
        var formatters = config.Formatters.ToList();
        config.Formatters.Clear();
        foreach (var formatter in formatters) config.Formatters.Add(new UnityFormatter(formatter, container));
        config.Services.Insert(typeof(System.Web.Http.ModelBinding.ModelBinderProvider), 0, new UnityModelBinderProvider());

        // Send back the container in case of unforeseen needs.
        return container;
    }
}

The UnityFormatter and UnityModelBinderProvider classes are custom so it is fine to assume they work.

My first concern is the plumbing section. Here we integrate Unity into MVC, Web API, and Microsoft's service locator. The MVC and service locator parts, in particular, add dependencies to my library and there are no guarantee consumers would need the functionality. Should I try to avoid the potentially unused dependencies? Or is it not worth the worry?
My second concern is returning the container. I feel like I'd be denying a potential use case by not returning the container and making it a void function (though void is typical in similar configs). On the other hand, I'm exposing another implementation detail and the consumer should have plenty of room to set things up with the registrations parameter
My third concern is using params. Is that just an overkill? One should suffice for all the situations I'm familiar with but does that mean I should be restrictive now?

The bullet points highlight my main concerns but please feel free to comment on other things you think could be improved apart from (the lacking) documentation.


texts: Is the usage of JSONObject and JSONArray is correct, as it take lot of time to render UI

texts:
I am working on struts 2 based web application, where an Action Class render 7000+ records in UI. The query which fetches the record is already been optimized by the DB developer, but instead it took around 7+ seconds to load UI it also freeze the UI for a moment,on deep inspection I have found there is something wrong with java code itself, but for more deep analysis, I would like my code to be review by community here.

In Action class, the fetched data collected and one by one putting into the JSONObject later on it then putting into in the JSONArray, it seems, such kind of implementation took time.

public String execute() throws Exception {
        logger.debug("---------Enter In HoldingMembersDataAction---------");

        JSONObject obj = new JSONObject();
        JSONObject obj1 = null;
        ArrayList<JSONArray> extlist =  new ArrayList<JSONArray>();
        JSONArray arr = new JSONArray(extlist);
        /* Field is use to store the session id */
        int total = 0;
        /* List is use to store the account details object */
        List<Account> accountList = null;

        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            String holdingId = request.getParameter("holdingId");

            CreditTrade creditTrade = new CreditTradeDAO();
            logger.debug("Sort In Add Member" + getSort());
            PagingInfo pageInfo= new PagingInfo(getStart(), getLimit(), getSort(), getDir());
            pageInfo.setSearchText(getSearchText());

        /*  accountList = creditTrade.getAccountMemberList(holdingId,
                    getCoreProduct(), getSearchText().trim(), getMemberType(),
                    getMemberCountry(), getSort(), getDir());*/

            accountList = creditTrade.getAccountMembersList(holdingId,
                    getCoreProduct(),getMemberType(),
                    getMemberCountry(),pageInfo);
            /*
             * Iterate account list and prepare JSONObject
             */
            for (Account ac : accountList) {
                String memberType=ac.getMemberType();
                memberType=memberType.replaceAll(",", ", ");
                obj1 = new JSONObject();
                obj1.put("accountId", ac.getId());
                obj1.put("externalReferenceID", ac.getExternalReferenceId());
                obj1.put("name", ac.getName());
                obj1.put("countryName", ac.getVisitingCountryName());
                obj1.put("membercategory", memberType);
                obj1.put("membershipId", ac.getMemberID());
                obj1.put("isPartOfHolding", ac.getIsPartOfHolding());
                obj1.put("isPartOfSameHolding", ac.getIsPartOfSameHolding());
                arr.put(obj1);

            }
            //obj.put("totalCount", total);
            //obj.put("data", arr);
            /* Write JSONData into output stream */
            writeJSONData(arr);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

I wanna ask if such usage of JSONObject and JSONArray is correct, or it can be furhter optimized to reduce time.

Network Activity Log:

RENDER TIME:

TimeAnazer timeAna = new TimeAnazer();
            timeAna.startMillSec();
            accountList = creditTrade.getAccountMemberList(holdingId,
                    getCoreProduct(), getSearchText().trim(), getMemberType(),
                    getMemberCountry(), getSort(), getDir());
            timeAna.endMillSec();
            timeAna.showTimeTaken("HoldingMembersDataAction::getAccountMemberList");
            timeAna.resetTime();


texts: Encrypting messages to be sent over a socket

texts:
I recognize the importance of properly implement cryptographic functions. Since this is my first time using them I really wanted a second opinion on my method. Therefore, I was wondering if my method of sign-then-encrypt as implemented would be a valid method of safely achieving those results.

def gen_keys(size):
    print('Generating new keys...')
    pubkey, privkey = rsa.newkeys(size, poolsize=8)
    print('Keys generated!')
    return pubkey, privkey

def encrypt_full_message(message, pubkey, privkey):
    parts = textwrap.wrap(message, 245)
    message_to_send = b''
    for part in parts:
        part = part.encode('utf-8')
        signature = rsa.sign(part, privkey, 'SHA-256')
        encrypted_message = rsa.encrypt(part, pubkey)
        message_to_send += encrypted_message
        message_to_send += signature
    return message_to_send

def decrypt_full_message(message, privkey, pubkey):
    parts = [message[i:i+256] for i in range(0, len(message), 256)]
    messages = parts[0::2]
    signatures = parts[1::2]
    fmessage = b''
    for signature, message in zip(signatures, messages):
        message = rsa.decrypt(message, privkey)
        if rsa.verify(message, signature, pubkey):
            fmessage += message
        else:
            print('Message has been tampered with.')
    return fmessage


texts: Generating rooted labelled subtrees of a JS object

texts:
I recently had cause to write some code which would take an object like
const obj = {
      a: 1,
      c: {
            d: 1,
            e: 1
      }
};

Which we regard as a rooted labelled tree, I then want the rooted labelled subtrees, e.g. in this example
{ c: { e: 1, d: 1 }, a: 1 }
{ c: { e: 1, d: 1 } }
{ c: { e: 1 }, a: 1 }
{ c: { e: 1 } }
{ c: { d: 1 }, a: 1 }
{ c: { d: 1 } }
{ c: {}, a: 1 }
{ c: {} }
{ a: 1 }
{}

It was important to me that the function be a generator function, and that I avoid making any deep copies of the initial object.
So I wrote the following
function* generateRootedSubtreesOfObject(tree) {
      const children = Object.keys(tree);

      if (children.length === 0) {
            yield tree;
            return;
      }

      const firstChild = children[0];
      const firstSubtree = tree[firstChild];

      const isLeaf =
            typeof firstSubtree !== "object" || Array.isArray(firstSubtree);

      delete tree[firstChild];

      for (const remainingSubtree of generateRootedSubtreesOfObject(tree)) {
            const elSubtrees = isLeaf
                  ? [firstSubtree]
                  : generateRootedSubtreesOfObject(firstSubtree);

            for (const firstChildSubtree of elSubtrees) {
                  remainingSubtree[firstChild] = firstChildSubtree;
                  yield remainingSubtree;
                  delete remainingSubtree[firstChild];
            }
            yield remainingSubtree;
      }
      tree[firstChild] = firstSubtree;
}

Which works as desired, but is extremely cryptic in my opinion. The idea is simple enough, go to the first child of the root, find the rooted subtrees with this as the root, and combine this in all the possible ways with the rooted subtrees once you detach this child. But the current implementation I think is too subtle.
How could this be improved?
Re error handling, please assume (it is true in my case) that the caller of this function will know it is appropriate to call.


texts:
CodeWars 6 Kyu: Reverse or rotate?

I wrote my Javascript "hello world" on Thursday, so I'm definitely a JS beginner. I do have some experience in Python though, so I'm not a complete novice to programming in general.

Question

  The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz).

  If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.

  If

  sz is <= 0 or if str is empty return ""
  sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "".

  Examples:

revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> ""
revrot("563000655734469485", 4) --> "0365065073456944"

Solution

function revrot(str, sz)
{
   ln = str.length;
   if(sz < 1 || !str || sz > ln) return "";

   const test = s => Array.prototype.reduce.call(s, (acc, val) => acc + Number(val) ** 3, 0) % 2 === 0;
   const reverse = s => s.split("").reverse().join("");
   const rotate = s => s.slice(1) + s.slice(0, 1);

   let arr = [];
   for(let i = 0; i < ln; i += sz) arr.push(i+sz <= ln ? str.slice(i, i+sz) : "")
   return arr.map(x => test(x) ? reverse(x) : rotate(x)).join("");
}


texts: LeetCode 552: Student Attendance Record II

texts:
I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!
Problem

Given a positive integer n, return the number of all possible
attendance records with length n, which will be regarded as
rewardable. The answer may be very large, return it after mod 109 + 7.
A student attendance record is a string that only contains the
following three characters:

'A' : Absent.
'L' : Late.
'P' : Present.

A record is regarded as rewardable if it doesn't contain more than one
'A' (absent) or more than two continuous 'L' (late).
Example 1:

Input: n = 2
Output: 8

Explanation:
There are 8 records with length 2 will be regarded as rewardable:

"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"

Only "AA" won't be regarded as rewardable owing to more than one absent times.

Note: The value of n won't exceed 100,000.

Accepted Code
class Solution {
public:
    static int checkRecord(int edges) {
        if (edges == 0) {
            return 1;
        }

        // possible candidates
        uint32_t adj_matrix[MATRIX_WIDTH_SQUARED] = {
            1, 1, 1, 0, 0, 0,
            1, 0, 0, 0, 0, 0,
            0, 1, 0, 0, 0, 0,
            1, 1, 1, 1, 1, 1,
            0, 0, 0, 1, 0, 0,
            0, 0, 0, 0, 1, 0,
        };

        uint32_t a[MATRIX_WIDTH_SQUARED];
        uint32_t b[MATRIX_WIDTH_SQUARED];
        uint32_t* accumulated = a;
        uint32_t* temp = b;
        uint32_t* adj_matrix_pointer = adj_matrix;

        std::memset(a, 0, sizeof(a));

        for (unsigned int node_x = 0; node_x < MATRIX_WIDTH_SQUARED; node_x += MATRIX_WIDTH + 1) {
            a[node_x] = 1;
        }

        // Square
        while (edges > 1) {
            if (edges & 1) {
                matrix_multiply(accumulated, adj_matrix_pointer, temp);
                std::swap(temp, accumulated);
            }

            matrix_multiply(adj_matrix_pointer, adj_matrix_pointer, temp);
            std::swap(temp, adj_matrix_pointer);
            edges >>= 1;
        }

        matrix_multiply(adj_matrix_pointer, accumulated, temp);
        uint64_t first_col_sum = 0;

        // Sum up
        for (int node_y = 0; node_y < MATRIX_WIDTH_SQUARED; node_y += MATRIX_WIDTH) {
            first_col_sum += temp[node_y];
        }

        return (uint32_t) (first_col_sum % MODE);
    }

private:
    static constexpr int MATRIX_WIDTH = 6;
    static constexpr int MATRIX_WIDTH_SQUARED = MATRIX_WIDTH * MATRIX_WIDTH;
    static constexpr uint64_t MODE = 1000000007UL;

    static void matrix_multiply(uint32_t* a, uint32_t* b, uint32_t* c) {
        for (unsigned int node_y = 0; node_y < MATRIX_WIDTH; node_y++) {
            for (unsigned int node_x = 0; node_x < MATRIX_WIDTH; node_x++) {
                uint64_t matrix_multi = 0;

                for (unsigned int k = 0; k < MATRIX_WIDTH; k++) {
                    matrix_multi += (uint64_t) (a[node_y * MATRIX_WIDTH + k]) * (uint64_t) (b[k * MATRIX_WIDTH + node_x]);
                    matrix_multi %= MODE;
                }

                c[node_y * MATRIX_WIDTH + node_x] = matrix_multi;
            }
        }
    }
};

Reference
In LeetCode's answer template, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss


texts: Shift part of char array to the same array after encountering a delimiter

texts:
I have a char tempBuffer which stores say my!string!hello!. After every ! is encountered that token is moved to a char codeBuffer and the rest of the characters are shifted to the begiinging of tempBuffer. So after my is moved to codeBuffer, tempBuffer contains string!hello!.

I have currently implemented it as follows:

while (tempBuffer[0] != '\0') {
    /* Read input contents into tempBuffer */
    bytesReadTotal = read(fd, tempBuffer, BUFFER_SIZE);

    /* Copy contents of tempBuffer into codeBuffer till delimiter is found*/
    for (startOfBlock = 0; startOfBlock < strlen(tempBuffer); startOfBlock++){
        if (tempBuffer[startOfBlock] != opt.separator[0])
            codeBuffer[startOfBlock] = tempBuffer[startOfBlock];
        else
            break;
    }

    if (tempBuffer[startOfBlock] == '\0')
        break;

    /* Copy contents of tempBuffer into temp2Buffer from new block position*/
    for (int i = 0; i < strlen((char*) tempBuffer); i++) {
        temp2Buffer[i] = tempBuffer[startOfBlock + 1];
        startOfBlock++;
    }

    /* Copy contents of temp2Buffer to tempBuffer */
    for (startOfTB = 0; startOfTB < strlen((char*) temp2Buffer); startOfTB++) {
        tempBuffer[startOfTB] = temp2Buffer[startOfTB];
    }

    /* Reset all contents of tempBuffer after last copied position
       to '\0' to avoid overlap */
    tempBuffer[startOfTB] = '\0';
}

I would like to avoid multiple copy operations.How can I improve this code?


texts:
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?

Example:

  str = "happy" substr = "app"

  index = 1

My code:

public static int subStringIndex(String str, String substr) {
    int substrlen = substr.length();
    int strlen = str.length();
    int j = 0;
    int index = -1;

    if (substrlen < 1) {
        return index;
    }
    else {
        for (int i = 0; i < strlen; i++) {              // iterate through main string
            if (str.charAt(i) == substr.charAt(j)) {    // check substring
                index = i - j;                              // remember index
                j++;                                    // iterate
                if (j == substrlen) {                   // when to stop
                    return index;
                }
            }
            else {
                j = 0;
                index = -1;
            }
        }
    }
    return index;
}


texts:
Breadcrumbs should look like this:
Home > Mobiles & Tablets > Mobile Phones > Phone Super Duper

every product belongs only to one category. e.g Phone Super Duper can be found only under Mobile Phones.
This is just a sketch but i want to know your opinion if the direction is ok or i should change the strategy.

ANY critique or suggestions are welcome
 JSP

    <c:forEach items="${breadcrumbs}" var="breadcrumb" varStatus="status">

&gt;

<c:choose>
                <c:when test="${breadcrumb.url eq '#'}">
                    <a href="#" onclick="return false;"
                        <c:if test="${status.last}">class="last"</c:if>>${breadcrumb.name}
                </c:when>

                <c:otherwise>
                    <a href="${baseURL2}${breadcrumb.url}"
                        <c:if test="${status.last}">class="last"</c:if>>${breadcrumb.name}
                </c:otherwise>

            </c:choose>

    </c:forEach>

HomePageController

@RequestMapping("/")
    public String showHomePage(HttpServletRequest request, Model model) {
        model.addAttribute("breadcrumbs", contentPageBreadcrumbBuilder.getBreadcrumbs(request.getServletPath()));
        return "welcome";
    }

ProductPageController

@RequestMapping(value = "/product")
    public String getProductById(@RequestParam("id") int productId, Model model) {
        Product product = new Product();
        Category  category = new Category();
        category.setCategoryName("someCategory");
        product.setProductId(1);
        product.setProductName("someProductName");
        product.setCategory(category);
        model.addAttribute("breadcrumbs",  productBreadcrumbBuilder.getBreadcrumbs(product));
        return "product";
    }

ProductBreadcrumbsBuilder

@Component
public class ProductBreadcrumbBuilder {
    public List<Breadcrumb> getBreadcrumbs(final Product productModel) throws IllegalArgumentException {
            final List<Breadcrumb> breadcrumbs = new ArrayList<>();
            breadcrumbs.add(getProductBreadcrumb(productModel));
            Breadcrumb category = getCategoryBreadcrumb(productModel.getCategory());
            breadcrumbs.add(category);
            Collections.reverse(breadcrumbs);
            return breadcrumbs;
        }

        protected Breadcrumb getProductBreadcrumb(final Product product) {
            final String productUrl = "/products/" + product.getProductId();
            return new Breadcrumb(productUrl, product.getProductName());
        }

        protected Breadcrumb getCategoryBreadcrumb(final Category category) {
            final String categoryUrl = "/categories/" + category.getId();
            return new Breadcrumb(categoryUrl, category.getCategoryName());
        }

Breadcrumb

public class Breadcrumb {

    private String url;
    private String name;

    public Breadcrumb(final String url, final String name)
    {
        this.url = url;
        this.name = name;
    }


texts:
Today I had an interview where I was asked to solve "Given an binary tree, convert it to binary search tree in minimum time, space complexity".

I wrote this code, but got the feedback that complexity could be improved without using sort and without using external storage.

How to do it?

##code goes below##:

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def inorder(root,arr):
    if root is None:
        return
    inorder(root.left, arr)
    arr.append(root.data)
    inorder(root.right, arr)

def binary_to_bst(root, arr):
    if root is None:
        return
    binary_to_bst(root.left, arr)
    root.data = arr.pop(0)
    binary_to_bst(root.right, arr)

root = Node(4)
root.left = Node(2)
root.right = Node(1)
root.left.left = Node(5)
root.left.right  = Node(7)
root.right.left = Node(12)
arr = []
inorder(root,arr)
arr.sort()
binary_to_bst(root, arr)


texts: Adding labels and fields to a nested JSON

texts:
I have a dataframe:

Name_ID | URL                    | Count | Rating
------------------------------------------------
ABC     | www.example.com/ABC    | 10    | 5
123     | www.example.com/123    | 9     | 4
XYZ     | www.example.com/XYZ    | 5     | 2
ABC111  | www.example.com/ABC111 | 5     | 2
ABC121  | www.example.com/ABC121 | 5     | 2
222     | www.example.com/222    | 5     | 3
abc222  | www.example.com/abc222 | 4     | 2
ABCaaa  | www.example.com/ABCaaa | 4     | 2

I am trying to create a JSON:

{"name": "sampledata",
 "children": [
{
    "name":9,
    "children":[
        {"name":4,
        "children":[
            {"name":"123","size":100}
                    ]
        }
                ]
},
{
    "name":10,
    "children":[
        {"name":5,
        "children":[
            {"name":"ABC","size":100}
                    ]
        }
                ]
},
{
    "name":4,
    "children":[
        {"name":2,
        "children":[
            {"name":"abc222","size":50},
            {"name":"ABCaaa","size":50}
                    ]
        }
                ]
},
{
    "name":5,
    "children":[
        {"name":2,
        "children":[
            {"name":"ABC","size":16},
            {"name":"ABC111","size":16},
            {"name":"ABC121","size":16}
                    ]
        },
        {"name":3,
        "children":[
            {"name":"222","size":50}
                    ]
        }
                ]
}
]
}

In order to do that:

I am trying to add labels such as "name" and "children" to the JSON while creating it.

I tried something like results = [{"name": i, "children": j} for i,j in results.items()]. But it won't label it properly, I believe.
Add another field with the label "size" which I am planning to calculate based on the formula
(Rating*Count*10000)/number_of_children_to_the_immediate_parent.

import pandas as pd
from collections import defaultdict
import json

data =[('ABC', 'www.example.com/ABC', 10   , 5), ('123', 'www.example.com/123', 9, 4), ('XYZ', 'www.example.com/XYZ', 5, 2), ('ABC111', 'www.example.com/ABC111', 5, 2), ('ABC121', 'www.example.com/ABC121', 5, 2), ('222', 'www.example.com/222', 5, 3), ('abc222', 'www.example.com/abc222', 4, 2), ('ABCaaa', 'www.example.com/ABCaaa', 4, 2)]

df = pd.DataFrame(data, columns=['Name', 'URL', 'Count', 'Rating'])

gp = df.groupby(['Count'])

dict_json = {"name": "flare"}
children = []

for name, group in gp:
    temp = {}
    temp["name"] = name
    temp["children"] = []

    rgp = group.groupby(['Rating'])
    for n, g in rgp:
        temp2 = {}
        temp2["name"] = n
        temp2["children"] = g.reset_index().T.to_dict().values()
        for t in temp2["children"]:
            t["size"] = (t["Rating"] * t["Count"] * 10000) / len(temp2["children"])
            t["name"] = t["Name"]
            del t["Count"]
            del t["Rating"]
            del t["URL"]
            del t["Name"]
            del t["index"]
        temp["children"].append(temp2)
    children.append(temp)

dict_json["children"] = children

print json.dumps(dict_json, indent=4)

Though the code does print what I need, I am looking for a more efficient and cleaner way to do the same, mainly because the actual dataset might be even more nested and complicated.


texts: How to hide implementation of JDBC while processing large query in client's code?

texts:
I have client's methods that processes a large SQL query. I wouldn't like to do that through getting whole query result to memory, but process it in batches. It entails with exposing JDBC API to client's code.  I think that this code could be refactored much better.

    //client's method
    m_jdbcManager = JdbcManagerUtil.getInstance();
    m_tupleManager = DbTupleManager.getInstance();
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = m_jdbcManager.getConnection();
        connection.setAutoCommit(false);
        statement = connection
                .prepareStatement(Statements.SELECT_RIGHT_TUPLES);
        statement.setInt(1, id);
        statement.setFetchSize(JdbcManagerUtil.FETCH_SIZE);
        resultSet = statement.executeQuery();
        while (resultSet.next()) {
            Tuple tuple = (Tuple) m_tupleManager
                    .readObject(resultSet);
            //process tuple, invokes methods from client class
        }
        connection.setAutoCommit(true);
        JdbcManagerUtil.closeEverything(connection, statement, resultSet);
    } catch (<exceptions>) {
    }

I tried to expose method that returns ResultSet, but after processing, there must be released resources Connection, PreparedStatement and ResultSet.
JDBC 4 and PostreSQL database.


texts: Counting the occurrences of a string in each file

texts:
I am trying to find a phrase or a string in file and count the number of occurrences of that string:

 private static HashMap<String, Integer> bruteForceSearch(
      String stringToLookFor, List<File> list) throws IOException {

    HashMap<String, Integer> result = new HashMap<String, Integer>();
    for (File file : list) {
      String fileName = file.getName();
      // System.out.println(fileName);
      FileInputStream fstream = new FileInputStream(file);
      BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
      String readLine = "";
      int count = 0;
      while ((readLine = in.readLine()) != null) {
        String[] words = readLine.split(" ");
        for (String text : words) {
          if (text.equalsIgnoreCase(stringToLookFor)) {
            count++;
          }
        }
      }
      if (count != 0) {
        result.put(fileName, count);
      }

      in.close();
    }

    return result;

  }

Are there any improvements to do in my code? Please let me know.


texts:
def draw_board(board):
    display_board = ''

    for number in list(range(len(board))):
        if (number + 1) % 3 == 0:
            if number < 6:
                display_board += '  ' + str(board[number]) + '  \n—————————————————\n'
            else:
                display_board += '  ' + str(board[number]) + '  '
        else:
            display_board += '  ' + str(board[number]) + '  |'

    return display_board

def check_win(board, letter):
    if all(item == letter for item in board[:3]):
        return True
    elif all(item == letter for item in board[3:6]):
        return True
    elif all(item == letter for item in board[6:9]):
        return True
    elif all(item == letter for item in board[::3]):
        return True
    elif all(item == letter for item in board[1::3]):
        return True
    elif all(item == letter for item in board[2::3]):
        return True
    elif all(item == letter for item in board[::4]):
        return True
    elif all(item == letter for item in board[2:8:2]):
        return True

x = input('Who is X?  > ')
o = input('Who is O?  > ')

squares = {
    'nw': 0, 'n': 1, 'ne': 2,
    'w': 3, 'c': 4, 'e': 5,
    'sw': 6, 's': 7, 'se': 8
}

directions = list(squares.keys())

tic_tac_toe_board = [
    '.', '.', '.',
    '.', '.', '.',
    '.', '.', '.'
]

valid_turns = 0
x_turn = True
print(draw_board(tic_tac_toe_board) + '\n(Xs first) ', end='')

while valid_turns < 9:
    square = input('Exactly type in the following available directions: ' + ', '.join(directions) + '  > ')

    if square.lower() in directions:
        directions.remove(square.lower())

        if x_turn:
            tic_tac_toe_board[squares[square.lower()]] = 'X'
            x_turn = False
        else:
            tic_tac_toe_board[squares[square.lower()]] = 'O'
            x_turn = True

        valid_turns += 1
    else:
        print('INVALID MOVE')

    print(draw_board(tic_tac_toe_board))

    if check_win(tic_tac_toe_board, 'X'):
        print(x + ' has won!')
        break
    elif check_win(tic_tac_toe_board, 'O'):
        print(o + ' has won!')
        break

if valid_turns == 9:
    print('DRAW!')


texts: How do I reduce the if..else soup in this Controller function?

texts:
The processing is the same, but the response type differs based on whether it's an AJAX request or not.

One way I can think of is to store all the response calls inside closure functions, and return once at the end (twice in the function overall because of the first return). That would only make it look a teensy bit better, in my subjective opinion. Not much of an improvement...

public function post_update()
{
    $submission = Input::all();
    $rules = array(
        'password' => 'required',
        'password_repeat' => 'required|same:password',
        'terms_accepted' => 'required'
    );

    $validator = Validator::make($submission, $rules);
    if (! $validator->passes()) {
        if (Request::ajax()) {
            return Response::json($validator->errors, 400);
        } else {
            return Redirect::to('signup/manual_password')->with_errors($validator);
        }
    }

    $user = Auth::user();
    $user->password = $submission['password'];
    $user->set_repeated_password($submission['password_repeat']);
    $user->password_set_manually = 1;

    try {
        $user->save_or_ex();

        if (Request::ajax()) {
            return Response::json(Session::get('_next_uri'));
        } else {
            return Redirect::to(Session::get('_next_uri'));
        }

    } catch (ValidationException $e) {

        if (Request::ajax()) {
            return Response::json($e->getErrors(), 500);
        } else {
            return Response::error(500);
        }

    }
}


texts:
I'm using django and I wrote this decorator to take away some of the repetitive code I found for ajax views and I want to know your opinion (too basic, bad design, try this instead, etc).

def ajax_only(func):
    def _ajax_only(request,*args,**kwargs):
        if not request.is_ajax():
            return HttpResponse('
Ajax not supported.
')
        else:
            return func(request,*args,**kwargs)
    return _ajax_only


texts:
Recently, I've solved this "Number of Islands" problem on LeetCode, the solution was accepted by the LeetCode OJ.

Problem Description

  Given a 2d grid map of '1's (land) and '0's (water), count the number
  of islands. An island is surrounded by water and is formed by
  connecting adjacent lands horizontally or vertically. You may assume
  all four edges of the grid are all surrounded by water.

Examples/Test Cases

A single island:

11110
11010
11000
00000

3 islands:

11000
11000
00100
00011

The Solution

The idea behind the solution posted below is to:

iterate over every cell of the grid
when find a 1 value, increment the island counter, use the BFS to find all cells in the current island
mark all the cells in the current island with value 2

The Code:

from collections import deque

class Solution(object):
    def append_if(self, queue, x, y):
        """Append to the queue only if in bounds of the grid and the cell value is 1."""
        if 0 <= x < len(self.grid) and 0 <= y < len(self.grid[0]):
            if self.grid[x][y] == '1':
                queue.append((x, y))

    def mark_neighbors(self, row, col):
        """Mark all the cells in the current island with value = 2. Breadth-first search."""
        queue = deque()

        queue.append((row, col))
        while queue:
            x, y = queue.pop()
            self.grid[x][y] = '2'

            self.append_if(queue, x - 1, y)
            self.append_if(queue, x, y - 1)
            self.append_if(queue, x + 1, y)
            self.append_if(queue, x, y + 1)

    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """

        if not grid or len(grid) == 0 or len(grid[0]) == 0:
            return 0

        self.grid = grid

        row_length = len(grid)
        col_length = len(grid[0])

        island_counter = 0
        for row in range(row_length):
            for col in range(col_length):
                if self.grid[row][col] == '1':
                    # found an island
                    island_counter += 1

                    self.mark_neighbors(row, col)

        return island_counter

if __name__ == '__main__':
    grid = """11000
    11000
    00100
    00011"""

    grid = [list(line) for line in grid.splitlines()]
    print(Solution().numIslands(grid))

The Questions:

Is it the most optimal solution to the problem, or is there a more efficient approach? What would you improve code-quality or code-organization wise?


texts:
I'm using Pygame to create a small game with few rectangle shapes.  However, I want to learn more about classes, and I'm trying to use them.  I'm very new to classes and inheritance, but I want to learn the best habits possible. I'm using Python 3.3.2.

import pygame

class Screen(object):
    ''' Creates main window and handles surface object. '''
    def __init__(self, width, height):
        self.WIDTH = width
        self.HEIGHT = height
        self.SURFACE = pygame.display.set_mode((self.WIDTH, self.HEIGHT), 0, 32)

class GameManager(object):
    ''' Handles game state datas and updates. '''
    def __init__(self, screen):
        self.screen = screen

pygame.init()
Window = Screen(800, 500)
Game = GameManager(Window)

I skipped a few functions to make it simpler.  The thing that bothers me is that I've been told that I don't need GameManager to be subclasses of Screen.  I was advised to use this implementation, but I find it very strange to use 'Window' as a parameter to GameManager.

Do I need to use inheritance?  Should I use super()?  Later on, I will have class Player and I will need some of the attributes from the Screen class.  From the viewpoint of designing OO for a GUI game using Pygame.


texts:
Illustration

  You're testing a new driverless car that is located at the Southwest
  (bottom-left) corner of an n×n grid. The car is supposed to get to the
  opposite, Northeast (top-right), corner of the grid. Given n, the size
  of the grid’s axes, write a function numOfPathsToDest that returns
  the number of the possible paths the driverless car can take.

  For convenience, let's represent every square in the grid as a pair
  (i,j). The first coordinate in the pair denotes the east-to-west axis,
  and the second coordinate denotes the south-to-north axis. The initial
  state of the car is (0,0), and the destination is (n-1,n-1).

  The car must abide by the following two rules: it cannot cross the
  diagonal border. In other words, in every step the position (i,j)
  needs to maintain i >= j. See the illustration above for n = 5. In
  every step, it may go one square North (up), or one square East
  (right), but not both. E.g. if the car is at (3,1), it may go to (3,2)
  or (4,1).

Example

input:  n = 4

output: 5 # since there are five possibilities:
          # “EEENNN”, “EENENN”, “ENEENN”, “ENENEN”, “EENNEN”,
          # where the 'E' character stands for moving one step
          # East, and the 'N' character stands for moving one step
          # North (so, for instance, the path sequence “EEENNN”
          # stands for the following steps that the car took:
          # East, East, East, North, North, North)

My approach:

import java.io.*;
import java.util.*;

class Solution {

  static int numOfPathsToDest(int n) {
    // your code goes here
    //n = 2
    int startX = 0;
    int startY = 0;

    int numPoss = numPaths(startX,startY,n);

    return numPoss;

  }

  static private int numPaths(int startX, int startY, int n )
  {
    int destX = n - 1;
    int destY = n - 1;
    int numPoss = 0;

    //Base case
    if((startX == destX) && (startY == destY ))
      numPoss++;

    //Recursive condition
    else
      {
        if( (startX >= startY) && (startX < n) && ( startY < n ))
        {
          //East
          numPoss += numPaths(startX+1, startY,n);

          //North
           numPoss +=  numPaths(startX,startY + 1, n);
        }

        //Time complexity: O(2^n) -> O(n^2) in memoization
       //Space complexity: O(n^2)
      //Bottom up approach: O(n) space complexity
      //Time complexity: O(n)
      }

    return numPoss;
  }

  public static void main(String[] args) {
    System.out.println(numOfPathsToDest(2));
  }

}

//n = 4
//#squares = 4 + 3 + 2 + 1

//#squares = n + n-1 + n-2 + ... 1 = n(n + 1)/2

//square 0 - eastx 4/ n - 1

//square (1,0): up - 1, east -  3/(n - 1)

//square (2,0): up - 2, east: 2/(n - 2)

//east + north : n
//

I have the following questions with respect to the code:

What can I further improve my code in terms of space and time complexity?
Is there any smarter approach to solve this question?
Does my code violate any of the coding conventions?
Are there any other ways that I can further optimize the code?

Reference


texts:
I'm working on a school project right now. It's an ordered(ascending) doubly linked list. I just wrote the Insert operation on it but I feel like the way I wrote it isn't that great.

void OrdListClass::Insert(ItemType item)
{
    if(Find(item))
    {
        //throw DuplicateKeyException;
    }//End Duplicate Key Check
    else
    {
        //Due to Find, currPos points to the node that we're inserting AFTER
        node* newNode = new node;
        newNode->data = item;

        if(currPos == nullptr)
        {
            //We're inserting at the head.
            newNode->prev = nullptr;
            newNode->next = head;
            head->prev = newNode;
            head = newNode;
        }
        else if(currPos->next == nullptr)
        {
            //We're inserting at the tail
            newNode->next = nullptr;
            newNode->prev = tail;
            tail->next = newNode;
            tail = newNode;
        }
        else
        {
            //We're inserting in the middle of the list.
            newNode->prev = currPos;
            newNode->next = currPos->next;
            currPos->next->prev = newNode;
            currPos->next = newNode;
        }
        currPos = newNode;
    }//End Not Duplicate Else
}//End Insert

EDIT: Of note.. ItemType is just a typedef for an int.

bool OrdListClass::Find(/*IN*/ItemType searchKey)
{
    //Skip operations if empty.
    if(IsEmpty()) return false;

    currPos = head;
    while(!EndOfList())
    {
        if(currPos->data == searchKey)
        {
            return true;
        }
        else if (currPos->data > searchKey)
        {
            currPos = currPos->prev;
            return false;
        }
        //else continue;
    }
}


texts:
For reasons I'd rather like to not talk about, I am in a VBA environment that doesn't have the replace function (Access 97). I have wrote this to alleviate my frustrations.

My question is,  what is the quickest and most efficient way of writing this function? I am not married to it, I just want the best possible piece of code. While I do enjoy readability I am also OK with stepping away from that to learn something super cool.

Public Function RepStr(InputString As String, InvalidStr As String, ValidStr As String) As String
    Dim ModString As String

    ModString = InputString

    While InStr(1, ModString, InvalidStr) > 0
        ModString = Left(ModString, InStr(1, ModString, InvalidStr) - 1) & _
        ValidStr & Mid(ModString, Len(InvalidStr) + InStr(1, ModString, InvalidStr))
    Wend
    RepStr = ModString
End Function


texts: Python Constant Class, Different Enum Implementation

texts:
So I saw a need for and came up with a class implementation to group constants, which I'm calling a Constant Class. I wondered if there existed other similar implementations or if there is a flaw in what I'm doing. My team is currently finding it fairly useful and thought we should see what other people thought. Also to offer out into the world if it indeed is useful to others.

The need was simple. We wanted to group constants as to allow auto-completion and also the ability to reference a list of all the values for validation. This mainly was for the development of an API backend which handle many groups of different types.

import inspect
import re

class ConstantClass(object):
    """ Container class for meant for grouped constants """

    @classmethod
    def all(cls):
        """
        Returns all constant values in class with the attribute requirements:
          - only uppercase letters and underscores
          - must begin and end with a letter

        """
        regex = r'^[A-Z][A-Z_]*[A-Z]$'
        class_items = inspect.getmembers(cls)
        constants = filter(lambda item: re.match(regex, item[0]), class_items)
        values = map(lambda constant: constant[1], constants)

        return values

class TypeNames(ConstantClass):
    TYPE_A = 'Whatever you want it to be'
    TYPE_B = 'Another example'

TypeNames.TYPE_A # returns 'Whatever you want it to be'
TypeNames.all() # returns list of constant values
TypeNames.TYPE_A in TypeNames.all() # Returns True

Enums the closest thing but it requires we type out EnumClass.CONSTANT.value (I honestly find kind of annoying) and there isn't a built-in function to get all the values. I don't know, maybe I'm splitting hairs here but I'm just curious if there is any draw-back to what I'm doing.


texts: Counting occurrences of values in C Array (Shannon Entropy)

texts:
I have written the following C code for calculating the Shannon Entropy of a distribution of 8-bit ints. But obviously this is very inefficient for small arrays and won't work with say 32-bit integers, because that would require literally gigabytes of memory. I am not very experienced in C and don't know what would be the best approach here. If it would simplify things, I could use C++ or Objective-C...

Also, please tell me about any other issues with the code you may find :-)

double entropyOfDistribution(uint8_t *x, size_t length)
{
    double entropy = 0.0;

    //Counting number of occurrences of a number (using "buckets")
    double *probabilityOfX = calloc(sizeof(double), 256);
    for (int i = 0; i < length; i++)
        probabilityOfX[x[i]] += 1.0;

    //Calculating the probabilities
    for (int i = 0; i < 256; i++)
        probabilityOfX[x[i]] /= length;

    //Calculating the sum of p(x)*lg(p(x)) for all X
    double sum = 0.0;
    for (int i = 0; i < 256; i++)
        if (probabilityOfX[i] > 0.0)
            sum += probabilityOfX[i] * log2(probabilityOfX[i]);

    entropy = -1.0 * sum;

    free(probabilityOfX);

    return entropy;
}

btw, this is the formula I implemented:  $$ H(x) = -\sum_{x} p(x) \log(p(x))$$


texts:
I wrote a program to implement to find the count of words for a given string.
I have applied two different approaches.
The test works for these two approaches and I am looking for other approaches to solve this problem.
Thanks for your valuable comments advance.
package test;

import main.algorithms.WordCount;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class WordCountTest {

    WordCount wc;

    @Before
    public void setUp(){
        wc = new WordCount();
    }

    @Test
    public void testWordCount(){

        String str = "nesly amazon google facebook apple";

        Assert.assertEquals(5,wc.countWords(str));

        Assert.assertEquals(5,wc.countWordsTokenizer(str));
    }

}

package main.algorithms;

import java.util.StringTokenizer;

public class WordCount {

    public int countWords(String str)
    {
        int end = 0;
        int in = 1;

        int state = end; int wc = 0; int i = 0;

        while (i < str.length())
        {
            if(str.charAt(i) == ' ' || str.charAt(i) == '\n'
                    || str.charAt(i) == '\t')
                state = end;

            else if (state == end)
            {
                state = in;
                ++wc;
            }
            ++i;
        }
        return wc;
    }

    public int countWordsTokenizer(String str){

        return new StringTokenizer(str).countTokens();
    }

}


texts: Checking errors from a series of function calls

texts:
I have to work with C-style functions which return ERROR_SUCCESS when successful or an error code when not. I want my code to be nice and neat and easy to read but I am not sure I like what I have.

Option one:

int Foo()
{
    int result = Init();

    if (result == ERROR_SUCCESS)
    {
        result = SetTemperature( 30 );
    }
    else
    {
        return result;
    }

    if (result == ERROR_SUCCESS )
    {
        result = SetVoltage( 5 );
    }
    {
        return result;
    }

}

Option two:

int Foo()
{
    int result = Init();

    if (result != ERROR_SUCCESS)
        return result;

    result = SetTemperature( 30 );

    if (result != ERROR_SUCCESS)
        return result;

    result = SetVoltage( 5 );

    if (result != ERROR_SUCCESS)
        return result;

}

Please note that I can't use exceptions here. If there is an error then I simply need to return from the function with that error. Is there an even better way to organize this code?


texts: Read a space delimiters settings file in C

texts:
I'm a C# programmer and I would like to start getting better at coding in C. I wrote a function which reads a space delimiters settings file (supports comments / and #).
The code works fine. But from the point of view of C coding style, I'd like to know if this code is well written.

example settings file:

//Destination information
DestAddr 192.168.1.101
DestSSHPort 22

code:

int ReadConfigFile(char * in_filename)
{
    int t_buffSize = 612;
    char t_key[t_buffSize];
    char t_value[t_buffSize];

    //if input filename is null
    if(!in_filename ||
       *in_filename == '\0' ||
       in_filename == NULL)
    {
        return -1;
    }

    //open file
    FILE *t_fd   = NULL;
    t_fd         = fopen (in_filename,"r");

    if (t_fd == NULL)
    {
        fprintf(stderr, "Error opening input file: %s\n",
                in_filename);
        return -1;
    }

    //read individual settings lines
    char t_firstChar;
    while( (t_firstChar = getc(t_fd)) != EOF )
    {
        //skip comment line
        if(t_firstChar == '/' || t_firstChar == '#')
        {
            char t_comment[t_buffSize];
            long t_currFP = getline(t_fd, t_comment, t_buffSize);
            fseek(t_fd, t_currFP + 1, SEEK_SET);
        }
        else
        {
            long t_currFP = ftell (t_fd);
            fseek(t_fd, t_currFP - 1, SEEK_SET);

            if(fscanf (t_fd, "%s %s", t_key, t_value) != EOF)
            {
                printf("%s -- %s \n", t_key, t_value);
                //just print the values for now
            }
        }
    }

    return 0;
}


texts: Find all k points which are closest to origin

texts:
We have a list of points on the plane.  Find the K closest points to
  the origin (0, 0).

  (Here, the distance between two points on a plane is the Euclidean
  distance.)

  You may return the answer in any order.  The answer is guaranteed to
  be unique (except for the order that it is in.)

  Example 1:

  Input: points = [[1,3],[-2,2]], K = 1

  Output: [[-2,2]]

  Explanation: The distance between (1, 3) and the origin is
  \$\sqrt{10}\$.  The distance between (-2, 2) and the origin is
  \$\sqrt{8}\$.  Since \$\sqrt{8} < \sqrt{10}\$, (-2, 2) is closer to
  the origin.  We only want the closest K = 1 points from the origin, so
  the answer is just [[-2,2]].

  Example 2:

  Input: points = [[3,3],[5,-1],[-2,4]], K = 2

  Output: [[3,3],[-2,4]]

  (The answer [[-2,4],[3,3]] would also be accepted.)

  Note:

  1 <= K <= points.length <= 10000
  -10000 < points[i][0] < 10000
  -10000 < points[i][1] < 10000

  Also note that there can be a situation where distance of 2 nodes are
  equal and hence can print any of the node.

Here is my approach.

Took tree map (So that I get all sorted distance)
Start filling tree map for all points
Finally took first k element.

public class KClosestPointsToOrigin {

    public int[][] kClosest(int[][] points, int K) {

        int rows = points.length;

        SortedMap<Double, List<CoordinatePoint>> distanceToPoint = new TreeMap<>();

        for(int i =0; i<rows; i++) {
            double distance = getDistance(points[i]);
            if(Objects.nonNull(distanceToPoint.get(distance))) {
                List<CoordinatePoint> coordinatePointList = distanceToPoint.get(distance);
                coordinatePointList.add(new CoordinatePoint(points[i][0], points[i][1]));
            } else {
                List<CoordinatePoint> coordinatePoints = new ArrayList<>();
                coordinatePoints.add(new CoordinatePoint(points[i][0], points[i][1]));
                distanceToPoint.put(distance, coordinatePoints);// x and y coordinates.
            }
        }

        int[][] arrayToReturn = new int[K][2];
        int counter = 0;
        for (Double key : distanceToPoint.keySet()) {
            List<CoordinatePoint> coordinatePoints = distanceToPoint.get(key);
            Iterator iterator1 = coordinatePoints.iterator();
            while (iterator1.hasNext() && counter < K) {
                CoordinatePoint coordinatePoint = (CoordinatePoint) iterator1.next();
                arrayToReturn[counter][0] = coordinatePoint.x;
                arrayToReturn[counter][1] = coordinatePoint.y;
                counter++;
            }
        }

        return arrayToReturn;
    }

    private double getDistance(int[] point) {
        int x = point[0];
        int y = point[1];

        int x2 = Math.abs(x) * Math.abs(x);
        int y2 = Math.abs(y) * Math.abs(y);

        return Math.sqrt(x2+y2);
    }
}

class CoordinatePoint {
    int x;
    int y;

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

However, this solution is not efficient as runtime and memory usage is high. Can you please help me to optimize the solution.