texts: Preparing a walkthrough: Freeze effect :s

texts:
I have a method that load my walkthrough view. I have my view controller composed of a scroll view. And others views controllers used only for the walkthrough (maybe I should used xib uiview instead of uiviewcontroller). And when I'm on the viewWillAppear, I'm calling this method:

/**
Prepare dynamicly the walkthrough views ( app presentation ), like the final content size of `myScrollView, the origin of the views, etc..
So if we want to add another view on our walkthrough, we just add it to `listPages` and on the storyboard.

Copied from an old personal project
*/
func prepareWalkthroughViews() {

    // I use a contentView with the scroll view because of the auto layout.
    var i = CGFloat(self.listPages.count-1)

    // We iterate each view controller. We add the views on the inverse order, like a stack
    for currentController in reverse(self.listPages) {
        contentView.addSubview(currentController.view)
        var currentFrame       = currentController.view.frame
        currentFrame.origin.x  = i-- * currentFrame.width // ex : 6 * 320
        currentController.view.frame = currentFrame
    }

    self.myScrollView.addSubview(self.contentView)
    let scrollWidth  = CGFloat(self.listPages.count) * self.view.frame.width
    let scrollHeight = self.myScrollView.frame.height
    self.myScrollView.contentSize = CGSizeMake(scrollWidth, self.contentView.frame.height)
}

When my segue is performed, there is something like 2-3 seconds of freeze (the time the method is executed).

How can this be improved?

I thought about adding some properties global so I can call the method in background queue when I launch the app, but I think that's not very safe to have a lot of global properties everywhere.


texts:
I see that on Linux there are various built-in functions to convert endianness for specific integer width types, and they are probably faster than anything one can write and compile on their own.  But I want to write a size_t (under Linux in C), which does not have a specified width, to big-endian array of bytes, as fast as possible.

Is this the fastest way?

#include <limits.h>

// write "from" to array of bytes "to" in big-endian fashion
void big_endian_size(unsigned char to[], size_t from) {

    unsigned char *p = to + (sizeof(size_t) - 1);

    while (1) {
        *p = from;

        if (to == p)
            break;

        p--;
        from >>= CHAR_BIT;
    }
}


texts: Coverage processing on multiple Java projects with gmake

texts:
As part of my data collection, I have to run multiple kinds of coverage processing on multiple Java projects. Below is my main Makefile intented only for gmake. Portability is not a requirement for me (for this project), but DRY and following make best practices are. Please comment on my code, and if there is any way to make this better.

.PHONY: checkout all clobber clean $(checkout.all)
.SECONDARY: $(addprefix projects/,$(names))

root:=$(CURDIR)
names=$(shell cat etc/projects.txt)
checkout.all=$(addprefix checkout-,$(names))
clean.all=$(addprefix clean-,$(names))

testgen.types=original randoop tpalus

all:
  @echo use 'make <type>-<project>'
  @echo projects = $(names)
  @echo types = $(testgen.types)

checkout: $(checkout.all)
  @echo $@ done.

checkout-%: projects/%/pom.xml
  @echo $@ done.

projects build: ;  mkdir -p $@

projects/%/pom.xml: | projects build
  cd projects && $(root)/bin/checkout $*
  touch $@

clean: $(clean.all)
  @echo $@ done.

clean-%: | projects/%/pom.xml
  cd projects/$* && git clean -xfd && git reset --hard
  @echo $@ done.

clobber-%:
  cd projects && rm -rf $*

#-----------------------------------------------------------------
root:=$(CURDIR)

define testgen =
$1 : $(addprefix $(1)-,$(names))
  @echo $$(@) done.

$1-% : projects/%/.$(1).done
  @echo $$(@) done.

%/.$1.done : | %/pom.xml
  echo $$(MAKE) -C $$(*) root=$$(root) $(1)
endef

$(foreach var,$(testgen.types),$(eval $(call testgen,$(var))))

Some clarification about the intended purpose of this project. I am doing an analysis on a large number of  projects from github. My method of action is to clone each project, run multiple tests on them. Before running any project, I do a git clean to make sure that the artifacts of previous tests are not present in the project directories. The types of tests and projects names vary frequently, and hence I have kept them outside the main Makefile.


texts:
The author of my book does not release odd-numbered solutions to students, so I can't check my solutions. I was wondering if there was a better way to solve this problem without simply printing out the square roots.

Here is the question:

  (Game: locker puzzle) A school has 100 lockers and 100 students. All
  lockers are closed on the first day of school. As the students enter,
  the first student, denoted S1, opens every locker. Then the second
  student, S2, begins with the second locker, denoted L2, and closes
  every other locker. Student S3 begins with the third locker and
  changes every third locker (closes it if it was open, and opens it if
  it was closed). Student S4 begins with locker L4 and changes every
  fourth locker. Student S5 starts with L5 and changes every fifth
  locker, and so on, until student S100 changes L100.

  After all the students have  passed through the building and changed
  the lockers, which lockers are open? Write a program to find your
  answer.

  (Hint: Use an array of 100 Boolean elements, each of which indicates
  whether a locker is open (true) or closed (false).  Initially, all
  lockers are closed.)

Here is my solution:

public class Main {
    public static void main(String[] args) {
        boolean[] lockers = new boolean[101];
        //Open all multiples of 1 before moving on to 2
        for (int i = 1; i < lockers.length; i++) {
            lockers[i] = true;
        }

        //open every locker for every multiple of i
        for (int i = 2; i <= 100; i++) {
            for (int j = 1; i * j <= 100; j++) {
                lockers[i * j] = (lockers[i * j] == true) ? false : true;
            }
        }

        //Display the indices of the open lockers
        for (int i = 0; i < lockers.length; i++) {
            if (lockers[i] == true)
                System.out.println("locker " + i + " is open.");
        }
    }
}


texts: Finding the similarity between the two movies using Pearson correlation coefficient

texts:
I am trying to find the similarity between the two movies using Pearson correlation coefficient. The programs is working well for small inputs but for large inputs (like 100000 lines) it takes forever. My professor said it would take few minutes, but my program is executing forever.

The input format: user|movie|rating.

If two or more users watch two movies, we will find similarity between them based on rating.

# -*- coding: utf-8 -*-
"""
Created on June 06, 2016

@author: Praveen Allam
"""

from mrjob.job import MRJob
from mrjob.step import MRStep
from itertools import combinations
from itertools import izip
from math import sqrt

class PearsonCorrelation(MRJob):
    def steps(self):
        return [
            MRStep(mapper=self.mapper1,
                  reducer=self.reducer1),
            MRStep(mapper=self.mapper2,
                  reducer=self.reducer2)
        ]

    def mapper1(self, _, line):

        ##yield each line to first mapper
        user,movie,rating=line.split('|')
        yield None,[user,movie,rating]

    def reducer1(self, _, value):

        ##yield all combinations to second mapper
        for item1,item2 in combinations(value,2):
            yield item1,item2

    def mapper2(self,value1,value2):

        ##yield movie1,movie2 and corresponding ratings of user.
        if(value1[0]==value2[0]):
            yield [value1[1],value2[1]],[float(value1[2]),float(value2[2])]

    def reducer2(self,movies,ratings):
        rating=[]
        for item in ratings:
            rating.append(item)

        ##extract using izip only if there are more than one instance.
        if(len(rating)>1):
            v1,v2=izip(*rating)

            ##calculate the pearson coefficient
            corr=self.pearsonCoefficient(v1,v2)

            ##yield the result
            yield "The Similarity between "+movies[0]+" and "+movies[1]+" is: " , corr
    def pearsonCoefficient(self,a,b):
        n=len(b)
        value=range(n)

        #sums of individual lists
        sum_x=sum([float(a[i]) for i in value])
        sum_y=sum([float(b[i]) for i in value])

        #sum of the squares of each lists
        sum_xSq=sum([a[i]**2.0 for i in value])
        sum_ySq=sum([b[i]**2.0 for i in value])

        #sum of the products
        sumP=sum([a[i]*b[i] for i in value])

        #Calculate Pearson coefficient
        numerator=sumP-(sum_x*sum_y/n)
        denominator=((sum_xSq-pow(sum_x,2)/n)*(sum_ySq-pow(sum_y,2)/n))**0.5

        if denominator == 0: return 1

        result=numerator/denominator
        return result

if __name__ == '__main__':
     PearsonCorrelation.run()


texts: Printing integers with spaces between the digits

texts:
Problem:  Given an integer between 1 and 32767 print the individual digits with 2 spaces between them.

I am using C How To Program but this is not homework.  The book has not gotten to arrays or anything more complicated than looping structures and function. I try to avoid using those structures and concepts that have not been introduced yet.  I get the digits to separate and output.  I was wondering if there is a better way to do this using the tools I have.

My Code:

//-----------------------------------------------------------------------------
// Program: EX5_22.c - Separating Digits
// Programmer:  Joseph Cunningham
// Class: CsC_20 - c
// Date: 2/16/19
//
// This program will prompt the user for a number from 1 - 32767.  It will then
// output that number separated into its constituent digits with 2 spaces
// between each digit
//-----------------------------------------------------------------------------

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

int getNumLength(int number);
void separate(int number, int power); // Fucntion prototype

int main (void)
{
  // Variable declaration

  int number; // User entered number to digitize
  int power;  // Power to generate divisor

  // Prompt user for number

  printf("Please input a number (1-32767): ");
  scanf("%d", &number);

  // Get the power for the divisor

  power = getNumLength(number);

  // Output digits

  separate(number, power);

  return 0;
}

//-----------------------------------------------------------------------------
// Function: getPower(number) - counts the number of digits in the number to
// generate a power
// Input:  int number - the user entered number
// Output: none
// Return value - length of thr number
//-----------------------------------------------------------------------------

int getNumLength(int number)
{
  int length; // the length of number

  while (number != 0)
  {
    number = number / 10;
    length++;
  }

  return length;
}

//-----------------------------------------------------------------------------
// Function: separate(number) - separates and displays an integer between 1
// -32767 into its digits
// Input: int number - intger betwenn 1 - 32767, int power - power for divisor
// Output: numbers digits separated by 2 spaces
// Return value: none
//-----------------------------------------------------------------------------

void separate(int number, int power)
{
  int divisor; // the divisor from power
  int i;  // loop counter

  for(i = power - 1; i >=0; i--)
  {
    divisor = (int)pow(10, i);
    printf("%d  ", number / divisor);
    number = number % divisor;
  }
}


texts:
I have a third party system that submits what I am assuming is a byte array data from OBDII port on our fleet vehicles.

I was getting values like:

AA== (bool)
AQ== (bool)
AAAaMA== (int)
AAA0IQ== (int)
Mjow (string)
UzozLTIwNA== (string)

I know what the type is for each field but the regular base64_decode() function wouldn't decode them and neither did the online Base64 decoders.

Here is what I came up with that works, I just curious if this is the right way to decode base64 encoded bytes.

It essentially takes the input down to binary and converts the binary to the type. It works as expected but I feel like I'm over complicating it.

class Decoder
{
    /**
     * Decodes Base64 ByteArray to Number
     *
     * @param string $encoded
     * @return number
     */
    public static function getNumber($encoded)
    {
        $decoded = base64_decode($encoded);

        $byteArray = array();

        foreach(str_split($decoded) as $byte)
        {
            $byteArray[] = sprintf("%08b", ord($byte));
        }

        $raw_bytes = implode(' ', $byteArray);

        return bindec($raw_bytes);
    }

    /**
     * Decodes Base64 ByteArray to ASCII String
     *
     * @param string $encoded
     * @return string
     */
    public static function getString($encoded)
    {
        $decoded = base64_decode($encoded);

        $raw = "";

        foreach(str_split($decoded) as $byte)
        {
            $raw .= chr(bindec(sprintf("%08b", ord($byte))));
        }

        return $raw;
    }

    /**
     * Decodes Base64 ByteArray to Boolean
     *
     * CHEATER FUNCTION
     *
     * Simply interprets Base64 value against known true/false values
     *
     * Value: "AQ==" will return true everything else will be false
     *
     * @param $encoded
     * @return bool
     */
    public static function getBool($encoded)
    {
        return ($encoded == "AQ==");
    }

    /**
     * Decodes Base64 ByteArray to Boolean
     *
     * Actually does decode and comparison on byte level.
     *
     * More expensive but is a true decode.
     *
     * @param $encoded
     * @return bool
     */
    public static function zDecodeBool($encoded)
    {
        $decoded = base64_decode($encoded);

        $byteArray = array();

        foreach(str_split($decoded) as $byte)
        {
            $byteArray[] = sprintf("%08b", ord($byte));
        }

        return $byteArray[0] == "00000001";
    }
}


texts:
I am trying to get ordered components of an interface properly without having a local variable orderedComponents outside, and here is my current code.

Reason is because orderedComponents will be in Interface.java and getChildren will be in componentDefinitions.java and I want a more controllable code.

I was also thinking of changing from List to single dimension array and ill soon remove the static ones I separate them.

public static List<Integer> orderedComponents = new ArrayList<Integer>();

/**
 * returns the components ordered
 *
 * @param interfaceId
 * @return The components of an interface sorted
 */
public static List<Integer> getOrderedComponents() {

    orderedComponents.clear();

    for (int i = 0; i < inter.getComponents().length; i++) {

        // if all comps are added, stop the loop
        if (orderedComponents.size() == inter.getComponents().length)
            break;

        if (orderedComponents.isEmpty() && inter.getComponent(i).hasParent()
                && !orderedComponents.contains(inter.getComponent(i).getParentId()))
            continue;

        // do the magic
        getAllChildren(i);

    }
    return orderedComponents;
}

public static void getAllChildren(int componentId) {

    // get the current component definitions
    ComponentDefinitions component = inter.getComponent(componentId);

    // TODO first parent of the parents
    // if component has parent and it is not added to the list, add it
    if (component.hasParent() && !orderedComponents.contains(component.getParentId())) {
        orderedComponents.add(component.getParentId());
    }

    // if component is not added to the list, add it
    if (!orderedComponents.contains(component.componentId)) {
        orderedComponents.add(component.componentId);
    }

    // loop through all childs of the current components and re-add their childs
    for (int j = 0; j < inter.getComponent(componentId).getChilds().size(); j++) {
        ComponentDefinitions child = inter.getComponent(componentId).getChilds().get(j);
        getAllChildren(child.componentId);
    }
}

Please let me know what improvements could be done here and what I am doing wrong or is advisable to be changed.


texts:
I'm pretty new to ruby and programming in general.

I had an idea for a fun little project that I could use to gain a little experience. I wrote a simple program that takes a 4 bit binary sequence (ie. 1001, 1110, etc) and converts it into its decimal counterpart (ie 1111 = 15). I got the program working but even I can tell it's pretty ugly and limited code. I've been racking my brain trying to figure out a way to improve and I'm thinking if I do something similar to this app (converting to an array and reversing so i can work left to right instead of right to left) but instead of hard coding the if statements for each digit I could use a loop that just doubles the last digit and add that to the sum if it's a one in that spot.

#!/usr/bin/ruby
# binary_conversion.rb

puts "
    ***************************************************
            BINARY CONVERSION TOOL
                VERSION: 0.1
            CREATED BY: Micky Scandal
    ***************************************************
"
sleep(1)
again = 0
while again != "n"
    @zero = 0
    @one = 0
    @two = 0
    @three = 0
    @bin_input = ""
    until @bin_input.length == 4                                    # && bin_input.class == Fixnum
        print "Please enter a 4 bit binary string (ex: 0110):> "
        @bin_input = gets.chomp
    end
    puts "You entered #{@bin_input}"

    @bin_array = @bin_input.to_s.split(//).map(&:to_i)
    @bin_array.reverse!
    p @bin_array
    puts "converting..."; sleep(0.5)

    if @bin_array[0] == 1
        @zero = 1
    end
    if @bin_array[1] == 1
        @one = 2
    end
    if @bin_array[2] == 1
        @two = 4
    end
    if @bin_array[3] == 1
        @three = 8
    end

    ans = @zero + @one + @two + @three
    puts "answer is #{ans}"
    puts ""
    puts "Run again? (Y/N)"
    again = gets.chomp
end


texts: Emulating the pipe operator in javascript in a readable way

texts:
In this article I found this quite elegant looking Elixir code:

conn
|> put_session(:current_user, user)
|> put_resp_header(location, "/")
|> put_resp_content_type("text/html")
|> send_resp(302, "You are being redirected")

It works by using the output of each of the functions as the first argument to the next function. The given args are bound to the second argument and up.

I know two different proposals for the pipe operator are being considered for a future version, but I am wondering if there is a way of writing something visually and functionally similar looking using the Javascript of today?

I am guessing I could use currying in some sense, binding everything but the first argument?

For reference, here are the original function definitions from the article. They all return a conn

assign(conn, key, value)
clear_session(conn)
put_resp_content_type(conn, content_type, charset)
put_resp_header(conn, key, value)
put_session(conn, key, value)
send_resp(conn, status, body)

I tried making some suggestions, but I would like input on how this could be improved/be more readable/look better for the casual programmer coming to modify my code.

A basic attempt using ES5.1 would look like this:

const {bind, flow} = require('lodash');
const _ = bind.placeholder;

flow(
  bind(put_session, null, _, current_user, user),
  bind(put_resp_header, null, _, location, '/'),
  bind(put_resp_content_type, null, _, 'text/html'),
  bind(send_resp, null, _, 302, 'You are being redirected')
)(conn);

It's a little bit too verbose compared to the original, so I tried compacting it down a bit:

// bind all but first argument - what should I call this?
// bindAllButFirstArgument is a tad bit long
const $$ = (...args) => bind(args[0], null, _, args.slice(1));

flow(
  $$(put_session, current_user, user),
  $$(put_resp_header, location, '/'),
  $$(put_resp_content_type, 'text/html'),
  $$(send_resp, 302, 'You are being redirected')
)(conn);

This looks a bit better (except for the mysterious $$ :) ), and with some minor modifications I could try to make the function in itself syntactically stand out by having a line like

  $$(put_session, current_user, user),

look like

  pipe.prepare(put_session)(current_user, user),

where pipe would be the equivalent of flow and pipe.prepare a utility function that "prepared" the function for the pipe flow mentioned above. Better? What do you think of this? Too dense? Needing to much reading of JSDocs? Different ways?

Would look like this

const pipe = (...args) => flow(...args);
pipe.prepare = fn => (...args) => bind(fn, null, _, args);

pipe(
  pipe.prepare(put_session)(current_user, user),
  pipe.prepare(put_resp_header)(location, '/'),
  pipe.prepare(put_resp_content_type)('text/html'),
  pipe.prepare(send_resp)(302, 'You are being redirected')
)(conn);

Runnable example: https://runkit.com/fatso83/piping-with-binding


texts:
(The next iteration: A simple Java class for implementing code stop watches - follow-up)

Here is my attempt at more convenient benchmarking (yes, this time I am aware of JVM warmup, etc.), and it looks like this:

package net.coderodde.stopwatch;

public final class StopWatch {

    private long earliestMillis = Long.MAX_VALUE;

    public StopWatch() {
        this(System.currentTimeMillis());
    }

    public StopWatch(long earliestMillis) {
        this.earliestMillis = earliestMillis;
    }

    public void push(long earliestMillis) {
        if (earliestMillis < this.earliestMillis) {
            throw new IllegalArgumentException("Cannot go back in time.");
        }

        this.earliestMillis = earliestMillis;
    }

    public long pop() {
        return System.currentTimeMillis() - earliestMillis;
    }

    public long popAndPush() {
        long ret = pop();
        this.earliestMillis = System.currentTimeMillis();
        return ret;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(")
                     .append(System.currentTimeMillis() - earliestMillis)
                     .append(" starting from ")
                     .append(earliestMillis)
                     .append(" ms -> ")
                     .append(System.currentTimeMillis())
                     .append(")");

        return stringBuilder.toString();
    }

    public static void main(String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();

        Thread.sleep(3_000L);
        System.out.println(sw.pop());
        System.out.println(sw);

        Thread.sleep(2_000L);
        System.out.println(sw.pop());

        sw.popAndPush();
        Thread.sleep(1_230L);
        System.out.println(sw);
    }
}

Is there more reasonable/extensive approach to this?


texts:
The following Python program generates heat maps of the roots of Littlewood polynomials. It works fine with a small number of roots, however I tried to use 2^21 in the first loop and it ate up 12 gigabytes of RAM on my computer. How can I make the code less memory-intensive while still allowing reasonably fast performance? Ideally, I would like to use this code to generate very large images but I cannot do so with the program in its current state. Any help would be greatly appreciated. Thanks!

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from math import sqrt, sin, log10
def f(x): # function that maps [0,1] to itself for the color space so that values closer to 1 end up further from 1
    return sqrt(x)
def roots(n): # given n, returns a Littlewood polynomial with coefficients representing the binary representation of n
    roots = np.polynomial.polynomial.polyroots([int(i)*2-1 for i in bin(n)[2:]])
    return [[i.real,i.imag] for i in roots]
# get array of all possible roots and split values up into arrays x and y
temp=[]
for i in xrange(2**16):
    if i%100==0: print i
    for j in roots(i):
        temp.append(j)
x=[i[0] for i in temp]
y=[i[1] for i in temp]

# generate histogram of roots to make heatmap
gap=0.01
print len(np.arange(-2.5,2.5,gap))
normal_histogram = np.histogram2d(x,y,bins=np.arange(-2.5,2.5,gap),normed=True)

# generate image
from PIL import Image
normal_histogram = normal_histogram[0]
size=len(normal_histogram)
im = Image.new("RGB",(size,size))
im2 = Image.new("RGB",(size,size))
#color = [int(256*k) for k in cm.hot(histogram[i][j])[0:3]]
for i in range(len(normal_histogram)):
    print i
    for j in range(len(normal_histogram)):
        temp = int(normal_histogram[i][j]*256)
        im.putpixel((i,j),tuple([int(256*k) for k in cm.hot(f(normal_histogram[i][j]))][0:3]))
        im2.putpixel((i,j),tuple([int(256*k) for k in cm.nipy_spectral(f(normal_histogram[i][j]))][0:3]))
im.save("test.png")
im2.save("test2.png")

Things I've tried

using a txt file to store the polynomial roots
using matplotlib's ability to make heatmaps to plot the data


texts:
I was given an assignment, it was as follows:

Give a JS code snippet which writes to the console from:
"0" to "ZZZZZ" all the combination of the characters of a-z, 0-9 and A-Z.

Is my solution correct?
I am sure there are better ways to achieve the same, can anybody show some?
My code is:

function createCharSet(){
    var charset = "", c;

    for(c=48;c<58;c++){
        charset += String.fromCharCode(c);
    }
    for(c=97;c<123;c++){
        charset += String.fromCharCode(c);
    }
    for(c=65;c<91;c++){
        charset += String.fromCharCode(c);
    }

    return charset;

}

function getNext(curr, charSet){
    var
        length = curr.length,
        arr = curr.split(""),
        radix = charSet.length,
        i, c;

    for(i=length-1;i>-1;i--){
        c = charSet.indexOf(arr[i])+1;

        if(c==radix){
            arr[i]=charSet[0];
            if(i==0)
                return;
        }else{
            arr[i]=charSet[c];
            break;
        }
    }

    return arr.join("");
}

function iterate() {
    var
        charSet = createCharSet(),
        maxLen = 4,
        len,
        i,
        arr,
        curr;

    for(len = 1;len<maxLen+1;len++){
        arr = [];
        for(i=0;i<len;i++){
            arr.push(charSet[0]);
        }

        curr = arr.join("");
        while(curr) {
            console.log(curr);
            curr = getNext(curr, charSet);
        };
    }

}

iterate();


texts:
I have just wrote this Pong game in Pygame:

import pygame
import sys
import math

class Ball(object):
    def __init__(self, x, y, width, height, vx, vy, colour):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vx = vx
        self.vy = vy
        self.colour = colour

    def render(self, screen):
        pygame.draw.ellipse(screen, self.colour, self.rect)

    def update(self):
        self.x += self.vx
        self.y += self.vy

    @property
    def rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Paddle(object):
    def __init__(self, x, y, width, height, speed, colour):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vx = 0
        self.speed = speed
        self.colour = colour

    def render(self, screen):
        pygame.draw.rect(screen, self.colour, self.rect)

    def update(self):
        self.x += self.vx

    def key_handler(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                self.vx = -self.speed
            elif event.key == pygame.K_RIGHT:
                self.vx = self.speed
        elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                self.vx = 0

    @property
    def rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Pong(object):
    COLOURS = {"BLACK": (  0,   0,   0),
               "WHITE": (255, 255, 255),
               "RED"  : (255,   0,   0)}
    def __init__(self):
        pygame.init()
        (WIDTH, HEIGHT) = (640, 480)
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Lewis' Pong")
        self.ball = Ball(5, 5, 50, 50, 5, 5, Pong.COLOURS["BLACK"])
        self.paddle = Paddle(WIDTH / 2, HEIGHT - 50, 100,
                             10, 3, Pong.COLOURS["BLACK"])
        self.score = 0

    def play(self):
        clock = pygame.time.Clock()
        while True:
            clock.tick(50)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type in (pygame.KEYDOWN, pygame.KEYUP):
                    self.paddle.key_handler(event)

            self.collision_handler()
            self.draw()

    def collision_handler(self):
        if self.ball.rect.colliderect(self.paddle.rect):
            self.ball.vy = -self.ball.vy
            self.score += 1

        if self.ball.x + self.ball.width >= self.screen.get_width():
            self.ball.vx = -(math.fabs(self.ball.vx))
        elif self.ball.x <= 0:
            self.ball.vx = math.fabs(self.ball.vx)

        if self.ball.y + self.ball.height >= self.screen.get_height():
            pygame.quit()
            sys.exit()
        elif self.ball.y <= 0:
            self.ball.vy = math.fabs(self.ball.vy)

        if self.paddle.x + self.paddle.width >= self.screen.get_width():
            self.paddle.x = self.screen.get_width() - self.paddle.width
        elif self.paddle.x <= 0:
            self.paddle.x = 0

    def draw(self):
        self.screen.fill(Pong.COLOURS["WHITE"])

        font = pygame.font.Font(None, 48)
        score_text = font.render("Score: " + str(self.score), True,
                                 Pong.COLOURS["RED"])
        self.screen.blit(score_text, (0, 0))

        self.ball.update()
        self.ball.render(self.screen)
        self.paddle.update()
        self.paddle.render(self.screen)

        pygame.display.update()

if __name__ == "__main__":
    Pong().play()

This is my first ever game in Pygame, so I'm asuming there's a few bad practices. Can anyone improve my code and find those bad practices?


texts: List creation, manipulation, user interaction, loops, and just winging some fun stuff for a game

texts:
I'm trying to learn Python and this is my fist functioning little bit I wrote for a campaign I'm doing in D&D. I was wondering if I was doing anything wrong or if anyone had tips on how to make it more readable, function smoother, or be more interactive.

from random import randint
spells = '''Rol
#A LOT OF TEXT FROM HERE

I copied this part from roll20 website list of spells then just broke it up biased on the line breaks.
#to here...
'''

spells=spells.split('''\n\n''')

for i in [348, 332, 315, 294, 262, 224, 192, 149, 94, 44, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]:
  del spells[i]

def ask():
  print('"So ya done goofed I see, usin magic where there not be, I have your roll and the spell out of control, just tell me what you need!"')
  while True:
    print()
    print('if you need a random spell type random or r, if you need a specific spell enter a number from 1 to '+str(len(spells)))
    need=input()
    if need.isdigit():
      need=int(need)
      if need > len(spells)  :
        print('"THERES NOT THAT MANY SPELLS YE TROLLUP"')
      elif need<1:
        print('"thee list start at ONE ye trollup"')
      else:
        print(spells[need-1])

    elif need.lower().startswith('r'):
      need=randint(0,len(spells)+1)
      need=need-1
      print(spells[need])

    else:
      print('FOLLOW MY INSTRUCTS WITH INTIGER OR RANDOM YE GOD FEARING REBEL')

ask()

Also, to get that fun little list that I made to get rid of useless strings in my spells list, I went ahead and wrote this:

guess=0
correctGuess=[]
for i in spells:
  if len(i)<15: #because I knew the strings I wanted to remove were under 15 in length
    print(i)
    x=i
    while x != spells[guess]:
      guess=guess+1
      if x==spells[guess]:
        print('That spell is '+str(guess))
        correctGuess.append(guess)

#reversed list so that when it removes the specific threads it isn't changing the length that the next thread to be removed is at
revCorrectGuess=list(reversed(correctGuess))

Then I manually copied the output list and took out the bit to make my code a little shorter.

Full code


texts: Reading strings into a vector, without using namespace std

texts:
I have been told that using namespace std is a bad practice (especially in header files). But wouldn't this make the program less readable?

int main()
{
    std::string text;
    std::vector<std::string> svec;

    while(std::cin >> text)
        svec.push_back(text);

    for(std::vector<std::string>::size_type i = 0; i < svec.size(); i++)
        std::cout << svec[i]  + " " << svec[i].size() << "\n";

    return 0;
}

Does this not make the for loop difficult to read, even for a simple program as this? Is there a better way to do this?


texts:
I have written the following php class method to traverse an array and build a query from the array.

The data of this array looks like:

0 => [
    'key1' => 'value',
    'key1' => 'value',
    'key3 => 'value'
],
1 => [
    'key1' => 'value',
    'key1' => 'value',
    'key3 => 'value'
]

The project is not my own, but the module im working on is so I am making use of the existing database class which is based on pdo within the project.

As you can see I am looping through the array building a query and inserting the contents of each into one row. Is there a more efficient way to build the queries?

/**
 *
 * @param string $table
 * @param string $keyColumn
 * @param int $keyID
 * @param array $data
 * @return int
 */
private function insertKeyed($table, $keyColumn, $keyID, $data) {
    // each array element
    foreach ($data as $topkey => $topval) {

        // start of query string
        $buildQuery[] = "INSERT INTO `{$table}` SET `{$keyColumn}` = '{$this->db->escape($keyID)}'";

        foreach ($topval as $key => $value) {
            if (!is_array($value)) {
                // add each column as array element
                $buildQuery[] = "`{$key}` = '{$this->db->escape($value)}'";
            }
        }

        // merge into string
        $queryString = implode(',', $buildQuery);

        $result = $this->db->query($queryString);

        // ensure that $buildQuery is reset for multiple rows.
        unset($buildQuery);

        if (!$result->num_rows) {
            $this->log->message('INSERT FAILED.');
            break;
        } else {
            $this->log->message('INSERT SUCCEEDED.');
        }
    }

    return $this->db->getLastId();
}


texts: HTML5 Local Storage toggle and save multiple classes

texts:
I put together a code will allow me to toggle a class and save it in local storage.

Now I need to add 2 more classes to be toggled and be saved in the same manner.
I don't know how to iterate properly with the code and the DOM to achieve this.

This is my "semi-working" example:
http://jsbin.com/nimekebura/1/edit?html,css,js,output

HTML:

    toggle and save state

JS:

 //retrieve current state
 $('.container').toggleClass(localStorage.toggled);

    /* Toggle */
    $('.bar-toggle').on('click',function(){

     // set 1 localstorage values are always strings (no booleans)
       if (localStorage.toggled != "with_toggle" ) {
          $(".container").toggleClass("with_toggle", true );
          localStorage.toggled = "with_toggle";

       } else {
          $(".container").toggleClass("with_toggle", false );
          localStorage.toggled = "";
       }

    });

I need to add and toggle another 2 classes to each .box class already in the code.

so the code would toggle like this:

what would be the best code practice to achieve the above?

Also  Iwas told, the localStorage object is not meant to be extended with new keys like toggled and If wanted to add a new item, I would need to you use localStorage.setItem('key', 'value') https://developer.mozilla.org/en-US/docs/Web/API/Storage

Needless to say I have no idea how to do this the best code practice way. Could someone help me refactor the code properly and also add the two new classes?


texts:
In my application I have a class responsible to save in a file the current status of the application (model) when it change :
public class BackupAgent
{
    private readonly Model _model;

    public BackupAgent(Model model)
    {
        _model = model;
        _model.Changed += Save;
    }

    private void Save()
    {
        // serialize model and save it to a file
        ...
    }
}

It works fine but when there is a lot of modification the file is written again and again.
I came out with a RecurringActionHandler that ensure that

the Save method is not called twice in a minimum amount of time.
the Save method is always called (sooner or later) after a modification.

It is used like that:
public class BackupAgent
{
    private readonly Model _model;
    private readonly RecurringActionHandler _saveHandler;

    public BackupAgent(Model model)
    {
        _model = model;
        _saveHandler = new RecurringActionHandler(Save, TimeSpan.FromMilliseconds(100));

        _model.Changed += RequestSave;
    }

    private void RequestSave() => _saveHandler.RequestCall();

    private void Save()
    {
        // serialize model and save it to a file
        ...
    }
}

Here is my current implementation:
public class RecurringActionHandler
{
    // Action to call recurrently
    private readonly Action _action;

    // a lock to protect _hasTask and _isCallRequested
    private readonly object _lock = new();

    // minimum time span between two calls to _action
    private readonly TimeSpan _minimumRestTime;

    // a boolean indicating whether a task is already running or not
    private bool _hasTask;

    // a boolean indicating whether a call to _action is request or not
    private bool _isCallRequested;

    public RecurringActionHandler(Action action, TimeSpan minimumRestTime)
    {
        _action = action;
        _minimumRestTime = minimumRestTime;
    }

    public void RequestCall()
    {
        lock (_lock)
        {
            _isCallRequested = true;

            if (_hasTask)
                return;

            _hasTask = true;
            Task.Run(Work);
        }
    }

    private async Task Work()
    {
        for (;;)
        {
            lock (_lock)
            {
                if (!_isCallRequested)
                {
                    _hasTask = false;
                    break;
                }

                _isCallRequested = false;
            }

            _action();
            await Task.Delay(_minimumRestTime).ConfigureAwait(false);
        }
    }
}

I'm looking for advice on the code and the method / class names. Is Throttling a matching name here ?


texts:
I'm still learning from designing with types non strings by Scott Wlaschin.
For my project I transform some XML to HTML with xslt.
Because every filename can have side effects, they are stored in string option types.
If I do the transformation I get an ugly pyramid of Option.map and five times more lines of code compared to the simple version.
Is there a shorter way to write that code?

open System.Xml.Xsl

type HtmlPage = HtmlPage of string
type XmlFile  = XmlFile of  string
type XslFile  = XslFile of  string

type HtmlTransformer =
    {
        HtmlPage :  HtmlPage    option
        XmlFile :   XmlFile     option
        XslFile :   XslFile     option
    }

let toHtmlNoOption (xmlFn:string) (xsltFn:string) (htmlFn:string) =
    try
        let xslt = new XslCompiledTransform()
        xslt.Load xsltFn
        xslt.Transform (xmlFn,htmlFn)
    with _-> ()

let toHtml (sc:HtmlTransformer) =
    try
        let xslt = new XslCompiledTransform()
        let xfn =
            sc.XslFile
            |> Option.map (fun (XslFile xf)  -> xf)
        let xmlFn =
            sc.XmlFile
            |> Option.map (fun (XmlFile xf)  -> xf)
        let htmlFn =
            sc.HtmlPage
            |> Option.map (fun (HtmlPage lp)  -> lp)
        xfn
        |> Option.map xslt.Load
        |> Option.map
            (fun () ->
                htmlFn
                |> Option.map
                    (fun hFn ->
                        xmlFn
                        |> Option.map
                            (fun xFn -> xslt.Transform(xFn,hFn)))
            )
    with
        _ -> None


texts:
Newbie to PHP.

Trying to output the results of an array inside a foreach loop. I have got the following code but I cannot understand what to do with it next.

Mainly;

Where/how do I start and end the php statements?
Is there a better way to format this code?

I want to make it as easy to understand and legible as possible.

I'm not sure how to echo my rows within the specified html below?

My code so far;

<?php foreach ($userResults as $row) : ?>

echo $row['user_id'] here

echo $row['user_name'] here

echo $row['user_email'] here

<?php endforeach; ?>

Any help or advice is appreciated.


texts: Simulating Natural Sorting in MySQL with PHP

texts:
I have a MySQL table which contains product SKUs among other things. PHP powers importing data into this database, managing data through a control panel, displaying the information on the front-end, etc. (For clarity, this is a Magento site.) On the front-end, I need to be able to list SKUs in natural sorting order, however MySQL does not have a natsort method the way PHP does.

There are a number of MySQL only solutions, each with their own problems. The simplest that you see is to cast the string with something like ORDER BY sku + 0 but this only works for the simplest strings. Let's look at more complex options:

MySQL: ORDER BY LENGTH(col), col

The idea here is that test5 is shorter than test10 and will be sorted first. But test10 is alphabetically before test20 so that also is sorted first, giving you test5, test10, test20 which looks correct.

However, this doesn't match PHP's natsort method. For example, test50 will come before test100 but test50a will come after test100 which is incorrect. This is because test50a is longer than test50 and the 5 comes after the 1 when comparing test50a and test100. This should read test50, test50a, test100

PHP: natsort

I have the opportunity for the PHP application (Magento) to create an Index and either totally rebuild it on command, or update it on a SKU-by-SKU basis. At first, my solution was something like this:

// $skus = array() of strings

// Natural sort the SKUs
natsort($skus);

// Reset the keys to be in sequential order by array position
$skus = array_values($skus);

foreach ($skus as $position => $sku) {
     // Assume this is correctly escaped and sent to MySQL
     $sql = "UPDATE database.products SET position = {$position} WHERE sku = '{$sku}'";
}

You could then sort by position.

The problem with this is that any time you change a SKU or add a new SKU you would have to re-sort the entire array again, and update the entire index. (Deleting a SKU wouldn't have an effect.)

PHP: preg_replace_callback + str_pad

I landed on this method:

// $skus = array() of strings

foreach ($skus as $sku) {
     $paddedSku = preg_replace_callback('#\d+#', function($m) {
          return str_pad($m[0], 8, '0', STR_PAD_LEFT);
     }, $sku);

     // Assume this is correctly escaped and sent to MySQL
     $sql = "UPDATE database.products SET padded_sku = '{$paddedSku}' WHERE sku = '{$sku}'";
}

In this case, test50 becomes test00000050 and test50a becomes test00000050a and test100 becomes test00000100. You can then do ORDER BY padded_sku and it will alphanumerically sort correctly. This even works for more complex strings like test50a-abc45

In actuality, I've collected all of these padded SKUs into an array, and then inserted them using a REPLACE (which my indexes in MySQL make possible) in chunks of 500. The padded_sku column can be indexed for speed, and I can insert or change a single SKU at any time without having to rebuild the whole index.

Question

Is there a better way to naturally sort in MySQL that supports test50 coming before test50a coming before test100? I think that with some complex MySQL I could have it doing this preg_replace and str_pad through MySQL functions on the fly, but isn't it faster to calculate this once and store it as a simple string? (Even if it has to go back and forth to PHP to do that?)


texts: Prepare data for a contour plot with matplotlib

texts:
My question concerns the following Python code which is already working. As far as I have seen, there are very elegant solutions of compacting code. Do you have any ideas on how to make the following code look smoother?

mom = [0.,0.13,0.27,0.53,0.67]
strings = ['overview_files/root/file_' + str(e) for e in mom]
myfile = [np.loadtxt(s) for s in strings]
nbinp = len(mom)
nbinomega = len(myfile[0][:,0])

x, y, z = (np.empty(nbinp*nbinomega) for i in range(3))
for i in range(nbinomega):
  for j in range(nbinp):
    i_new = i + j*nbinomega
    y[i_new] = myfile[j][i,0] - 1.4
    x[i_new] = mom[j]
    z[i_new] = myfile[j][i,1]


texts:
Its my first attempt to unit-test in Js. Not yet TDD.
What I can change?

EventsPersistancyService.js:

var Q = require('q');

var EventsPersistancyService = {
  accept: function acceptService(msg) {

    var worker_id = WorkerCacheService.get('some login');
    var app_category = AppCategoryService.get('some');

    var p = Q.all([worker_id, app_category]).then(function () {
      var content = msg.content.toString();
      content = JSON.parse(content);
      return Event.create(content);
    });

    return p;
  }
}

module.exports = EventsPersistancyService;

Unit tests:

"use strict";

var assert = require('assert');
var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require('chai-as-promised');
var sinonChai = require("sinon-chai");
chai.use(chaiAsPromised);
chai.use(sinonChai);
var sinon = require('sinon');
var Q = require('q');

var TPL = {
};

describe('EventsPersistancyService', function () {

  describe('#accept', function () {

    var s1, s2, s3, s4;

    var message = {
      fields: null,
      properties: null,
      content: new Buffer(JSON.stringify(TPL))
    };

    beforeEach(function () {
      s1 = sinon.stub(WorkerCacheService, 'get').returns(Q.resolve(""));
      s2 = sinon.stub(AppCategoryService, 'get').returns(Q.resolve(""));
      s3 = sinon.stub(Event, 'create').returns(Q.resolve(1));
    });

    afterEach(function () {
      sinon.sandbox.restore();
      s1.restore();
      s2.restore();
      s3.restore();
    });

    it('should return error when accept param is null', function () {
      var res = EventsPersistancyService.accept(null);
      return expect(res).to.be.rejected;
    });

    it('should return resolve promise on non error situation', function () {
      var res = EventsPersistancyService.accept(message);
      return expect(res).to.be.not.rejected;
    });

    it('should call WorkerCacheService to get worker_id', function () {
      EventsPersistancyService.accept(message);
      return expect(s1).to.have.been.calledOnce;
    });

    it('should call AppCategoryService to get app_category', function () {
      EventsPersistancyService.accept(message).then();
      return expect(s2).to.have.been.calledOnce;
    });

    it('should call Event.create when all if ok', function () {
      EventsPersistancyService.accept(message).then(function () {
        expect(s4).to.have.been.calledOnce;
      }, function () {
        expect(s4).to.have.been.calledOnce;
      });
    });

    it('should reject when Event.create reject', function () {
      s3.restore();
      s3 = sinon.stub(Event, 'create').returns(Q.reject(1));
      var p = EventsPersistancyService.accept(message);
      return expect(p).to.be.rejected;
    });

    it('should reject when Event.create throw', function () {
      var p = EventsPersistancyService.accept({});
      return expect(p).to.be.rejected;
    });

    it('should reject when WorkerCacheService.get fails', function () {
      s1.restore();
      s1 = sinon.stub(WorkerCacheService, 'get').returns(Q.reject(''));
      var p = EventsPersistancyService.accept(message);
      return expect(p).to.be.rejected;
    });

    it('should reject when AppCategoryService.get fails', function () {
      s2.restore();
      s2 = sinon.stub(AppCategoryService, 'get').returns(Q.reject(''));
      var p = EventsPersistancyService.accept(message);
      expect(p).to.be.rejected;
    });

  });
});


texts: Efficiently read in 2nd column of CSV into List of Lists in Python 3

texts:
I created a function to read in arbitrary numbers of .csv files, their 2nd column only, into a list of lists (or if there is a more efficient data structure, then that). I want it to be efficient and scalable/customizable.
Is there anything in it that can be tweaked and improved?

import os
FILE_NAMES=["DOCS/1.csv","DOCS/2.csv"]

def FUNC_READ_FILES(file_names):
    nr_files=len(file_names)
    filedata=[[] for x in range(nr_files)] # efficient list of lists

    for i in range(nr_files):   # read in the files
        if(os.path.isfile(file_names[i])):
           with open(file_names[i],'r') as f:
              filedata[i]=f.readlines()
        else:
             print("ERROR: FILES ARE MISSING!!!!")
             exit()

    for i in range(nr_files):  # iterate through the files and only keep the 2nd column, remove \n if it's end of line
       for k in range(len(filedata[0])):
        filedata[i][k]=filedata[i][k].strip().split(',')[1]

    return (filedata)

FUNC_READ_FILES(FILE_NAMES)


texts:
I have to develop a class that creates new files. If a file with the given name already exists, it should be renamed by addition of the timestamp to the file name. The file name should be human-readable, so I can use neither UUID nor createTempFile. The code works, but looks too bulky.

public class FileBackup {

    /**
     * Creates new file. If file with given name exists, then backups
     * it by renaming and adding time stamp to file name;
     *
     * @param filePath the fully qualified name of file

     * @return the file on success; otherwise returns null
     *
     * @throws IOException
     */
    public static File backupAndCreateFile(String filePath) throws IOException  {

        File fileToCreate = new File(filePath);

        boolean backupRequired =  fileToCreate.isFile();

        if (backupRequired && !backupFile(fileToCreate)) {
            return null;
        }

        File file = new File(filePath);
        return file.createNewFile() ? file : null;
    }

    private static final String pattern = "-dd_M_yyyy-hh_mm_ss";
    private static final DateFormat dateFormat = new SimpleDateFormat(pattern);
    private static String generateBackupName (String filePath) {
        String name = getFileName (filePath);
        String ext = getFileExtention (filePath);
        return name + dateFormat.format(new Date()) + ext;
    }

    private static String getFileName (String filePath) {
        int i = filePath.lastIndexOf('.');
        return i == -1 ? filePath : filePath.substring(0, i);
    }

    private static String getFileExtention (String filePath) {
        int i = filePath.lastIndexOf('.');
        return i == -1 ? "" : filePath.substring(i);
    }

    private static boolean backupFile (File file) {

        String filePath = file.getAbsolutePath();

        while (true) {

            String backupName = generateBackupName (filePath);
            File backup = new File(backupName);

            if (!backup.isFile()) return file.renameTo(backup);

            // File with generated name exists, so
            // sleep for 0.5 second and try another name
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {return false;}; // never should be here
        }
    }
}


texts:
I've written a Minesweeper program, but my code for generating the buttons is taking much longer than I'd like. Here is the GUI code:

        this.boardPanel.Controls.Clear();
        this.boardValues = new int[mode.size.Width, mode.size.Height];
        this.boardFound = new bool[mode.size.Width, mode.size.Height];
        this.boardButtons = new Button[mode.size.Width, mode.size.Height];
        EventHandler click = new EventHandler(btn_Click);
        for (int x = 0; x < boardButtons.GetLength(0); x++)
        {
            for (int y = 0; y < boardButtons.GetLength(1); y++)
            {
                boardButtons[x, y] = new Button();
                boardButtons[x, y].Size = new Size(Minesweeper.BUTTON_LENGTH, Minesweeper.BUTTON_LENGTH);
                boardButtons[x, y].Location = new Point(x * Minesweeper.BUTTON_LENGTH, y * Minesweeper.BUTTON_LENGTH);
                boardButtons[x, y].Tag = new Point(x, y);
                boardButtons[x, y].Click += click;
                this.boardPanel.Controls.Add(boardButtons[x, y]);
            }
        }
        this.boardPanel.Size = new Size(mode.size.Width * Minesweeper.BUTTON_LENGTH, mode.size.Height * Minesweeper.BUTTON_LENGTH);
        this.Size = new Size(5 + this.boardPanel.Width + 5 + 8, this.tstMain.Height + 5 + this.boardPanel.Height + 5 + this.stsStatus.Height + 30);

As you can see I am creating an EventHandler for a method called btn_Click, outside of the loop, and assigning it to each button. This method reads the Tag field of the clicked button to determine which button as pressed.

In an Intermediate game with a board size of 16x16, generating the buttons takes approximately 2-3 seconds. I know WinForm controls aren't known for the best performance, but is there a way I can generate a number of buttons, assign Event handlers and add them to a panel more efficiently?


texts:
THIS is the link to the problem on SPOJ. I thought it would be better to give the link to the problem instead of me trying to explain as the question is not very clear at first sight.

I was able to clear all the test cases and would like to know if it can be optimized further or anything redundant is there.

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

public class Main
{
    //100000 could be the maximum money that can be paid. thats why choose this
    //as invalid.
    public static int invalid = 100001;
    public static int[] arr = null;
    public static int[][][] dp = null;
    public static int n;
    public static int k;
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t  = Integer.parseInt(br.readLine());
        while(t > 0)
        {
            String[] strArr = br.readLine().split(" ");
            n = Integer.parseInt(strArr[0]);
            k = Integer.parseInt(strArr[1]);
            arr = new int[k + 1];
            strArr = br.readLine().split(" ");
            for(int i = 0 ; i < k ; i++)
            {
                arr[i + 1] = Integer.parseInt(strArr[i]);
            }
            dp = new int[k + 1][n + 1][k + 1];
            for(int i = 0 ; i < k + 1 ; i++)
                for(int j = 0 ; j < n + 1 ; j++)
                    for(int z = 0 ; z < k + 1 ; z++ )
                        dp[i][j][z] = invalid;

            int ans = func2(1,n,k);
            if(ans >= invalid)
                System.out.println(-1);
            else
                System.out.println(ans);

            t--;
        }
    }

    //pos is the index
    //rp is the remaining number of maximum packets that can be bought
    //rw is remaining weight.
    public static int func2(int pos,int rp , int rw)
    {
        if(pos > k)
            return invalid;
        if(rw < 0)
            return invalid;
        if(dp[pos][rp][rw] != invalid)
            return dp[pos][rp][rw];
        if(rw == 0)
            return dp[pos][rp][rw] = 0;
        if(rp == 0)
            return invalid;
        if(pos > rw)
            return invalid;
        if(arr[pos] == -1)
            return dp[pos][rp][rw] = func2(pos + 1,rp,rw);

        //minimum of three scenarios.
        //first scenario : we skip buying the packet at index pos and move to
        //pos + 1.
        //Second scenario : we buy at index pos and again try to buy packet at
        //index pos.
        //third scenario : we buy at index pos and move to pos + 1;

        return dp[pos][rp][rw] = min(func2(pos + 1,rp,rw),  arr[pos] + func2(pos , rp - 1, rw - pos) , arr[pos] + func2(pos + 1,rp - 1,rw - pos));
    }

    /*public static int func(int pos,int rp,int rw)
    {
        if(rw == 0)
            return 0;
        if(rp == 0)
            return invalid;
        if(pos > rw)
            return invalid;
        if(arr[pos] == -1)
            return func(pos + 1,rp,rw);
        return min(func(pos + 1,rp,rw),  arr[pos] + func(pos , rp - 1, rw - pos) , arr[pos] + func(pos + 1,rp - 1,rw - pos));
    }*/

    public static int min(int ... arr)
    {
        int min = arr[0];
        for(int num : arr)
            if(num < min)
                min = num;

        return min;
    }
}

Please go through the question carefully as in the comments of the question as well, people conveyed that it's not framed gracefully.
Ignore function func.


texts:
I there a better way to write this query?  I feel sure it can be done in one statement with joins, but I couldn't get it, and I'm afraid I've made it too slow.  What suggestions do you have?  I'm running it in SQL Server 2000 (yeah, I know, upgrade is coming).

Basically, I want to match estimated and actual costs, but sometimes the estimate is done on 1 cost center, and the actual costs are set to another cost center (hence the possibility of having null in est or act.  I want to get all possible combinations for that job.

ALTER view [dbo].[JobCost_EstVsAct]     --SELECT * FROM JobCost_EstVsAct Where jobnumber = '122773'

as

SELECT JobNumber, CostCenter, sum(Amount) as Est, sum(cost) as Act
FROM
(
SELECT JobNumber, CostCenter, Amount, 0 as cost
FROM Avanti_ActiveJobBudgets AJB

UNION

SELECT jobnumber, costcentre as CostCenter, 0 as Est, cost as Act
FROM Avanti_ActiveCostDetails
) temp
--where cost + Amount > 0     This line is a bug
GROUP by JobNumber, CostCenter
HAVING sum(Amount) + sum(cost) > 0   --bug correction


texts: Filter array elements using variable number of filters

texts:
This is a question generated from a coding challenge, and I solved it, but I'm just not sure it's a great solution, nor am I sure why the first way I was trying didn't work.

Challenge: Implement a function called destroyer().  "You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments."

Some test cases:
- destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1]
- destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"]

So here is the function that passed the test.

  function destroyer(arr) {
    // make a temp array to store iterations of the loop used to filter
    var newArr = [];

    // get the items to filter from the arguments passed.
    // EDIT: changed this for loop to use slice
    var filterItems = Array.from(arguments).slice(1);

    // use the array of items to filter, to filter the 'arr'
    // NOTE:I get a warning about calling a function in a loop. but it works in my lab environment anyhow.
    for (i=0; i < filterItems.length; i++){
      newArr = arr.filter(function(el){ // cannot assign directly to arr here for some reason???
       return el !== filterItems[i] }
     );
    arr = newArr;
    }

    return newArr;
  }

Okay, so calling the function with this, the array passed in argument 1 gets filtered, removing any numbers passed later.

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

What didn't work, is using arr = arr.filter... to iterate over the array passed into the function.  Instead, I first had to output the filter into the temp newArray and then reassign it in the for loop.  That kind of confuses me. if I can change arr with arr = newArr.  Why does that work and not the other way where I output the arr.filter right back into arr?


texts:
Just created my first C++ project, and wondering if I could get some feedback on where to improve? I might swap from arrays to vectors and add alpha beta pruning later, but wanted to first see where I can improve on the base code.
#include <iostream>
#include <cmath>

const char PLAYER_ONE_MARKER = 'X';
const char PLAYER_TWO_MARKER = 'O';
const char UNFILLED_MARKER = ' ';

char board[3][3];
const int MAX_TURNS = sizeof(board);

void drawBoard();
void placeMarker(bool isPlayerOne, int row, int col);
bool checkValidInput(int row, int col);
bool checkWon(int row, int col);

int  main()
{
    int row, col;
    bool isPlayerOneTurn = true;
    int turn = 0;
    bool isGameRunning = true;
    bool isValidInput;

    // fills board with unfilled_marker
    std::fill(&board[0][0], &board[0][0] + sizeof(board) / sizeof(board[0][0]), ' ');

    while (isGameRunning)
    {
        // loops until we get a valid set of input from player
        isValidInput = false;
        do {
            std::cout << "Player " << (isPlayerOneTurn ? "1" : "2") << ", what is your move?\n";
            std::cin >> row >> col;

            isValidInput = !std::cin.fail() && checkValidInput(row, col);
            std::cin.clear();
            std::cin.ignore(10, '\n');

        } while (!isValidInput);

        placeMarker(isPlayerOneTurn, row, col);

        // after we place marker, check if player has won
        if (checkWon(row, col)) {
            std::cout << "Player " << (isPlayerOneTurn ? "1" : "2") << " has won!\n";
            isGameRunning = false;
        }
        else if (++turn >= MAX_TURNS) {
            std::cout << "It's a draw\n";
            isGameRunning = false;
        }
        drawBoard();

        // switches to other player's turn
        isPlayerOneTurn = !isPlayerOneTurn;
    }

    return 0;
}

void drawBoard()
{
    int rows = sizeof(board) / sizeof(board[0]);
    for (int i = 0; i < rows; ++i)
    {
        std::cout << board[i][0] << "  |  " << board[i][1] <<
            "  |  " << board[i][2] << std::endl;

        // draws line between rows
        if (i < rows - 1)
        {
            std::cout << "---------------\n";
        }
    }

}

bool checkValidInput(int row, int col)
{
    if (row < 0 || col < 0 || row > 2 || col > 2) return false;

    // checks if position supplied is already marked
    return board[row][col] == UNFILLED_MARKER;
}

void placeMarker(bool isPlayerOne, int row, int col)
{
    char marker = isPlayerOne ? PLAYER_ONE_MARKER : PLAYER_TWO_MARKER;
    board[row][col] = marker;
}

// given the move played, check if user has won
bool checkWon(int row, int col)
{
    // first check for horizontal/vertical victory cases
    if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) return true;
    if (board[0][col] == board[1][col] && board[1][col] == board[2][col]) return true;

    // for top-left to bottom-right diagonals, row and col must be the same
    // for instance (0, 0) - (1, 1) - (2, 2)
    // for bottom left to top-right, one of th terms must be (0, 2) or (2, 0)
    // hence we can just use abs(row - col) == 2 to test
    if (row == col || std::abs(row - col) == 2) {
        if (board[0][0] == board[1][1] && board[1][1] == board[2][2]
            && board[1][1] != UNFILLED_MARKER) return true;
        if (board[2][0] == board[1][1] && board[1][1] == board[0][2]
            && board[1][1] != UNFILLED_MARKER) return true;
    }

    return false;
}


texts: IMDB website query to find actors by time period

texts:
I'm using data from a database from the IMDB website. The database consists of five relevant tables.

Actor (id, fname, lname, gender)
Movie (id, name, year, rank)
Director (id, fname, lname)
Cast (pid, mid, role)
Movie_Director(did, mid)

It's worth noting that the id column in Actor, Movie & Director tables is a key for the respective table.

Cast.pid refers to Actor.id, and Cast.mid refers to Movie.id.

Here's the prompt and my initial attempt at solving it. Any help in improving/speeding up the query would be greatly appreciated.

/* List all the actors who acted in at least
   one film in 2nd half of the 19th century and
   in at least one film in the 1st half of the 20th century */

    SELECT DISTINCT a.fname, a.lname
    FROM Actor a, Movie m1, Movie m2, Cast c1, Cast c2
    WHERE c1.pid = a.id
    AND c1.mid = m1.id
    AND m1.year BETWEEN 1850 AND 1900
    AND c2.pid = a.id
    AND c2.mid = m2.id
    AND m2.year BETWEEN 1901 AND 1950;


texts:
I'm working on building a website to help people practice English. In this practice, the answer in the blank needs to be validated on hitting enter.

I'd like to know if there is a simpler/better way to write it since I need to use it for a lot of pages.

HTML:

There’s an energy here. At least, I think there is. Is it just that I know this city to be so? That there can be skiing a half hour away on the north shore mountains <input class="fillBlank" type="text" id="one" placeholder="your answer"> there is tennis in the city?

But then, <input class="fillBlank" type="text" id="two" placeholder="your answer"> my walk I took this photo below.

The city is also lush which means that it rains on <input class="fillBlank" type="text" id="three" placeholder="your answer">. Okay, maybe more than occasionally at this time of year.

CSS:

.fillBlank {
width: 100px;
border-radius: 0;
border: none;
background-color: #eff9f7;
padding: 3px;
text-align: center;
}

JS:

 $("#vancouver").ready(function() {
  $(".fillBlank").val("");
  });

// vancouver quiz answer one

var one = document.getElementById("one");
one.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
valone(e);
}
});

function valone(e) {

var one = document.getElementById("one").value;

if (one === "while") {

document.getElementById("one").style.color = "green";
}

else {
document.getElementById("one").style.color = "red";
}
}

// vancouver quiz answer two

var two = document.getElementById("two");
two.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
valtwo(e);
}
});

function valtwo(e) {

var two = document.getElementById("two").value;

if (two === "on") {

document.getElementById("two").style.color = "green";
}

else {
document.getElementById("two").style.color = "red";
}
}

// vancouver quiz answer three

var three = document.getElementById("three");
three.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
valthree(e);
}
});

function valthree(e) {

var three = document.getElementById("three").value;

if (three === "occasion") {

document.getElementById("three").style.color = "green";
}

else {
document.getElementById("three").style.color = "red";
}
}


texts:
So, I have been preparing for an interview and I thought of coding up a Binary search on a Bitonic array for practice. A bitonic array has a bunch of numbers in increasing order at the beginning of the array and then a bunch of numbers in decreasing order after that. And the problem is to find out whether or not a number exists in the Bitonic array.

import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
public class Bitonic{
    private Integer[] array;

    // This is the maximum possible number in the array.
    private int maxPossibleValue = 45645454;

    public Bitonic(int n, int inv)
    {
        // Make a n element array and initialize each position with a random value.
        array = new Integer[n];
        for(int i = 0; i < n; i++){
            array[i] = (int)Math.floor(Math.random() * maxPossibleValue);
        }

        // inv is the inversion point where the numbers stop increasing and start decreasing.
        // To make this artificially happen, I sorted one half of the array in ascending order
        // And the other half in descending.
        Arrays.sort(array, 0, inv);
        Arrays.sort(array, Math.min(inv + 1, n), n, Collections.reverseOrder());

        // Print the array.
        System.out.println(Arrays.toString(array));
    }

    private int finder(int target, int start, int end){
    System.out.printf("Processing: %d to %d\n", start, end);
    int currentPoint = (int)Math.floor(end + start)/2;
    int left = Math.max(start, currentPoint - 1);
    int right = Math.min(end, currentPoint + 1);
    int leftValue = array[left];
    int rightValue = array[right];
    int currentValue = array[currentPoint];
    if(currentValue == target){
        System.out.println("Found the value.");
        return currentPoint;
    }
    if(start == end && currentValue != target){
        return -1;
    }
    if(currentValue > leftValue && currentValue < rightValue){
        // Behind inversion point.
        if(currentValue < target){
            return finder(target, right, end);
        }
        else{
            int result = finder(target, start, left);
            if(result != -1){
                return result;
            }
            return finder(target, right, end);
        }
    }
    else if(currentValue < leftValue && currentValue > rightValue){
        // After inversion point.
        if(currentValue < target){
            return finder(target, start, left);
        }
        else{
            int result = finder(target, right, end);
            if(result != -1){
                return result;
            }
            return finder(target, start, left);
        }
    }
    else{
        // At inversion point or at one of the extreme corners or a plateau.
        int result = finder(target, right, end);
        if(result != -1){
            return result;
        }
        return finder(target, start, left);
    }
}

    public int find(int target){
        // Set up the recursion for the binary search.
        return finder(target, 0, array.length - 1);
    }

    public int get(int location){
        return array[location];
    }
    public static void main(String args[]){
        Scanner reader = new Scanner(System.in);
        int n, inv;
        n = reader.nextInt();
        inv = reader.nextInt();
        Bitonic BitonicArray = new Bitonic(n, inv);

        int targetLoc = reader.nextInt();
        int target = BitonicArray.get(targetLoc);
        System.out.printf("Value Queried: %d\n", target);
        int result = BitonicArray.find(target);
        if(result != -1)
            System.out.printf("Found it at: %d, value at that location: %d", result, BitonicArray.get(result));
        else
            System.out.println("Not found.");

    }
}


texts: FizzBuzz encapsulation In Ruby (identifying and separating concerns)

texts:
I'm working on an article about encapsulation in OOP, and I'm using the FizzBuzz problem to demonstrate what I think is so great about it. I'm hoping to share this with developers that might also be intermediate, as a way to start building a bridge for understanding common OO principles.

To this end, any feedback, criticism, or questions are greatly appreciated.

The concerns I'm trying to extract and encapsulate are:

The printing of the numbers
The iteration of the collection
The logic for determining what should be returned

class FizzNumber

  FIZZ_MAP = {
    "Fizzbuzz" => :fizzbuzz?,
    "Fizz" => :fizz?,
    "Buzz" => :buzz?
  }

  def initialize(number)
    @number = number
  end

  def fizz?
    @number % 3 == 0
  end

  def buzz?
    @number % 5 == 0
  end

  def fizzbuzz?
    fizz? && buzz?
  end

  def fizz_value
    value = FIZZ_MAP.find { |key, value| send(value) }
    value&.first || @number.to_s
  end
end

class FizzBuzzer
  include Enumerable

  def initialize(collection)
    @collection = collection
  end

  def each
    @collection.each do |item|
      yield FizzNumber.new(item)
    end
  end
end

fizzer = FizzBuzzer.new((1..100).to_a)
puts fizzer.map(&:fizz_value).join("\n")


texts: Continuously receive messages async from Azure Service Bus Queues

texts:
I'd like to get input on my approach of continuously receiving messages from an Azure Service Bus queue using the async part of the library.
My main concern being whether its "safe" to use Task.Factory.StartNew to process the incoming messages and then continue to call the Action's to continue receiving new messages.

The processor class is started like this:

public void Start()
{
    ThrowIfDisposed();
    lock (_lockObject)
    {
        Trace.WriteLine(string.Format("Started '{0}' allocation.", _projectSettings.Name));

        _cancellationSource = new CancellationTokenSource();
        Task.Factory.StartNew(ReceiveAllocationMessages, _cancellationSource.Token);
    }
}

And then the actual continuous receival of messages from the (Azure Service Bus) QueueClient (from the Microsoft.ServiceBus.Messaging namespace):

private void ReceiveMessage()
{
    Task.Run(async () =>
    {
        //Receive a new message async within 1 minute
        return await _queueClient.ReceiveAsync(TimeSpan.FromMinutes(1));
    })
    .ContinueWith(t =>
    {
        if (t.Result != null)
        {
            //The result is not null so we process the Brokered Message
            Task.Factory.StartNew(() =>
            {
                ProcessMessage(t.Result)
                ReceiveNextMessage();
            }, _cancellationSource.Token);
        }
        else
        {
            // Continue receiving and processing
            // new messages until told to stop.
            ReceiveNextMessage();
        }
    });
}

private void ReceiveNextMessage()
{
    if (_cancellationSource.IsCancellationRequested == false)
    {
        //Continue to receive new messages every 1 minute
        Task.Delay(TimeSpan.FromMinutes(1))
            .ContinueWith(t => ReceiveMessage());
    }
}

When the process is stopped or disposed the Stop method is called in order to cancel the CancellationTokenSource as shown here:

public void Stop()
{
    lock (_lockObject)
    {
        using (_cancellationSource)
        {
            if (_cancellationSource != null)
            {
                _cancellationSource.Cancel();
                _cancellationSource = null;
            }
        }

        Trace.WriteLine(string.Format("Stopped '{0}' allocation.", _projectSettings.Name));
    }
}

Does this seem like a reasonable way to go about implementing continuous receival of messages in an async fashion?

UPDATE: I posted a gist with the code from above polished and put into a class. Hopefully improves readability Gist of the queue Processor class


texts: Cut float numbers in a stream (putchar, getchar) and in a string

texts:
For example, the following row:

"a+12.3456-b-0.456789+1.3-45678"

will be transformed into

"a+12.34-b-0.45+1.3-45678"

That is, we need to cut out the figures after the point from the third figure. The signal of the row's end is the sign '&'.

With the getchar and putchar functions:

char c = 0, c_ = 0,flag=0;
while ((c = getchar()) != '&')
{

    if (isdigit(c) && !(isdigit(c_)))
    {
        flag = 1;
    }

    putchar(c);

    if (flag)
    {
        while ((c = getchar()) != '.') putchar(c);

        putchar(c);

        c = getchar();
        putchar(c);
        if (!isdigit(c)){ flag = 0; continue; }

        c = getchar();
        putchar(c);
        if (!isdigit(c)){ flag = 0; continue; }

        while (isdigit(c=getchar()));
        putchar(c);
        flag = 0;
    }
    c_ = c;
}

Using strings:

char s[100] = { 0 }, s1[100] = { 0 };
inti = 0, j = 0;

gets(s);

while (s[i] != '&')
{
    if (isdigit(s[i])
    {
        while (s[i] != '.')
        {
            s1[j++] = s[i++];
        }

        s1[j++] = s[i];

        s1[j++] = s[++i];
        if (!isdigit(s[++i])) continue;

        s1[j++] = s[i];
        if (!isdigit(s[++i])) continue;

        while (isdigit(s[++i]));

        continue;

    }

    s1[j++] = s[i++];
}
puts(s1);

The programs are confusing and ugly, but they're the best ones I ended up with. Please suggest a better algorithm or change mine to help it make more sense.


texts: Linux HDD/CPU Temperature Logging Bash Script to run every minute in crontab

texts:
I wrote a simple script to log HDD and CPU temps to a log file.
If those temperatures reach a threshold, it will shutdown the server. I also made the script make sure the log files don't get over a certain file size. Any ways to improve the code would be greatly appreciated, as I am a noob to programming.

#!/bin/bash
# Check HDD Temps, CPU temp.. shut down server if any exceed acceptable limit
# Using hddtemp to check HDD temps, sensors command to check CPU temp.
date=$(TZ='America/Los_Angeles' date)
HDD1=$(sudo hddtemp /dev/sdb | cut -d":" -f1,2)
HDD2=$(sudo hddtemp /dev/sdc | cut -d":" -f1,2)
T1=$(sudo hddtemp /dev/sdb | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2)
T2=$(sudo hddtemp /dev/sdc | cut -d":" -f3 | cut -d" " -f2 | cut -c1-2)
CPU1=$(sensors | grep "Core" | head -1 | cut -d"+" -f2 | cut -d"." -f1)
CPU2=$(sensors | grep "Core" | tail -1 | cut -d"+" -f2 | cut -d"." -f1)
base_file='/home/brandon/logs/temp1.log'
file='/home/brandon/logs/temp'
log='.log'
error='.error'

find_lowest_file_num() {
        local lowest_file_num=$(ls /home/brandon/logs/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | tail -1)

        if [ -z "$lowest_file_num" ]
        then
                touch $base_file
                echo 1
        else
                echo $lowest_file_num
        fi
}

find_highest_file_num() {
        local highest_file_num=$(ls /home/brandon/logs/ | grep temp | cut -d"p" -f2 | cut -d"." -f1 | sort -rn | head -1)

        # if highest_file_num is empty, that means there is no temp files, so create one
        if [ -z "$highest_file_num" ]
        then
                touch $base_file
                echo 1
        #else return highest_file_num
        else
               echo $highest_file_num
        fi
}

highest_file_num=$(find_highest_file_num)
lowest_file_num=$(find_lowest_file_num)

get_curr_highest_file() {
        local h=${file}${highest_file_num}${log}
        echo $h
}

get_curr_lowest_file() {
        local l=${file}${lowest_file_num}${log}
        echo $l
}

curr_file=$(get_curr_highest_file)

echo "HDD1: ${HDD1}  Temp:${T1}C     ${date} " >> $curr_file
echo "HDD2: ${HDD2}  Temp:${T2}C     ${date} " >> $curr_file
echo "CPU Core 1 Temp:${CPU1}C     ${date} " >> $curr_file
echo "CPU Core 2 Temp:${CPU2}C     ${date} " >> $curr_file

#if files get bigger than 1000k, make a new one
if [ $(du -k $curr_file | cut -f1) -gt 1000 ]
then
        let "highest_file_num++"
        touch $(get_curr_highest_file)
fi

if [ $(du -k /home/brandon/logs | cut -f1) -gt 100000 ]
then
        rm -f $(get_curr_lowest_file)
fi

if [ $T1 -gt 50 ] || [ $T2 -gt 50 ] || [ $CPU1 -gt 80 ] || [ $CPU2 -gt 80 ]
then
        echo "HIGH TEMPS DETECTED!!! HDD1 Temp: ${T1}C    HDD2 Temp: ${T2}C     ${date}" >> ${curr_file}${error}
        echo "CPU1: ${CPU1}C, CPU2: ${CPU2}           ${date}" >> ${curr_file}${error}
        echo "Shutting down..." >> ${curr_file}${error}
        sudo shutdown now
fi


texts: Choosing a CSS class based on an HTTP status code

texts:
I was having a discussion with my coworker about a function that returns either an empty string, or a string of a css class. The function is passed an object which has an HTTP status code, and then depending on that statusCode, it returns a value. We couldn't agree which is cleaner.

He wanted the function written as so:

function getCssClass(options) {
  var statusCodeCssClass = '';
  var statusCode = parseInt(options.statuscode, 10);

  if ((statusCode >= 100 && statusCode < 200) || statusCode >= 400) {
    statusCodeCssClass = 'text-danger';
  }
  return statusCodeCssClass;
};

And I wanted it written as so:

function getCssClass(options) {
  var statusCode = parseInt(options.statuscode, 10);
  if ((statusCode >= 100 && statusCode < 200) || statusCode >= 400) {
    return 'text-danger';
  }
  return '';
};

The main difference is that I don't think the initial empty variable should be there, and he does. His argument is that the variable makes it easier to read, and my argument is that the variable obfuscates the function.

I know it's splitting hairs, but I was unable to find an answer in the Clean Code book or on Google about unnecessary variable declarations.

Can someone tell me why one is better than the other?


texts: Multi-page form with each step loaded via Ajax

texts:
I've building a multi-step form that saves data in multiple models. The "base" or parent model is the Venue, and has_one or has_many other models. In the screen below, the "Basic Information" tab is the only one which is mandatory to fill. Once that is saved, a row is generated in the Venue table in the database, and the Venue.id is used in the remaining tabs for the associations. The other tabs are "good to have" data. When I click on Save Changes, the form data is POSTed via ajax and a success message div is shown, and I avoid reloading the page.

In order to render only the form when the different tabs are clicked, I've used Ajax. My _form.html.erb looks like this:

<%= link_to 'Basic Information', {:action => 'new_basic'}, remote: true %>

<%= link_to 'Function Spaces', {:action => 'new_halls'}, remote: true %>

<%= link_to 'Pricing & Terms', {:action => 'new_pricing'}, remote: true %>

<%= link_to 'Amenities', {:action => 'new_amenities'}, remote: true %>

<%= link_to 'Account Settings', {:action => 'new_settings'}, remote: true %>

      <%= render partial: 'venues/basic', locals: { :venue => @venue } %>

For each tab, I created:

Two .js.erb files - e.g: new_basic.js.erb, edit_basic.js.erb
One partial - e.g: _basic.html.erb

Both the .js.erb files have the same one liner code plus any javascript specific to that form:

$("#venueContent").html('<%=j render partial: 'venues/basic', locals: { :venue => @venue } %>')

The partial file will have the actual form code. The files for the other tabs are similar.

My controller looks like this:

class VenuesController < ApplicationController
  #new, index, show and other actions are unchanged from default, snipped here for brevity

  def new_basic
    @venue = Venue.new
    @venue.build_address
    @venue.build_contact

    respond_to do |format|
      format.js   #new_basic.js.erb
    end
  end

  def new_halls
    @venue = Venue.new
    @hall = Hall.new
    #@hall.venue_id = @venue.id

    respond_to do |format|
      format.js   #new_halls.js.erb
    end
  end

  def create
    @venue = Venue.new(params[:venue])

    respond_to do |format|
      if @venue.save
        format.html { redirect_to @venue, notice: 'Venue was successfully created.' }
        format.json { render json: @venue, status: :created, location: @venue }
      else
        format.html { render action: "new" }
        format.json { render json: @venue.errors, status: :unprocessable_entity }
      end
    end
  end

  def edit_basic
    @venue = Venue.find(params[:id])

    respond_to do |format|
      format.js   #edit_basic.js.erb
    end
  end

  def edit_halls
    @venue = Venue.find(params[:id])

    respond_to do |format|
      format.js   #edit_halls.js.erb
    end
  end
end

I did this in my routes.rb:

resources :venues do
    member do   #member - requires an ID
      get 'edit_basic'
      get 'edit_halls'
      ...
    end
    collection do   #works on a collection, does not require an ID
      get 'new_basic'
      get 'new_halls'
      ...

    end
end

This works so far, but for 5 tabs, I've 15 files. Also, in my _form.html.erb, I've to write code to distinguish between new and edit and link to that action correctly. I'm not sure how well it will work, but before I go down that route, this whole approach looks hackish. Am I doing this the RAILS way? Is there a better way to do this?


texts: Special summation of integer array elements

texts:
I looked at this question and thought that I could find a much simpler way of doing this, here is the criteria that was given:

  My current task is to find a score from an array where the highest/lowest scores have been taken away, and if the highest/lowest occur more than once (ONLY if they occur more than once), one of them can be added:

  E.g. int[] scores = [4, 8, 6, 4, 8, 5]

  therefore the final addition will be \$\sum{4,8,6, 5} = 23 \$.

  Another condition of the task is that LINQ cannot be used, as well as any of the System.Array methods

Here is what I came up with: (Link to Answer)

static void Main(string[] args)
{
    // take an array and sum the distinct numbers
    int[] numberArray = { 4, 8, 6, 4, 8, 5 };
    int[] numberArray2 = { 4, 4, 5, 6, 8, 8 };

    Console.WriteLine(sumSpecial(numberArray).ToString());
    Console.WriteLine(sumSpecial(numberArray).ToString());

    Console.ReadLine();
}

static int getHighestScore(int[] integerArray)
{
    var high = 0;
    foreach (int number in integerArray)
    {
        high = high < number ? number : high;
    }
    return high;
}

static int getLowestScore(int[] integerArray)
{
    var low = int.MaxValue;
    foreach (int number in integerArray)
    {
        low = low > number ? number : low;
    }
    return low;
}

static int sumWithoutHighAndLowScores(int[] integerarray)
{
    int sum = 0;
    int high = getHighestScore(integerarray);
    int low = getLowestScore(integerarray);
    foreach (int number in integerarray)
    {
        if (number != high && number != low)
        {
            sum += number;
        }
    }
    return sum;
}

//sum of numbers using high or low only if there is a duplicate of high or low
static int sumSpecial(int[] integerArray)
{
    var sum = sumWithoutHighAndLowScores(integerArray);
    var high = getHighestScore(integerArray);
    var low = getLowestScore(integerArray);

    var highs = 0;
    var lows = 0;
    foreach (int number in integerArray)
    {
        if (number == high) { highs++; }
        if (number == low) { lows++; }
    }
    if (lows > 1) { sum += low; }
    if (highs > 1) { sum += high; }

    return sum;
}

What could be done better or more efficiently without losing the intentions of the exercise?


texts: Implementing min of 3 numbers in Mic-1 code

texts:
I have the following algorithm to find a minimum of three input numbers:

min(a,b,c):
   x := a
   if b < x then x := b
   if c < x then x := c
   return x
end min(a,b,c)

I'm trying to implement a Mic-1 micro code following the algorithms above:

OP1, OP2, OP3 = any 16 bit 2s complement value

OPRES: 0
      .LOC 50
main: LODD OP1: push
      LODD OP2: push
      LODD OP3: push
      CALL min:
      INSP 2
      STOD OPRES
      HALT
min:  LODL 1; OP1
      SUBL 2; OP2 - OP1
      JPOS op1small
      SUBL 3; OP3 - OP1
      JPOS op1small
op1small:
      LODL 1
      RETN ; OP1

I'm pretty new to Mic-1 and would like to get any input on this Mic-1 code above. Is there a better or shorter way I can find a min of three numbers in Mic-1?


texts:
I came across this problem in a career cup. Below I have the questions and the Java solution. I was wondering if anyone could scrutinize my code and tell me if there are any improvements, or better coding practices that I should know, as I am working on being able to produce proficient code.

Problem statement:

  Write a program to accept a nonempty string of alphanumeric characters. Define a run as a consecutive sequence of a single character. For example, aaaa is a run of length \$4\$. The program will print the longest run in the given string. If there is no single longest run, then you may print any of those runs whose length is at least as long as all other runs in the string.

Example input: a

Example output: a

Example input: aab

Example output: aa

Example input: abbbbbcc

Example output: bbbbb

Example input: aabbccdd

Example output: aa

Solution:

public class StringRunCount {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(maxRun("aaabbbbbbbbcccccc"));
    }

    public static int maxRun(String testString) {
        int len = testString.length();
        String substr = "";
        for (int i = 0; i < len;) {
            char current = testString.charAt(i);
            String tempSubstr = "" + current;
            while ((i + 1) < len && (current == testString.charAt(i + 1))) {
                tempSubstr = tempSubstr + testString.charAt(++i);
            }

            if (tempSubstr.length() >= substr.length()) {
                substr = tempSubstr;

            }
            i += 1;
        }
        System.out.println(substr);
        return substr.length();
    }

}


texts: Accessing a String value from multiple threads without synchronization

texts:
I'm looking for some input here.  I have a class that contains a value which is updated every few seconds by a method within that class.  Right now, access to this value across multiple threads is done via synchronization, which I would like to eliminate.  Would this make sense?

class DataSegment {

    private MetricsUpdater metrics = new MetricsUpdater.getInstance();

    public String printValues() {
        StringBuilder sb = new StringBuilder();
        sb.append(value1);
        sb.append(morevalues);
        sb.append(metrics.myValue); // this is the value that's currently synchronized
        return sb.toString();
    }
}

class MetricsUpdater {

    private String myValueSynchronized;
    public String myValue;

    public static MetricsUpdater getInstance() {
        if (theInstance == null) {
            theInstance = new MetricsUpdater();
        }
        return theInstance;
    }

    // this runs on a timer but to keep it simple I'll just define the method...
    private void updateMetrics() {

        synchronized(myValue) {
            // also, to keep things simple, I've replaced all of the actual logic with a method called someMethodToUpdateMyValue()
            myValueSynchronized = someMethodToUpdateMyValue();
            myValue = myValueSynchronized;
        }
    }
}

There can be many instances of DataSegment all reading from myValue, but the metrics class is a singleton.  myValue only updates every 5 seconds or so and only MetricsUpdater is allowed to write to it.  Does that make sense?

Does it even need to be synchronized at all if all of the other threads are only allowed to read it?


texts:
At some point, I have this function which updates a color picker according the the mouse position, according to whether the user clicked a mouse button and according to its previous state:

updateColorPickerState :: ColorPicker -> (GLfloat, GLfloat) -> Bool -> ColorPicker
updateColorPickerState c (x,y) mouseClicked = if isPointWithinColorPicker c (x, y)
                                                then if mouseClicked
                                                  then if state c == Opened
                                                    then c {state = Idle, selectedColor = getColorAt (x',y')}
                                                    else c {state = Opened}
                                                  else if state c == Opened
                                                    then c
                                                    else c {state = Hovered}
                                                else if state c == Opened
                                                  then if mouseClicked
                                                    then c {state = Idle}
                                                    else c
                                                  else c {state = Idle}
                                              where (posX, posY) = pos c
                                                    (sizeX, sizeY) = openedSize c
                                                    x' = truncate ((x - posX) * 25 / sizeX)
                                                    y' = truncate (((-y) - posY) * 11 / sizeY)

How can I change the if-then-else tree to something more readable?


texts: Searching for pairs of integers that satisfy primality and divisibility conditions

texts:
I wrote a program in Python 3 to check all tuples of the form (s,t) where s and t are positive integers satisfying three conditions:

The inequalities s <= t^2 and t <= s^2 hold, and the value s+t divides st(s+1)(t+1);
The value of s+1 is prime;
The inequalities both s * [math.ceil( math.ceil( (t^2)/(s+1) ) * ((s+1)/t) )] > s(s+t) and s > t hold.

I'm interested in how often a tuple (s,t) satisfies each of these conditions in turn; that is, how often a tuple meets condition (1), versus meeting both (1) and (2), versus meeting (1) - (3).

import math

def IsPrime(n):
# This returns True if a number is prime, and False if the number is composite.
    if n % 2 == 0 and n > 2:
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

def IsGQ(s,t):
# This checks the divisibility condition.
    return (s*t*(s+1)*(t+1)) % (s+t) == 0 and s <= t**2 and t <= s**2

def IsNotTransitive(s,t):
    n = math.ceil((t**2)/(s+1))
    k = math.ceil(n*((s+1)/t))
    return (s*k) > t*(t+s) and s > t

rng = 1000 # The upper limit that `t` will iterate up to
quads = 0 # Counter for tuples (s,t) that satisfy conditions (1) and (2)
prime_quads = 0 # Counter for tuples (s,t) that satisfy conditions (1) - (3)
intransitive_quads = 0 # Counter for tuples (s,t) that satisfy conditions (1) - (4)

# The next 5 lines place all prime numbers up to rng^2 into a list.
# Ideally, this cuts down on how many times s+1 has to be checked to be a prime.
primes = []
for i in range(1, rng**2):
    if IsPrime(i):
        primes.append(i)

for t in range(4, rng + 1): # Due to project details, I don't care about t<4.
    if t % 50 == 0:
        print("We have reached t = " + str(t) + ".")
    for s in range(2, t**2 + 1): # To satisfy condition (1), I don't want s to iterate above t^2
        if IsGQ(s,t): # Condition (1) and (2)?
            quads += 1
            if s+1 in primes:            # Condition (3)?
                prime_quads += 1
                if IsNotTransitive(s,t): # Condition (4)?
                    intransitive_quads += 1

print(str(quads))
print(str(prime_quads))
print(str(intransitive_quads))

Currently, this runs to completion in over 10 minutes for rng = 1000. Ideally, running this for rng = 10000 in a reasonable amount of time is my current goal; computing these numbers for the value rng = 100000 is my most optimistic goal.

Is there any way to reorder my iteration or change my method of checking for primeness that could be more efficient? It seems that the time for s+1 in primes to complete grows quadratically with rng. Since, after a certain point, s+1 will be less than every value in primes that hasn't been checked yet, would it be better to write my own "in" function along the lines of

def CheckPrime(s, primes):
    for n in primes:
        if s+1 == n:
            return True
        elif s+1 < n:
            return False

or would this still be slower than the current code?

Note: IsPrime comes from this Stack Overflow answer.


texts: Link shortener application - return the "following" string

texts:
I'm working on developing an application to shorten links. Part of that requires me to be able to get the "next" string based on an allowed character ranges, as if we were counting up. Characters go from A-Z to a-z to 0-9. Some samples:

"A" => "B"
"AA" => "AB"
"AZ" => "Aa"
"Az" => "A0"
"A9" => "BA"
"999" => "AAAA"

I've written a small class to accomplish this. My main concerns are the way I've hard-coded the ranges, and I'm not sure if doing this recursively made the most sense.

package proceduralstring;

/**
 * Char succession: A-Z a-z 0-9
 * @author User
 *
 */
public class ProceduralStringCreator {

    public static String getFirst(){
        return "A";
    }

    public static String getFirst(int minLength){
        StringBuilder result = new StringBuilder();
        for(int i=0; i<minLength; i++){
            result.append("A");
        }
        return result.toString();
    }

    public static String getNext(String current) throws BadFormatException{
        if(!current.matches("[a-zA-Z0-9]+")){
            throw new BadFormatException("String contains illegal characters.");
        }
        if(current.matches("9{"+current.length()+"}")){
            return getFirst(current.length()+1);
        }
        StringBuilder result = new StringBuilder(current);
        replaceWithNext(result, result.length()-1);
        return result.toString();
    }

    private static StringBuilder replaceWithNext(StringBuilder toReplace, int index){
        char currentChar = toReplace.charAt(index);
        if(currentChar != '9'){ //base case
            if(currentChar != 'z' && currentChar != 'Z'){
                toReplace.replace(index, index+1, ((char)(currentChar+1))+"");
            }else{
                if(currentChar == 'z'){
                    toReplace.replace(index, index+1, "0");
                }else if(currentChar == 'Z'){
                    toReplace.replace(index, index+1, "a");
                }
            }
            return toReplace;
        }else{ //recursive case
            toReplace.replace(index, index+1, "A");
            return replaceWithNext(toReplace, index-1);
        }
    }
}

The code is tested and works as intended (the exception is the desired behavior, as there is an invalid character):

package proceduralstring;

public class ProcStringTest {

    public static void main(String[] args) throws BadFormatException {
        System.out.println("getFirst: "+ProceduralStringCreator.getFirst());
        System.out.println("getFirst(5): "+ProceduralStringCreator.getFirst(5));
        System.out.println("Next of A: "+ProceduralStringCreator.getNext("A"));
        System.out.println("Next of AA: "+ProceduralStringCreator.getNext("AA"));
        System.out.println("Next of AAA: "+ProceduralStringCreator.getNext("AAA"));
        System.out.println("Next of A9: "+ProceduralStringCreator.getNext("A9"));
        System.out.println("Next of Adhs3hdfh9: "+ProceduralStringCreator.getNext("Adhs3hdfh9"));
        System.out.println("Next of 9: "+ProceduralStringCreator.getNext("9"));
        System.out.println("Next of 99: "+ProceduralStringCreator.getNext("99"));
        System.out.println("Next of Aas9s99: "+ProceduralStringCreator.getNext("Aas9s99"));
        System.out.println("Next of 9z9999: "+ProceduralStringCreator.getNext("9z9999"));
        System.out.println("Next of 9Z9999: "+ProceduralStringCreator.getNext("9Z9999"));
        System.out.println("Next of AUHR(#H: "+ProceduralStringCreator.getNext("AUHR(#H"));
    }

}

Output:

getFirst: A
getFirst(5): AAAAA
Next of A: B
Next of AA: AB
Next of AAA: AAB
Next of A9: BA
Next of Adhs3hdfh9: Adhs3hdfiA
Next of 9: AA
Next of 99: AAA
Next of Aas9s99: Aas9tAA
Next of 9z9999: 90AAAA
Next of 9Z9999: 9aAAAA
Exception in thread "main" proceduralstring.BadFormatException: String contains illegal characters.
    at proceduralstring.ProceduralStringCreator.getNext(ProceduralStringCreator.java:24)
    at proceduralstring.ProcStringTest.main(ProcStringTest.java:18)
Picked up JAVA_TOOL_OPTIONS: -Duser.language=en