texts:
https://leetcode.com/problems/insert-delete-getrandom-o1/
please comment on performance

Implement the RandomizedSet class:
bool insert(int val) Inserts an item val into the set if not present.
Returns true if the item was not present, false otherwise. bool
remove(int val) Removes an item val from the set if present. Returns
true if the item was present, false otherwise. int getRandom() Returns
a random element from the current set of elements (it's guaranteed
that at least one element exists when this method is called). Each
element must have the same probability of being returned. Follow up:
Could you implement the functions of the class with each function
works in average O(1) time?
Example 1:
Input ["RandomizedSet", "insert", "remove", "insert", "getRandom",
"remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []]
Output [null, true, false, true, 2, true, false, 2]
Explanation RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1
was inserted successfully. randomizedSet.remove(2); // Returns false
as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2
to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2
randomly. randomizedSet.remove(1); // Removes 1 from the set, returns
true. Set now contains [2]. randomizedSet.insert(2); // 2 was already
in the set, so return false. randomizedSet.getRandom(); // Since 2 is
the only number in the set, getRandom() will always return 2.
Constraints:
\$-2^{31} <= val <= 2^{31} - 1\$. At most \$10^5\$ calls will be made to insert, remove, and getRandom. There will be at least one element in the data
structure when getRandom is called.

public class RandomizedSet {

     private HashSet<int> _set;
        /** Initialize your data structure here. */
        public RandomizedSet()
        {
            _set = new HashSet<int>();
        }

        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public bool Insert(int val)
        {
            if (_set.Contains(val))
            {
                return false;
            }
            _set.Add(val);
            return true;
        }

        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public bool Remove(int val)
        {
            if (_set.Contains(val))
            {
                _set.Remove(val);
                return true;
            }
            return false;
        }

        /** Get a random element from the set. */
        public int GetRandom()
        {
            Random rand = new Random();
            int key = rand.Next(_set.Count);
            return _set.ElementAt(key);
        }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * bool param_1 = obj.Insert(val);
 * bool param_2 = obj.Remove(val);
 * int param_3 = obj.GetRandom();
 */


texts:
def triangularNumber(n):
    if(n == 1):
        return 1
    else:
        return triangularNumbers(n-1)+n

works great to find the nth triangular number up to 996...
I get some error in the recursion after 996. But can tell what it is because it just keeps running through the loop. Anyone see the error?


texts:
My code looks ugly. What can you recommend? I already know about Enum; maybe it's a good variant for this situation.  Anything else?

   private void writerContent(Integer firstRow, List<Record> records){
        int firstColumn=0;
        int lastColumn=7;
        XSSFSheet sheet = workBook.getSheetAt(0);
        for (int lineId=firstRow;lineId<records.size();lineId++)   {
            Row row = sheet.getRow(lineId);
            for (int columnId=firstColumn;columnId<lastColumn;columnId++){
                switch (columnId){
                    case 0:  row.createCell(columnId).setCellValue(records.get(lineId).getNumber()); break;
                    case 1:  row.createCell(columnId).setCellValue(records.get(lineId).getName());  break;
                    case 2:  row.createCell(columnId).setCellValue(records.get(lineId).getCode());   break;
                    case 3:  row.createCell(columnId).setCellValue(records.get(lineId).getCount());  break;
                    case 4:  row.createCell(columnId).setCellValue(records.get(lineId).getSimultaneouslyProcessedProducts());  break;
                    case 5:  row.createCell(columnId).setCellValue(records.get(lineId).isSimultaneousProcessing());   break;
                    case 6:  row.createCell(columnId).setCellValue(records.get(lineId).getInterchangeability()); break;
                }
            }
        }

    }


texts:
I have created a class intended to average the previous few data points submitted. It is able to change in size and has a feature to bypass the average without affecting the data contained therein. Are there any improvements I could make, or any exceptions thrown in certain situations that I haven't thought of?

public class RollingAverage {

    private double[] data;
    private boolean bypass = false;

    public RollingAverage(int size) {
        if (size == 1) {
            bypass = true;
        }

        data = new double[size];
        Arrays.fill(data, Integer.MIN_VALUE);
    }

    /**
     * Adds a data point to the rolling average
     *
     * @param newData
     * @return the new average
     */
    public double addData(double newData) {
        if (bypass) {
            return newData;
        }
        boolean full = true;
        for (double point : data) {
            if (point == Integer.MIN_VALUE) {
                full = false;
                break;
            }
        }

        if (full) {
            int j = 0;
            while (j < data.length - 1) {
                data[j++] = data[j];
            }
            data[0] = newData;

            int sum = 0;
            for (double point : data) {
                sum += point;
            }
            return sum / data.length;
        } else {
            double sum = newData;
            int j = 0;
            while (data[j] != Integer.MIN_VALUE) {
                sum += data[j++];
            }
            data[j] = newData;
            return sum / (j + 1);
        }
    }

    public void changeSize(int size) {
        if (size == data.length) {
            return;
        }

        if (size == 1) {
            bypass = true;
        }

        double[] oldData = data;
        data = new double[size];

        for (int i = 0; i < size; i++) {
            if (i < oldData.length) {
                data[i] = oldData[i];
            } else {
                data[i] = Integer.MIN_VALUE;
            }
        }
    }

    public void setBypass(boolean bypass) {
        this.bypass = bypass;
    }

    public void clear() {
        Arrays.fill(data, Integer.MIN_VALUE);
    }

    public int getAverage() {
        return (int) getAverageDouble();
    }

    public double getAverageDouble() {
        int sum = 0;
        int count = 0;
        for (double point : data) {
            if (point != Integer.MIN_VALUE) {
                sum += point;
                count++;
            } else {
                break;
            }
        }
        return sum / count;
    }
}


texts: React/Redux/Node/Express crud application with a React class component

texts:
https://try.gitea.io/nadal/repository

Used this in a coding challenge after a job interview. I didn't get chosen, but I was wondering if it was because of the code quality in the project.

import React, { Component } from 'react';
import * as ExpenseActions from '../actions/ExpenseActions';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import ExpenseTable from '../components/ExpenseTable';

export class ExpenseContainer extends Component {

    constructor(props) {
        super(props)
    }

    /**
     * Triggers the create action
     * @method
     *
     */
    createExpense = (expense) => {
        this.props.actions.CreateExpense(expense)
    }

    /**
     * Triggers the start edit action
     * @method
     *
     */
    startEditing = (id) => {
        this.props.actions.StartEditing(id);
    }

    /**
     * Triggers the cancel action
     * @method
     *
     */
    cancelEditing = (id) => {
        this.props.actions.CancelEditing(id);
    }

    /**
     * Triggers the edit action
     * @method
     *
     */
    editExpense = (expense) => {
        this.props.actions.UpdateExpense(expense);
    }

    /**
     * Triggers the delete action
     * @method
     *
     */
    deleteExpense = (expense) => {
        this.props.actions.DeleteExpense(expense);
    }

    render() {
        return (
            <div className="expense-container">
                <ExpenseTable
                    subTotal={this.props.expenses.subTotal}
                    total={this.props.expenses.total}
                    expenses={this.props.expenses.expenses}
                    createExpense={this.createExpense}
                    startEditing={this.startEditing}
                    cancelEditing={this.cancelEditing}
                    editExpense={this.editExpense}
                    deleteExpense = {this.deleteExpense}
                />
            </div>
        );
    }
}

ExpenseContainer.propTypes = {
    actions: PropTypes.object.isRequired,
    expenses: PropTypes.object.isRequired
}

function mapStateToProps(state, ownProps) {
    return {
        expenses: state.expenses
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(ExpenseActions, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ExpenseContainer);

Aside the fact, I could have used a hook called useSelector and useDispatch. I am not sure how I could have made it better. The backend side, I am not too sure if there's anything wrong with it, because I am not too familiar with Node/Express. Try to be as nitpicky as possible.


texts:
I have a simple brute-force search function:

function run_query(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int}
    current_best = Inf
    loc = -1
    q_len = length(query)

    for d_i in 1:(length(data) - q_len)

        dist = search_f(data[d_i:d_i+q_len-1], query)
        if dist < current_best
            current_best = dist
            loc = d_i
        end
    end

    return current_best, loc
end

I have an alternative version of the function which also returns the maximum distance found while searching to data:

function run_query_max(search_data::Vector{Float64}, query::Vector{Float64}, search_f::Function)::Tuple{Float64, Int, Float64}
    current_best = Inf
    loc = -1
    q_len = length(query)
    max_dist = 0.

    for d_i in 1:(length(data) - q_len)

        dist = search_f(data[d_i:d_i+q_len-1], query)

        if dist > max_dist
            max_dist = dist
        end

        if dist < current_best
            current_best = dist
            loc = d_i
        end
    end

    return current_best, loc, max_dist
end

This can be tested as follows:

function simple_dist(data::Vector{Float64}, query::Vector{Float64})::Float64
    return sum((data .- query) .^ 2)
end

data = [0., 0., 1., 2.,
        3., 1.1, 3., 3.,
        1., 0., 0., 1.,
        0., 0., 1., 4.5,
        2., 1., 0., 0.]

query = [1., 2., 3., 1.]
val, idx = run_query(data, query, simple_dist)
@assert (idx == 3)
@assert isapprox(val, 0.01, atol=0.001)

val, idx, max_dist = run_query_max(data, query, simple_dist)
@assert (idx == 3)
@assert isapprox(val, 0.01, atol=0.001)
@assert isapprox(max_dist, 21.25, atol=0.001)

This pattern of:

Basic search function
Add keeping track of maximum distance in search function

Occurs in multiple places in my code. What is a reasonable way to refactor it out?


texts: Javascript check if server time is greater than or less than 9am EST

texts:
I offer same day shipping if the user places an order before 9AM ET. If they place the order after 9AM, same day shipping is unavailable.
My server is using UTC time so I need to check if the time is greater than or less than 9AM ET regardless of the time where the user is located.
Not being an expert with JS, I cobbled together this code.
var d = new Date();
var e = d.getHours().toLocaleString('en-US', { timeZone: 'America/New_York' });
var f = '';

if(e >= 9) {
  f = 'shipping unavailable';
}
else {
  f = 'shipping available';
}

I am getting the correct result after 9AM ET on my computer but I am concerned that same day shipping will be offered after 9AM ET.


texts:
Below is a case class and a companion object with a method putRecord which adds a new row into Hbase using Put API. This code has some repetitive parts. Is there a way to abstract away the repetitive code

case class HbaseRow(_id: Option[String], field1: Option[Array[String]], field2: Option[Array[String]], field3: Option[String], field4: Option[Long])

object HbaseRow {
    def putRecord(row: HbaseRow): Put = {
        val put = new Put(Bytes.toBytes(row._id.get))

        def addColumn[T](columnName: String,value: T): Put = {
          val columnFamily:Array[Byte] = Bytes.toBytes("cf")
          val col: Array[Byte] = Bytes.toBytes(columnName)
          // Repetative, almost same method call but for different types
          value match {
            case v: String => put.addColumn(columnFamily, col,Bytes.toBytes(v))
            case v: Long => put.addColumn(columnFamily, col,Bytes.toBytes(v))
            case v: Boolean => put.addColumn(columnFamily, col,Bytes.toBytes(v))
            case v: Array[String] => put.addColumn(columnFamily, col,Bytes.toBytes(v.mkString(",")))
          }
        }

        //Repetitive will be tedious as columns increase.
        row.field1.map(value => addColumn[Array[String]]("f1",value.mkString(",")))
        row.field2.map(value => addColumn[Array[String]]("f2",value.mkString(",")))
        row.field3.map(value => addColumn[String]("f3",value))
        row.field4.map(value => addColumn[Long]("f4",value))

        put
    }
}


texts:
A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m > 0\$ or \$(m, 0]\$ when \$m < 0\$. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it.

use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;

struct Mod<T: Modulo<T>> {
    modulo: T,
    i: T,
}

trait Modulo<T> {
    fn modulo(&self, n: T) -> T;
}

impl Modulo<i32> for i32 {
    fn modulo(&self, n: i32) -> i32 {
        let mut x: i32 = *self;
        while x.signum() != n.signum() {
            x += n;
        }
        x % n
    }
}

impl Mod<i32> {
    fn new(modulo: i32, i: i32) -> Mod<i32> {
        let n = i.modulo(modulo);
        Mod {
            modulo: modulo,
            i: n,
        }
    }
}

impl Add for Mod<i32> {
    type Output = Mod<i32>;
    fn add(self, other: Mod<i32>) -> Mod<i32> {
        Mod::new(self.modulo, self.i + other.i)
    }
}

impl Sub for Mod<i32> {
    type Output = Mod<i32>;
    fn sub(self, other: Mod<i32>) -> Mod<i32> {
        Mod::new(self.modulo, self.i - other.i)
    }
}

impl Mul for Mod<i32> {
    type Output = Mod<i32>;
    fn mul(self, other: Mod<i32>) -> Mod<i32> {
        Mod::new(self.modulo, self.i * other.i)
    }
}

fn main() {
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x + y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x - y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x * y).i);
}

All suggestions are welcome, but I am particularly interested in:

Extending to u32, u16, u8, i16, i8 etc without too much code duplication.
Increasing performance.


texts: Injecting the Repository into the business layer

texts:
I am developing an application using Asp.NET core with MVC framework. I would like to ask your opinion about whether I inject my repository in a good way into my business layer.

First of all, lets see my IRepository interface:

public interface IRepository<T>
{
    IEnumerable<T> GetAll();
    T Get(long id);
    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
}

Lets see one of my service class:

public interface IContainersGridService
{
    IList<ContainerGridViewModel> GetGridViewModels(string searchText);
}

public class ContainersGridService : IContainersGridService
{
    private readonly IRepository<Container> _containersRepository; //TODO: when write test, test when throws same db exception
    private readonly IContainerGridViewModelsGetter _containerGridViewModelsGetter;

    public ContainersGridService(IRepository<Container> containersRepository, IContainerGridViewModelsGetter containerGridViewModelsGetter)
    {
        _containersRepository = containersRepository;
        _containerGridViewModelsGetter = containerGridViewModelsGetter;
    }

    public IList<ContainerGridViewModel> GetGridViewModels(string searchText)
    {
        var containers = _containersRepository.GetAll();
        return _containerGridViewModelsGetter.Get(containers, searchText);
    }
}

As you can see I have an IRepository interface with the basic CRUD method signatures. I also have a ContainersGridService which is responsible to get some containers (domain: dump containers) from the database.

Furthermore, I have an ContainersGridService injected which is responsible for mapping and sorting the data coming from the database:

public interface IContainerGridViewModelsGetter
{
    IList<ContainerGridViewModel> Get(IEnumerable<Container> containers, string searchText);
}

public class ContainerGridViewModelsGetter : IContainerGridViewModelsGetter
{
    private readonly IContainerMappingService<ContainerGridViewModel> _containerMappingService;
    private readonly IContainersGridGlobalSearcher _containersGridGlobalSearcher;

    public ContainerGridViewModelsGetter(IContainerMappingService<ContainerGridViewModel> containerContainerMappingService, IContainersGridGlobalSearcher containersGridGlobalSearcher)
    {
        _containerMappingService = containerContainerMappingService;
        _containersGridGlobalSearcher = containersGridGlobalSearcher;
    }

    public IList<ContainerGridViewModel> Get(IEnumerable<Container> containers, string searchText)
    {
        var containerGridViewModels = GetContainerGridViewModels(GetSortedContainers(containers));

        return _containersGridGlobalSearcher.Search(containerGridViewModels,searchText);
    }

    private List<ContainerGridViewModel> GetContainerGridViewModels(IEnumerable<Container> sortedContainers)
    {
        return sortedContainers
            .Select(c => _containerMappingService.Map(c))
            .ToList();
    }

    private IEnumerable<Container> GetSortedContainers(IEnumerable<Container> containers)
    {
        return containers.OrderBy(c => c.DesiredTakeUpDate);
    }
}

As you can see, I have injected two additional (one mapping and one searching) logic class here. At this point I am wondering if it is the best way to implement my business layer like this, with the repository.

First I wanted to inject my repository into the ContainerGridViewModelsGetter but later I realized that it is (maybe) better if I separate the my repository from this logic class and I only pass an IList to my ContainerGridViewModelsGetter.Get(...) method. Using this way, I separated the data from this class, so the corresponding tests are also cleaner and clearer.

My questions are the following: Is it a good way to inject my repository to my service layer? Or maybe I would have injected the IRepository into my ContainerGridViewModelsGetter? Maybe do you have any other remarks regarding my code generally?


texts:
Is this a good way to solve the quiz "Chessboard" from http://eloquentjavascript.net/02_program_structure.html ?

  Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.

  When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

This is my code:

 size = 10;

    grid = ""

    for (var i = 1; i <= size; i++) {
      for (var j = 1; j <= size; j++) {
        if (i % 2 === 0) {
         grid+= "# "
        } else {
         grid+= " #"
        }
      }
      grid+= "\n"
    }

    console.log(grid)


texts:
I have created a data structure to handle some audio data I am generating (simple sine wave right now). It had some errors in it due to some misunderstanding of my ancient C knowledge that has been fixed by my cousin. I am wondering if there may yet still be more issues.

I have considered turning this into a C++ class, but because I don't have enough experience with C++ I would likely turn it into a huge memory leak waiting to happen. This is really being used with Objective C on the iPad - but nothing prevents this from being used elsewhere.

All of the functions are publicly accessible, and should be fairly obvious how they should be used. But essentially you alloc the structure, push and pop (which make it sound like a stack but it very much is not), and finally release the structure. You will notice it is in a C Object Oriented Design - I did that intentionally to make things easier to remember.

I did not use a circular buffer because I hadn't reached the ballmer peak yet when I was writing this and I couldn't quite get the right form. The queue basically works on the principle that you append on the end, and take data off the top - and the stuff left is moved up to the top.

I was looking to use some vector acceleration functions from this at some point. It presently is being used in threaded code behind locks with NSCondition.

To see how this is being used now, the structure is used in this .m file and is part of this project.

// from the header file - just converted to a typedef, untested...
typedef struct {
    float *buffer;
    float *end;
    size_t max_length;
} FIFO;

#include "FIFO.h"

FIFO *FIFO_alloc(size_t length) {
    FIFO *restrict ptr = NULL;

    ptr = (FIFO*)calloc(1, sizeof(FIFO));
    if (ptr == NULL) {
        return NULL;
    }

    ptr->buffer = (float*)calloc(length, sizeof(float));
    if (ptr->buffer == NULL) {
        free(ptr);
        return NULL;
    }

    ptr->end = ptr->buffer;
    ptr->max_length = length;

    return ptr;
}

void FIFO_release(FIFO *fifo) {
    if (fifo) {
        free(fifo->buffer);
        free(fifo);
    }
}

bool FIFO_push(FIFO *restrict fifo, const float *restrict data, size_t count) {
    if (!fifo || !data || count == 0) return false;

    // test for the length available
    if (fifo->max_length - (int)(fifo->end - fifo->buffer) < count) {
        return false;
    }

    memcpy(fifo->end, data, count*sizeof(float));
    fifo->end += count;

    return true;
}

bool FIFO_pop(FIFO *restrict fifo, float *restrict data, size_t count) {
    if (!fifo || !data) return false;
    if (count == 0 || FIFO_size(fifo) < count) return false;

    // move count items from the buffer
    memcpy(data, fifo->buffer, count*sizeof(float));
    // move empty space back to the beginning
    memmove(fifo->buffer, fifo->buffer + count, (fifo->end - fifo->buffer - count) * sizeof(float));

    // reposition end pointer
    fifo->end -= count;

    return true;
}

size_t FIFO_size(const FIFO *fifo) {
    if (fifo) {
        return (size_t)(fifo->end - fifo->buffer);
    }

    return 0;
}

size_t FIFO_maxsize(const FIFO *fifo) {
    if (fifo) {
        return fifo->max_length;
    }

    return 0;
}


texts:
I was wondering if my code is safe for sql injection.
This code just checks if the username exists in my db or not.

$username = $_POST['username'];
$stmt = mysqli_stmt_init($con);
$query = "SELECT username FROM users WHERE username = ?" ;
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $user['username']);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_fetch($stmt)){
    if ($user['username'] === $username){
    echo $username, ' exists';
    }
}
elseif (!mysqli_stmt_fetch($stmt)){
    echo $username, ' doesn\'t exists';
}


texts: is there a better way than replace to write this function?

texts:
I am doing my homework and i have done this? Is there any other better way to do this?

def write_log(name, total):
    # change user input with shape names
    name = name.replace('1', 'triangle')
    name = name.replace('2', 'square')
    name = name.replace('3', 'rectangle')
    name = name.replace('4', 'pentagon')
    name = name.replace('5', 'hexagon')
    name = name.replace('6', 'octagon')
    name = name.replace('7', 'circle')

    total = int(total)

    logfile = open("text.txt", "a")

    if (total == 1):
       towrite = ('%i %s \n'
                  % (total, name))

    elif (total >= 2 and total <= 5):
       name += 's' # add s to name to make it plural
       towrite = ('%i %s \n'
                  % (total, name))
    else:
       towrite = ''
    try:
       logfile.write(towrite)
    finally:
       logfile.close()
    return


texts: Cython functions for generating NumPy date ranges

texts:
I have rewritten my python code in cython in order to speed up it quite a bit. However after checking the code in jupyter it seems that part of it is still compiled as python code, therefore its not being sped up enough.

My function is pretty basic, it gets start date, end date and creates array of additional dates based on that and some other conditions.

The thing is I’m a bit clueless how could I change the highlighted yellow part of code of the date_range_np function as seen on the attached imaged. Because I’m already using numpy arrays so I thought it would be compiled as cython code. There is also one loop that I think is slowing down the function but so far I wasn’t able to come up with any replacement that sginificatly sped up the function. Actually speed is very important as those functions are executed thousands of times.
Any ideas how could I refactor it to speed it up?

Here is my code:

%%cython -a
import numpy as np
cimport numpy as np
from datetime import datetime

cpdef np.int64_t get_days(np.int64_t year, np.int64_t month):
    cdef np.ndarray months=np.array([31,28,31,30,31,30,31,31,30,31,30,31])
    if month==2:
        if (year%4==0 and year%100!=0) or (year%400==0):
            return 29
    return months[month-1]

cpdef np.ndarray[np.int64_t] date_range_np(np.int64_t start, np.int64_t end, char* freq):
    cdef np.ndarray res
    cdef np.int64_t m_start
    cdef np.int64_t m_end
    if freq.decode("utf-8")[len(freq)-1] == "M":
        m_start = np.int64(start).astype('M8[D]').astype('M8[M]').view("int64")
        m_end = np.int64(end).astype('M8[D]').astype('M8[M]').view("int64")
        res = np.arange(m_start, m_end-2, np.int64(freq[:(len(freq)-1)])).view("M8[M]").astype("M8[D]").view("int64")
        return np.array([np.min([x+datetime.fromtimestamp(start*24*60*60).day-1, x+get_days(datetime.fromtimestamp(start*24*60*60).year,datetime.fromtimestamp(start*24*60*60).month)]) for x in res])
    elif freq.decode("utf-8")[len(freq)-1] == "D":
        return np.arange(start, end-2, np.int64(freq[:(len(freq)-1)]))

cpdef np.ndarray[np.int64_t] loanDates(np.int64_t startDate,np.int64_t endDate,np.int64_t freq):
    # if frequency indicates repayment every n months
    if int(12 / freq) == 12 / freq:
        # Generate date range and add offset depending on starting day
        #print(date_range_np(start=startDate, end=endDate, freq=(str(-int(12 / freq)) + "M").encode("utf8")))
        ts = date_range_np(start=startDate, end=endDate, freq=(str(-int(12 / freq)) + "M").encode("utf8"))
    else:
        ts = date_range_np(start=startDate, end=endDate, freq=(str(-int(365 / freq)) + "D").enocode("utf8"))
    #print(ts)

    if ts.shape[0] == 0:
        return np.array([])
    elif ts.shape[0] >= 1 and ts[0] > startDate:
        ts = np.delete(arr=ts, obj=0)
    if ts[ts.shape[0]-1] < endDate:
        ts = np.delete(arr=ts, obj=-1)
    if ts[0] != startDate:
        ts = np.insert(ts,0,startDate)

    # If no dates generated (start date>end date)
    ts = ts

    # If last date generated is not end date add it
    return ts.astype('int64')

And the function highlighted:

If you want to test the functions you can try:

%timeit date_range_np(20809,17986, b"-1M")

I get about 1ms for that function.


texts: Syllabification function for Turkish words

texts:
I wrote an NLP script for processing Turkish language. Yesterday I added syllabication but I wonder if it could be done better. It is kinda hard-coded, so I would like to know if I can improve it.

Here is the syllabication part.

def syllabicate(self, word):
    """
    :param word: The word to be syllabicated
    :return: The syllabicated list that contains syllabs
    """
    word = word.lower()
    syllabs = []
    syllab = ""
    keep_index = 0
    last_was_vowel = False
    next_is_vowel = False

    for let_ind in range(len(word)):
        if let_ind != len(word) - 1:
            if word[let_ind + 1] in self.vowels:
                next_is_vowel = True
            else:
                next_is_vowel = False
        else:
            syllab = word[keep_index:]
            syllabs.append(syllab)
            break

        if next_is_vowel and not last_was_vowel and syllab:
            syllabs.append(syllab)
            syllab = ""
            keep_index = let_ind

        elif next_is_vowel and word[let_ind] not in self.vowels and syllab:
            syllabs.append(syllab)
            syllab = ""
            keep_index = let_ind

        syllab += word[let_ind]

        if word[let_ind] in self.vowels:
            last_was_vowel = True
        else:
            last_was_vowel = False

    return syllabs


texts: Defining application flow in ASP.NET MVC5

texts:
Currently I am assigned to a project which has a standard view-flow, yet this flow is determined by whether settings are set to either true or false.

So, for example, let the standard flow be View1 > View2 > View3. When the customer has no need for View2, the application should be adjusting this to View1 > View3.

It is quite important to note that these Views do not require any information from eachother and are in no way bound to eachother.

I've thought of some ways to implement this, but I can't really decide which one to use and which one is better or whether there are better options. Consider this Settings object;

public class Settings
{
    public bool HasView1 { get; set; }
    public bool HasView2 { get; set; }
    public bool HasView3 { get; set; }
}

Implementation 1: Controller controls

This is the first implementation I came up with;

public class ViewController : Controller
{
    public ActionResult View1()
    {
        if(!Settings.HasView1)
            return View2();
        else
            return View("View1");
    }

    public ActionResult View2()
    {
        if(!Settings.HasView2)
            return View3();
        else
            return View("View2");
    }

    public ActionResult View3()
    {
        if(!Settings.HasView3)
            return View4();
        else
            return View("View3");
    }

    //etc.
}

Which works fine as-is. However, if I were to implement another ViewN, I would also have to update ViewN-1, which seems inconsistent.

Implementation 2: Some other object which determines the flow based on settings.

Another implementation I came up with is some kind of ViewManager which returnes a View based on the current View and the settings provided. Something like this;

public class ViewManager
{
    public string GetNextView(string CurrentViewName)
    {
        //Logic to determine the next View
        //I probably have to bind the View names to the settings somehow
        //to achieve this
    }
}

An implementation in the Controller would be as follows, considering View1 is part of the flow;

public class ViewController : Controller
{
    [HttpPost]
    public ActionResult View1(string currentViewName)
    {
        //handle View Post-logic
        var vm = new ViewManager();
        return View(vm.GetNextView(currentViewName));
    }
}

The second implementation seems to be the better one, yet the first one seems easier to implement.

Any suggestions on why you would choose one over another, or perhaps any other ideas on how to implement this?


texts: Finding solution for pancake sort efficiently without actually flipping each time

texts:
Problem

Solve correct flips to sort given input with pancake sort.

Example

input (input size and values):
8
6 7 2 5 1 4 3 8

solution (number of flips and how many elements to flip per operation):
6
2 7 4 5 3 4

    2 -> 7 6 2 5 1 4 3 8
    7 -> 3 4 1 5 2 6 7 8
    4 -> 5 1 4 3 2 6 7 8
    5 -> 2 3 4 1 5 6 7 8
    3 -> 4 3 2 1 5 6 7 8
    4 -> 1 2 3 4 5 6 7 8

alternative solution:
6
3 6 2 5 7 3

Program doesn't need to actually sort anything, just give one possible solution.

What would be faster way to calculate needed flips without resorting to sorting input with ineffective pancake sort?

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    using namespace std;
    ios::sync_with_stdio(false);

    int N;
    cin >> N;
    vector<int> v(N);
    vector<int> flips;

    for (int i=0; i<N; ++i)
        cin >> v[i];

    auto first  = v.begin();
    auto last   = v.end();
    for (; first != last; --last)
    {
        auto mid = max_element(first, last);
        if (mid == last - 1) {
            continue;
        }
        if (first != mid) {
            flips.push_back(distance(first, mid+1));
            reverse(first, mid + 1);
        }
        flips.push_back(distance(first, last));
        reverse(first, last);
    }

    cout << flips.size() << endl;
    for (auto flip : flips)
        cout << flip << " ";
    cout << endl;
}


texts: Satellite orbit simulation in Matlab using Runge Kutta 4

texts:
I have a satellite orbit simulation in Matlab (Using Runge Kutta 4).  It seems ugly and I don't know how to fix it.

fx.m file:

function v = fx(t,x,vx)
v = vx;

fy.m file:

function v = fy(t,y,vy)
v = vy;

gx.m file:

function v = gx(t,x,y,vx,vy)
global G M;
v = -G*M*(x/((x^2+y^2)^(3/2)));

gy.m file:

function v = gy(t,x,y,vx,vy)
global G M;
v = -G*M*(y/((x^2+y^2)^(3/2)));

Simulation file:

clear all
clc
R=6.37e6;
h=20.20e6;
global G M;
G=6.672e-11;
M=5.97e24;
vx(1)=3870 %2;
vy(1)=0;
x(1)=0;
y(1)=R+h;
t(1)=0;
dt=200;
%------
delta_T = 200;
t1 = 0;
x0 = 0;
vx0 = 3870;
y0 = R+h;
vy0 = 0;
%-----

load('topo.mat','topo','topomap1');
colormap(topomap1);
[a,b,c]=sphere(50);
props.AmbientStrength = 0.1;
props.DiffuseStrength = 1;
props.SpecularColorReflectance = .5;
props.SpecularExponent = 20;
props.SpecularStrength = 1;
props.FaceColor = 'texture';
props.EdgeColor = 'none';
props.FaceLighting = 'phong';
props.Cdata = topo;
surface(R.*a,R.*b,R.*c,props);
light ('position',[-1 0 1]);
light ('position',[-1.5 0.5 -0.5],'color',[.6 .2 .2]);
view(-131,8);
%axis equal;
hold on

%-----

r=R+10^6;
hh=plot(x(1),y(1),'--rs','LineWidth',2,'MarkerEdgecolo','k','MarkerFacecolor','g', 'MarkerSize',15);
for i=0:0.05:2000

    k1 = delta_T*fx(t1,x0,vx0);
    l1 = delta_T*gx(t1,x0,y0,vx0,vy0);
    m1 = delta_T*fy(t1,y0,vy0);
    n1 = delta_T*gy(t1,x0,y0,vx0,vy0);

    k2 = delta_T*fx(t1+delta_T/2, x0+k1/2, vx0+l1/2);
    l2 = delta_T*gx(t1+delta_T/2, x0+k1/2, y0+m1/2, vx0+l1/2, vy0+n1/2);
    m2 = delta_T*fy(t1+delta_T/2, y0+k1/2, vy0+l1/2);
    n2 = delta_T*gy(t1+delta_T/2, x0+k1/2, y0+m1/2, vx0+l1/2, vy0+n1/2);

    k3 = delta_T*fx(t1+delta_T/2, x0+k2/2, vx0+l2/2);
    l3 = delta_T*gx(t1+delta_T/2, x0+k2/2, y0+m2/2, vx0+l2/2, vy0+n2/2);
    m3 = delta_T*fy(t1+delta_T/2, y0+k2/2, vy0+l2/2);
    n3 = delta_T*gy(t1+delta_T/2, x0+k2/2, y0+m2/2, vx0+l2/2, vy0+n2/2);

    k4 = delta_T*fx(t1+delta_T, x0+k3, vx0+l3);
    l4 = delta_T*gx(t1+delta_T, x0+k3, y0+m3, vx0+l3, vy0+n3);
    m4 = delta_T*fy(t1+delta_T, y0+k3, vy0+l3);
    n4 = delta_T*gy(t1+delta_T, x0+k3, y0+m3, vx0+l3, vy0+n3);

    x0 = x0 + (k1+2*k2+2*k3+k4)/6;
    vx0 = vx0 + (l1+2*l2+2*l3+l4)/6;
    y0 = y0 + (m1+2*m2+2*m3+m4)/6;
    vy0 = vy0 + (n1+2*n2+2*n3+n4)/6;

    t1 = t1 + delta_T;

    rr=sqrt(x0*x0 + y0*y0);
    aa=rr*sin(i);
    bb=rr*cos(i);
    set(hh,'XData',aa,'YData',bb);
    drawnow;
end


texts: Angular directive with use of scope.$parent and $timeout

texts:
For the over eager people: check out this plunker

I create a directive which has to add buttons on top of input fields, to select the language you want to input.

This is used on forms, such as a product form. A product has translations (i.e. has a description that is language dependant).

Things I am not really happy with:

I use $scope.$parent to get the required translation for the given field
The use of the timeout to handle model info that arrives with a delay (from a web service)

for the people that took the time to read this: check out the example on plunker

Let me know if you need any more information / explanation.

The directive in question:

app.directive('translationMenu', function($compile, $timeout) {
  return {
    restrict: 'E',
    scope: {
      languages: '=',
      defaultLanguage: '='
    },
    templateUrl: 'translation-menu.html',
    controller: function($scope, $element, $attrs) {
      // check if the current field is available in the given dictionary
      var checkFieldAvailability = function(l) {
        return $scope.$parent[$attrs.dictionary] && $scope.$parent[$attrs.dictionary][l] && $scope.$parent[$attrs.dictionary][    l][$attrs.field];
      }

      // check if the language is available in the dictionary, and if so, if the field is already translated.
      // is used to color the button text red
      var dictionaries = {};
      $scope.languages.forEach(function(l) {
        dictionaries[l] = checkFieldAvailability(l);
      });

      // the muscles of this operation
      // it will replace the input field with a clone of the original (and with ng-model filled out)
      var inputElementTemplate = $element.next().clone();
      var setInputField = function(lang) {
        var inputElement = inputElementTemplate.clone();
        inputElement.attr('ng-model', $attrs.dictionary + '.' + lang + '.' + $attrs.field);
        $element.next().replaceWith(inputElement);
        $compile(inputElement)($scope.$parent);
      };

      // function used in the ng-click.
      // when navigating away, it will also check again if it needs transalation.
      var selectLanguage = function(lang) {
        var oldLang = $scope.selectedLanguage;
        dictionaries[oldLang] = checkFieldAvailability(oldLang);
        $scope.selectedLanguage = lang;
        setInputField(lang);
      };

      // Dirty fix, this "ensures" that the dictionary is returned from the ajax request.
      $timeout(function() {
        console.dir(dictionaries);
        for (var lang in dictionaries) {
          dictionaries[lang] = checkFieldAvailability(lang);
        }
      }, 300);

      $scope.selectedLanguage = $scope.defaultLanguage;
      $scope.selectLanguage = selectLanguage;
      $scope.dictionaries = dictionaries;

      selectLanguage('en');
    }
  }
});

The View:

<div class="col-sm-5">
  <translation-menu languages="allLanguages" default-language="currentUser.DefaultLanguage" field="name" dictionary="desc" ></translation-menu>
  <input class="form-control" type="text" />
</div>

the controller:

function MyController($rootScope, $scope,$timeout) {
  $rootScope.allLanguages = ['en', 'nl', 'fr'];
  $rootScope.currentUser = {
    DefaultLanguage: 'en'
  };

  // Simulate slow-ish web service
  $scope.desc = {};
  $timeout(function(){
    $scope.desc = {
      'en': {
        'name': 'Joseph',
        'code': 'EN123'
      },
      'nl': {
        'name': 'Jos',
        'code': 'NL123'
      }
    };
  }, 200);
}


texts: Using await to break long-running processes

texts:
I have a Node.js app / Web API that runs on an Azure app service with a single CPU.

One of the functions needs to run for a long time, perhaps tens of seconds, while the server should continue to process other requests, i.e. the function should not be blocking.

My idea is to use await new Promise(resolve => setTimeout(resolve, 0)); at the end of each loop cycle to requeue the microtask at the end of the queue, giving other users a chance to receive the response too.

The code is processing data using the node-tfidf package like this:

const Tfidf = require('node-tfidf');
const tfidf = new Tfidf();

for (let document of documents) {
  tfidf.addDocument(document);

  // Break the blocking code:
  await new Promise(resolve => setTimeout(resolve, 0));
}

for (let keyword of keywords) {
  tfidf.tfidfs(keyword, function(i, measure) {
      results.add({keyword, i, measure});
  });

  // Break the blocking code:
  await new Promise(resolve => setTimeout(resolve, 0));
}

I want to get your comments about whether using Promise + setTimeout is a sensible way to break long-running tasks and whether there is a big performance drawback (perhaps break it every 10 loop cycles?).


texts:
I recently wrote a small Python 3 script to count the number of projects in a Scratch studio:

import re, functools
import requests

PARSE_RE = re.compile(r"""^
                          (?:  http://  |  https://  |  //  )?   # optional header
                          scratch\.mit\.edu/studios/             # main part of URL
                          (\d+)                                  # studio ID
                          (?:  /projects  )?                     # optional /projects
                          /?                                     # optional trailing slash
                          $
                            |
                          ^(\d+)$                                # alternative: just a number for the studio ID
                          """, re.VERBOSE)

EXIT_NO_ARGS = 1
EXIT_INVALID_STUDIO_ID = 2

@functools.lru_cache(maxsize=16)
def query_page(studio_id, page, verbose):
    if verbose:
        print(end="Querying page {0}... ".format(page))
    url = "https://scratch.mit.edu/site-api/projects/in/{0}/{1}/".format(studio_id, page)
    text = requests.get(url).text
    if verbose:
        print("done")
    return text

def is_404(page_html):
    # The 404 page is a full webpage with a <!DOCTYPE>
    return ("<!D" in page_html)

def count_li(page_html):
    # Counts the number of instances of the string "<li" in the argument
    return page_html.count("<li")

def count_pages(studio_id, verbose=False):
    page_maximum = 1
    while True:
        page_html = query_page(studio_id, page_maximum, verbose)
        if is_404(page_html):
            page_minimum = page_maximum // 2
            break
        page_maximum *= 2

    # preform a binary search to find the first 404 studio
    while page_maximum - page_minimum > 1:
        page_num = (page_minimum + page_maximum) // 2
        page_html = query_page(studio_id, page_num, verbose)
        if is_404(page_html):
            page_maximum = page_num
        else:
            page_minimum = page_num

    page_count = page_minimum
    highest_page_html = query_page(studio_id, page_count, verbose)
    highest_page_project_count = count_li(highest_page_html)
    total = (page_count - 1) * 60 + highest_page_project_count
    return total

if __name__ == "__main__":
    import sys

    if len(sys.argv) == 1:
        print("Usage:")
        print("  {0} <url or studio ID>:    counts the projects in that studio".format(sys.argv[0]))
        print("  {0} -v <url or studio ID>: verbose mode (logs all queries)".format(sys.argv[0]))
        sys.exit(EXIT_NO_ARGS)

    verbose = ("-v" in sys.argv)
    studio_match = PARSE_RE.match(sys.argv[-1])
    if not studio_match:
        print("Error: Invalid studio ID")
        print("Must be a URL (scratch.mit.edu/studios/12345678) or a number (12345678)")
        sys.exit(EXIT_INVALID_STUDIO_ID)
    studio_id = studio_match.group(1) or studio_match.group(2)
    print(count_pages(studio_id, verbose))

It requires requests. It can be called from the command line as python3 count.py https://scratch.mit.edu/studios/??? (where ??? is the studio ID), or it can be imported as a module and called using count.count_pages. It also supports a verbose logging mode which logs all requests.

How could this be improved?


texts: Avoiding a large 'switch' call in the main loop

texts:
I am writing a Unix shell in C, which uses a rather large switch in the main loop.

It is used to handle built-in commands like 'cd' or'help'. The way it works is that it parses the user input and return a 'comand_t' struct, with 'name' being the first word of the input.

The in order to switch on a string, I translate it into an int by reading this initialized struct:

built_in_commands my_commands[CMD_NBR] = {
    {""     , EMPTY_CMD         , ""},
    {"cd"   , CD_CMD            , "change directory"},
    {"env"  , ENV_CMD           , "print enviroment. Can show single variable"},
    {"exit" , EXIT_CMD          , "exit from AGROS"},
    {"help" , HELP_CMD          , "print help"},
    {"?"    , SHORTHELP_CMD     , "print short help"}
};

The macros are defined in the header file:

#define EMPTY_CMD           0

#define CD_CMD              1
#define ENV_CMD             2
#define EXIT_CMD            3
#define HELP_CMD            4
#define SHORTHELP_CMD       5
#define SETENV_CMD          6
#define GETENV_CMD          7

#define OTHER_CMD           8

#define CMD_NBR             9

the main loop of the program is this:

while (AG_TRUE){

    /* Set the prompt */
    get_prompt(prompt, MAX_LINE_LEN, username);

    /*
     * Read a line of input
     * commandline should be deallocated with free()
     */
    commandline = read_input (prompt);

    parse_command (commandline, &cmd);

    switch (get_cmd_code (cmd.name)){ //returns an int
        case EMPTY_CMD:
            break;

        case CD_CMD:
            change_directory (cmd.argv[1], ag_config.loglevel);
            break;

        case HELP_CMD:
            print_help(&ag_config, cmd.argv[1]);
            break;

        case SHORTHELP_CMD:
            print_help(&ag_config, "-s");
            break;

        case ENV_CMD:
            print_env (cmd.argv[1]);
            break;

        case EXIT_CMD:
            free (commandline);
            commandline = (char *)NULL;
            closelog ();
            return 0;

        case OTHER_CMD:
            fork_and_exec();
            break;
    }
}

Every time I add a new builtin function, I wonder if there isn't a better way to do this.
What would it be? How can I call a function dynamically?


texts: Checking if string contains other strings

texts:
This is simply an extension method which checks if a string str contains all the values in values.

However, there are cases when str might be null, values might be null, or any item in values might be null. I am handling those cases by using the ternary ?:, null-conditional ?. and null-coalesce ?? operators.

Should this piece of code be refactored?

public static bool ContainsAll(this string str, string[] values)
{
    return str == null ? false : values?.All(v => str.Contains(v ?? "")) ?? false;
}


texts:
I am trying to move some logic outside my controller for creating my view models for the view.

I have a lot of queries to fire to make sure the complete view model is ready, so to keep my controllers thin I came up with this design - any feedback, comments or suggestions are welcome!

The interfaces looks as following:

public interface IViewModel
{
    // Marker interface
}

public interface IHandleViewModel<TViewModel> where TViewModel : IViewModel
{
    Task<TViewModel> Handle();
}

public interface IProcessViewModels
{
    Task<TViewModel> Create<TViewModel>() where TViewModel : IViewModel, new();
}

The implementation of the IProcessViewModels is using dependency injection (Simple Injector) to find the correct handler for the view model:

internal sealed class ViewModelProcessor : IProcessViewModels
{
    private readonly Container _container;

    public ViewModelProcessor(Container container)
    {
        _container = container;
    }

    public Task<TViewModel> Create<TViewModel>() where TViewModel : IViewModel, new()
    {
        var handlerType = typeof(IHandleViewModel<>).MakeGenericType(typeof(TViewModel));
        dynamic handler = _container.GetInstance(handlerType);
        return handler.Handle();
    }
}

The setup is done in the Composition Root using this extension:

 public static void RegisterViewModels(this Container container, Assembly[] viewModelAssemblies)
    {
        if (container == null)
            throw new ArgumentNullException("container");

        if (viewModelAssemblies == null)
            throw new ArgumentNullException("viewModelAssemblies");

        container.RegisterSingle<IProcessViewModels, ViewModelProcessor>();
        container.RegisterManyForOpenGeneric(typeof(IHandleViewModel<>), viewModelAssemblies);

        container.RegisterSingleDecorator(
            typeof(IHandleViewModel<>),
            typeof(ViewModelLifetimeScopeDecorator<>)
        );
    }

The usage

public HomeViewModel : IViewModel {

    public string PageTitle { get; set; }

    public IList<TodoItem> TodoItems { get; set; }

}

public HandleHomeViewModel : IHandleViewModel<HomeViewModel> {

    private readonly IProcessQueries _queries; // CQRS

    public HandleHomeViewModel(IProcessQueries queries) {
            _queries = queries;
    }

    public async Task<HomeViewModel> Handle() {
        var model = new HomeViewModel {
             PageTitle = "This is the page title";
             TodoItems = await _queries.Execute(new GetTodoItemsFromDatabase()); // for demo purpose
        }

        return model;
    }

}

public class HomeController : Controller
{
    private readonly IProcessViewModels _models;

    public HomeController(IProcessViewModels models)
    {
        _models = models;
    }

    public async Task<ActionResult> Index()
    {
            var model = await _models.Create<HomeViewModel>();
            return model;
    }
}


texts:
Shape represents an abstract class and the other two classes inherits from it. This looks insufficiently abstract to me. How could I improve it?

import math
class Point:

    def __init__(self,x,y):
        self.x = x
        self.y = y

    def move(self,x,y):
        self.x += x
        self.y += y

    def __str__(self):
        return "<"+ str(self.x) + "," + str(self.y) + ">"

class Shape:
    def __init__(self, centrePoint, colour, width, height):
        self.centrePoint = centrePoint
        self.colour = colour
        self.width = width
        self.height = height
        self.type = "Square"

    def __init__(self, centrePoint, radius, colour):
        self.type = "Circle"
        self.radius = radius
        self.colour = colour
        self.centrePoint = centrePoint

    def move(self,x,y):
        self.centrePoint.move(x,y)

    def getArea(self):
        if (self.type == "Square"):
            return self.width * self.height
        elif (self.type == "Circle"):
            return math.pi*(self.radius**2)

    def __str__(self):
        return "Center Point: " + str(self.centrePoint) + "\nColour: "+ self.Colour + "\nType: " + self.type + "\nArea: " + self.getArea()

class Rectangle (Shape):

    def scale(self, factor):
        self.scaleVertically(factor)
        self.scaleHorizontally(factor)

    def scaleVertically(self, factor):
        self.height *= factor

    def scaleHorizontally(self, factor):
        self.width *= factor

class Circle (Shape):

    def scale(self, factor):
        self.radius * factor


texts:
since in my website I have a lot of <HEADER>, <FOOTER> AND <SECTION> do you think is appropriate if i use a .main class for the main HEADER, main FOOTER AND main SECTION?

In the CSS I will never style the .main class like this:

.main { ... }

but always like this:

header.main { ... }
footer.main { ... }
section.main { ... }

Of course it will be total different styling.


texts: Optimize performance of flatten function in python

texts:
I have to flatten a large number (>300k) dicts to write them to a csv file.

Example:

dict = {
    a: b,
    c: [
       {
           d:e
       },
       {
           f:g
       }
    ]
}

becomes:

a, c.0.d, c.1.f
b, e, g

The dicts can be really big with a lot of dicts as values.

My function to flatten them generically is:

def flatten(self, d, parent_key='', sep='.'):
        items = []
        for k, v in d.items():
            new_key = parent_key + sep + k if parent_key else k
            if isinstance(v, collections.MutableMapping):
                items.extend(self.flatten(v, new_key, sep=sep).items())
            elif isinstance(v, list):
                if isinstance(v[0], dict):
                    counter = 0
                    for entry in v:
                        new_count_key = new_key + sep + str(counter)
                        items.extend(self.flatten(entry, new_count_key, sep=sep).items())
                        counter += 1
                else:
                    items.append((new_key, v))
                    if new_key not in self.key_list:
                        self.key_list.append(new_key)
            else:
                items.append((new_key, v))
                if new_key not in self.key_list:
                    self.key_list.append(new_key)
        return dict(items)

When I meassure the time needed for exceution I found out the highest amount of time is caused by the instance checks. With 2500 dicts for example, the instance checks need around 6 seconds out of 12 seconds total.

Is there any way, I can speed up this function?


texts: Finding the first stream of non-repeating elements in Scala (without recursion or side-effects)

texts:
Here are some examples:

[1, 2, 3, 4, 5] => [1, 2, 3, 4, 5]
[10, 15, 10, 15, 30] => [10, 15]
[1, 2, 3, 4, 1, 5, 6, 7] => [1, 2, 3, 4]

Here's my best (and deeply ugly) non-recursive, side-effect-free solution so far:

x.scanLeft(List[Int]())((B, Term) => Term :: B).drop(1).takeWhile(i => !(i.tail contains i.head)).last.reverse

Minor optimization:

x.tail.scanLeft(List(x.head))((B, Term) => Term :: B).takeWhile(i => !(i.tail contains i.head)).last.reverse

This is different from distinct:

[1, 2, 3, 4, 1, 5, 6, 7] => [1, 2, 3, 4] and not [1, 2, 3, 4, 5, 6, 7]

Also, considering List[_] is a monoid, isn't there a scan that uses the monoid zero?


texts:
I'm new to Java and am following a series of lectures on Stanford's YouTube. I know that the code works, but I'd like to know if it can be improved upon.

/*
 * File: PythagoreanTheorem.java
 * Name: Will
 * Section Leader: N/A, I'm freeloading the class off Youtube.
 * -----------------------------
 * This file is the starter file for the PythagoreanTheorem problem.
 */

import acm.program.*;

public class PythagoreanTheorem extends ConsoleProgram {
    public PythagoreanTheorem() {}
    public void run() {
        PythagoreanTheorem myCalculator = new PythagoreanTheorem();
        double a = readDouble("a= ");
        double b = readDouble("b= ");
        if(myCalculator.formula(a,b) ==
            Math.floor(myCalculator.formula(a,b))) {
            println("C= "+(int)myCalculator.formula(a,b));}
        else {
            println("C= "+myCalculator.formula(a,b));}
                      }
    private double formula(double x, double y) {
        double c = Math.sqrt(x*x+y*y);
        return c;
    }
}


texts: How to use recursion to turn object into string?

texts:
EDIT
To me JSON.stringify is not the solution here, as it is much slower than recursion
    JSON.stringify(fakeData)
        .replace(/,/g, ';')
        .replace(/:(?={)/g, '')
        .replace(/"/g, '')

//Result
Recursion with reduce x 816,321 ops/sec ±7.38% (80 runs sampled)
JSON.stringify x 578,221 ops/sec ±1.72% (92 runs sampled)
Fastest is Recursion with reduce

I am making a css-in-js library, and I need to use recursion to turn object into string like this:
Input:
const fakeData = {
  a: {
    b: 'c',
    d: 'e'
  }
}

Output:
a{b:c;d:e;}

My recursion function:
const buildKeyframe = (obj) => {
    return Object.entries(obj).reduce((acc, [prop, value]) => {
        if (typeof value === 'string') {
            return `${acc}${prop}:${value};`
        }

        return `${acc}${prop}:{${buildKeyframe(value)}}`
    }, '')
}

This function works, but I think there is room for improvement(e.g. use TCO, avoid using reduce)... How can I write a better function to recurse this data structure?


texts:
I'm working on a communications layer for a system that reads data from a TCPIP client that is formatted as fixed-width ASCII (yeah, old school). I was quite surprised that there seemed to be no built in way to do this, and ended up using the following simple StreamReader subclass:

/// <summary>
/// A Stream reader that reads values as fixed width fields from a stream
/// </summary>
class FixedWidthFieldStreamReader : StreamReader
{
    #region Private/Protected fields
    private char[] buffer; // Local buffer used to copy data before conversion
    #endregion

    #region Methods
    /// <summary>
    /// Instantiates a new FixedWidthFieldStreamReader for a stream
    /// </summary>
    /// <param name="stream">Stream to read from</param>
    /// <param name="initialBufferSize">Initial size of the buffer used to copy data before formatting</param>
    /// <param name="encoding">Encoding to use when reading from the stream</param>
    public FixedWidthFieldStreamReader(Stream stream, int initialBufferSize, Encoding encoding)
        : base(stream, encoding)
    {
        buffer = new char[initialBufferSize];
    }

    /// <summary>
    /// Checks if the buffer exists and is large enough,
    /// and allocates or grows it if necessary.
    /// </summary>
    /// <param name="length">The required buffer length</param>
    private void EnsureBufferLength(int length)
    {
        if (null == buffer ||
            buffer.Length < length)
        {
            buffer = new char[length];
        }
    }

    /// <summary>
    /// Reads a number of bytes into the buffer
    /// </summary>
    /// <param name="length">The number of bytes to read</param>
    /// <returns>True if the required number of bytes was read, false otherwise</returns>
    private bool ReadToBuffer(int length)
    {
        EnsureBufferLength(length);

        // Read from the stream
        int read = Read(buffer, 0, length);
        return read == length;
    }

    /// <summary>
    /// Reads a specified number of bytes from the stream and
    /// converts and returns the read value.
    /// </summary>
    /// <typeparam name="T">Type of the object to read and return</typeparam>
    /// <param name="length">Number of bytes in the field to read from the stream.</param>
    /// <returns>The read object if successful, or the default value for the type otherwise.</returns>
    public T Read<T>(int length) where T : IConvertible
    {
        if (ReadToBuffer(length))
        {
            return (T)Convert.ChangeType(new string(buffer, 0, length), typeof(T));
        }

        return default(T);
    }

    /// <summary>
    /// Skips a specified number of bytes in the stream
    /// </summary>
    /// <param name="length">The number of bytes to skip</param>
    public void Skip(int length)
    {
        // Ideally we should be able to just seek on the current stream,
        //  but that seems to seek to an incorrect location?
        //this.BaseStream.Seek(length, SeekOrigin.Current);
        ReadToBuffer(length);
    }
    #endregion
}

This would be used something like this:

using (MemoryStream stream = new MemoryStream(buffer))
{
    stream.Seek((int)FieldOffsets.DATA, SeekOrigin.Begin);
    using (FixedWidthFieldStreamReader reader = new FixedWidthFieldStreamReader(stream, 15, Encoding.ASCII))
    {
        intVal = reader.Read<int>(3);
        stringVal = reader.Read<string>(15);
        floatVal= reader.Read<float>(5);
    }
}

I have two questions based on this:

Am I just missing some completely obvious existing utility to do this? It really does seem like a common problem that would have been solved by the framework team ages ago.
Aside from the obvious optimization of having some type specific versions of Read that don't do the conversion, are there any suggestions to improve this approach?


texts:
The program reads in a queue of integers and returns determines whether or not it is valid (ascending).
How can this code be improved?
I assume iterator include statement is unnecessary?

#include <iostream>
#include <queue>
#include <deque>
#include <iterator>

template<typename T, typename Container=std::deque<T> >
class iterable_queue : public std::queue<T,Container>
{
public:
    typedef typename Container::iterator iterator;
    typedef typename Container::const_iterator const_iterator;

    iterator begin() { return this->c.begin(); }
    iterator end() { return this->c.end(); }
    const_iterator begin() const { return this->c.begin(); }
    const_iterator end() const { return this->c.end(); }
};

bool checkValidity(iterable_queue<int>& q) {
    if (q.empty() || q.size() <= 1){
        std::cout << "invalid entry, insufficient elements" << '\n';
        return false;
    }
    while(q.size()){
        auto i = q.begin();
        auto j = ++q.begin();
        for(; i < q.end() && j < ++q.end();){
            std::cout << *i << " " << *j << '\n';
            if (*(i) > *(j)) {
                std::cout << "invalid entry, not properly sorted" << '\n';
                return false;
            }
            i++, j++;
        }
        std::cout << "valid entry, properly sorted" << '\n';
        return true;
    }
    std::cout << "invalid entry, insufficient elements" << '\n';
    return false;
}

const char* bool_cast(const bool b) {
    return b ? "true" : "false";
}

int main () {
    iterable_queue<int> numbers;
    int temp;

    std::cout << "Pushing..." << '\n';
    while(temp >= 0){
        std::cout << "Enter numbers: ";
        std::cin >> temp;
        if(temp >= 0){
            numbers.push(temp);
        }
    }

    bool ck = checkValidity(numbers);
    std::cout << bool_cast(ck) << '\n';

    std::cout << "{ ";
    while(numbers.size() > 0){
        std::cout << numbers.front();
        numbers.pop();
        std::cout << " ";
    }
    std::cout << "}" << '\n';

    return 0;
}


texts: Applying a transformation to all the text nodes inside a given node using lxml.html?

texts:
I would like to apply a transformation, say uppercase, to all the text nodes inside a given node. I came up with the following code which works fine for my sample input.

Is there something else that should be considered? I felt that the usage of text vs tail in lxml is a bit asymmetric because text needs to be applied to the main node and tail needs to be applied to the child node.

Can someone review this code?

import lxml.html

def transform(node):
    if node.text:
        node.text = node.text.upper()
    for child in node.getchildren():
        if child.tail:
            child.tail = child.tail.upper()
        transform(child)

Here is the test case used:

html = """

      <link href="great.css" rel="stylesheet" type="text/css">
      <title>Best Page Ever</title>

      Body Start

         Div 1 Start

            Div 11 Start
            Address 1

            Address 2
            Div 11 End

            Div 12 Start

              Inside Div 121

            Div 12 End

         Div 1 End

      Body End

"""

root = lxml.html.fromstring(html)

transform(root.get_element_by_id('121'))

print(lxml.html.tostring(root))


texts: Initiating an action based on product type

texts:
I am starting my studies with Ruby and OO and I have received a test to do about OO. I am looking for new ways to improve the scenario following object-oriented concepts. Is there a better way to develop this design applying polymorphism?

Here is my problem:

If the product is physical, I have to generate a shipping label.
If it's a book, I have to mention that this product doesn't have taxes.
If the product is a membership, I have to activate the signature and notify the buyer via email.
If the product is digital, I have to send an email for the buyer and give a $10 discount for this product.

class Product
  attr_reader :name, :description, :type, :amount
  include Shipping
  include Discount

    def initialize(name, description, type, amount)
        @name = name
        @description = description
        @type = type
        @amount = amount
    end
end

class Physical < Product
    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

    def shipping
        case @type
            when :book
                create_shipping_label
                notify_buyer_product_without_taxes
            else
                create_shipping_label
            end
    end

    def discount
        discount_for_physical_product = 0.0
      return discount_for_physical_product
    end
end

class Membership < Product
    attr_reader :membership_status

    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

  def activate_membership()
    @membership_status = true;
  end

  def shipping
    notify_buyer_via_email
    activate_membership
  end

  def discount
    discount_for_membership_product = 0
    return discount_for_membership_product
  end
end

class Digital < Product

    def initialize(name, description, type, amount)
        super(name, description, type, amount)
    end

  def shipping
    notify_buyer_via_email
  end

  def discount
    discount_for_digital_product = 10.00
    return discount_for_digital_product
  end
end

module Discount

    def prepare_discount(order)
        total_discount = 0
        order.get_items.each do |item|
             total_discount += item.product.discount
        end
        return total_discount
    end

    def discount
        discount_default = 0.0
        return discount_default
    end
end


texts: Find max values of all subarrays of specific length

texts:
This is one of the coding questions that I subscribe to and I wanted to solve it in Rust. I would really appreciate your feedback for improving this code and writing idiomatic Rust.

  Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.

  For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should
  get: [10, 7, 8, 8], since:

10 = max(10, 5, 2)
7 = max(5, 2, 7)
8 = max(2, 7, 8)
8 = max(7, 8, 7)

  Do this in \$O(n)\$ time and \$O(k)\$ space. You can modify the input array
  in-place and you do not need to store the results. You can simply
  print them out as you compute them.

This is my first attempt:
https://gist.github.com/ginghamtaus/236e8a1d75237a47769ca74b23ac45ac

This is my second attempt:
https://gist.github.com/ginghamtaus/6e0003e43e020130c8fd9346c9019522

use std::collections::VecDeque;

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;
    let mut deque: VecDeque<usize> = VecDeque::new();
    for i in 0..a.len() {
        match deque.front() {
            None => deque.push_back(i),
            Some(_) => {
                let mut done = false;
                while !done {
                    match deque.back() {
                        Some(&x) => {
                            if a[i] > a[x] {
                                deque.pop_back();
                            }
                            else {
                                done = true;
                            }
                        },
                        _ => { done = true; }
                    }
                }
                deque.push_back(i);
            }
        }

        if i + 1 >= k  {
            match deque.front() {
                Some(&x) => {
                    println!("max({:?}) = {}", &a[i+1-k..i+1], a[x]);
                    if x <= (i + 1 - k) {
                        deque.pop_front();
                    }
                },
                _ => ()
            };
        }
    }
}


texts:
I have began taking the CS50 course on EDX the past couple of days, and one of the tasks to accomplish was to write a credit card validator in C. I wrote it in C, and then I thought that I could go about the same thing in Python, and wrote the same program in Python. For those of you unfamiliar with the problem, here is the description.

Because I took the program and converted from C to Python, it is probably not going to be written in the most Pythonic way. I tried to add some Pythonic ways of doing things, but there are probably many more things I could have done. If you find anything that could be done in a better, faster, or more Pythonic way, please let me know. Thanks.

def main():
    # cc_number = int(input("Enter a valid credit card number: "))

    cc_number = 12345678912356789
    if not checksum(cc_number):
        print("INVALID")
    else:
        print(check_provider(cc_number))

def check_provider(number):
    if len(str(number)) < 13 or len(str(number)) > 16:
        return 'INVALID'

    if ((list(str(number)))[:2]) == ['3', '4'] or ((list(str(number)))[:2]) == ['3', '7']:
        return 'AMEX'
    elif ((list(str(number)))[:2]) == ['5', '1'] or ((list(str(number)))[:2]) == ['5', '2'] \
            or ((list(str(number)))[:2]) == ['5', '3'] or ((list(str(number)))[:2]) == ['5', '4'] \
            or ((list(str(number)))[:2]) == ['5', '5']:
        return 'MASTERCARD'
    elif ((list(str(number)))[0]) == '4':
        return 'VISA'
    else:
        return 'INVALID'

def checksum(number):
    list_number = list(str(number))
    odd_indices = []
    even_indices = []

    last_index = len(list_number) - 1

    rev_list = list(reversed(list_number))

    for i in rev_list[1::2]:
        odd_indices.append(i)

    for i in rev_list[::2]:
        even_indices.append(i)

    sum_odd = sum(split_to_digits(''.join(int_to_str(mul(odd_indices, 2)))))
    sum_even = sum(split_to_digits(''.join(int_to_str(even_indices))))
    s = sum_odd + sum_even

    print(s)

    if s % 10 == 0:
        return True
    return False

def mul(list, x):
    return [(int(n) * 2) for n in list]

def split_to_digits(n):
    return [int(i) for i in str(n)]

def int_to_str(n):
    return [str(x) for x in n]

def str_to_int(n):
    return [int(x) for x in n]

main()


texts: Create palindrome by rearranging letters of a word

texts:
Inspired by a recent question that caught my interest (now deleted), I wrote a function in Python 3 to rearrange the letters of a given string to create a (any!) palindrome:

Count the occurrences of each letter in the input
Iterate over the resulting (letter, occurrences) tuples only once:

If the occurences are even, we remember them to add them around the center later
A valid palindrome can contain only 0 or 1 letter(s) with an odd number of occurrences, so if we've already found the center, we raise an exception. Otherwise, we save the new-found center for later

Finally, we add the sides around the center and join it to create the resulting palindrome string.

I'm looking for feedback on every aspect you can think of, including

readability (including docstrings),
how appropriate the data structures are,
if the algorithm can be expressed in simpler terms (or replaced altogether) and
the quality of my tests.

Implementation: palindromes.py

from collections import deque, Counter

def palindrome_from(letters):
    """
    Forms a palindrome by rearranging :letters: if possible,
    throwing a :ValueError: otherwise.
    :param letters: a suitable iterable, usually a string
    :return: a string containing a palindrome
    """
    counter = Counter(letters)
    sides = []
    center = deque()
    for letter, occurrences in counter.items():
        repetitions, odd_count = divmod(occurrences, 2)
        if not odd_count:
            sides.append(letter * repetitions)
            continue
        if center:
            raise ValueError("no palindrome exists for '{}'".format(letters))
        center.append(letter * occurrences)
    center.extendleft(sides)
    center.extend(sides)
    return ''.join(center)

Unit tests: test_palindromes.py (using py.test)

def test_empty_string_is_palindrome():
    assert palindrome_from('') == ''

def test_whitespace_string_is_palindrome():
    whitespace = ' ' * 5
    assert palindrome_from(whitespace) == whitespace

def test_rearranges_letters_to_palindrome():
    assert palindrome_from('aabbb') == 'abbba'

def test_raises_exception_for_incompatible_input():
    with pytest.raises(ValueError) as error:
        palindrome_from('asdf')
    assert "no palindrome exists for 'asdf'" in error.value.args

Manual testing in the console

while True:
    try:
        word = input('Enter a word: ')
        print(palindrome_from(word))
    except ValueError as e:
        print(*e.args)
    except EOFError:
        break


texts: C++ breadth-first search using adjacency matrix

texts:
I have written this Breadth First Search program using Adjacency Matrix, taking help from Introduction to Algorithm(CLSR) and from Internet.

I want to optimise this code.

#include <iostream>
#include <queue>
#include <limits>
#include <vector>

class Graph
{
  int vertexCount;
  //WHITE means Undiscovered, GRAY means Discovered, BLACK menas Processed
  enum class Color{ WHITE, GRAY, BLACK };

  const int imax = std::numeric_limits<int>::max();

  struct Vertex
  {
    int id;
    Color color;
    size_t distance;

    Vertex(const int vertex, Color clr, int imax) : id(vertex),
                                                    color(clr),
                                                    distance(imax)
                                                    {};
  };
  std::vector< std::vector<bool> > adjMatrix; //adjacency adjMatrix
  std::vector<Vertex> vertices;
public:
    Graph(int size)
  {
    vertexCount = size;
    adjMatrix.resize(vertexCount, std::vector<bool>(vertexCount));
    for(int i = 0; i < vertexCount; i++)
    {
      vertices.push_back( Vertex(i, Color::WHITE, imax));
      for(int j = 0; j < vertexCount; j++)
        adjMatrix[i][j] = false;
    }
  }
    ~Graph() {};

    void BFS(const int);
    void addEdge(int, int);
    void printPath(const int,  const int) const;

};

void Graph::BFS(const int src)
{
    const auto s = vertices[src].id;
    vertices[s].color = Color::GRAY;
    vertices[s].distance = 0;

    std::queue<int> Q;
    Q.push(vertices[s].id);

    while(!Q.empty())
    {
        auto u = Q.front();
        Q.pop();

        for (int j = 0; j < vertexCount; j++)
        {
            if(vertices[j].color == Color::WHITE && adjMatrix[u][j] == true)
            {
                vertices[j].color = Color::GRAY;
                vertices[j].distance = vertices[u].distance + 1;
                Q.push(j);
            }
        }
        vertices[u].color = Color::BLACK;
    }
}

void Graph::addEdge(int u, int v)
{
    adjMatrix[u][v] = true;
  adjMatrix[v][u] = true;
}

void Graph::printPath(const int src, const int ver) const
{
    auto s = vertices[src].id;
    auto v = vertices[ver].id;

  std::cout << s;
  for(int j = s + 1; j <= v; j++)
  {
    if(adjMatrix[s][j] == true)
    {
      std::cout << " --> "<< j;
      s = j;
    }
  }
}

int main()
{
    Graph grp1(8);
    grp1.addEdge(0, 1);
  grp1.addEdge(0, 2);
  grp1.addEdge(1, 3);
  grp1.addEdge(1, 4);
  grp1.addEdge(2, 5);
  grp1.addEdge(3, 4);
  grp1.addEdge(3, 6);
  grp1.addEdge(4, 6);
  grp1.addEdge(4, 7);
  grp1.addEdge(6, 7);

    grp1.BFS(0);
    grp1.printPath(1, 7);
}


texts: Creating and manipulating a variant number of bufferedImages for vision algorithm

texts:
I'm developing an algorithm that takes structured light patterns to determine 3D properties of objects.  This class builds the structured light objects.  It creates a buffered image, and based upon initialization parameters and the needed iteration step, manipulates the image to form a structured light pattern that will be be projected.  After the total space has been iteratively exhausted a 3D model of the surface will be constructed.  The projection process is then repeated.

The manipulation step of this class constructs different versions of the same image (the pixels will converge towards the center at each step).

Any suggestions on how I can speed this up, make it smoother, or more readable?

class ImageCollection implements Iterable<BufferedImage> {

private ArrayList<BufferedImage> ImageList = new ArrayList<>();
private static int width;
private static int height;
private static double pointXResolution;
private static double pointYResolution;
private static final Color red = new Color(255, 0, 0);
private static final Color green = new Color(0, 255, 0);
private static final Color blue = new Color(0, 0, 255);
private static final Color white = new Color(255, 255, 255);
private static final ArrayList<Color> colorList = new ArrayList<>();
private static double amountOfSets;

public ImageCollection(int numberOfRows, int numberOfColumns, double xResolution, double yResolution) {
    int typeIntRGB = 1;
    colorList.add(red);
    colorList.add(green);
    colorList.add(blue);
    colorList.add(white);
    ImageCollection.pointYResolution = Math.floor(yResolution / numberOfRows);
    ImageCollection.pointXResolution = Math.floor(xResolution / numberOfColumns);
    ImageCollection.width = (int) xResolution;
    ImageCollection.height = (int) yResolution;
    ImageCollection.height = (int) yResolution;
    int amountOfXPoints = numberOfRows;
    double amountOfYPoints = numberOfColumns;
    int rightPosition = width;
    int leftPosition = 0;
    ImageCollection.amountOfSets = Math.floor(height / (2 * (colorList.size()) * pointYResolution));
    for (int i = 0; i < amountOfSets; i++) {
        BufferedImage image = new BufferedImage(width, height, typeIntRGB);
        for (Color currentColor : colorList) {
            rightPosition-=pointXResolution;
            leftPosition+=pointXResolution;
            int otherPointer = 0;
            for (int k = 1; k < amountOfYPoints + 1; k++) {
                image.setRGB(leftPosition, (int) (k * pointYResolution), currentColor.getRGB());
                image.setRGB(rightPosition, (int) (k * pointYResolution), currentColor.getRGB());
            }
        }
        ImageList.add(image);
    }
}

@Override
public Iterator<BufferedImage> iterator() {
    Iterator<BufferedImage> nextImage = ImageList.iterator();
    return nextImage;
}
}


texts: Saving a contact and dealing with exceptions

texts:
try{save.Username = usernamedetails.Rows[0].ItemArray[0].ToString(); }
catch{ save.Username = ""; }
try { save.Firstname = dtdetails.Rows[0].ItemArray[1].ToString(); }
catch { save.Firstname = ""; }
try { save.LastName = dtdetails.Rows[0].ItemArray[2].ToString(); }
catch { save.LastName = ""; }
try { save.Address1 = dtdetails.Rows[0].ItemArray[3].ToString(); }
catch { save.Address1 = ""; }
try { save.Address2 = dtdetails.Rows[0].ItemArray[4].ToString(); }
catch { save.Address2 = ""; }
try { save.Postoffice = dtdetails.Rows[0].ItemArray[5].ToString(); }
catch { save.Postoffice = ""; }
try { save.District = dtdetails.Rows[0].ItemArray[6].ToString(); }
catch { save.District = ""; }
try{ save.State = dtdetails.Rows[0].ItemArray[7].ToString(); }
catch{ save.State = ""; }
try { save.Country = dtdetails.Rows[0].ItemArray[8].ToString(); }
catch { save.Country = ""; }
try { save.MobileNumber = dtdetails.Rows[0].ItemArray[9].ToString(); }
catch { save.MobileNumber = ""; }
try { save.LandLine = dtdetails.Rows[0].ItemArray[10].ToString(); }
catch { save.LandLine = ""; }
try { save.Pin = dtdetails.Rows[0].ItemArray[11].ToString(); }
catch { save.Pin = ""; }
try { save.Cmpnyname = dtdetails.Rows[0].ItemArray[12].ToString(); }
catch { save.Cmpnyname = ""; }
try { save.Design = dtdetails.Rows[0].ItemArray[13].ToString(); }
catch { save.Design = ""; }
try { save.Loc = dtdetails.Rows[0].ItemArray[14].ToString(); }
catch { save.Loc = ""; }
try { save.CmpnyPincode = dtdetails.Rows[0].ItemArray[15].ToString(); }
catch { save.CmpnyPincode = ""; }
try { save.EmailID = dtdetails.Rows[0].ItemArray[16].ToString(); }
catch { save.EmailID = ""; }
try { save.OffNumber = dtdetails.Rows[0].ItemArray[17].ToString(); }
catch { save.OffNumber = ""; }

Is this type of strategy suitable for coding?


texts: Changing player between bot and human in python tic tac toe

texts:
As a noob I'm creating Tic Tac Toe on Python (Jupyter Notebook used). Granted my coding looks almost childish compared to some of the more advanced examples i've seen, but I am still learning the various built-in functions and becoming more efficient, so I apologize for that. The issue regards the changing of human player ('X') and bot ('O') after 2nd move of human.Below is my code and the final output. Could anyone possibly advise as to why the bots choices stop reflecting after round 1?
winner = False
moves = 0

 while winner == False or moves < 10:
    player_choice(moves)
    print (f'(The current player is {moves})')
    final_output()
    if result_check() == True:
        winner == True
        break
    if game_on() == False:
        break
    moves += 1

    if winner == True:
        print(f'(We have a winner, player {curr_player})')
        print(final_output())
    else: print("Game has been ended by User...goodbye")

The function I used to alternate the moves between bot and human was as follows:
def player_choice(mover):

    placed = ''
    placed_2 = ''
    filled_cells = []

    if mover %2 !=0:
        while placed_2 == '':
            bot_choice = random.randint(0,8)
            print(f'(the bots choice was {bot_choice})')
            if bot_choice not in filled_cells:
                test[bot_choice] = 'O'
                placed_2 == "done"
                filled_cells.append(bot_choice)
                return True

    elif mover%2 == 0':
        while placed == '':
            p_choice = int(input('Please select cell from 1-9 : '))-1
            if test[p_choice] not in filled_cells:
                test[p_choice] = 'X'
                filled_cells.append(p_choice)
                placed == 'done'
                return True
            elif test[p_choice] in filled_cells:
                print('Sorry, that cell has been chosen, please select another')

My result looks as follows:


texts: Evaluating π using Monte Carlo methods - Serial vs OMP

texts:
I wrote this simple code for evaluating the π using Monte Carlo method. This is the serial version:

long double compute_pi_serial(const long interval) {

  srand(time(NULL));

  double x, y;
  int i, circle = 0;

  for (i = 0; i < interval; i ++) {
    x = (double)(rand() / (double) RAND_MAX);
    y = (double)(rand() / (double) RAND_MAX);

    if (pow(x,2) + pow(y, 2) <= 1.0) circle ++;
  }

  return (long double) circle / interval * 4.0;
}

After, I wrote a parallel version using OpenMP and this is the result:

long double compute_pi_omp(const long interval) {

  double x, y;
  int i, circle = 0;

  #pragma omp parallel private(x, y) num_threads(omp_get_max_threads())
  {

    srand(SEED);

    #pragma omp for reduction(+:circle)
    for ( i = 0; i < interval; i++ ) {
      x = (double)(rand() / (double) RAND_MAX);
      y = (double)(rand() / (double) RAND_MAX);

      if ( pow(x, 2) + pow(y, 2) <= 1 ) circle++;
    }
  }

  return (long double) circle / interval * 4.0;
}

This is an efficient method or there is a most efficient version always using OpenMP?


texts:
I am trying to solve this problem:

  Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

and this is my implementation:

public int searchInsert(int[] numbers, int target) {
    int startIndex = 0;
    int endIndex = numbers.length - 1;
    int midIndex;
    while (startIndex <= endIndex) {
        midIndex = (endIndex - startIndex) / 2 + startIndex;
        if(numbers[midIndex] == target)
            return midIndex;
        else {
            if(numbers[midIndex] > target) {
                if(midIndex <= 0 || numbers[midIndex - 1] < target) {
                    return midIndex;
                }
                endIndex = midIndex - 1;
            }
            else {
                if(midIndex >= numbers.length - 1 || numbers[midIndex + 1] > target) {
                    return midIndex + 1;
                }
                startIndex = midIndex + 1;
            }
        }
    }
    return -1;
}

How can I make it more efficient?


texts: How can I improve this code without using static or singleton?

texts:
I used to use static or singleton for my DAL class. However, I read some articles saying that singleton is evil and should be avoided. Therefore I try to rewrite my code like this:

public class CustomerBLL
{
    private CustomerHelper helper = new CustomerHelper();
    private CustomerDAL dal = new CustomerDAL();

    public void Method1(string param)
    {
        dal.Method1(param);
    }

    public void Method2(string param)
    {
        dal.Method2(param);
    }

    public void MethodA(int param)
    {
        helper.MethodA(param);
    }
}

How do I improve this code?  It just doesn't look right.


texts: Drawing a word, with a box around one letter

texts:
I'm working on a draw function which needs to draw the word 'crux' in the center of the current view and then draw a red box around the 'x' character like this:

My code to do this looks like this

override func draw(_ rect: CGRect) {

    guard let context = UIGraphicsGetCurrentContext() else { return }

    // Flip the coordinate system
    context.textMatrix = .identity
    context.translateBy(x: 0, y: bounds.size.height)
    context.scaleBy(x: 1.0, y: -1.0)

    // Create the logo as an attributed string
    let font = UIFont(name: "EntangledPlainBRK", size:self.bounds.size.width * 0.4)!
    let attrs:[String:Any] = [
        kCTForegroundColorAttributeName as String: UIColor.black.cgColor,
        kCTFontAttributeName as String: font
    ]
    let logo = NSMutableAttributedString(string: "crux", attributes: attrs)

    // Work out the position of the logo in the view.
    let path = CGMutablePath()
    let textSize = logo.size()
    let logoOrigin = CGPoint(x: (rect.width - textSize.width) / 2.0, y: (rect.height - textSize.height) / 2.0)
    let logoRect = CGRect(origin: logoOrigin, size: logo.size())
    path.addRect(logoRect)

    // get the frame setters.
    let framesetter = CTFramesetterCreateWithAttributedString(logo as CFAttributedString)
    let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, logo.length), path, nil)

    CTFrameDraw(frame, context)

    // Set the text position of the context to the location of the run on screen.
    var lineOrigins = [CGPoint] (repeating: .zero, count: 1)
    CTFrameGetLineOrigins(frame, CFRange(), &lineOrigins)
    let lineOrigin = lineOrigins[0]
    context.textPosition = CGPoint(x:logoOrigin.x + lineOrigin.x, y:logoOrigin.y + lineOrigin.y)

    // Get the position of the last character.
    let lines = CTFrameGetLines(frame)
    let line = unsafeBitCast(CFArrayGetValueAtIndex(lines, 0), to:CTLine.self)
    let runs = CTLineGetGlyphRuns(line)
    let run = unsafeBitCast(CFArrayGetValueAtIndex(runs, 0), to:CTRun.self)
    let glyphPosition = CTRunGetImageBounds(run, context, CFRange(location:3, length:1))

    // Draw a box around it.
    context.setStrokeColor(UIColor.red.cgColor)
    context.setLineWidth(2.0)
    context.stroke(glyphPosition)

}

It took some time to work out and feels a bit messy. I was wondering if there are any Core Text experts out there who know some tricks to shorten this code.


texts: Recursively listing the content of an FTP server

texts:
Today I found myself in need of programmatically getting a recursive list of the files on a remote FTP server to look for some data archives. Much to my surprise, I could not find this functionality implemented in some kind of Python library. So I decided to write a simple recursive version of ftplib.mlsd, that can be found below:

ftphelper.py

def recursive_mlsd(ftp_object, path="", maxdepth=None):
    """Run the FTP's MLSD command recursively

    The MLSD is returned as a list of tuples with (name, properties) for each
    object found on the FTP server. This function adds the non-standard
    property "children" which is then again an MLSD listing, possibly with more
    "children".

    Parameters
    ----------
    ftp_object: ftplib.FTP or ftplib.FTP_TLS
        the (authenticated) FTP client object used to make the calls to the
        server
    path: str
        path to start the recursive listing from
    maxdepth: {None, int}, optional
        maximum recursion depth, has to be >= 0 or None (i.e. no limit).

    Returns
    -------
    list
        the recursive directory listing

    See also
    --------
    ftplib.FTP.mlsd : the non-recursive version of this function
    """
    if maxdepth is not None:
        maxdepth = int(maxdepth)
        if maxdepth < 0:
            raise ValueError("maxdepth is supposed to be >= 0")

    def _inner(path_, depth_):
        if maxdepth is not None and depth_ > maxdepth:
            return

        inner_mlsd = list(ftp_object.mlsd(path=path_))
        for name, properties in inner_mlsd:
            if properties["type"] == "dir":
                rec_path = path_+"/"+name if path_ else name
                res = _inner(rec_path, depth_+1)
                if res is not None:
                    properties["children"] = res

        return inner_mlsd

    return _inner(path, 0)

A very basic example usage could be like:

import ftplib
import getpass
import pprint
import sys

import ftphelper

host = "ftp1.at.proftpd.org"   # from the Python docs
directory = "historic"
print(f"Login to '{host}' to list '{directory}'", file=sys.stderr)

default_user = ""   # getpass.getuser() could also be used where appropriate
prompt = f"Username (default: '{default_user}'): "
if sys.stdout.isatty():
    user = input(prompt)
else:
    print(prompt, end="", file=sys.stderr)
    user = input()
user = user.strip()
user = user if user else default_user

with ftplib.FTP(host=host) as ftp:
    ftp.login(user=user, passwd=getpass.getpass())
    listing = ftphelper.recursive_mlsd(ftp, directory)

pp = pprint.PrettyPrinter(indent=2)
pp.pprint(listing)

As always, every kind of feedback is welcome and much appreciated.


texts: Check divisibility of each line in a large dataset

texts:
I have solved this assignment in online coding community, and it has run successfully. But it's showing 12.09s of execution.
How could this be optimized ?

The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer t(i), not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers t(i) are divisible by k

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

class InputTest{

public static void main(String args[]) throws Exception{

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String arr[]=br.readLine().split(" ");
    int n=Integer.parseInt(arr[0]);
    int k=Integer.parseInt(arr[1]);
    int count=0;

    if(n<=0 || k<=0 || k>Math.pow(10,7)){
        throw new Exception();
    }
    else{

        for(int i=0;i<n;i++){
            int m=Integer.parseInt(br.readLine());
            if(m>Math.pow(10,9))
                throw new Exception();
            if(m%k==0)
                count++;

        }
        System.out.println(count);
    }

}
}


texts:
I'm working on interfacing some older positioning equipment with an arduino, but having done the majority of my work with higher level language I'm having trouble adjusting to the limitations of AVR-GCC.

I basically have two questions: Is this a good way to parse out the strings? What can I do to optimize this code for an embedded platform?

// this is in the global scope of my program. normally accepted as bad code,
// but it seems to make sense in the context of an embedded platform.
// "global" cache
int data[10];

void getPosition(){
    // position message is always less than 25 bytes with null termination characters
    byte bufferIndex = 0;
    char buffer[25];

    // read the position command from the serial port
    // should look like:
    //      D20BIX+00733Y+00080S99\r\n
    //
    // and we need the X+00000 and Y+00000 parts
    //
    if (Serial.available() > 0){
        while (Serial.available() > 0 && bufferIndex < 25){
            buffer[bufferIndex] = Serial.read();

            if (buffer[bufferIndex++] == '\n'){
                buffer[bufferIndex] = '\0';
                break;
            }
        }

        Serial.flush();

        // check to see if we have good orientation on the buffer by
        // checking for lines starting with model identifier 'D'
        String input = String(buffer);

        if (buffer[0] == 'D' && bufferIndex <=24){
            int x_result = data[1];
            int y_result = data[4];
            String check;
            char token_buffer[8] = {'0', '0', '0', '0', '0', '0', '0', '0' };

            // scan for x, target token is X+00000
            String x_token = input.substring(5, 11);
            check = x_token.substring(2, 6);
            check.toCharArray(token_buffer, 8);

            x_result = atoi(token_buffer);
            if (x_token[1] == '-'){
                x_result *= -1;
            }

            // scan for y, target token is Y+00000
            String y_token = input.substring(12, 18);
            check = y_token.substring(2, 6);
            check.toCharArray(token_buffer, 8);

            y_result = atoi(token_buffer);
            if (y_token[1] == '-'){
                y_result *= -1;
            }

            // finalize results
            data[1] = x_result;
            data[4] = y_result;
        }
    }
}


texts: A linked list with push pop append and destructor

texts:
I tried to implement a linked list that can do pop(), push(), append(), printall(), and so on, and also I tried to handle the wraparound features, and de-wrap it when check if the list is cyclic to avoid endless loop, but I am sure this wrap and de-wrap features can be implemented better...

#include <iostream>

struct Node{
    int value;
    Node* next;
};

class LinkedList{

    std::size_t count;
    Node* head;

    public:
    void pop();           //pop from head
    void push(int);       //push from head
    void append(int);     //append at end
    void wraparound();    //wrap around the list
    bool isCyclicDwrap(); //check if cyclic, if yes, de-wrap-around it

    void printll() const;
    std::size_t size() const { return count; }

    LinkedList(): head(nullptr),count(0) {}
    ~LinkedList();
};

void LinkedList::pop(){

  if(head==nullptr){
    std::cout<<"empty stack !"<<std::endl;
    exit(0);
  }

  Node* cur = head;
  Node* tmp = cur->next;
  head = tmp;
  delete cur; count--;

}

void LinkedList::append(int data){
    Node* cur = head;
    Node* tmp = new Node;
    tmp->value = data;
    tmp->next = nullptr;

    if(!cur){
        head = tmp; count++;
    }
    else{
        while(cur->next != nullptr){
            cur = cur->next;
        }
        cur->next = tmp; count++;
    }

}

void LinkedList::wraparound(){
    Node* cur =head;
    while(cur->next != nullptr)
        cur=cur->next;

    cur->next = head;
}

bool LinkedList::isCyclicDwrap()
{
    Node *n1, *n2;
    n1 = head;
    n2 = head->next;

    do{
        n1 = n1->next;
        n2 = n2->next->next;

        if(n1 == n2){

            Node* cur =head;
            size_t cnt=count;
            while(--cnt != 0)
                cur=cur->next; //move to the last node
            cur->next=nullptr; // -> de-warp-around !

            return true;
        }

    }while(n1 != head);

    return false;
}

void LinkedList::push(int data)
{
    Node* cur = (Node*)malloc(sizeof(Node));
    cur->value=data;
    cur->next=head;
    count++;
    head=cur;
}

void LinkedList::printll() const{
    if(head==nullptr)
        std::cout<<"empty Linkedlist!"<<std::endl;
    Node* cur = head;
    while(cur != nullptr){
        std::cout << cur->value << '\n';
        cur = cur->next;
    }
}

LinkedList::~LinkedList()
{
    Node* cur = head;

    while (cur != NULL)
    {
        Node* next = cur->next;
        delete cur;
        cur = next;
    }

    head = NULL;
}

int main(){
    LinkedList LL;
    LL.append(5);
    LL.append(6);
    LL.append(7);
    LL.printll();
    std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;

    LL.wraparound();
    std::cout<<"Cyclic: "<<LL.isCyclicDwrap()<<"; if 1, then remove the Cyclic feauture!"<<std::endl;

    LL.push(4); //push
    LL.printll();
    std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;

    LL.pop();
    LL.printll();
    std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;

    LL.pop();
    LL.printll();
    std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;

    LL.pop();
    LL.printll();
    std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;

    LL.pop();
}