texts:
I was wondering if you could provide some feedback on this Router class I built. Worth noting that it relies on an Apache rewrite rule that always redirects to this file, but passes the path into $_GET['url'] as a string (e.g. A request to http://foo.com/foo/bar) goes into $_GET['url] => 'foo/bar'.

You can then define routes that match against this path string, and the function defined with the route can execute any aribtrary code, like handing off to a controller.

Mainly I would like to know if I should be sanitizing any strings? How could I handle paths that don't match any defined routes?

class Router
{
    private $routes = null;
    private $req_path = null;

    function __construct()
    {
        if (isset($_GET['url']))
            $this->req_path = $_GET['url'];

        // Build the requested path.
        $this->req_path = is_null($this->req_path) ? "/" : "/" . $this->req_path;
    }

    // Create a route with a path and a function associated with that path that we
    // can call.
    function route($path, $handler)
    {
        $this->routes[] = array('path' => $path, 'handler' => $handler);
    }

    // Run the router to compare the request against any defined routes, run the
    // associated function.
    function run()
    {
        if (is_null($this->routes))
            throw new RuntimeException("No routes have been defined");

        foreach($this->routes as $route) {
            if ($route['path'] == $this->req_path) {
                $route['handler']();
                return;
            }
        }
    }
}

$router = new Router();

$router->route("/steve", function() {
    echo "steve";
});

$router->run();


texts:
I'm looking for comments on both the micro (individual lines of code) and macro (overall design) scale. My input/output format is a single string, with newlines delimiting rows and '*'/' ' denoting alive and dead, respectively.

from itertools import product
from enum import Enum
class Direction(Enum): forwards = 1; backwards = 0

class State:
    table = {'*':True, ' ':False}

    def convert(self, grid, direction):
        if direction == Direction.forwards:
            table = self.table
        elif direction == Direction.backwards:
            table = {value:key for (key,value) in self.table.items()}
        else:
            raise ValueError("Invalid conversion direction!")

        return [[table[x] for x in row] for row in grid]

    def __init__(self, grid):
        grid = list(filter(None, grid.split('\n')))
        self.rows = len(grid); self.cols = len(grid[0])

        if not all(len(grid[i]) == self.cols for i in range(self.rows)):
            raise ValueError("Invalid game state!")

        self.grid = self.convert(grid, Direction.forwards)

    def __getitem__(self, i):
        return self.grid[i]

    def __str__(self):
        return '\n'.join(map(lambda x: ''.join(x), self.convert(self.grid, Direction.backwards)))

def game(state):
    ''' Takes a state in the input format and yields states in the output format. '''

    state = State(state)

    def alive(x,y):
        try:
            return state[x][y]
        except IndexError:
            return False

    while True:
        state.grid = [
            [2 <= sum(alive(xx,yy) for xx, yy in product([x-1,x+1], [y-1,y+1])) <= 3
             for (y,col) in enumerate(row)]
            for (x,row) in enumerate(state.grid)
        ]
        yield str(state)


texts: Speed up calculating relative strength index

texts:
I am trying to program the calculation of the relative strength index indicator described on a stockcharts.com page.

On the same page there are Excel formulas used for calculations.

My code below is accurate, but when I have many rows, its execution is quite slow, so I believe that it could be optimized.

import pandas as pd
import numpy as np

pd.set_option('display.width', 300)

close = [44.3389, 44.0902, 44.1497, 43.6124, 44.3278, 44.8264, 45.0955, 45.4245, 45.8433, 46.0826, 45.8931, 46.0328, 45.6140, 46.2820, 46.2820, 46.0028, 46.0328, 46.4116, 46.2222, 45.6439, 46.2122, 46.2521, 45.7137, 46.4515, 45.7835, 45.3548, 44.0288, 44.1783, 44.2181, 44.5672, 43.4205, 42.6628, 43.1314]
date = pd.date_range('20170101',periods=len(close))

df = pd.DataFrame(close, columns=['close'], index=date)

period = 14

df['delta'] = df['close'].diff()
df['up'] = df['dn'] = df['delta']

df.loc[df['up'][df['up'] < 0].index, 'up'] = 0
df.loc[df['dn'][df['dn'] > 0].index, 'dn'] = 0
df['dn'] = abs(df['dn'])

df['avg_gain'] = df['avg_loss'] = 0
df['rs'] = df['rsi'] = np.nan

df.loc[df.index[period], 'avg_gain'] = np.mean(df.iloc[1:period + 1]['up'])
df.loc[df.index[period], 'avg_loss'] = np.mean(df.iloc[1:period + 1]['dn'])
df.loc[df.index[period], 'rs'] = df.loc[df.index[period], 'avg_gain'] / df.loc[df.index[period], 'avg_loss']
df.loc[df.index[period], 'rsi'] = 100.0 - (100.0 / (1.0 + df.loc[df.index[period], 'rs']))

# can this part be optimized?
avg_gain = df[0:period + 1]['avg_gain'].values
avg_loss = df[0:period + 1]['avg_loss'].values

for idx in range(period + 1, len(df.index)):
    avg_gain = np.append(avg_gain, ((avg_gain[idx - 1] * (period - 1)) + df.up.values[idx]) / period)
    avg_loss = np.append(avg_loss, ((avg_loss[idx - 1] * (period - 1)) + df.dn.values[idx]) / period)

df['avg_gain'] = avg_gain
df['avg_loss'] = avg_loss
# end of can this part be optimized?

df['rs'] = df['avg_gain'] / df['avg_loss']
df['rsi'] = 100.0 - (100.0 / (1.0 + df['rs']))

print(df)

The for loop is the biggest performance problem.

Another question I have is how do I avoid potential division by zero at this line?

df['rs'] = df['avg_gain'] / df['avg_loss']


texts:
I'm stuck with the slow VBA routine below, which I think is the cause of lagging (taking to long). I was wondering if there is a faster way to do this:

With Sheets("Groups")
    .Cells(1, 1).Value = "Groups"
    .Cells(1, 2).Value = "Aantal"
    .Cells(2, 1).Value = "9N4"
    .Cells(2, 2).Value = n9N4
    .Cells(3, 1).Value = "1A2A"
    .Cells(3, 2).Value = n1A2A
    .Cells(4, 1).Value = "1A2B"
    .Cells(4, 2).Value = n1A2B
    .Cells(5, 1).Value = "2A2"
    .Cells(5, 2).Value = n2A2
    .Cells(6, 1).Value = "2A3"
    .Cells(6, 2).Value = n2A3
    .Cells(7, 1).Value = "2A4"
    .Cells(7, 2).Value = n2A4
    .Cells(8, 1).Value = "3A3"
    .Cells(8, 2).Value = n3A3
    .Cells(9, 1).Value = "3A4"
    .Cells(9, 2).Value = n3A4
    .Cells(10, 1).Value = "4A4"
    .Cells(10, 2).Value = n4A4
    .Cells(11, 1).Value = "1B4A"
    .Cells(11, 2).Value = n1B4A
    .Cells(12, 1).Value = "1B4B"
    .Cells(12, 2).Value = n1B4B
    .Cells(13, 1).Value = "1B4C"
    .Cells(13, 2).Value = n1B4C
    .Cells(14, 1).Value = "1B4D"
    .Cells(14, 2).Value = n1B4D
    .Cells(15, 1).Value = "2G4"
    .Cells(15, 2).Value = n2G4
    .Cells(16, 1).Value = "3G4"
    .Cells(16, 2).Value = n3G4
    .Cells(17, 1).Value = "4G4"
    .Cells(17, 2).Value = n4G4
    .Cells(18, 1).Value = "1E3"
    .Cells(18, 2).Value = n1E3
    .Cells(19, 1).Value = "1E4"
    .Cells(19, 2).Value = n1E4
    .Cells(20, 1).Value = "2E4"
    .Cells(20, 2).Value = n2E4
    .Cells(21, 1).Value = "3E3"
    .Cells(21, 2).Value = n3E3
    .Cells(22, 1).Value = "3E4"
    .Cells(22, 2).Value = n3E4
    .Cells(23, 1).Value = "4E4"
    .Cells(23, 2).Value = n4E4
    resultst = n9N4 + n1A2A + n1A2B + n2A2 + n2A3 + n3A3 + n1B4A + n1B4B + n1B4C + n1B4D + n2G4 + n3G4 + n4G4 + n2A4 + n3A4 + n4A4 + n1E3 + n1E4 + n2E4 + n3E3 + n3E4 + n4E4
    .Cells(24, 1).Value = "result"
    .Cells(24, 2).Value = resultst

'check if the sum is correct
    .Cells(24, 3).Value = "=Sum(b2:b23)"
End With

The labels are written and the values come from the code below.
This is a whole list here are a few:

n2E4 = Application.WorksheetFunction.CountIf(Sheets("totallist").Range("G2:G" & rn_totallist), "2E4")
n3E3 = Application.WorksheetFunction.CountIf(Sheets("totallist").Range("G2:G" & rn_totallist), "3E3")
n3E4 = Application.WorksheetFunction.CountIf(Sheets("totallist").Range("G2:G" & rn_totallist), "3E4")
n4E4 = Application.WorksheetFunction.CountIf(Sheets("totallist").Range("G2:G" & rn_totallist), "4E4")


texts:
I was looking for a thread safe implementation of the observer pattern. I read https://xinhuang.github.io/posts/2015-02-11-how-a-multi-threaded-implementation-of-the-observer-pattern-can-fail.html and was thinking about point 4 "Don't reinvent the wheel, use Boost.Signals2 instead". So I tried the following code and wanted to  ask if it is safe to be used in a multithreaded application? What happens if an Observer is destructed during notifyObservers?

#include <boost/signals2.hpp>
#include <iostream>
#include <string>

class AbstractObserver {
public:
    using SignalType = boost::signals2::signal<void()>;

    virtual ~AbstractObserver() = default;

    virtual void notify() = 0;

    void registerAtSubject(SignalType &sig)
    {
        connection_ = sig.connect([this]() { notify(); });
    }

private:
    boost::signals2::scoped_connection connection_;
};

class Subject {
    AbstractObserver::SignalType sig_;
public:
    void registerObserver(AbstractObserver &observer)
    {
        observer.registerAtSubject(sig_);
    }

    void notifyObservers() const
    {
        sig_();
    }
};

class Observer : public AbstractObserver {
    std::string id_;
public:
    explicit Observer(std::string id) : id_(std::move(id))
    {};

    void notify() override
    {
        std::cout << "Observer " << id_ << " got notified" << std::endl;
    }
};

int main()
{
    Subject c;
    {
        Observer o2("B");
        {
            Observer o1("A");
            c.registerObserver(o1);
            c.notifyObservers();
            c.registerObserver(o2);
            c.notifyObservers();
        }
        c.notifyObservers();
    }
    c.notifyObservers();
}


texts: Controller with too many parameters with DI

texts:
Is there a way to reduce the number of parameters of this constructor?
All the services must be used in this Controller. The majority of them are used more than 2 times(some of them >10), with the exception of IService7 that is used only in one method.

public class MyController : CustomBaseApiController
  {
    private readonly IService1 service1;
    private readonly IService2 service2;
    private readonly IService3 service3;
    private readonly IService4 service4;
    private readonly IService5 service5;
    private readonly IService6 service6;
    private readonly IService7 service7;
    private readonly IService8 service8;

    public MyController(IService1 service1, IService2 service2, IService3 service3, IService4 service4, IService5 service5, IService6 service6, IService7 service7, IService8 service8)
    {
      this.service1 = service1;
      this.service2 = service2;
      this.service3 = service3;
      this.service4 = service4;
      this.service5 = service5;
      this.service6 = service6;
      this.service7 = service7;
      this.service8 = service8;
    }

All the methods are specific for this controller and no more refactoring into different Controllers should be done.
How can I refactor this in order to have fewer parameters?
This Controller is heavily tested (using Moq), so, if possible, I would want to keep it easier to mock the dependencies.


texts:
The code below generates only 10 email domains. To me, this is bruteforce programming. Is there another random integer library? Could I use something like random.seed() in C++?

What is a more elegant way to generate 100 emails names using some Python libs/APIs?

import random
domains = [ "hotmail.com", "gmail.com", "aol.com", "mail.com" , "mail.kz", "yahoo.com"]
letters = ["a", "b", "c", "d","e", "f", "g", "h", "i", "j", "k", "l"]

def get_one_random_domain(domains):
        return domains[random.randint( 0, len(domains)-1)]

def get_one_random_name(letters):
    email_name = ""
    for i in range(7):
        email_name = email_name + letters[random.randint(0,11)]
    return email_name

def generate_random_emails():

    for i in range(0,10):
         one_name = str(get_one_random_name(letters))
         one_domain = str(get_one_random_domain(domains))
         print(one_name  + "@" + one_domain)

def main():
    generate_random_emails()

In get_one_random_name(), how can I make this email_name string grow with random letters without using "+ "?

How can I choose letters randomly and put them together without +?


texts: Racing promises and consuming them in the order of their resolution time

texts:
The ideas are

When multiple async calls are made, to be able to start consuming from the first resolving one regardless in what order the promises are fired.
To construct a modern emitter of async values to be consumed by the for await loop.
One may achieve this functionality by making repeated (promise many times) Promise.race()s but i want to believe that no good programmer would feel comfortable with that.
Because both it's wasteful and  i never liked Promise.race(). It's a misnomer. I mean where in the world there is a race that finalizes once somebody wins? It's an insult. It's like calling the second one "Hey.. you are at the top of all losers". Let's change that.

One implementation of this functionality could be starting to render a multipart entity earlier than otherwise. There might be other use cases too, since this will not reject altogether even if a promise in the system gets somehow rejected. We can easily handle rejections in an isolated manner, separatelly, perhaps for retrying or whatnot. Also the promises can be identified as they resolve and we can tell where to use their resolution.
The code below is just a skeleton.

It just shows the mechanism with a simple exception handling.
It doesn't include any retry or promise identification abilities.
It doesn't remove the consumed (fulfilled) promise from the structure. This can be iplemented in the finally block. Once it's implemented, the count variable will be redundant and we can then use the dynamic length property instead.
Being able to use the dynamic length property would allow us to add, remove or replace promises at any point in time just by using standard array methods like .push() or .splice() etc.
It uses the new Private Class Fields which i like a lot.

We will start with a new data type called SortedPromisesArray which in fact is an extension to the Array type. We will empower it with generator and asyncIterator abilities.
export default class SortedPromisesArray extends Array {
  #resolve;
  #reject;
  #count;
  constructor(...args){
    super(...args.filter(p => Object(p).constructor === Promise)); // Make sure everybody is a Promise
    this.#count = this.length;
    this.forEach(p => p.then(v => this.#resolve(v), e => this.#reject(e)));
  };
  async *[Symbol.asyncIterator]() {
    while(this.#count--) {
      try {
        yield new Promise((...rs) => [this.#resolve,this.#reject] = rs);
      }
      catch(e){
        console.log(`Caught an exception ${e}`);
      }
      finally{
        // a handy stage to do useful things
      };
    };
  };
};

and we can consume it like;
import SPA from "../lib/promise-sort.js";

var promise  = (val,delay,isOK) => new Promise((v,x) => setTimeout(_ => isOK ? v(val) : x(val), delay)),
    promises = [ promise("Third", 3000, true)
               , promise("First", 1000, true)
               , Promise.resolve("this is solved first @ microtask queue")
               , promise("Second", 2000, false) // NOTE: this one rejects!
               ],
    sortedPS = new SPA(...promises);

async function sink() {
  for await (let value of sortedPS){
      console.log(`Got: ${value}`);
  };
};

sink();

Any thoughts and recommendations are most welcome.


texts: Finding min value of an array using SIMD

texts:
I have the following code to find the minimum sbyte value in an array. It is using System.Runtime.Intrinsics to perform a SIMD min on chunks of the array, and then loops over the resulting vector to find the true minimum.

public static sbyte Min( sbyte[] array )
{
  if( array.Length <= 0 )
    return 0;

  var length = array.Length;
  var stepSize = Vector128<sbyte>.Count;

  fixed ( sbyte* pStep = &array[ 0 ] )
  {
    var i = stepSize;
    var minVector = Avx.LoadVector128( pStep );
    for( ; i <= length - stepSize; i += stepSize )
      minVector = Avx.Min( minVector, Avx.LoadVector128( pStep + i ) );

    var _ = stackalloc sbyte[ stepSize ];
    Avx.Store( _, minVector );

    // Find min of minVector
    var min = sbyte.MaxValue;
    for( var j = 0; j < stepSize; j++ )
      if( min > _[ j ] )
        min = _[ j ];

    // Evaluate remaining elements
    if( i < length )
      while( i < length )
      {
        if( min > pStep[ i ] )
          min = pStep[ i ];
        i++;
      }

    return min;
  }
}

I feel like this is a slightly excessive amount of code, but seeing how this function is meant to handle arrays with lengths that can't be equally partitioned into a 128-bit register, I'm not sure if there's any cleaner way to do this.

I do intend to implement this method for all supported primitive types, but it seems like most of the code will just be duplicated.


texts:
Please review my balanced parenthesis string checker code below.

I would love to know how to improve my algorithm and if you have any other feedback.

// comments inline

function validateParenthesisString(inputString){

  if(inputString.length === 0){ // empty string is as good as a valid string
    console.log('String is valid.');
    return;
  }

  var element,
      parenthesisStack = [];

 // iterate through the string
  for(var index = 0, length = inputString.length; index < length; index++){

    element = inputString.charAt(index); // cache the character

    switch(element){
      case '(':
        parenthesisStack.push('('); // openeing bracket, so just push it
        break;

      case ')':
        if(parenthesisStack[parenthesisStack.length-1] === '('){ // check if corresponding counterpart pushed already
          parenthesisStack.pop(); // remove
        } else {
          parenthesisStack.push(')');
        }
        break;

      case '[':
        parenthesisStack.push('[');
        break;

      case ']':
        if(parenthesisStack[parenthesisStack.length-1] === '['){
          parenthesisStack.pop();
        } else {
          parenthesisStack.push(']');
        }
        break;

      case '{':
        parenthesisStack.push('{');
        break;

      case '}':
        if(parenthesisStack[parenthesisStack.length-1] === '{'){
          parenthesisStack.pop();
        } else {
          parenthesisStack.push('}');
        }
        break;

      default: // garbage character
        console.log('Invalid character encountered: ' + inputString.charAt(index));
        console.log('Please enter a valid string.');
        console.log('parenthesisStack:', parenthesisStack);
        console.log('***********************************');
        return;
    };

  }

  console.log('parenthesisStack:', parenthesisStack); // just for debugging

 // check parenthesisStack
  if(parenthesisStack.length === 0){
    console.log('String is valid!');
  } else {
    console.log('String is invalid!');
  }

  console.log('***********************************');

};

validateParenthesisString('test'); // invalid
validateParenthesisString('({)}[()]{'); // invalid
validateParenthesisString('[({})]{}'); // valid

Equivalent jsFiddle.


texts: Counts the number of times a particular character, such as e, appears in a file

texts:
This question came from a Java tutorial online:

  Write an example that counts the number of times a particular character, such as e, appears in a file.

I was just wondering if there is any way to improve this particular solution.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CountLetter{
    public static void main(String[] args) {
        Path file = Paths.get("/Users/justin/Desktop/Codes Netbean/JavaRandom/xanadu.txt");
        CountLetter cl1 = new CountLetter(file, 'e');
        System.out.println(cl1.count());
    }

    private Path file;
    private char lookFor;

    CountLetter(Path file, char lookFor){
        this.file = file;
        this.lookFor = lookFor;
    }

    private int count(){
        int count = 0;
        try(BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(file)))){
            String line = null;
            while((line = br.readLine()) != null){
                for(int i = 0; i < line.length(); i++){
                    if(line.charAt(i) == lookFor){
                        count++;
                    }
                }
            }
        } catch (IOException x){
            System.err.println(x);
        }
        return count;
    }
}


texts: Reading a file and storing all the data in a buffer

texts:
I wrote a function to read the entire content of a file and return a pointer to an allocated bufer containing all the data.

Please could you tell me if there is a better way of doing this ? One solution could be to use stat() to pre-allocate a buffer and do only one read() call but I don't know if it's better, any though ?

#include <stdio.h>
#include <memory.h>

char *file_read(const char *path, size_t *file_size)
{
    FILE *file = fopen(path, "r");
    char buffer[FILE_READ_BUFFER_SIZE];
    char *tmp = NULL;
    char *data = NULL; // The buffer containing the data of the file
    char *data_cursor = NULL; // The current position in the data buffer
    size_t data_size = 0; // The size of the data buffer
    size_t n = 0; // The number of bytes read by fread()

    if (file == NULL)
        goto error;

    while ((n = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0) {
        if (data == NULL) {
            data = malloc(sizeof(char) * n);
            data_cursor = data;
            data_size = n;
        } else {
            // We compute the position in the buffer as an integer
            // to be able to re-apply after realloc(). Because realloc()
            // can move the pointer we need this position as an integer.
            size_t cursor_pos = data_cursor - data;
            tmp = realloc(data, sizeof(char) * data_size + n);
            if (tmp == NULL)
                goto error;
            data = tmp;
            data_cursor = data + cursor_pos;
            data_size += n;
        }
        memcpy(data_cursor, buffer, n);
    }

    if (ferror(file))
        goto error;

    fclose(file);
    if (file_size != NULL)
        *file_size = data_size;
    return data;

    error:
    if (file != NULL)
        fclose(file);
    if (data != NULL)
        free(data);
    return NULL;
}


texts: Monitoring navigation function: logic judgment

texts:
Write a simple monitoring navigation function.

I feel logic judgment still needs to be optimized.
I don't have a clear idea right now about code logic such as reducing if statements
How can I optimize the performance of this code?


texts:
I'm attempting to provide an agnostic means of identifying a member. I need a nickname, a guid, and one of user_id, email, or phone_number. Since I'm using Python, I try to not care about the Python type of member because, after all, if it has what I'm looking for then I don't really care whether it really is a Member... or so I have been taught.

There is a circumstance in my application in which actual Member instances may be lumped in with objects that represent the information necessary to create a member. Also, note that actual Member instances have a handy identification() method, which my code tries first.

The problem is in attempting to not care about its type.  I've gone to the extent of trying attributes and items, and now my code looks incredibly repetitive.

try:
    return member.identification()
except AttributeError:
    pass

id_types = ['user_id', 'email', 'phone_number']
if isinstance(member, dict):
    if 'guid' not in member:
        member['guid'] = cls._next_guid()
    for idt in id_types:
        if idt in member:
            try:
                return {
                    'nickname': member['nickname'],
                    'guid': member['guid'],
                    idt: member[idt]
                }
            except KeyError:
                raise ValueError('no nickname')
    else:
        raise ValueError('no user_id, email, or phone_number')
else:
    if 'guid' not in member:
        member['guid'] = cls._next_guid()
    for idt in id_types:
        if hasattr(member, idt):
            try:
                return {
                    'nickname': member.nickname,
                    'guid': member.guid,
                    idt: getattr(member, idt)
                }
            except AttributeError:
                raise ValueError('no nickname')
raise ValueError('no identification could be made')

The question is, if my attempts to not care about the type to this extent are reasonable, then is there a way to make this code better adhere to the principle of DRY?


texts: Using Array to store calculations in VBA

texts:
I have the following VBA code, which works perfectly well to calculate "q"

However, the code is very slow and that is due to the large number of q's being calculated (roughly 7.2m q's are being calculated).

So I thought the best way to proceed is to try store the calculated q values in an array and then dump them into the spreadsheet once all of them are calculated.

The q's will vary for each i and j combination. I have tried to add the following to try and store results in an array to the to the main code given below:

Dim results() as variant
Redim results(I,j)
Results (I,j)= q
Range("G5").value=results

This did not work and I know it does not even look half right, but if you could help me spot where I am going wrong it would be really appreciated.

Sub mort()
Dim age As Integer
Dim month As Integer

For i = 0 To ActiveSheet.Range("F5", Range("F5").End(xlDown)).Count

For j = 0 To ActiveSheet.Range("G3", Range("G3").End(xlToRight)).Count

    gender = Range("C5").Offset(i, 0)

    If gender = "F" Then
    mortable = Worksheets("Female Tabs").Range("A3:C122")
    Else
    mortable = Worksheets("Male Tabs").Range("A3:C122")
    End If

month = Range("G3").Offset(0, j)
age = WorksheetFunction.RoundDown(Range("F5").Offset(i, 0) + (month - 3) / 12, 0)

If age < 119 Then

    a = (12 - ((month - 3) Mod 12)) / 12
    a1 = Application.VLookup(age, mortable, 3, False)

    b = ((month - 3) Mod 12) / 12
    b1 = Application.VLookup(age + 1, mortable, 3, False)

Else

a1 = 0
b1 = 0

End If

q = (1 / 12) * (a * a1 + b * b1)

Worksheets("Policy Mortality Qx").Range("G5").Offset(i, j).Value = q

Next j
Next i

End Sub


texts:
I was referred here from StackOverflow, so here is what I posted over there:

So, for an assignment, I have to construct a binary search tree, plus an assortment of related functions. I have them all working, but I'm looking for a way to optimize my way of finding in-order predecessors and successors. Here's my code for finding the predecessor (successor is, of course, nearly identical):

public double findPredecessor(double num) {
        if(this.has(num) == true) {
            node temp = this.root;
            node iterator = this.root;
            node returner = null;

            while(temp.key != num) { //match the passed "num" to a key
                if(num < temp.key) {
                    temp = temp.left;
                } else {
                    temp = temp.right;
                }
            }

            if(temp.left != null) {
                return findMaxInternal(temp.left);
            }

            while(iterator != null) {
                if(temp.key < iterator.key) {
                    iterator = iterator.left;
                }
                else if(temp.key > iterator.key) {
                    returner = iterator;
                    iterator = iterator.right;
                }
                else break;
            }
            return returner.key;
        }
        else return Double.NaN;
    }

Yes, it is part of the assignment that my function take a double as argument, and not a node. I'm looking to see if there is a way that I can do this in one loop, to cut a bit on running time. I know that two successive, non-nested loops still is O(n), but still.


texts:
I have a function f(i, j) that accepts two std::size_t arguments and I want to make a constexpr std:array out of its values on a 2d grid, (i = 0, ..., rows-1; j = 0, ..., cols-1) in, say, column-major order.

The code:

#include <array>
#include <tuple>
#include <type_traits>

template<std::size_t rows, std::size_t cols>
constexpr auto make_2d_index_table()
{
    std::array<std::array<std::size_t, 2>, rows * cols> table{};
    for (std::size_t i = 0; i < table.size(); ++i)
        table[i] = {i % rows, i / rows};

    return table;
}

template<std::size_t rows, std::size_t cols, class Func>
constexpr std::array<std::invoke_result_t<Func, std::size_t, std::size_t>, rows * cols>
    make_array_of_2d_func_values(Func&& func)
{
    return apply([&func](auto... row_col)
    {
        return std::array<std::invoke_result_t<Func, std::size_t, std::size_t>, rows * cols>
            {std::apply(std::forward<Func>(func), row_col)...};
    }, make_2d_index_table<rows, cols>());
}

Usage:

constexpr auto arr = make_array_of_2d_func_values<5, 3>(
    [](auto i, auto j) { return i + 2 * j; });

The object of the type returned by a function may not be default constructible. So I can't just create an array<invoke_result_t<...>, rows * cols> arr{} of default constructed objects and then initialize it in the for loop like in make_index_table().

Is this a good solution?


texts: Improving function that parses string and returns first integer present

texts:
This exercise is from jshero.com.
Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN.
Here is my working solution. I'm posting in hopes of receiving pointers on how I could have written the code more effectively.
function parseFirstInt(str) {
    if (Number.isNaN(str) === true) {
        return NaN;
    } else {
        let searchFrom = str.search(/[-+]?[0-9]+/g);
        let searched = str.substr(searchFrom);
        return parseInt(searched, 10);
    };
}

Example: parseFirstInt('No. 10') should return 10 and parseFirstInt('Babylon') should return NaN.
parseFirstInt('No. -3) should return -3.
Thank you!


texts: Refactor similar queries but reverse side of inequality operator

texts:
How can I refactor this?

public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseAtLeast(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)
{
    if (date == null)
    {
        query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||
                                     ( (company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count) >= minimum) );
        return query;
    }
    else
    {
        var notNullDate = date.Value;

        var result = (from company in query
                      let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)
                      let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)
                      let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)
                      let productCount = company.Products.Count(item => item.create_date <= notNullDate)
                      let referenceCount = company.References.Count(item => item.create_date <= notNullDate)
                      where (rfqCount + poCount + invoiceCount) >= minimum || (productCount + referenceCount) >= minimum
                      select company);

        return result;
    }

}

public static IQueryable<T_COMPANY> WhereTotalTransactionOrShowCaseLessThan(this IQueryable<T_COMPANY> query, int minimum, DateTime? date = null)
{
    if (date == null)
    {
        query = query.Where(company => (company.Products.Count + company.References.Count) >= minimum ||
                                     ((company.T_RFQs.Count + company.T_POs.Count + company.T_INVOICEs.Count) < minimum));
        return query;
    }
    else
    {
        var notNullDate = date.Value;

        var result = (from company in query
                      let rfqCount = company.T_RFQs.Count(item => item.create_date <= notNullDate)
                      let poCount = company.T_POs.Count(item => item.create_date <= notNullDate)
                      let invoiceCount = company.T_INVOICEs.Count(item => item.create_date <= notNullDate)
                      let productCount = company.Products.Count(item => item.create_date <= notNullDate)
                      let referenceCount = company.References.Count(item => item.create_date <= notNullDate)
                      where (rfqCount + poCount + invoiceCount) >= minimum || (productCount + referenceCount) < minimum
                      select company);

        return result;
    }

}


texts:
I'm doing some simple validations using jQuery to check if all textboxes are filled.

$(document).ready(function () {
$("#<%= btnInsertCountry.ClientID %>").click(function () {
    var codeValue = $("#<%= txtCountryCode.ClientID %>").val();
    var nameValue = $("#<%= txtCountryName.ClientID %>").val();

    if (codeValue == "" || nameValue == "") {
        if (codeValue == "") {
            $("#divCodeValidation").show();
        }
        else {
            $("#divCodeValidation").hide();
        }

        if (nameValue == "") {
            $("#divNameValidation").show();
        }
        else {
            $("#divNameValidation").hide();
        }

        return;
    }
});
});

The divs have the property display: none and contains the error message. This code works but I don't like it because I use an if to check if the values are empty and inside I have an if for each variable.

Is there a better way to do this validation?


texts: Simple implementation of LRU caching in PHP

texts:
This is my implementation of LRU caching in PHP.

It works fine when I tested as. What are the things that I miss or need attention?

<?php

class Cache{
    private $cache;
    private $size;

    public function __construct($size)
    {
        $this->cache = [];
        $this->size = $size;
    }

    public function put($item)
    {
        if($this->isFull())
        {
            if(in_array($item, $this->cache))
            {
                $this->cache = array_diff($this->cache, [$item]);
            }
            else
            {
                array_pop($this->cache);
            }
        }

        array_unshift($this->cache,$item);
    }

    public function display()
    {
        var_dump($this->cache);
    }

    private function isFull()
    {
        if(count($this->cache) >= $this->size)
        {
            return true;
        }
    }
}

$cache_size = 4;
$entries = [3,4,4,5,6,7,4,4,3,5,2,3,1,1,4];

$cache = new Cache($cache_size);
$cache->display();

foreach($entries as $entry)
{
    $cache->put($entry);
}

$cache->display();

Output for above provided data

//blank cache
array(0) {
}
//insertion of all entries
array(4) {
  [0]=>
  int(4)
  [1]=>
  int(1)
  [2]=>
  int(3)
  [3]=>
  int(2)
}


texts:
I am new toboost::thread and am making a producer-consumer with a Monitor. This is how I've coded it so far:

//{ Declarations in header
private:
  boost::condition_variable    _condition;
  boost::mutex                 _mutex;
  std::deque<RawMatrix*>       _queue;
  boost::detail::atomic_count  _count;
//}

void MatrixMonitor::deposit(RawMatrix* rawMatrix){
    boost::unique_lock<boost::mutex> lock(_mutex);
    _condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
    _queue.push_back(rawMatrix);
    ++_count;
    _condition.notify_one();
}

RawMatrix* MatrixMonitor::withdraw(){
    boost::unique_lock<boost::mutex> lock(_mutex);
    _condition.wait(lock, boost::bind(std::greater_equal<int>(), boost::ref(_count), min));
    RawMatrix* elem = _queue.front();
    _queue.pop_front();
    --_count;
    _condition.notify_one();
    return elem;
}

So far I've written the Producer like this:

void MatrixProducer::produce(){
    while(true){
        boost::mutex::scoped_lock lock(_mutex);
        RawMatrix* matrix = rawMatrix();
        _monitor->deposit(matrix);
        boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
    }
}
boost::thread& MatrixProducer::start(){
    _thread = boost::thread(boost::bind(&MatrixProducer::produce, this));
    return _thread;
}
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}

The Consumer:

boost::thread& MatrixConsumer::start(){
    _thread = boost::thread(boost::bind(&MatrixConsumer::consume, this));
    return _thread;
}

void MatrixConsumer::consume(){
    while(true){
        boost::mutex::scoped_lock lock(_mutex);
        RawMatrix* matrix = _monitor->withdraw();
        _matrix->deposit(Matrix);
        boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
    }
}

Is this okay? Also, who will have the ownership of this: Producer or Consumer and Monitor?


texts: Pure functional code for the sublists of a list

texts:
The code below gives me the list of sublists of a list. Code can still be improved to avoid the use of append, right?

(defun sublists (alist)
  (labels ((aux (list p r)
             (if (null list)
                 (append r (maplist #'identity p))
                 (aux (cdr list)
                      (append p (list (car list)))
                      (append r (maplist #'identity p))))))
    (aux alist nil nil)))

CL-USER> (sublists (list 1 2 3 4))
((1) (1 2) (1 2 3) (1 2 3 4) (2) (2 3) (2 3 4) (3) (3 4) (4))

ideas? This question was posted in https://stackoverflow.com/questions/49019045/pure-functional-code-for-the-sublists-of-a-list originally.


texts:
I made this little function for flyweighting any type that has operator<. I followed the convention of make_unique and make_shared with make_one. Not sure if that's the best name.

// Create a single instance of an object, using
// operator< to determine equality.
// Note that we take a value instead of a constructor
// arguments because often we'll want to mutate a field,
// then create a new object, without passing in everything.
template<class T>
std::shared_ptr<const T> make_one(const T& value) {

  struct cmp {
    bool operator()(const T* a, const T* b) const {
      return *a < *b;
    }
  };

  static std::set<const T*, cmp > values;

  auto iter = values.find(&value);

  if(iter != values.end()) {
    return (*iter)->shared_from_this();
  }

  auto ptr = std::shared_ptr<T>(new T(value), [](T* p) {
    values.erase(p); delete p;
  });
  values.insert(ptr.get());
  return ptr;

}

Test code:

  struct Foo : std::enable_shared_from_this<Foo> {
    int x = 0;
    Foo(int x) : x(x) { }
    bool operator<(Foo rhs) const { return x < rhs.x; }
  };

  auto p0 = make_one(Foo{0});
  auto p1 = make_one(Foo{0});
  assert(p0 == p1);

  auto p2 = make_one(Foo{42});
  assert(p2 != p0);

Review goals:

Can I avoid requiring enable_shared_from_this?
Can I make it thread safe without too much trouble?
Any other ideas for improvement.


texts: Correct control of execution of Java thread

texts:
I'm writing an application that will use the JLayer library to play an mp3 file. Since the player does not have any methods to pause the playback - play() does not return until the song is finished - I decided to put it in a thread and simply control that thread. This is possible because one can execute play(1) which plays a single frame of the song. Putting this in a loop will thus play the entire song smoothly.

What I have done is the following:

Create a Thread class Mp3PlayerThread that can be used to play a song in a different thread.
Create a wrapping class Mp3Player that holds a thread object and controls the volatile flags inside the Thread.

I built the object Mp3Player such that it should be thread safe. I.e., pass an instance of Mp3Player around. To do this I made all the control methods synchronized.

I am wondering if this code can be made more solid without using volatile variables? I have always learned that you should not use the volatile keyword if possible.

Mp3PlayerThread

public class Mp3PlayerThread extends Thread
{
    public  volatile boolean playing = false;
    public  volatile boolean abort   = false;
    private Player   player;
    private String   path;

    public Mp3PlayerThread(String file)
    {
        this.path = file;
    }

    public void run()
    {
        // http://stackoverflow.com/questions/7313657/should-you-synchronize-the-run-method-why-or-why-not
        try
        {
            FileInputStream     fis = new FileInputStream(this.path);
            BufferedInputStream bis = new BufferedInputStream(fis);
            this.player             = new Player(bis);

            while (!abort)
            {
                if (playing)
                    player.play(1);
            }
            Printer.debugMessage(this.getClass(), "end of file or stopped");

        } catch (FileNotFoundException | JavaLayerException e)
        {
            e.printStackTrace();
        }
    }
}

Mp3Player

public class Mp3Player
{
    private Mp3PlayerThread playerThread;
    private String          song;

    public Mp3Player(String filename)
    {
        song = filename;
    }
    /**
     * Initializes the playerThread with the given song, sets the flag to true
     * and starts playing the song.
     */
    public synchronized void play()
    {
        playerThread         = new Mp3PlayerThread(song);
        playerThread.playing = true;
        playerThread.start();
    }
    /**
     * Pauses the execution of the playerThread.
     */
    public synchronized void pause()
    {
        Printer.debugMessage(this.getClass(), "paused");
        playerThread.playing = false;
    }
    public synchronized void resume()
    {
        Printer.debugMessage(this.getClass(), "resuming");
        playerThread.playing = true;
    }
    public synchronized void stop()
    {
        Printer.debugMessage(this.getClass(), "stopping");
        playerThread.abort = true;
        playerThread       = null; // Needed or not?
    }
}


texts: Console program, let users to enter prices calculate subtotal, tax, and total with C Sharp

texts:
I am posting this here because it was suggested that it is the best place by a seasoned user.

This is a project I already submitted, but I never received feedback. All my upcoming assignments will be based on this, so I wanted to make sure it is correct. I got this program to work as far as calculating the information, but I was hoping someone could please let me know if it meets the parameters/requirements?

I did attempt it. It works and adds the items exactly how the example showed in the video. However, I wanted to make sure my code is solid, and not just a mishmash or working because I got lucky, and if there is a better more solid way to do this I want to make sure I can. I do want feedback so I can learn and get better and I am trying my hardest. I always right out all the code I see here and try it and learn what it does piece by piece, because it helps me learn and improve. I also want to make sure it is going to work once I start the code for the next half of the requirements.

**Write a Console program, let users to enter prices calculate subtotal, tax, and total. - Delcare variable data type as decimal (6 variables needed) decimal apple;

Conver string to decimal from input apple = Convert.ToDecimal(Console.ReadLine());
Do addition for subtotal
Multiplication for tax (0.065M) --- M or m stands for money value, read page 94.
Addition for total
You need to show only two digits after decimal point
The class example:

`Console.WriteLine(" Subtotal: ${0}", String.Format("{0:0.00}", subTotal)); blank line: Console.WriteLine("") Console.Write(" Apple: $"); apple = Convert.ToDecimal(Console.ReadLine());`

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculatorRun
{
    class Calculator
    {
        static void Main(string[] args)
        {
            decimal FirstOperand, SecondOperand, Result, result;
            Console.Write("Addition Calculation");
            Console.Write("      \n\n");
            Console.Write("   Enter first operand:       ");
            FirstOperand = Convert.ToDecimal(Console.ReadLine());
            Console.Write("   Enter second operand:      ");
            SecondOperand = Convert.ToDecimal(Console.ReadLine());
            Console.Write("-------------------------\n\n");
            Result = FirstOperand + SecondOperand;
            result = Convert.ToDecimal(Result);
            Console.WriteLine("Addition Result: {0}", string.Format("{0}", result));
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

The next part of the assignment is this, which is what I need to make sure my code is correct so I can build towards:

Delcare variable data type as decimal (5 variables needed) count, price, subtotal, tax, total

Write a do while loop, if the price is not -1, loop continues show count number enter price get subtotal increase count

Calculate tax, total

Display total count, subtotal, tax, total

Feedback I received I am working on:
What happens if the user enters an invalid number for either operand? (Thanks yo PaulF. I am not quit sure what this means, I think it means if someone enters a number such as -1. However, I will have to research a fix as this is a bit outside my realm).

This line is uncessary: result = Convert.ToDecimal(Result); because Result is already a decimal. You don't need two of them... (Thanks to Rufus L. I have to look into this and understand decimals more.)

This is the book I am using, and what I have to match so if some code seems oddly specific or old, that is why.
https://cscnt.savannahstate.edu/StudentFiles/Data_Structure/Visual%20C%23%202012%20How%20to%20Program.pdf


texts:
This is a C++17 is_integral trait implementation.

Most implementations exhaust all integral types:

bool
char, char16_t, char32_t, wchar_t
[unsigned] short
[unsigned] [long [long]] int

However, it is possible that the implementation defines some extended signed integer types and extended unsigned integer types. One workaround is to exhaust all the implementations using #ifdefs, but this workaround is not theoretically (in the language lawyer's point of view) portable. For example, if Mickey Mouse just rolls out a brand-new standard-conforming extended integer type, such workarounds fail.

I theorized that for any type T, is_integral<T>::value is true if and only if it is convertible to std::intmax_t or std::uintmax_t via a non-narrowing standard conversion sequence. I tried to deploy this fact, enforcing the two restrictions respectively, by:

using the so-called "uniform initialization" syntax (formally list-initialization) to prevent narrowing conversions; and
using a dummy class (which I call a generator class) with a conversion operator to prevent user-defined conversion sequences.

I tested with the cases of standard integral types (expecting true,) standard floating point types (expecting false,) user-defined types convertible to some standard integral type (expecting false.) All tests passed.

Here is my code, within 40 lines.

// C++17 is_integral implementation
// which handles extended integer types
// in a portable way
// (without resorting to #ifdef chains)

#include <cinttypes> // for std::intmax_t, std::uintmax_t
#include <type_traits> // for std::is_same, std::bool_constant
                       // can be trivially defined manually, just lazy

namespace my_std {
    namespace detail {
        // Generator type to bypass user-defined conversions
        template <typename T>
        struct Generator {
            operator T();
        };
        // helper type to designate substitution failure
        struct Failed {};
        // check functions (exploit SFINAE)
        // uses brace syntax to prevent narrowing conversions
        template <typename T>
        auto check_signed(int) -> decltype(std::intmax_t{Generator<T>{}});
        template <typename T>
        auto check_signed(...) -> Failed;
        template <typename T>
        auto check_unsigned(int) -> decltype(std::uintmax_t{Generator<T>{}});
        template <typename T>
        auto check_unsigned(...) -> Failed;
        // function invoker trait
        template <typename T>
        struct Int_trait {
            static constexpr bool is_signed_int = !std::is_same_v<
                Failed, decltype(check_signed<T>(0))
            >;
            static constexpr bool is_unsigned_int = !std::is_same_v<
                Failed, decltype(check_unsigned<T>(0))
            >;
            static constexpr bool is_int = is_signed_int || is_unsigned_int;
        };
    }
    // "the" trait
    template <typename T>
    struct is_integral
        :std::bool_constant<detail::Int_trait<T>::is_int>
        { };
}

Any criticism or suggestion is highly appreciated!

<joke>The absolute best implementation with maximum portability and simplicity and clarity that is guaranteed to work on all machines is:

#include <type_traits>
namespace my_std {
    template <typename T>
    struct is_integral
        :std::is_integral<T>
        { };
}

</joke>


texts: Scan similar files in different directories and report differences

texts:
I wrote a program in Python that scans all files in a directory, makes dictionaries with stuff like date of creation and a hash of the contents of a file. Then i scan another directory which is just a copy of the original dir, but with some files added, deleted and changed. My program reports these changes.

import os
import stat
import hashlib
import json

class DirInfo:
    def __init__(self):
        self._dirInfo = {}

    def probe(self, dirname):
        fname = os.path.join(dirname, "data.txt")
        blocksize = 512000000
        for file in os.listdir(dirname):
            if file != "data.txt":
                fileWithPath = os.path.join(dirname, file)
                fileInfo = {}
                fileInfo['name'] = file
                if os.path.isfile(fileWithPath):
                    sbuf = os.fstat(os.open(fileWithPath, os.O_RDONLY))
                    fileInfo['type'] = stat.S_IFMT(sbuf.st_mode)
                    fileInfo['mode'] = stat.S_IMODE(sbuf.st_mode)
                    fileInfo['mtime'] = sbuf.st_mtime
                    fileInfo['size'] = sbuf.st_size
                    hasher = hashlib.sha256()
                    with open(fileWithPath, 'rb') as x:
                        for chunk in iter(lambda: x.read(blocksize), b""):
                            hasher.update(chunk)
                    fileInfo['sha256'] = hasher.hexdigest()
                if os.path.islink(fileWithPath):
                    fileInfo['symlink'] = os.readlink(fileWithPath)
                self._dirInfo[file] = fileInfo
                del fileInfo
        DirInfo.save(self._dirInfo, fname)
        pass

    def compare(self, other):
        pad = "D:\\Testmapje met random files\\data.txt"
        pad2 = "D:\\Testmapje met random files 2\\data.txt"
        dct = DirInfo.load(self, pad)
        dct2 = DirInfo.load(other, pad2)
        assert isinstance(other, DirInfo)
        for key in dct:
            if key not in dct2:
                print (key, "is verwijderd")
        for key in dct2:
            fileHuidig = key
            if key not in dct:
                print (key, "is toegevoegd")
            else:
                allKeysPerFileMeasurement1 = (dct.get(key))
                allKeysPerFileMeasurement2 = (dct2.get(key))
                for key in allKeysPerFileMeasurement2:
                    Measurement1Value = (allKeysPerFileMeasurement1.get(key))
                    Measurement2Value = (allKeysPerFileMeasurement2.get(key))
                    if Measurement1Value != Measurement2Value:
                        print("In bestand:", fileHuidig, "was", key, Measurement1Value, "nu is", key, Measurement2Value)
        return []

    def save(self, fname):
        json.dump(self, open(fname, 'w'))
        pass

    def load(self, fname):
        return json.load(open(fname, 'r'))

if __name__ == '__main__':
    dirname = "D:\\Testmapje met random files"
    dirnameanders = "D:\\Testmapje met random files 2"
    dirInfo1 = DirInfo()
    dirInfo1.probe(dirname)
    # change some files
    dirInfo2 = DirInfo()
    dirInfo2.probe(dirnameanders)
    for err in dirInfo1.compare(dirInfo2):
        print(err)

My program gives the following output:

LinkNaarTestFolder2 is verwijderd (deleted)

In bestand: Lief dagboek.txt was mtime 1530555920.17531 nu is mtime 1530723663.3718975

In bestand: Lief dagboek.txt was size 30 nu is size 22

In bestand: Lief dagboek.txt was sha256 c33b32ad0a34316c970febc149199ca59946e75753ddc6438f09d1204835d0e4 nu is sha256 4728379b3f491004319de08ca6161d0b47d3f7921d79d7a9b95e1ca2c458ed48

In bestand: LinkNaarTestFolder was symlink C:\Test voor python nu is symlink C:\Users\Kevin\Documents\Battlefield 3

lol.txt is toegevoegd (is added)

Any ways to make my code shorter?


texts:
My program is supposed to sort a stack such that the smallest item are on the top. I can use a temporary stack, but you may not copy the elements into any other data structure. The program works overall, but I was wondering if there is anything that I can do to make it more efficient/better.

import java.util.Stack;

public class SortStack {

    Stack sorted;

    public Stack sort(Stack unsorted) {

        int temp2 = 0; // to keep track of number of top of the sorted stack

        while(!unsorted.isEmpty()) {
            int temp1 = (int) unsorted.pop();

            if(sorted == null) { // if sorted stack is empty, create it and push the first number onto it
                sorted = new Stack();
                sorted.push(temp1);
                System.out.println(temp1 + " pushed from s1 to s2");
            } else if(temp1 >= temp2) { // push onto sorted stack if what is popped from original stack >= unsorted stack
                sorted.push(temp1);
                temp2 = temp1;
                System.out.println(temp1 + " pushed from s1 to s2");
            } else { // keep on popping from sorted stack to unsorted stack until unsortedTop < sortedTop
                    // this will make sure whatever is popped from original stack will not be less than the peek of the sorted stack
                while(temp1 < temp2) {
                    int sortedPop = (int) sorted.pop();
                    unsorted.push(sortedPop);
                    System.out.println(sortedPop + " pushed from s2 to s1");
                    temp2 = (int) sorted.peek();
                }
                sorted.push(temp1); // after both stacks are balanced, push element to sorted stack
                System.out.println(temp1 + " pushed from s1 to s2");
            }
        }
        return sorted;
    }

    public static void main(String[] args) {

        SortStack ss = new SortStack();

        Stack unsorted = new Stack();
        unsorted.push(7);
        unsorted.push(10);
        unsorted.push(5);
        unsorted.push(12);
        unsorted.push(8);
        unsorted.push(3);
        unsorted.push(1);

        ss.sort(unsorted);

    }

}


texts:
Im implementing and designing a workflow that performs both HTTP and BLE requests.

Im having trouble figuring out the best approach to design a service to handle both types of requests, and manage state.

I thought to make a base class Request with an execute method that all types of requests will conform to.

BLE and HTTP are quite different and dont share any attributes, so I made an enum to handle their associated values. It includes a provider which is a client that exposes api to perform actual BLE or HTTP request.

enum RequestCode: UInt {
    case getStatus             = 0x01
    case download              = 0x02
    case confirm               = 0x03
    case cancel                = 0x04
    case getAuthToken          = 0xF5
}

enum RequestType {
    case BLE(code:RequestCode, provider:BLEProvider, characteristic: CBCharacteristic, service: CBService)
    case HTTP(code:RequestCode, provider:NetworkProvider, data: Data, accessToken:String, method:HTTPMethod, params:[String:Any]?)
}

class Request {

    var type: RequestType

    init(type: RequestType) {
        self.type = type
    }

    func execute() {

        switch type {

        case .BLE(let code, let provider, let characteristic, let service):
            provider.writeValue(data: code.rawValue, characteristic: characteristic, service:service)

        case .HTTP(let code, let provider, let data, let accessToken, let method, let params):
            provider.performRequest(data: data, token: accessToken, method: method, params:params)

        }

    }
}

Questions

What is a better way to structure my requests, to handle both BLE and HTTP?
How can I handle transitions from one state/event to the next? Does it make sense to try to use promises, where I can call execute on each request, and chain them all together? If not, should I think of adding each request to a queue, if and how could a state machine be designed around RequestCode which are the events in the sequence?


texts: Enabling discard pending changes on DbContext

texts:
This code review request is tightly coupled with this SO question, this is the solution I implemented to solve the problem being asked about there.

All my ViewModels get constructor-injected with a Model that itself gets constructor-injected with a DbContext-derived class, and that works well in all cases, except when the View has a command to allow the user to discard pending changes, in which case the DbContext should be disposed and then reinstantiated.

Obviously since the DbContext is created by an IoC container it would be a very bad idea to just dispose and reinstantiate the context, so I came up with a solution involving a factory.

public interface IContextFactory<out TContext> where TContext : DbContext
{
    TContext Create();
}

public interface IDiscardModelChanges
{
    void DiscardChanges();
}

Now IDiscardModelChanges is implemented by the model, so to facilitate this I've created a base class that will ensure I have a context factory at hand:

public abstract class DiscardableModelBase<TContext> : IDiscardModelChanges, IDisposable
    where TContext : DbContext
{
    private readonly IContextFactory<TContext> _factory;

    protected TContext Context { get; private set; }

    protected DiscardableModelBase(IContextFactory<TContext> factory)
    {
        _factory = factory;
        Context = _factory.Create();
    }

    public virtual void DiscardChanges()
    {
        Context.Dispose();
        Context = _factory.Create();
    }

    public void Dispose()
    {
        Context.Dispose();
    }
}

The model that needs to control its DbContext then derives from this class:

public class SomeModel : DiscardableModelBase<SomeContext>, ISomeModel
{
    public SomeModel(IContextFactory<SomeContext> factory)
        : base(factory)
    { }

    /* methods that act upon protected Context property */
}

And then the ViewModel that needs to discard pending changes can do it like this (given a private readonly ISomeModel _model):

var model = _model as IDiscardModelChanges;
if (model != null) model.DiscardChanges();

As far as binding conventions are concerned, I'm keeping the existing "Context" convention, and adding a "ContextFactory" one:

_kernel.Bind(t => t.From(_dataLayerAssembly)
                   .SelectAllClasses()
                   .Where(type => type.Name.EndsWith("ContextFactory"))
                   .BindSingleInterface());

Bottom line, as far as ViewModels are concerned, nothing changes; the Model is still injected as an interface that exposes the available model methods, and the IDiscardModelChanges interface is only needed if the ViewModel needs to use it, and the ViewModel can't assume the interface is implemented by the Model.

Any known issues with this approach, any blatant mistake made?


texts:
I've created a script using Python in association with Scrapy to parse the movie names and its years spread across multiple pages from a torrent site. My goal here is to write the parsed data in a CSV file other than using the built-in command provided by Scrapy, because when I do this:

scrapy crawl  torrentdata -o outputfile.csv -t csv

I get a blank line in every alternate row in the CSV file.

However, I thought to go in a slightly different way to achieve the same thing. Now, I get a data-laden CSV file in the right format when I run the following script. Most importantly I made use of a with statement while creating a CSV file so that when the writing is done the file gets automatically closed. I used crawlerprocess to execute the script from within an IDE.

  My question: Isn't it a better idea for me to follow the way I tried below?

This is the working script:

import scrapy
from scrapy.crawler import CrawlerProcess
import csv

class TorrentSpider(scrapy.Spider):
    name = "torrentdata"
    start_urls = ["https://yts.am/browse-movies?page={}".format(page) for page in range(2,20)] #get something within list
    itemlist = []

    def parse(self, response):
        for record in response.css('.browse-movie-bottom'):
            items = {}
            items["Name"] = record.css('.browse-movie-title::text').extract_first(default='')
            items["Year"] = record.css('.browse-movie-year::text').extract_first(default='')
            self.itemlist.append(items)

        with open("outputfile.csv","w", newline="") as f:
            writer = csv.DictWriter(f,['Name','Year'])
            writer.writeheader()
            for data in self.itemlist:
                writer.writerow(data)

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
})
c.crawl(TorrentSpider)
c.start()


texts: Merge the multiple observables responses into a single array

texts:
Here's what I trying to do:
Given a paginated API, get all the resources using parallel requests.
The API returns a limited number of resources per call. So, you need to use an offset parameter to get to the next set of data until all data is extracted.
Here's my idea (but getting some warning because I'm using flat on the response), so maybe there's a better way to do this.

Get the total count of items.
Given the count and the limit, calculate how many requests are needed to get all data.
Trigger all requests in parallel and combine all data into a flattened array.

Here's an example:
https://stackblitz.com/edit/paginated-api?embed=1&file=index.ts&hideExplorer=1&devtoolsheight=100
getCount().pipe(
  mergeMap(count => range(0, Math.ceil(count / limit))),
  map(offset => getDevices(offset, limit)),
  combineAll(),
).subscribe(res => {
  const a = res.flat(); // <--- warning: Property 'flat' does not exist on type '{ name: string; }[][]'.
  console.log(JSON.stringify(a));
});

I feel this solution is a little hacky. It's flattening the response in the subscription. I'd like to know if there's an RXJS operator that I can use on the pipe to flatten the response, so I don't have to in the subscription?
How to merge the multiple observables responses into a single array?


texts: Balanced smileys check algorithm (part 3)

texts:
This is a follow-up for here, for bug fixes and applied advice.

  Problem

  Your friend John uses a lot of emoticons when you talk to him on
  Messenger. In addition to being a person who likes to express himself
  through emoticons, he hates unbalanced parenthesis so much that it
  makes him go :(

  Sometimes he puts emoticons within parentheses, and you find it hard
  to tell if a parenthesis really is a parenthesis or part of an
  emoticon.

  A message has balanced parentheses if it consists of one of the
  following:

  An empty string ""
  One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)
  An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.
  A message with balanced parentheses followed by another message with balanced parentheses.
  A smiley face ":)" or a frowny face ":("
  Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:

At any point, the number of ) (close) should be less than the number of ( (open) + number of :( (frown)
At the end, the number of ( (open) should be less than the number of ) (close) and :) (smile)

I'm wondering if there are any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.

def check_balance(source):
    left = 0
    right = 0
    smile = 0 # :)
    frown = 0 # :(
    pre = ''
    for c in source:
        if c == ')':
            if pre == ':':
                smile += 1
            else:
                right += 1
                if right > left + frown:
                    return False
        elif c == '(':
            if pre == ':':
                frown += 1
            else:
                left += 1
        pre = c
    if left > right + smile:
        return False
    return True

if __name__ == "__main__":
    raw_smile_string = 'abc(b:)cdef(:()' # true
    raw_smile_string = 'a)' # false
    raw_smile_string = ')('  # false
    print check_balance(raw_smile_string)


texts: Implementing the observer pattern for a stock exchange scenario

texts:
I am trying to implement the observer pattern for a stock exchange scenario. Multiple stocks can be registered at a stock exchange. There will be stock observers who are observing some specific stocks. Please advise how this implementation can be improved.

stock_exchange.hpp

#ifndef STOCK_EXCHANGE_HPP
#define STOCK_EXCHANGE_HPP

#include "stock_observer.hpp"
#include "stock.hpp"
#include<unordered_map>
#include<string>
#include<list>

class Stock_Observer;
class Stock;

class Stock_Exchange
{
    std::unordered_map<std::string, Stock*> registered_stocks;
    std::unordered_map<std::string, std::list<Stock_Observer*>> stock_observers;

    public:
        void notify_observers(std::string stock_name);
        void unregister_observer(Stock_Observer& so, std::string stock_name);
        void register_observer(Stock_Observer& so, std::string stock_name);
        void add_stock(Stock& new_stock);
        void remove_stock(Stock& s);
        Stock& get_stock(std::string stock_name);
};

#endif // STOCK_EXCHANGE_HPP

stock_exchange.cpp

#include "stock_exchange.hpp"
#include "stock_observer.hpp"
#include<algorithm>

void Stock_Exchange::add_stock(Stock& new_stock)
{
    registered_stocks[new_stock.get_name()] = &new_stock;
}

void Stock_Exchange::remove_stock(Stock& s)
{
    registered_stocks.erase(s.get_name());
    stock_observers.erase(s.get_name()); //Memory leak!!!
}

Stock& Stock_Exchange::get_stock(std::string stock_name)
{
    return *registered_stocks[stock_name];
}

void Stock_Exchange::register_observer(Stock_Observer& observer, std::string stock_name)
{
    stock_observers[stock_name].push_back(&observer);
}

void Stock_Exchange::unregister_observer(Stock_Observer& observer, std::string stock_name)
{
    auto l = stock_observers[stock_name];
    l.erase(std::find(l.begin(), l.end(),&observer));
}

void Stock_Exchange::notify_observers(std::string stock_name)
{
    for(auto o : stock_observers[stock_name])
    {
        o->notify(stock_name);
    }
}

stock_observer.hpp

#ifndef STOCK_OBSERVER_HPP
#define STOCK_OBSERVER_HPP

#include "stock.hpp"
#include "stock_exchange.hpp"
#include<string>

class Stock_Exchange;

class Stock_Observer
{
    static int id_sequence;
    int id;
    Stock_Exchange* se;
    public:
        Stock_Observer(Stock_Exchange* s)
        {
            se = s;
            id = id_sequence++;
        }
        void notify(std::string stock_name);
};

#endif // STOCK_OBSERVER_HPP

stock_observer.cpp

#include "stock_observer.hpp"
#include<iostream>

int Stock_Observer::id_sequence = 1;

void Stock_Observer::notify(std::string stock_name)
{
    std::cout << "Object " << id << " notified about " << stock_name << std::endl;
}

stock.hpp

#ifndef STOCK_HPP
#define STOCK_HPP
#include "stock_exchange.hpp"
#include<string>

class Stock_Exchange;

class Stock
{
    std::string name;
    double price;
    Stock_Exchange* se;

    public:
        Stock(Stock_Exchange* s, std::string stock_name, double stock_price)
        {
            se = s;
            name = stock_name;
            price = stock_price;
        }
        std::string get_name();
        void set_price(double p);

};
#endif // STOCK_HPP

stock.cpp

#include "stock.hpp"

std::string Stock::get_name()
{
    return name;
}

void Stock::set_price(double p)
{
    price = p;
    se->notify_observers(this->name);
}

main.cpp

#include<iostream>
#include "stock_exchange.hpp"
#include "stock_observer.hpp"
#include "stock.hpp"

int main()
{
    Stock_Exchange se;

    Stock_Observer so1(&se), so2(&se);

    Stock infy(&se,"INFY",1234.33);
    Stock tcs(&se,"TCS",1100);
    Stock sbi(&se,"SBI",2312.33);

    se.register_observer(so1,"INFY");
    se.register_observer(so2,"INFY");
    se.register_observer(so1,"TCS");

    infy.set_price(1250.33);
    tcs.set_price(999.32);
    sbi.set_price(2300.00);

}


texts: Searching for a better implementation to EnumBase

texts:
In a former question on SO I described a problem with a construct called 'EnumBase'.

As I sad there, I am not involved when basic implementation happened. So I'm not sure why the thinks are a they are. I only know that the code was written in times of .Net 2 and 3.5. The derived classes are useed as DataSources in ASP.Net and WinForm GUIs and also for Switch-Statements.

Here the shorted main code of a typical derivates class:

public class Elements : EnumBase<int, Elements>
{
    public static readonly Elements Element1 = Create("Number 0", 0);
    public static readonly Elements Element2 = Create("Number 1", 1);

    // This empty constuctor is the solution of the previous question
    static Elements() {}

    private static Elements Create(string text, int value)
    {
        return new Elements() { text = text, value = value };
    }

    public static String GetElement(int id)
    {
        return BaseItemList.Single(v => v.Value == id).Text;
    }
}

And the EnumBase inself (the parameter dosentMatter in the empty constructor is no joke):

[Serializable()]
public class EnumBase<T, E> :  IEqualityComparer<E>
        where E : EnumBase<T, E>
{
    private static readonly List<E> list = new List<E>();
    protected string text;
    protected T value;

    protected static IList<E> BaseItemList
    {
        get
        {
            return list.Distinct(new EnumBase<T, E>(false)).ToList();
        }
    }

    protected EnumBase()
    {
        list.Add(this as E);
    }

    /// <summary>
    /// Constructor for distinct to avoid empty elements in the list
    /// </summary>
    private EnumBase(bool dosentMatter) {}

    public string Text
    {
        get { return text; }
    }

    public T Value
    {
        get { return value; }
    }

    #region IEqualityComparer<E> Member

    // ...

    #endregion
}

The switch statemaents are also not really nice (i'm not a friend of long switch an if-else-constructs, but bring polymorphism in the code is still a very very long way):

Switch
  Case Elements.Element1.value
  ...
  Case Elements.Element2.value
  ...

As you see, you have to use .value every time, which is a nice source for bugs if you forgot it :-/

All in all living with EnumBase leaves every time a strange feeling. There is a lot of code which is to write in every derived class again and again. And a lot of things can go wrong if you create or use an EnumBase derived-class. One the other hand it works but this can be 'the' argument.

From my point of view it would be nice if I can use more types form .Net-Framework instead of own programmed types. So the Question is, is there maybe something new in .net 4.0 (or even exists in .Net before 4.0) which make this implementation (in parts) obsolete?

I would be grateful for any hint.


texts: Caching large object in multithreading environment

texts:
I'm having to dabble with caching and multithreading (thread per request), and I am an absolute beginner in that area, so any help would be appreciated.

My project requirements are:

Cache one single large object that has ether interval refresh or refresh from user
Because retrieving object data is very time consuming make it thread-safe
When retrieving object data return "old data" until new data is available
Optimize it

public enum DbCachedObject {

INSTANCE;

private final CountDownLatch initLock = new CountDownLatch(1);
private final Object refreshLock = new Object();
private final AtomicReference<CachedObject> cachedInstance = new AtomicReference<CachedObject>();
private final AtomicLong lastUpdate = new AtomicLong();
private volatile boolean refreshing;
private long cachePeriodMs = 1000L;

public CachedObject get() {

    CachedObject o = cachedInstance.get();
    if (o == null || isCacheOutdated()) {
        updateCache();
        if (o == null) {
            awaitInit();
            o = cachedInstance.get();
        }
    }
    return o;
}

public void refresh() {
    updateCache();
}

private boolean isCacheOutdated() {
    return (System.currentTimeMillis() - lastUpdate.get() > cachePeriodMs);
}

private void updateCache() {

    synchronized (refreshLock) {
        // prevent users from refreshing while an update is already in progress
        if (refreshing) {
            return;
        }
        refreshing = true;
        // prevent other threads from calling this method again
        lastUpdate.set(System.currentTimeMillis());
    }
    new Thread() {
        @Override
        public void run() {
            try {
                cachedInstance.set(getFromDb());
                // set the 'real' last update time
                lastUpdate.set(System.currentTimeMillis());
                initLock.countDown();
            } finally {
                // make sure refreshing is set to false, even in case of error
                refreshing = false;
            }
        }
    }.start();
}

private boolean awaitInit() {

    boolean initialized = false;
    try {
        // assume cache-period is longer as the time it takes to create the cached object
        initialized = initLock.await(cachePeriodMs, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return initialized;
}

private CachedObject getFromDb() {
    // dummy call, no db is involved
    return new CachedObject();
}

public long getCachePeriodMs() {
    return cachePeriodMs;
}
}


texts: Find the kth largest element of an array

texts:
Find the kth largest element in an array of integers. You may assume
  that:

  1 <= k <=size(array).

Any comments? Is there a more efficient solution?

public int findKthLargest(int[] nums, int k) {
    int p = 0;
    int numElements = nums.length;
    // create priority queue where all the elements of nums will be stored
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

    // place all the elements of the array to this priority queue
    for (int n : nums){
        pq.add(n);
    }

    // extract the kth largest element
    while (numElements-k+1 > 0){
        p = pq.poll();
        k++;
    }

    return p;
}


texts:
I am looking for a better way to do a while cycle with the variable update.

The background is that I'm writing a StAX-line XML reader in JavaScript and want to implement a skipElement function. The function may only be called on the start tag and should skip everything until the closing end tag.

this.nextTag() skips to the next tag and returns Jsonix.XML.Input.START_ELEMENT or Jsonix.XML.Input.END_ELEMENT depending on whether it is a start or an end tag.
numberOfOpenTags holds the number of open tags, increased/decreased accordingly.
If we have a closing tag and numberOfOpenTags is 1, we're done.

skipElement : function() {
    if (this.eventType !== Jsonix.XML.Input.START_ELEMENT) {
        throw new Error("Parser must be on START_ELEMENT to skip element.");
    }
    // We have one open tag at the start
    var numberOfOpenTags = 1;
    // Skip to the next tag
    var et = this.nextTag();
    // If we have an END_ELEMENT and there is exactly one tag still open, we're done
    while (et !== Jsonix.XML.Input.END_ELEMENT || numberOfOpenTags !== 1)
    {
        if (et === Jsonix.XML.Input.START_ELEMENT)
        {
            numberOfOpenTags++;
        }
        else
        {
            numberOfOpenTags--;
        }
        et = this.nextTag();
    }
    return et;
}

I am looking for improvements. What I don't like:

this.nextTag() is called on two occasions.
Another check for et within the cycle: if (et === Jsonix.XML.Input.START_ELEMENT).
Too verbose if/else in the cycle.


texts:
I'm trying to figure out if I'm doing superclasses right.  Also, I welcome critique on Java structure/syntax etc.

Animal.java:

public class Animal{
    private static int counter = 0; // how many animals we have created (to demonstrate a static variable)
    private Boolean isWild = true; // is the animal wild?
    private Boolean hasSharpPointyTeeth = false; // does it have sharp, pointy teeth?!
    private int age = 0; // how old

    Animal(){ // default constructor
        this.isWild = isWild;
        this.hasSharpPointyTeeth = hasSharpPointyTeeth;
        this.age = age;

        counter++;
    }

    Animal(Boolean isWild, Boolean hasSharpPointyTeeth, int age){
        this.isWild = isWild;
        this.hasSharpPointyTeeth = hasSharpPointyTeeth;
        this.age = age;

        counter++;
    }

    //begin getters/setters
    public void setIsWild(Boolean isWild){
        this.isWild = isWild;
    }
    public void setAge(int age){
        this.age = age;
    }
    public void setHasSharpPointyTeeth(Boolean hasSharpPointyTeeth){
        this.hasSharpPointyTeeth = hasSharpPointyTeeth;
    }
    public Boolean getIsWild(){
        return isWild;
    }
    public Boolean getHasSharpPointyTeeth(){
        return hasSharpPointyTeeth;
    }
    public int getAge(){
        return age;
    }
    public static int getCounter(){
        return counter;
    }
    //end getters/setters

    public String speak(){
        return "Grrrr!";
    }

    public String toString(){
        String out =    speak() + "\n" +
                        "Age: " + getAge() + "\n" +
                        "Wild? " + getIsWild() + "\n" +
                        "Has Sharp Pointy Teeth? " + getHasSharpPointyTeeth() + "\n";
        return out;
    }
}

Dog.java

public class Dog extends Animal{
    private String name = "None";
    private String owner = "None";
    private String breed = "Unknown";
    private String sex = "Unknown";

    Dog(){
        super(false, false, 0); // call the constructor from the Animal class
        this.name = name;
        this.owner = owner;
        this.breed = breed;
        this.sex = sex;
    }

    Dog(Boolean isWild, Boolean hasSharpPointyTeeth, int age, String name, String owner, String breed, String sex){
        super(isWild, hasSharpPointyTeeth, age); // call the constructor from the Animal class
        this.name = name;
        this.owner = owner;
        this.breed = breed;
        this.sex = sex;
    }

    //begin getters/setters
    public void setName(String name){
        this.name = name;
    }
    public void setOwner(String owner){
        this.owner = owner;
    }
    public void setBreed(String breed){
        this.breed = breed;
    }
    public void setSex(String sex){
        this.sex = sex;
    }
    public String getName(){
        return name;
    }
    public String getOwner(){
        return owner;
    }
    public String getBreed(){
        return breed;
    }
    public String getSex(){
        return sex;
    }
    //end getters/setters

    @Override
    public String speak(){
        return "Woof!";
    }

    @Override
    public String toString(){
        String out =    super.toString() + // call the toString method of Animal, not the overridden one in Dog
                        "Name: " + getName() + "\n" +
                        "Breed: " + getBreed() + "\n" +
                        "Sex: " + getSex()+ "\n" +
                        "Owner: " + getOwner() + "\n";
        return out;
    }
}

Test.java

public class Test{
    public static void main(String[] args){
        Dog fluffy = new Dog(false,true,3,"Fluffy","Ted","Westie","Male");
        Animal rabbit = new Animal(true,true,8);

        System.out.println("We made " + Animal.getCounter() + " animals.  Here's their info:");
        System.out.println();
        System.out.println(fluffy);
        System.out.println(rabbit);
    }
}


texts: Refactoring code to implement clean code using repositories

texts:
I've been refactoring code today, try to implement a clean code setup using repositories. Is this on track? Can any improvements be made?

public class IndexModel : PageModel
{
    private readonly MembershipFormRepository _membershipFormRepository;
    private readonly IMembershipFormViewModelService _membershipFormViewModelService;

    public IndexModel(IMembershipFormViewModelService membershipFormViewModelService, MembershipFormRepository membershipFormRepository)
    {
        _membershipFormViewModelService = membershipFormViewModelService;
        _membershipFormRepository = membershipFormRepository;
    }

    [BindProperty]
    public MembershipFormViewModel MembershipFormModel { get; set; } = new MembershipFormViewModel();

    public async Task OnGetAsync()
    {
        MembershipFormModel = await _membershipFormViewModelService.GetViewModel();
    }

    public async Task<IActionResult> OnPostAddMemberAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        await _membershipFormRepository.AddMember(MembershipFormModel);

        return RedirectToPage("Index");
    }
}

MembershipFormViewModelService

public class MembershipFormViewModelService : IMembershipFormViewModelService
{
    private readonly MembershipContext _context;
    private readonly MembershipFormRepository _membershipFormRepository;

    public MembershipFormViewModelService(MembershipContext context, MembershipFormRepository membershipFormRepository)
    {
        _context = context;
        _membershipFormRepository = membershipFormRepository;
    }

    public async Task<MembershipFormViewModel> GetViewModel()
    {
        var viewModel = new MembershipFormViewModel()
            {
                Titles = await SetTitlesDropDown(),
            };

        return viewModel;
    }

    private async Task<IEnumerable<SelectListItem>> SetTitlesDropDown()
    {
        var titlesList = new List<SelectListItem>();

        var titles = await _membershipFormRepository.GetTitles();

        titlesList.AddRange(titles.Select(title => new SelectListItem() {
            Value = title.TitleId.ToString(),
            Text = title.Title
        }));

        return titlesList;
    }
}

IMembershipFormViewModelService

public interface IMembershipFormViewModelService
{
    Task<MembershipFormViewModel> GetViewModel();
}

MembershipFormRepository

public class MembershipFormRepository : IMembershipFormRepository
{
    private readonly MembershipContext _context;
    private readonly IMapper _mapper;

    public MembershipFormRepository(MembershipContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<IEnumerable<Title>> GetTitles()
    {
        return await _context.Title.ToListAsync();
    }

    public async Task AddMember(MembershipFormViewModel membershipForm)
    {
        var membership = new Membership();

        membership = _mapper.Map(membershipForm, membership);

        _context.Membership.Add(membership);

        await _context.SaveChangesAsync();
    }
}

IMembershipFormRepository

public interface IMembershipFormRepository
{
    Task<IEnumerable<Title>> GetTitles();
    Task AddMember(MembershipFormViewModel membershipForm);
}


texts: Sum of all paths between all pairs of nodes in a tree

texts:
I'm trying to solve a competitive programming problem. It basically gives a undirected graph (tree-like: no multiple paths between two nodes...) and asks for the sum of all possible paths between any pair of nodes in the graph  (each path must be counted only once, in other words, if you have already counted the path from A to B, you shouldn't count the path from B to A).
To solve this, I've tried to remove each edge (separating the tree in 2 components) and count the number of vertices in one of the components (the count of nodes of the second component can be derived from the count found in the first).
The total weight that a edge will contribute is: (the number of paths that pass by it = first_component_size * second_component_size) * (the weight of the edge).
Input description:

The input is composed of several instances (the number of instances is given on the first line of input).
The first input row of each instance contains an integer N (1 ≤ N ≤ 10000), representing the number of nodes. The nodes are enumerated from 1 to N.
Each one of the following N-1 rows contains three integers A, B and C (1 ≤ A, B ≤ N, 1 ≤ C ≤ 50), indicating that the edge that connects the nodes A and B has length C.

Output description:

For each instance print the sum of lenghts of the paths that connects all the pairs of nodes. The answer must be in MOD 1300031.

#include <cstdio>
#include <vector>
#include <utility>

const int MOD = 1300031;

using edge = std::pair<int, int>;
using adj_list   = std::vector<edge>;
using graph  = std::vector<adj_list> ;

struct myEdge {
    int from, to, weight;
};

std::vector<bool> visited;
int count_nodes_on_component(graph &g, int v) {
    int count_of_nodes = 1; //1 for itself
    adj_list &adj = g[v];
    for(auto &e : adj) {
        if(!visited[e.first]) {
            visited[e.first] = true;
            count_of_nodes += count_nodes_on_component(g, e.first);
            visited[e.first] = false;
        }
    }
    return count_of_nodes;
}

int main ( void ) {
    int test_cases;
    scanf("%d", &test_cases);
    while (test_cases--) {
        int total_nodes_in_graph;
        scanf("%d", &total_nodes_in_graph);

        visited.resize(total_nodes_in_graph + 1);

        graph g(total_nodes_in_graph + 1);
        std::vector<myEdge> vector_all_edges;
        for (int i = 1, node1, node2, weight; i < total_nodes_in_graph; ++i) {
            scanf("%d %d %d", &node1, &node2, &weight);
            g[node1].push_back( {node2, weight} );
            g[node2].push_back( {node1, weight} );
            vector_all_edges.push_back( {node1, node2, weight} );
        }

        long long total_sum = 0;
        for (auto &e : vector_all_edges) {
            visited[e.from] = visited[e.to] = true;
            int cc = count_nodes_on_component(g, e.to);
            total_sum = (total_sum + cc * (total_nodes_in_graph - cc) * e.weight) % MOD;
            visited[e.from] = visited[e.to] = false;
        }

        printf("%lld\n", total_sum);
    }
}

This code takes a lot of time with huge graphs. Is it possible to exploit something to make it run faster?


texts: Find number of inversions in a given array

texts:
Can you please give me a hint on how to improve performance of the following algorithm meant to find the number of inversions in a given array?

/* *
 * INPUT:
 * 1. t : number of test cases; t test cases follow
 * 2. n : number of elements to consider in each test case
 * 3. ar[i] : n numbers, elements of considered array
 * */

import java.util.*;

public class Inversions1 {

    public static long[] ar;
    public static long[] buff;

    // Merges arrays left[] and right[] into ar[], returns number of
    // inversions found in the process
    public static long merge(int low, int middle, int high) {
        int i = low;
        int j = middle + 1;
        int k = low;
        long count = 0;

        for(int l = low; l <= high; l++) {
                buff[l] = ar[l];
        }

        while (i <= middle && j <= high) {
            if (buff[i] <= buff[j]) {
                ar[k] = buff[i];
                i++;
            } else {
                ar[k] = buff[j];
                j++;
                count += middle-i+1;
            }
                k++;
        }

        while (i <= middle) {
            ar[k] = buff[i];
            i++; k++;
        }
        while(j <= high) {
            ar[k] = buff[j];
            j++; k++;
        }
        return count;
    }

    // Traditional merge sort on arr[], returns number of inversions
    public static long invCount(int low, int high) {
        if(low < high) {

            int middle = low + (high - low)/2;

            return invCount(low, middle) + invCount(middle+1,high) + merge(low, middle, high);
        }
        return 0;
    }

    public static void main (String args[]) {
        int t, n;
        Scanner sc = new Scanner(System.in);
        t = sc.nextInt();
        while(t-- > 0) {
            n = sc.nextInt();
            ar = new long[n];
            buff = new long[n];
            for(int i = 0; i < n; i++) {
                ar[i] = sc.nextLong();
            }
            System.out.println(invCount(0,n-1));
        }
    }
}


texts:
I am new to Python programing language. I have created the codes, based on this solution.

I prepared two simple programs:

import simplekml

List2 = [ [ 'Placemark','old file', 51.500152, -0.126236 ] ] # description, lat, lon
List3 = [ [ 'New placemark','new file', 51.600152, -0.136236 ] ]

kml = simplekml.Kml()
for row in List2:
    kml.newpoint(name=row[0], description=row[1],
    coords=[(row[3], row[2])])  # lon, lat, optional height
for row in List3:
    kml.newpoint(name=row[0], description=row[1],
    coords=[(row[3], row[2])])

kml.save("test2.kml")

and from another file here:

import simplekml
kml = simplekml.Kml()
kml.newpoint(name="Kirstenbosch", description="Description", coords=[(18.432314,-33.988862)])  # lon, lat,optional height
kml.newpoint(name="Kirstenbosch2", description="<b> Botanic garden </b> in South Africa", coords=
 [(18.532314,-33.788862)])
kml.save("output/botanicalgarden2.kml")

I know that this code (simplekml tool) can be used for the bulk .kml data, as it was mentioned here.

Could you tell me how to write this code not repeatedly, as I did? I would like to have a multitude of place mark locations within one list/new point, when possible.


texts: Default initialization of items using Scrapy

texts:
I am writing a scraper, using Scrapy, in which I need to populate items with default values at first.

Could my method be improved?

 def sp_offer_page(self, response):
            item = MallCrawlerItem()
            for key, value in self.get_default_item_dict().iteritems():
                item[key] = value
            item['is_coupon'] = 1
            item['mall'] = 'abc'
            # some other logic
            yield item

    def get_default_item_dict(self):     # populate item with Default Values
        return {'mall': 'null', 'store': 'null', 'bonus': 'null',
                'per_action': 0, 'more_than': 0,
                'up_to': 0, 'deal_url': 'null', 'category': 'null', 'expiration': 'null', 'discount': 'null',
                'is_coupon': 0, 'code': 'null'}


texts: Reverse words in a string without affecting space

texts:
I came across a problem that needs to reverse each word in a string without affecting space in it. For example, if a string has two spaces between the word, the answer needs to have space between two words. These are example test cases, I have been given
/This is a sentence/
/ This  is a Sentence /
My approach is:

string oreverse(string s){
    for(int i=0,n=s.size();i<n/2;++i)
        swap(s[i],s[n-i-1]);
    return s;
}
string reverseWords(string s) {
    string re;
    for(auto i=0;i<s.size();){
        if(s[i]!=' '||s[i]=='/0'){
            int _t = s.find_first_of(' ',i);
            re+=oreverse(s.substr(i,_t-i));
            i=_t;
        }else{
            re+=s[i];
            i++;
        }
    }
    return re;
}

I like to know, is there any further optimisation can be done or any other approaches with increased efficiency.


texts: Requesting information about people from a web API

texts:
I'm requesting from a web API information about 20,000 people that I need to update continuously at lightning speed (the web server doesn't throttle the number of requests). I can request an update on 20 people at a time (it's the maximum allowed per request) so i loop the List of people and ask the server info on groups of 20 just like this:

Public Sub GetInformation()
    Do
        For Each Person In ListOfPerson
            RequestList.Add Person
            If RequestList.Count = 20 Then RequestToWebServer(RequestList): RequestList.Clear
        Next
    Loop
End Sub

Public RequestToWebServer(ResquestList as List(Of Person))
    'Code to ask the web server the info'
    'Then code to process the response'
    For Each Person In ResquestList
        If Person.Status = "Old" then RequestServerForMoreDetails
    Next
End Sub

This could be very slow because a request could stall and everything just stops waiting for that request to be completed or timed out. So my solution is to fire a thread for each request:

Public Sub GetInformation()
    Do
        For Each Person In ListOfPerson
            RequestList.Add Person
            If RequestList.Count = 20 Then ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf RequestToWebServer), RequestList) : RequestList.Clear
        Next
    Loop
End Sub

I don't know if this is the right way to tackle the problem, worse, I have a second problem. If a Person has a status of "Old" (status is updated when i ask the web API for information) then I have to make an extra web request and I don't want to slow down the process of the others in the list, so I fire them in a thread also like this:

Public RequestToWebServer(ResquestList as List(Of Person))
    'Code to ask the web server the info'
    For Each Person In ResquestList
        If Person.Status = "Old" then ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf RequestServerForMoreDetails), Person)
    Next
End Sub

This creates a lot of threads, and from what I heard it's usually not a good practice. Is there a better way to do this or am I in the right track?


texts: Comparison of incoming error strings to known set and transformation into 3rd string

texts:
I have a function where I am comparing an error string returned from a web service to several lists of known strings, and then based on which list the error is a member of, returning from the function a more 'user-friendly' error to display.

I am hoping someone could offer some tips on making it shorter and more efficient.  I think I'm missing some obvious shortcuts, but I am not sure what.

def interpret_error(error):
    display_error_1 = 'User error 1'

    display_error_2 = 'User error 2'

    display_error_3 = 'User error 3'

    error_list_1= ["Failure: 'mean_va' is not in list",
                   "Failure: No JSON object could be decoded",
                   "Failure: Expecting ':' delimiter: line 1 column 14410098 (char 14410097)",
                   "Failure: cannot concatenate 'str' and 'ContentDecodingError' objects",
                   "Failure: Unknown error",
                   "Failure: Error returned by EPA WATERS web service: No Results Returned"]

    error_list_2 = ["Failure: Error returned by EPA WATERS web service: Flowline comid 4505568 at measure 79.99388 not found in NHDPlus stream network",
                    "Failure: Error returned by EPA WATERS web service: No Catchments match navigation results"]

    error_list_3 = ["Failure: Error returned by EPA WATERS web service: Start permid must have a hydroseq greater than the hydroseq for stop permid",
                    "Failure: Error returned by EPA WATERS web service: Start measure must be greater than stop measure when navigating a single reach"]

    match1 = 0.0
    match2 = 0.0
    match3 = 0.0
    temp_match = 0.0

    for internal_error in error_list_1:
        temp_match = fuzz.token_set_ratio(error,internal_error)
        match1 = max(temp_match, match1)

    temp_match = 0.0

    for internal_error in error_list_2:
        temp_match = fuzz.token_set_ratio(error,internal_error)
        match2 = max(temp_match, match2)

    temp_match = 0.0

    for internal_error in error_list_3:
        temp_match = fuzz.token_set_ratio(error,internal_error)
        match3 = max(temp_match, match3)

    if match1 > match2 and match1 > match3:
        return display_error_1
    elif match2 > match1 and match2 > match3:
        return display_error_2
    elif match3 > match1 and match3 > match2:
        return display_error_3
    else:
        return "Error of unknown cause"


texts:
The website I'm working on is essentially project-management software. Each project has a code (alphanumeric lowercase, with hyphens). The URL must include the codes and treat them as directories.

website.com/p/<code>/<page> => website.com/p/<page>?code=<code>

Each project will have files associated with it. All file downloads are handled through a single script called 'files.php'. The file name itself must be in the URL. Files.php can also index all the files, only when $_GET['file'] is empty.

website.com/p/<code>/files/<filename> => files.php?code=<code>&file=<filename>

Another requirement is that all project codes must be treated as directories. And the files must also serve as a directory. Attempting to otherwise will cause redirection.

website.com/p/<code> (redirects to) website.com/p/<code>/
website.com/p/<code>/files (redirects to) website.com/<code>/files/

Below is my solution, however it feels sloppy. Any advice?

<Directory ${DOC_ROOT}>
        RewriteEngine On
        RewriteBase /
        RewriteCond  %{QUERY_STRING}  !code
        RewriteRule ^p/([a-z0-9\-]+)/files$ p/$1/files/ [R,L]
        RewriteCond  %{QUERY_STRING}  !code
        RewriteRule ^p/([a-z0-9\-]+)/files/(.*)?$ p/files.php?code=$1&name=$2&%{QUERY_STRING} [L]

        RewriteCond  %{QUERY_STRING}  !code
        RewriteRule ^p/([a-z0-9\-]+)$ p/$1/ [R,L]
        RewriteCond  %{QUERY_STRING}  !code
        RewriteRule ^p/([a-z0-9\-]+)/(.*)$ p/$2?code=$1&%{QUERY_STRING} [L]
</Directory>