texts: Python algorithm for identification of low-level jets (meteorology)

texts:
A low-level jet is a local wind speed maximum near the surface. Baas (2009) defined a low-level jet as follows:

  the lowest maximum of the wind speed profile in the lowest 500 m of the atmosphere that is at least both 2 m/s and 25% faster than the next minimum above (...) A minimum is neglected if the wind speed above that minimum increases less than 1 m/s before decreasing again to values lower than the wind speed of that minimum. When no minumum is present, the lowest value of the wind speed profile above the jet is taken as a minimum.

I have a 2D numpy array that contains wind speed values at several measurement heights and times. I've written an algorithm to identify for each time step whether the wind profile obeys this criterion. However, I think my code can be improved. Right now I'm using nested loops and a lot of if statements. Also I need to catch an index error because I need to check whether the 'next' value in the array is lower or higher.

I was hoping to get some feedback from more experienced programmers. Here's my code:

def findLLJ(wspd_matrix, time, hgt):
  '''Find low-level jets according to Peter Baas' algorithm
     input: wind speed matrix with time as first axis and height as second axis
            time and height arrays
     output: jet index array, jet height array, jet speed array
     use: jetidx,jethgt,jetspd = findLLJ(wsp_matrix,time,height)'''
  #Allocate output arrays:
  jet = np.zeros(time.shape,dtype=bool)
  jetspd = np.zeros(time.shape)
  jethgt = np.zeros(time.shape)
  #Shape of input array:
  ntime,nlev = wspd_matrix.shape
  #Consistency check:
  if not (ntime == len(time) and nlev == len(hgt)):
    raise Exception("Shapes of input arrays are not consistent")
  #Loop over all wind profiles at given times
  for t,prof in enumerate(wspd_matrix):
    maxflg = False
    minflg = False
    maxspd = 0.
    #Loop over all vertical points in the profile
    for i,x in enumerate(prof):
      #Find out whether vertical point is a maximum
      if np.any(x>(prof[i:]+2.5)) and np.any(x>1.25*prof[i:]) and x>maxspd:
        maxflg = True
        maxind = i
        maxspd = x
        print 'Maximum found at time',t,'and level',i,'with speed',x,'m/s'
      #Find out whether vertical point is a minimum
      try:
        if x<0.8*maxspd and x<maxspd-2.5 and x<prof[i+1] and not prof[i+2]<x:
          minflg = True
          minind = i
          minspd = x
          print 'Minimum found at time',t,'and level',i,'with speed',x,'m/s'
      except IndexError:
        if i == nlev-2 and x<0.8*maxspd and x<maxspd-2.5 and x<(prof[nlev-1]-1):
          minflg = True
          minind = i
          minspd = x
          print 'Minimum found at time',t,'and level',i,'with speed',x,'m/s'
        else:
          minflg = True
          minind = nlev-1
          minspd = prof[nlev-1] # this should be changed to minumum of the profile, but that might return NaN, need to find an update for that.
          print 'No minumum found, using lowest value from profile'
      #Determine wheter a LLJ occured
      if maxflg and minflg:
        print 'Low-level jet found at time',t,'and height',hgt[maxind],'m with speed',maxspd,'m/s and minimum at',hgt[minind],'m with speed',minspd,'m/s'
        jet[t] = True
        jetspd[t] = maxspd
        jethgt[t] = hgt[maxind]
        break
      else:
        continue
  if maxflg and not minflg:
    print 'probably something wrong with NaNs'
  #End of loop, next profile...
  return jet,jethgt,jetspd


texts: Seq[Either[A, B]] => Either[A, Seq[B]] Function

texts:
I wrote a function of type Seq[Either[String,Int]] => Either[String, Seq[Int]]

scala> xs
res11: List[Either[String,Int]] = List(Right(1), Right(55))

scala> acc
res12: Either[String,Seq[Int]] = Right(List())

scala> xs.foldLeft(acc){ (acc, elem) => {
     |     acc.right.flatMap(list => elem.right.map(_ +: list) )
     | }}
res10: Either[String,Seq[Int]] = Right(List(55, 1))

Please review my foldLeft solution. Perhaps there's a higher order function that can more elegantly do this work?


texts: Fetch Reattempt and Hold Date count in efficient way

texts:
I am using 4 queries to get below 4 values , like this i need to use about 14 queries , Is there any way to reduce queries ?

<?php
echo " " . date("Y-m-d")." ";
echo "Reattempt : "." ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(reattemptdate) = CURDATE()
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

echo " "." Hold : ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(holddate) = CURDATE()
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;
echo "<br>";
?>

<?php
echo date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-1,date("Y")))." ";
echo "Reattempt : "." ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(reattemptdate) = DATE(NOW() - INTERVAL 1 DAY)
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

echo " "." Hold : ";

$sql =

"SELECT
 COUNT(*) as count FROM orders
 WHERE DATE(holddate) = DATE(NOW() - INTERVAL 1 DAY)
 ";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];
echo $numrowsresult;

?>


texts: Trading Card Game database schema for statistics

texts:
This database schema will be used in conjunction with various systems as related to an online Trading Card Game, mostly for permanent storage and statistics. Some example cases would include:

JDBC calling the DB to get information about player decks, or returning after-game stats;
Website displaying stats relating to the game via JavaScript, PHP, etc.

Any advice on naming, table relations and such are appreciated.

START TRANSACTION;
DROP SCHEMA IF EXISTS cardshifter_stats CASCADE;
CREATE SCHEMA cardshifter_stats;
SET SEARCH_PATH TO cardshifter_stats;

CREATE TABLE player
(
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    password TEXT NOT NULL, -- this will be made secure once implemented
    email TEXT,
    website TEXT NULL,
    about TEXT NULL,
    create_date TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(),
    delete_date TIMESTAMP WITHOUT TIME ZONE NULL DEFAULT NULL,
    last_seen_date TIMESTAMP NULL
);
CREATE TABLE mod
(
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT NULL,
    owner_player_id INT NOT NULL,
        FOREIGN KEY (owner_player_id) REFERENCES player(id),
    create_date TIMESTAMP WITHOUT TIME ZONE NULL DEFAULT NOW(),
    delete_date TIMESTAMP WITHOUT TIME ZONE NULL DEFAULT NULL
);
CREATE TABLE player_mod
(
    player_id INT NOT NULL,
        FOREIGN KEY (player_id) REFERENCES player(id),
    mod_id INT NOT NULL,
        FOREIGN KEY (mod_id) REFERENCES mod(id)
);
CREATE TABLE card
(
    id SERIAL PRIMARY KEY,
    version INT NOT NULL,
    name TEXT NULL,
    description TEXT NULL,
    effect_description TEXT NULL,
    type TEXT NULL,
    attack INT NULL,
    health INT NULL,
    mana_cost INT NULL,
    scrap_cost INT NULL,
    scrap_value INT NULL,
    sickness INT NULL,
    attack_available INT NULL,
    create_date TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(),
    delete_date TIMESTAMP WITHOUT TIME ZONE DEFAULT NULL
);
CREATE TABLE deck
(
    id SERIAL,
    version INT NOT NULL,
    player_id INT NOT NULL,
        FOREIGN KEY (player_id) REFERENCES player(id),
    mod_id INT NOT NULL,
        FOREIGN KEY (mod_id) REFERENCES mod(id),
    card_id INT NOT NULL,
        FOREIGN KEY (card_id) REFERENCES card(id),
    card_quantity INT NOT NULL
);
CREATE TABLE game_master
(
    game_id SERIAL PRIMARY KEY,
    player1 INT,
        FOREIGN KEY (player1) REFERENCES player(id),
    player2 INT,
        FOREIGN KEY (player2) REFERENCES player(id),
    start_time TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(),
    end_time TIMESTAMP WITHOUT TIME ZONE
);
CREATE TABLE game_actions
(
    game_id INT NOT NULL,
        FOREIGN KEY (game_id) REFERENCES game_master(game_id),
    turn INT NOT NULL,
    action_player INT NOT NULL,
        FOREIGN KEY (action_player) REFERENCES player(id),
    action_card INT NULL,
        FOREIGN KEY (action_card) REFERENCES card(id),
    action_attack INT NULL,
    target_player INT NULL,
        FOREIGN KEY (action_player) REFERENCES player(id),
    target_card INT NULL,
        FOREIGN KEY (action_player) REFERENCES player(id)
);

COMMIT;

SELECT
    tables.table_schema,
    tables.table_name,
    columns.column_name,
    columns.ordinal_position,
    columns.is_nullable,
    columns.data_type
FROM information_schema.tables AS tables
    INNER JOIN information_schema.columns AS columns
        ON tables.table_name = columns.table_name
WHERE
    tables.table_schema = 'cardshifter_stats'
ORDER BY
    tables.table_name ASC,
    columns.ordinal_position ASC;

This is what the schema looks like:


texts:
I studying for a Python course. I was finished working on task about creating a file class which can read, write lines to file. This class also needs magic methods (__add__, __str__, __iter__, __next__)

Can you review code and give a tip about improvements using the DRY principle (for example, how avoid to copy/paste with open).

from tempfile import gettempdir
from os import path
import uuid

class File():

    def __init__(self, file_path):
       self.file_path = file_path
       self.current_position = 0

    def __iter__(self):
       return self

    def __next__(self):
        try:
            with open(self.file_path, 'r') as f:
                f.seek(self.current_position)
                line = f.readline().strip()
                if not line:
                    self.current_position = 0
                    raise StopIteration('EOF')
                self.current_position = f.tell()
                return line
        except IOError:
            return 'Cant read next line'

    def write(self, line):
        try:
            with open(self.file_path, 'w') as file_obj:
                file_obj.write(line)
        except IOError as err:
            return 'Cant write to file: {0}'.format(err)

    def read(self):
        try:
            with open(self.file_path, 'r') as file_obj:
                return file_obj.read().strip()
        except IOError:
            return ''

    def __add__(self, obj):
        if isinstance(obj, File):
            tmp_file_path = path.join(gettempdir(), str(uuid.uuid4()))
            tmp_file = File(tmp_file_path)
            tmp_file.write(self.read() + '\n' + obj.read())
            return tmp_file

    def __str__(self):
        return self.file_path

f_obj = File('somepath1')
f_obj2 = File('somepath2')
f_obj3 = f_obj + f_obj2
for line in f_obj:
    print(line)
print(f_obj3.read())


texts:
This is a solution to the problem: "The Broken Pedometer" on the UVA online judge. (Note: I can not use anything beyond what is in g++ 4.6 which is what is used for the competition I'm training for.)

Algorithmic approach (pretty simple, but fast enough, not needed to understand to comment on the code):

possible_led_removals recursively attempts to remove one integer from all the strings in leds while maintaining a unique array of strings (leds):
If removing an integer leads to duplicates in leds, return (base case)
Otherwise, return the maximum amount of possible removals (depth) at the same index from the strings in leds, while maintaining leds to be an array of unique strings (recursion)

My C++ is /very/ rough, and I mostly use C++ because of the STL. However, I'd like to improve my C++ to improve my contest performance, so any help, algorithmic as well as code-wise is much appreciated! Thanks!

#include<iostream>
#include<cstdlib>
#include<vector>
#include<sstream>
#include<algorithm>
using namespace std;

size_t n_leds, n_symbols;

bool any_duplicates(vector<string> &leds)
{
  for(size_t i = 0; i < (int)leds.size(); ++i)
    for(size_t j = i + 1; j < (int)leds.size(); ++j)
      if(leds[i] == leds[j]) return true;

  return false;
}

int possible_led_removals(size_t erase_index, vector<string> leds, size_t depth)
{
  for(vector<string>::iterator it = leds.begin(); it != leds.end(); ++it) {
    string::iterator string_it;
    string_it = (*it).begin() + erase_index;
    (*it).erase(string_it);
  }

  int max_depth = 0;

  if (any_duplicates(leds)) {
    return depth;
  } else {
    for(size_t i = 0; i < (int)leds[0].length(); ++i)
      max_depth = max(possible_led_removals(i, leds, depth + 1), max_depth);
  }

  return max_depth;
}

int main()
{
  size_t problems;
  cin >> problems;

  for(size_t i = 0; i < problems; ++i) {
    cin >> n_leds >> n_symbols;

    vector<string> symbols;

    for(size_t j = 0; j < n_symbols; j++) {
      ostringstream led;

      for(size_t k = 0; k < n_leds; k++) {
        bool on;
        cin >> on;
        led << on;
      }

      symbols.push_back(led.str());
    }

    int max_removals = 0;
    for(int i = 0; i < n_leds; ++i)
      max_removals = max(max_removals, possible_led_removals(i, symbols, 0));

    cout << n_leds - max_removals << endl;
  }

  return 0;
}


texts: Google Code jam puzzle - Welcome to Code Jam

texts:
The problem is to count all possible sub-sequences of "welcome to code jam" in a given input string (and only return the last 4 digits of the count).  Here is the link to the problem for reference.

I've implemented a solution in Haskell that worked fine on the examples and small datasets but failed on the large data set. Here is the code:

I'm interested in correctness first. (Am I missing some corner case?) I guess performance can be improved by memoization; and I'd be happy get any other tips on that front too.

w_s is short for welcome_solve: This calculates the total number of sub-sequences.

w_s x [] = 0
w_s (x: []) str_xs = length ( filter (\z -> z==x) str_xs )
w_s (x:xs) (str_x:str_xs) = if x==str_x
                            then (w_s xs str_xs)  + (w_s (x:xs) str_xs)
                            else w_s (x:xs) str_xs

And here is the code to get the last 4 digits:

getLast4 (w:x:y:z: []) = [w,x,y,z]
getLast4 (x:xs) = getLast4 xs
format_solve problem
         | solution < 1000 = getLast4 $ show $ 10000 + solution
         | otherwise  = getLast4 $ show solution
         where solution = w_s "welcome to code jam" problem

Example usage:

λ> format_solve "format_solve welcome to codejam"
"0000"
λ> format_solve "wweellccoommee to code qps jam"
"0256"
λ> format_solve "elcomew elcome to code jam"
"0001"


texts: Copy autodiscovery results from list to an array

texts:
I copy addresses from the endpoints to an array that should only hold the endpoint addresses. This works but it seems so old school :/

Can I make this faster, better, more sexy (LINQ)?

public static EndpointAddress[] Find()
{
    EndpointAddress[] endpointAddresses = null;
    var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
    var findResponse = discoveryClient.Find(
        new FindCriteria(
            typeof(ICommunicationService)));

    if(findResponse != null)
    {
        if(findResponse.Endpoints.Count > 0)
        {
            endpointAddresses = new EndpointAddress[findResponse.Endpoints.Count];

            for (int i = 0; i <= findResponse.Endpoints.Count; i++)
            {
                endpointAddresses[i] = findResponse.Endpoints[i].Address;
            }
        }
    }

    return endpointAddresses ?? new EndpointAddress[0];
}


texts: Better option than "errno" for file IO error handling

texts:
I have the following method for opening a file:

void TankFile::OpenForReading(const std::string & filename)
{
    assert(!filename.empty());

    errno = 0;
    file.exceptions(0); // Don't throw
    file.open(filename, (std::fstream::in | std::fstream::binary));

    if (!file.is_open() || !file.good())
    {
        const char * errorStr = strerror(errno);
        throw TankFileError(Format("Failed to open Tank file \"%s\": '%s'", filename.c_str(), errorStr));
    }
}

The objective here is to attempt to open a file and throw TankFileError with a proper error description on failure. The caller will be expecting this exception type.

Everything works fine and I get a nice error message like this if the exception is thrown:

  Failed to open Tank file "unexistent_file": 'No such file or directory'

But what I don't like in that block is having to use the errno global and strerror().

A way around it would be to let the stream throw an exception, then catch it, get the error message from the what() member and re-throw with TankFileError, but I find this solution also a bit hackish, plus, in the tests I did, the resulting error message from std::fstream::failure was pretty cryptic:

void TankFile::OpenForReading(const std::string & filename)
{
    assert(!filename.empty());

    try
    {
        file.exceptions(std::fstream::failbit);
        file.open(filename, (std::fstream::in | std::fstream::binary));
    }
    catch (std::fstream::failure & err)
    {
        throw TankFileError(Format("Failed to open Tank file \"%s\": '%s'", filename.c_str(), err.what()));
    }
}

Produced the error message:

  Failed to open Tank file "unexistent_file": 'ios_base::clear: unspecified iostream_category error'.

Is there a better way to implement this? I was hoping that the new C++11 system_error library would provide a way to query this kind of error messages, but from what I've seen, you still have to pass errno around to get an error string.


texts: Finding the most popular element with C# given O(1) space complexity requirement

texts:
I have tried to solve the following problem in C# with LINQ:

  Given an integer array, find the most frequent number and it's count in the array. If multiple numbers have the same highest frequency return the smallest number.

One requirement here is also to make the code execute in O(1) space complexity.

public struct MostPoularItem
{
    public MostPoularItem(int item, int count)
    {
        Item = item;
        Count = count;
    }

    public int Item { get; }
    public int Count { get; }
}

public static class Utils
{
    public static MostPoularItem FindMostPopularElement(int[] integers)
    {
        if(integers == null)
        {
            throw new ArgumentNullException(nameof(integers));
        }

        return integers.GroupBy(x => x)
            .OrderBy(x => x.Key)
            .OrderByDescending(x => x.Count())
            .Select(x => new MostPoularItem(x.Key, x.Count()))
            .FirstOrDefault();
    }
}

Would be nice to have someone else's eye on this, especially around trying to see if there is any room of improving its time and space complexity. Feel free to offer alternative solutions which don't also use LINQ as well.


texts: Makefile that places object files into an alternate directory (bin/)

texts:
I'm trying to learn how to use makefiles, and this is my attempt at making a makefile that compiles source files in a source directory (src/) into object files that are created in a bin directory.

##########################################
#           Editable options             #
##########################################

# Compiler options
CC=g++
CFLAGS=-c -Wall
LDFLAGS=
EXECUTABLE_NAME=testes

# Folders
SRC=src
BIN=bin
OBJ=$(BIN)/obj

# Files
SOURCE_FILES=\
    main.cpp \
    test.cpp

##########################################
#    Don't touch anything below this     #
##########################################
OBJECT_FILES=$(addprefix $(OBJ)/, $(SOURCE_FILES:.cpp=.o))

build: create_directories create_executable
    @echo "Build successful!"

create_executable: create_objects
    @$(CC) $(LDFLAGS) $(OBJECT_FILES) -o $(BIN)/$(EXECUTABLE_NAME)
    @echo "Created executable."

create_objects: $(SOURCE_FILES)
    @echo "Created objects."

create_directories:
    @mkdir -p $(OBJ)

%.cpp:
    @echo "Compiling "$@
    @$(CC) $(LDFLAGS) -c $(SRC)/$@ -o $(OBJ)/$(patsubst %.cpp,%.o,$@)

clean:
    @rm -r -f $(BIN)

This makefile works, I just want to make sure I'm doing everything correctly.  Any changes you guys would suggest?


texts:
I am writing a method to find me a price range for special price as well as the retail price. Such as in example below I have price range for retail from 129 to 329 where as special price range is 89 to 199

array
0 =>
    array
            'id' => 83739000038374
            'special-price' => 99.99
            'retail-price' => 199
1 =>
    array
            'id' => 83739000038374
            'special-price' => 199.99
            'retail-price' => 299
2 =>
    array
            'id' => 83739000038374
            'special-price' => 89
            'retail-price' => 129
3 =>
    array
            'id' => 83739000038374
            'special-price' => 179
            'retail-price' => 329

my code is

public function getPriceRange(){
    $priceRange = array();
    $showRange = true;
    if($originalArray && count($originalArray) > 1){
        foreach($originalArray as $idx => $originalArraySingle){
            if($idx == 0){
            $priceRange['price']['max'] = $originalArraySingle['price'];
            $priceRange['price']['min'] = $originalArraySingle['price'];
            $priceRange['original-price']['max'] = $originalArraySingle['original-price'];
            $priceRange['original-price']['min'] = $originalArraySingle['original-price'];
            }else{
                if($originalArraySingle['price'] > $priceRange['price']['max'] ){
                    $priceRange['price']['max'] = is_int($originalArraySingle['price']) ? number_format((float)$originalArraySingle['price'], 2, '.', '') : $originalArraySingle['price'];
                }
                if($originalArraySingle['price'] < $priceRange['price']['min'] ){
                    $priceRange['price']['min'] = is_int($originalArraySingle['price']) ? number_format((float)$originalArraySingle['price'], 2, '.', '') : $originalArraySingle['price'];
                }
                if($originalArraySingle['original-price'] > $priceRange['original-price']['max'] ){
                    $priceRange['original-price']['max'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price'];
                }
                if($originalArraySingle['original-price'] < $priceRange['original-price']['min']){
                    $priceRange['original-price']['min'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price'];
                }
            }
        }
        //doesnt make sense to show price range if its same.
        if($priceRange['price']['max']===$priceRange['price']['min'] ||  $priceRange['price']['max']===$priceRange['price']['min']){
            $showRange = false;
        }
    }
    return $showRange ? $priceRange : null;
}

I am looking for scalability and for fastest code processing.


texts: GLSL function used to differentiate between pixels above/below a line

texts:
I've recently acquired a program which is capable of using a GLSL fragment shader as a plugin. After a short amount of experimentation, I've realized that - for my use-case - I desperately need a function that does the equivalent of the following:

Takes two 2D points and calculates a line between them
Returns 1.0 if the current pixel is above (or below, callers choice) the line, and 0.0 otherwise. If the points are horizontally coincident, "above" == "to the left"

For this reason I've created the slice function. For my use-case this function has the potential to be called many, many times within a single shader, and should be As Performant As Possible™, but I am no GLSL guru...

My current, working code is below. The function arguments are as follows:

aspect: the current pixel's coordinate
p1, p2: the points defining the line
top: whether above or below the line returns 1.0

//Note: !(x ^^ y) == XNOR(x, y)
float slice(vec4 aspect, vec2 p1, vec2 p2, bool top) {
    // degenerate case - shade left or right
    if (p2.x == p1.x) return float(!(top ^^ aspect.x < p1.x));

    // we must center the line over the leftmost point
    vec2 base = p2.x > p1.x ? p1 : p2;

    //calculate the line's slope
    float slope = (p2.y-p1.y) / (p2.x-p1.x);

    //return 1.0 or 0.0 according the rules defined above
    return float(!(top ^^ (aspect.y - base.y)>slope*(aspect.x - base.x)));
}

Can this code be made to run faster using only GLSL?


texts:
I'm new to data science. I wrote this script for plotting all different kinds of iris data set scatter plot. trying not to plot something with itself . how can I optimize my code ?

        from sklearn.datasets import load_iris
        import matplotlib.pyplot as plt
        import numpy as np

        import pandas as pd

        iris=load_iris()

        list1=[]

        fig, ax =plt.subplots(nrows=3,ncols=2,figsize=(10,10))

    for ii in range(4):
      for jj in range(1,4):
        if ii==jj:
          break
        if ii*jj not in list1[1::2]:
          list1.extend((ii+jj,ii*jj))
        elif ii+jj in list1[::2]:
          break
        a=ii
        b=jj
        x_index=ii
        y_index=jj
        colors=['blue','red','green']
        if ii==0:
          b=b-1
        elif jj==1:
          a=a-2
          b,a=a,b
        elif ii==3:
          a=a-1
          b=b-1
          a,b=b,a
        for label , color in zip(range(len(iris.target_names)),colors):
          ax[b,a].scatter(iris.data[iris.target==label,x_index]
                  , iris.data[iris.target==label,y_index]
                  , label=iris.target_names[label]
                  , color=color)

        ax[b,a].set_xlabel(iris.feature_names[x_index])
        ax[b,a].set_ylabel(iris.feature_names[y_index])
        ax[b,a].legend(loc="upper right")
        fig.tight_layout()
        fig.show()

this is the output
how would you write it if it was you?
I appreciate any help.


texts: Is this the most efficient way to track word changes in a string?

texts:
I'm working on a writing platform and am using a modified version of the Levenshtein distance algorithm to track a writer's engagement with their writing. It tracks not only words added to their content, but also rewards editing by including words removed and words substituted in the count.

Here's my algorithm in Ruby (which I run between (auto)saves):

def words_changed_since(second)
  first = self.split # array of words in first string
  second = second.split # array of words in second string

  # initialize the matrix
  matrix = [(0..first.length).to_a]
  (1..second.length).each do |j|
    matrix << [j] + [0] * (first.length)
  end

  # for each word in the second string
  (1..second.length).each do |i|
    # for each word in the first string
    (1..first.length).each do |j|
      if first[j-1] == second[i-1]
        matrix[i][j] = matrix[i-1][j-1]
      else
        matrix[i][j] = [
          matrix[i-1][j], # word deletion
          matrix[i][j-1], # word insertion
          matrix[i-1][j-1] # word substitution
        ].min + 1
      end
    end
  end
  return matrix.last.last
end

Is this the most efficient way of tracking these changes?


texts: A WinAPI C++ program for printing the master boot record of the hard drive

texts:
I have rolled this program for reading the MBR:

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>
#include <cctype>
#include <iostream>
#include <string>
#include <utility>

using std::isprint;
using std::cout;
using std::cin;
using std::move;
using std::size_t;
using std::string;

constexpr size_t MBR_SIZE = 512;
constexpr size_t BYTES_PER_LINE = 4;
constexpr size_t NUMBER_OF_LINES = MBR_SIZE / BYTES_PER_LINE;

// Converts 4 least significant bits of 'c' to corresponding
// hexadecimal string.
static string fourBitsToString(char c)
{
    string s = " ";

    if (c >= 0 && c <= 9) {
        s[0] = '0' + c;
    } else {
        c -= 10;
        s[0] = 'A' + c;
    }

    return move(s);
}

// Converts a character to its hexadecimal representation.
static string charToHex(char c)
{
    char lo = c & 0xf;
    char hi = (c >> 4) & 0xf;
    string s;
    char chars[] = {hi, lo};

    for (char ch : chars) {
        s += fourBitsToString(ch);
    }

    return std::move(s);
}

// Prints the MBR to console.
static void PrintMBR(char buffer[MBR_SIZE])
{
    size_t byteIndex = 0;
    string lineSeparator;
    string columnSeparator;

    for (size_t i = 0; i < NUMBER_OF_LINES; i++) {
        cout << lineSeparator;
        lineSeparator = '\n';
        columnSeparator = "";

        for (size_t j = 0; j < BYTES_PER_LINE; j++) {
            string ch = charToHex(buffer[byteIndex++]);
            cout << columnSeparator << ch;
            columnSeparator = " ";
        }

        cout << ' ';

        for (size_t j = 0; j < BYTES_PER_LINE; j++) {
            char c = buffer[byteIndex - BYTES_PER_LINE + j];
            cout << (isprint((unsigned int) c) ? c : '.');
        }
    }
}

// Reads the entire master boot record (MBR) into lpBuffer.
// Expects lpBuffer to point to a memory point that may
// hold at leasst 512 bytes.
static DWORD ReadMBR(PCHAR lpBuffer)
{

    HANDLE diskHandle = CreateFile(
        TEXT("\\\\.\\PhysicalDrive0"),
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);

    char* buffer = new char[MBR_SIZE];

    ReadFile(
        diskHandle,
        lpBuffer,
        MBR_SIZE,
        NULL,
        NULL);

    return GetLastError();
}

int main() {
    char buffer[MBR_SIZE];
    ReadMBR(buffer);
    PrintMBR(buffer);
    cin.get();
    return 3;
}

(Compile as Release instead of Debug if it throws a nasty runtime breakpoint.)

I would love to hear any comments possible, but my main question is whether it is  idiomatic C/C++/WinAPI.

Note: To see the actual MBR, run this as administrator.


texts: Optimize LINQ search with custom fixed ranking

texts:
I have to perform on some collection and return ranking based on some logic
I wish to optimize this working code since I think it can be bettered (maybe using tasks?).

I need to search on Counterparts item. I load this data from DB and I've got more aliases per counterpart.

I need to return the result based on those criteria:

Counterpart Code is equal to search string
Counterpart Code starts with search string
Counterpart Code contains search string
Counterpart Description contains search string
Counterpart Alias is equal to search string
Counterpart Alias starts with search string
Counterpart Alias contains search string

Each of those rules starts from Ranking 1 to 7 and I have to sort ok that ranking ascending.

public class Counterpart
{
    public int Id { get; set; }

    public string Code { get; set; }

    public string Description { get; set; }

    public IEnumerable<Alias> Aliases { get; set; }

    public override bool Equals(object obj)
    {
        Counterpart obj2 = obj as Counterpart;
        if (obj2 == null) return false;
        return Id == obj2.Id;
    }
}

public class Alias
{
    public int? Type { get; set; }

    public string Description { get; set; }
}

internal class CounterPartRanking
{
    public int Rank { get; set; }

    public Counterpart CounterPart { get; set; }
}

public static class CounterpartExtensions
{
    public static IEnumerable<Counterpart> SearchWithRank(this IEnumerable<Counterpart> source, string pattern)
    {
        var items1 = source.Where(x => x.Code == pattern);
        var items2 = source.Where(x => x.Code.StartsWith(pattern));
        var items3 = source.Where(x => x.Code.Contains(pattern));
        var items4 = source.Where(x => x.Description.Contains(pattern));
        var items5 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description == pattern));
        var items6 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description.StartsWith(pattern)));
        var items7 = source.Where(x => x.Aliases != null && x.Aliases.Any(y => y.Description.Contains(pattern)));

        Stopwatch sw = Stopwatch.StartNew();
        var rankedItems = new List<CounterPartRanking>();

        if (items1.Any())
            rankedItems.AddRange(items1.Select(x => new CounterPartRanking { Rank = 1, CounterPart = x }));
        if (items2.Any())
            rankedItems.AddRange(items2.Select(x => new CounterPartRanking { Rank = 2, CounterPart = x }));
        if (items3.Any())
            rankedItems.AddRange(items3.Select(x => new CounterPartRanking { Rank = 3, CounterPart = x }));
        if (items4.Any())
            rankedItems.AddRange(items4.Select(x => new CounterPartRanking { Rank = 4, CounterPart = x }));
        if (items5.Any())
            rankedItems.AddRange(items5.Select(x => new CounterPartRanking { Rank = 5, CounterPart = x }));
        if (items6.Any())
            rankedItems.AddRange(items6.Select(x => new CounterPartRanking { Rank = 6, CounterPart = x }));
        if (items7.Any())
            rankedItems.AddRange(items7.Select(x => new CounterPartRanking { Rank = 7, CounterPart = x }));

        sw.Stop();

        Debug.WriteLine("Time elapsed {0} for {1}", sw.Elapsed, pattern);
        var items = rankedItems.OrderBy(x => x.Rank).Select(x => x.CounterPart);
        var distinct = items.Distinct();

        return distinct;
    }
}


texts: Improving Point Cloud Slice Parameter's Adjusting loop

texts:
This part of the function is adjusting the sliceDepthSubtractor and startDepthSlice parameters that are used in order to take a geometrical slice (h) of a point cloud object (a[i]), that it will be used for determining if the object is a circle or not.

If the slice it is containing too few points in order to make a circle determination, the slice is retaken with different parameters before throwing an exception.

sliceDepthSubtractor and startDepthSlice are local parameters that are filled with data from XML file parsing class (The XML file is read at the application initialization inside of a dedicated class). Initial values are 1 (sliceDepthSubtractor) and 0.98 (startDepthSlice).

The list of point cloud object (a) is given as a parameter to this method.

As I hate nested loops, I would like to improve this code.

double sliceDepthSubtractor =  xlmClass.sliceDepthSubtractor;
double startDepthSlice      =  xlmClass.startDepthSlice;
bool adjustSliceDepthSubtractor = true;
while (adjustSliceDepthSubtractor)
{
   adjustSliceDepthSubtractor = false;
   bool adjustingStartDepthSlice = true;
   while (adjustingStartDepthSlice)
   {
     adjustingStartDepthSlice = false;
     for (int i = 0; i < Count; i++)
     {
        PointCloud h = TakeSlice(a[i],sliceDepthSubtractor,
                     startDepthSlice);

       if ((h.PointCount < 100) && (startDepthSlice > 0.10))
       {
         startDepthSlice  -= 0.1;
         adjustingStartDepthSlice  = true;
         break;
       }
       if ((h.PointCount < 100) && (sliceDepthSubtractor < 3))
       {
         sliceDepthSubtractor += 1;
         adjustSliceDepthSubtractor = true;
         break;
       }
       if (h.PointCount < 100)
       {
         throw new ComputationException("Insufficient Points");
       }
       LmsSolver(h, a[i]);
     }
   }
   if (adjustSliceDepthSubtractor) {continue;}
   Save(a);
}


texts:
I have made an equivalent of Python's "eval" command in Arduino (which in itself is quite a feat) but the part that decodes the output of it is not small enough to fit in another 30 functions since this will be running on an Arduino Micro.

Any suggestions on compacting it? (btw I don't care about the actual function, rather the bit in "void Loop()" since that part is gonna be repeated a lot.)

struct evals {
  int pointer;
  bool boolout;
  String stringout;
  int intout;
  float floatout;
};
String variables[50];
String LocalVariables[50];

void setup() {
  for (int Variable = 0; Variable < 50; Variable++) {
    LocalVariables[Variable] = "";
  }
  Serial.begin(9600);
  LocalVariables[0] = "TestVariable";
  variables[0] = "true";
}
void loop() {
  if (Serial.available()) {
    String read = Serial.readString();
    evals read2 = eval(read);
    switch (read2.pointer) {
      case 0:
        Serial.println("NULL");
        break;
      case 1:
        Serial.print("INT ");
        Serial.println(read2.intout);
        break;
      case 2:
        Serial.print("FLOAT ");
        Serial.println(read2.floatout);
        break;
      case 3:
        Serial.print("STRING ");
        Serial.println(read2.stringout);
        break;
      case 4:
        Serial.print("BOOL ");
        Serial.println(read2.boolout);
        break;
      case 5:
        read2 = eval(variables[read2.intout]);
        switch (read2.pointer) {
          case 0:
            Serial.println("NULL");
            break;
          case 1:
            Serial.print("INT ");
            Serial.println(read2.intout);
            break;
          case 2:
            Serial.print("FLOAT ");
            Serial.println(read2.floatout);
            break;
          case 3:
            Serial.print("STRING ");
            Serial.println(read2.stringout);
            break;
          case 4:
            Serial.print("BOOL ");
            Serial.println(read2.boolout);
            break;
        }
    }
  }
}
struct evals eval(String input) {
  evals output;
  input.replace("\n", "");
  input.replace("\r", "");
  char input2[input.length() + 1];
  input.toCharArray(input2, input.length() + 1);
  if (input.length() == 0) {
    output.pointer = 0;
    return output;
  }
  if (input2[0] == '"' and input2[strlen(input2) - 1] == '"') {
    input.remove(0, 1);
    input.remove(strlen(input2) - 2, 1);
    output.pointer = 3;
    output.stringout = input;
    return output;
  } else if (input == "true") {
    output.pointer = 4;
    output.boolout = true;
    return output;
  } else if (input == "false") {
    output.pointer = 4;
    output.boolout = false;
    return output;
  } else {
    String inputs = input;
    inputs.replace("0", "");
    inputs.replace("1", "");
    inputs.replace("2", "");
    inputs.replace("3", "");
    inputs.replace("4", "");
    inputs.replace("5", "");
    inputs.replace("6", "");
    inputs.replace("7", "");
    inputs.replace("8", "");
    inputs.replace("9", "");
    if (inputs.length() == 0) {
      output.pointer = 1;
      output.intout = input.toInt();
      return output;
    } else {
      if (inputs[0] == '.' and inputs.length() == 1) {
        output.pointer = 2;
        output.floatout = input.toFloat();
        return output;
      } else {
        for (int Variable = 0; Variable < 50; Variable++) {
          if (LocalVariables[Variable] == "") {
            continue;
          } else if (LocalVariables[Variable] == input) {
            output.pointer = 5;
            output.intout = Variable;
            return output;
          }
        }
        output.pointer = 0;
        return output;
      }
    }
  }
}


texts:
Follow up of - Which is a better implementation of a stack data structure (based on an array)?

Please review my stack implementation from before.  I've made it dynamically sized if needed and made a few tweaks.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct
{
    int *elementData;
    unsigned int stackSize;
    unsigned int capacityIncrement;
    unsigned int elementCount;
} Stack;

void initializeStack(Stack*, unsigned int, unsigned int);
void stackPush(Stack*, int);
int stackPop(Stack*);
int stackPeek(Stack*);
bool isStackEmpty(const Stack*);
void setCapacityIncrement(Stack*, unsigned int);
int getNumberOfElements(const Stack*);
int getStackSize(const Stack*);

int main()
{
    Stack s1;
    initializeStack(&s1, 4, 10);
    for(int i = 0; i < 25; i++)
    {
        stackPush(&s1, i + 1);
    }
    stackPop(&s1);
    stackPush(&s1, 88);
    stackPush(&s1, 25);
    printf("The top of the stack is %d.\n", stackPeek(&s1));
    while(!isStackEmpty(&s1))
    {
        int top = stackPop(&s1);
        printf("Popping %d from the top of the stack.\n", top);
    }
    return 0;
}

void initializeStack(Stack *p, unsigned int stackSize, unsigned int capacityIncrement)
{
    p->elementData = calloc(stackSize, sizeof(int));
    p->stackSize = stackSize;
    p->capacityIncrement = capacityIncrement;
    p->elementCount = 0;
}

void stackPush(Stack *p, int value)
{
    if (p->elementCount == p->stackSize)
    {
        p->stackSize *= p->capacityIncrement;
        p->elementData = (int*)realloc(p->elementData, sizeof(int) * p->stackSize);
    }
    p->elementData[p->elementCount] = value;
    p->elementCount++;
}

int stackPop(Stack *p)
{
    if (!isStackEmpty(p))
    {
        p->elementCount--;
        return p->elementData[p->elementCount];
    }
    fputs("ERROR : Stack is empty!", stderr);
    return 0;
}

int stackPeek(Stack *p)
{
    if (!isStackEmpty(p))
    {
        p->elementCount--;
        int topValue = p->elementData[p->elementCount];
        p->elementCount++;
        return topValue;
    }
    fputs("ERROR : Stack is empty!", stderr);
    return 0;
}

bool isStackEmpty(const Stack *p)
{
    return p->elementCount == 0;
}

void setCapacityIncrement(Stack *p, unsigned int capacityIncrement)
{
    p->capacityIncrement = capacityIncrement;
}

int getNumberOfElements(const Stack *p)
{
    return p->elementCount;
}

int getStackSize(const Stack *p)
{
    return p->stackSize;
}


texts:
I have a task to write the function:
  int read_palindrome(); // input comes from stdin

which will read one line from standard input and returns 1 if the line is a palindrome and 0 otherwise. A line is terminated by the newline character (’\n’) and the does not include the newline.

There are requirements to be met:

There is no assumption about the length of the input.
You are also not allowed to read the input twice, e.g. read the input, forget you read the input but remember the length, read the input again. which results in the input being read twice.

You are also not allowed to create a very large buffer to store the input reasoning that the input line might be expected to be smaller than a very large buffer.
The reason for this restriction is that we will consider the memory usage of the program.

The task is to come out with a correct program with the best CPU time and memory usage.

I have attempted my code below. May I know if there is anything I could improve on here to optimise for correctness, CPU and memory?

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

int read_palindrome();
int check_palindrome2(char *, int);

int main()
{
    if (read_palindrome()) printf("input is a palindrome");
    else printf("input is not a palindrome");
    return 0;
}

int read_palindrome() {
    unsigned int len_max = 128;
    unsigned int current_size = 0;
    char *pStr = malloc(len_max);
    current_size = len_max;
    int i;
    char c;
    if (pStr != NULL) {
        while (( c = getchar() ) != '\n') {
            pStr[i] = (char)c;
            i++;
            if(i == current_size) {
                current_size = i+len_max;
                pStr = realloc(pStr, current_size);
            }
        }

        pStr[i] = '\0';
        free(pStr);
    }
    return check_palindrome2(pStr,i);
}

int check_palindrome2(char *s, int length) {
    for (int i = 0; i < length; i++) {
        if (s[i]!= s[length-i-1]) {
            return 0;
        }
    }
    return 1;
}


texts: Boost::python class overloading, issues in exposing more than one constructor

texts:
I am very new to boost::python and I am doing the first experiments.
The following code works, but how to improve the code exposing also the non empty constructor?
Some failed attempts have been commented...

#include <string>
#include <sstream>

class Box
{

    private:

        std::string m_box_name;  // m_ for class variable k_ for class constant
        float m_height;
        float m_length;
        float m_width;

    public:

        // constructors:
        Box() {
            m_box_name = "default box";
            m_height = 1.0;
            m_width = 1.0;
            m_length = 1.0;
        }

        Box(std::string box_name, float height, float width, float length) {
            m_box_name = box_name;
            m_height = height;
            m_width = width;
            m_length = length;
        }

        // destructors:
        ~Box() {}

        // getters:
        std::string get_name() {
            return m_box_name;
        }

        float get_height() {
            return m_height;
        }

        float get_width() {
            return m_width;
        }

        float get_length() {
            return m_length;
        }

        //setter methods
        void set_name(std::string box_new_name) {
            m_box_name = box_new_name;
        }

        void set_height(float new_height) {
            m_height = new_height;
        }

        void set_width(float new_width) {
            m_width = new_width;
        }

        void set_length(float new_length) {
            m_length = new_length;
        }

        // extra

        float get_surface() {
            return 2 * m_height * m_width + 2 * m_width * m_length + 2 * m_length * m_height;
        }

        float get_volume() {
            return m_height * m_width + m_width;
        }

        // viewer
        std::string get_info() {
            std::string s = "info here";
            return s;
        }

};

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(box)
{
    class_<Box>("Box")
        .def(init<>())
        //.def(init<std::string , float, float, float>())
        //.def("__init__" Box::Box(std::string , float, float, float))
        .add_property("name", &Box::get_name, &Box::set_name)
        .add_property("height", &Box::get_height, &Box::set_height)
        .add_property("width", &Box::get_width, &Box::set_width)
        .add_property("length", &Box::get_length, &Box::set_length)
        .add_property("surface", &Box::get_surface)
        .add_property("volume", &Box::get_volume)
        .add_property("info", &Box::get_info);

}


texts:
Starting from React 16.3 there are some new lifecycle methods introduced. One of them is the static getDerivedStateFromProps(props,state) method. This method essentially synchronizes properties and state.

The props and state of a react component aren't always a one-on-one match. But for simple components often a couple of props do match exactly on the state.

It's not strictly necessary to have this getDerivedStateFromProps(...) method actually. If your component doesn't really have an internal state, then there is no need to worry about it.

Anyway, in a case where there is an exact match of props and state I am trying to find the most elegant way to write this code.

The following is rather verbose:

static getDerivedStateFromProps(props, state) {
  // these 3 properties can change over time.
  const activeBaseNode = props.activeBaseNode;
  const filterOID = props.filterOID;
  const quickFilterRequest = props.quickFilterRequest;

  // compare them to the state
  if ((state.filterOID !== filterOID) ||
    (state.activeBaseNode !== activeBaseNode) ||
    (state.quickFilterRequest !== quickFilterRequest)) {

    // updates the state
    return ({ activeBaseNode, filterOID, quickFilterRequest });
  }

  // no changes --> no updates
  return null;
}


texts: Customized method for dataframe in my analysis module

texts:
Please download the file and save in home directory and extract it:

https://www.dropbox.com/s/swtw8bk35zr1i6d/analyse.7z?dl=0

I can get some warrants info.

import analyse
df = analyse.warrants.get('0788')

Now we got 0788's warrants info. It output df with better format:

analyse.tabulate.tabulate(df)

I want to simply the expression as df.tabulate(). How do I refactor the code in analyse directory?

Show content in tabulate.py:

import pandas as pd
from terminaltables import AsciiTable

def tabulate(df):
    rows = len(df)
    head = [df.columns.tolist()]
    nr = df.values.tolist()
    content = head + nr
    table = AsciiTable(content)
    data_str = table.table.split('\n')
    sep_line = data_str[0]
    transformed_str = []
    for ind in range(0,len(data_str)-1):
        if ind < 3 :
            transformed_str.append(data_str[ind])
        else:
            transformed_str.append(data_str[ind])
            transformed_str.append(sep_line)
    new_str = "\n".join(transformed_str) + '\n' + '\n'  + '[ {} records ]'.format(rows-1)
    print(new_str)

I want to refactor analyse.tabulate.tabulate(df) as df.tabulate(). It is the simplest way to use df.tabulate() to get well-formatted dataframe.


texts: De-linearize a 2d linearized grid and calculate distance between 2 points

texts:
In a simulation of mine, for which performance is paramount, I have the following bottleneck.

I have a huge 2D grid of dimensions width and height, whose dimensions are stored in linearized form, i.e. positions at x and y are stored as one integer x + y*width. Every iteration I have to get thousands of such linearized coordinates, de-linearize an calculate distance between 2d coordinates.

Currently, what I do is:

y1 = linPos1 / width; //int divided by int disregards remainders
x1 = linPos1 - width * y1;

y2 = linPos2 / width; //int divided by int disregards remainders
x2 = linPos2 - width * y2;

int xDiff = x2-x1;
int yDiff = y2-y1;
double distance = sqrt(xDiff*xDiff  + yDiff*yDiff);

How could I improve upon that? What is the most performant way to take two of such integer values, retrieve back x and y and then calculate the 2D distance between said points? I am open to all suggestions, including SIMD instructions.


texts: Is it bad practice to have executable code in my channel state object?

texts:
I have a CommunicationStateMachine object that's attached to my channels. It keeps track of who's turn it is to speak, how far along the conversation the server and client are, things like the client ID, all bytes read to date, the ByteBuffer etc.

My previous version of this server did some checks in the Selector thread (bad idea, I know), like checking if the message was complete, and checking if the client was a valid one.
To that end I had the methods that did those checks declared in the CommunicationStateMachine.class and the Selector thread called those methods on every OP_READ pass.

Now I'm removing all that work and putting the responsibility on the worker threads, and in order to keep things a bit cleaner I've decided to use the State design pattern. I've made a class called Processor.class which contains abstract methods.
Depending on what mode the server is in (reading/writing text or reading/writing hex commands) I've created classes that extend Processor.class and implement it's methods. The result of the JSON mode processor so far is this:

public class JsonMode extends Processor {

    @Override
    public void processBytes(CommunicationStateMachine commsState,
            DataDAO database) {

        boolean validHeaderFormat = commsState.isValidClientHeaderFormat();

        if (validHeaderFormat) {

            boolean messageComplete = commsState.checkJsonMessageIntegraty();
            log.debug("JsonProcessor: messageComplete: " + messageComplete);
            String deviceId = commsState.getDeviceId();
            FirmwareFile file = database
                    .checkScheduledFirmwareUpgrade(deviceId);
            if (file != null) {
                commsState.setScheduledUpdate(true);
                log.debug("This is a scheduled update for " + deviceId
                        + " for file: " + file);
            } else {
                commsState.setScheduledUpdate(false);
                log.info("Device "
                        + deviceId
                        + ": Not scheduled for an update, scheduledUpgrade returned null");
            }
        }
    }

    @Override
    public void prepareWriteBytes(CommunicationStateMachine commsState,
            DataDAO database) {
        // TODO Auto-generated method stub

    }

}

So my thinking here, is that the methods in the commsState object that are called here, such as commsState.isValidClientHeaderFormat() and commsState.checkJsonMessageIntegraty() should be removed from the CommunicationStateMachine object and placed in the JSONMode.class processor, meaning I will only call get and set methods from commsState and keep all processing outside that class.
This is the way to go right?  My thinking is otherwise I'll either start adding callable code for the other modes to the CommunicationStateMachine.class and it will get more unwieldy, or I'll have JSONMode code in the CommunicationStateMachine.class and other Modes codes outside, which would definitely be wrong.

Any other thoughts you might have on this process would be greatly appreciated too.


texts: Thread safe enqueue and dequeue method in Queue

texts:
As an exercise, I have implemented a linked queue whose enqueue and dequeue methods are synchronized. There is a Producer thread which keeps inserting elements into the queue as long as there are less than 10 items in it. When the queue is full, the thread waits. The second thread Consumer keep removing elements  from queue as long as it is not empty. I would like to get a review of this code - is there any flaw? How could I improve it?

MyLinkedQueue.java

public class MyLinkedQueue<T> implements Iterable<T> {
  private Node first, last;
  private int size = 0;
  private static final int MAX_QUEUE_SIZE = 10;
  public Iterator<T> iterator() { return new QueueIterator(); }

  private class Node {
    T item;
    Node next;
  }

  public boolean isEmpty() { return first == null; }
  public boolean isFull() { return MAX_QUEUE_SIZE == size(); }

  public synchronized void enqueue(T item) throws InterruptedException {
      while (isFull()) {
        wait();
      }

      Node oldLast = last;
      last = new Node();
      last.item = item;
      last.next = null;

      if (isEmpty()) {
        first = last;
      } else {
        oldLast.next = last;
      }
      notifyAll();
      size++;
    }

  public synchronized T dequeue() throws InterruptedException {
      while (0 == size()) {
        wait();
      }

      T item = first.item;
      first = first.next;

      if (isEmpty()) { last = null; }
      size--;
      notifyAll();
      return item;
    }

  public synchronized int size() { return size; }

  private class QueueIterator implements Iterator<T> {
    private Node current = first;

    public boolean hasNext() { return current != null; }
    public void remove() {}
    public T next() {
      T item = current.item;
      current = current.next;
      return item;
    }
  }
}

Producer.java

public class Producer implements Runnable {
  private static final int DELAY = 1000;
  private MyLinkedQueue queue;
  private int count;

  public Producer(MyLinkedQueue queue, int count) {
    this.queue = queue;
    this.count = count;
  }

  public void run() {
    try {
      for (int i = 0; i < count; ++i) {
        queue.enqueue(new Date().toString());
        Thread.sleep(DELAY);
      }
    } catch(InterruptedException e) {
    }
  }
}

Consumer.java

public class Consumer implements Runnable {
  private static final int DELAY = 1000;
  private MyLinkedQueue queue;
  private int count;

  public Consumer(MyLinkedQueue queue, int count) {
    this.queue = queue;
    this.count = count;
  }

  public void run() {
    try {
      for (int i = 0; i < count; ++i) {
        queue.dequeue();
        Thread.sleep(DELAY);
      }
    } catch(InterruptedException e) {
    }
  }
}

QueueThreadrunner.java

public class QueueThreadrunner {
  public static void main(String[] args) {
    MyLinkedQueue queue = new MyLinkedQueue();
    final int THREADS = 10;
    final int REPETITIONS = 50;

    for (int i = 1; i <= THREADS; ++i) {
      Producer pr = new Producer(queue, REPETITIONS);
      Consumer cr = new Consumer(queue, REPETITIONS);

      Thread dt = new Thread(pr);
      Thread wt = new Thread(cr);

      dt.start();
      wt.start();
    }
  }
}


texts: Moving files while preserving the folder structure

texts:
I'm writing a console application that will look through a directory and move any log files that have a date modified older than X days (configurable in the app.config file).

The problem I'm having is with the Move method I wrote. It works, but I think there might be a better way to write this method and eliminate the need for the sourceRoothPath parameter. Here's what I have (it's part of a LogManager class I wrote to do the checking and moving of log files):

public void Move(string sourceRootPath, string sourcePath, string targetPath)
{
    if (String.IsNullOrWhiteSpace(sourcePath))
        throw new ArgumentNullException("sourcePath");

    if (String.IsNullOrWhiteSpace(targetPath))
        throw new ArgumentNullException("destinationPath");

    if (!File.Exists(sourcePath))
        throw new FileNotFoundException(sourcePath);

    try
    {
        // trimmedPath becomes the file path with all the subfolders, but without the
        // sourceRootPath that comes in front of it. i.e. it strips the value passed
        // in sourceRootPath from the value passed in sourcePath. The "+ 1" is to include the
        // trailing "\" in the path.
        string trimmedPath = sourcePath.Substring(sourceRootPath.Length + 1);
        string newPath = Path.Combine(targetPath, trimmedPath);
        string fileName = Path.GetFileName(sourcePath);

        // folderStructure is used for creating the subfolder structure I want to preserve.
        // (It is just removing the file name and extension from the newPath.)
        string folderStructure = newPath.Substring(0, (newPath.Length - fileName.Length));

        // Directory.CreateDirectory will create the entire folder structure for me; no need
        // for looping or recursive calls.
        Directory.CreateDirectory(folderStructure);

        // File.Move has no ability to overwrite, so I have to delete the file if it exists in the
        // destination directory so that File.Move doesn't throw an exception.
        if (File.Exists(newPath))
            File.Delete(newPath);

        File.Move(sourcePath, newPath);
        loggingService.LogInfo("Moved file from " + sourcePath + " to " + newPath + ".");
    }
    catch (Exception ex)
    {
        loggingService.LogError(ex.Message);
        throw ex;
    }
}

I included the sourceRootPath parameter because I need this method to duplicate the folder structure of the sourcePath, but I don't want it to include some of the top level folders.

So, for example, if I'm having this application scan a log file directory at C:\someFolder\test\logs, and there are some subfolders like production\someDate or HR\HRSystem\someDate etc. I want to keep the subfolder structure in the production and HR folders, but move them to a new location like C:\test_log_archive. So C:\someFolder\test\logs\production\someDate should become C:\test_log_archive\production\someDate, and the value I would pass for sourceRootPath would be C:\someFolder\test\logs.

Does it make sense to remove the sourceRootPath and how would I do it? I feel like I should be able to accomplish this with just sourcePath and targetPath parameters, but I can't figure out a way to do it other than the code I provided above.


texts:
I am a beginner in python and to learn python I have written this program. How can this code be improved? Should I use main method in this program? Python

lst = []

def insertion_sort(thelist):
    for index in range(1, len(thelist)):
        key = thelist[index]
        position = index - 1
        while position >= 0 and thelist[position] > key:
            thelist[position + 1] = thelist[position]
            position = position - 1
        thelist[position + 1] = key

n = int(input("Enter number of elements: "))
for i in range(0, n):
    ele = int(input())
    lst.append(ele)

insertion_sort(lst)
print(*lst, sep = ", ")


texts: Trim certain characters from a string in JavaScript

texts:
I want to remove not only spaces, but certain characters, as well from the beginning or end of a JavaScript string.

function trim(str, characters) {
  var c_array = characters.split('');
  var result  = '';

  for (var i=0; i < characters.length; i++)
    result += '\\' + c_array[i];

  return str.replace(new RegExp('^[' + result + ']+|['+ result +']+$', 'g'), '');
}

The function can be used as follows:

trim(' - hello**   +', '+*- ');

The escaping is required as + * . etc. would be used in the regular expression. Is there a better way to trim any character in JavaScript? Or a better way to do the escaping, as not every character needs it?


texts: Producing triangles of asterisks based on height

texts:
I have created a simple terminal program: it allows the user to enter a height and it will produce triangles of asterisks (*'s) based on the height.

I have just started learning C# as practice for my internship. I would appreciate any feedback.

using System;

public class Triangle
{
    public int height;
    private string pyramid = "";

    public Triangle(int height)
    {
        this.height = height;
    }

    public String makeTriangle()
    {
        //4
        //   *    = 1         ***+***  = Even on both sides  7/2
        //  ***   = 3 - (+2)  **+++**  =
        // *****  = 5 - (+2)  *+++++*
        //******* = 7 - (+2)  +++++++
        int cutEnds = biggestOddNumber() / 2;

        for (int i = 0; i < height; i++)
        {
            for (int j = 1; j <= biggestOddNumber(); j++)
            {
                String singleElement = "*";

                if (j <= cutEnds || j > (biggestOddNumber()-cutEnds))
                {
                    pyramid = pyramid + " ";
                }
                else
                {
                    pyramid = pyramid + singleElement;
                }

                if (j == biggestOddNumber())
                {
                    pyramid = pyramid + "\r\n";
                }
            }
            cutEnds--;

        }
        return pyramid;
    }

    public int biggestOddNumber()
    {
        // 1 2 3 4 5 6 7 8 9 10
        // ?   ?   ?   ?
        //
        //Formula for Odd Numbers = 2n + 1
        //2*0 + 1 = 1
        //2*1 + 1 = 3
        //2*2 + 1 = 5
        //...
        // we do height -1 since if you look at formula we start from 0 not 1
        // if we do 2*4 + 1 = (9)
        //4
        //   *    = 1
        //  ***   = 3 - (+2)
        // *****  = 5 - (+2)
        //******* = 7 - (+2) However it should be (7)

        return (2 * (height-1) + 1);

    }
}

Main method

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter height of pyramid");
            int height = int.Parse(Console.ReadLine());
            Triangle triangle = new Triangle(height);
            Console.WriteLine(triangle.makeTriangle());
        }
    }
}


texts: Replacing a for loop that iterates over an array with the functional programming equivalent

texts:
How would I accomplish the same thing in a functional paradigm?

Player.prototype.d2 = function(ratingList, rdList) {
    var tempSum = 0;
    for (var i = 0; i < ratingList.length; i++) {
        var tempE = this.e(ratingList[i], rdList[i]);
        tempSum += Math.pow(this.g(rdList[i]), 2) * tempE * (1 - tempE);
    }
    return 1 / Math.pow(q, 2) * tempSum;
};


texts:
I've been working on a new project and I've found myself needing to make multiple Ajax calls, often on the same page and at the same time. I decided rather than repeating code that I would try and make a reusable object that to handle these calls.

I'm very new to Object Orientated JavaScript so I'm looking for some feedback and advice on my code; am I doing it right? is there something I'm not doing? should I be doing things differently etc?

Here's my Ajax constructor:

/**
 *
 * AjaxRequest Constructor
 *
 * @param url
 * @param success_callback
 * @param limit
 * @param type
 * @constructor
 */

function AjaxRequest (url, success_callback, limit, type) {
    this.url = url;
    this.success_callback = success_callback;
    this.limit =  limit || 3;
    this.type = type || "POST";

    //init ajax
    this.init();
}

/**
 * initialise
 * ajax
 */

AjaxRequest.prototype.init = function () {

    var _self = this;

    $.ajax({
        dataType: "json",
        url: this.url,
        type: this.type,
        data: {
            member_id: 1,
            limit: this.limit
        },
        beforeSend : function (){
            console.log('loading');
            //spinner.spin(target);
        },
        success: function (response) {
            if (response.success === 1) {
                _self.success_callback(response);
            }
        },
        error: function (a, b, c) {

        }
    });
}

/**
 * change number of
 * displayed outputs
 * @param limit
 */

AjaxRequest.prototype.set_limit = function (limit) {
    this.limit = limit;
    this.init();
}

and here is how I'm calling it

/**
 * instantiate getAchievements
 * @type {AjaxRequest}
 */

getAchievements = new AjaxRequest("/ajax-member/get-achievements", function (response) {

    var i,
        container = document.getElementsByClassName('achievements-container')[0],
        achievements_data = '';

    for (i in response.achievements) {
        achievements_data += ("

" + response.achievements[i].t_achievement_name + "
" + response.achievements[i].t_achievement_description + "

");
    }

    container.innerHTML = achievements_data;
});

/**
 * instantiate getComments
 * @type {AjaxRequest}
 */

getComments = new AjaxRequest("/ajax-member/get-comments", function (response) {

    var i,
        container = document.getElementsByClassName('comments')[0],
        comments_data = '';

    for (i in response.comments) {
        comments_data += ("

" + response.comments[i].t_fname + " " + response.comments[i].t_lname + "
" + response.comments[i].t_comment_content + "

");
    }

    container.innerHTML = comments_data;
});

It would be good to hear some feedback on this.  I'm always looking to improve and find the best ways of doing things so if you spot something I should be doing differently then please shout.


texts:
https://leetcode.com/problems/number-of-enclaves/
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.
Example 1:
Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.
Example 2:
Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.
Note:
1 <= A.length <= 500
1 <= A[i].length <= 500
0 <= A[i][j] <= 1
All rows have the same size.
please review for performance.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/number-of-enclaves
    /// </summary>
    [TestClass]
    public class NumberOfEnclavesTest
    {

        [TestMethod]
        public void FirstTest()
        {

            int[][] A =
            {
                new[] { 0, 0, 0, 0 },
                new[] { 1, 0, 1, 0 },
                new[] { 0, 1, 1, 0 },
                new[] { 0, 0, 0, 0 }
            };
            int expected = 3;
            Assert.AreEqual(expected, NumEnclaves(A));

        }

        [TestMethod]
        public void FailedTest()
        {

            int[][] A =
            {
                new[] { 0, 1, 1, 0 },
                new[] { 0, 0, 1, 0 },
                new[] { 0, 0, 1, 0 },
                new[] { 0, 0, 0, 0 }
            };
            int expected = 0;
            Assert.AreEqual(expected,NumEnclaves(A));

        }

        public int NumEnclaves(int[][] A)
        {
            int count = 0;
            for (int row = 1; row < A.Length - 1; row++)
            {
                for (int col = 1; col < A[0].Length - 1; col++)
                {
                    if (A[row][col] != 0)
                    {
                        bool isDone = false;
                        int res = DFS(row, col, A, ref isDone);
                        if (!isDone)
                        {
                            count += res;
                        }
                    }
                }
            }
            return count;
        }

        private int DFS(int row, int col, int[][] A, ref bool isDone)
        {
            if (row <= 0 || col <= 0 || row >= A.Length-1 || col >= A[0].Length-1 )
            {
                if (A[row][col] == 1)
                {
                    isDone = true;
                }
                return 0;
            }

            if (A[row][col] == 0)
            {
                return 0;
            }

            int count = 1;
            A[row][col] = 0;
            count += DFS(row, col - 1, A,ref isDone);
            count += DFS(row, col + 1, A,ref isDone);
            count += DFS(row - 1, col, A,ref isDone);
            count += DFS(row + 1, col, A,ref isDone);
            if (isDone)
            {
                count = 0;
            }
            return count;
        }
    }
}


texts:
I want to use the variables that have been declared in a config.php file in a class for testing. I am not sure if this is the right way like I have done it.

I have a configuration file, config.php:

class Config {

    public $hosts = array(
        'a' => '192.168.1.10'
        'b' => '192.168.1.11',
    );

    public $ports = array(
        'a' => 22,
        'b' => 22,
    );
}

These are the variables I want to include in a file called Tests.php:

require_once 'config.php';

    class Test extends PHPUnit_Framework_TestCase
    {
        protected $hosts;
        protected $ports;
        ...

        public function __setUp()
        {
            $config = new Config();
            $this->hosts = $config->hosts;
            $this->portsSsh = $config->ports;
            ...
        }

        public function testConnect()
        {
            $session = $this->connect($this->hosts['a'], $this->ports['a']);
            $this->closeConnection($session);
        }
    ...
    }

Is it right doing it like this? I have the impression it is too complicated. I have to make a class for the config.php file and in the test class I have to do like a mapping $this->hosts = $config->hosts.

That I don't like so much, because I have about 14 variables and first I have to declare them all and later I have to assign them all in the setUp() method. Isn't there a shorter or simpler way? I was thinking of using a loop and I don't want to use globals.

I wonder if I should do it like this:

require_once 'config.php';

        class Test extends PHPUnit_Framework_TestCase
        {
            protected $hosts;
            protected $ports;
            ...

            public function __setUp()
            {
                $this->config = new Config();
            }

            public function testConnect()
            {
                $session = $this->connect($this->config->hosts['a'], $this->config->ports['a']);
                $this->closeConnection($session);
            }
        ...
        }


texts:
Given a string, find its rank among all its permutations sorted
  lexicographically. For example, rank of “abc” is 1, rank of “acb” is
  2, and rank of “cba” is 6. Assuming there is no duplicated character.

The following is my code:

#include <iostream>
using namespace std;

// A utility function to find factorial of n
int factorial(int i)
{
    if(i == 0)
        return 1;
    return i*factorial(i-1);
}

// A utility function to count smaller characters
// starting from index of ind
int count_smaller_than_cur(string& s, int ind)
{
    int count = 0;
    for(int i = ind+1; i < s.size(); ++i)
        if(s[i] < s[ind])
            count++;
    return count;
}

// A function to find rank of a string in all permutations
// of characters
int rank(string& s)
{
    int r=1;
    int len = s.size();
    int f = factorial(len);

    for(int i=0; i < len; ++i)
    {
        f /= (len-i);

        // count number of chars smaller than str[i]
        // fron str[i+1] to str[len-1]
        int t = count_smaller_than_cur(s, i);
        r += t*f;
    }

    return r;
}

int main()
{
    string str("string");
    cout << rank(str) << endl;

    system("pause");
    return 0;
}

Can anyone help me check it?


texts: How May I extract this ternary operator in independent statement

texts:
Somehow this code looks messy to me:

 var results = query.GroupBy(x => x.ProductStatusId == ProductStatus.Sold || x.ProductStatusId == ProductStatus.OnHold ? "Delivered" :
                                x.ProductStatusId == ProductStatus.Shiped ? "Shiped" :
                                x.ProductStatusId == ProductStatus.NotAvailable ? "NotAvailable" :
                                x.ProductStatusId == ProductStatus.Paid ? "Paid" : "New").Where(g => g.Key != "New")

Is it possible to extract this ternary operator in independent statement.

Thanks!

Cheers


texts: Python script to store nd array into images

texts:
I am trying to write a generic Python script that do the following types of tasks:

Load .npy file (the .npy file is of shape (m_samples, channels, row, column), which corresponds to m_samples images, and here the channels are always 1
Check whether a given path exists
Iterate against the .npy file, and save each image into the given path

I am not sure whether I am using the best practices to save an nd array into an image.

import numpy as np
from scipy.misc import toimage, imsave
import os
image_path = "raw"

def ensure_directory_exist(image_path):
    if not os.path.exists(image_path):
        print("Allocating '{:}'",format(image_path))
        os.mkdir(image_path)

if __name__ == '__main__':
    img_array = np.load('imgs_mask_test.npy')
    ensure_directory_exist(image_path)
    for i in range(img_array.shape[0]):
       name = "img"+str(i)+".png"
       imsave(os.path.join(image_path,name),img_array[i,0])


texts:
This config has 3 main features but there seems to be a lot of duplication and I wonder if I could improve it.

1 Detect all pngs and jpgs in static/img and try a webp version if the requesting browser supports it

2 Detect non-ES6 supporting browsers and serve site.babel.js, otherwise serve site.js which is un-babelified

3 Proxy all other requests to a node app running on port 3000

upstream node_upstream {
    server node:3000;
    keepalive 64;
}

#Required since SSL termination is higher up at the AWS load balancer
map $http_x_forwarded_proto $is_https {
  default off;
  https on;
}

map $http_accept $webp_suffix {
    default   "";
    "~*webp"  ".webp";
}

map $http_user_agent $script_file {
    default                                 "site.js";
    "~MSIE"                                 "site.babel.js";
    "~Trident"                              "site.babel.js";
    "~Opera.*Version/[0-9]\."               "site.babel.js";
    "~Opera.*Version/[0-1][0-9]\."          "site.babel.js";
    "~Opera.*Version/2[0-1]\."              "site.babel.js";
    "~AppleWebKit.*Version/[0-9]\..*Safari" "site.babel.js";
    "~Chrome/[0-9]\."                       "site.babel.js";
    "~Chrome/[0-2][0-9]\."                  "site.babel.js";
    "~Chrome/3[0-3]\."                      "site.babel.js";
    "~Chrome/4[0-3]\."                      "site.babel.js";
    "~Edge/1[0-3]\."                        "site.babel.js";
}

server {
    root /var/www/html/src;

    gzip on;

    # AWS traffic will come via a load balancer with the original protocol stored in http_x_forwarded_proto
    # If this is set to http then we need to redirect any request onto https equivalent
    # Should be ignored in non AWS environment as http_x_forwarded_proto should not be set
    if ($http_x_forwarded_proto = "http") {
      rewrite ^(.*)$ https://$http_host$1 permanent;
    }

    location = /static/site.js {
        root  /var/www/html/src;
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
        try_files /static/$script_file =404;
    }

    location ~* ^/static/img/.+\.(png|jpg)$ {
        root /var/www/html/src;
        add_header Vary Accept;
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
        try_files $uri$webp_suffix $uri =404;
    }

    location ~* ^/static/.*$
    {
        root  /var/www/html/src;
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
    }

    location / {
        proxy_redirect off;
        proxy_set_header   X-Real-IP            $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Host                   $http_host;
        proxy_set_header   X-NginX-Proxy    true;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_pass         http://node_upstream;
    }

    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
}


texts: Raising an assertation error if string is not an email

texts:
I created a class EmailParser and check if a supplied string is an email or not with
the help of the standard librarie's email module. If the supplied string is not an
email I raise an exception.

Is this a pythonic way to deal with inappropiate input values an assertation error?
How do you generally check input values and report inappropiate states and values?

code:

class EmailParser(object):

    def __init__(self, message):
        assert isinstance(message, basestring)

        parsed_message = email.message_from_string(message)

        if self._is_email(parsed_message):
            self.email_obj = parsed_message
        else:
            assert False, 'The supplied string is no email: %s' % parsed_message

    def __str__(self, *args, **kwargs):
        return self.email_obj.__str__()

    def _is_email(self, possible_email_obj):
        is_email = False

        if isinstance(possible_email_obj, basestring):
            is_email = False

        # I struggled a lot with this part - however, I came to the conclusion
        # to ask for forgiveness than for permission, see Zen of Python and
        # http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923
       try:
           if '@' in possible_email_obj['To']:
               is_email = True

       except TypeError, e:
           is_email = False

       return is_email


texts:
The following code list all files in a folder and allows the user to download one of them. It is working but I think it could be done better.

Is there a way to reduce the number of forms to only one and to improve the way I retrieve the name of the file to download?

My second concern is about the security of my getFile function.

function listDir($directoryName)
{
    $directory = opendir($directoryName);
    $files = array();
    while ($elem = readdir($directory))
    {
        if ($elem != '.' && $elem != '..' && $elem != '.htaccess')
        {
            $files[] = $elem;
        }
    }
    closedir();
    if (!empty($directory))
    {
        sort($files);
        echo "
";
        foreach ($files as $file)
        {
            $filePath = $directoryName.'/'.$file;
            echo "<form method='post' action=".htmlentities($_SERVER['PHP_SELF']).">";
            echo "
($fileDate)";
            echo "<input type='hidden' name='$file' value='$filePath'>";
            echo " <button type='submit' name='getFile'>Télécharger</button> ";
            echo "$file
";
            echo "</form>";
        }
        echo "
";
    }
}

function getFile($file)
{
    if (file_exists($file))
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
}

if (isset($_POST['getFile']))
{
    $keys = array_keys($_POST);
    $file = $_POST[$keys[0]];
    getFile($file);
}

listDir('data');


texts: A baby monitor using a Raspberry Pi to send push notifications when triggered by noise

texts:
I have a Raspberry Pi 3B with a USB microphone. I have used a combination of Bash and Python scripts to detect noise levels above a certain threshold that trigger a notification on my phone. The actual sound is not streamed.

The scripts are called using a command line alias for the following:

bash /home/pi/babymonitor.sh | /home/pi/monitor.py

Bash script - babymonitor.sh

This uses arecord to repeatedly record 2-second snippets via a temporary file, sox and grep to get the RMS (root mean square) amplitude (see this example for sox stat output) and then tail to get only the numerical data at the end of the line. This is then piped to the Python script.

#!/bin/bash
trap break INT
while true; do
    arecord --device=hw:1,0 --format S16_LE --rate 44100 -d 2 /dev/shm/tmp_rec.wav ; sox -t .wav /dev/shm/tmp_rec.wav -n stat 2>&1 | grep "RMS     amplitude" | tail -c 9
done

Python processing script - monitor.py

This receives the volume data and compares it to an arbitrarily defined threshold that I chose based on testing. If a noise is detected in one of the 2-second snippets, a push notification is sent and it suppresses further notifications for 10 seconds (5 cycles of 2-second snippets).

#!/usr/bin/env python

import sys
import push

THRESHOLD = 0.01

count = 0
suppress = False

while True:
    try:
        line = sys.stdin.readline().strip() # e.g. "0.006543"
        number = float(line)
        if number > THRESHOLD and not suppress:
            p = push.PushoverSender("user_key", "api_token")
            p.send_notification("There's a noise in the nursery!")
            count = 0
            suppress = True
        elif suppress:
            print("Suppressing output")
        else:
            print("All quiet")

        # Count 5 cycles after a trigger
        if suppress:
            count += 1
        if count >= 5:
            count = 0
            suppress = False

    except ValueError:
        # Cannot coerce to float or error in stdin
        print("Value error: " + line)
        break

    except KeyboardInterrupt:
        # Cancelled by user
        print("Baby monitor script ending")
        break

sys.exit()

Script for push notification service - push.py

This sends an http request to the Pushover service, which results in a push notification on my phone.

#!/usr/bin/env python

import httplib
import urllib

class PushoverSender:
    def __init__(self, user_key, api_key):
        self.user_key = user_key
        self.api_key = api_key

    def send_notification(self, text):
        conn = httplib.HTTPSConnection("api.pushover.net:443")
        post_data = {'user': self.user_key, 'token': self.api_key, 'message': text}
        conn.request("POST", "/1/messages.json", urllib.urlencode(post_data), {"Content-type": "application/x-www-form-urlencoded"})
        print(conn.getresponse().read())

I would be grateful for any feedback on how I can improve my code or the conceptual aspects of this project. I am not very familiar with Bash scripting so feedback is particularly welcome on this.

Is it acceptable to have the Bash script and Python script called
together with a pipe between them and both running while True
loops? It certainly seems to work.
Is there a better way to exit? Current pressing
ctrl+c will terminate both the Bash script
(due to trap break INT) and the Python script (due to except
KeyboardInterrupt).


texts: Removing trailing whitespace from input lines

texts:
I'm going through the K&R C book (coming from Python) and am on exercise 1-18, which states:

  Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

I wasn't able to find another solution online that looks quite like mine so I am questioning whether it is truly correct, even though it appears to work on anything I throw at it. I let an ending \n be whitespace, removed it and added a general newline to each printed output, but I'm not sure if that is cheating.

If there are any bad practices (or bugs in the code) for standard C please let me know.

#include <stdio.h>

#define MAXLINE 1000

int getli(char line[], int maxline);

main() {

    int len;
    int i;
    char line[MAXLINE];

    while ((len = getli(line, MAXLINE)) > 0) {
        i = len-1;

        /* replace any trailing whitespace character with null character */
        while (line[i] == '\n' || line[i] == '\t' || line[i] == ' ') {
            line[i] = '\0';
            i--;
        }

        if (line[0] == '\0') {
            printf("Blank line\n");
        }

        else printf("%s\n", line);
    }

    return 0;
}

/* function to capture input line as char array */
int getli(char s[], int lim) {

    int i, c;

    for (i=0; i<lim-1 && (c=getchar()) != EOF && c != '\n'; i++) {
        s[i] = c;
    }

    if (c == '\n') {
        s[i] = c;
        i++;
    }

    s[i] = '\0';
    return i;

}


texts: Determining whether a string ends with one of a few given options

texts:
I wrote the following function to determine whether a string ends with one of a few given options.

I'm sure it can be written more elegantly, probably avoiding the loop.

bool EndsWithOneOf(string value, IEnumerable<string> suffixes)
{
    foreach(var suffix in suffixes)
    {
        if value.EndsWith(suffix)
            return true;
    }
    return false;
}


texts: MS Access query complexity on finding duplicates

texts:
I have a list of names and ID's, with many multiplication (it's a payroll list). I'd like to see those ID's and names where the name changed somewhen.
Input:
id1 name

1   Josephine Baker
2   Norma Jeane Morteson
2   Marilyn Monroe
33  Sandra Bullock
15  Issur Danielovitch
1   Freda Josephine McDonald
15  Kirk Douglas
28  Meg Ryan
28  Margaret Hyra
36  Vin Diesel
36  Mark Sinclair
8   Sean Connery
11  Mel Gibson
16  Julia Roberts
Desired output:
ID  Name

1   Freda Josephine McDonald
1   Josephine Baker
2   Marilyn Monroe
2   Norma Jeane Morteson
15  Issur Danielovitch
15  Kirk Douglas
28  Margaret Hyra
28  Meg Ryan
36  Mark Sinclair
36  Vin Diesel
I'm running this query. It works well, it is fast enough, I just have a feeling that this could be a lot more professional.
SELECT first(ST.id1) as ID , first(ST.nam) as Name
FROM Stars AS ST
INNER JOIN
       (select id1, first(nam), count(id1) from
            (select [ST1.id1]&[ST1.nam], first(ST1.id1) as id1, first(ST1.nam)  as nam,
                   count(*) from Stars ST1
             group by [ST1.id1]&[ST1.nam])
       group by id1
       having count(id1)>1) AS SJ
ON SJ.id1=ST.id1
GROUP BY ST.id1, ST.nam
ORDER BY ST.id1;

The logic behind is to select unique id&name pairs, then select those id's that come up more than once, then (self)join the table and select the unique names to those id's.
Any advise is welcome!


texts:
I've decided to work on my Perl skills. I've written a small subroutine that splits a string based on an optional delimiter. I'd like any feedback on this program so I can kick bad habits to the curb. Written in Perl 5.

sub split_string {
    my $string = @_[0];
    my $delimiter = @_[1] ? @_[1] : " ";
    my @result = ();
    my $temp = "";

    for $i (0..length($string)) {
        my $char = substr($string, $i, 1);
        if (($char eq $delimiter) or $i == length($string)) {
            push(@result, $temp);
            $temp = "";
        } else {
            $temp .= $char;
        }
    }
    return @result;
}

And this is how I test this subroutine.

@test = split_string("This is a test to ensure this works correctly.");
foreach $element (@test) {
    print $element . "\n";
}


texts:
Just started learning Java three days ago and am currently doing a problem in my textbook where I do some basic cash register functionality. So far my code can
factor in taxes, let the user get change, and tell them the amount the actual tax is.

public class Register {
    private double purchase;
    private double payment;
    private double tax;
    public Register()
    {
    }
    public Register(double tax)
    {
        this.tax = tax;
    }

    public void recordPurchase(double amount)
    {
        purchase = purchase + amount;
    }
    public void enterPayment(double amount)
    {
        payment = amount;
    }

    public void recordTaxablePurchase()
    {
        purchase = purchase  + (purchase *(tax/100));
    }
    public double getTotalTax()
    {
        return (purchase*0.10);
    }
    public void getSalesTotal()
    {

    }
    public double giveChange()
    {
        double change = payment - purchase;
        purchase = 0;
        payment = 0;
        return change;
    }

}

Running it

public class RegisterTest {

    public static void main(String [] args)
    {
        Register pay = new Register(10);
        pay.recordPurchase(100);
        pay.recordTaxablePurchase();
        pay.enterPayment(200);

        double change = pay.giveChange();
        System.out.println(change);
    }
}

Now the next part is to do:

  After closing time, the store manager would like to know how much business was transacted during the day. Modify the CashRegister class to enable this functionality. Supply methods getSalesTotal and getSalesCount to get the total amount of all sales and the number of sales. Supply a method reset that resets any counters and totals so that the next day’s sales start from zero.

My thoughts: let's add two instance variables which should always be private:

private double totalPurchase;
private int count;

Change recordPurchase to:

public void recordPurchase(double amount)
    {
        purchase = purchase + amount;
        totalPurchase = totalPurchase + amount;
        count = count+1;
    }

Also do the same for tax.

Then simply do:

public double giveSalesTotal()
    {
        return totalPurchase;
    }

    public int getSalesCount()
    {
        return count;
    }

Does this seem like an ok way of doing it? It works, but seems really bad to create another new variable like totalPurchase, instead of using the original purchase.


texts:
So... I have a program in which I want to flip heads three times in the row.

What I'm asking for is for proposals of other solutions for this program, in pro way, as You do in natural sense.

That's my code as Java novice.

/*
 * File: ConsecutiveHeads.java
 * ----------------
 * This program flips a coin repeatly until three consecutive heads
 * are tossed.
 */

import acm.program.*;
import acm.util.*;

public class ConsecutiveHeads extends ConsoleProgram {
    /* Run the program */
    public void run() {
        println("This program flips a coin until there are three" +
                "heads in the row.");
        while(counter != 3) {
            FlipACoin();
        }
        println("Yupii! There are already three same heads in the row :)");
    }

    /* Flip a coin. Then if heads are tossed, increment our counter.
     * In tails case, zero counter. */
    private void FlipACoin() {
        boolean rank = rgen.nextBoolean();
        if(rank) {
            println("heads");
            counter++;
        } else {
            println("tails");
            counter = 0;
        }
    }

    /* Create an instance variable for the random number generator */
    private RandomGenerator rgen = new RandomGenerator();

    /* Create an instance variable for counter detecting three heads in row */
    private int counter = 0;
}


texts: Excel VBA speed up code to hide rows/delete color

texts:
I am using following code to delete color and hide rows that include several criteria before exporting sheets to pdf's. Is there any way to speed up this process as it is taking quite a lot of time to process. Especially in situations when I have several sheets in one workbook and to apply this on each sheet = "printed page".

Sub Color()
    Dim myRange As Range
    Dim cell As Range
    Application.ScreenUpdating = False
    Set myRange = ThisWorkbook.Sheets("Print version").Range("Print_Area")
        For Each cell In myRange
        myRange.Interior.ColorIndex = 0
        If cell.HasFormula = True And cell.Value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
    Next
    Application.ScreenUpdating = True
End Sub


texts:
I've made a simple game for testing math facts (think practice for elementary school-age kids). It displays a random addition, subtraction, multiplication, or division problem, and feedback on if the right answer was entered.

For now it works interacts with the user via prompt(), but I plan to add a GUI later. You can exit out of the infinite prompt() loop by clicking cancel.

I'd like feedback on how to improve the code, particularly if there's a better way of doing the getCorrectAns() function, and if I'm using best practices.

var maxNum = 12,
  stillPlaying = true,
  ans, isCorrect = '',
  correctAns = '',
  sign, num1 = 0,
  num2 = 0,
  prob, correctAns;

function randInt(max) {
  return Math.floor(Math.random() * max);
}
function getCorrectAns(n1, sign, n2) {
  switch (sign) {
    case '+':
      return n1 + n2;
    case '\u2212':
      return n1 - n2;
    case '\xD7':
      return n1 * n2;
    case '\xF7':
      return n1 / n2;
    default:
      return false;
  }
}
while (stillPlaying) {
  sign = ['+', '\u2212', '\xD7', '\xF7'][randInt(4)];
  num1 = randInt(maxNum + 1);
  num2 = randInt(maxNum + 1);
  if (sign == '\u2212') num1 += num2;
  if (sign == '\xF7') {
    num2 = randInt(maxNum) + 1;
    num1 *= num2;
  }
  prob = num1 + ' ' + sign + ' ' + num2;
  ans = prompt(isCorrect + prob);
  if (!ans) stillPlaying = false;
  correctAns = getCorrectAns(num1, sign, num2);
  isCorrect = (correctAns == ans) ? 'Correct! ' : 'Incorrect, ' + prob + ' = ' + correctAns + '.\n';
}


texts: Bool function in PHP to check if you run the script inside docker

texts:
I had to do a CLI script that does something, I also had to add a validation that checks if it runs inside the Docker. After some research I found a solution that people check some processes via cat /proc/self/cgroup and then grep to search for a docker phrase within.

So I ended-up with this method. It works pretty well. Inside docker it returns true, while on my local mac it returns false.

It's not rocket science however I would like people to take a look and tell me if this is a sufficient method or a completely different approach is better.

private function isDocker(): bool
{
    $processStack = explode(PHP_EOL, shell_exec('cat /proc/self/cgroup'));
    $processStack = array_filter($processStack); // remove empty item made by EOL

    foreach ($processStack as $process) {
        if (strpos($process, 'docker') === false) {
            return false;
        }
    }

    return true;
}

Later call to this script looks like:

if ($this->isDocker() === false) {
    throw new \Exception('This helper script can be called only inside Docker container.' . "\n");
}


texts: Checking that an entered date is before the current date

texts:
I want to write a function which returns true if a selected date is smaller than the current date, else return false.

This function is working as expected but I want to know the best possible way to do this.

private boolean isValidDate() {

    if(year<yearCurr)
    {
        //selected year is small date is small
        return true;
    }else
        if(year>yearCurr)
        {
            //selected year is greater date is greater
            return false;
        }else
        {
            //selected year is same as current year check month

            if(month<monthCurr)
            {
                //selected month is small date is small
                return true;
            }else
                if(month>monthCurr)
                {
                    //if selected month is greater date is greater
                    return false;
                }
                else
                {
                    // selected day of month is less than or equal to current date; date is valid
                    if(day<=dayCurr)
                        return true;
                    else
                        return false;
                }
        }
}