texts: Stack that does Push, Pop and Median in O(1)

texts:
Here are two implementation of a stack that does Push, Pop and Median in O(1). Invite comments on complexity and betterment.

  Option - 1

public class MedianStack {

    private Deque<Integer> stack;
    private PriorityQueue<Integer> minHeap;
    private PriorityQueue<Integer> maxHeap;

    public MedianStack(){
        stack = new ArrayDeque<>();
        minHeap = new PriorityQueue<>();
        maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    }
    public void push(int item){
        stack.offerFirst(item);
        minHeap.add(item);
        maxHeap.add(item);
    }
    public int pop(){
        int item = stack.poll();
        minHeap.remove(item);
        maxHeap.remove(item);
        return item;
    }

    public int median(){
        return (minHeap.peek() + maxHeap.peek())/2;

    }
}

  Option - 2

Modified and added after realizing the first implementation was not correct.

public class MedianStack {

    private Deque<Integer> stack;
    private MedianHeap medianHeap;

    public MedianStack(){
        stack = new ArrayDeque<>();
        medianHeap = new MedianHeap();

    }
    public void push(int item){
        stack.offerFirst(item);
        medianHeap.add(item);

    }
    public int pop(){
        int item = stack.poll();
        medianHeap.remove(item);
        return item;
    }

    public int median(){
        return medianHeap.median();
    }
}

Median Heap Implementation

public class MedianHeap {

    private PriorityQueue<Integer> maxHeap;
    private PriorityQueue<Integer> minHeap;

    public MedianHeap(){
        maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        minHeap = new PriorityQueue<>();
    }

    public void add(int item){
        if(isEmpty()) minHeap.add(item);
        else{
            if(Integer.compare(item, median()) >= 0) minHeap.add(item);
            else maxHeap.add(item);
        }
        balance();
    }

    public boolean isEmpty(){
        return maxHeap.size() == 0 && minHeap.size() == 0;
    }
    public void balance(){
        if(Math.abs(maxHeap.size() - minHeap.size()) > 1){
            if(minHeap.size() > maxHeap.size()){
                maxHeap.add(minHeap.poll());
            }else minHeap.add(maxHeap.poll());

        }
    }
    public void remove(int item){
        if(!minHeap.contains(item) || !maxHeap.contains(item)) throw new IllegalStateException("Illegal item removal");
        if(minHeap.contains(item)) minHeap.remove(item);
        else maxHeap.remove(item);
        balance();
    }

    public int median(){
        if (minHeap.size() == maxHeap.size()) return (maxHeap.peek() + minHeap.peek())/2;
        else if(minHeap.size() > maxHeap.size()) return minHeap.peek();
        else return maxHeap.peek();
    }
}


texts:
My goal is to parse this CSV data:

Time,Tank,Product,Volume,TC Vol,Ullage,90 Ul,Height,Water,Temp
2017-10-19T18:52:41.118408,1,UNLEADED,4406,4393,7221,6058.3,37.49,0,64.15
2017-10-19T18:52:41.118408,3,SUPER,8317,8278,3310,2147.3,61.4,0,66.74
2017-10-19T18:52:41.118408,4,ADSL2,6807,6774,4820,3657.3,51.98,0,70.46
2017-10-19T18:53:13.894066,1,UNLEADED,4406,4393,7221,6058.3,37.49,0,64.15
2017-10-19T18:53:13.894066,3,SUPER,8313,8273,3314,2151.3,61.37,0,66.74
2017-10-19T18:53:13.894066,4,ADSL2,6805,6772,4822,3659.3,51.97,0,70.46

Given the a list of Tank numbers, a primary key, and a data column:

>>>tank_numbers = [1, 3]
>>>primary_key = 'Time'
>>>data_column = 'Volume'
>>>
>>>parse_csv('csv_file.csv', tank_numbers, primary_key, data_column)

[
  {'Time': '2017-10-19T18:52:41.118408', 'UNLEADED': '4406', 'SUPER': '8317'}
  {'Time': '2017-10-19T18:53:13.894066', 'UNLEADED': '4406', 'SUPER': '8317'}
]

I have a few questions about the following code;

Using only the standard library, is there a more simple way?
What I have seems like too much just to get the needed information.
Should I be breaking up the parse_csv function into smaller pieces similar
to _parse_csv_to_dicts and _get_tank_names.

import csv

def _parse_csv_to_dicts(file):
    with open(file, 'r') as f:
        return list(csv.DictReader(f))

def _get_tank_names(tanks=None, data=None):
    names = list()
    for n in tanks:
        for tank_dict in data:
            if tank_dict['Tank'] == str(n):
                names.append(tank_dict['Product'])
                break
    return names

def parse_csv(file, tanks, primary_key, data_key):
    """
    :param file: The raw csv data file
    :param tanks: A list of tank numbers, as labeled in the raw csv
    :param key: a list of the keys needed from the raw csv
    :return: a list of dictionaries
    """
    d1 = _parse_csv_to_dicts(file)

    # Remove unneeded tanks from data
    d2 = [row for row in d1 if int(row['Tank']) in tanks]

    # Remove unneeded keys from rows
    keys = [primary_key, data_key, 'Product']
    d3 = [{key:row[key] for key in keys} for row in d2]

    # Create new row template
    tank_names = _get_tank_names(tanks=tanks, data=d1)
    row_template = {key:None for key in (tank_names + [primary_key])}

    # New rows from row template
    d4 = []
    for row in d3:
        # update new row with available keys
        new_row = {key:row.get(key) for key in row_template}

        # update new row with matching values
        for key in new_row:
            if key in row.values():
                new_row[key] = row[data_key]

        # remove keys with None value
        new_row = {k:v for k,v in new_row.items() if v is not None}
        d4.append(new_row)

    # Merge all rows based on Time key
    merged = {}
    for row in d4:
        if row[primary_key] in merged:
            merged[row[primary_key]].update(row)
        else:
            merged[row[primary_key]] = row

    return [value for value in merged.values()]


texts:
I'm making a simple 2D framework / engine for the first time based on two books and before the project gets too big I would like to know if I'm ordering things the right way. Maybe there are better ways of doing this. I tried to apply patterns so I could decouple as much as possible and keep things abstract.
For example this is the Game class:
#include "Game.h"

void Game::Create(int width, int height, const char * title, int window_flag, int renderer_flag){
      display.CreateWindow(800,600,"Game", SDL_WINDOW_SHOWN, SDL_RENDERER_ACCELERATED);
}

void Game::Start(){
      Uint32 first_frame_ticks; float delta_time = 0;
      SDL_Renderer * renderer = display.GetRenderer();
      while(input_handler.GetLastEvent() != SDL_QUIT){
            first_frame_ticks = SDL_GetTicks();

            bool state_manager_empty = state_manager.isEmpty();
            //update
            input_handler.Update();
            if(!state_manager_empty) state_manager.GetGameState()->onUpdate(delta_time);

            //render
            SDL_RenderClear(renderer);
            if(!state_manager_empty) state_manager.GetGameState()->onRender();
            SDL_RenderPresent(renderer);

            delta_time = (SDL_GetTicks() - first_frame_ticks) / 1000.0f;
      }

      display.Clear();
}

void Game::AddState(GameState* state){
      state->Set(display.GetRenderer(), &input_handler);
      state_manager.Add(state);
}

Or the Drawer class (wich I have some doubts about, the DrawEntity method is static)
#include "Drawer.h"

void Drawer::DrawEntity(Entity& entity, TextureManager* texture_manager, SDL_Renderer * renderer){
      texture_manager->Draw(entity.GetSprite(), entity.GetPosition(), renderer);
}

It acts like a mediator between TexureManager(wich draws texures) and Entity wich has all the information like position, scale, etc.
Finally the example input class
#include "InputHandler.h"
#include <cstdio>

InputHandler::InputHandler(){
      keyboard_state = SDL_GetKeyboardState(NULL);
      printf("Event handler initialized\n");
}

void InputHandler::Update(){
      SDL_Event ev;
      while(SDL_PollEvent(&ev)){
            if(ev.type == SDL_KEYUP || ev.type == SDL_KEYDOWN){
                  keyboard_state = SDL_GetKeyboardState(NULL);
            }else last_event = ev.type;
      }
}

bool InputHandler::isKeyPressed(SDL_Scancode key){
      if(keyboard_state[key]) return true;
      else return false;
}

Uint32 InputHandler::GetLastEvent(){
      return last_event;
}

I'm going to upload a dependency diagram as well as the GitHub repo:

Github Repo with all the Code
https://github.com/grazianobolla/monke-engine


texts:
I have this function which takes a list as input and computes the powerset.

let rec powerset = function
    | []    -> [[]]
    | x::xs -> List.collect (fun subset -> [subset; x::subset]) (powerset xs)

let ps = powerset [1..3]
val ps: int list list =
[[]; [1]; [2]; [1; 2]; [3]; [1; 3]; [2; 3]; [1; 2; 3]]

Is there a cleaner way to do it? I'm also a little confused by how it actually works. List.collect takes a function and a list and concats the results into a new list, which is then returned. But I have a little trouble following the flow in this case.

Why is the first list empty?


texts:
I want inputs on how I can square the sorted Array more efficiently in haskell. I wrote a very naive algorithm to solve the problem. What I am doing is comparing the head and the last element of list on absolute value and whichever is max I square the element and add it to accumulator.

But I think it is very slow. Is there any data structure that I can use to make it more efficient.

import qualified Data.List as List

sqrarr:: [Int] -> [Int]
sqrarr xss = helper  xss []

helper::[Int] -> [Int] -> [Int]
helper  [] acc = acc
helper [x] acc = [(x^ 2)] ++ acc
helper (x:xss) acc = case abs x > abs (List.last xss) of
  False -> helper (x: (List.init xss)) (((List.last xss)^2): acc)
  True -> helper xss ((x ^ 2):acc)

The above code works and gives the desired input

sqrarr [-7, -4, 2,5,8]
[4,16,25,49,64]

I have found another solution

import Data.Array
sqrarr2::[Int] -> [Int]
sqrarr2 xss = helper2 0 (length xss -1)
                (listArray (0,(length xss -1)) xss)
                []

helper2::Int -> Int -> Array Int Int -> [Int] -> [Int]
helper2 l r arr acc = case l > r of
  True -> acc
  False -> case abs (arr!l) > abs (arr!r) of
    False -> helper2 l (r - 1) arr ((arr!r ^ 2):acc)
    True -> helper2 (l + 1) r arr ((arr!l ^ 2):acc)


texts:
I want to determine a path (x and y coordinates) by using curvature data (radius, with constant distance (length_of_arc) travelled between data points. I want to repeat this calculation every 0.010 seconds and visualize the points in pyhon kivy (at the moment a raw calculation takes 0.006 - 0.014 seconds).

Assume sample data

radius = [68.96551724, 69.73500697, 71.78750897, 75.98784195, 81.96721311, 90.74410163, 102.6694045, 120.0480192,
          146.1988304, 187.9699248, 265.9574468, 458.7155963, 1694.915254, -1020.408163, -393.7007874, -244.4987775]

This is the code (inside a class) that I use to calculate the coordinates. Is there a way to increase performance / readability of the code. It is important to note that performance has higher priority.

EDIT: I already tried small angle approximation (sin x \approx x, cos x \approx 1 - 0.5 x^2) but that did only lead to insignificant changes.

# positive curvature is a right bend, negative curvature is a left bend
# scale_factor: used to scale the values for plotting them
# initial_displacement_x and initial_displacement_y: values are displaced such that the plot is in the Center of the screen.
@staticmethod
def calculate_coordinates_from_length_of_arc_and_radius(_radius, length_of_arc, scale_factor,
                                                    initial_displacement_x, initial_displacement_y):
    phi = 0  # accumulation of angle
    number_of_data_points = len(_radius)
    x_accumulated = number_of_data_points * [0]
    y_accumulated = number_of_data_points * [0]
    track_coordinates = 2 * number_of_data_points * [0] # x,y alternating needed for ploting values as line in python kivy

    for data_point in range(number_of_data_points - 1):
        delta_phi = - length_of_arc / _radius[data_point]
        phi = phi + delta_phi
        dx = - _radius[data_point] * (cos(delta_phi) - 1)
        dy = - _radius[data_point] * sin(delta_phi)

        if data_point != 0:
            dx_rotated = cos(phi) * dx - sin(phi) * dy # apply rotation matrix
            dy_rotated = sin(phi) * dx + cos(phi) * dy # apply rotation matrix
        else:
            dx_rotated = dx  # the displacements are not rotated
            dy_rotated = dy  # for the first data point

        x_accumulated[data_point + 1] = x_accumulated[data_point] + dx_rotated
        y_accumulated[data_point + 1] = y_accumulated[data_point] + dy_rotated
        track_coordinates[2 * data_point + 2] = scale_factor * (x_accumulated[data_point] + dx_rotated)
        track_coordinates[2 * data_point + 3] = scale_factor * (y_accumulated[data_point] + dy_rotated)

    for data_point in range(len(track_coordinates)):
        if data_point % 2:
            track_coordinates[data_point] = track_coordinates[data_point] + initial_displacement_x
        elif not data_point % 2:
            track_coordinates[data_point] = track_coordinates[data_point] + initial_displacement_y
    return track_coordinates


texts: Laravel 5.3 model for mapping pages to multilingual translations

texts:
I have a Many To Many Polymorphic Relation like this:

pages
    id - integer
    name - string

products
    id - integer
    name - string

languages
    id - string ('it', 'en', 'de', 'es', etc.)
    name - string ('Italiano', 'English', 'Deutsch', 'Espanol', etc.)
    icon

translations
    language_id - string
    item_id - integer
    item_type - string ('App\Page', 'App\Product', etc.)
    ...

On my Page (or Product) Model, I have methods like this:

public function translations()
{
    return $this->morphMany('App\Translation', 'item')
        ->select('translations.*', 'languages.icon', 'languages.name')
        ->join('languages', 'languages.id', '=', 'translations.language_id')
        ->orderBy('languages.position');
}

public function languages()
{
    return $this->morphToMany('App\Language', 'item', 'translations')->orderBy('languages.position');
}

So far so good: for each Page (or Product) I can retrieve their respective Translations.

Now comes the tricky part: for each Page (or Product) I need to retrieve also missing translations, so that user knows that some items still must be translated; so, if I have 'it' and 'en' translations for my Page #1, I need to retrieve 'de' and 'es' languages

So I create a ModelTrait with this:

public function _morphToMissing($related, $name, $table = null, $foreignKey = null, $otherKey = null, $inverse = false)
{
    $relation = $this->morphToMany($related, $name, $table, $foreignKey, $otherKey, $inverse);
    $current = $relation->getRelatedIds();
    $object = new $related;
    return $object->whereNotIn('id', $current)->get();
}

And updated my Model(s) with another method:

public function missing()
{
    return $this->_morphToMissing('App\Language', 'item', 'translations');
}

And my view(s) accordingly:

@foreach($records as $item)
<li>{{ $item->missing()->count() ? 'There are missing translations!' : 'Translations completed' }}</li>
@endforeach

It works, and it works fine, but seems that I have a huge amounts of database queries! That's because the _morphToMissing() method is doing a over-job:

find the existing translations' languages (a query here)
find the missing languages (another query here)

Maybe it's a dumb question, but is there a way to reduce the numbers of queries, or some other way to improve performance? At last, I'd need to compare the # of available languages with the # of translations for a given item...


texts:
The following code is for a calculator made in ruby, I find that this way saves much time than having to build this calculator from scratch, especially that I want it to support BEMDAS operations. However, I'm feeling that it is inefficient because I'm using eval, and I think this could be dangerous.
Is it a good idea to use this in a real life application?

include Math
puts "enter an expression:"
input =  gets.chomp
begin
    result = eval(input)
    if (result.is_a? Numeric)
        puts result
    else
        puts "syntax error"
    end
rescue Exception
end


texts: Compare two tables and arrange the values in a new array

texts:
I have t things working with this current setup:

Route::get('test', function(){
    $finished = \App\Progress::select('stack_id')->get();
    $unfinished = \App\Stack::select(['id as stack_id'])->get();

    foreach ($unfinished as $key => $value) {
        if(!isset($finished[$key])){
            break;
        }
        if($value->stack_id == $finished[$key]->stack_id){
            unset($unfinished[$key]);
        }
    }
    return response()->json(['finished' => $finished->flatten(), 'unfinished' => $unfinished->flatten()]);
});

Two current values in progresses table and three values in stacks table

Progresses

id user_id stack_id
6   1   1
9   1   2

Stacks

id
1
2
3

The response:

{
"finished": [
{
"stack_id": 1
},
{
"stack_id": 2
}
],
"unfinished": [
{
"stack_id": 3
}
]
}

Can this be done in another, more efficient way?


texts: Input memory buffer exceeding situation handling

texts:
Please review the following code:

static int md5_encode(const char *  input_md5  , char *  output  , int size)
{
  // checking pre-requisits //
  if( output == NULL || input_md5 == NULL || size == 0)
  {
   printf( "main.cpp:md5_encode() error check for the prerequisites. \n");
   exit(0);
  }

  int input_length = strlen(input_md5);

  // null terminate the output first //
  output[0] = 0;
  char * buffer [10];

  for (int i=0; i<input_length,i++)
  {
    char current_char = input_md5 [i];
    // encode it //
    strcat(output,"uc");
    sprintf(buffer,"%d",current_char);
    strcat(output,buffer);

  }
  // check for the buffer overflow condtions //
  // if something goes out of the buffer then assert //
  if(size < strlen(output) )
  {
    printf("Warning: Possible buffer-overflow\n");
    return 0;
  }

  // return on success //
  return 1;
}

As you can see, what this does is to encode an md5 string into ucuc format. The output buffer is allocated by the caller and its size and address are passed as parameters.

The function just writes to the output buffer with 'strcat()' without any checking. Then afterwards it checks whether 'size' is less than the amount that was written. If it exceeds the limit, then the function gives an error message.

Any more suggestions than just a warning message? How could I improve this?


texts: Looks at order data and arranges it to focus on order locations

texts:
I have a sheet that order a bunch of information on individual orders. Order numbers are in column A, other information is in columns B-P, and then product numbers are the headers for columns Q-DL. The cells within the order number and product number contains an integer that corresponds to the location that product is placed.

My code creates a new sheet that loops through all of these rows and then each cell within the row and compares it to headers of the new sheet which contain the location numbers.
If a cell matches the location header, it puts a 1 in the corresponding cell of the new sheet to indicate that product is needed from that location and a 0 if it does not match.

My code works, but it works very slow. So advice on how to make it faster would be appreciated.

Sub PopulateData()
    Dim s1 As Worksheet: Dim s2 As Worksheet
    Dim rng As Range: Dim rng2 As Range
    Dim cell: Dim header

    With Application
        .ScreenUpdating = False
    End With

    With ThisWorkbook
        Set s1 = .Sheets("OrderLvl")
        Set s2 = .Sheets("sheet1")
    End With
    With s1
        Set rng = Range(.Cells(4, 16), .Cells(.Cells(Rows.Count, 116).End(xlUp).row, 116))
    End With
    Set rng2 = Range(s2.Cells(3, 2), s2.Cells(3, 265))

    For Each cell In rng.Cells
        For Each header In rng2.Cells
            If cell.Value = 0 Then

            ElseIf cell.Value <> header.Value And s2.Cells(cell.row, header.Column).Value <> 1 Then
                s2.Cells(cell.row, header.Column).Value = 0
            Else
                s2.Cells(cell.row, header.Column).Value = 1

            ' indicates that this order features a line from this location
            End If
        Next header
    Next cell
    With Application
        .ScreenUpdating = True
    End With
End Sub


texts:
Is this a correct method of Fibonacci with recursion?

function fibb($limit,$first_numer=0,$second_number=1){
        echo $first_numer."\n";
        echo $second_number."\n";
        if($limit > 0){
            fibb($limit-2,$first_numer+$second_number,($first_numer+$second_number+$second_number));
        }
}


texts:
Here is my simple ticketing system:

 <?php
        session_start();
        session_id();
        ob_start();
        require("../configuration/config.php");
        $GetTickets = $con->query("SELECT * FROM tickets WHERE open='true'");
        if(!$_SESSION['Admin']) {
        header('Location: login.php'); exit();
        }
        ?>
        <!DOCTYPE HTML>

            <title> ticketExpress | Admin </title>
            <link rel='stylesheet' href='../assets/css/style.css'>

  Logout

 Open Tickets

        <?php
        while($TicketInfo = $GetTickets->fetch_object()) {
        $Subject = $TicketInfo->Subject;
        if(strlen($Subject)>50) {
            $Subject = substr($Subject,0,50)."...";
        } else {
        $Subject = $TicketInfo->Subject;
        }
        echo "
".$Subject ."ID'>ID'> Close
";
        }
        if(isset($_GET['delete'])) {
        $ID = $_GET['delete'];
        echo "

            ";
        }
        if(isset($_GET['logout'])) {
        session_destroy();
        header('Location: login.php');
        }
        if(isset($_GET['close'])) {
        $ID = $_GET['close'];
        echo "

            ";
        }
        ?>

Could you give me tips on improving the performance of my script? I've noticed that it takes some time to receive a response, so performance can definitely be further improved. I've been doing PHP for the last 8 months or so and am still a newbie.


texts: Merge sort implementation: sorting feels clunky

texts:
I got bored and decided to make a merge sort from scratch.  I like everything, except for my "merging" of the two arrays into a sorted array inside the for loop.  I had several bugs that I had to iron out, which were along the lines of if subArray1 or subArray2 ran out of elements, checking them caused ArrayOutOfBoundsException.  This prompted me to add the two ifs above the sorting to finish the sorting.

Is there a better / less clunky way to "merge" the two arrays together?

import java.util.Arrays;
import java.util.Random;

public class MergeSort {

    public static void main(String[] args) {

        Random random = new Random();
        int max = 10000;
        int arr[] = new int[max];

        for (int i=0; i < max; i++) {
            arr[i] = random.nextInt(2147483647);
        }

        System.out.println("boop!");
        long start = System.currentTimeMillis();
        arr = merge(arr).clone();
        long end = System.currentTimeMillis();

        System.out.println("it took " + (end - start) + " milliseconds");
        System.out.println(Arrays.toString(arr));

    }

    public static int[] merge(int[] array) {

        int maxIndex = array.length;
        int halfIndex = (array.length) / 2;

        // if the array was split into one
        if (array.length <= 1) {
            return array;
        }

        int[] subArray1;
        int[] subArray2;
        int[] sorted;

        subArray1 = Arrays.copyOfRange(array, 0, halfIndex);
        subArray2 = Arrays.copyOfRange(array, halfIndex, maxIndex);

        subArray1 = merge(subArray1);
        subArray2 = merge(subArray2);

        sorted = new int[subArray1.length + subArray2.length];

        int index1 = 0, index2 = 0;
        for (int i = 0; i < sorted.length; i++) {

            // if subArray1 ran out of elements
            if (index1 == subArray1.length) {
                for (; i < sorted.length; i++) {
                    sorted[i] = subArray2[index2++];
                }

                break;
            }

            // if subArray2 ran out of elements
            if (index2 == subArray2.length) {
                for(; i < sorted.length; i++) {
                    sorted[i] = subArray1[index1++];
                }

                break;
            }

            if (subArray1[index1] <= subArray2[index2]) {
                sorted[i] = subArray1[index1++];
                continue;
            }

            if (subArray1[index1] > subArray2[index2]) {
                sorted[i] = subArray2[index2++];
                continue;
            }

        }
        return sorted;

    }


texts:
I need to turn a lot of html elements as editable elements. You will double click on the element to edit, press enter to validate (send a PUT to the RESTapi), press esc to undo.

I've written this piece of code. Are there any performance improvements to be made?

var editable = (function() {

    var DELAY = 300,
        clicks = 0,
        timer = null;

    var addEditDelegateEvents = function(element, selector, url, idInUrl, idAttr, ajaxAttr) {
        // disable the double click, and handle it in the single click envent
        element.on("dblclick", selector, function(event) {
            event.preventDefault();
        });
        element.on("click", selector, function(event) {
            event.preventDefault();
            var href = $(this).attr('href');
            clicks++; //count clicks

            if (clicks === 1) { // single click action
                timer = setTimeout(function() {
                    // For some browsers, `attr` is undefined; for others,
                    // `attr` is false.  Check for both.
                    if (typeof href !== typeof undefined && href !== false) {
                        window.location = href // follow hlink
                    };
                    clicks = 0; //after action performed, reset counter
                }, DELAY);

            } else { //double click action
                clearTimeout(timer); //prevent single-click action
                // double click action
                //transform the double clicked element into an <input>
                var originElement = $(this);
                var editElement = $(document.createElement('input'));
                editElement.val(originElement.text());
                originElement.replaceWith(editElement);
                editElement.focus();
                id = originElement.attr(idAttr);
                url = url.replace(idInUrl, id); //replace idInUrl in url by id

                editElement.on("keypress", function(event) {

                    if (event.which == 13) {
                        //send ajax call then re-populate the list
                        var newVal = editElement.val();
                        var obj = {};
                        obj[ajaxAttr] = newVal;
                        $.ajax({
                            method: "PUT",
                            url: url,
                            data: JSON.stringify(obj),
                            contentType: "application/json; charset=utf-8",
                            success: function(data) {
                                console.log('sheet updated');
                                // Very careful here : the RESTapi should return a JSON
                                // with the updated infos
                                originElement.text(data[ajaxAttr]);
                                editElement.replaceWith(originElement);

                            },
                            error: function() {
                                console.log('error on sheet update');
                                editElement.replaceWith(originElement);
                            }
                        });
                    }
                    if (event.which == 27) {
                        editElement.replaceWith(originElement);
                    }
                });
                clicks = 0; //after action performed, reset counter
            }

        });

    };
    // public API
    return {
        addEditDelegateEvents: addEditDelegateEvents
    }
})();

And I will register my events as:

editable.addEditDelegateEvents($("p.editable_sheet_date_end"), "span", "/api/v1/sheets/ID/update", "ID", "sheet_id", "end");

I'm aware of the weakness of my implementation of url,idInUrl,idAttr, ajaxAttr.

But my question is rather: is this a solid design? My primary goal is the speed (loading and interactions).

I will have around 1000 delegates to deal with.


texts: Calculating factorial using Stirling's approximation

texts:
I've used Stirling's approximation to compute a factorial but I want to know if it is a cleaner and more concise way to solve this kind of problem.

Here is my code:

from numba import jit
from decimal import Decimal
from math import pi

getcontext().prec = 128

@jit
def stirling(n):
    return Decimal((2.0*n+1.0/3.0)*pi).sqrt()*Decimal(n**n)/Decimal(n).exp()

if __name__ == "__main__":
    print(stirling(255144))

Also , how can I get rid off decimal.Overflow error?


texts: Decrease Image downloading time with HttpURLConnection

texts:
This is piece of code is using to download images. Can somebody tell me how to optimize this code to decrease download time for each image?

        URL url;
        HttpURLConnection connection = null;
        InputStream input = null;
        System.setProperty("http.keepAlive", "true");
        try {
            url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);
            connection.setRequestProperty("Connection", "Keep-Alive");
            input = connection.getInputStream();
            return BitmapFactory.decodeStream(input);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            currentRequestInProgress.remove(urlString);
            if (connection != null)
                connection.disconnect();
            if(input != null){
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


texts: 3D plot from lm model with a nonlinear parameter

texts:
I am trying to plot a 3Dplot of a linear regression with two variables.

My linear model:

ls = lm(mpg ~ disp + qsec, data = mtcars)

The minimum and maximum values to predict:

mmd = min(mtcars$disp):max(mtcars$disp)
mmq = min(mtcars$qsec):max(mtcars$qsec)

The linear function:

flm = function(x1, x2) ( (ls$coefficients[1]) + (ls$coefficients[2] * x1) + (ls$coefficients[3] * x2))

The outer matrix:

t = outer(X = mmd, Y = mmq, FUN = flm)

The plot:

persp3D(z = t, ticktype = "detailed")

Now I would like to control for the non-linearity of the qsec parameter.

Is this the right way to do it?

ls = lm(mpg ~ disp + poly(qsec, degree = 2), data = mtcars)
mmd = min(mtcars$disp):max(mtcars$disp)
mmq = min(mtcars$qsec):max(mtcars$qsec)

flm = function(x1, x2) ( (ls$coefficients[1]) + (ls$coefficients[2] * x1) +
                           (ls$coefficients[3] * x2)
                         + (ls$coefficients[4] * x2)
                         )

t = outer(X = mmd, Y = mmq, FUN = flm)
persp3D(z = t, ticktype = "detailed")


texts: Convert JSON from a webservice to text file

texts:
I get list JSON text from a webservice and list_of_columns is predefined, I need the output in that format. I am not sure about few things which are as follows

I don't need "\n" towards the very end and this code seems sub-optimal to me but right now I can't think of any pythonic way to do it.
My order for the code should be defined by list_of_columns. I don't know if this I have done is the optimal way to do it.

All in all my code does the job but I want to improve more. I suspect I could have used something that's already present that would have been much easier from what I have done. I am here for some criticism and learning :)

NOTE: I have used csv module to do the same but since separator had to be 2 characters long I had to drop that idea.

For formatting I tried using strftime but since dates in the data were less than 1900, I had to drop that idea.
I think from what I have done with the date something better could have been done.

def read_json_text_write_text_file(json_text,file_name,list_of_columns,separator = "|~"):
    list_of_dictionaries = json.loads(json_text)

    with open(file_name, "w") as text_file:
        text_file.seek(0)
        for dictionary in list_of_dictionaries:
            for column in list_of_columns:
                if column in dictionary.keys():
                    if "DATE" in column:
                        text_file.write(convert_utc_to_est(dictionary[column]))
                    else:
                        text_file.write(str(dictionary[column]))
                if column != list_of_columns[-1]:
                    text_file.write(separator)
            if dictionary != list_of_dictionaries[-1]:
                text_file.write("\n")

def convert_utc_to_est(date_string):

    from_zone = dateutil.tz.gettz('UTC')
    to_zone = dateutil.tz.gettz('EST5EDT')

    utc = parser.parse(date_string)
    utc = utc.replace(tzinfo=from_zone)
    central = utc.astimezone(to_zone)
    # tzinfo is set to None else it would be present during the return
    central = central.replace(tzinfo=None)
    # This split is performed to remove the micro seconds part.
    return str(central).split(".")[0]


texts: Implementation of oil-painting filter for images

texts:
This is web exercise 3.1.14. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Set pixel (i, j) to the color of the most frequent value among pixels
with Manhattan distance W of (i, j) in the original image.

Here is my program:
import java.awt.Color;

public class OilPaintingFilter
{
    public static int findNumberOfPixels(int distance)
    {
        int numberOfPixels = 4;
        if (distance == 1) return numberOfPixels;
        int increment = 8;
        for (int i = 2; i <= distance; i++)
        {
            numberOfPixels += increment;
            increment += 4;
        }
        return numberOfPixels;
    }
    public static Color[] findNeighboringColors(Picture picture, int col, int row, int distance)
    {
        int width = picture.width();
        int height = picture.height();
        Color[] pixels = new Color[findNumberOfPixels(distance)+1];
        int counter = 0;
        for (int j = col-distance; j <= col+distance; j++)
        {
            for (int i = row-distance; i <= row+distance; i++)
            {
                if ((Math.abs(col-j) + Math.abs(row-i)) <= distance)
                {
                    pixels[counter] = picture.get(Math.abs(j)%width,Math.abs(i)%height);
                    counter++;
                }
            }
        }
        return pixels;
    }
    public static Color findMostFrequentNeighbor(Color[] pixels)
    {
        int[] colors = new int[pixels.length];
        for (int i = 0; i < pixels.length; i++)
        {
            for (int j = 0; j < pixels.length; j++)
            {
                if (pixels[i].equals(pixels[j]))
                {
                    colors[i]++;
                }
            }
        }
        int max = 0;
        int index = 0;
        for (int i = 0; i < pixels.length; i++)
        {
            if (colors[i] > max)
            {
                max = colors[i];
                index = i;
            }
        }
        return pixels[index];
    }
    public static Picture applyPaintingFilter(Picture picture, int distance)
    {
        int width = picture.width();
        int height = picture.height();
        Picture newPicture = new Picture(width,height);
        for (int col = 0; col < width; col++)
        {
            for (int row = 0; row < height; row++)
            {
                Color newColor = findMostFrequentNeighbor(findNeighboringColors(picture, col, row, distance));
                newPicture.set(col,row,newColor);
            }
        }
        return newPicture;
    }
    public static void main(String[] args)
    {
        Picture picture = new Picture(args[0]);
        int distance = Integer.parseInt(args[1]);
        Picture newPicture = applyPaintingFilter(picture, distance);
        newPicture.show();
    }
}

Picture is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input (picture of a puffin taken from Pinterest):

with Manhattan distance = 10
Output:

Is there any way that I can improve my program?
Thanks for your attention.


texts:
I'm using this class for producer-consumer setup in C++:

#pragma once

#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <atomic>

template <typename T> class SafeQueue
{
public:
    SafeQueue() :
    _shutdown(false)
    {

    }

    void Enqueue(T item)
    {
        std::unique_lock<std::mutex> lock(_queue_mutex);
        bool was_empty = _queue.empty();
        _queue.push(std::move(item));
        lock.unlock();

        if (was_empty)
            _condition_variable.notify_one();
    }

    bool Dequeue(T& item)
    {
        std::unique_lock<std::mutex> lock(_queue_mutex);

        while (!_shutdown && _queue.empty())
            _condition_variable.wait(lock);

        if(!_shutdown)
        {
            item = std::move(_queue.front());
            _queue.pop();

            return true;
        }

        return false;
    }

    bool IsEmpty()
    {
        std::lock_guard<std::mutex> lock(_queue_mutex);
        return _queue.empty();
    }

    void Shutdown()
    {
        _shutdown = true;
        _condition_variable.notify_all();
    }

private:
    std::mutex _queue_mutex;
    std::condition_variable _condition_variable;
    std::queue<T> _queue;
    std::atomic<bool> _shutdown;
};

Most of it looks fine to me, but the Shutdown function looks like it might have some problems. If there are problems, what is the best way to 'unblock' a thread waiting on Dequeue when I want to stop it?


texts:
I recently built an improved version of a bank account program I made. It has no GUI or any interaction with users, but I simply built it to test it and play with it via main(). I'll post all my classes below and you can run the program yourself or just critique my code. I'll take any and all suggestions, so please leave corrections that you see (this code will most likely be rough, as I'm a beginner programmer altogether, but I'm still learning a lot).

Bank Class:

package improvedBank;
import java.util.*;

public class Bank {

    public static ArrayList<Account> bankAccounts = new ArrayList<Account>();
    static int time = 0;
    int bankCash = 0;

    public ArrayList<Account> addAcc(Account acc) {
        bankAccounts.add(acc);
        return bankAccounts;
    }

    public static void passTime(Account acc) {
        time += 1;
        acc.getInterest();
    }

    // testing code, not sure how to implement user control yet :/
    public static void main(String[] args) {
        Bank myBank = new Bank();

        BusinessAccount billsAccount = new BusinessAccount("Bill's Donut Shop", "Bill", 372);
        BusinessAccount joesAccount = new BusinessAccount("Joe's Italian Restaurant", "Joe", 568);
        SavingsAccount dillonsAccount = new SavingsAccount("Dillon", 57);
        SavingsAccount jessicasAccount = new SavingsAccount("Jessica", 72);

        myBank.addAcc(billsAccount);
        myBank.addAcc(joesAccount);
        myBank.addAcc(dillonsAccount);
        myBank.addAcc(jessicasAccount);

        billsAccount.deposit(37);
        System.out.println(bankAccounts);

        dillonsAccount.withdraw(12);
        jessicasAccount.deposit(12);
        billsAccount.withdraw(4);
        System.out.println(bankAccounts);
    }
}

Account class (abstract class):

package improvedBank;

public abstract class Account {

    public String accountType;
    public String owner;
    public int balance;
    public int timeOpened;

    public int getInterest() {
        int newBal = (int) (balance * 0.15);
        balance += newBal;
        timeOpened += 1;
        return balance & timeOpened;
    }

    public int deposit(int amount) {
        Bank.passTime(this);
        return balance += amount;
    }

    public int withdraw(int amount) {
        Bank.passTime(this);
        return balance -= amount;
    }

    public String toString() {
        return "Account Type: " + this.accountType + " | Account owner: " + this.owner + " | Account balance: $" + this.balance + " | Account active for: " + timeOpened + " days";
    }
}

SavingsAccount class (extends Account class):

package improvedBank;

public class SavingsAccount extends Account {

    public SavingsAccount(String own, int cash) {
        this.accountType = "Savings Account";
        this.owner = own;
        this.balance = cash;
        System.out.println("Savings account created.");
        Bank.passTime(this);
        return;
    }

}

BusinessAccount class (also extends Account class):

package improvedBank;

public class BusinessAccount extends Account {

    String businessName;

    public BusinessAccount(String bizName, String own, int cash) {
        this.accountType = "Business Account";
        this.businessName = bizName;
        this.owner = own;
        this.balance = cash;
        System.out.println("Business account created");
        Bank.passTime(this);
        return;
    }
}


texts:
I am writing a python class to implement a object moving along a Fundamental Polygon.  It takes in a size of the square and config option with three booleans enumerating the 8 possibilities, the first bit indicates whether connected sides are opposite or adjacent, the second indicates if the primary sides are parallel or antiparallel, and the third indicates if the secondary sides are parallel or antiparallel.

For example to denote a torus the config would be:

 (False, False, False)

My implementation of the wraparound (when the pointer moves off the edge of the square), is quite messy.  I'm not sure what I should do to make the code more readable and straight forward.

class Topology(object):
    def __init__(self,dim,config):
        self.dim = dim
        self.direction = [0,1]
        self.location = [0,0]
        # (matching, primary twist, secondary twist)
        self.config = config
    def move(self):
        self.location = [
            self.location[0]+self.direction[0],
            self.location[1]+self.direction[1]
        ]
        #Important bit
        if self.location[0] >= self.dim[0]:
            if config[1]:
                self.location[1] *= -1
            if config[0]:
                self.location = self.location[::-1]
                self.direction = self.direction[::-1]
        if self.location[1] >= self.dim[1]:
            if config[2]:
                self.location[0] *= -1
            if config[0]:
                self.location = self.location[::-1]
                self.direction = self.direction[::-1]
        if self.location[0] < 0:
            if config[2]:
                self.location[1] *= -1
            if config[0]:
                self.location = self.location[::-1]
                self.direction = self.direction[::-1]
        if self.location[1] < 0:
            if config[1]:
                self.location[0] *= -1
            if config[0]:
                self.location = self.location[::-1]
                self.direction = self.direction[::-1]
        self.location[0] %= self.dim[0]
        self.location[1] %= self.dim[1]


texts: RCU in C++11 using std::shared_ptr and a little more

texts:
Here's some code I wrote to solve a problem at the server I'm working on. Is this valid? I've tested it, and it works, but I would like some opinions on this.

It's basically a singly_lock_free_linked_list based on the RCU concept.

class data_list
{
    CRITICAL_SECTION update;
    std::atomic_int64_t count;
    concurrency::concurrent_queue<std::shared_ptr<data>> to_add;
    concurrency::concurrent_queue<int> to_remove;

public:
    data_list() :head(nullptr), count(0) { InitializeCriticalSection(&update); }
    ~data_list() {
        DeleteCriticalSection(&update);

        std::shared_ptr<node> cursor = head;
        head = nullptr;
        while (1)
        {
            if (!cursor) break;
            cursor = cursor->next;
        }
    }

    struct node { std::shared_ptr<data> d; std::shared_ptr<node> next; };
    std::shared_ptr<node> head;

    int push_front(std::shared_ptr<data> d)
    {
        to_add.push(std::move(d));
        if (!TryEnterCriticalSection(&update))
            return 0;

        int a = 0;
        while (1)
        {
            if (!to_add.try_pop(d)) break;

            std::shared_ptr<node> temp = std::make_shared<node>();
            temp->d = d;
            temp->next = head;
            while (1) { if (std::atomic_compare_exchange_weak(&head, &head, temp)) break; }

            a++;
            count++;
        }
        LeaveCriticalSection(&update);
        return a;
    }

    void remove(int uid)
    {
        to_remove.push(uid);
        if (!TryEnterCriticalSection(&update))
            return;

        std::shared_ptr<node> back;
        std::shared_ptr<node> front;
        while (1)
        {
            if (!to_remove.try_pop(uid)) break;

            back = nullptr;
            front = head;
            while (1)
            {
                if (!front) break;

                if (front->d->uid == uid) {

                    if (back)
                    {
                        back->next = front->next;
                        while (1) { if (std::atomic_compare_exchange_weak(&back->next, &back->next, front->next))break; }
                    }
                    else
                    {
                        while (1) { if (std::atomic_compare_exchange_weak(&head, &head, front->next))break; }
                    }

                    count--;
                    break;
                }

                back = front;
                front = front->next;
            }

        }

        LeaveCriticalSection(&update);
    }

    std::shared_ptr<data> get(int uid) const
    {
        std::shared_ptr<node> temp = std::atomic_load(&head);

        while (1)
        {
            if (!temp)break;

            if (temp->d->uid == uid)
                return temp->d;

            temp = std::atomic_load(&temp->next);
        }

        return nullptr;
    }

    void collect(int v, std::vector<std::shared_ptr<data>> & out_collection) const
    {
        std::shared_ptr<node> temp = std::atomic_load(&head);

        while (1)
        {
            if (!temp)break;

            if (temp->d->b == v)
                out_collection.push_back(temp->d);
            temp = std::atomic_load(&temp->next);
        }
    }

    int64_t get_count() const
    {
        return count.load(std::memory_order_relaxed);
    }
};


texts:
My htaccess has this block in it:

RewriteRule ^login$ _user/login.php
RewriteRule ^login\.php$ _user/login.php
RewriteRule ^_user/login$ _user/login.php
RewriteRule ^_user/login\.php$ _user/login.php

How do I consolidate this block? The objective is to point to _user/login.php regardless of where on the server it's called from.


texts: Counting nonexisting records with foreign key

texts:
I have two tables Room and RoomDate. Here's the structure for Room

Room
roomID
checkInDate
checkOutDate
roomType

Here's the structure for RoomDate. They have a one to many relationship.

RoomDateID
checkInDate
checkOutDate
RoomID // foreign key

Now I want to find how many rooms per roomType are available in a specific date range. That is, if a date range with a specified roomID does not yet exist in the RoomDate table, it can be added. This is how I do it.

Count all records in the Room table per type. RoomTypes are single, double and triple.
Count all records in the RoomDate that already have the inputed date range per type (E.G. if exist in single, cannot be added in single but can still be added in other room types).
Subtract the RoomDate results from Room to get all rooms that are still available per type. So if there are no records in RoomDate, all rooms are available.

Sample input:

number of rooms in the database (RoomDate does not have records yet):
single rooms: 5
doubleRooms: 6
triple rooms: 7

User: 2015-11-11 - 2015-11-21 - 5 single rooms

Sample output:

five single rooms with the date range of 2015-11-11 - 2015-11-21 is added to the RoomDate table.
number of rooms in the database without the range 2015-11-11 - 2015-11-21:
single rooms: 0
doubleRooms: 6
triple rooms: 7

Next time the user enters a date in the range of 2015-11-11 - 2015-11-21 and again chose any number of single rooms, he cannot insert it in the database because there aren't any single rooms left. But he can still insert it with other room types double and triple as long as they are still available.

I used inner join before, but it does not count null records in RoomDate, so I mad individual queries instead.

Please review my code. I think this is too slow (6 HQL select statements), how can I improve this code and make it more efficient?

public long[] countRooms() {
    Session session = getSessionFactory().getCurrentSession();
    long[] count = new long[3];
    String query = "select count (r) from Room r where r.roomType=";
    count[0] = (long)session.createQuery(query+"0").uniqueResult();
    count[1] = (long)session.createQuery(query+"1").uniqueResult();
    count[2] = (long)session.createQuery(query+"2").uniqueResult();
    return count;
}

public long[] countAvailableRooms(LocalDate checkInDate, LocalDate checkOutDate) {
    Session session = getSessionFactory().getCurrentSession();
    String query = "select count(d) from Room r join r.roomDates d where d.checkInDate=:checkInDate and d.checkOutDate=:checkOutDate and r.roomType=";
    long[] count = countRooms();
    count[0] -= (long)session.createQuery(query+"0").setParameter("checkInDate", checkInDate).setParameter("checkOutDate", checkOutDate).uniqueResult();
    count[1] -= (long)session.createQuery(query+"1").setParameter("checkInDate", checkInDate).setParameter("checkOutDate", checkOutDate).uniqueResult();
    count[2] -= (long)session.createQuery(query+"2").setParameter("checkInDate", checkInDate).setParameter("checkOutDate", checkOutDate).uniqueResult();
    return count;
}


texts: How to optimize Karatsuba algorithm (using arraylist and java)

texts:
I was using Karatsuba algorithm to multiply two polynomials and return the coefficients and I am using java, we are asked to use arraylists here, however, my code is too complicated and it takes much longer to run than I expected, can anyone help me with reducing the running time and simplify my code? Thanks a lot!
public static List<Long> smellCosmos(List<Long> a, List<Long> b) {
    int n = a.size();
    int n1 = a.size() / 2;

    List<Long>c = new ArrayList<Long>();

    if (n == 1) {
        c.add(0, a.get(0) * b.get(0));
        return c;
    };

    List<Long>ahigh = new ArrayList<Long>(n1);

    List<Long>alow = new ArrayList<Long>(n1);

    List<Long>amed = new ArrayList<Long>(n1);

    List<Long>bhigh = new ArrayList<Long>(n1);

    List<Long>blow = new ArrayList<Long>(n1);

    List<Long>bmed = new ArrayList<Long>(n1);

    for (int i = 0; i < n1; i++) {
        ahigh.add(a.get(i));
        alow.add(a.get(i + n1));
        amed.add(alow.get(i) + ahigh.get(i));
        bhigh.add(b.get(i));
        blow.add(b.get(i + n1));
        bmed.add(blow.get(i) + bhigh.get(i));
    }

    List<Long>chigh = smellCosmos(ahigh, bhigh);
    List<Long>clow = smellCosmos(alow, blow);
    List<Long>cmed = smellCosmos(amed, bmed);

    for (int j = 0; j < n1; j++)
        c.add(chigh.get(j));

    for (int m = 0; m < cmed.size(); m++)
        c.add(cmed.get(m) - chigh.get(m) - clow.get(m));

    for (int g = cmed.size() - n1; g < clow.size(); g++)
        c.add(clow.get(g));

    for (int i = n1; i < chigh.size(); i++)
        c.set(i, c.get(i) + chigh.get(i));

    for (int i = 0; i < cmed.size() - n1; i++)
        c.set(n1 * 2 + i, c.get(n1 * 2 + i) + clow.get(i));

    return c;

}
```


texts: How can I improve my code which dynamically populates a section of a page?

texts:
My site consists of a lot of asynchronous calls, and because of this a lot of content is dynamically added to the page. For this section of code I've dynamically added tabs to a page and need to create the selected tab section. This function is fired when a tab is clicked (note that $devices_page is a pre-existing divider):

function populateDevicesPage(deviceArray) {
    // Hide the current page
    $devices_page.stop().slideUp(animationSpeed, function() {
        // Check if the $devices_page has any current children
        if($devices_page.children().length > 0)
        { /* Ignore this part, it's the below else that matters */ }
        // If not, create page elements
        else
        {
            // Create the main devices page elements
            var
                $device_name = $('<h1/>').appendTo($devices_page),
                $device_inner_page = $('<div id="devices-page-inner"/>').appendTo($devices_page),
                $commands_table = $('<table/>').appendTo($device_inner_page),
                $commands_thead = $('<thead/>').appendTo($commands_table),
                $commands_tbody = $('<tbody/>').appendTo($commands_table),
                $commands_thead_row = $('<tr/>').appendTo($commands_thead)
            ;

            // Create the table headings
            $('<th/>').text('Name').appendTo($commands_thead_row);
            $('<th/>').text('Command').appendTo($commands_thead_row);

            // Loop through each of the commands to populate the table
            for(var i=0;i<deviceArray.commands.length;i++)
            {
                var $command_tbody_row = $('<tr/>').appendTo($commands_tbody);
                $('<td/>').text(deviceArray.commands[i].name).appendTo($command_tbody_row);
                $('<td/>').text(deviceArray.commands[i].com).appendTo($command_tbody_row);
            }

            $device_name.text(deviceArray.deviceName);
        }

        // Show the newly populated page
        $devices_page.stop().slideDown(animationSpeed);
    });
}

As you can see there are a lot of elements being created and added to the pre-existing $devices_page divider. This does only happen once (when a tab is selected for the first time), but I was wondering if there's a much better approach I could adopt instead.

The full code can be seen here if anyone wants a further poke around: https://github.com/JamesDonnelly/WebRemoteNotifier/blob/master/js/generic.js. Do note that this is a very rough draft of a project I've only spent about 3-4 hours working on, so I imagine there are a lot of imperfections; for now I'm only really concerned about the above function.

Thanks a lot!


texts: Online command line JavaScript optimization

texts:
Here is a light command line I built with JavaScript. I would like to ask if there are many stupidities, bad code and such? The only test command right now is add arg1 arg2 so writing add 1 1 should get you >>> 2. It will print Command *** not found with other commands than add. See the fiddle below.

jsfiddle.net
http://jsfiddle.net/Nr2Am/26/

JavaScript

function cli_focus() {
    var cli = document.getElementById("commandline");
    cli.focus();
}

function arguments_to_array(args) {
    var arr = new Array();
    for (var i=0; i<args.lentgh; ++i) {
        arr[i] = args[i];
    }
    return arr;
}

function cli_go(input) {
    var lines = input.value;
    var lines_arr = lines.split(/\n+/);
    var cmd = lines_arr[lines_arr.length-1];

    cli_run(cmd);
    return false;
}

function cli_parse(cmd) {
    return cmd.split(/\s+/);
}

function cli_remove_blank_words(words) {

    while (words.length>0 && words[0]==="") {
        words = words.slice(1);
    }
    while (words.length>0 && words[words.length-1]==="") {
        words = words.slice(0, words.length-1);
    }

    return words;
}

function cli_run(cmd) {
    var words = cli_parse(cmd);
    words = cli_remove_blank_words(words);

    var last_word = null;

    for (var i=0; i<words.length; ++i) {
        var func_name = words.slice(0, i+1).join("_");
        if (window[func_name] === undefined) {
            break;
        } else {
            last_word = i;
        }
    }

    if (last_word===null || words.length===0) {
        document.getElementById('commandline').value = document.getElementById('commandline').value + '\n>>> Command ' + words[0] + ' not found';
        return;
    }

    var func_name = words.slice(0, last_word+1).join( "_" );
    var func = window[func_name];
    var args = words.slice(last_word+1);
    func.apply(this, args);
}

function add(a,b) {
    var result = parseInt(a)+parseInt(b);
    document.getElementById('commandline').value = document.getElementById('commandline').value + '\n>>> ' + result;
}


texts: Detect strings that consist of some a's followed by some b's

texts:
This program needs to detect strings in which the first few characters are 'a', than few 'b'.
Is it possible that in this implementation may be undefined behavior.

string str;
while (cin >> str) {
    unsigned int i = 0;
    while (str[i] == 'a' && i < str.length()) {
        i++;
    }
    while (str[i] == 'b' && i < str.length()) {
        i++;
    }
    if (i == str.length()) {
        cout << "ok" << endl;
    } else {
        cout << "Not ok" << endl;
    }
}


texts:
Beginner programmer here. What can I improve in my code? Are there things I'm doing wrong or are there easier ways of doing what I did?

def reduce(n):
    n = abs(n)
    ctr = 0
    factors_list = []
    for i in range(2,n+1):
        if ctr >= 1:
            break
        if n % i == 0:
            factors_list.append(i)
            factors_list.append(int(n/i))
            ctr += 1
    return factors_list

def isPrime(n):
    return 1 in reduce(n)

def primeFactorization(n):
    if isPrime(n):
        return reduce(n)
    factors = reduce(n)
    primeFactors = []
    while True:
        for e in factors:
            if isPrime(e):
                primeFactors.append(e)
                factors.remove(e)
            else:
                factors.extend(reduce(e))
                factors.remove(e)
        if len(factors) == 0:
            break
    return sorted(primeFactors)


texts: Check if current time is within the timeframe using Joda-Time

texts:
Novice Java developer here. I've never really used a time/date library before and I'm curious how an experienced developer would solve this. You're given 4 ints: startHour, startMinute, endHour and endMinute. Now, check if current time is within the given timeframe. Is there a more clean way of doing this than what I've done here:

private void checkTimeframe(int startHour, int startMinute, int endHour, int endMinute) {
    LocalDateTime now = LocalDateTime.now();
    LocalTime localTimeStart = new LocalTime(startHour, startMinute);
    LocalTime localTimeEnd = new LocalTime(endHour, endMinute);

    LocalDateTime startTime = new LocalDateTime(now.getYear(), now.getMonthOfYear(),
            now.getDayOfMonth(), startHour, startMinute);

    LocalDateTime endTime = new LocalDateTime(now.getYear(), now.getMonthOfYear(),
            now.getDayOfMonth(), endHour, endMinute);

    //Check if start/end is, for instance, 23:00 - 03:00
    if (localTimeStart.isAfter(localTimeEnd) || localTimeStart.equals(localTimeEnd)) {
        endTime = endTime.plusDays(1);
    }

    if ( (now.equals(startTime) || now.isAfter(startTime) ) && now.isBefore(endTime)) {
        System.out.println("Ok, we're within start/end");
    } else {
        System.out.println("Outside start/end");
    }
}


texts:
I'm using boost::program_options to parse input from the user. However, while the standard library makes this an easy task to do, it's causing an (in my opinion) excessive amount of allocations. Of course, for such a small program on modern systems, it probably isn't that big of a deal, but I would like to nip the problem in the bud before it spirals out of control.

How can I reduce the number of allocations in this program?

Here's an example of what valgrind reports:

 $ test
Compression level was not set.
 $ test --help
Allowed options:
  --help                produce help message
  --compression arg     set compression level

 $ test --compression 10
Compression level was set to 10.
 $ test --compression 5
Compression level was set to 5.
 $ test --compressio

error: the required argument for option '--compression' is missing
total heap usage: 266 allocs, 266 frees, 11,430 bytes allocated

And the code dump:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <memory>
#include <sstream>

#include <cstring>

#include <boost/program_options.hpp>
#include <boost/iterator/transform_iterator.hpp>
namespace po = boost::program_options;

// "std::vector<std::string> to char* array"
// http://stackoverflow.com/a/7048972/3920237
const char *convert_to_cstr(const std::string & s)
{
   return s.c_str();
}

int main(int argc, char* argv[])
{
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("compression", po::value<int>(), "set compression level")
    ;

    std::string input = "";

    const std::string prompt = " $ ";

    std::vector<std::string> args;
    std::istringstream iss;

    std::string token;

    po::variables_map vm;
    while (true)
    {
        try {
            std::cout << prompt;
            std::getline(std::cin, input);
            if (input == "quit")
                break;

            iss.clear();
            iss.str(input);

            args.clear();
            while (iss >> token)
            {
                args.push_back(token);
            }

            auto beg = boost::make_transform_iterator(args.begin(),
                convert_to_cstr);
            auto end = boost::make_transform_iterator(args.end(),
                convert_to_cstr);

            const std::vector<const char*> vc { beg, end };

            /* std::transform(args.begin(), args.end(), std::back_inserter(vc), convert); */
            vm.clear();
            po::store(po::parse_command_line(vc.size(), vc.data(), desc), vm);
            po::notify(vm);

            if (vm.count("help")) {
                std::cout << desc << "\n";
                continue;
            }

            if (vm.count("compression")) {
                std::cout << "Compression level was set to "
                     << vm["compression"].as<int>() << ".\n";
            } else {
                std::cout << "Compression level was not set.\n";
            }
        }
        catch(std::exception& e) {
            std::cerr << "error: " << e.what() << "\n";
            continue;
        }
        catch(...) {
            std::cerr << "Exception of unknown type!\n";
        }
    }

    return 0;
}


texts:
I am solving a question in which we are given the LCM and HCF and two numbers 'a' and 'b', our task is to find the pairs of numbers between a and b [inclusive] whose HCF is the given HCF and LCM is the given LCM

I have written a code with time complexity O(m) where m is the number of integers lying between the range a and b, But on submission i am getting time limit exceeded error

IMO this is the best we can do , can we do better?
Here is the code

  #include<bits/stdc++.h>
  using namespace std;

  //function for calculatin gcd
  int gcd( int a,int b){
  int h;
   for(h = a<b?a:b; h >= 1; h--){
    if((a%h == 0) && (b%h == 0))
     break;
   }

   return h;
   }

  int main(){
  int n1,n2,lcm,hcf,cnt = 0;
  cin>>n1>>n2>>hcf>>lcm;//The numbers a,b and hcf and lcm
   for(int i = n1; i <= n2;i++){
   //checking if the number divides the lcm completely
   if(lcm%i == 0){
    int a = lcm/i;// its other multiplier
    int b = gcd(a,i);//finding their gcd
        //checking if their gcd is equal to given hcf
        if(b == hcf){
         int c = (i*a)/b;//finding the lcm by a*b = lcm*hcf formula and
                         //checking
          if(c == lcm){
           cnt++;
          }
         }
        }
       }

   cout<<cnt<<endl;
   return 0;
   }


texts: Handling user permissions in Code Igniter

texts:
I haven't done much work with Code Igniter, and can't seem to get much of a definitive answer poking around as to what the best solution to this problem is. Before moving forward, I wanted to see if you had any suggestions.

The idea is that each user has access to about 30 specific 'sites', out of many (~1000). I will store an array in the session info, then when each site is about to be loaded, check to see if the site is in the array.

class Sessions extends CI_Controller{

  public function authenticate()
    {
        $this->load->model('User_model', '', true);

        if ($this->User_model->authenticate($this->input->post('username'), $this->input->post('password')))
        {
            $this->session->set_userdata('loggedin', true);
            $this->session->set_userdata('sites', $this->model->get_user_sites());

        }
        else
        {
            header('Location: /sessions/login/'.'1');
        }
    }

// http://domainname/protected_pages/serve_protected/24
class protected_pages extends MY_Controller{

     public function serve_protected ($site_id){
          if (in_array($this->session->unset_userdata('sites'), $site_id)||$this->session->unset_userdate('role')=='admin'){
               $this->load->view(page_view.php);
          }
     }

 }


texts: Generating the property name of an object

texts:
$roleId     = pg_escape_string($_POST['role']);
$grantValue = pg_escape_string($_POST['grant']);
$feature    = pg_escape_string($_POST['feature']);
$permission = pg_escape_string($_POST['permission']);

$permissionsModel = new Permissions();
$record           = $permissionsModel->getPermission($roleId);

//assemble object's property name based on the action taking place and save changes.
$property          = trim($feature . '_' . $permission);
$record->$property = $grantValue;
$record->save(false);

Here is an example of an actual property of the object:

$record->report_w;

$record->facebook_d;

My second question is about escaping the data: can you suggest a better way of validating user input?


texts: Defining array contents using multiple statements on one line

texts:
I'm writing a sub which is going to determine which type of business is being detailed on a particular line of data. It's going to use column positions to check if the data exists, and then output the corresponding string if it does.

I've decided that the best way to organise a group of my arguments is using a 2D array. Now, for readability, clarity and general good coding practice, which is better:

This:

arrAmountColumns(1, 1) = lngInvestmentAmountColumn: arrAmountColumns(1, 2) = "Investment Amount"
arrAmountColumns(2, 1) = lngSinglePremiumColumn: arrAmountColumns(2, 2) = "Single Premium"
arrAmountColumns(3, 1) = lngMonthlyPremiumColumn: arrAmountColumns(3, 2) = "Monthly Premium"

or this:

arrAmountColumns(1, 1) = lngInvestmentAmountColumn
arrAmountColumns(1, 2) = "Investment Amount"

arrAmountColumns(2, 1) = lngSinglePremiumColumn
arrAmountColumns(2, 2) = "Single Premium"

arrAmountColumns(3, 1) = lngMonthlyPremiumColumn
arrAmountColumns(3, 2) = "Monthly Premium"


texts:
For no particular reason, I wanted to create a function that would take a string and "encrypt" it via Caesar cipher. This function takes a string and shifts the letters left or right (in the alphabet) depending on the input. Shift right(2) for instance would be -

ABCDEFGHIJKLMNOPQRSTUVWXYZ
CDEFGHIJKLMNOPQRSTUVWXYZAB

The UDF:

Option Explicit

Public Function CaesarCipher(ByVal TextToEncrypt As String, ByVal CaesarShift As Long) As String

    'Positive means shift to right e.g. "A" Shift 1 returns "B"
    Dim IsPositive As Boolean
    IsPositive = True
    If CaesarShift < 0 Then IsPositive = False
    CaesarShift = Abs(CaesarShift)

    Dim OutputText As String
    TextToEncrypt = UCase(TextToEncrypt)

    If CaesarShift > 26 Then
        CaesarShift = CaesarShift Mod 26
    End If

    If IsPositive Then
          OutputText = ShiftRight(TextToEncrypt, CaesarShift)
    Else: OutputText = ShiftLeft(TextToEncrypt, CaesarShift)
    End If

    CaesarCipher = OutputText
End Function

The shifting functions:

Private Function ShiftRight(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String

    Dim TextLength As Long
    TextLength = Len(ShiftString)

    Dim CipherText As String
    Dim CharacterCode As Long
    Dim AsciiIndex As Long
    Dim AsciiIdentifier() As Long
    ReDim AsciiIdentifier(1 To TextLength)

    For AsciiIndex = 1 To TextLength
        CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1))
        If CharacterCode + ShiftQuantity > 90 Then
            CharacterCode = CharacterCode - 26 + ShiftQuantity
        ElseIf CharacterCode = 32 Then GoTo Spaces
        Else:  CharacterCode = CharacterCode + ShiftQuantity
        End If
Spaces:
        AsciiIdentifier(AsciiIndex) = CharacterCode
    Next

        For AsciiIndex = 1 To TextLength
            CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex))
        Next
    ShiftRight = CipherText
End Function

Private Function ShiftLeft(ByVal ShiftString As String, ByVal ShiftQuantity As Long) As String

    Dim TextLength As Long
    TextLength = Len(ShiftString)

    Dim CipherText As String
    Dim CharacterCode As Long
    Dim AsciiIndex As Long
    Dim AsciiIdentifier() As Long
    ReDim AsciiIdentifier(1 To TextLength)

    For AsciiIndex = 1 To TextLength
        CharacterCode = Asc(Mid(ShiftString, AsciiIndex, 1))
        If CharacterCode = 32 Then GoTo Spaces
        If CharacterCode - ShiftQuantity < 65 Then
            CharacterCode = CharacterCode + 26 - ShiftQuantity
        Else: CharacterCode = CharacterCode - ShiftQuantity
        End If
Spaces:
        AsciiIdentifier(AsciiIndex) = CharacterCode
    Next

        For AsciiIndex = 1 To TextLength
            CipherText = CipherText & Chr(AsciiIdentifier(AsciiIndex))
        Next
    ShiftLeft = CipherText
End Function


texts:
The situation is, I have two fields in a database (or that can be derived) - when the message was received (Received, of type DateTime), and the day of the month (but not the month itself) that the message was supposed to be received (DayOfRun of type Integer, which is the last two digits of an ID column that doesn't otherwise contain date-time information). I need to know the difference (in whole days, ignoring the time) between the two. If the message arrived before the day of run, the number will be negative.
I can guarantee that the entries will not differ by more than half a month in either direction.
The pseudo-code logic I have come up with is as follows:
DayOfRun = Extract last two characters from ID Field
DayReceived = Extract DayOfMonth from Received;
DaysInPreviousMonth = Extract Count of Days in (Month before Received)
Pick the closest to 0 from the following:
A:   If DayReceived < DayOfRun then
 :      DaysInPreviousMonth + DayReceived - DayOfRun ;
 :   Otherwise
 :       DaysInPreviousMonth + DayOfRun - DayReceived ;

B:   DayReceived - DayOfRun;

Examples:

Day of Run
Received
Answer
Reasoning

01
2021-04-29
-2
29th April is 2 days before 1st May (can't be 1st April - would be too far away)

28
2021-05-02
4
02nd May is 4 days after 28th April (which gives a smaller absolute number than assuming 28th May, which would be too far away anyway)

14
2021-04-28
14
28th April is 14 days after 14th April (which gives a smaller absolute number than if we assumed 14th May)

My KQL to implement this logic is as follows:
tableName
| project DayOfRun = toint(substring(['ID Field'], -2, 2)), ['Day Of Month Received'] = datetime_part("day",ErrorTimestamp), ErrorTimestamp
| where DayOfRun <> ['Day Of Month Received']
| project ['Days In Previous Month'] =  datetime_part("day",endofmonth( datetime_add("month",-1, ErrorTimestamp))), DayOfRun, ['Day Of Month Received']
| project ['Day Of Month Received'], Diff = (['Day Of Month Received'] - DayOfRun), CrossMonthDiff = iif(['Day Of Month Received'] < DayOfRun,(['Days In Previous Month']+['Day Of Month Received']-DayOfRun),(['Days In Previous Month']+DayOfRun-['Day Of Month Received']))
| summarize ['Day Of Month Received'], ['Difference (Days)'] = iif(min_of(abs(Diff),abs(CrossMonthDiff)) == abs(Diff),Diff,CrossMonthDiff)
| order by ['Difference (Days)'] desc, ['Day Of Month Received'] asc

This query seems overly complex, and is quite slow to run. Any thoughts on how to improve either the logic or the query itself?


texts:
Some context

I've been tasked with supplying an escaping function to arbitrary CSS values that are entered through a form. The goals and caveats are:

I know it's bad practice to let users input CSS. Deal with it.
Data will be injected either to a style attribute, or to an external stylesheet.
This is run on PHP 5.1 (Again, I know, deal with it).
I'm trying to follow this cheat sheet as closely as possible.

The Code

/**
 * ord() alternative that works with UTF8 characters
 * @param string $c
 *
 * @return int      UTF-8 character code value
 */
function getUTF8CharCode($c) {
    $h = ord($c{0});
    if ($h <= 0x7F) {
        return $h;
    } else if ($h < 0xC2) {
        return false;
    } else if ($h <= 0xDF) {
        return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
    } else if ($h <= 0xEF) {
        return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
        | (ord($c{2}) & 0x3F);
    } else if ($h <= 0xF4) {
        return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
        | (ord($c{2}) & 0x3F) << 6
        | (ord($c{3}) & 0x3F);
    } else {
        return -1;
    }
}

/**
 * Escape a single character for CSS context.
 * @param $c
 * @return string
 */
function escapeCSSCharacter($c) {
    return "\\" . base_convert(getUTF8CharCode($c), 10, 16) . " ";
}

/**
 * Escape CSS rule
 *
 * @param string $data          The CSS rule
 * @param array $immuneChars    Array of immune character. These characters will not be escaped.
 *
 * @return string               Escaped string
 */
function escapeCSSValue($data, array $immuneChars = array()) {
    $result = "";
    for ($i = 0; $i < mb_strlen($data); $i++) {
        $currChar = mb_substr($data, $i, 1);
        if (getUTF8CharCode($currChar) < 256 && //Character value is less than 256
            !preg_match("/^\w$/", $currChar) && //Character is not alphanumeric (underscore is considered safe too)
            !in_array($currChar, $immuneChars)  //Character is not immune
        ) {
            $result .= escapeCSSCharacter($currChar);
        }
        else {
            $result .= $currChar;
        }
    }
    return $result;
}

Usage

$colorRule = "color: " . escapeCSSValue("#BADA55;}*{display:none;}/*", array("#")) . ";"; //Will be obviously broken, but will not break the rest of the document.
echo $colorRule;

My worries

Is this a good way to escape CSS? Is this safe? Will this method be impossible to break out of?
Am I doing this relatively efficiently? Given that the strings I'm going to be encoding are arbitrary, I'm worried about attacks that involve thousands of characters.

Any review will be welcomed.


texts: Bind component state to redux store state

texts:
I've recently started working on some projects with react & redux.

I understand it is best practice to manage component/UI state inside a component with setState etc. However there are various advantages to fully utilising the global state to do with making components and the application as w whole easier to test, debug, and mock; the more the application state resembles a single object tree and the components resemble pure functions.

I wonder if it is possible to have the best of both with a mechanism resembling the following, which allows the usual use of this.setState and this.state inside the component but actually relies on the redux store to maintain this state, thus making it mockable, audit-able, repayable etc along with the rest of the store:

// reducer/componentState.js

export (state, action) => {
  const id = action.id;
  switch (action.type) {
    case 'REGISTER_COMPONENT':
      return state.set(id, Object.assign({}, action.initialState));
    case 'DEREGISTER_COMPONENT':
      return state.remove(id);
    case 'SET_STATE':
      return state.set(id, Object.assign({}, state.get(id), action.newState));
    case 'REPLACE_STATE':
      return state.set(id, Object.assign({}, action.newState));
  }
  return state;
};

// components/MyComponentContainer.js

function mapStateToProps(state, ownProps) {
  return {
    state: state.getIn(['componentState', ownProps.id])
  };
}

function mapDispatchToProps(dispatch, ownProps) {
  return {
    _binding: {
      registerComponent(initialState) {
        dispatch({type: 'REGISTER_COMPONENT', ownProps.id, initialState});
      },
      deregisterComponent() {
        dispatch({type: 'DEREGISTER_COMPONENT', ownProps.id});
      },
      setState(newState) {
        dispatch({type: 'SET_STATE', ownProps.id, newState});
      },
      replaceState(newState) {
        dispatch({type: 'REPLACE_STATE', ownProps.id, newState});
      }
    }
  };
}

...

// components/MyComponent.js

export class Contacts extends React.Component {
  constructor(props) {
    super(props);
    this.setState = this.props._binding.setState;
    this.replaceState = this.props._binding.setState;

    this.state = {
      something: true
    };
  }

  componentWillMount() {
    this.props._binding.registerComponent(this.state);
  }

  componentWillReceiveProps(nextProps) {
    this.state = nextProps.state;
  }

  componentWillUnmount() {
    this.props._binding.deregisterComponent();
  }

  ...
}

Obviously this pattern, contains a lot of boilerplate in the component that could be abstracted with helper functions or by maybe subclassing React.Component.

Besides general feedback on my reasoning and code, I'd like to know if any libraries exist that do something similar, or if I'm fundamentally abusing react here in some way that makes this a bad idea.


texts: Calculate probability that knight does not attempt to leave chessboard after at most k random moves (LeetCode #688)

texts:
I'm learning competitive programming and came across this question on LeetCode : 688. Knight Probability in Chessboard

On an n x n chessboard, a knight starts at the cell (row, column) and
attempts to make exactly k moves. The rows and columns are 0-indexed,
so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n-1).
A chess knight has eight possible moves it can make, each move is two cells in a cardinal direction,
then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight > possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly k moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.

I wrote following BFS solution for it
from collections import deque

class Solution:
    def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
        i = 0
        pos_moves = deque([[r, c, 1]])  # (r, c, prob)
        self.moves_memo = {}
        while i < K and len(pos_moves):
            increase_i_after = len(pos_moves)
            for j in range(increase_i_after):
                move = pos_moves.popleft()

                for next_move in self.get_pos_moves(N, move[0], move[1], move[2]):
                    pos_moves.append((next_move[0], next_move[1], next_move[2]))

            i += 1

        ans = 0
        for m in pos_moves:
            ans += m[2]

        return ans/len(pos_moves) if len(pos_moves) > 0 else 0

    def get_pos_moves(self, n, r, c, prev_p):
        # Returns a list of possible moves
        if (r, c) in self.moves_memo:
            pos_moves = self.moves_memo[(r, c)]
        else:
            pos_moves = deque([])
            if r+2 < n:
                if c+1 < n:
                    pos_moves.append([r+2, c+1, 0])
                if c-1 >= 0:
                    pos_moves.append([r+2, c-1, 0])
            if r+1 < n:
                if c+2 < n:
                    pos_moves.append([r+1, c+2, 0])
                if c-2 >= 0:
                    pos_moves.append([r+2, c-2, 0])
            if r-2 >= 0:
                if c+1 < n:
                    pos_moves.append([r-2, c+1, 0])
                if c-1 >= 0:
                    pos_moves.append([r-2, c-1, 0])
            if r-1 >= 0:
                if c+2 < n:
                    pos_moves.append([r-1, c+2, 0])
                if c-2 >= 0:
                    pos_moves.append([r-1, c-2, 0])

            self.moves_memo[(r, c)] = pos_moves

        l = len(pos_moves)
        if l == 0:
            return pos_moves
        else:
            for move in pos_moves:
                move[2] = prev_p*l/8

            return pos_moves

For n = 8, K = 30, r = 6, c = 4, this solution exceeds time limits. I am not able to figure out why is this solution less time efficient than this. I'm looking for reasons why my code is 'slow'. Thank you!


texts: Displaying a String array in tabular format


texts: Determine whether there exists a one-to-one character mapping from one string to another

texts:
The task

  Determine whether there exists a one-to-one character mapping from one
  string s1 to another s2.

  For example, given s1 = abc and s2 = bcd, return true since we can map
  a to b, b to c, and c to d.

  Given s1 = foo and s2 = bar, return false since the o cannot map to
  two characters.

The task is ambiguous. Here are my interpretations of the task and the corresponding solution:

Interpretation 1:

For every letter in one string there exists exactly one in the other. (order and position of the corresponding letter are irrelevant)

My solution

const s1 = "foo";
const s2 = "bar";

const isMappable = (s1, s2) => {
  if (s1.length !== s2.length) { return false; }

  const createOrderedMap = str => Object.values([...str]
    .reduce((map, s) => {
      map[s] = map[s] ? map[s] + 1 : 1;
      return map;
  }, {})).sort();
  const o1 = createOrderedMap(s1);
  const o2 = createOrderedMap(s2);
  if (o1.length !== o2.length) { return false; }
  for (let i = 0, len = o1.length; i < len; i++) {
    if (o1[i] !== o2[i]) {
      return false;
    }
  }
  return true;
};

console.log(isMappable(s1, s2));

Interpretation 2:

For every letter in one string there exists exactly one in the other at the exact order and position of the corresponding letter.

My solution

const s1 = "aab";
const s2 = "cdc";
const isMappable = (s1, s2) => {
  if (s1.length !== s2.length) { return false; }

  const map1 = new Map();
  const map2 = new Map();

  return [...s1].every((s, i) => {
    if (!map1.has(s) && !map2.has(s2[i])) {
      map2.set(s2[i], s);
      map1.set(s, s2[i]);
    }
    return map1.get(s) === s2[i]  && map2.get(s2[i]) === s;
  });
};

console.log(isMapable(s1, s2));


texts:
It only does expressions with 2 operands yet, but I'm wondering if there are any ways I can improve this:

# infix.rb: parse infix-operated math expressions

class String
  def is_number?
    true if Float(self) rescue false
  end
end

class InfixParser
  @operations = [ '/', '*', '+', '-' ]

  testString = '(24 + 6) / 10 * 3'
  shouldEqual = 9

  def parseExpression(expr) #TODO: implement parsing of entire expressions

  end

  def self.parseChunk(chunk)
    chunk = chunk.gsub ' ', ''

    if not (chunk.include?('/') or chunk.include?('*') \
        or chunk.include?('+') or chunk.include?('-'))
        puts "error: no operations in chunk: #{chunk}"
        exit
    end

    firstNumber = ''
    secondNumber = ''

    i = 0
    currentChar = ''
    while not @operations.include? currentChar
      currentChar = chunk[i]
      if not currentChar.is_number? and not @operations.include? currentChar \
         and currentChar != '.'
        puts "error: non-numerical digit in chunk: #{currentChar}"
        exit
      end
      firstNumber += currentChar
      i += 1
    end
    firstNumber = firstNumber[0 .. -2]

    for c in i-1 .. chunk.length-1
      if not chunk[c].is_number? and not @operations.include? currentChar \
         and currentChar != '.'
        puts "error: non-numerical digit in chunk: #{currentChar}"
        exit
      end
      secondNumber += chunk[c]
    end
    secondNumber = secondNumber[1 .. secondNumber.length - 1]

    if chunk[i - 1] == '/'
      return Float(firstNumber) / Float(secondNumber)
    elsif chunk[i - 1] == '*'
      return Float(firstNumber) * Float(secondNumber)
    elsif chunk[i - 1] == '+'
      return Float(firstNumber) + Float(secondNumber)
    elsif chunk[i - 1] == '-'
      return Float(firstNumber) - Float(secondNumber)
    else
      puts "error: invalid operator in chunk: #{chunk}"
    end

  end

end


texts: Filling up a hand with random cards that are not yet drawn - Monte Carlo

texts:
I would like to know if there is a more efficient way to speed up below code. This function is meant to fill in a set of poker hand with the remaining
cards using Mersenne Twister for a Monte Carlo simulation.

void HandEvaluator::RandomFill(std::vector<std::shared_ptr<Card>>& _Set, std::vector<std::shared_ptr<Card>>& _Dead, unsigned int _Target){
    //Add the cards that are currently in Set as dead cards
    for (auto const& CardInSet : _Set)
    {
        if (CardInSet == nullptr)
            break;

        _Dead.push_back(CardInSet);
    }

    bool IsDead;
    unsigned int RequiredAmt = _Target - _Set.size();

    unsigned int CardIndex = 0;
    std::uniform_int_distribution<unsigned int> CardsDistribution(0, 51);

    for (unsigned int Index = 0; Index < RequiredAmt; Index++)
    {
        while (true)
        {
            IsDead = false;
            CardIndex = CardsDistribution(MTGenerator);

            for (auto const& Dead : _Dead)
            {
                if (ReferenceDeck[CardIndex]->GetRank() == Dead->GetRank() && ReferenceDeck[CardIndex]->GetSuit() == Dead->GetSuit())
                {
                    IsDead = true;
                    break;
                }
            }

            if (!IsDead)
            {
                _Set.push_back(ReferenceDeck[CardIndex]);
                break;
            }
        }
    }
}

The Visual Studio Profiler had identified that this line

    CardIndex = CardsDistribution(MTGenerator);

is the main culprit behind the high compute time. Is Mersenne Twister itself not meant for a Monte Carlo Simulation and another PRNG should be used instead ? Or there are some inefficient lines that I had missed out ?


texts: Reducing execution time for a python program

texts:
The following is code that I used to do a task. the code runs fine but takes over 2 minutes to get executed. And this is with only one rule (Rule_1), the rule is checked using an .exe ( written in CPP).Actually there are many CSV files that are needed to pass through the rules.

My question is will the program always use this much amount of time, because I have to implement more the 50 rule for the files, or there is any other way around?

import os
import fnmatch
import subprocess
import xml.etree.ElementTree as ElementTree
from xml.parsers.expat import ExpatError
import sys
from shutil import copyfileobj

def locate(pattern, root="Z:/Automation/"):
    '''Locate all files matching supplied filename pattern in and below
    supplied root directory.'''
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

csv_path_unrefined = []
for xml in locate("*.csv"):
    try:
        ElementTree.parse(xml)
    except (SyntaxError, ExpatError):
        csv_path_unrefined.append(xml)
csv_path = []
for paths in csv_path_unrefined:
    if "results" in str(paths):
        csv_path.append(paths)

def check_rule1(path):
    # path = "PWLLOGGER_DEMO.csv"
    file = 'ConsoleApplication9.exe "' + path + '"'
   # print(file)
    details = os.popen(file).read()
    log_file = open("logs/Rule_1.txt")
    state = log_file.read()
    with open('results/Rule_1_log.log', 'a+') as files:
        files.write("\n========" + path + "========\n")
        files.close
    with open('results/Rule_1_log.log', 'a+') as output, open('logs/Rule_1.txt', 'r') as input:
        copyfileobj(input, output)
    if "failed" in state:
        return False
    else:
        return True

rule_1_passed = []
rule_1_failed = []

for paths in csv_path:
    result_r1 = check_rule1(paths)
    # print(result_r1)
    if result_r1 == False:
        rule_1_failed.append(paths)
        #print("Rule 1 has failed for " + paths)
    elif result_r1 == True:
        rule_1_passed.append(paths)
        #print("Rule 1 has passed for " + paths)
    open('logs/Rule_1.txt', 'w').close()

print(rule_1_failed)
print(rule_1_passed)


texts: Regex, match the most informative pattern

texts:
I have a function that is designed to parse an utterance (or typed in string) and identify the intent as a yes or no answer.

There are many ways of saying "yes" to something, and similarly for "no" or "unsure"; however, some of these phrases may include sub-phrases that have alternative meanings. For example: certainly vs. certainly not.

I can't guarantee that not will always refer to a negative statement either, for example sure vs not sure; I do not know; or even why not! (the latter could be taken as an affirmative.)

Since I am interested only in phrases and sub-phrases (not words within words), I realised that the way to identify the most informative phrase is to attempt to match them in order of size. Also, if the larger phrase matches, I also don't want to match the sub-phrases as separate. Fortunately, there is a feature of regular expressions that can do this quite easily.

/\b(a b c|a b|a c|b c|a|b|c)\b/ where 'a', 'b', and 'c' are words, will match the first phrase it can find over the others. Therefore, /\b(a b c|a b|a c|b c|a|b|c)\b/.matches("a b c a") == ["a b c", "a"] as opposed to ["a", "b c", "a"] or another combination.
Example here

(Note that for this to work, the order of the 'or'ed phases need to be in descending order of length. Regex captures lazy, and will succeed on the first 'or'-block in the capture group.)

So here's a test function of the idea in C#:

public enum Affirmation { No=0, Yes, Unsure, NoAnswer }
public Affirmation getAffirmation(string utterance)
{
    string[] yesses = new string[] { "yes", "yep", "y", "yeah", "certainly", "sure", "why not", "agree", "affirmative" };
    string[] nos = new string[] { "no", "nope", "nah", "nup", "negative", "n", "certainly not", "yeah nah" };
    string[] unsures = new string[] { "unsure", "not sure", "i don't know", "maybe", "come again", "i do not know" };
    string[] responses = yesses.Concat(nos).Concat(unsures).OrderByDescending(w => w.Length).ToArray();
    Regex response = new Regex($"\\b({string.Join("|", responses)})\\b", RegexOptions.IgnoreCase);
    MatchCollection matches = response.Matches(utterance);
    if (matches.Count == 0)
    {
        return Affirmation.NoAnswer;
    }

    IEnumerable<Affirmation> affirmations = matches.Cast<Match>().Select(m => {
        if (yesses.Contains(m.Value.ToLower())) { return Affirmation.Yes; }
        else if (nos.Contains(m.Value.ToLower())) { return Affirmation.No; }
        else { return Affirmation.Unsure; }
    });
    return affirmations.Aggregate((agg, aff) =>
    {
        if (agg == Affirmation.Unsure || agg == aff) { return agg; }
        else { return Affirmation.Unsure; }
    });
}

Obviously the three string arrays aren't particularly long in this example; however there's no reason I couldn't try and enumerate all sorts of different phrases and categorise them by intent.

My question is with that Regex builder:

Regex response = new Regex($"\\b({string.Join("|", responses)})\\b", RegexOptions.IgnoreCase);

This pattern could end up being very large.

Is there a limit to the number of characters for a Regex string?
Is there a performance issue to worry about as a capture block
becomes an extremely large 'Or' block?
Is there a better way to do this in general?


texts:
I have the following code and I'm trying to find a cleaner way to run the year functions. At the moment I have 5 years as divs with an onclick event to bring the appropriate year image into view. So if you click on 1950, the 1950 year image will appear. If you then click on 1960, the 1950 image will disappear and the 1960 image will appear and so on.

In order to make sure that only the year image I want to see appears I have coded each function to remove every other years' image but this is going to lead to massive bloat as I want to be able to increase my 5 years to 20 and up.

Is there a way such as using a loop to work something like:
"If I click on 1950 then hide anything other 1950 and just show 1950"
rather than what I have now which is
"If I click on 1950, then hide 1960 image, hide 1970 image, hide 1980 image... and show 1950 image"

<!doctype html>

<meta charset="utf-8">
<base href="http://dtwdev.co.uk/new/">
<title>Year test</title>

1950

1960

1970

1980

1990


texts:
I've done this piece of code for creating all possible samples without repetitions, but I think that it is a so heavy algorithm because every time I call this recursive function I create a new vector that is passed to it. What means create any samples without repetitions? it means creating every combination given a population. Is there a way for making this algorithm faster?

Here is the algorithm and the description:

As already said, this function creates samples without repetitions recursively. If n, that is the number of elements that should be found, is equals 0 I print the sample.

Else to the sample that is passed I add the elements of the population that there aren't yet in the combination in a way that there should't be samples that are equals between every samples(I have to create a vector for everyone of this new samples), and I call the function with this new sample and n(the number of element to be found) decremented and incrementing the element from wich I'll start to add.

private static void distribuzioneInBlocco(int n, int firstElementConsidered, Vector<Float> population, Vector<Float> sample){
    // exit condition, when n equals 0 the fuction doesn't self-calls
    if(n==0){
        JOptionPane.ShowMessageDialog(null, sample);
        return;
    }

    // for every element of the population the function adds this element
    // at the previous combination
    for(int x = firstElementConsidered; x<population.size();x++){
        Vector<Float> aggiunta = new Vector<Float>(sample);
        aggiunta.add(population.elementAt(x));
        distribuzioneInBlocco(n-1, x+1, population, aggiunta);
    }
}

for example if I give as population the vector 0 2 4 6 and n = 3 the answer will be

0 2 4
0 2 6
0 4 6
2 4 6

if I give the same population but n = 2 the result will be:

0 2
0 4
0 6
2 4
2 6
4 6

if n = 4

0 2 4 6

Moreover is there a way for doing it without recursion?


texts:
please review my code on selection sort algorithm:

selectionSort();

function selectionSort(){
    var numArray = [4,34,2,5,12];
    var MIN = 0;
    var totalNum = numArray.length,
        temp = 0,
        next_position = 0

    for(var i = 0; i < totalNum; i++){
        MIN = numArray[i];

        next_position = i + 1;
        for(var j = next_position; j < totalNum; j++){

           if(numArray[j] < MIN){
              temp = MIN;
              MIN = numArray[j];
              numArray[j] = temp;
           }
        }

        numArray[i] = MIN;
    }

    console.log(numArray);
}

After running, the output is:

[ 2, 4, 5, 12, 34 ]


texts:
I wrote a word splitting function. It splits a word into random characters. For example if input is 'runtime' one of each below output possible:

['runtime']

['r','untime']

['r','u','n','t','i','m','e'] ....

But it's runtime is very high when I want to split 100k words do you have any suggestions to optimize or write it smarter.

def random_multisplitter(word):
    from numpy import mod
    spw = []
    length = len(word)
    rand = random_int(word)
    if rand == length:       #probability of not splitting
        return [word]

    else:
        div = mod(rand, (length + 1))#defining division points
        bound = length - div
        spw.append(div)
        while div != 0:
            rand = random_int(word)
            div = mod(rand,(bound+1))
            bound = bound-div
            spw.append(div)
        result = spw
    b = 0
    points =[]
    for x in range(len(result)-1): #calculating splitting points
        b=b+result[x]
        points.append(b)
    xy=0
    t=[]
    for i in points:
        t.append(word[xy:i])
        xy=i
    if word[xy:len(word)]!='':
        t.append(word[xy:len(word)])
    if type(t)!=list:
        return [t]
    return t


texts: Javascript - varargs constructors, method chaining, and static methods

texts:
I am wondering if the code beneath considered as the proper way to achieve the topics stated in the title of the post.

I wonder is the best practice for achieving it?

var Obj = function() {
    if (arguments.length) {
        //do something
        for (var i in arguments) //iterate over the arguments
            alert(arguments[i]);
    }
};

Obj.prototype.foo = function() {
    alert("foo");
    return this;
};

Obj.prototype.bar = function() {
    alert("bar");
    return this;
};

Obj.spam = function() {
    alert("spam");
};

//varargs constructor
var varargs = ["arg1", "arg2"];
new Obj();
new Obj(varargs);
new Obj("a", "b", 1, 2.5);

//method chaining
new Obj().foo().bar();

//static method
Obj.spam();