texts: Rails controller to manage EC2 instances

texts:
I did a small sample application for an Interview. Since I didn't got accepted I would like your opinion on how to improve it.

The aux methods are private.
I have a usage_common to remove duplication in the usage and usage_instance methods
add_item_hash is used because the format written in the database is different from the used in the API response

The start stop and status actions are used to simple operations in EC2 instances

Maybe I should've broken it in services? one for usage, one for processes and one for EC2.

Should send the params already in the format for database and thus eliminate the methods build_usage_hash and build_process_hash

https://github.com/mabranches/monitor_api/blob/master/app/controllers/instances_controller.rb

class InstancesController < ApplicationController
  before_action :set_instance, only: [:show, :update, :destroy]

  def usage
    usage_common(:get, (Time.now - 24.hours).utc.iso8601, Time.now.utc.iso8601)
  end

  def usage_instance
    usage_common(:get_instance, params[:id], (Time.now - 24.hours).utc.iso8601, Time.now.utc.iso8601)
  end

  def processes_instance
    items = ProcessList.get_instance(params[:id])
    process_items = {}
    items.each do |item|
      process_items[item['instance_id']] = item
    end
    render json: process_items
  end

  def create
    usage = build_usage_hash params
    process = build_process_hash params

    Usage.create(usage)
    ProcessList.create(process)

    render json: [usage, process], status: :created
  rescue => e
    Rails.logger.error("Was not possible to update instance data: #{e.message}")
    render json: { error: e.message }, status: :unprocessable_entity
  end

  def processes
    items = ProcessList.get
    process_items = {}
    items.each do |item|
      process_items[item['instance_id']] = item
    end
    render json: process_items
  end

  def stop
    @params = params
    ec2_action(:stop, 'stopped')
  end

  def start
    @params = params
    ec2_action(:start, 'started')
  end

  def status
    @params = params
    ec2_instance do |ec2|
      @status = ec2.state.name
    end
  end

  private

  def usage_common(method, *args)
    items = Usage.send(method, *args)

    result = {}
    items.each do |item|
      add_item_hash(result, item)
    end
    render json: result
  end

  def ec2_instance
    instance_id = @params[:id]

    return render json: {}, status: :unprocessable_entity unless instance_id
    ec2 = Aws::EC2::Resource.new(region: 'us-west-2').instance(instance_id)
    @status = 'unknown'
    begin
      yield ec2
    rescue => e
      Rails.logger.error("Was not possible to execute action #{@params[:action]}: #{e.message}")
    end
    render json: { instance: instance_id, status: @status }
  end

  def ec2_action(method, status)
    ec2_instance do |ec2|
      ec2.send(method)
      @status = status
    end
  end

  def add_item_hash(result, item)
    result[item['instance_id']] ||= Hash.new { |h, k| h[k] = [] }
    result[item['instance_id']]['mem'] << item['mem']
    result[item['instance_id']]['disk'] << item['disk']
    result[item['instance_id']]['cpu'] << item['cpu']
    result[item['instance_id']]['usage_time'] << item['usage_time']
  end

  def build_usage_hash(params)
    instance = params[:instance]
    {
      instance_id: params[:id],
      cpu: instance[:cpu],
      mem: instance[:mem],
      disk: instance[:disk],
      usage_time: Time.now.utc.iso8601
    }
  end

  def build_process_hash(params)
    instance = params[:instance]
    {
      instance_id: params[:id],
      process: instance[:process].try(:values) || []
    }
  end
end


texts:
I would appreciate any feedback you could offer. I'm self-learning, so I don't really know a "standard" that my code should be up to. I'm also not sure how to get rid of that bit of logic at the bottom, or if it's acceptable.

class Board
    attr_reader :board, :place

    def initialize
        @board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        puts "Player 1 is X, Player 2 is O."
        show_board
    end

    def show_board
        @board.each_slice(3) { |x| puts x.join }
    end

    def get_place
        @place = gets.to_i - 1
    end

    def free_space?
        @board[place].is_a? Integer
    end

    def put_marker(mark)
        get_place
        until free_space?
            puts "Invalid move, choose again!"
            get_place
        end
        @board[place] = mark
        show_board
    end

    def player1_win_condition
        ary = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
        ary.any? do |array|
            array.all? { |num| @board[num - 1] == "X" }
        end
    end

    def player2_win_condition
        ary = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
        ary.any? do |array|
            array.all? { |num| @board[num - 1] == "O" }
        end
    end

    def draw_condition
        @board.all? { |num| num.is_a? String }
    end

    def end_game
        if player1_win_condition == true
            puts "Player 1 wins!"
            exit
        elsif player2_win_condition == true
            puts "Player 2 wins!"
            exit
        elsif draw_condition == true && player1_win_condition == false && player2_win_condition == false
            puts "It's a draw!"
            exit
        end
    end
end

class Player
    attr_accessor :mark

    def initialize(mark)
        @mark = mark
    end
end

player_1 = Player.new("X")
player_2 = Player.new("O")
new_board = Board.new

until new_board.end_game
    puts "Player 1 turn"
    new_board.put_marker(player_1.mark)
    if new_board.end_game != true
        puts "Player 2 turn"
        new_board.put_marker(player_2.mark)
    end
end


texts:
I have such a method which takes a URL, such as http://twitter.com/ttt or twitter.com/dasd, and should show its domain with http: http://twitter.com and name twitter

def show_domain(url):
    sites = {
        'twitter': ['http://www.twitter.com/', 'twitter'],
        'facebook': ['http://www.facebook.com/', 'facebook'],
        'pininterest': ['http://www.pininterest.com/', 'pininterest']
    }

    if sites['twitter'][0] in url:
        link = sites['twitter'][0]
        brand = sites['twitter'][1]
    elif sites['facebook'][0] in url:
        link = sites['facebook'][0]
        brand = sites['facebook'][1]

    else:
        link = sites['pininterest'][0]
        brand = sites['pininterest'][1]
    return link, brand

Is there way to optimise this code?


texts:
As far as readability and best practises go I am not sure how best to write this helper method:

Here are two options I have tried:

private decimal? selectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
     if(localTolerance == null)
     {
               if(globalTolerance == null){
                   return null;
               }else{
                   return globalTolerance;
               }
     }
    else
     {
               if(globalTolerance == null){
                    return localTolerance;
               }else{
                   if(globalTolerance < localTolerance){
                       return globalTolerance;
                   }else{
                       return localTolerance;
                   }
               }
         }
 }

Alternatively,

private decimal? selectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
           if (localTolerance == null && globalTolerance == null)
           {
               return null;
           }

           if (localTolerance != null && globalTolerance == null)
           {
               return localTolerance;
           }

           if (localTolerance == null && globalTolerance != null)
           {
               return globalTolerance;
           }

           if (globalTolerance < localTolerance)
           {
               return globalTolerance;
           }
           else
           {
               return localTolerance;
           }
  }

Which of these are better? Any other alternatives?


texts:
My code below find the duplicates based on 2 criteria:

The first criteria is the Name in Column A
The second criteria is the Country in Column D

Sheet("RawData") :

Sheets("Conso") after the macro:

What I am looking is to increase the speed of this code, because I am working with more than 150K rows and it takes hours.

Sub MDMDuplicates()

Dim WB As Workbook
Dim wsRawData As Worksheet, wsConso As Worksheet
Dim i As Long, j As Long, Lastrow As Long, LastrowConso as Long
Dim SupNameToCheck As String, ConsoSupplierDUNS As String, ConsoSupplierMDM As String, ConsoSupplierNAME As String

Set WB = ThisWorkbook
Set wsRawData = WB.Sheets("RawData")
Set wsConso = WB.Sheets("Conso")

Lastrow = wsRawData.Range("A" & Rows.Count).End(xlUp).Row

Application.ScreenUpdating = False
With wsRawData

For i = 2 To Lastrow

SupNameToCheck = .Cells(i, "A").Value
SupCountryToCheck = .Cells(i, "D")
ConsoSupplierDUNS = ""
ConsoSupplierMDM = ""
ConsoSupplierNAME = ""

j = Lastrow
    Do
        If i <> j And SupNameToCheck = .Cells(j, "A") And SupCountryToCheck = .Cells(j, "D") Then

            If ConsoSupplierNAME = "" Then

            ConsoSupplierDUNS = .Cells(i, "B") & "," & .Cells(j, "B")
            ConsoSupplierMDM = .Cells(i, "C") & "," & .Cells(j, "C")
            ConsoSupplierNAME = SupNameToCheck & "," & .Cells(j, "A")

            Else

            ConsoSupplierDUNS = .Cells(j, "B") & "," & ConsoSupplierDUNS
            ConsoSupplierMDM = .Cells(j, "C") & "," & ConsoSupplierMDM
            ConsoSupplierNAME = .Cells(j, "A") & "," & ConsoSupplierNAME

            End If

           .Cells(j, "A").EntireRow.Delete

        End If

        j = j - 1

      Loop Until j = 1

LastrowConso = wsConso.Range("A" & Rows.Count).End(xlUp).Row + 1
If Not ConsoSupplierNAME = "" Then
        wsConso.Cells(LastrowConso, "B") = ConsoSupplierDUNS
        wsConso.Cells(LastrowConso, "C") = ConsoSupplierMDM
        wsConso.Cells(LastrowConso, "A") = ConsoSupplierNAME
    Else
        wsConso.Cells(LastrowConso, "B") = .Cells(i, "B")
        wsConso.Cells(LastrowConso, "C") = .Cells(i, "C")
        wsConso.Cells(LastrowConso, "A") = SupNameToCheck
 End If

Next i
Application.ScreenUpdating = True

End With
End Sub


texts: Find the best path amongst N random points

texts:
For an application with a graphical canvas, I want to generate N points. But then I want to link those points, and I want to find the best path through those points.
I wanted to use a dynamic programming approach as N will be limited to a maximum of 15 points.

The following program works for me running

python dp.py

with python 2.7.3.

I would appreciate any tips to improve the speed and the memory use of that program.

The content of dp.py is

import random
import math

# Container for the points
points = []

# Generate N random points
def create_random_points(size):
    global points
    for n in range(size):
        x = random.uniform(0, 500)
        y = random.uniform(0, 500)
        points.append([x, y])

# Find the path through those points
def order_points():
    global points

    # How many points do we have?
    L = len(points)

    # No points at all
    if L < 1:
        return []

    # A single point
    if L == 1:
        return [0]

    # Calculate all the different distances
    distances = [0 for n in range(L * L)]

    for n in range(L):
        for m in range(n):
            A = points[n]
            B = points[m]
            distances[n * L + m] = math.sqrt((B[0] - A[0]) ** 2 + (B[1] - A[1]) ** 2)
            distances[m * L + n] = distances[n * L + m]

    # Calculate the best path: dynamic programming
    # Initialise the distance and path variables
    sum_path = [0 for n in range(L - 1)]
    path = [[0] for n in range(L - 1)]

    # Calculate the first iteration
    for point_m in range(1, L):
        sum_path[point_m - 1] += distances[point_m]
        path[point_m - 1].append(point_m)

    # Calculate the following iterations
    for n in range(1, L - 1):
        for point_m in range(1, L):
            dist = -1
            prev = -1
            for point_n in range(1, L):
                if point_n == point_m:
                    continue
                if point_n in path[point_m - 1]:
                    continue

                d = distances[point_m * L + point_n]
                if dist == -1 or dist < d:
                    dist = d
                    prev = point_n
            sum_path[point_m - 1] += dist
            path[point_m - 1].append(prev)

    # Calculate the last iteration
    for point_m in range(1, L):
        sum_path[point_m - 1] += distances[point_m]
        path[point_m - 1].append(0)

    best_score = min(sum_path)
    for point_m in range(1, L):
        if sum_path[point_m - 1] == best_score:
            best_path = path[point_m - 1]

    return best_path

create_random_points(5)

print 'We have the following points:'
print points

print ''
print 'And the best path is:'
print order_points()


texts: Comparing each property to the same value

texts:
My code keeps some int value about the date range, and there is a method to check if all of it is zero. Is there a better way to do it than doing this?

public bool IsAllDayZero
{
    get
    {
        return
            Today == 0 &&
            Days1_2 == 0 &&
            Days3_6 == 0 &&
            Days7_10 == 0 &&
            Days11_15 == 0 &&
            Days16_30 == 0 &&
            Days31_45 == 0 &&
            Days46_60 == 0 &&
            Days60Plus == 0
            ;
        }
}


texts: Simulation of Multiple Producer Consumer

texts:
I am trying to implement the Multiple Producer-Consumer problem. I have made the buffer as the lock to maintain consistency of the system. Does this system actually implement multithreading? How can I improve the system using wait and notify?

Producer.java

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

class Producer extends Thread
{
    private Buffer buffer;
    private String name;

    Producer(Buffer buffer,String name)
    {
        this.buffer = buffer;
        this.name = name;
    }
    @Override
    public void run()
    {
        while(true)
        {
            Random r = new Random();
            int x = r.nextInt(100);
            produce(x);
            try
            {
                //(r.nextInt(6)+1)*
                Thread.sleep(100);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public void produce(int x)
    {
        synchronized(buffer)
        {

            if(buffer.size()==buffer.cap)
            {
                System.out.println("QF");
            }
            else
            {
                buffer.add(x);
                System.out.println(name+": "+x);
            }
        }
    }
}

Buffer.java

class Buffer
{
    private Vector<Integer> buffer;
    int cap;
    Buffer(int cap)
    {
        buffer = new Vector<Integer>();
        this.cap = cap;
    }
    int size()
    {
        return buffer.size();
    }
    boolean isEmpty()
    {
        return buffer.isEmpty();
    }
    void add(int x)
    {
        buffer.add(x);
    }
    int remove()
    {
        if(buffer.isEmpty())
            return -1;
        int x = buffer.firstElement();
        buffer.remove(buffer.firstElement());
        return x;
    }
}

Consumer.java

class Consumer extends Thread
{
    private Buffer buffer;
    private String name;

    Consumer(Buffer buffer,String name)
    {
        this.buffer = buffer;
        this.name   = name;
    }
    @Override
    public void run()
    {
        while(true)
        {
            consume();
            try
            {
                Random r = new Random();
                Thread.sleep(100);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public void consume()
    {
        synchronized(buffer)
        {
            int x = buffer.remove();
            if(x==-1)
            {
                System.out.println("QE");
            }
            else
            {
                System.out.println(name+": "+x);
            }
        }
    }
}

App.java

public class App
{
    public static void main(String args[]){
        Buffer b = new Buffer(5);
        Producer p = new Producer(b,"P1");
        Producer p2 = new Producer(b,"P2");
        Consumer c = new Consumer(b,"C1");
        p.start();
        p2.start();
        c.start();
    }
}


texts: Matching a checkbox caption to a cell's value

texts:
There are 30 checkboxes that need to have their caption compared to a cell value.

The basic code is repeated 30 times for 30 different check boxes

The only Lines that Change per CheckBox are the Following:

The First Line - CheckBox3.Value (will increase by 1 for every checkbox)
Fourth Line from Bottom - Cells(eRow, 24).Value = Controls("CheckBox" & 3).Caption (Needs to match Checkbox Selected (3, 4, 5 etc.))
Third Line from Bottom - Cells(eRow, 25).Value = TextBox11.Value (will increase by 1 for every checkbox)

The basic block is:

If CheckBox3.Value = True Then
    eRow = Sheet3.Cells(Rows.Count, 6).End(xlUp).Offset(1, 0).Row
    Cells(eRow, 7).Value = ComboBox1.Value
    If CheckBox29.Value = True Then
        Cells(eRow, 8).Value = Controls("CheckBox" & 29).Caption
            If CheckBox1.Value = True Then
                Cells(eRow, 14).Value = "Yes"
            Else
                Cells(eRow, 14).Value = "No"
            End If
        Cells(eRow, 15).Value = ComboBox6.Value
        Cells(eRow, 16).Value = ComboBox7.Value
            If CheckBox2.Value = True Then
                Cells(eRow, 17).Value = "Yes"
            Else
                Cells(eRow, 17).Value = "No"
            End If
        Cells(eRow, 18).Value = ComboBox8.Value
        Cells(eRow, 19).Value = TextBox5.Value
        Cells(eRow, 20).Value = TextBox6.Value
        Cells(eRow, 21).Value = TextBox7.Value
        Cells(eRow, 22).Value = TextBox8.Value
        Cells(eRow, 26).Value = TextBox9.Value
        Cells(eRow, 27).Value = TextBox10.Value
    Else
        Cells(eRow, 8).Value = "Sales Call"
        Cells(eRow, 15).Value = "-"
        Cells(eRow, 16).Value = "-"
        Cells(eRow, 18).Value = "-"
        Cells(eRow, 19).Value = "-"
        Cells(eRow, 20).Value = "-"
        Cells(eRow, 21).Value = "-"
        Cells(eRow, 22).Value = "-"
        Cells(eRow, 26).Value = "-"
        Cells(eRow, 27).Value = "-"
        Cells(eRow, 14).Value = "No"
        Cells(eRow, 17).Value = "No"
    End If
    Cells(eRow, 9).Value = ComboBox3.Value
    Cells(eRow, 10).Value = TextBox2.Value
    Cells(eRow, 11).Value = TextBox3.Value
    Cells(eRow, 12).Value = TextBox4.Value
    Cells(eRow, 13).Value = ComboBox4.Value
    Cells(eRow, 23).Value = ComboBox5.Value
    Cells(eRow, 24).Value = Controls("CheckBox" & 3).Caption
    Cells(eRow, 25).Value = TextBox11.Value
    Cells(eRow, 6).Value = TextBox1.Value
End If

The above code is repeated another 29 times with those three lines changed to match the corresponding checkbox.

Addendum

I have the Linked Spread Sheet - Follow Up Spread Sheet

Basically I created a userform for my sales reps to fill out with there sales calls. we have approximately 30 different product lines so I made it where they could enter one call and if they talked about more than one of our lines they could just check they box and add a comment. so in theory if they talked about all the products we offer the one call would have 30 new lines in the spreadsheet.

The macro works great and does what it needs to but the problem I am running into was with 32 bit Excel versions they would get an error saying file is to large so I broke the code into 2 which isn't very efficient.

I am trying to use loops and arrays but since I am teaching myself how to code I am running into issues.


texts: Functions that build a path to the model and command files for some tests

texts:
I'm currently working in a model-based testing tool. I'm writing some integration tests for it, which require two kind of input:

Model files: which contain models to be parsed and run by the tool.
Command files: which contain commands to be input to the tool.

To reduce the boilerplate I've written two functions that build a the path to the model and command files depending on the type of tests. The solution I came up with is shown below. However I don't like the fact that I have to use a dummy parameter in my type-classes.

{-
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
{-# LANGUAGE OverloadedStrings #-}
-- | Utilities for working with tests paths within 'sqatt'.
module Paths
    ( BenchTest (BenchTest)
    , IntegrationTest (IntegrationTest)
    , txsFilePath
    , txsCmdPath
    )
where

import           Data.Text
import           Filesystem.Path
import           Filesystem.Path.CurrentOS
import           Prelude                   hiding (FilePath)

-- | Types of tests supported by 'sqatt'.
class TestType a where
    -- | Directory that contains the model and command files that are used in
    -- the tests. This is relative to 'sqatt' root folder.
    dataDir :: a -> FilePath

-- | Test of the examples used in the benchmarks.
data BenchTest = BenchTest
instance TestType BenchTest where
    dataDir _ = "data" </> "bench"

-- | Integration test.
data IntegrationTest = IntegrationTest
instance TestType IntegrationTest where
    dataDir _ = "data" </> "integration-test"

-- | Make a TorXakis model file path. It appends the given directory to the
-- test data directory, and appends the '.txs extension to the given file path.
--
txsFilePath :: TestType a
            => a
            -> FilePath -- ^ Directory of the current example.
            -> Text     -- ^ File name of the current example.
            -> FilePath
txsFilePath tt currExampDir fp =
  dataDir tt </> currExampDir </> fromText fp <.> "txs"

-- | Make a TorXakis commands file path. It appends the given directory to the
-- test data directory, and appends the .txscmd extension to the given file
-- path.
txsCmdPath :: TestType a
           => a        -- ^ Test type. This will determine the location of the test data directory.
           -> FilePath -- ^ Directory of the current example.
           -> Text     -- ^ File name of the current example.
           -> FilePath
txsCmdPath tt currExampDir fp =
  dataDir tt </> currExampDir </> fromText fp <.> "txscmd"


texts:
Please tell me what you think of this its my first try and I have only been learning Python for 3 days now, works with both 'index' and 'find':

data = ["XBOX 360 | 150 | New",
        "PlayStation 3 | 35 | Broken",
        "Windows 8 | 275 | New"]

Id = 0
one = data[Id].index("|")
two = data[Id].index("|", one+1)

product = data[Id][:one]
price = data[Id][one+2:two]
condition = data[Id][two+2:]

print(product)
print(price)
print(condition)

#Just add more like these:
#three = data[Id].index("|", two+1)
#four = data[Id].index("|", three+1)
#etc... If you want to add more 'Pipes'
#Add one to each 'pipe' no more then that or you'll get an error

#You can add as many new 'data' items as you want
#just change the 'Id' to view them


texts: Throw an exception to control the flow of code execution

texts:
There is a recommendation not to use an Exception to control the flow of execution. This gives me a reason for doubt when I do something like this:

 public void initApplication(String input) {
        try {
            MyClass mClass = new mClass(input);
            saveToDatabase(mClass);
            updateSettingsTheAppIsReady();
        } catch (CancelPreparationsException e) {
            showErrorMessageToUser();
            doRollbacks();
        }
    }

mClass instantiation, save operation to a database, settings update may go wrong, each of them throw their own exceptions, which I catch within the methods/classes and throw my custom exception to stop the initApplication() method execution.

This sounds an easier way than having preconditions checking like:

Create MyClass object.
Check the MyClass object is created then save it to db.
Ensure the object was saved in db then update settings.

Is it really not recommended way of using the Exception to control the flow? Thank you.


texts:
For the record, this is part of a homework assignment, but I have already implemented a solution. I am simply wondering if there is a better way to do it.

Background: I am asked to write a procedure, (complete ls), that takes a list of elements and creates a fully connected graph from them, i.e. complete. I am able to write helper functions to assist in my solution.

A sample graph is defined as '((a (b c)) (b (a c))). Where the car of each sub-list is a vertex and the cdr of each sub-list is a list of vertices that vertex is connected to.

For example:

(complete? '((a (b c)) (b (a c)) (c (a b)))) => #t
(complete? '((a (b)) (b (a c)) (c ()))) => #f

My working solution:

(define (complete ls)
    (helpComplete ls ls)
)

(define (helpComplete origLst ls)
  (if (null? ls)
    '()
    (cons
      (list
        (car ls)
        (remove-first (car ls) origLst))
      (helpComplete origLst (cdr ls)))))

(define (remove-first element ls)
  (cond
    [(null? ls) '()]
    [(eqv? element (car ls)) (cdr ls)]
    [else (cons (car ls) (remove-first element (cdr ls)))]
  ))

I am not allowed to change the inputs for the complete procedure, as our grading server is expecting it to look like it is now. I am also not allowed to use and ! procedures. We are running Petite Chez Scheme Version 8, if anyone cares.

The above code does work, but I was wondering if there is a better way to do it?


texts: Performance difference between declaring Regex inside or outside of often-called method.

texts:
I am curious as to what the performance/functional differences are between:

private bool OftenCalledMethod(string s)
{
    Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase);
    return (reg.IsMatch(s));
}

Versus:

readonly Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase);
private bool OftenCalledMethod(string s)
{
    return (reg.IsMatch(s));
}

Does the compiler optimize the former in such a way that it doesn't matter? Or is the object reg being allocated repeatedly and unnecessarily?


texts:
Here is the problem description (from an algorithm course: https://www.coursera.org/learn/algorithm-design-analysis):

  The goal of this problem is to implement a variant of the 2-SUM
  algorithm (covered in the Week 6 lecture on hash table applications).

  The file contains 1 million integers, both positive and negative
  (there might be some repetitions!). This is your array of integers,
  with the \$i\$th row of the file specifying the \$i\$th entry of the array.

  Your task is to compute the number of target values \$t\$ in the interval
  [-10000,10000] (inclusive) such that there are distinct numbers \$x,y\$ in
  the input file that satisfy \$x+y=t\$.

I wrote the following Python program. It runs already 25 minutes and just calculated 6200 of 20000 numbers.
This is too slow.

import sys

def has_two_sum(n,num_set,nums):
  res = any(((n-x) in num_set) and 2*x !=n for x in nums)
  return res

with open(sys.argv[1], 'r') as fp:
  nums = [int(line) for line in fp]
  num_set = set(nums)

two_sum = sum(1  for n in range(-10000,10001) if has_two_sum(n,num_set,nums))
print(two_sum)


texts: Delegated condition_variable against spurious wakeup

texts:
This is my attempt at dealing with spurious wakeups: A new class which replaced std::condition_variable in my code.

Some questions which came to my mind are (and I hope CR is the right place for that):

Is this actually effective? Or will I run into concurrency-related problems?
Would inheriting std::condition_variable be better than delegation?
Is it better to use bool guarded by a std::mutex or std::atomic<bool>?

This is the class:

#include <mutex>
#include <condition_variable>

class Condition {
private:
    std::condition_variable _condition; // Delegation
    bool _waiting;
    std::mutex _internalMutex;
public:
    Condition()
        : _waiting(false) {}

    void wait(std::unique_lock<std::mutex>& lock)
    {
        std::unique_lock<std::mutex> lock(_internalMutex);
        _waiting = true;
        _condition.wait(lock, [this]() { return !_waiting; });
    }

    template< class Rep, class Period >
    void wait_for(std::unique_lock<std::mutex>& lock,
                  const std::chrono::duration<Rep, Period>& relTime)
    {
        std::unique_lock<std::mutex> lock(_internalMutex);
        _waiting = true;
        _condition.wait_for(lock, relTime, [this]() { return !_waiting; });
    }

    template< class Clock, class Duration >
    void wait_until(std::unique_lock<std::mutex>& lock,
                    const std::chrono::time_point<Clock, Duration>& timeoutTime)
    {
        std::unique_lock<std::mutex> lock(_internalMutex);
        _waiting = true;
        _condition.wait_until(lock, timeoutTime, [this]() { return !_waiting; });
    }

    void notify_all()
    {
        std::unique_lock<std::mutex> lock(_internalMutex);
        _waiting = false;
        _condition.notify_all();
    }

    void notify_one()
    {
        std::unique_lock<std::mutex> lock(_internalMutex);
        _waiting = false;
        _condition.notify_one();
    }
};

The usage would be the same as with std::condition_variable (but without the typical caveat that you have to prevent spurious wakeups by encapsulating .wait() with a predicate check.


texts: Missing level of technical depth (Recursive to Iterative)

texts:
I recently have given a coding test in a reputable IT company. There were three coding questions.

They refused me by saying that

  as we felt they didn't demonstrate the level of technical depth we're
  seeking from candidates

Please help me understanding what type of the technical depth my solution is missing? Thanks

Question 2 : Missing level of technical depth (Flatten Tree)

Question 3 : Missing level of technical depth (Common Ancestor)

and this is the 1st question.

Question 1:

  Reimplement this code so that its results will always be the same, but
  that it does not cause a stack overflow on large inputs.  Your
  solution must still implement the Folder interface.

Answer 1:

package iteration;

import java.util.Queue;

public interface Folder<T, U>
{
    U fold(U u, Queue<T> list, Function2<T,U,U> function);
}

package iteration;

public interface Function2<T, U, R>
{
  R apply(T t, U u);
}

package iteration;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class MyFolder<T, U> implements Folder<T, U>
{

     public U fold(U u, Queue<T> ts, Function2<T, U, U> fun) {

        if(u == null || ts == null || fun == null)
            throw new IllegalArgumentException();

        if (ts.isEmpty()) {
            return u;
        }

      //get an iterator first instead of forEach loop, because poll() is modifying underlying collection/queue
        Iterator<T> iter = ts.iterator();
        while (iter.hasNext()) { //loop over the items

            u = fun.apply( ts.poll() , u);

        }

        return u;
    }

    public static void main(String[] args) {

        Folder<Integer,Integer> folder = new MyFolder<Integer, Integer>();

        Queue<Integer> q = new LinkedList<Integer>();

        for(int lop =0; lop < 1000000; lop++ ){ //add some values in the Queue
            q.add(lop);
        }
        Integer result = folder.fold(0, q, new Function2<Integer, Integer, Integer>() {
            public Integer apply(Integer val1, Integer val2) {
                return val1 + val2;
            }
        });

        System.out.println("Result: " + result);
    }
}


texts: I want to get weekdays for common time sets from the following hashmap

texts:
I have the following HashMap :

  HashMap<String, String> days = new HashMap<String, String>(){
        days.put("MON", "9-5");
        days.put("TUE", "9-4");
        days.put("WED", "9-5");
        days.put("THU", "9-5");
        days.put("FR", "9-5");
        days.put("SAT", "Closed");
        days.put("SUN", "Closed");
};

I want to display following output :

  MON-WED-THU-FRI : 9-5,
  TUE: 9-4,
  SAT-SUN : Closed

NOTE:The value of hashmap("9-5") may change depending upon the inputs from the admin panel.

I have done the below code but it's too lengthy:

    private void days() {

         String timing1 = null;
         String timing2 = null;
         String timing3 = null;
         String timing4 = null;
         String timing5 = null;
         String timing6 = null;
         String timing7 = null;

         ArrayList<String> time1 =new ArrayList<>();
         ArrayList<String> time2 =new ArrayList<>();
         ArrayList<String> time3 =new ArrayList<>();
         ArrayList<String> time4 =new ArrayList<>();
         ArrayList<String> time5 =new ArrayList<>();
         ArrayList<String> time6 =new ArrayList<>();
         ArrayList<String> time7 =new ArrayList<>();

         //iterating over the hash map and taking value ie time storing in respected variable

        for (Map.Entry<String, String> entry : days.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println("key" + key + "Val" + value.toString());

            if (timing1 ==null || timing1.equals(value.toString())){
                timing1 = value.toString();
                continue;
            }

            if (timing2 ==null || timing2.equals(value.toString())){
                timing2 = value.toString();
                continue;
            }

            if (timing3 ==null || timing3.equals(value.toString())){
                timing3 = value.toString();
                continue;
            }

            if (timing4 ==null || timing4.equals(value.toString())){
                timing4 = value.toString();
                continue;
            }

            if (timing5 ==null || timing5.equals(value.toString())){
                timing5 = value.toString();
                continue;
            }

            if (timing6 ==null || timing6.equals(value.toString())){
                timing6 = value.toString();
                continue;
            }

            if (timing7 ==null || timing7.equals(value.toString())){
                timing7 = value.toString();

            }

        }

         //based on value from hash-map appending the key ie. days name(eg. MON) to the respected array-list

        for (Map.Entry<String, String> entry : days.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (timing1!=null && timing1.equals(value.toString())){

                time1.add(key);
                continue;
            }

            if (timing2!=null && timing2.equals(value.toString())){

                time2.add(key);
                continue;
            }

            if (timing3!=null && timing3.equals(value.toString())){

                time3.add(key);
                continue;
            }

            if (timing4!=null && timing4.equals(value.toString())){

                time4.add(key);
                continue;
            }

            if (timing5!=null && timing5.equals(value.toString())){

                time5.add(key);
                continue;
            }

            if (timing6!=null && timing6.equals(value.toString())){

                time6.add(key);
                continue;
            }

            if (timing7!=null && timing7.equals(value.toString())){

                time7.add(key);
               // continue;
            }

        }


texts: Suppress API call in Redux Saga based on a timer

texts:
I have an API that provides data that is updated on an infrequent schedule, about once every 2½ minutes on average. Assuming that it's okay to fetch only as often as every 2½ minutes or less often, I'd like to construct a saga (I use redux-saga) in a way that it does nothing if it's not yet time to do an API call. The code I came up with is quite simplistic (API error handling omitted):

import { select, put, call } from "redux-saga/effects";

const FETCH_INTERVAL = 1000 * 60 * 60 * 2.5;

function* fetchApiSaga(apiUrl) {
  // get data from the store
  const data = select(state => state.theDataWeNeed);

  // signal to the user that we're about to fetch data
  put(WAITING_FOR_DATA);

  // if fetched 2.5 ago or earlier, fetch again
  if (!data || new Date() - !data.lastFetchedAt > FETCH_INTERVAL) {
    const response = yield call(apiUrl);

    // signal to the user that now we have new data from the API
    put(REWRITE_DATA, response);
  } else {
    // signal to the user that we just reuse old data
    put(JUST_USE_CACHED_DATA);
  }
}

Now, I have two questions:

Is this an idiomatic way to suppress consecutive actions in Redux Saga based on time?
Is this idiomatic Redux Saga if the generator function selects from the store and therefore is not pure?


texts: Show/hide function with multiple div ids

texts:
I know close to nothing about jQuery, but I swear I'm trying to learn. The thing is, I've got some code that works, but I know it's repetitive and probably not kosher for a real programmer, which is why I've turned to you all.

What I want to do is show/hide (or toggle, whatever you think is best) some informational divs, or so you might call them, on this page.

The show/hide code that I have right now stands at this:

    $(document).ready(function(){

    $('#meet_growlab, #buddy_tv').hide();

    $('a#growlab').click(function(){
    $('#meet_growlab').show('slow');
});

    $('a#growlab_close').click(function(){
    $('#meet_growlab').hide('slow');
})

    $('a#buddytv').click(function(){
    $('#buddy_tv').show('slow');
});

    $('a#buddytv_close').click(function(){
    $('#buddy_tv').hide('slow');
})

});

With the HTML being:

BLAH BLAH BLAH

Close

BLAH BLAH BLAH

Close

Meet GrowLab - Canada’s Y-Combinator Arrives in Vancouver (June 24, 2011)

Building the Web's Best Entertainment-Based Community Site: Andy Liu, CEO and Founder of BuddyTV (April 1, 2011)

It works, but it's not pretty.


texts:
As an answer to excersise 2.3 in Chris Okasaki's book, Purely Functional Data Structures,

  Inserting an existing element into a binary search tree copies the
  entire search path even though the copied nodes are indistinguishable
  from the originals. Rewrite insert using exceptions to avoid this
  copying. Establish one handler per insertion rather than one handler
  per  iteration.

I've written the following haskell implementations of insertion in a binary heap:

import Data.Maybe

data Tree e = Leaf | T (Tree e) e (Tree e) deriving Show

empty = Leaf

insert x Leaf = T Leaf x Leaf
insert x tree@(T l e r)
  | x == e = tree
  | x < e = T (insert x l) e r
  | otherwise = T l e (insert x r)

ins x t =
  t >>= \t -> case t of
                Leaf   -> Just $ T Leaf x Leaf
                tree@(T l e r)
                  | x == e -> Nothing
                  | x < e -> (ins x (Just l)) >>= \nt -> Just $ T nt e r
                  | ot herwise -> (ins x (Just r)) >>= \nt -> Just $ T l e nt

fastInsert x t =
  fromMaybe t $ ins x $ Just t

The fastInsert function (using ins as a 'helper') and the insert function will return the same tree given the same input, but fastInsert wont copy sub-trees if no insertion is needed (if the tree already contains the node to be inserted).

The question is: how would this look if written more idiomatically, with regard to monadic operations/syntax in ins?

Another question: I'm using monads as a substitute for exceptions as suggested in the book. The point is to avoid rebuilding (reference copying) the tree when returning in the recursive calls. How should I have gone about this?


texts:
I am currently working on a game, and I get the configuration in an .ini file, and I get information with this library https://github.com/benhoyt/inih I would like to improve the readability / performance of this code, as I do not know much about good practices.

include "project.h"

// typedef struct s_server_conf {
//      const char              *ip;
//      unsigned int    port;
// }                            t_server_conf;

// typedef struct       s_db_conf {
//      const char              *host;
//      const char              *user;
//      const char              *passwd;
//      const char              *db;
//      unsigned int    port;
// }                            t_db_conf;

// typedef struct s_conf {
//      t_server_conf   server;
//      t_db_conf               conf;
// }                            t_conf;

static int      parse_server(t_conf *conf, const char *name, const char *value)
{
        # define MATCH(n) (strcmp(name, n) == 0)

        if (MATCH("ip"))
                conf->server->ip = strdup(value);
        else if (MATCH("port"))
                conf->server->port = atoi(value);
        else
                return (0);
        return (1);
}

static int      parse_database(t_conf *conf, const char *name, const char *value)
{
        # define MATCH_NAME(n) (strcmp(name, n) == 0)

        if (MATCH_NAME("host"))
                conf->db->host = (strdup(value));
        else if (MATCH_NAME("user"))
                conf->db->user = (strdup(value));
        else if (MATCH_NAME("passwd"))
                conf->db->passwd = (strdup(value));
        else
                return (0);
        return (1);
}

static int      handler(void *conf, const char *section, const char *name, const char *value)
{
        # define MATCH_SECTION(s) (strcmp(section, s) == 0)

        printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section)
;

        if (MATCH_SECTION("database"))
                return (parse_database((t_conf*)conf, name, value));
        if (MATCH_SECTION("server"))
                return (parse_server((t_conf*)conf, name, value));
        return (0);
}

void            clear_conf(t_conf *conf)
{
        if (conf->db)
                free(conf->db);
        if (conf->server)
                free(conf->server);
        free(conf);
}

static  t_conf          *create_conf(void)
{
        t_conf  *conf;

        if (!(conf = (t_conf*)malloc(sizeof(t_conf))))
                return (NULL);
        memset(conf, '\0', sizeof(t_conf));
        if (!(conf->db = (t_db_conf*)malloc(sizeof(t_db_conf))))
        {
                clear_conf(conf);
                return (NULL);
        }
        conf->db->port = 3306;
        if (!(conf->server = (t_server_conf*)malloc(sizeof(t_server_conf))))
        {
                clear_conf(conf);
                return (NULL);
        }
        return (conf);
}
t_conf          *get_conf(void)
{
        t_conf  *conf;

        if (!(conf = create_conf()))
                return (NULL);
        if (ini_parse("settings.ini", handler, conf) < 0)
        {
                printf("Unable to load configuration\n");
                exit (1);
        }
        return (conf);
}


texts:
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.

The IsIsogram() method takes a string and returns boolean value.

INPUT: anik      OUTPUT: true
INPUT: A nika    OUTPUT: false

Approach 01: Using Dictionary<TKey, TValue>

static bool IsIsogram(string str)
    {
        //create a dictionary with 26 keys and assign false as default value
        var storeOccurance = new Dictionary<int, bool>();
        for (int i = 0; i <= 25; i++)
        {
            storeOccurance[i] = false;
        }

        str = Regex.Replace(str, "[ -]", ""); //ignore whitespace and dash

        //iterate over each character of the string
        foreach (var ch in str.ToLower())
        {
            //(ch - 'a') is used to calculate the key. Check if the character key has false as it's value,
            //meaning they were never stored
            if (!storeOccurance[ch - 'a'])
            {
                storeOccurance[ch - 'a'] = true; //assign true when they are stored in the dictionary
            }
            else //otherwise, if a character key has true as it's value then it means that it exists in the dictionary
            {
                return false; //return false and exits the iteration..Multiple occurance in dictionary
                               //means the string has repeating character so it's not Isogram
            }
        }
        return true;
    }

Approach 02: Using HashSet<T>

static bool IsIsogram(string str)
    {
        //TRICK: HashSet<T>.Add(T) returns false if an item already exists in HashSet<T>,
        //otherwise returns true and add the character to the datastructure

        var charHash = new HashSet<char>();

        foreach (var ch in str.ToLower())
        {
            //check if the charHash.Add() returns false, if it does then terminate
            //as it means the character already exists
            if (!charHash.Add(ch) && char.IsLetter(ch))
                return false;
        }
        return true; //otherwise return true
    }

Approach 03: Using LINQ

static bool IsIsogram(string str)
    {                                    //Suppose "anik a" is a given string
        return str.Where(char.IsLetter) //filter only the letters ||here- only a, n, i, k, a will be taken
                  .GroupBy(char.ToLower) //create group by characters(and transform them to lowercase) || here, there will be a group for each character a, n, i, k
                  .All(g => g.Count() == 1); //for every group, count the number of it's element and check if it's 1
                                            //|| here, 'a' group has 2 elements so it return false though other groups has only one element in their group
    }

Given those above approaches:

Which approach would you recommend regarding readability, clean code and performance?
Is there any scope for improvement in the existing approaches?


texts:
I wrote a generic Queue that could with work any data type you give it. The Queue can do any the basic operations that you would expect a Queue can do such as enqueue, dequeue, peek and so on.

I would like you to critique me on:

My general style
My ability to properly deallocate memory so that there is no memory leaks
Properly handling memory allocation failure
Anything else that you would like to add

Queue.h

#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED

typedef struct Node
{
  void *data;
  struct Node *next;
}node;

typedef struct QueueList
{
    int sizeOfQueue;
    size_t memSize;
    node *head;
    node *tail;
}Queue;

void queueInit(Queue *q, size_t memSize);
int enqueue(Queue *, const void *);
void dequeue(Queue *, void *);
void queuePeek(Queue *, void *);
void clearQueue(Queue *);
int getQueueSize(Queue *);

#endif /* QUEUE_H_INCLUDED */

Queue.c

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

void queueInit(Queue *q, size_t memSize)
{
   q->sizeOfQueue = 0;
   q->memSize = memSize;
   q->head = q->tail = NULL;
}

int enqueue(Queue *q, const void *data)
{
    node *newNode = (node *)malloc(sizeof(node));

    if(newNode == NULL)
    {
        return -1;
    }

    newNode->data = malloc(q->memSize);

    if(newNode->data == NULL)
    {
        free(newNode);
        return -1;
    }

    newNode->next = NULL;

    memcpy(newNode->data, data, q->memSize);

    if(q->sizeOfQueue == 0)
    {
        q->head = q->tail = newNode;
    }
    else
    {
        q->tail->next = newNode;
        q->tail = newNode;
    }

    q->sizeOfQueue++;
    return 0;
}

void dequeue(Queue *q, void *data)
{
    if(q->sizeOfQueue > 0)
    {
        node *temp = q->head;
        memcpy(data, temp->data, q->memSize);

        if(q->sizeOfQueue > 1)
        {
            q->head = q->head->next;
        }
        else
        {
            q->head = NULL;
            q->tail = NULL;
        }

        q->sizeOfQueue--;
        free(temp->data);
        free(temp);
    }
}

void queuePeek(Queue *q, void *data)
{
    if(q->sizeOfQueue > 0)
    {
       node *temp = q->head;
       memcpy(data, temp->data, q->memSize);
    }
}

void clearQueue(Queue *q)
{
  node *temp;

  while(q->sizeOfQueue > 0)
  {
      temp = q->head;
      q->head = temp->next;
      free(temp->data);
      free(temp);
      q->sizeOfQueue--;
  }

  q->head = q->tail = NULL;
}

int getQueueSize(Queue *q)
{
    return q->sizeOfQueue;
}

TestQueue.c

#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"

int main()
{
    int val;
    Queue q;

    queueInit(&q, sizeof(int));

    for(val = 0; val < 10; val++)
    {
        enqueue(&q, &val);
        printf("The value %d has been enqueued.\n", val + 1);
    }

    printf("\n");

    queuePeek(&q, &val);

    printf("The value that is at the front of the queue is %d\n\n", val + 1);

    while(getQueueSize(&q) > 0)
    {
        dequeue(&q, &val);
        printf("%d has been dequeued.\n", val + 1);
    }

    return 0;
}

Output


texts:
using Microsoft.AspNetCore.WebUtilities;
using System.Security.Cryptography;

namespace UserManager.Cryptography
{
    public class UrlToken
    {
        private const int BYTE_LENGTH = 32;

        /// <summary>
        /// Generate a fixed length token that can be used in url without endcoding it
        /// </summary>
        /// <returns></returns>
        public static string GenerateToken()
        {
            // get secure array bytes
            byte[] secureArray = GenerateRandomBytes();

            // convert in an url safe string
            string urlToken = WebEncoders.Base64UrlEncode(secureArray);

            return urlToken;
        }

        /// <summary>
        /// Generate a cryptographically secure array of bytes with a fixed length
        /// </summary>
        /// <returns></returns>
        private static byte[] GenerateRandomBytes()
        {
            using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) {
                byte[] byteArray = new byte[BYTE_LENGTH];
                provider.GetBytes(byteArray);

                return byteArray;
            }
        }
    }
}

I've created the above class (C#, .Net Core 2.0) to generate a cryptographically secure string token that is URL safe, so it can be used in an URL without the necessity to be encoded.

I will use that token as a GET parameter (e.g. www.site.com/verify/?token=v3XYPmQ3wD_RtOjH1lMekXloBGcWqlLfomgzIS1mCGA) in a user manager application where I use the token to verify the user email or to recover a user password.

The above link will be sent as email to the user that has requested the service.

I store the token into a DB table with an associated expiration datetime.

I've seen other implementations on this and other sites but all seem to be unnecessarily complicated.  Am I missing something?


texts: Finding legal knight moves in a chessboard in APL

texts:
I wrote a function that takes as input a vector with two integers between 1 and 8 representing a position in a chessboard and that should output a vector where each cell is a similar vector of integers, with the positions that a knight in the input position could reach.

E.g. for the input 1 1, my function should output [2 3] [3 2] (I'm using the [] to represent the boxes of the cells).

This is what I wrote:

knight_moves ← {
  ⍝ Monadic function, expects a vector with 2 integers
  ⍝ Given a chessboard position, find the legal knight moves
  signs ← , ∘.,⍨(¯1 1)
  offsets ← ((⊂⌽),⊂) 2 1
  moves ← , signs ∘.× offsets
  locations ← moves + ⊂⍵
  valid ← ^/¨(1∘≤∧≤∘8) locations
  valid/locations
}

This works and gives the expected result for a series of test cases. Since I am quite new to APL, I wanted to know what could be written in a cleaner way.

This question has been followed-up here.


texts:
The dictionary class loads entries from a file and then can perform operations on them. The dictionary class then stores the entries back into the file.

I would like to know the best way to check if the arguments to my dictionary member functions are valid terms/definitions.  I have thought of two possible solutions, but I am open to any other solutions.  I could either check the arguments passed in to the functions or make a term and definition class and and have the class check instead.

The reason why I want to distinguish strings from terms/definitions is so that I can read them from a file without having to encounter cases where definitions do not end in periods or other cases caused by human error.

dictionary.cpp

#include "dictionary.h"

//*** @TODO: What constitutes a term/definition ***

bool dictionary::search_term(const std::string& term){
    for(auto& it: entries){
        if(it.first != term);
        else return true;
    }return false;
};

bool dictionary::erase_entry(const std::string& term){
    if(search_term(term)){
        entries.erase(term);
        return true;
    }else return false;
};

bool dictionary::define_term(const std::string& term, const std::string& definition){
    if(search_term(term)){
        entries[term] = definition;
        return true;
    }else return false;
};

bool dictionary::write_entry(const std::string& term, const std::string& definition){
if(!search_term(term)){
    entries[term] = definition;
        return true;
    }else return false;
};

inline bool exists (const std::string& name) {
   struct stat buffer;
   return (stat (name.c_str(), &buffer) == 0);
}

bool dictionary::ofs_entries(const std::string& path){
    std::string file = (path + title);
    std::ofstream ofs(file.c_str());
    if(!ofs) return false;
    for(auto& it: entries){
        ofs << it.first << ": " << it.second << '\n';
    }ofs.close();
};

bool dictionary::ifs_entries(const std::string& path){
    std::string file = (path + title);
    if(!exists(file)) return false;
    std::ifstream ifs(file.c_str());
    if(!ifs) return false;
    std::string entry;
    while(true){
        //read entries
        if(!ifs.eof()) break;
    }return true;
};

dictionary.h

#ifndef DICTIONARY_H
#define DICTIONARY_H

#include <algorithm>
#include <iterator>
#include <fstream>
#include <string>
#include <map>

class dictionary{
   public:
        dictionary(const std::string& title, const std::string& definition = "")
            : entries{{title, definition}}, title(title){;};

        bool write_entry(const std::string& term, const std::string& definition = "");
        bool define_term(const std::string& term, const std::string& definition);

        bool erase_entry(const std::string& term);
        bool search_term(const std::string& term);

        bool ofs_entries(const std::string& path);
        bool ifs_entries(const std::string& path);
    private:
        std::map<std::string, std::string> entries;
        std::string title;
};

#endif//DICTIONARY_H


texts: Is this the correct way to expose a setting for a vb.net class library?

texts:
I define in the Settings Tab of a VB.Net class library some user scoped settings. I want to expose these settings to other projects that reference the class library. I chose to do this using a public Module. This works, but it requires exposing each and every setting manually. Is there a better way?

Public Module Settings

    Public Property SomeSetting As Integer
        Get
            Return My.Settings.SomeSetting
        End Get
        Set(value As Integer)
            My.Settings.SomeSetting = value
            My.Settings.Save()
        End Set
    End Property

End Module


texts: Stored procs fine tuning for processing bulk data - 5 million records

texts:
I have this procedure which is used for bulk upload data from a temporary table (temp_rules_master) into two other related tables.
It has 5 million records. The actual 5 million records to temp table upload take less than 10 mins using this query:
LOAD DATA LOCAL INFILE 'my_data.txt'
INTO TABLE temp_rules_master
COLUMNS TERMINATED BY '|'
LINES TERMINATED BY '\n' IGNORE 1 LINES

But later the following procs takes around 10 hrs for running through all those 5 million records and do the processing.
Code Logic:

It iterates the master records one by one (5+ million)
And insert into 2 related tables compatibility_error (ce) and compatibility_rule (cr)
it does the below validations during the process
It checks if already a record exists in ce for the groupname. If exists, use that record id (@ERROR_ID) in the cr table. If it does not exist, creates a new ce record and use that id (@ERROR_ID) in the cr table.
Then checks if a record exists in the starting _material table for the starting_material_code. If exists use that starting_material_id (@SM_ID) in the cr table else set @SM_ID=null for it.
Generates a uuid (@CODE) for every cr record.
Insert a new cr record with the above-found values @CODE, @ERROR_ID, @SM_ID
Continues the iteration for all 5+ million records

Is there any way to improve the speed?
Stored Procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS load_rules$$

CREATE PROCEDURE load_rules()
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE groupname,starting_material_code,lower_limit,higher_limit,description,severity,active,create_date,created_by VARCHAR(255);
    DECLARE cur CURSOR FOR SELECT r.groupname,r.starting_material_code,r.lower_limit,r.higher_limit,r.description,r.severity,r.active,r.create_date,r.created_by from temp_rules_master r;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

    OPEN cur;

    read_loop: LOOP
        FETCH cur INTO groupname,starting_material_code,lower_limit,higher_limit,description,severity,active,create_date,created_by;

        IF finished = 1 THEN
            LEAVE read_loop;
        END IF;

        /* Checks if an error already exists for the groupname */
        IF (SELECT ce.id FROM compatibility_error ce WHERE ce.code=groupname) THEN
            /* if exists use the existing error */
            BEGIN
                SELECT ce.id INTO @ERROR_ID FROM compatibility_error ce WHERE ce.code=groupname;
            END;
        ELSE
            /* If no error exists for the groupname create a new error record */
            BEGIN
                insert into compatibility_error(active,create_date,created_by,modified_by,modified_date,code,description,severity)
                    values(true,create_date,0,0,NOW(),groupname,description,severity);
                SET @ERROR_ID=LAST_INSERT_ID();
            END;
        END IF;

        /* Checks if starting material exists */
        IF (select id from starting_material sm where sm.code=starting_material_code) THEN
            BEGIN
                select id INTO @SM_ID from starting_material sm where sm.code=starting_material_code;
            END;
        ELSE
            BEGIN
                SET @SM_ID = null;
            END;
        END IF;

        /* Insert rule */
        select UPPER(md5(UUID())) INTO @CODE;
        insert into compatibility_rule(active,create_date,created_by,modified_by,modified_date,code,description,groupname,higher_limit,lower_limit,compatibility_error_id,starting_material_id)
            values(true,create_date,0,0,NOW(),@CODE,description,groupname,higher_limit,lower_limit,@ERROR_ID,@SM_ID);

    END LOOP read_loop;

    CLOSE cur;

    select 'done...';
End$$

DELIMITER ;


texts: Automapper - Mapping a nested collection to a list

texts:
I'm using Automapper to do some mapping from XSD-generated serialization object to more sane POCO's.

I'm having an issue with a particular type of mapping.

public class SourceOuterObject
{
  public SourceSet SourceSet { get; set; }
}

public class SourceSet
{
  public List<SourceObject> SourceList{ get; set; }
}

I want to map this to:

public class TargetOuterObject
{
  public List<TargetObject> TargetList{ get; set; }
}

I have tried a wide variety of mapping configurations, but the only thing that I've been able to make work is this:

Mapper.CreateMap<SourceOuterObject, TargetOuterObject>();
Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceSet, List<TargetObject>>()
    .ConvertUsing(ss => ss.SourceList.Select(bs => Mapper.Map<SourceObject, TargetObject>(bs)).ToList());

This works but seems to be way more complicated than it should be - I feel dirty calling a mapping within a mapping config.

Is this the best I can hope for or is there a better way?


texts: Ensure that ICommand implementation properly uses weak references

texts:
I am building an implementation of System.Windows.Input.ICommand that is like the commonly used RelayCommand, but doesn't keep a strong reference to targets of the delegates it uses. Such a structure is useful for when a control wants to expose some of its functionality as a command (which can be assigned to a ViewModel). Using a traditional RelayCommand would cause a memory leak, because the RelayCommand would contain strong references to the delegates that it runs, which in turn contain strong references to the control. Here is the code:

public class WeakRelayCommand : ICommand
{
    public WeakRelayCommand(Action<object> executeCallback, Func<object, bool> canExecuteCallback = null)
    {
        ExecuteTargetReference = new WeakReference<object>(executeCallback.Target);
        if (canExecuteCallback != null)
            CanExecuteTargetReference = new WeakReference<object>(canExecuteCallback.Target);
        ExecuteCallbackInfo = executeCallback.GetMethodInfo();
        CanExecuteCallbackInfo = canExecuteCallback?.GetMethodInfo();
    }

    private WeakReference<object> ExecuteTargetReference;
    private WeakReference<object> CanExecuteTargetReference;
    private MethodInfo ExecuteCallbackInfo;
    private MethodInfo CanExecuteCallbackInfo;

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        if (CanExecuteCallbackInfo == null)
            return true;
        object canExecuteTarget = null;
        if (CanExecuteTargetReference?.TryGetTarget(out canExecuteTarget) ?? false)
        {
            return (bool)CanExecuteCallbackInfo.Invoke(canExecuteTarget, new[] { parameter });
        }
        else
            return false; //Target of the delegate for CanExecute has been garbage collected
    }

    public void Execute(object parameter)
    {
        object executeTarget = null;
        if (ExecuteTargetReference?.TryGetTarget(out executeTarget) ?? false)
        {
            ExecuteCallbackInfo.Invoke(executeTarget, new[] { parameter });
        }
        //Cannot execute the command if the target of the Execute delegate has been garbage collected
    }

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

The basic summary is that instead of holding strong references to delegates, which in turn hold strong references to the delegates' targets of invocation, it instead holds a reference to the MethodInfo associated with the actual method of the delegate, and holds a WeakReference to the targets of invocation separately from the method. This way, the targets of invocation are free to be garbage collected by the garbage collector.

I have tested this implementation and it works just fine as an implementation of ICommand, and it appears to properly use WeakReferences to achieve my objective. Can I get a verification that this is in fact the case?


texts: Controlling a Windows Service from a WPF app

texts:
I have a WPF Control Panel app, where I'm trying to stay close to an MVVM architecture. The control panel (the "the CP") is for a WCF service ("the Scheduler"), hosted in a Windows Service ("the Host"). My main concern, and topic for review here, is how I am avoiding blocking the CP responsiveness for too long. The Host control operations sometimes take longer than 3 seconds, which is long for a UI.

Because the start and stop methods are typed void, and I have been advised to steer well clear of using async void methods, instead I use a method I derived from an example somewhere:

private void ExecuteWithTimeout(Action task, int? timeout = null)
{
    timeout = timeout ?? HostServiceConstants.ServiceControlTimeout;
    var source = new CancellationTokenSource();
    var timedTask = Task.Factory.StartNew(task, source.Token).ContinueWith((t) =>
        {
            if (t.Exception != null)
            {
                t.Exception.Handle(ex =>
                    {
                        var frame = new StackFrame(1);
                        var methodName = frame.GetMethod().Name;
                        _logger.Warn("'ExecuteWithTimeout' exception from: '{0}': {1}", methodName, ex.Message);
                        return true;
                    });
            }
        });
    bool done = timedTask.Wait(timeout.Value);
    if (!done)
    {
        source.Cancel();
        var frame = new StackFrame(1);
        var methodName = frame.GetMethod().Name;
        _logger.Warn("'{0}' timed out after {1} milliseconds.", methodName, timeout);
    }
}

This is called from the viewmodel, when a Command is invoked from the view:

void ExecuteStartHostCommand()
{
    Exception exception = null;
    ExecuteWithTimeout(() =>
        {
            try
            {
                _host.Start();
            }
            catch (Exception ex)
            {
                exception = ex;
            }
        });
    if (exception != null)
    {
        _logger.Error("Exception caught while trying to execute 'StartHostCommand': " + exception.Message, exception);
        if (exception is HostServiceException)
        {
            MessageBoxFacility.ServiceControlError((HostServiceException)exception);
        }
        else
        {
            throw exception;
        }
    }
}

Here, _host.Start() is a call to the model, which in turn uses a System.ServiceProcess.ServiceController to start the Host. My logging is showing such calls time out quite often, after 3000ms, but then said logging goes on to sow that the Host stopped anyway, as expected. I would like to avoid the kludgy looking ExecuteWithTimeout and rather use await, but that would involved using some async void methods, which I have been advised to avoid.

The code I have shown here is still quite experimental, and I have little experience controlling long running tasks so many steps away from the UI, so please ignore smaller  discrepancies etc.


texts: Using a variable in a for loop: is it proper practice or is there a better approach

texts:
The goal of this code was to create a table from an associative array.

I need to create horizontal rows where  the keys need to be used as "headers" while the values are posted below each header.
I need to be able to reuse the code with associative arrays of unknown lengths and varying number of columns allowed in the tables.

I realize this is not set up as a function. I'm just playing with the code for now.

The code that I have actually does work. I'm not sure if it's "proper" form especially here - $startIndex = $index in the for loop.

I create two rows at a time - one for the header, one for the values. After the end of these two rows, I'm re-setting the index on the for loop so it runs through the next group in the array. I'm trying to get better at coding and would like some input on what I've done.

Print out a horizontal table with a capability to vary the number of  cells across

<table class="<?php echo $tableClass; ?>">

Horizontal

<?php
$array = array(
    "A" => 1,
    "B" => 2,
    "C" => 3,
    "D" => 4,
    "E" => 5,
    "F" => 6,
    "G" => 7,
    "H" => 8,
    "I" => 9,
    "J" => 10,
    "K" => 11,
    "L" => 12,
    "M" => 13
);

$maxColumns = 8;//set the number of columns allowed in the table
$arrayOfKeys = array_keys($array);//grab the keys from the initial array
$count = count($arrayOfKeys);//gets a count of the number of items in  the array
$maxRows = ceil($count/$maxColumns) * 2;//takes the count and determines the number of rows based on the number of items and the maxColumns * 2 for total rows  (need a "header" and value for each set of keys/values in the array
$endIndex = $maxColumns-1;//initialize the endIndex on the loop that runs the
$startIndex = 0;//initialize the start index for the second loop which will loop through the array assigning keys to first row - value to second

for ($row=1; $row<=$maxRows; $row++){//loops based on the number of rows required to generate the table for the number of cells required

    echo '
';//start the row
    $rowEvenOdd = ($row % 2); //figures whether an even or odd row

    for ($index=$startIndex; $index<=$endIndex; $index++){//creates the rows
            if($rowEvenOdd == 1) {//if the row is odd, grab and display the key
                if(array_key_exists($index, $arrayOfKeys))
                    {$thiskey = $arrayOfKeys[$index];}
                    else {$thiskey ="&nbsp;";}
                echo "$thiskey	";
                }//end of odd rows
            if($rowEvenOdd == 0) {//if the row is even, grab and display the value
                if(array_key_exists($index, $arrayOfKeys))
                    {$thisvalue = $array[$arrayOfKeys[$index]];}
                    else {$thisvalue ="&nbsp;";}
                echo "". $thisvalue ."	";
                }//end of odd rows
    }//end of loop to generate content for the cells
    echo '
';//end the row
    if($rowEvenOdd == 0) {$startIndex = $index; $endIndex = $index + $maxColumns-1;/* reset the index begin and end  to loop through next group of rows */                           }
    }//end loops that creates the rows

?>


texts:
I solved the problem to print all possible subsets of an array. I just want to know a better approach or anything different I could have done.

Question: Print all possible subsets of an array.

My approach: I know that there are \$2^N\$ (no. of elements in the set) subsets and each subset can be represented with the help of \$N\$-bit binary number. As a part of an assignment I have already made a decimal to binary and to reverse(prints no. in reverse digit by digit) a number program.So I combined the two to solve this question.

Input: {1, 2, 3}

Output: 3, 2, 32, 1, 31, 21, 321

My Code:

private static void subset(int[] arr) {
    int size = arr.length;
    int binaryLimit = (int) Math.pow(2, size) - 1;
    for (int i = 0; i <= binaryLimit; i++) {       //generate decimal no.
        //generate corresponding binary no & counter(how many bit binary no. is)
        int N = i;
        int counter = 0;
        int power = 0, binary = 0;
        while (N != 0) {
            int rem = N % 2;
            rem = rem * ((int) Math.pow(10, power));
            binary = binary + rem;
            N = N / 2;
            power++;
            counter++;
        }
        // loop to traverse array
        for (int j = arr.length - 1; j >= arr.length - counter; j--) {
            // if binary no is greater then one digit, compare each digit separately.
            if (counter > 1) {
                int k = binary;
                while (k != 0) {
                    int rem = k % 10;
                    if (rem == 1) {     //if binary digit == 1, print corresponding no. from array
                        System.out.print(arr[j]);
                    }
                    j--;
                    k = k / 10;
                }
                System.out.println();
            } else {
                if (binary == 1) {
                    System.out.println(arr[j]);
                    j--;
                }
            }
        }
    }
}


texts: Is there a better way to do this linq sort?

texts:
I have the following linq statement that is ordering a list of assets by the sort order of a child item:

 Assets.OrderBy(a => a.GalleryItems != null &&
                a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId) != null
                     ? a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId).SortOrder : 1000);

I was wondering if there was a more efficient way to do this as I would have thought having to do 2 a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId) would be pretty poor for performance


texts: De-bouncing a (Gray) Rotary Encoder Switch in C

texts:
I  would like feedback on the correctness and performance of this code.

My priorities are also are readability, simplicity and self-documenting code - but I'm happy with those as they are.

I still need to do some factoring of common code between the two input lines - but I'm brushing up my C and will do that.

RA2 and RA3 are the two digital input lines. My algorithm is not dissimilar to how debouncing would be done with a low pass capacitor and resistor followed by a schmitt trigger. This function is called by the ISR every 0.5ms, and the rotary switch produces transitions as short as 5-10ms.

I am curious how to deal with situations where the rotary switch is turned a bit faster than the algorithm can process. Can further information be deduced from the Gray encoding, even when a step  is missed because of the low pass delay and limited sample rate? I suppose this could be taken as far as using neural networks?!

I'm mainly asking this question because I think the running time and the amount of code of the below can both be reduced by a factor of two at least. And I'd just prefer not to get out the logic analyzer and completely reinvent the wheel.

rotsw.h

#define ROTSW_AVG_SIZE 8
#define ROTSW_MAX 7
#define ROTSW_UPPER 5
#define ROTSW_LOWER 2
#define ROTSW_MIN 0

void rotsw_sample_avg_schmitt_count();

extern volatile int rotsw_count_steps;

rotsw.c

unsigned int rotsw_samples[ROTSW_AVG_SIZE];
unsigned char rotsw_write_idx = 0;

int rotsw_avg_ra2 = 0;
int rotsw_avg_ra3 = 0;

int ra2 = 0;
int ra3 = 0;

volatile int rotsw_count = 0;

void rotsw_sample_avg_schmitt_count()
{
    int sample, old_sample, ra2_changed, ra3_changed, count = rotsw_count;

    // Sample RA2 and RA3
    old_sample = rotsw_samples[rotsw_write_idx];
    rotsw_samples[rotsw_write_idx] = sample = PORTA & 0b00001100;
    if (++rotsw_write_idx >= ROTSW_AVG_SIZE) rotsw_write_idx = 0;

    // Moving average, turning digital sample to "analogue"
    if (old_sample & 0x04)  rotsw_avg_ra2--;
    if (old_sample & 0x08)  rotsw_avg_ra3--;
    if (sample & 0x04)      rotsw_avg_ra2++;
    if (sample & 0x08)      rotsw_avg_ra3++;

    // 3. Do limit for Schmitt trigger
    if      (rotsw_avg_ra2 < ROTSW_MIN) rotsw_avg_ra2 = ROTSW_MIN;
    else if (rotsw_avg_ra2 > ROTSW_MAX) rotsw_avg_ra2 = ROTSW_MAX;
    if      (rotsw_avg_ra3 < ROTSW_MIN) rotsw_avg_ra3 = ROTSW_MIN;
    else if (rotsw_avg_ra3 > ROTSW_MAX) rotsw_avg_ra3 = ROTSW_MAX;

    // Do Schmitt trigger
    if (rotsw_avg_ra2 > ROTSW_UPPER){
        ra2_changed = !ra2;
        ra2 = 1;
    } else if (rotsw_avg_ra2 < ROTSW_LOWER){
        ra2_changed = ra2;
        ra2 = 0;
    }
    if (rotsw_avg_ra3 > ROTSW_UPPER){
        ra3_changed = !ra3;
        ra3 = 1;
    } else if (rotsw_avg_ra3 < ROTSW_LOWER){
        ra3_changed = ra3;
        ra3 = 0;
    }

    // Do rotsw state change count.
    if (ra2_changed){
        if (ra2 == ra3) count++;
        else count--;
    }
    if (ra3_changed){
        if(ra2 == ra3) count--;
        else count++;
    }
    rotsw_count = count;
}


texts: PyQt5 validator for decimal numbers (V2)

texts:
This class is similar to QDoubleValidator, but it improves slightly on the editing comfort.

Are there any corner- or special cases of inputs I didn't consider, which would lead to bad behaviour?

Is it wrong to assume the last inserted character is left of the cursor (for the case that I'm sure that a character was inserted, because there are two separators, or too many digits at the end)?

class DecimalValidator(QDoubleValidator):
    '''This is intended to be used with a QLineEdit.
    It has some features of an inputMask, but without the disadvantages.
    For inputMask, the right alignment and the inserting of digits on
    the left hand side of the separator isn't really nice.'''
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            # When we're left of the separator, and separator is entered again,
            # remove the inserted separator and move right of the old separator.
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            # When we're right of the separator, and all decimal places are used already,
            # go into overwrite mode (by removing the old digit)
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)


texts: Count unique IP address in a date range from Apache log

texts:
I use the following command to get specific entries between certain dates from Apache log files. Then I filter out my own address and some bots, then I print out the IP, sort it, get the uniques, output the ip with count, and for summary I count lines to get a total.

Is there a way to improve this, reducing the amount of awk commands?
Or to get this process down more efficient? I'm not that proficient with awk, but I have the feeling this should be accomplish able in maybe one awk instruction.

zgrep '"GET /my/path/to/page.html' other_vhosts_access*
| awk -F'[][]'
    -v dstart=`date -d"2019-12-09" +%Y%m%dT%0H:%0M:%0S`
    -v dend=`date -d"2020-01-09" +%Y%m%dT%0H:%0M:%0S`
    '{ $2 = substr($2,8,4)sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",substr($2,4,3))+2)/3)substr($2,1,2)"T"substr($2,13,8);
    if ($2 >= dstart && $2 < dend) print }'
| awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/'
| awk '{print $2}'
| sort
| uniq -c
| sort -n
| wc -l

the one liner:

zgrep '"GET /my/path/to/page.html' other_vhosts_access* | awk -F'[][]' -v dstart=`date -d"2019-12-09" +%Y%m%dT%0H:%0M:%0S` -v dend=`date -d"2020-01-09" +%Y%m%dT%0H:%0M:%0S` '{ $2 = substr($2,8,4)sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",substr($2,4,3))+2)/3)substr($2,1,2)"T"substr($2,13,8); if ($2 >= dstart && $2 < dend) print }' | awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/' | awk '{print $2}' | sort | uniq -c | sort -n | wc -l


texts:
I am implementing a parent-child relationship, represented by hashes that look like this:

parent = { 'parent' => nil, 'id' => 3 }
child = { 'parent' => parent, 'id' => 7 }

These hashes are data given to me, for example, through a JSON API.

(As per a question in the comments, the JSON for the child would look like:)

{
  "parent": { "parent": null, "id": 3, ...etc.},
  "id": 7,
  ...etc.
}

Parent and child have more keys like name, etc. (they are a lot so I am only showing the id as an example). They both have the same keys. There are only parents and children, i.e., no grandchildren or grandparents, etc. There is only one "level". Each child has only one parent, but each parent may have several children.

I wrapped the data in a class to represent it, so that my application can use an object. Both parent and child are represented by the same class. So I did this:

class Item
  def initialize(data)
    @data = data
  end

  def parent
    @parent ||= Item.new(data['parent']) if data['parent']
  end

  def id
    data['id']
  end

  private

  attr_reader :data
end

Every key in the hash has its method to retrieve it, and Item is the class that represents parents and children. I use it like this:

describe 'children' do
  let(:subject1) { Item.new(child) }

  it 'is an item' do
    subject1.class.must_equal(Item)
  end

  it 'has an id' do
    subject1.id.must_equal(7)
  end

  it 'has a parent' do
    subject1.parent.id.must_equal(3)
  end
end

describe 'parent' do
  let(:subject2) { subject1.parent }

  it 'is also an item' do
    subject2.class.must_equal(Item)
  end

  it 'does not have a parent' do
    assert_nil(subject2.parent)
  end
end

With this, children know who is their parent, and for a parent to know its children we can iterate through all the children and compare their parent's id with the id we are searching.

However, I have a bad feeling about calling Item.new inside of Item. Is like a lot of things could go wrong. I thought of using a Item factory through dependency injection, but really all the knowledge about how to build a Item is in Item, so why introduce that dependency. Is this like a weird kind of recursion?

It doesn't help that I haven't seen this implementation anywhere (I'm not a computer scientist though). Is this bad code? I have a weird feeling, but I can't quite word why.


texts: Using Poor Man's DI to inject helper class dependencies

texts:
I had a rather large method in one public class that I refactored into 2 helper classes. The thing is though, that those 2 helper classes have dependencies. I refactored them into helper classes so I could mock and test them easily, which worked out perfectly.

However, the thing is I don't want to have to register my helper classes in the DI container, because I know the public class will always be using those specific implementations.

This is how I implemented the public class' constructors:

    /// <summary>
    /// Internal constructor used by tests for mocking.
    /// </summary>
    internal TranslationCompiler(ITranslationCatalogTransformer translationCatalogTransformer, ICompiledCatalogTransformer compiledCatalogTransformer)
    {
        if (compiledCatalogTransformer == null) throw new ArgumentNullException("compiledCatalogTransformer");
        if (translationCatalogTransformer == null) throw new ArgumentNullException("translationCatalogTransformer");
        _translationCatalogTransformer = translationCatalogTransformer;
        _compiledCatalogTransformer = compiledCatalogTransformer;
    }

    /// <summary>
    /// Public constructor that passes dependencies to concrete implementations of helper classes.
    /// </summary>
    public TranslationCompiler(IResourceService resourceService, ITranslationSerializer serializer)
    {
        if (resourceService == null) throw new ArgumentNullException("resourceService");
        if (serializer == null) throw new ArgumentNullException("serializer");
        _translationCatalogTransformer = new TranslationCatalogTransformer(resourceService);
        _compiledCatalogTransformer = new CompiledCatalogTransformer(serializer);
    }

Is this an acceptable use for poor man's DI? This way, the DI container only has to know the actual dependencies for the public class to work, while still being very testable.


texts:
I took a little heat on a method I had to resize an image and I'm hoping I can get a little help on the best way to do it. This is intended for a simple Java Helper Library I'm developing. I have a few ways to do it.

New Method:

/**
* This method resizes the given image
*
* @param image
* @param width
* @param height
* @param max if true, sets the width and height as maximum heights and widths, if false, they are minimums
* @return
*/
public static BufferedImage resizeImage(BufferedImage image, int width, int height, boolean max) {
  int type = (image.getTransparency() == Transparency.OPAQUE)
          ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
  BufferedImage bi = new BufferedImage(width, height, type);
  Graphics2D graphics = bi.createGraphics();
  graphics.drawImage(image, 0, 0, width, height, null);
  graphics.dispose();
  return bi;
}

Original Method:

/**
* This method resizes the given image
*
* @param width
* @param height
* @param max if true, sets the width and height as maximum heights and widths, if false, they are minimums
* @return
*/
public static ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max) {
  Image image = imageIcon.getImage();
  Image newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
  int width1 = newimg.getWidth(null);
  if ((max && width1 > width) || (!max && width1 < width)) {
    newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
  }
  return new ImageIcon(newimg);
}

Are these kinds of convenience methods ok?

/**
* Convenience method. Creates ImageIcon from the given file location and calls resizeImage with it
*
* @param location
* @param width
* @param height
* @param max
* @return
*/
public static ImageIcon resizeImageFromFile(String location, int width, int height, boolean max) {
  ImageIcon imageIcon = new ImageIcon(location);
  return resizeImage(imageIcon, width, height, max);
}

/**
* Convenience method. Creates ImageIcon from the given resource location and calls resizeImage with it
*
* @param location
* @param width
* @param height
* @param max
* @return
*/
public static ImageIcon resizeImageFromResource(String location, int width, int height, boolean max) {
  ImageIcon imageIcon = new ImageIcon(SwingHelper.class.getResource(location));
  return resizeImage(imageIcon, width, height, max);
}


texts: Assign value based on 100s of switch statement

texts:
In the following code I have potentially hundreds of possible cases. (This is just a small subset.) Is there some way to more effectively set state.dimensionQty based on the string held in state.dimensionType? For example, some kind of function or loop, that would make switch less imperative?

Simply put, state.dimensions contains all possible dimension measurement, and the user has specified a dimensionType that they would like to save.

Example is Vue.js code within Vuex, but the general case is relevant too.

switch (state.dimensionType) {
    case 'quantity':
      state.dimensionQty = state.dimensions.quantity
      break
    case 'in':
      state.dimensionQty = state.dimensions.in
      break
    case 'm':
      state.dimensionQty = state.dimensions.m
      break
    case 'cm':
      state.dimensionQty = state.dimensions.cm
      break
    case 'ft':
      state.dimensionQty = state.dimensions.ft
      break
    case 'yd':
      state.dimensionQty = state.dimensions.yd
      break
    default:
      throw new Error(
        'No dimension type specified.'
      )
  }


texts:
I would like someone to review my code on find indices of 2 numbers in array that sums up to an number. Following is the code that I have tried and it works.
The real issue in the code is I am doing Map.lookup twice. Is there a way to avoid it.

Input [1,2,3,4,5] 5
Output [2,1]

Input [1,2,3,4,5] 4
Output [2,0]

Code

import Data.Char
import Data.Maybe
import Data.List
import qualified Data.Map as Map
{--
 - two sums
 - https://leetcode.com/problems/two-sum/
 - --}
twosums :: [Int]-> Int -> [Int]
twosums [] _ = []
twosums k g = flip twosum' Map.empty $ zip k [0..]
  where
  twosum'::[(Int, Int)] -> Map.Map Int Int -> [Int]
  twosum' [] _ = []
  twosum' (x:xs) mp
    | Map.lookup (g - fst x) mp  == Nothing = twosum' xs qmap'
    | otherwise = [snd x, fromMaybe (-1) $ Map.lookup ( g - fst x)  mp ]
    where
    qmap' = Map.insert (fst x) (snd x) mp
```


texts:
I am filtering a List (childList) based on the contents of another List (parentList).

The parentList can contain 0-n entities where items of the childList are referenced by an ID (btw. ID is in this case a string, you could also call it "Name" or whatever you like). I want to filter the childList in a way that the result is all elements that have at least one entry in the parentList.

The obvious solution is:

List<childItem> resultList = new List<childItem>();

foreach(var childItem in childList){
    foreach(var parentItem in parentList){
        if(childItem.ID.Equals(parentItem.ChildID,StringComparison.InvariantCultureIgnoreCase){
            resultList.Add(childItem); //found entity
            break; // search for next childItem
        }
}

What I have done by now is:

// Group by childID and create List with all relevant IDs
var groupedParentList = parentList.AsParallel().GroupBy(p => p.ChildID).Select(group => group.First()).ToList();

// Filter childList on groupedParentList
var result = childList.AsParallel().Where(child => groupedParentList.AsParallel().Count(parent => parent.childID.Equals(child.ID, StringComparison.InvariantCultureIgnoreCase)) > 0).ToList();

But it's lasting rather long. The parentList contains about 75k entries and the childList about 4.5k entries. I just can't believe it actually takes time - imo this should be done in almost no time?

Maybe I am on the wrong track or am I missing some obvious performance-stopper?

Btw.: I have chosen the names parent- and childList just as an example. It's actaully no parent-child-relation.

Additional Question: Could it be faster to direcly check if the parentList contains the childList-Item? Something a lá:

var test = childList.RemoveWhere(child => !parentList.Contains(item => item.childID.Equals(child.ID));

So I would just skip the grouping? Any suggestions/ideas?


texts:
This is a cut-and-dried Fisher-Yates implementation. As not typically a JS developer, I've tried to incorporate as many best practices as I can. I would appreciate any input as to make it conform to more best practices and continue to be maintainable.

(function fisherYates () {

    "use strict";

    var shuffle = function shuffle (array) {

        var beginningIndex = 0,
            currentIndex = array.length,
            indexDecrement = 1,
            randomIndex = 0,
            temporaryValue = 0;

        // While elements remain to be shuffled...
        while (currentIndex !== beginningIndex) {

            // Pick an element from the remaining elements...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= indexDecrement;

            // Swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;

        }

        return array;

    };

    return shuffle;

}());


texts: A class to stop XML parser from converting UTF-8 entity hex characters

texts:
I'm trying to stop the xml parser from converting the UTF-8 enitity hex codes to its character alternative and also not adding the extra space in self-closing nodes after parsing.

I've created a class for this (say DB_class) shown as below

using System.IO;
using System.Xml.Linq;
class tDocument:XDocument
{
    string input_string;
    int option;

    public tDocument(string input,int opt)
    {
        this.input_string=input;
        this.option=opt;
    }
    public static XDocument tParse(string path)
    {
        string file_content = escape_string(File.ReadAllText(path), 0);
        XDocument doc = XDocument.Parse(file_content, LoadOptions.PreserveWhitespace);
        return doc;
    }
    public static void tSave(string path, XDocument doc)
    {
        doc.Save(path, SaveOptions.DisableFormatting);
        File.WriteAllText(path, escape_string(doc.ToString(), 1));
    }
    public static string escape_string(string input_string, int option)
    {
        switch (option)
        {
            case 0:
                return input_string.Replace("&", "&amp;");
            case 1:
                var x = input_string.Replace(" />", "/>");
                var y = x.Replace("&amp;", "&");
                return y;

            default:
                return null;

        }
    }
}

Here is a random example to show how I'm using this class to do stuff (basically the program gets the value of node ID by matching the name from info.xml and adding it to the respective names attribute id in the xml file that I want to modify)

XDocument myfile=tDocument.tParse(@"D:\test\APril 2018\testing.xml");
var names=myfile.Descendants("name").ToList();
foreach (var name in names)
{
    XDocument infofile=tDocument.tParse(@"D:\test\APril 2018\info.xml");
    var data=infofile.Descendants("student").Where(x=>x.Element("s-name").Value==name.Value).Select(y=>y.Element("ID").Value).First();
    name.Add(new XAttribute("id",data));
}
tDocument.tSave(@"D:\test\APril 2018\testing.xml",myfile);
Console.ReadLine();

Here is the testing.xml and the info.xml

What I want to know is how can I make my class (DB_class) more efficient, and also if there is a better way doing what the class is doing?


texts:
As I am getting my Linq query to a functional point, I start looking at the query and think about all the "ANY" and wonder if those should be a different method and then I have data conversions going on.

Does anything jump out as being a performance issue? What is recommended to make this more performant? (Yes, I need all the &&.)

etchVector =
    from vio in list
    where excelViolations.Any(excelVio => vio.VioID.Formatted.Equals(excelVio.VioID.ToString()))
    && excelViolations.Any(excelVio => vio.RuleType.Formatted.Equals(excelVio.RuleType))
    && excelViolations.Any(excelVio => vio.VioType.Formatted.Equals(excelVio.VioType))
    && excelViolations.Any(excelVio => vio.EtchVects.Any(x => x.XCoordinate.Equals(excelVio.XCoordinate)))
    && excelViolations.Any(excelVio => vio.EtchVects.Any(y => y.YCoordinate.Equals(excelVio.YCoordinate)))
    select new EtchVectorShapes
    {
        VioID = Convert.ToInt32(vio.EtchVects.Select(x => x.VioID)),
        ObjectType = vio.EtchVects.Select(x => x.ObjectType).ToString(),
        XCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.XCoordinate)),
        YCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.YCoordinate)),
        Layer = vio.EtchVects.Select(x => x.Layer).ToString()
    };


texts: Simple simulated annealing template in C++11

texts:
This simulated annealing program tries to look for the status that minimizes the energy value calculated by the energy function.

The status class, energy function and next function may be resource-intensive on future usage, so I would like to know if this is a suitable way to code it.

#pragma once

#include <cmath>
#include <random>
#include <utility>
#include <algorithm>

// To find a status with lower energy according to the given condition
template<typename status, typename count, typename energy_function, typename temperature_function, typename next_function, typename generator>
status simulated_annealing(status i_old, count c, const energy_function& ef, const temperature_function& tf, const next_function& nf, generator& g){

    auto   e_old  = ef(i_old);

    status i_best = i_old;
    auto   e_best = e_old;

    std::uniform_real_distribution<decltype(e_old)> rf(0, 1);

    for(; c > 0; --c){
        status i_new = nf(i_old, g);
        auto   e_new = ef(i_new);

        if(e_new < e_best){
            i_best =           i_new ;
            e_best =           e_new ;
        }

        if( e_new < e_old || std::exp( (e_old - e_new) / tf(c) ) > rf(g) ){
            i_old  = std::move(i_new);
            e_old  = std::move(e_new);
        }
    }
    return(i_best);
}

Example usage:

#include <cmath>
#include <random>

#include <chrono>
#include <cstdlib>
#include <iostream>

#include "simulated_annealing.hpp"

template<typename Clock = std::chrono::system_clock>
class timer{
private:
    typedef std::chrono::time_point<Clock> time_point;
    time_point _start;
    time_point _finish;
public:
    void start(){
        _start = Clock::now();
    }
    void finish(){
        _finish = Clock::now();
    }
    template<typename rtype>
    rtype count(){
        std::chrono::duration<rtype> elapsed = _finish - _start;
        return elapsed.count();
    }
};

auto ef = [](long double x){
    return std::abs( (x - 10)*(x + 20)*(x - 30) );
};

auto tf = [](long double k){
    return std::exp( -20 * k );
};

template<typename generator>
long double nf(long double x, generator& g){
    std::normal_distribution<decltype(x)> d(0, 1);
    return x + d(g);
}

int main(int argc, char const *argv[])
{
    std::random_device rd;
    std::mt19937_64 g(rd());
    timer<std::chrono::high_resolution_clock> t;

    long double root   = std::atof(argv[1]);
    std::size_t count  = std::atoi(argv[2]);

    t.start();
    root = simulated_annealing(root, count, ef, tf, nf<decltype(g)>, g);
    t.finish();

    std::cout << "Result: " << root << std::endl;
    std::cout << "Time elapaed: " << t.count<double>() << '\n';

    return 0;
}


texts:
Are there any possible speed improvements I can make to the following method. It takes a JDBC ResultSet and breaks it into several CSV files:

public static void convertToCSV(final ResultSet rs) throws SQLException, IOException {
    final DateFormat format = new SimpleDateFormat("yyyyMMdd,HH:mm:ss");
    format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
    final StringBuilder sb = new StringBuilder();
    while (rs.next()) {
        final File file = new File(sb.append(rs.getString("FIELD1")).append(".csv").toString());
        if (!file.exists()) {
            file.createNewFile();
        }
        final BufferedWriter fw = new BufferedWriter(new FileWriter(file.getAbsoluteFile(), true));
        fw.write(rs.getString("FIELD2"));
        fw.write(',');
        fw.write(rs.getString("FIELD3"));
        fw.write(',');
        final String clobValue = rs.getString("FIELD4");
        if(clobValue==null)
            fw.write("null,");
        else{
            fw.write('\"');
            fw.write(clobValue);
            fw.write("\",");
        }
        final Date date = new Date(rs.getLong("FIELD5"));
        fw.write(format.format(date));
        fw.write('\n');
        fw.close();
        sb.setLength(0);
    }
    rs.close();
}