texts: Minimise function with single minimum and no maximums

texts:
I'm learning F#. I wrote a function to minimise a function with a single minimum and no maximums. At the bottom I test it on Math.Cos.

What do you think? I've wrote it pretty much as I would in an imperative language. Could it be done more functionally?

/// <summary>Assuming f is a continuous function with a single minimum and
/// no maximums in (lower,upper), find the minimum point.</summary>
let rec minimise f (lower:float) (upper:float) =
    let lmid = (2.0*lower+upper)/3.0
    let umid = (lower+2.0*upper)/3.0
    if lmid = lower && umid = upper then
        Seq.minBy f [lower; upper]
    else if f lmid < f umid then
        minimise f lower umid
    else
        minimise f lmid upper

let solution = minimise Math.Cos 0.0 6.0
printf "solution: %g" solution
printf "absolute error: %g" (solution - Math.PI)


texts: (Java) Read .txt and organize activities for hours / minutes

texts:
Doubts in logic to generate the output file according to the example
I need that even if he reaches the total_min <720 condition he continues to travel the lines. 720 is the total number of minutes before lunch, when reached, it should separate the activities that should be performed after lunch (lunch must be inserted manually).

I need to make a system that reads a TXT file (intput.txt).
This file has several lines.
Each line an activity with execution time (30min, 45min, 60min)
Activities should start at 9 am.
Half day (12:00) lunch break
Generate a TXT with organized activities (output.txt)

  intput.txt

Correr 60min
Estudar 30min
Ler 45min
Escrever 60min
Caminhar 45min
Jogar 30min

  Example how the output.txt file should look

09:00 Correr 60min
10:00 Estudar 30min
10:30 Ler 45min
11:15 Caminhar 45min
12:00 Almoço 60min
13:00 Jogar
(...)

  My code:

    public static void main(String[] args) throws IOException {
    // TODO code application logic here

    ArrayList<String> antes_almoco = new ArrayList<String>();
    ArrayList<String> depois_almoco = new ArrayList<String>();

    int total_min = 540;
    int horas = total_min / 60;
    int minutos = total_min % 60;
    String trinta = "30min";
    String quarentaCinco = "45min";
    String sessenta = "60min";
    boolean trinta_min = false;
    boolean quarentaCinco_min = false;
    boolean sessenta_min = false;
    String path = "C:\\input.txt";
    String outputDir = "C:\\output.txt";

    FileReader arq = new FileReader(path);
    BufferedReader lerArq = new BufferedReader(arq);
    String linha;

    //Output
    File file2 = new File(outputDir);
    FileWriter arq_output = new FileWriter(file2, true);
    PrintWriter gravarArq = new PrintWriter(arq_output);

    if (!file2.exists()) {
        file2.createNewFile();
    }

    while ((linha = lerArq.readLine()) != null) {

        trinta_min = linha.toLowerCase().contains(trinta.toLowerCase());
        quarentaCinco_min = linha.toLowerCase().contains(quarentaCinco.toLowerCase());
        sessenta_min = linha.toLowerCase().contains(sessenta.toLowerCase());

        if (sessenta_min == true) {
            total_min += 60;
            if (total_min < 720) {
                antes_almoco.add(linha);
            } else if (total_min > 720) {
                depois_almoco.add(linha);
            }
        }

        if (trinta_min == true && total_min < 720) {
            total_min += 30;
            if (total_min < 720) {
                antes_almoco.add(linha);
            } else if (total_min > 720) {
                depois_almoco.add(linha);
            }
        }

        if (quarentaCinco_min == true && total_min < 720) {
            total_min += 45;
            if (total_min < 720) {
                antes_almoco.add(linha);
            } else if (total_min > 720) {
                depois_almoco.add(linha);
            }
        }

        if (total_min == 720) {
            total_min += 60;
            antes_almoco.add("12:00 Almoço");
        }
    }

    for (String cont : antes_almoco) {
        System.out.println(cont);
        gravarArq.printf("%d:%02d %s \n", horas, minutos, cont);
    }
    for (String cont : depois_almoco) {
        //System.out.println(cont);
        gravarArq.printf("%d:%02d %s \n", horas, minutos, cont);
    }
    lerArq.close();
    gravarArq.close();
    arq.close();
}


texts: Pausing and resuming a concurrent database update queue

texts:
I have a class DatabaseQueue which asynchronously runs SQLite updates that it takes from a LinkedBlockingQueue.

I implemented a pausing mechanism for this class which should ideally stop the execution of the queue as soon as possible and then wait for it to be unpaused before executing more queries.

I'm very new to concurrent programming but I managed to get this working using multiple ReentrantLock's and Condition's. This seems very verbose and clumsy though, especially with all the lock()'s and unlock()'s.

In addition to this, I also don't like how I have to execute an additional dummy query just to get the executor thread to continue its loop. What would be a better way to implement this?

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DatabaseQueue {

    private static final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
    private static final QueueExecutor executor = new QueueExecutor();

    private static boolean locked = false;
    private static ReentrantLock lockAttempted = new ReentrantLock();
    private static ReentrantLock lockAcquired = new ReentrantLock();
    private static Condition attempted = lockAttempted.newCondition();
    private static Condition acquired = lockAcquired.newCondition();

    public static void start() {
        if (locked) {
            locked = false;
            lockAttempted.lock();
            attempted.signal(); //Signal to resume queue execution
            lockAttempted.unlock();
        } else {
            executor.start();
        }
    }

    public static void pause() {
        locked = true;
        if (queue.isEmpty()) {
            queue.add("SELECT 1");
        }
        lockAcquired.lock();
        acquired.awaitUninterruptibly(); //Wait for the lock to be acquired
        lockAcquired.unlock();
    }

    public static void queue(String update) {
        queue.add(update);
    }

    public static class QueueExecutor extends Thread {

        public QueueExecutor() {
            setName("Database Queue Executor");
            setDaemon(true);
        }

        @Override
        public void run() {
            Connection connection = Database.getConnection();
            while (true) {
                try {
                    if (locked) {
                        lockAcquired.lock();
                        acquired.signal(); //Signal that the lock has been acquired
                        lockAcquired.unlock();
                        lockAttempted.lock();
                        attempted.awaitUninterruptibly(); //Wait for the lock to be released
                        lockAttempted.unlock();
                    }
                    String update = queue.take();
                    connection.createStatement().executeUpdate(update);
                    Database.update(update);
                } catch (InterruptedException | SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}


texts: Game boot to some operations every second

texts:
I am building game, like Ogame, or Ikariam where you can play with other users in real-time. You train some soldiers, and build some vehicles or buildings. Every building or vehicle has some level. If a building has a higher level you must wait longer to use it etc. I will be grateful for any comments, especially about Scala language.

import java.text.SimpleDateFormat
import java.util.Date

import com.redis._

object worker extends App {

    override def main(args: Array[String]): Unit = {
        println("Worker start...")
        val r = new RedisClient("localhost", 6379)
        var i: Int = 0

        while (true) {
            Thread.sleep(1000)
            i = i + 1
            val numbers: List[Int] = getUsers(r)
            checkQueue(r, numbers)
        }
    }

    private def checkQueue(r: RedisClient, numbers: List[Int]): Unit = {
        val d1 = new Date()
        val format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val now = new Date()
        for (nr <- numbers) {
            val ranges = r.hkeys("user_" + nr + ":soldier:queue_time")
            ranges match {
                case Some(ss) => for (range <- ss) {
                    val added_time = r.hget("user_" + nr + ":soldier:queue_time", range)
                    val saved = format.parse(added_time.get)
                    val diff = (now.getTime - saved.getTime) / 1000 // diff in sec
                    val interval = r.hget("user_" + nr + ":soldier:interval", range)
                    val modulo = diff % interval.get.toInt
                    if (modulo == 0) {
                        val queue_amount = r.hget("user_" + nr + ":soldier:queue_amount", range)
                        if (queue_amount.get.toInt >= 1) {
                            r.hincrby("user_" + nr + ":soldier:amount", range, 1)
                            r.hincrby("user_" + nr + ":soldier:queue_amount", range, -1)
                        }
                    }
                }
                case None =>
            }
        }
        val d2 = new Date()
        println("loop time: " + (d2.getTime - d1.getTime) + " milliseconds")
    }

    private def getUsers(r: RedisClient): List[Int] = {
        val list = r.keys("*user_*:soldier:interval*")
        var numbers = List[Int]()

        list match {
            case Some(s) => for (k <- s) {
                val key = k.get
                val nr = key.replaceAll("[^0-9?]", "")
                numbers = nr.toInt :: numbers
            }
            case None =>
        }
        numbers
    }
}


texts:
I have recently started using Ruby and would like to hear your take on the following piece of code.

class Generator

  def initialize
    @context = nil
  end

  def start(params)
    @context = Context.new params
    image = create_image
    if cache_update_request?
      upload image
    end
    return image
  end

  def create_image
    composer = Composer.new @context
    execution_context = ExecutionContext.new(@context, composer)
    execution_context.render
  end

  def upload(image)
    uploader = CompositorCommons::CacheUpdater.new
    filename = @context.parameters[:cache]
    location = 'dual/' + filname
    type = 'image/jpeg'
    uploader.upload(image,location,type)
  end

  def cache_update_request?
    @context.parameters.has_key?(:cache)
  end

end


texts: Removing duplicates from an unsorted Array

texts:
I have written this program to remove the duplicates from an unsorted array. Please review and give me your input on how I can improve it a little more.

public static void main(String[] args) {

    int[] arr = {4, 3, 4, 2, 6, 1, 1, 7, 6, 8, 9, 9, 1, 1};

    // perform quick sort for o(n log n) time.
    quickSort(arr, 0, arr.length - 1);

    System.out.println(Arrays.toString(arr));
    // now remove the duplicate elements.
    arr = removeDuplicates(arr);
    System.out.println("Unique elements in Array :" + Arrays.toString(arr));
}
private static int[] removeDuplicates(int[] arr) {
    // if array length is one, return the array
    if (arr.length <= 1) {
        return arr;
    }

    // new array keep the length equal to current array.
    int[] uniqueArray = new int[arr.length];
    // keep the lastfound number to be 0th index.
    int lastFound = arr[0];
    // copy the 0th index value to new arrays 0th.
    uniqueArray[0] = arr[0];

    // keep track of number of duplicates found.
    int totalDuplicates = 0;

    // current index position to put the unique number
    int currPos = 1;
    for (int i = 0; i < arr.length; i++) {

        if (lastFound == arr[i]) {
            totalDuplicates++;
        } else {
            lastFound = arr[i];
            uniqueArray[currPos] = arr[i];
            currPos++;
        }
    }

    // at this point array wil have unique numbers along with empty
    // slots at the end in array, lets remove those.

    int newLength = arr.length - totalDuplicates;

    uniqueArray = Arrays.copyOf(uniqueArray, newLength + 1);
    return uniqueArray;
}

private static void quickSort(int[] arr, int s, int e) {

    if (s < e) {
        int pivot = findPivot(arr, s, e);
        System.out.println(pivot);
        // sort left
        quickSort(arr, s, pivot - 1);
        // sort right
        quickSort(arr, pivot + 1, e);
    }

}

private static int findPivot(int[] arr, int s, int e) {
    int p = arr[e];
    int i = s;
    for (int j = s; j < e; j++) {
        if (arr[j] <= p) {
            swap(arr, i, j);
            i = i + 1;
        }
    }
    swap(arr, e, i);
    return i;
}

private static void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}


texts: Fastest way to create random pixel image

texts:
I want to create a very big gigantic PNG image. The image pixel are generated randomly, being
How can I improve the below code to create a fast random pixel image in java?
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class RandomImage
{
    public static void main(String args[])throws IOException
    {
        // Image file dimensions
        int width = 30000, height = 24000;

        // Create buffered image object
        BufferedImage img = null;
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // file object
        File f = null;

        // create random values pixel by pixel
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int a = (int)(Math.random()*256); //generating
                int r = (int)(Math.random()*256); //values
                int g = (int)(Math.random()*256); //less than
                int b = (int)(Math.random()*256); //256

                int p = (a<<24) | (r<<16) | (g<<8) | b; //pixel

                img.setRGB(x, y, p);
            }
        }

        // write image
        try
        {
            f = new File("G:\\Out.png");
            ImageIO.write(img, "png", f);
        }
        catch(IOException e)
        {
        System.out.println("Error: " + e);
        }
    }
}


texts: Python port scanner using multithreading

texts:
I have written a rather simple port scanner using python and I would like to know things I could do better regarding:

Code quality, making the code in general better
Performance, making the code run faster and more efficient
Making the scan more lightweight for the system being scanned so there is no risk of it crashing

At the moment it takes around 160 seconds to scan all ports.

Thank you in advance.

import socket
import time
import threading
from queue import Queue

socket.setdefaulttimeout(0.25)
print_lock = threading.Lock()

target = '127.0.0.1'

def portscan(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        con = s.connect((target, port))
        with print_lock:
            print('Port', port, 'is open!')
        con.close()
    except:
        pass

def threader():
    while True:
        worker = q.get()
        portscan(worker)
        q.task_done()

q = Queue()
startTime = time.time()

for x in range(100):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()

for worker in range(1, 65536):
    q.put(worker)

q.join()

print('Time taken:', time.time() - startTime)


texts: Converting decimal to Roman numerals using MATLAB

texts:
I have written a MATLAB function that converts decimals into Roman numerals.

function ans = dec2rom(z)
d = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
c =  {'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
[];
for ii = 1:numel(d)
    if z >= d(ii)
        ans = [ans,repmat(c{ii},1,fix(z/d(ii)))];
        z = rem(z,d(ii));
    end
end


texts:
I've just finished building my slider and currently trying to refactor some redundant if/else code. Here is a preview of the code that I have built. Inside the event handlers. I have some if/else that are redundant, the purpose of the condition is to detect if slider reaches the last slide it will hide the next button and if the slider goes to the first slide. It will hide the previous button.

The slider I have built has no looping function.

    var programSliderContainer = $('.programs-slider'),
        programSliderWidth     = $('.programs-slider').outerWidth(),
        sliderContainer        = $('.programs-slider .view-programs-description .view-content'),
        totalSlides            = $('.programs-slider .view-programs-description .view-content .views-row').length,
        slides                 = $('.programs-slider .view-programs-description .view-content .views-row'),
        position               = 0,
        move                   = 0;

    //Reset Slider Position when resizing
    $('.programs-slider .view-programs-description .view-content').css({'right' : 0 });

    //Apply the Maximum width based on the total number of slides
    sliderContainer.width(programSliderWidth * totalSlides);

    //Apply the width of the slides based on the width of programSliderWidth
    slides.outerWidth(programSliderWidth);

    //Add Class active on Start
    $('.program-controls .program-list ul li:first-child').addClass('active');

    //Hide Previous Arrow on Start
    if( position == 0 ) {
        $('.arrow-controls .prev').hide();
    }

    $('.program-controls .program-list ul li').on('click', function() {
        position = $(this).index();
        $('.programs-slider .view-programs-description .view-content').css({'right' : position*programSliderWidth });

        $('.program-controls .program-list ul li.active').removeClass('active');
        $(this).addClass('active');

        //Show Hide Directional Navigation based on Slider Position
        if( position == 0 ) {
            $('.arrow-controls .prev').hide();
        }

        else {
            $('.arrow-controls .prev').show();
        }

        if( position == totalSlides - 1  ) {
            $('.arrow-controls .next').hide();
        }

        else {
            $('.arrow-controls .next').show();
        }

    });

    $('.arrow-controls .prev').on('click', function() {
        if( position > 0 ) {
            position--;
            $('.programs-slider .view-programs-description .view-content').css({'right' : position*programSliderWidth });

            $('.program-controls .program-list ul li.active').removeClass('active');
        }

        if( position == 0 ) {
            $('.arrow-controls .prev').hide();
        }

        else {
            $('.arrow-controls .prev').show();
        }

        if( position == totalSlides - 1 ) {
            $('.arrow-controls .next').hide();
        }

        else {
            $('.arrow-controls .next').show();
        }

    });

    $('.arrow-controls .next').on('click', function() {
        if( position < totalSlides - 1 ) {
            position++;
            $('.programs-slider .view-programs-description .view-content').css({'right' : position*programSliderWidth });

            $('.program-controls .program-list ul li.active').removeClass('active');
        }

        if( position == 0 ) {
            $('.arrow-controls .prev').hide();
        }

        else {
            $('.arrow-controls .prev').show();
        }

        if( position == totalSlides - 1 ) {
            $('.arrow-controls .next').hide();
        }

        else {
            $('.arrow-controls .next').show();
        }

    });

}


texts: Finding pairs of numbers with a given difference

texts:
Without changing the outputs or the inputs of the method, how would you make this code more readable ?

I am interested in any general improvement it can be made in terms of readability without WORSEN the time complexity.

Above all I'm interested of know if there is a way of doing all this steps in one line:

check if the key exist in the map.
if exist create a list with two elements (pair) and then append the
pair to list of pairs that will be the result.
if not exist do nothing.

Also is there a more elegant way to return array[][] from an ArrayList<ArrayList<Integer>> ?

static int[][] findPairsWithGivenDifference(int[] arr, int k) {

    int n = arr.length;
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();

    for (int i = 0; i < n; i++){
      map.put(arr[i]-k,arr[i]);
    }

    for (int i = 0; i < n; i++){
      int x = arr[i];
      if (map.get(arr[i]) != null) {
        int y = map.get(x);
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(y);
        al.add(x);
        all.add(al);
      }
    }

    int m = all.size();
    int[][] res = new int[m][2];

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < 2; j++) {
        res[i][j] = all.get(i).get(j);
      }
    }

  return res;
}


texts: UnitOfWork, removing abstraction of abstraction (Repository)

texts:
I'm creating a small project, but in the past I've used a Repository pattern for it, and it just seemed too bloated. I ended up having repo classes with huge amounts of queries. I'm trying to move away from that. I invite you to critique/help/guide me on my journey to less abstraction:

Note: I like the syntax style of Simple.Data and "Fluentness" of FluentApi. So my naming/style is inspired by them.

I start off with an IUnitOfWork Interface:

public interface IUnitOfWork : IDisposable
{
    void Save();
    IDbSet<T> Set<T>() where T : class;
}

My DB Context (pretty standard):

public partial class MyDbContext : DbContext, IUnitOfWork
{
    public MyDbContext() : base("DBConnection") { }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UsersMap());
    }
    public void Save()
    {
        SaveChanges();
    }
}

A Query object/service:

public class UserService : IService
{
    private readonly IUnitOfWork unitOfWork;

    public UserService(IUnitOfWork _u)
    {
        this.unitOfWork = _u;
    }
    public string GetUserName(string Name)
    {
        return unitOfWork.Set<User>().Single(s => s.Name == Name).UserName;
    }

}

Here's my Database Class (name inspired by Simple.Data):

public sealed partial class Database
{
    private readonly IUnitOfWork context;

    public Database(IUnitOfWork _context = null)
    {
        if (_context == null)
            this.context = new MyDbContext();
        else
            this.context = _context;
    }

    public static Database Open()
    {
        return new Database();
    }

    // I may move these into a separate file:
    public UserService Users { get { return new UserService(context); } }
}

Usage:

var userName = Database.Open().Users.GetUserName("John");
Console.WriteLine(userName);

This is all fine and good for simple tasks. But let's say I want to do multiple things whilst the Database connection is open. I could move Database.Open() to a separate variable then use it like this:

var database = Database.Open();
var userName = database.Users.GetUserName("John");
var userFirstName = database.Users.GetFirstName("john123");

So my question is, am I doing it wrong? Obviously, my main concern is to not open multiple connections to the Database, and use it like a UnitOfWork.

My other question is about how to handle CRUD. I have IService there (currently empty) because I was thinking of putting Insert/Update/Delete in there and adding methods to each Service class - BUT, this turns into a type "Repository" which I was trying to avoid. I don't think it's right for me to expose the DbSet<TEntity>() so I can .Add()/.Attach() - so what should I do here?

I'm still at the planning stage of this, so any changes/recommendations are welcome.


texts: Polymorphic components for graphics and program state

texts:
I asked this question on StackOverflow, got some answers, most notably a link to this one, and basing on that I've implemented this:

{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import Control.Monad.State
import Control.Monad.IO.Class

-- Module
----------------------------------------------------------------------------------------
newtype Module m a b =
    Module (a -> m (b, Module m a b))

{-
instance (Monad m) => Applicative (Module m a)
instance (Monad m) => Arrow (Module m)
instance (Monad m) => Category (Module m)
instance (Monad m) => Functor (Module m a)
-}

-- GraphicsModule
----------------------------------------------------------------------------------------
data GraphicsState = GraphicsState Int

render :: (MonadState GraphicsState m, MonadIO m) => Int -> m ()
render x = do
    (GraphicsState s) <- get
    liftIO $ print $ x + s
    put . GraphicsState $ s + 1

type GraphicsModule = Module IO Int ()

initialGraphicsState = GraphicsState 0

createGraphicsModule :: GraphicsState -> GraphicsModule
createGraphicsModule initialState = Module $ \x -> do
    (r, s') <- runStateT (render x) initialState
    return (r, createGraphicsModule s')

initialGraphicsModule = createGraphicsModule initialGraphicsState

runModule (Module m) x = m x

-- Program
----------------------------------------------------------------------------------------
data ProgramState = ProgramState {
    graphicsModule :: GraphicsModule
}

renderInProgram :: (MonadState ProgramState m, MonadIO m) => Int -> m ()
renderInProgram x = do
    gm <- gets graphicsModule
    (r, gm') <- liftIO $ runModule gm x

    modify $ \g -> g { graphicsModule = gm' }

initialProgramState = ProgramState initialGraphicsModule

main = runStateT prog initialProgramState

prog = do
    renderInProgram 1
    renderInProgram 1
    renderInProgram 1

I can see how this could be quite easily extended to allow more functions in a module (instead of just render). I am not sure if I'm keeping the state correctly, though. That was the only way I saw to not expose the inner, stateful context (note that the outer monad to the module is just IO).

Also I am aware of the fact that Lens could make it less verbose. I deliberately chose to not depend on Lens, and I think it's really functionally equivalent.


texts: Finding the distance between the two closest points in a 2-D plane

texts:
Here is my code:

import sys
import math
def dist(a,b):
    return math.hypot((b[0]-a[0]),(b[1]-a[1]))

def minimum_distance(x, y):
    points = list(zip(x,y))
    points_y = sorted(points, key= lambda z:z[1])
    points.sort(key=lambda g:g[0])
    return min_dist(points,points_y)

def min_dist(points,points_y):
    if len(points)==2: return dist(points[0],points[1])
    elif len(points)==3: return min(dist(points[0],points[1]),dist(points[0],points[2]),dist(points[1],points[2]))
    ave = (len(points)+1)//2
    yleft = [t for t in points_y if t[0]<=points[ave-1][0]]
    yright = [q for q in points_y if q[0]>=points[ave][0]]
    d1 = min_dist(points[0:ave],yleft)
    d2 = min_dist(points[ave:len(points)],yright)
    d = min(d1,d2)
    arr_split = [point for point in points_y if abs(point[0]- points[ave][0]) <= d]
    d_=2*(10**18)
    for i in range(len(arr_split)-1):
        for j in range(i+1,min(len(arr_split),i+7)):
            temp = dist(arr_split[i],arr_split[j])
            if temp<d_:d_=temp
    return min(d,d_)

Example input:([2,5,1],[3,6,2]) and output is \$ \sqrt 2 \$ since (2,3) and (1,2) are the closest points. The input arrays to minimum_distance are the x and y values of each point respectively and the inputs to min_dist are the points sorted based on their x values and y values respectively.

I have implemented pre-sort and have used computational geometric theory (comparison between 7 points only in the strip) to make the time complexity \$ O(n \log n) \$ and my code works swiftly and correctly for most test cases. However, for some hidden test cases generated by Coursera, my code is taking more than 20 seconds. Any optimisations/ corrections?


texts: Parsing a Conditional statement with Python

texts:
Recently I built a Usenet newsreader in Python and for that I built a keyword search which supports AND and OR functionalities (e.g., python AND django should bring up articles containing both. I defined a find function for this which takes a keyword query and a string and returns a bool signifying whether the string qualifies (i.e., for the above example, the string qualifies if it contains both 'python' and 'django').

Here's the snippet:

search = 'python AND django OR ruby AND rails'
query = search.split(' OR ')
query = [phrase.split(' AND ') for phrase in query]

def find(query, string):
    is_there = False
    for chunk in query: #OR
        chunk_qualified = False
        for word in chunk: #AND
            if word not in string:
                break
        else:
            chunk_qualified = True

        if chunk_qualified:
            is_there = True
            break

    return is_there

It works, but can I do it in a better manner (less code, more efficient)?


texts:
I am running a simulation with 250 interacting agents and have a few functions that are called over and over again. Even with precomputing all distances between agents before the N2 (250x250) interaction loop, my simulation is still very slow. Are there any C++ optimization tricks that I could use to speed these up?

This is the most-used function in my simulation. It calculates the distance2 between two agents in a continuous space. I have a feeling there isn't much that can be done to further optimize this, but you guys have surprised me with some tricks before:

double tGame::calcDistanceSquared(double fromX, double fromY, double toX, double toY)
{
    double diffX = fromX - toX;
    double diffY = fromY - toY;

    return ( diffX * diffX ) + ( diffY * diffY );
}

Here's another expensive function in my simulation. It calculates the angle from one agent to another agent relative to the 'from' agent's heading. As you can see, I already did a little precomputing with the atan2() function (and that DOES speed things up a bit, despite what I've read in other posts).

double tGame::calcAngle(double fromX, double fromY, double fromAngle, double toX, double toY)
{
    double Ux = 0.0, Uy = 0.0, Vx = 0.0, Vy = 0.0;

    Ux = (toX - fromX);
    Uy = (toY - fromY);

    Vx = cosLookup[(int)fromAngle];
    Vy = sinLookup[(int)fromAngle];

    int firstTerm = (int)((Ux * Vy) - (Uy * Vx));
    int secondTerm = (int)((Ux * Vx) + (Uy * Vy));

    if (fabs(firstTerm) < 1000 && fabs(secondTerm) < 1000)
    {
        return atan2Lookup[firstTerm + 1000][secondTerm + 1000];
    }

    else
    {
        return atan2(firstTerm, secondTerm) * 180.0 / cPI;
    }
}

Finally, here's the monster function that uses the calcDistanceSquared() function so much. This is run every simulation time step, and there's 2,000 time steps per simulation (and MANY simulations). The most expensive part is the calcDistanceSquared() in the N2 loop.

void tGame::recalcPredAndPreyDistTable(double preyX[], double preyY[], bool preyDead[],
                                       double predX, double predY,
                                       double predDists[250], double preyDists[250][250])
{
    for (int i = 0; i < 250; ++i)
    {
        if (!preyDead[i])
        {
            predDists[i] = calcDistanceSquared(predX, predY, preyX[i], preyY[i]);
            preyDists[i][i] = 0.0;

            for (int j = i + 1; j < 250; ++j)
            {
                if (!preyDead[j])
                {
                    preyDists[i][j] = preyDists[j][i] = calcDistanceSquared(preyX[i], preyY[i], preyX[j], preyY[j]);
                }
            }
        }
    }
}


texts: Function to alternate players' turns, unless a player has won

texts:
I am doing a coding challenge and it basically says this. There are two players, "black" and "white" and they take turns at a game. If a player won the last turn then it is his turn again, otherwise it is the other player's turn. The whole challenge is here.

Here is the original code I used for that:

function whoseMove(lastPlayer, win) {
  if (lastPlayer == "white") {
      if (win) {
          return "white";
      }
      return "black";
  } else {
      if (win) {
          return "black";
      }
      return "white";
  }
}

however I realised that this could be simplified by changing it to this:

function whoseMove(lastPlayer, win) {
  if (lastPlayer == "white") {
      return win ? "white" : "black";
  } else {
      return win ? "black" : "white";
  }
}

I wonder if this could be simplified even more? Is it possible to have more than one condition in the conditional return statement (I think that is what it is called)?


texts:
This is an implementation of the TCP/IP checksum computation as described in https://tools.ietf.org/html/rfc1071.

The function is writen in DynASM, an assembler preprocessor that is part of LuaJIT. I didn't use much of the fancy stuff of DynASM so pretty much it looks like native X86_64 I think.

  -- Prologue.
  | push rbp
  | mov rbp, rsp
  -- Accumulative sum (16-bit).
  | xor r9, r9                  -- Clear out r9. Stores accumulated sum.
  | mov rcx, 0                  -- Set index to 0.
  | 1:
  | cmp rcx, rsi                -- Rsi stores size arg. Compare index to size.
  | jg >2                       -- Go to branch '2' if equals.
  | mov ah, [rdi + rcx]         -- Read 16-bit of data and swapping byte order.
  | mov al, [rdi + rcx+1]
  | add r9, rax                 -- Sum and accumulate into r9.
  | add rcx, 2                  -- Increase index by 2.
  | jmp <1                      -- Go to beginning of loop.
  | 2:
  | mov rax, r9                 -- Save accumulated sum in rax.
  -- Sum carry until done.
  | 4:
  | shr r9, 16                  -- Right-shift r9 16-bit to obtain value of carry.
  | cmp r9, 0                   -- Check whether there's carry.
  | jz >5                       -- In case not, go to '4'.
  | and rax, 0xffff             -- Clear out higher part of rax.
  | add rax, r9                 -- Sum carry to rax.
  | mov r9, rax                 -- Assign rax to r9 to check if there's carry again.
  | jmp <4                      -- Go to beggining of loop.
  -- One-complement.
  | 5:
  | not rax                     -- One-complement of rax.
  | and rax, 0xffff             -- Clear out higher part of rax.
  -- Epilogue.
  | mov rsp, rbp
  | pop rbp
  -- Return.
  | ret

I verified against a Lua implementation the result is correct. I was wondering if I could write the code in a different way to use less instructions. For instance, the RFC says it's possible to sum the octets as a dword. I tried but I didn't manage to get a correct checksum.


texts:
Inspired by this question, but hopefully not a duplicate.

I understand that the Law of Demeter is very useful in case of services interacting with other services, for example it's much easier to mock the other services in unit tests.
What about services interacting with data models, though?

Let's say I have a hierarchy of immutable classes:

public final class Document {
    private final List<Page> pages;
    // Constructor, getter, ...
}

public final class Page {
    private final List<Paragraph> paragraphs;
    // Constructor, getter, ...
}

public final class Paragraph {
    private final List<Line> lines;
    // Constructor, getter, ...
}

Let's say I want to do something with certain lines in a document doc:

public void doSomething(Document doc) {
    for (Page page : doc.getPages()) {
        for (Paragraph para : page.getParagraphs()) {
            for (Line line : para.getLines()) {
                if (someCondition(line)) {
                    someAction(line);
                }
            }
        }
    }

Now, as far as I understand, the above code doesn't obey the Law of Demeter.
However, I don't want to force the law at all cost and clutter the model (here, the Document class) with tens of methods like:

public List<Line> filterWrtSomeCondition();
public List<Line> filterWrtSomeOtherCondition();

Or maybe there's a third way?  I suspect that the Law of Demeter applies primarily to services interacting with other services.  Is it a valid interpretation?


texts: Radio button selection and flash object initialization

texts:
Looking for a code review, as working alone on a project and don't have anyone who could possible help me.

if ($('.qp-content-right-scroll-panel').is(':visible')) {

    var isLiveData = $("input:radio[name=preview-options]").val();
    if (type.indexOf('DASHBOARD_LAYOUT') != -1) {
        var base = $('.qp-content-right-scroll-panel .layoutContent');
        var flashObj = $($.browser.mozilla ? "[name=layoutExternalflash]" :
            '#layoutExternalflash', base).get(0);
        if (flashObj != undefined && $.isFunction(flashObj.ext_sendLayoutDefinition)) {
            //get data from radio buttons
            $("input:radio[name=preview-options]").click(function () {
                var isLiveData = $(this).val();
                flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);
            });
        }
    } else {
        var base = $('.qp-content-right-scroll-panel .chartContent');
        var flashObj = $($.browser.mozilla ? "[name=chartExternalflash]" :
            '#chartExternalflash', base).get(0);
        if (flashObj != undefined && $.isFunction(flashObj.ext_sendChartDefinition)) {
            $("input:radio[name=preview-options]").click(function () {
                var isLiveData = $(this).val();
                flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);
            });
            flashObj.ext_sendChartDefinition(elementId, state, isLiveData);
        }
    }
}


texts: Optimize calculation for the amount of time between when a value changes in Pandas

texts:
I have some sensor data that contains timestamps from when a machine is turned on and an indicator variable showing whether or not the machine is actively running.  The data is mostly recorded every two minutes, but they there could be more or less time between two sensor readings due to issues with the sensor.

I want to create a new feature that captures at a specific datetime, how long has the machine been in that Run status for.

I currently have the data loaded in a DataFrame, and I have been able to create a new variable that shows whether or not the Run status has changed from the previous reading.  Next, I need to figure out how capture the amount of time since the last time the Run status changed.  If the readings where consistently every two minutes, I could maybe do some type of counter that resets when Run changes.  Instead, I took an approach where if the time changed, I hold onto that value and keep subtracting the next Datetime stamp from it, as long as Run didn't change. When Run changes, I start the processes over.

This approach seems to work fine on this small example, but I feel like it's not the most efficient use of resources, especially when trying to scale up to my 400,000 record dataset.

# load example data
df = pd.DataFrame(data = [['2015-01-01 00:00', 1],
                          ['2015-01-01 00:02', 1],
                          ['2015-01-01 00:04', 1],
                          ['2015-01-01 00:06', 0],
                          ['2015-01-01 00:08', 0],
                          ['2015-01-01 00:10', 1],
                          ['2015-01-01 00:12', 0],
                          ['2015-01-01 00:15', 1],
                          ['2015-01-01 00:17', 1],
                          ['2015-01-01 00:19', 1],
                          ['2015-01-01 00:23', 0],
                          ['2015-01-01 00:25', 0],
                          ['2015-01-01 00:30', 0],
                          ['2015-01-01 00:32', 0],
                          ['2015-01-01 00:34', 0]],
                  columns = ['Datetime', 'Run'])

# convert to datetime object
df.Datetime = pd.to_datetime(df['Datetime'])

# create an empty column to capture change point in Run
df['Run_Change'] = ""

# set the first Run_Change equal to 'Change', since we don't know what happened before it
df = df.set_value(df.index[0], 'Run_Change', 'Change')

# create a column to capture the amount of time between each Run_Change
df['Time_Since_Change'] = df['Datetime'] - df['Datetime']

# set the first time_since_change to 0 since we don't know what happened before it
first_change = df.ix[df.index[0]]['Datetime'] - df.ix[df.index[0]]['Datetime']
df = df.set_value(df.index[0], 'Time_Since_Change', first_change)

# set iniital datetime to based changes on
change_time = df.ix[df.index[0]]['Datetime']

# starting at the second event...
for i in df.index[1:]:

    # ...compare Run at this time to Run at the previous time...and if it changeed...
    if df.ix[i]['Run'] != df.ix[i-1]['Run']:

        # ...set Status equal to 'Change'
        df.set_value(i, 'Run_Change', 'Change')

        # ...and grab the 'Datetime' that the change happeneed
        change_time = df.ix[i]['Datetime']

    # otherwise...
    else:

        #...set equal to 'No Change'
        df.set_value(i, 'Run_Change', 'No Change')

    # calculate the time since the last change
    time_since_change = df.ix[i]['Datetime'] - change_time

    # update DF
    df.set_value(i, 'Time_Since_Change', time_since_change)

# convert Time_Since_Change to minutes
df['Time_Since_Change_2'] = df['Time_Since_Change'] / np.timedelta64(1, 'm')


texts: Code to modify DOM element using DOM.style property

texts:
So, I've a code that is below which works just fine:

<html>
  <head>
    <title> Javascript Practice </title>
  </head>
  <body>
    <div id="myDiv">
    </div>
    <script>
      var a = 0;
      var b = 255;
      var c = 0;
      var color2 = 'RGB(' + a + ',' + b + ',' + c + ')';

      document.getElementById("myDiv").style.backgroundColor = color2;
      document.getElementById("myDiv").style.width = 50;
      document.getElementById("myDiv").style.height = 300;
    </script>
  </body>
</html>

I've got a lot of feedback saying that when accessing DOM style property, I need to set value as strings such as setting DOM.style.width not to a number like I've done here but appending w + "px"

I'm puzzled because I'm using Brackets as a code editor and deploying this on chrome. My code runs just fine and every time I load the HTML page, it initializes a div of the required dimensions. Everyone tells me it won't work which is what's confusing me.

TIA.


texts: Password and confirm password validation in Android Studio

texts:
I just wrote this password and password confirmation validation code function that checks to see if a password is empty or not, and is it match (password = confirmPassword). I'm not sure this is the best way to do it, but for now it dont works really well.

private void checkDataEntered()
{
    if(isEmpty(RegisterFirstName))
    {
        RegisterFirstName.setError("You must enter first name to register");
    }

    if(isEmpty(RegisterLastName))
    {
        RegisterLastName.setError("Last name is required");
    }

    if(isEmail(RegisterEmail) == false)
    {
        RegisterEmail.setError("Enter your valid email.");
    }

    if(isEmpty(RegisterPassword))
    {
        RegisterPassword.setError("Enter your password.");
    }

    if(isEmpty(RegisterConfirmPassword))
    {
        RegisterConfirmPassword.setError("Enter your confirmation password");

        if (!RegisterConfirmPassword.equals(RegisterPassword))
        {
            Toast.makeText(Signup.this, "Password do not match", Toast.LENGTH_SHORT).show();
        }
    }

    else
    {
        loadingBar.setTitle("Creating New Account");
        loadingBar.setMessage("Please wait while we are creating account for you.");
        loadingBar.show();

        String email = null;
        String password = null;

        mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>()
        {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {
                if(task.isSuccessful())
                {
                    Toast.makeText(Signup.this, "You have successfully signed up", Toast.LENGTH_SHORT).show();
                    Intent mainIntent = new Intent(Signup.this, MainActivity.class);
                    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(mainIntent);
                    finish();
                }
                else
                {
                    Toast.makeText(Signup.this, "Error occured, please try again.", Toast.LENGTH_SHORT).show();
                }
                loadingBar.dismiss();
            }
        });
    }
}


texts: Spring Data Redis - mapping object relationships?

texts:
I'm designing an app that will process a set of social media messages which are posted by users. Each message is then scored and there is a reporting layer that will spit out a set of reports. The app is implemented with spring-boot and has to use a Redis DB.

I'm more familiar with RDBM databases and perhaps I'm being too much of an ORM mapping mindset to this issue.

The main rules i need to enforce

A user can post multiple messages.
A message can have multiple scores.
It should be possible to chart a user's scores over time.

I've started with the logical mapping of data that i believe i need to record in the app. There are three main objects and I'm using spring-data-redis to define the @RedisHash, @Id, @Index and @Reference fields.

Message

The raw message details with thread, date, user and message content.

@RedisHash("messages")
public class Message {

    @Id String messageId;
    @Indexed String threadId;
    @Reference String userId;
    String message;
    Date date;
    @Reference List<User> userScores;
}

Score

A record of a score that each message has been recorded with

@RedisHash("scores")
public class Score {
    @Id String id;
    @Reference String messageId;
    Long score;
    @Reference User user;
}

User

The user details with title

@RedisHash("users")
public class User {

    @Id String userId;
    String grade;
    @Reference List<Score> scores;
}

I believe the Message and User objects are correctly defined, but my concern is I've over complicated the Score object mapping. Any comments or advise would be welcome.


texts:
I have been working on creating a code solution for the Hungarian Algorithm, and from the testing, the slowest and buggiest part has been the bipartite matching.  The most recent rendition is based on this GeeksforGeeks article, but, I removed the recursion since that was a stack-overflow waiting to happen for my intended use.

public static class MaximumMatchingAlgorithm
{
    private const int Invalid = -1;

    public static IEnumerable<BipartiteMatch> Solve<TValue>(TValue[,] values, Func<TValue, bool> interpreter)
    {
        var m = values.GetLength(0);
        var n = values.GetLength(1);

        var mappings = new Queue<int>[m];
        var matches = new int[n];

        for (var index = 0; index < n; index++)
        {
            matches[index] = Invalid;
        }

        for (var x = 0; x < m; x++)
        {
            var mapping = mappings[x] = new Queue<int>(n);

            for (var y = 0; y < n; y++)
            {
                if (interpreter(values[x, y]))
                {
                    mapping.Enqueue(y);
                }
            }

            var currentX = x;

            while (mapping.TryDequeue(out var y))
            {
                var tempX = matches[y];
                var otherMapping = tempX != Invalid ? mappings[tempX] : null;

                if (otherMapping == null)
                {
                    matches[y] = currentX;
                    break;
                }

                if (otherMapping.Count == 0) continue;

                matches[y] = currentX;
                currentX = tempX;
                mapping = otherMapping;
            }
        }

        for (var index = 0; index < n; index++)
        {
            yield return new BipartiteMatch(matches[index], index);
        }
    }
}

Are there any glaring issues with how I converted the code, or are there any optimizations that could/should be made?

UPDATE: After more testing, I found a test case where this algorithm produced an incorrect result.  I switched the Queue to a Stack, which is what it should have been in the first place in order to replicate recursion.


texts: Compute max population given a list of people's birth and death year

texts:
I recently came across a brief programming puzzle prompt (say that three times fast) which asked to return the year that population peaked.

The actual algorithm to compute it can be done several ways and is not particularly difficult, but I have recently been challenging myself to write .. ahem .. "more functional" code.

There are several tenets of FP, but a chief one is not producing what developers call "side effects". I'm hoping to get to a point where I do not rely as much on classic object-oriented patterns and feel more at ease diving right into the functional style. Of course this takes practice, so I decided to spend some extra time polishing up my code to meet my internal requirements:

val persons = Seq(
  Person(2000, 2010),
  Person(2000, 2005),
  Person(1990, 2005)
)

// Create an array of population change.
val births = persons.groupBy(_.birthYear).mapValues(_.length)
val deaths = persons.groupBy(_.deathYear).mapValues(_.length)
val populationChanges = (births.keySet ++ deaths.keySet).map { year =>
  (year, births.getOrElse(year, 0) - deaths.getOrElse(year, 0))
}.toMap

println("populationChanges", populationChanges)

val sortedYears = populationChanges.keys.toSeq.sorted
println(sortedYears)

// construct an array of total populations
val populations = populationChanges.toSeq
  .sortBy(_._1)
  .scanLeft(0) { (a, b) => a + b._2 }
  .tail
  .zip(sortedYears) // this is a bit hacky
  .map{ case(count, year) => (year, count) }

println("pop", populations)
println("max pop", populations.maxBy(_._2)) // (2000, 3)

This is a demonstration of what I created after a few minutes of iteration.

I was readily able to produce a list of population changes and from there, performed further transformations to arrive at a list of total populations for each year. From there determining the year that population peaked was trivial.

However, I'm not fully satisfied with this solution. I could be being too dogmatic, but in my mind I would not be breaking scope of a map function to reference external values, even though it proved expedient in this case.


texts: Backbone.js Dependency Injection API Design

texts:
I'm writing a dependency injection plugin for the Backbone javascript framework, and I'm not sure what the API for constructor argument injection should look like.

Just for reference, Backbone objects are defined as follows:

var LoginView = Backbone.View.extend({
  //constructor
  initialize: function(options) {
    //define an instance property
    this.loginProvider = options.loginProvider;
  },

  //method
  authenticate: function() { },

  //prototypal property (available via instance, shared between all instances)
  navigation: App.navigationService
});

My plugin supports instance property injection as follows:

var LoginView = Backbone.View.extend({
  //...
  loginProvider: needs.property('LoginProvider')
});

var loginView = new LoginView();
loginView.loginProvider.doLogin(); //loginProvider is auto-injected

I'm quite happy with this, but I also want to support constructor argument injection. Here I have run into doubt regarding best way forward. Here are the options I've considered:

Add class method inject

var LoginView = Backbone.View.extend({
  initialize: function(options, bar) {
    //property "foo" will be injected to options
    //second argument "bar" will be injected
  }
}).inject({foo:'Foo'}, 'Bar');

This is clean, but it "hides" the injection to the bottom of the class definition. I feel the constructor injection configuration should be somewhere near the constructor, at the very least.
Wrap the initialize method

var LoginView = Backbone.View.extend({
  initialize: needs.args({foo:'Foo'}, 'Bar', function(options, bar) {
    //property "foo" will be injected to options
    //second argument "bar" will be injected
  }
});

Now the injected arguments are right next to the constructor definition, but this gets a bit messy when you have more than one or two dependencies:

var LoginView = Backbone.View.extend({
  initialize: needs.args(
    { foo:'Foo', bar:'Bar' },
    'BazService',
    'QuxFactory',
    function(options, baz, qux) {
      //...
    })
});

This method also lies to the user, because the arguments are not actually injected to the initialize method directly. Instead they are injected into the class constructor function, which in turn passes them to initialize.
Define a "convention-based" property injectArgs, which is used, if present

var LoginView = Backbone.View.extend({

  injectArgs: [{foo:'Foo'}, 'Bar'],

  initialize: function(options, bar) {
    //property "foo" will be injected to options
    //second argument "bar" will be injected
  }
});

This solves problems posed by options 1 and 2, but it feels... icky. Because the property is defined on the class prototype, it will continue to hang around on every instance of the object even after initialization and I don't think it has any business being there.
None of the above

Got a better idea? I want to keep the plugin unobtrusive, so there are two maxima I want to keep to: No modifying Object prototype, and the Backbone objects must be creatable by extend, so no factory tricks.


texts: Performing several integer division operations on an array

texts:
Program:

  Given an array A of size N. Given Q operations, each operation
  contains an integer D. In each operation you have to divide all the
  elements of the array by D.

  For example, for each operation with a given D, the new array A would
  be: Finally, after processing all the operations you have to print the
  final array after Q operations. Note: The result of the each division
  will be an integer, for example 5 / 2 = 2

  Input:

  First line of input contains a single integer N denoting number of
  elements in the array A. Next line of input contains N space separated
  integers denoting the elements of array A. Next line contains Q
  denoting number of operations. Next Q lines contains a single integer
  D by which divide the elements of the array.

  Output:

  Print single line containing N space separated integers after
  processing Q operations.

  Sample Input

5
50 20 18 27 19
3
2
3
2

  Sample Output

4 1 1 2 1

  Explanation

  In operation 1 after dividing the whole array by D=2, the resultant
  array will be: [25, 10, 9, 13, 9] In operation 2 after dividing the
  array from operation 1 by 3, the resultant array will be: [8, 3, 3, 4,
  3] In operation 3 after dividing the array from operation 2 by 2, the
  resultant array will be: [4, 1, 1, 2, 1] So, the resultant array will
  be [4, 1, 1, 2, 1]

Solution:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class TestClass1 {

    public static void main(String[] args) {
    try{
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter No of element in Array:-");
         String line = br.readLine();
         int N = Integer.parseInt(line);
         int a[]=new int[N];
         System.out.println("Now Enter Array elemnt seperated by space :-");
           String line2= br.readLine();
           String s[]=line2.split(" ");
           for(int p=0;p<s.length ;p++){
               a[p]=Integer.parseInt(s[p]);
           }
           System.out.println("Now Enter No of operations :-");
           int d=Integer.parseInt(br.readLine());
           System.out.println("Now enter all the operationis elemnt one by one:- ");
           int t[]=new int[d];
            for(int i=0;i<d;i++){
                t[i]=Integer.parseInt(br.readLine());
            }
            System.out.println(Arrays.toString(t));
            for(int j=0;j<d;j++){
                for(int k=0;k<N;k++){
                    a[k]=a[k]/t[j];
                }
            }
           System.out.print(Arrays.toString(a));
    }catch(Exception ex){
        ex.printStackTrace();
    }
    }

}


texts: Combine similar methods with different text?

texts:
I made the popular Guess-The-Number game and included an AI version that picks random numbers. The AI version has slightly different Console output that differ slightly, for example:

I generated a number between 1 and 100. Can you guess it?
You generated a number between 1 and 100. Let me try

First I did this:

Console.WriteLine("{0} generated a number between 1 and 100. {1}", ai? "I" : "You", ai? "Can you guess it?", "Let me try");

As this needed to be done a few more times, it looked very clumsy, but could implement both versions in one medium length method. After that I seperated the different versions and made two shorter methods GuessUser and GuessAI which are cleaner, but both share a lot of similar code, almost everything besides Console.WriteLine(x).

Is there a smart way to combine those two versions into a small method?

Complete version


texts:
I'm trying to determine at which level I should validate a method on my class.  In my class method I throw an exception if it ever gets to that point.  In my service layer I do some validation and return a validation object to be used by the controller.  Here is my code.  Does it seem like I am moving in the right direction?  Let me know if you need any additional code.

// Class Method
public void Delete()
{
    if (Status == "UnIndexed")
        Deleted = true;
    else
        throw new InvalidOperationException("Only an UnIndexed thing may be deleted.");
}

// Service Layer
public IValidator<Thing> RemoveThing(int id)
{
    var thing = _repository.Get(id);
    if (thing == null)
        return null;

    var validator = new ThingValidator(thing);
    var isValid = validator.Validate(new StatusSpecification("UnIndexed"));

    if (isValid)
    {
        thing.Delete();
        _repository.Save(thing);
    }
    else
    {
        validator.AddError("Only an UnIndexed thing may be deleted.");
    }

    return validator;
}

// Controller
public JsonResult DeleteThing(int thingId)
{
    var command = _service.RemoveThing(thingId);

    if (command == null)
        return Json(HttpStatusCode.NotFound);

    if (command.IsValid())
    {
        return Json(HttpStatusCode.OK);
    }
    else
    {
        return Json(command.ListErrors());
    }
}


texts: Custom route for writing friendly URLs in ASP.NET MVC 3

texts:
I'm trying to build friendly URLs like /post/1/my-first-post. I started out with building my links like this:

@Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new
{
   id = Model.BlogPost.Id,
   title = Model.FriendlyUrl
},
new { })

which were processed by this route:

routes.MapRoute(
   "Post", // Route name
   "posts/{id}/{title}", // URL with parameters
    new { controller = "Post", action = "Index" }, // Parameter defaults
    new { id = "^[0-9]+$" }
 );

When I create my view model, I would give it an IUrlNiceName which it used to create the output of FriendlyUrl:

public string FriendlyUrl
{
    get{ return UrlNiceName.ConvertToNiceName(BlogPost.Title); }
}

Then I felt like I didn't want to manage UrlNiceName-ing on the controller level so then I build a custom Route to do this for me:

public class NiceNameRoute : RouteBase
{
    private IUrlNiceNames UrlNiceNames { get; set; }
    private string UrlPrefix { get { return "post/"; } }

    public NiceNameRoute(IUrlNiceNames urlNiceNames)
    {
        UrlNiceNames = urlNiceNames;
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RouteData result = null;
        string requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath;

        //match e.g. post/1 or post/1/my-first-post
        Regex regex = new Regex(UrlPrefix + "[0-9]+($|/)");

        if (regex.Match(requestedURL).Success)
        {
            //get the start of the post id
            int prefixPos = requestedURL.IndexOf(UrlPrefix, StringComparison.OrdinalIgnoreCase);
            int startIdPos = prefixPos + UrlPrefix.Length;

            //get the end of the post id
            int endIdPos = requestedURL.IndexOf("/", startIdPos, StringComparison.OrdinalIgnoreCase);
            endIdPos = endIdPos == -1 ? requestedURL.Length : endIdPos;

            //get post id
            string id = requestedURL.Substring(startIdPos, endIdPos - startIdPos);

            result = new RouteData(this, new MvcRouteHandler());
            result.Values.Add("controller", "Post");
            result.Values.Add("action", "Index");
            result.Values.Add("id", id);
        }

        return result;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext,
        RouteValueDictionary values)
    {
        VirtualPathData result = null;

        if (values.ContainsKey("title")
            && Convert.ToString(values["action"]) == "Index"
            && Convert.ToString(values["controller"]) == "Post")
        {
            string niceName = UrlNiceNames.ConvertToNiceName(Convert.ToString(values["title"]));

            result = new VirtualPathData(this, UrlPrefix + Convert.ToString(values["id"]) + "/" + niceName);
        }
        return result;
    }
}

which I registered like this:

routes.Add(new NiceNameRoute(new HyphenUrlNiceNames()));

and generate links like this:

@Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new
{
   id = Model.BlogPost.Id,
   title = Model.BlogPost.Title
},
new { })

I first wanted to take a crack at this but now I want to know how industry experts do it. Am I over engineering? Is there a simpler approach that is also elegant? Are there any issues with my custom Route?


texts:
This code is built on Json.NET and gets called hundreds of times per second. My data starts in an ArraySegment<byte>. I wrap that in a MemoryStream and pass it in to the code. It's generally small data: hundreds of bytes, not thousands. It just doesn't seem right that I have to construct multiple streams and readers for every single deserialization call. How do I optimize this? How do I reuse those two readers?

public object Deserialize(Stream stream, Type type)
{
    using (var utfReader = new StreamReader(stream, Encoding.UTF8, true, 2048, true))
    using (var reader = new JsonTextReader(utfReader) { CloseInput = false })
        return _serializer.Deserialize(reader, type);
}

public T Deserialize<T>(Stream stream)
{
    return (T)Deserialize(stream, typeof(T));
}


texts: ASP.NET Password Hashing reimplemented in PHP

texts:
Live link to Code: https://github.com/sqlcollaborative/AlwaysEncryptedSample/blob/features/phpSampleApp/AlwaysEncryptedSample.PHP/src/Security/AspNetIdentity.php

Unit tests to prove it works: https://github.com/sqlcollaborative/AlwaysEncryptedSample/blob/features/phpSampleApp/AlwaysEncryptedSample.PHP/tests/Security/AspNetIdentityTest.php

I am making a php CLI apps to add users to an AlwaysEncrypted application. Here is how I am encrypting the password. Its almost a direct port of the ASP.NET C# code and has 100% code coverage so I'm pretty sure it works. Just wondering if there is a better way to do things.

<?php
declare(strict_types = 1);

namespace SqlCollaborative\AlwaysEncryptedSample\Security;

use RuntimeException;

/**
 * Class AspNetIdentity
 * @package SqlCollaborative\AlwaysEncryptedSample\Security
 * A direct port of the algorithm to generate and verify ASP.NET password hashes found here:
 * @link https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Crypto.cs
 * For mor information:
 * @link http://stackoverflow.com/questions/20621950/asp-net-identity-default-password-hasher-how-does-it-work-and-is-it-secure
 */
class AspNetIdentity
{
    const PBKDF2_ITER_COUNT = 1000; // default for Rfc2898DeriveBytes
    const PBKDF2_SUBKEY_LENGTH = 256/8; // 256 bits
    const SALT_SIZE = 128/8; // 128 bits

    private function generateRandomSalt() : string
    {
        return random_bytes(self::SALT_SIZE);
    }

    public function getPasswordSalt(string $hashedPassword) : string
    {
        $hashedPasswordByteString = base64_decode($hashedPassword);
        $expectedHashLength = 1 + self::SALT_SIZE + self::PBKDF2_SUBKEY_LENGTH;
        $actualHashLength = strlen($hashedPasswordByteString);

        $header = substr($hashedPasswordByteString, 0, 1);
        if ($header != "\0"){
            throw new RuntimeException("Incorrect header [ $header ]");
        }

        if ($actualHashLength != $expectedHashLength)
        {
            throw new RuntimeException (
                "Salted hash is wrong length [ expected = {$expectedHashLength}, actual = {$actualHashLength} ]"
            );
        }

        return substr($hashedPasswordByteString, 1, self::SALT_SIZE);
    }

    /**
     * Creates a PBKDF2 (AKA Rfc2898) hash from a plaintext password.
     * @param string $password A plaintext password
     * @param string|null $salt Optionally specify the hash. This should only be used to verify existin passwords.
     * @return string The base64 encoded password hash
     */
    public function hashPassword(string $password, string $salt = null) : string
    {
        $salt = $salt ?? $this->generateRandomSalt();
        $subkey = hash_pbkdf2(
            'sha1',  // The SHA1 exploit google discovered is irrevelevant to HMAC_SHA1
            $password,
            $salt,
            self::PBKDF2_ITER_COUNT,
            self::PBKDF2_SUBKEY_LENGTH,
            true
        );

        return base64_encode("\0" . $salt . $subkey);
    }

    /**
     * verifies a plaintext password matches its hash.
     * @param string $hashedPassword must be of the format of HashWithPassword (salt + Hash(salt+input)
     * @param string $password the plain text version of the password
     * @return bool true if the password matches false if it does not.
     */
    public function verifyHashedPassword(string $hashedPassword, string $password) : bool
    {
        try {
            $salt = $this->getPasswordSalt($hashedPassword);
        }
        catch (RuntimeException $ex) {
            trigger_error($ex->getMessage());
            return false;
        }
        $actualHashedPassword = $this->hashPassword($password, $salt);
        return ($actualHashedPassword === $hashedPassword);
    }
}


texts: Refactor .each where each is redirected into a hash

texts:
What would be the best way to refactor this :

@busy.each do |b|
  title =  b.title
  @events << {
    :id => b.id,
    :title => title,
    :start => b.busy_start_time(b.start_date,b.start_time),
    :end => b.busy_end_time(b.end_date,b.end_time),
    :allDay => false,
    :recurring => false,
    :color => 'black',
  }

@events is initialized as an empty array:

@events = []

And this busy statement is the SECOND of two pushes into @events.

I think that I can use map here something like :

@events = @events + @busy.map do |b|
  stuff
end

Because I don't want to overwrite @events, I want to add stuff into it.

But what I'm really searching for is a way to store the entire 'each' into a lambda and say something like :

@events += @busy(&:create_busy_hash)

And move all the hash creation into the Busy class as create_busy_hash

I'm still grasping lambdas and procs


texts: VBA code to read Excel file and conditionally complete formulas based on the contents

texts:
The code below does the following:

Look at rows starting at row 10 and continuing through the last row of a sheet, and based off certain criteria, loops through each row.
If the scenarios match, then the code will drop in 0s and 1s onto another sheet in a formulated range
In some scenarios, the code will fill down formulas.

The correct time to run is 3.5 seconds, I am wondering if there are any adjustments to speed this up.

Option Explicit

Sub CleanupCrew()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim icounter As Long
Dim lastrowB As Long
Dim lastrowd As Long
Dim a As Variant
Dim rw As Long

Set ws = Worksheets("Dashboard")
Set ws1 = Worksheets("Base")
Set ws2 = Worksheets("LOOKUP")
Set ws3 = Worksheets("Control")

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual

lastrowB = ws1.Cells(Rows.Count, 1).End(xlUp).Row
lastrowd = ws.Cells(Rows.Count, 1).End(xlUp).Row

Application.Calculate
For icounter = 10 To lastrowd
Dim varL As Integer
Dim varM As Variant

varL = ws.Cells(icounter, "AD")
varM = ws.Cells(icounter, "AI")
a = ws.Cells(icounter, "AD")

'If proposed Box vacancy greater than 12
If ws.Cells(icounter, "AN") > 12 And ws.Cells(icounter, "AX") = "True" Then

rw = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
ws1.Cells(varM, a).Value = 1 - ws.Cells(icounter, "AE").Value
If a = 87 Then
ws1.Range(ws1.Cells(varM, a + 1), ws1.Cells(varM, 98)).Value = 0
ElseIf a = 98 Then
ws1.Range(ws1.Cells(varM, 87), ws1.Cells(varM, a - 1)).Value = 1
Else
ws1.Range(ws1.Cells(varM, 87), ws1.Cells(varM, a - 1)).Value = 1
ws1.Range(ws1.Cells(varM, a + 1), ws1.Cells(varM, 98)).Value = 0
End If

ws.Cells(rw, "A") = "Incumbent (Automated)"
ws.Cells(rw, "E").Value = ws.Cells(icounter, "N").Value
ws.Cells(rw, "B").Value = ws.Cells(icounter, "B").Value
ws.Cells(rw, "D").Value = Application.WorksheetFunction.VLookup(ws.Cells(rw, "E"), ws3.Range("C:I"), 7, 0)
ws.Cells(rw, "A").AddComment " " & ws.Cells(rw, "D") & ". "
ws.Range("Y" & lastrowd & ":AS" & rw).FillDown
End If

If ws.Cells(icounter, "AM") > 12 And ws.Cells(icounter, "AY") = "True" Then

rw = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
ws1.Cells(varL, a).Value = 1 - ws.Cells(icounter, "Ae").Value
If a = 87 Then
ws1.Range(ws1.Cells(varL, a + 1), ws1.Cells(varL, 98)).Value = 0
ElseIf a = 98 Then
ws1.Range(ws1.Cells(varL, 87), ws1.Cells(varL, a - 1)).Value = 1
Else
ws1.Range(ws1.Cells(varL, 87), ws1.Cells(varL, a - 1)).Value = 1
ws1.Range(ws1.Cells(varL, a + 1), ws1.Cells(varL, 98)).Value = 0
End If

ws.Cells(rw, "A") = ")"
ws.Cells(rw, "E").Value = ws.Cells(icounter, "E").Value
ws.Cells(rw, "B").Value = ws.Cells(icounter, "B").Value
ws.Cells(rw, "D").Value = Application.WorksheetFunction.VLookup(ws.Cells(rw, "E"), ws3.Range("C:I"), 7, 0)
ws.Cells(rw, "A").AddComment "" & ws.Cells(rw, "D") & ". ."
ws.Range("Y" & lastrowd & ":AS" & rw).FillDown
End If

If ws.Cells(icounter, "AS") = True And ws.Cells(icounter, "A") <> "Termination" And ws.Cells(icounter, "Aw") = "True" Then

rw = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1

ws.Cells(rw, "A") = ""
ws.Cells(rw, "E").Value = ws.Cells(icounter, "E").Value
ws.Cells(rw, "B").Value = ws.Cells(icounter, "B").Value
'ws.Cells(rw, "D") = Application.WorksheetFunction.VLookup(ws.Cells(rw, "E"), ws3.Range("C:I"), 7, 0)
ws.Cells(rw, "A").AddComment " " & ws.Cells(rw, "E") & " "

ws.Range("Y" & lastrowd & ":AS" & rw).FillDown
End If

Next icounter
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True

Application.Calculate

End Sub


texts: Having initialization code certain to run only once

texts:
I have this static class in an ASP.NET MVC project:

  public static class Setup
  {
    private static bool _intialized = false;

    public static void Initialize(IWindsorContainer Container)
    {
      //Check if it has already run
      if (_intialized)
      { return; }

      var connectionString = config.ConnectionStrings["ccsMongo"].ConnectionString;
      var dbName = config.AppSettings["ccsMongoDb"];

      //Initialization code here.
      Container.Register(
          Component.For<IOrgRepos>().ImplementedBy<OrgRepos>()
            .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
          Component.For<IIndividualRepos>().ImplementedBy<IndividualRepos>()
            .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName}),
          Component.For<IScoreboardRepos>().ImplementedBy<ScoreboardRepos>()
            .DependsOn(new { ConnectionString = connectionString, DatabaseName = dbName})
        );

      //Mark as run
      _intialized = true;
    }
  }

I then include a call to it in my Application_Start.  The intent is to be sure that it will never run more than once.

Is there a better way to create a function that can't be run more than once in the the application lifetime?
Am I being paranoid?  I could just put a call to the initialization code into my Application_Start and forget about the "run only once" guard code.

I would be delighted to get any feedback.


texts: Passing data between middleware in Express.js

texts:
I wrote a middleware for user authentication and I wanted to pass some data between authentication and request handler. What I thought would be a nice solution is to add that data into request body that then will be passed and process by handler. Here is how it looks like:
import { NextFunction, Request, Response } from 'express';

import UserModel, { UserDocument } from '../model/user_model';

export interface AuthenticationData {
    token: string,
    user: UserDocument
};

export interface AuthenticatedBody {
    body: any,
    authData: AuthenticationData
};

const auth = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    const token = req.header('Authorization')
        ?.replace('Bearer', '')
        .trim()!;
    const user = await UserModel.findByToken(token);
    if (user === null) {
        res.status(401).send({ error: 'Please authenticate' });
    } else {
        req.body = {
            body: req.body,
            authData: {
                token,
                user
            }
        };
        next();
    }
};

export default auth;

As I'm new to Express and Javascript I don't know whether it's good solution or not.


texts: Deleting a table row in JavaScript with OOP

texts:
I started learning OOP in JavaScript at school and I have to do my homework in OOP. It is a shopping list, one fills in a product and price and that is put into an array, the array its contents are put in a table in HTML. The list also has got delete buttons for every product, I have thought about using this in JavaScript, as I am working in OOP, but I am sceptic because of the scope.

The idea is that one clicks "verwijder" on the webpage (EDIT: in the corresponding row) and the table row is gone. I have thought about using this but also about dynamically updating the table after removing the selected row from the array.

Who can advise me about what to do and how to do that correctly? I have uploaded my JavaScript here: http://jsfiddle.net/hNAZ9/

Mainly, it is about this piece of code:

    function ShoppingList(){
    this.items = [];
    this.setItem = function(product, price){
        var item = new Item(product, price);
        this.items.push(item);
    };
    this.render = function(){
        var placeHolder = document.getElementById("shoppingList");
        placeHolder.innerHTML = "";

        for(var i = 0; i <this.items.length; i++){
            var tr = document.createElement("tr");
            tr.id = i;

            var tdProduct = document.createElement("td");
            tdProduct.innerHTML = this.items[i].product;
            tr.appendChild(tdProduct);

            var tdPrice = document.createElement("td");
            tdPrice.innerHTML = this.items[i].price;
            tr.appendChild(tdPrice);

            var tdDel = document.createElement("td");
            tdDel.innerHTML = "Verwijder";
            tdDel.addEventListener("click", delItem, false);
            tr.appendChild(tdDel);

            placeHolder.appendChild(tr);
        }
    };
}

    function delItem(e){
    e.preventDefault();

    // What do I have to do here?
}


texts: Simple linked hash map in JS (Node/browser)

texts:
I needed a simple data structure to cache the most recent few directory contents for this project I was working on. I thought a linked hash map would be the right approach since we will cache only one item per path (the key) and keep only X recent items. We will store the timestamp and directory contents as the "payload" for each node.

/**
 * A linked-list with key-based map. Use case: recent items cache, storing the
 * last X items with linear-time lookup and removal (constant average cost per
 * operation)
 *
 * - Adding an item to head will remove any existing items with that key
 * - Adding to head will remove an item from tail if needed to prevent
 *   exceeding max length
 */

function LinkedHashMap(maxLength) {
  this.map = {};
  this.head = null;
  this.tail = null;
  this.length = 0;
  this.maxLength = maxLength;
}

LinkedHashMap.prototype = {
  get: function(key) {
    var item = this.map[key] || {};
    return item.payload;
  },

  addHead: function(key, payload) {
    this.remove(key);
    if (this.length === this.maxLength) {
      this.removeTail();
    }
    var item = {
      key: key,
      prev: null,
      next: this.head,
      payload: payload
    };
    if (this.head) {
      this.head.prev = item;
    }
    this.head = item;
    if (!this.tail) {
      this.tail = item;
    }
    this.map[key] = item;
    this.length += 1;
  },

  removeTail: function() {
    if (this.tail) {
      this.removeItem(this.tail);
    }
  },

  // remove item by key
  remove: function(key) {
    var item = this.map[key];
    if (!item) return;
    this.removeItem(item);
  },

  // this removes an item from the link chain and updates length/map
  removeItem: function(item) {
    if (this.head === item) {
      this.head = item.next;
    }
    if (this.tail === item) {
      this.tail = item.prev;
    }
    if (item.prev) {
      item.prev.next = item.next;
    }
    if (item.next) {
      item.next.prev = item.prev;
    }
    delete this.map[item.key];
    this.length -= 1;
  }
};


texts: Leetcode Count of Smaller Numbers After Self solution

texts:
Question link

  You are given an integer array nums and you have to return a new
  counts array. The counts array has the property where counts[i] is the
  number of smaller elements to the right of nums[i].

Solution is done using customized BST where count stores the total number of elements lesser than current element found from left to right.

class Solution:
    def countSmaller(self, nums):
        class Node:
            def __init__(self, val):
                self.val = val
                self.left = None
                self.right = None
                self.count = 0

        def bst_insert(root, val, result, count):
            if not root:
                root = Node(val)
                root.left = None
                root.right = None
                result.append(count)
                return root
            if val > root.val:
                root.right = bst_insert(root.right, val, result, root.count + 1 + count)
            else:
                root.count += 1
                root.left = bst_insert(root.left, val, result, count)
            return root

        root = None
        result = []
        for num in nums[::-1]:
            if not root:
                root = Node(num)
                result.append(0)
            else:
                bst_insert(root, num, result, 0)
        return result[::-1]


texts: Testing the performance of a loop for a vector of unique_ptr

texts:
I wrote this simple program that tests how long it takes for a loop to iterate through a vector<unique_ptr<>>. I'm wondering if this a good way to perform such a speed test? Are there better methods to this?

Also, I can't seem to use myVector.max_size()(which is 1073741823) to allocate the maximum amount of entries for a vector. My program crashes even if I go above my current amount of 70 million.

Results:

> Basic took 0ms
> BasicR took 0ms
> Range took 0ms
> Iterator took 0ms
> IteratorR took 36ms

Program:

// main.cpp
#include <iostream>
#include <memory>
#include <vector>
#include <chrono>
#include <iterator>

namespace LoopType {
    enum Enum {
        Range,
        Basic,
        BasicR,
        Iterator,
        IteratorR
    };
}
class Test {
public:
    explicit Test(const int a) { mA = a; }
    int getNum() { return mA; }
private:
    int mA;
};

typedef std::vector<std::unique_ptr<Test>> TestVector;

// Loop Types
void RangeBasedForLoop(TestVector& vec) {
    for (auto& test : vec) {
        int num = test->getNum();
    }
}
void BasicLoop(TestVector& vec) {
    for (unsigned i = 0; i < vec.size(); ++i) {
        int num = vec[i]->getNum();
    }
}
void BasicLoopR(TestVector& vec) {
    for (unsigned i = vec.size() - 1; i > 0; --i) {
        int num = vec[i]->getNum();
    }
}
void IteratorLoop(TestVector& vec) {
    TestVector::iterator it;
    for (it = vec.begin(); it != vec.end(); ++it) {
        (*it)->getNum();
    }
}
void IteratorLoopR(TestVector& vec) {
    TestVector::reverse_iterator it;
    for (it = vec.rbegin(); it != vec.rend(); ++it) {
        (*it)->getNum();
    }
}

// Testing & Printing
long long TestLoop(TestVector& vec, void(*loop)(TestVector&)) {
    auto t1 = std::chrono::high_resolution_clock::now();
    loop(vec);
    auto t2 = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
}
void PrintLoopTime(LoopType::Enum type, TestVector& vec) {
    switch (type) {
    case LoopType::Basic:
        std::cout << "Basic took " << TestLoop(vec, &BasicLoop) << "ms" << std::endl;
        break;

    case LoopType::BasicR:
        std::cout << "BasicR took " << TestLoop(vec, &BasicLoopR) << "ms" << std::endl;
        break;

    case LoopType::Range:
        std::cout << "Range took " << TestLoop(vec, &RangeBasedForLoop) << "ms" << std::endl;
        break;

    case LoopType::Iterator:
        std::cout << "Iterator took " << TestLoop(vec, &IteratorLoop) << "ms" << std::endl;
        break;

    case LoopType::IteratorR:
        std::cout << "IteratorR took " << TestLoop(vec, &IteratorLoopR) << "ms" << std::endl;
        break;
    }
}

int main() {
    const unsigned long seventyMillion = 70000000UL;
    std::cout << "Creating vector..." << std::endl;
    std::vector<std::unique_ptr<Test>> testVector;
    testVector.reserve(seventyMillion);
    for (unsigned long i = 0; i < seventyMillion; ++i) {
        testVector.emplace_back(std::make_unique<Test>(i));
    }
    std::cout << testVector.size() << " Elements" << std::endl << std::endl;
    std::cout << "Testing loops..." << std::endl << std::endl;

    PrintLoopTime(LoopType::Basic, testVector);
    PrintLoopTime(LoopType::BasicR, testVector);
    PrintLoopTime(LoopType::Range, testVector);
    PrintLoopTime(LoopType::Iterator, testVector);
    PrintLoopTime(LoopType::IteratorR, testVector);

    std::cout << std::endl << "Any key to exit...";
    std::cin.get();
    return EXIT_SUCCESS;
}


texts:
So this a exercise from the book COMPUTERS SYSTEMS A PROGRAMMERS PERSPECTIVE

I need to add two signed numbers and in case it overflows or underflows return TMAX (011..1b) or TMIN (100..0b) respectively. In this case we can assumed two's complement representation.

The book imposes a set of rules that the solution must follow :

Forbidden:

Conditionals, loops, function calls and macros.
Division, modulus and multiplication.
Relative comparison operators (<, >, <= and >=).

Allowed operations:

All bit level and logic operations.
Left and right shifts, but only with shift amounts between 0 and w - 1
Addition and subtraction.
Equality (==) and inequality (!=) tests.
Casting between int and unsigned.

My code

int saturating_add(int x , int y) {
    int sum = x + y;
    int w = (sizeof(int) << 3) -1;
    int mask = (~(x ^ y) & (y ^ sum) & (x ^ sum)) >> w;
    int max_min = (1 << w) ^ (sum >> w);
    return  (~mask & sum) + (mask & max_min);
}

Compiled code in my machine

Note: I used the following command -> gcc -O2 -S sat_add.c.

leal    (%rdi,%rsi), %edx
    movl    %edx, %eax
    movl    %edx, %ecx
    xorl    %esi, %eax
    xorl    %edi, %esi
    xorl    %edx, %edi
    notl    %esi
    sarl    $31, %ecx
    andl    %esi, %eax
    addl    $-2147483648, %ecx
    andl    %edi, %eax
    sarl    $31, %eax
    movl    %eax, %esi
    andl    %ecx, %eax
    notl    %esi
    andl    %edx, %esi
    leal    (%rsi,%rax), %eax
    ret

So I want to know if there is a better solution in terms of elegance and performance. Also if there is a solution that compiles to a single instruction in x86_64 (Maybe PADDS although this instruction may not be the one I am looking for). Also any other kind of feedback is welcome.


texts: Project Euler #2 (Even Fibonacci numbers) in Swift

texts:
I figured working through Project Euler problems in Swift would be a good way to learn any tips or tricks.  For example, tuples are something I'm not used to using, but they proved useful here.  Using things makes me more confident with them, so perhaps this will help me find other uses for them in the future.

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

Here is my solution:

func swap(inout left: Any, inout right: Any) {
    let swap = left
    right = left
    left = swap
}

func findNextEvenFibonacci(var firstFibonacci: Int = 0, var secondFibonacci: Int = 1) -> (Int, Int) {
    do {
        firstFibonacci += secondFibonacci
        swap(&firstFibonacci, &secondFibonacci)
    } while firstFibonacci % 2 != 0

    return (firstFibonacci, secondFibonacci)
}

let maxFibonacci: Int = 4_000_000
var fibonacci: (first: Int, next: Int) = (0,1)
var sumOfEvenFibonnaccis: Int = 0

while fibonacci.next < maxFibonacci {
    fibonacci = findNextEvenFibonacci(firstFibonacci: fibonacci.first, secondFibonacci: fibonacci.next)
    sumOfEvenFibonnaccis += fibonacci.first
}

let answer = sumOfEvenFibonnaccis


texts:
I wrote a very small little DSL for spec testing:

(ns funky-spec.core)

(def described-entity (ref nil))

(defn it [fun & v]
  (assert (apply fun (cons (deref described-entity) v))))

(def it-is it)
(def it-is-the it)

(defmacro describe [value nest]
  `(dosync (ref-set described-entity ~value)
           ~nest))

(defmacro when-applied [nest]
  `(dosync (ref-set described-entity ((deref described-entity)))
           ~nest))

(defmacro when-applied-to [& args-and-nest]
  `(dosync (ref-set described-entity (apply (deref described-entity) (take (dec (count (quote ~args-and-nest))) (quote ~args-and-nest))))
           (eval (last (quote ~args-and-nest)))))

This turned out to be very nice, for writing some simple, concise specs:

(ns funky-spec.core-test
  (:require [clojure.test :refer :all]
            [funky-spec.core :refer :all]))

(describe 42
  (it = 42))

(describe 99
  (it not= 42))

(describe 0
  (it-is zero?))

(describe 99
  (it-is-the (complement zero?)))

(defn answer [] 42)

(describe answer
  (when-applied
    (it = 42)))

(describe identity
  (when-applied-to 99
    (it = 99)))

(describe +
  (when-applied-to 42 35
    (it = 77)))

(describe +
  (when-applied-to 42 35 9 10
    (it = 96)))

I'm new to Clojure and macros so any thoughts on this code would be appreciated. I have a few concerns that you could start with:

when-applied could (I believe) be an alias for when-applied-to. I can't get this to work with def, is there something I am missing?
Is there a better pattern I could use other than a "global" ref for the described-entity? I tried using let and shadowing, but couldn't get it to work with macros
In when-applied-to , there's a lot of quoting and an eval, I did this to keep it from pre-maturely executing. Is there a cleaner way to thunk it?


texts: Fahrenheit and Celsius converter in Rust

texts:
I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?

use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
    println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
    let mut convert_type = String::new();

    io::stdin().read_line(&mut convert_type)
        .expect("Failed to conversion type.");

    let t = String::from(convert_type);

    println!("You want to convert to: {}", t);
    println!("What temperature would you like to convert?");
    let mut temp = String::new();

    io::stdin().read_line(&mut temp)
        .expect("Failed to read temperature.");

    let temp: i32 = match temp.trim().parse() {
        Ok(temp) => temp,
        Err(_e) => {
            -1
        }
    };

    match t.as_str() {
        "C\n" => println!("{}", ftoc(temp)),
        "F\n" => println!("{}", ctof(temp)),
        _ => println!("t = {:?}", t),
}
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
    (c * (9 / 5)) + 32

}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
    (f-32) * (5 / 9)
}

Output:

    cargo run
   Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
    Finished dev [unoptimized + debuginfo] target(s) in 2.64s
     Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F

What temperature would you like to convert?
0
32


texts: Passing object back to Windows Form button event

texts:
I have windows form application. One button event starts the script via object called ScriptStarter. The status of object is used to pass message and color to UI (toolStripStatusLabel1). I'm not sure if this is good practice. Could you please give me advice or suggestion how to better set up the communication between object and UI? I have heard little about Action(). I don't know if should I consider using of this. Any suggestions are warmly welcomed.

    private void btnStartScript_Click(object sender, EventArgs e)
    {
        ScriptStarter scriptStarter = new ScriptStarter();
        scriptStarter.StartScript();
        toolStripStatusLabel1.Text = scriptStarter.Status.Message;
        toolStripStatusLabel1.ForeColor = scriptStarter.Status.FontColor;
    }

The class ScripStarter.cs is here (I've replaced some methods body with comment in this post):

class ScriptStarter
    {
        public StatusKeeper Status = new StatusKeeper();

        public void StartScript()
        {
            string scriptFilePath = Properties.Settings.Default.MyStartCacheScriptPath;
            if (scriptFilePath.Length == 0 || !File.Exists(scriptFilePath))
                scriptFilePath = setNewScriptFile();

            if (File.Exists(scriptFilePath))
            {
                tryToRunScript(scriptFilePath);
            }
            else
            {
                Status.Message = "Script not found";
                Status.FontColor = Color.Crimson;
            }
        }

        private void tryToRunScript(string scriptFilePath)
        {
            bool succeeded = runBatScript(scriptFilePath);
            if (succeeded)
            {
                Status.Message = "Script started";
                Status.FontColor = Color.ForestGreen;
            }
            else
            {
                Status.Message = "Script not started";
                Status.FontColor = Color.Crimson;
            }
        }

        private bool runBatScript(string scriptFilePath)
        {
            // returns true if run script was successful
        }

        private string setNewScriptFile()
        {
            // returns script path
        }
    }

The class StatusKeeper.cs

public class StatusKeeper
{
    public string Message { get; set; }
    public Color FontColor { get; set; }
}


texts: Consolidating a dictionary from nested dictionary

texts:
Currently learning from "LPTHW - Zed Shaw" and "Automating the boring stuff".

There is a nested dictionary of the type {'string1': {inner dict 1}, 'string2':{inner dict 2},...}.

I want a non nested consolidated dictionary of all the keys and values from all of the {inner dicts}. I have written the code below, but I am not convinced it is the most efficient way. I am looking for suggestions on how the code can be simplified by utilising logic within a single loop or by making use of some other modules and methods.

Is that new method efficient from a processing point of view?

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
           'Bob': {'ham sandwiches': 3, 'apples': 2},
           'Carol': {'cups': 3, 'apple pies': 1}}

item_list = []
count_list = []
consolidated = {}
all_items_list = list(allGuests.values()) #This is a list of sub dictionaries

#Loop for the number of guests who brought items
for guest in range(0, len(allGuests)):

#Creating 2 separate lists for 'items' and 'their count'

    item_list = item_list + list(all_items_list[guest].keys())
    count_list = count_list + list(all_items_list[guest].values())

#Creating a consolidated dictionary
for index in range(0, len(item_list)):

    if not consolidated.get(item_list[index]):
        consolidated.setdefault(item_list[index], count_list[index])

    else:
        consolidated[item_list[index]] = consolidated[item_list[index]] + count_list[index]

    pprint.pprint(consolidated)

Expected output:

{'apple pies': 1, 'apples': 7, 'cups': 3, 'ham sandwiches': 3, 'pretzels': 12}


texts:
By default, QSlider move his thumbtrack by a value belonging to the singleStep() prop on mouse click. To make thumbtrack jump directly at the mouse click point, we need to create a new class inherited by QSlider.

Header file (.h):

#include <QWidget>
#include <QAbstractSlider>
#include <QSlider>
#include <QMouseEvent>
#include <QStyle>
#include <QStyleOptionSlider>
#ifndef QIMPROVEDSLIDER_H
#define QIMPROVEDSLIDER_H

class QImprovedSlider : public QSlider
{
    Q_OBJECT
protected:
    void mousePressEvent(QMouseEvent *event);

public:
    explicit QImprovedSlider(QWidget *parent = 0);

    ~QImprovedSlider();

public slots:

private:

private slots:

signals:
    void onClick(int value);
};

#endif // QIMPROVEDSLIDER_H

Source file (.cpp):

#include "QImprovedSlider.h"

QImprovedSlider::QImprovedSlider(QWidget *parent) :
    QSlider(parent)
{

}

QImprovedSlider::~QImprovedSlider()
{
}

void QImprovedSlider::mousePressEvent(QMouseEvent *event) {
  QStyleOptionSlider opt;
  initStyleOption(&opt);
  QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);

  if (event->button() == Qt::LeftButton &&
      !sr.contains(event->pos())) {
    int newVal;
    if (orientation() == Qt::Vertical) {
       double halfHandleHeight = (0.5 * sr.height()) + 0.5;
       int adaptedPosY = height() - event->y();
       if ( adaptedPosY < halfHandleHeight )
             adaptedPosY = halfHandleHeight;
       if ( adaptedPosY > height() - halfHandleHeight )
             adaptedPosY = height() - halfHandleHeight;
       double newHeight = (height() - halfHandleHeight) - halfHandleHeight;
       double normalizedPosition = (adaptedPosY - halfHandleHeight)  / newHeight ;

       newVal = minimum() + (maximum()-minimum()) * normalizedPosition;
    } else {
        double halfHandleWidth = (0.5 * sr.width()) + 0.5;
        int adaptedPosX = event->x();
        if ( adaptedPosX < halfHandleWidth )
              adaptedPosX = halfHandleWidth;
        if ( adaptedPosX > width() - halfHandleWidth )
              adaptedPosX = width() - halfHandleWidth;
        double newWidth = (width() - halfHandleWidth) - halfHandleWidth;
        double normalizedPosition = (adaptedPosX - halfHandleWidth)  / newWidth ;

        newVal = minimum() + ((maximum()-minimum()) * normalizedPosition);
    }

    if (invertedAppearance())
        this->setValue( maximum() - newVal );
    else
        this->setValue(newVal);

    event->accept();
  }
  else {
        QSlider::mousePressEvent(event);
  }
  emit onClick(this->value());
}

This code works well, so is not a broken code. There is a way to improve this? Maybe trying to differentiate the direct jump from the handle dragging