texts:
My goal is to create a simple restful api that will be accessed by an AngularJS front end. Even though it's fairly simple, I'd like understand how to make it more reliable, secure, and best-practices compliant. The whole api is contained in a single file, I'm not overly concerned about organization at the moment (unless it can help with the items I've mentioned above). I'm using mongoose, hapi, and joi for validation.

server.js

'use strict';

var Hapi = require('hapi');
var Good = require('good');
var Mongoose = require('mongoose');
var Joi = require('joi');

Mongoose.connect('mongodb://xxxx:xxxx@proximus.modulusmongo.net:xxxx/xxxx');

var todoSchema = new Mongoose.Schema({
  title: { type: String, required: true },
  isCompleted: { type: Boolean, required: true },
  createdAt: { type: Date, required: true },
  updatedAt: { type: Date, required: true }
});

var Todo = Mongoose.model('Todo', todoSchema, 'Todos');

var server = new Hapi.Server(3000);

server.route({
  method: 'GET',
  path: '/api/v1/todos',
  handler: function(request, reply) {

    Todo.find(function(err, todos) {
      if (err) {
        reply(err);
        return;
      }

      reply(todos);
    });
  }
});

server.route({
  method: 'GET',
  path: '/api/v1/todos/{id}',
  handler: function(request, reply) {

    Todo.find({ _id: request.params.id }, function(err, todo) {
      if (err) {
        reply(err);
        return;
      }

      reply(todo);
    });

  },
  config: {
    validate: {
      params: {
        id: Joi.string().required()
      }
    }
  }
});

server.route({
  method: 'PUT',
  path: '/api/v1/todos/{id}',
  handler: function(request, reply) {

    Todo.findOne({ _id: request.params.id }, function(err, todo) {
      if (err) {
        reply(err);
        return;
      }

      todo.title = request.payload.title;
      todo.isCompleted = request.payload.isCompleted;
      todo.updatedAt = new Date();
      todo.save();

      reply(todo);
    });
  },
  config: {
    validate: {
      params: {
        id: Joi.string().required()
      },
      payload: {
        _id: Joi.string(),
        __v: Joi.number(),
        title: Joi.string(),
        isCompleted: Joi.boolean(),
        createdAt: Joi.date(),
        updatedAt: Joi.date()
      }
    }
  }
});

server.route({
  method: 'POST',
  path: '/api/v1/todos',
  handler: function(request, reply) {

    var newTodo = new Todo({
      title: request.payload.title,
      isCompleted: request.payload.isCompleted,
      createdAt: new Date(),
      updatedAt: new Date()
    });

    newTodo.save(function(err, todo) {
      if (err) {
        reply(err);
        return;
      }

      reply(todo);
    });
  },
  config: {
    validate: {
      payload: {
        title: Joi.string(),
        isCompleted: Joi.boolean(),
      }
    }
  }
});

server.route({
  method: 'DELETE',
  path: '/api/v1/todos/{id}',
  handler: function(request, reply) {

    Todo.findByIdAndRemove(request.params.id, function(err, todo) {
      if (err) {
        reply(err);
        return;
      }

      reply(todo);
    });
  },
  config: {
    validate: {
      params: {
        id: Joi.string().required()
      }
    }
  }
});

server.pack.register(Good, function(err) {
    if (err) {
      throw err;
    }

    server.start(function() {
      server.log('info', 'Server running at: ' + server.info.uri);
    });
});


texts:
I have written a simple window event capture wrapper that gets events that happen to the window, and can be checked anywhere in the program through a global class. I wanted to be able to create a callback anywhere in the program with any event that I have asked to be checked. To hold the data that is returned from the events, I have used a pointer that is allocated whenever an event occurs, so I can grab the data returned later on in the program.

I don't want to use templates to hold the data since that would require a lot of objects to be created, or a lot of vectors for each specific event that I want. I find this to be too clunky, and I wanted a clean, simple solution.

Data that is captured

struct windowEventData
    {
        void *data = nullptr;
        std::string id;
        sf::Event::EventType event;

        bool polled = false;
    };

Window Event Manager

class windowEventManager
    {
        private:
            std::vector<windowEventData> _subscribedEvents;

        public:
            void subscribe(const std::string &id, sf::Event::EventType event);
            void pollEvent(sf::Event event);
            void clearEvents();

            template<typename T>
            T* hasEventPolled(const std::string &id);

            ~windowEventManager();
    };

Grabbing and setting the pointer

void windowEventManager::pollEvent(sf::Event event)
    {
        for (auto &eventCheck : _subscribedEvents)
            {
                if (eventCheck.event == event.type)
                    {
                        switch (event.type)
                            {
                                case sf::Event::KeyPressed:
                                case sf::Event::KeyReleased:
                                    eventCheck.data = new sf::Event::KeyEvent(event.key);
                                    break;
                                case sf::Event::MouseButtonPressed:
                                case sf::Event::MouseButtonReleased:
                                    eventCheck.data = new sf::Mouse::Button(event.mouseButton.button);
                                    break;
                                case sf::Event::MouseWheelMoved:
                                case sf::Event::MouseWheelScrolled:
                                    eventCheck.data = new bool(true);
                                    break;
                                case sf::Event::TextEntered:
                                    eventCheck.data = new sf::String(event.text.unicode);
                                    break;
                                default:
                                    break;
                            }
                        eventCheck.polled = true;
                    }
            }
    }

I clear events before each poll, and in the destructor so I don't have memory leaks/too much on the heap

void windowEventManager::clearEvents()
    {
        for (auto &eventCheck : _subscribedEvents)
            {
                if (eventCheck.data)
                    {
                        delete eventCheck.data;
                        eventCheck.data = nullptr;
                    }
                eventCheck.polled = false;
            }
    }

Finding out if an event has occured

template<typename T>
inline T *windowEventManager::hasEventPolled(const std::string &id)
    {
        auto it = std::find_if(_subscribedEvents.begin(), _subscribedEvents.end(), [id] (windowEventData &dat) { return dat.id == id && dat.polled; });
        if (it != _subscribedEvents.end())
            {
                return static_cast<T*>((*it).data);
            }

        return nullptr;
    }

Is my use of a void* proper? I figured I could use a union as well for this, but I would rather see if using a pointer would be a good solution.


texts:
Here's an approach i came up with for checking IOS versions.

#define __PROCESS_INFO  ([NSProcessInfo processInfo])
#define CURRENT_IOS     ([__PROCESS_INFO operatingSystemVersion])

#define IOS(x)          ((NSOperatingSystemVersion){[x integerValue], 0, 0})
#define IOS9            ((NSOperatingSystemVersion){9, 0, 0})
#define IOS10           ((NSOperatingSystemVersion){10, 0, 0})
#define IOS11           ((NSOperatingSystemVersion){11, 0, 0})

#define IS_IOS9         ([__PROCESS_INFO isOperatingSystemAtLeastVersion:IOS9] && \
                                ![__PROCESS_INFO isOperatingSystemAtLeastVersion:IOS10])
#define IS_IOS10        ([__PROCESS_INFO isOperatingSystemAtLeastVersion:IOS10] && \
                            ![__PROCESS_INFO isOperatingSystemAtLeastVersion:IOS11])

that way this type of code is more readable

if (IS_IOS9) {
    // [... openURL: ...];
}
else if (IS_IOS10) {
   // [... openURL:options:completionHandler: ...];
}

Let me know what you think ...


texts:
Is anything what could I improve on my code?

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Helper {

    public static Map<User, BigDecimal> createPlayersScoreMap(List<User> users, List<Score> scores) {
        List<User> players = getPlayers(users);
        Map<User, BigDecimal> playersScoreMap = new HashMap<User, BigDecimal>();

        for (User player: players) {
            BigDecimal sumScore = new BigDecimal(0);
            for (Score score: scores) {
                if (player.equals(score.getPlayer())) {
                    sumScore = sumScore.add(score.getResult());
                }
            }
            playersScoreMap.put(player, sumScore);
        }
        return playersScoreMap;
    }

    private static List<User> getPlayers(List<User> users) {
        List<User> filteredUsers = new ArrayList<User>(users);
        for (Iterator<User> it = filteredUsers.iterator(); it.hasNext();) {
            if (!it.next().isPlayer())
                it.remove();
        }
        return filteredUsers;
    }

}


texts: Remove all adjacent duplicates in a string using a Stack

texts:
Input: careermonk
     Output:    camonk

  Input: mississippi
     Output:    m

I want to improve this code.

#include <iostream>
#include <string>

#define max 1000

class Stack
{
  int top;
public:
  char stk[max];
  Stack()
  {
    top = -1;
  }
  bool isStackEmpty();
  void push(char);
  char pop();
  std::string modifyString(std::string);
private:
  void removeAdjacentDuplicate(std::string);
};

bool Stack::isStackEmpty()
{
   if (top == -1)
      return true;
   else
      return false;
}

void Stack::push(char val)
{
   int s = max - 1;
   if (top < s)
   {
     top = top + 1;
     stk[top] = val;
   }
   else
    std::cerr << "Stack Overflow \n";
}

char Stack::pop()
{
   if (isStackEmpty() == true)
       std::cerr << "Stack Underflow \n";
   else
   {
      --top;
      return stk[top + 1];
   }
}

void Stack::removeAdjacentDuplicate(std::string str)
{
   int len = str.length();
   for (int i = 0; i < len; i++)
   {
      if (isStackEmpty() == true)
      {
         push(str[i]);
      }
      else if (str[i] == stk[top])
      {
         int discard = pop();
      }
      else
      {
         push(str[i]);
      }
   }
}

std::string Stack::modifyString(std::string str)
{
   removeAdjacentDuplicate(str);
   str.resize(top + 1);
   for (int i = 0; i <= top; i++)
   {
     str[i] = stk[i];
   }
   str[top + 1] = '\0';
   return str;
}

int main()
{
   Stack stack1;
   std::string str = "careermonk";
   std::cout << "Orignal string : " << str << "\n";
   str = stack1.modifyString(str);
   std::cout << "New string     : " << str << "\n";

   Stack stack2;
   std::string str2 = "mississippi";
   std::cout << "Original string : " << str2 << "\n";
   str2 = stack2.modifyString(str2);
   std::cout << "New string      : " << str2 << "\n";
}


texts: A c++ classs for recording audio samples

texts:
This question is a continuation of this.

Here, I modified the original code with the following changes.
1. Make a class Recorder() to store the information of audio data.

class Recorder {
    public:
        Recorder(uint32_t sample_rate, uint32_t rec_time);
        ~Recorder();
        uint32_t frame_step;
        uint32_t sample_rate;
        uint32_t step_buf_size;
        uint32_t num_sample;
        uint32_t sample_counter;
        uint32_t record_time;
        int16_t *total_buf;
        void append(int16_t *step_buf, uint32_t n);
    private:
};

Recorder::Recorder(uint32_t rate, uint32_t rec_time)
{
    sample_rate = rate;
    frame_step = sample_rate / 100;
    step_buf_size = sizeof(int16_t) * frame_step;
    num_sample = rec_time * sample_rate;
    record_time = rec_time;
    sample_counter = 0;
    total_buf = new int16_t[num_sample];
}

Recorder::~Recorder()
{
    delete[] total_buf;
}

void Recorder::append(int16_t *step_buf, uint32_t n)
{
    memcpy(&total_buf[sample_counter], step_buf, n);
    sample_counter += n;
}

2. Use the following code to save a *.wav file.

static int32_t DumpWav(char fname[], int16_t lpsSample[], uint32_t nNumSample, uint32_t nSampleRate)
{   // arrays passed to functions are converted to pointers.
    class WavFile wf;
    wf.Create(fname, 1, 16, nSampleRate);
    if (lpsSample != NULL && nNumSample > 0) {
        wf.Write((BYTE *)lpsSample, nNumSample * 2);
        wf.Flush();
    }
    return nNumSample;
}
void main(int argc, char *argv[])
{
    Recorder rec(44100, 10);
    class CWaveRecord oRecorder;

    // Here I have to use new, because It's not allow to use a variable to init array.
    // int16_t tmp_buf[sizeof(uint16_t) * rec.frame_step]; <-- this does not compile.
    int16_t *step_buf = new int16_t[sizeof(uint16_t) * rec.frame_step];

    // Do something to record audio
    oRecorder.Initialize(1, 16, rec.sample_rate, rec.step_buf_size, 300, NULL, 0); // 0.01 * 300 = 3s circular buffer
    char ch;
    while (1) {
        printf("Press any key to record , and press again to stop, 'q' to exit ...\nMaximum recording time is %d seconds.\n", rec.record_time);
        ch = _getch();
        if (ch == 'q' || ch == 'Q' || ch == 27)
            break;

        printf("Start Record ...\n");
        rec.sample_counter = 0;

        oRecorder.StartRecord();
        while (oRecorder.GetWave((unsigned char *)step_buf) == WR_ERROR_SUCCESS) {
            uint32_t n;
            n = oRecorder.GetSamplePerBuffer();
            if (rec.sample_counter < rec.num_sample) {
                //rec.append(step_buf, sizeof(uint16_t) * n); <-- This line doesn't work. Why?
                memcpy(&rec.total_buf[rec.sample_counter], step_buf, sizeof(uint16_t) * n);
                rec.sample_counter += n;
            } else {
                oRecorder.StopRecord();
                printf("Buffer is empty. Done\n");
                break;
            }

        }

        char lpszFileName[256];
        SYSTEMTIME time;
        GetLocalTime(&time);
        sprintf_s(lpszFileName, "cmd_%02d_%02d_%02d_%02d_%02d_%02d.wav", time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, 1);
        DumpWav(lpszFileName, rec.total_buf, rec.sample_counter, rec.sample_rate);
    }

    delete[] step_buf;
}

This block of code works on my PC, but I still have few questions.
1. Why is my Recorder::append not working?
2. I didn't use vector() to store my audio data. The reason is that I have to pass address of total_buf to memcpy() and DumpWav(). Is using vector possible here to replace array?
3. Do you see any other improvements of my code?
Thank you.


texts:
Inspired by some older questions, I decided to create my own postfix calculator using Java 8. I'd like to have all aspects reviewed.

public enum Operator implements DoubleBinaryOperator {
    PLUS    ("+", (l, r) -> l + r),
    MINUS   ("-", (l, r) -> l - r),
    MULTIPLY("*", (l, r) -> l * r),
    DIVIDE  ("/", (l, r) -> l / r);

    private final String symbol;
    private final DoubleBinaryOperator binaryOperator;

    private Operator(final String symbol, final DoubleBinaryOperator binaryOperator) {
        this.symbol = symbol;
        this.binaryOperator = binaryOperator;
    }

    public String getSymbol() {
        return symbol;
    }

    @Override
    public double applyAsDouble(final double left, final double right) {
        return binaryOperator.applyAsDouble(left, right);
    }
}

public class CalculationFailedException extends RuntimeException {
    private static final long serialVersionUID = 6849565649585489467L;

    public CalculationFailedException() {
        super();
    }

    public CalculationFailedException(final String message) {
        super(message);
    }

    public CalculationFailedException(final Throwable cause) {
        super(cause);
    }

    public CalculationFailedException(final String message, final Throwable cause) {
        super(message, cause);
    }
}

public interface Calculator {
    public double calculate(final String input);
}

public class PostfixCalculator implements Calculator {
    private static final List<String> OPERATORS_LIST = Arrays.stream(Operator.values())
            .map(Operator::getSymbol)
            .collect(Collectors.toList());

    private static final Map<String, Operator> STRING_TO_OPERATOR_MAPPING = Arrays.stream(Operator.values())
            .collect(Collectors.toMap(op -> op.getSymbol(), op -> op));

    private final Stack<Double> numberStack = new Stack<>();

    @Override
    public double calculate(final String input) throws IllegalArgumentException {
        try {
            Arrays.stream(input.split(" ")).forEach(this::processElement);
            return safePop();
        } catch (CalculationFailedException | NumberFormatException ex) {
            throw new CalculationFailedException("Calculation has failed for expression: " + input);
        }
    }

    private void processElement(final String element) {
        Objects.requireNonNull(element);
        if (OPERATORS_LIST.contains(element)) {
            processOperator(STRING_TO_OPERATOR_MAPPING.get(element));
        }
        else {
            processNumber(Double.parseDouble(element));
        }
    }

    private void processOperator(final Operator operator) {
        double right = safePop();
        double left = safePop();
        numberStack.push(operator.applyAsDouble(left, right));
    }

    private void processNumber(final double number) {
        numberStack.push(number);
    }

    private double safePop() {
        if (numberStack.isEmpty()) {
            throw new CalculationFailedException();
        }
        return numberStack.pop();
    }
}

Code can be called for example with:

Calculator calculator = new PostfixCalculator();
double result = calculator.calculate("3 4 +");

Which will give 7.0 as result.

Another example:

Calculator calculator = new PostfixCalculator();
double result = calculator.calculate("5 1 2 + 4 * + 3 -");

Which gives 14.0 as result.


texts:
I have some code which works fine. First, it checks that dates format are valid and then, checks that first date is lower than second date. I had to use free input text and custom validator because multiple date formats are supported such as quarter number (2014 Q1) etc.

But I find my code too long for what it's doing. Any advice on code improvement ?

DEMO

function check_handler(){
var from = $('#zeDateFrom').val(), to = $('#zeDateTo').val();

if(adu_date_format(from) && adu_date_format(to)){
    if( check_date_period(from.trim(), to.trim()) ){
        alert('OK');
    }
    else alert('Start Date must be lower then End Date.');
}
else{
    alert('Please use a valid date format. For your information, valid formats are:\ndd/mm/yyyy  (e.g 11/12/2011)\n yyyy  (e.g 2010)\n mm/yyyy  (e.g 11/2009)\n and yyyy qq (e.g 2012 Q2).');
}

}

function check_date_period(from, to){
  var result = false;
  var yearFrom, yearTo, monthFrom, monthTo, dayFrom, dayTo;

  // 0) If something to compare...
  if(from==""||to=="") return true;

  // 1) Test if input is type year only
  if(from.length==4){
      yearFrom = from; monthFrom = 1; dayFrom = 1;
  }
  if(to.length==4){
      yearTo = to; monthTo = 12; dayTo = 0; // 0 for last day of month
  }

  // 2) Test if input is type year[space] quarter

  var mySplit = from.split(" ");
  if(mySplit.length == 2){
    yearFrom = mySplit[0];
    dayFrom = 1;
    if(mySplit[1]=='Q1'){
        monthFrom = 1;
    }
    if(mySplit[1]=='Q2'){
        monthFrom = 4;
    }
    if(mySplit[1]=='Q3'){
        monthFrom = 7;
    }
    if(mySplit[1]=='Q4'){
        monthFrom = 10;
    }
  }
  mySplit = to.split(" ");
  if(mySplit.length == 2){
    yearTo = mySplit[0];
    dayTo = 0;
    if(mySplit[1]=='Q1'){
        monthTo = 3;
    }
    if(mySplit[1]=='Q2'){
        monthTo = 6;
    }
    if(mySplit[1]=='Q3'){
        monthTo = 9;
    }
    if(mySplit[1]=='Q4'){
        monthTo = 12;
    }
  }

  // 3) Test if input is type month/year
  mySplit = from.split("/");
  if(mySplit.length == 2){
    yearFrom = mySplit[1]; monthFrom = mySplit[0]; dayFrom = 1;
  }
  mySplit = to.split("/");
  if(mySplit.length == 2){
    yearTo = mySplit[1]; monthTo = mySplit[0]; dayTo = 0; // 0 for last day of month
  }

  // 4) test if input is type dd/mm/yyyy
  mySplit = from.split("/");
  if(mySplit.length == 3){
    yearFrom = mySplit[2]; monthFrom = mySplit[1]; dayFrom = mySplit[0];
  }
  mySplit = to.split("/");
  if(mySplit.length == 3){
    yearTo = mySplit[2]; monthTo = mySplit[1]; dayTo = mySplit[0];
  }

  // FINALLY: Compare dates
  // Note: 00 is month i.e. January
  monthFrom--;
  if(dayTo!=0) monthTo--;
  var dateOne = new Date(yearFrom, monthFrom, dayFrom); //Year, Month, Day
  var dateTwo = new Date(yearTo, monthTo, dayTo); //Year, Month, Day
  //alert(dayFrom+'/'+(monthFrom-1)+'/'+yearFrom+'---------'+dayTo+'/'+(monthTo-1)+'/'+yearTo)
  //alert(dateOne+'-'+dateTwo);
  if (dateOne < dateTwo) {
    result = true;
  }

  return result;
}

function adu_date_format(text){
  var result = false;

  // 0) If something to test...
  if(text=="") return true;

  // 1) Test if input is type year only
  if(text.length == 4){
    if(text >= 2000 && text <= 2030)
      result = true;
  }

  // 2) Test if input is type year[space] quarter
  var mySplit = text.split(" ");
  if(mySplit.length == 2){
    if((mySplit[0] >= 2000 && mySplit[0] <= 2030) && (mySplit[1].length == 2 && mySplit[1] >= 'Q1' && mySplit[1] <= 'Q4'))
      result = true;
  }

  // 3) Test if input is type month/year
  mySplit = text.split("/");
  if(mySplit.length == 2){
    if((mySplit[0] >= 1 && mySplit[0] <= 12) && (mySplit[1] >= 2000 && mySplit[1] <= 2030))
      result = true;
  }

  // 4) test if input is type dd/mm/yyyy
  mySplit = text.split("/");
  if(mySplit.length == 3){
    if(mySplit[2] >= 2000 && mySplit[2] <= 2030)
      result = true;
  }
  return result;
}


texts:
Related to this code golf challenge, I tried to find acronyms with Haskell without using regular expressions.

The idea is to split the input string at every space or dash before finally gluing the heads of these parts together, if they are uppercase.

This is my code:

import System.Environment
import Data.Char

main :: IO ()
main = do
    [inp] <- getArgs -- get input from the command line
    putStrLn $ getAcronym inp

getAcronym :: String -> String
getAcronym [] = []
getAcronym s  = foldr step [] parts
    where parts = split isWordSep s -- split into words
          step x acc = if isUpper . head $ x
                       then head x : acc else acc -- glue uppercase heads together

split :: (a -> Bool) -> [a] -> [[a]]
split p []       = []
split p s@(x:xs)
  | p x       = split p xs -- discard trailing white spaces
  | otherwise = w : split p r -- continue with the rest
      where (w, r) = break p s -- seperate prefix

isWordSep :: Char -> Bool
isWordSep x = x == ' ' || x == '-'

As this really seems like a very simple problem, my code looks like way too much complexity.

Do you have any helpful improvements to slim down my code?


texts: Filtering out objects in a CollectionViewSource

texts:
I hired a developer as a senior dev. He was the only one that successfully completed my coding test. Now that he's on the project, I'm reviewing some of his code and seeing constructs like this:

e.Accepted = true;

if ((_selectedDocumentCategoryFilter == null) || (_selectedDocumentCategoryFilter.PicklistStringId == 0))
{ }
else if (docToFilter.CategoryId == _selectedDocumentCategoryFilter.PicklistStringId)
{ }
else
{ e.Accepted = false; }

if ((_selectedDocumentTypeFilter == null) || (_selectedDocumentTypeFilter.PicklistStringId == 0))
{ }
else if (docToFilter.DocumentTypeId == _selectedDocumentTypeFilter.PicklistStringId)
{ }
else
{ e.Accepted = false; }

To my mind there are several issues with this, but I don't want to come down too hard if this is considered generally acceptable, these days. There is, of course, always more than one way to code a solution. I learned to code many years ago, so perhaps things have changed or I'm just set in my ways. But this just looks like awkward logic with the empty condition bodies and falling through to further logic even after it is determined that the item is not accepted.

I'd have approached it with something like this:

e.Accepted = false;

if ((_selectedDocumentCategoryFilter != null) &&                                  // If the doc category filter is populated,
    (_selectedDocumentCategoryFilter.PicklistStringId != 0) &&                    // and there is an actual value selected (i.e. not blank or All)
    (docToFilter.CategoryId != _selectedDocumentCategoryFilter.PicklistStringId)) // but the docToFIlter doesn't match the catagory,
  return;                                                                         // let's get out. No need for further checks.

if ((_selectedDocumentTypeFilter != null) &&                                      // If the doc type filter is populated,
    (_selectedDocumentTypeFilter.PicklistStringId != 0) &&                        // and there is an actual value selected (i.e. not blank or All)
    (docToFilter.DocumentTypeId != _selectedDocumentTypeFilter.PicklistStringId)) // but the docToFilter doesn't match the type,
  return;                                                                         // let's get out. No need for further checks.

e.Accepted = true;

What do you think? Should his code be considered acceptable?

Edit: I do appreciate the discussion, but the responses are going a little deeper than I expected. (Which is a good thing.) This was intended as just a quick check to see if folks agreed that the empty conditions were a strange way to implement, along with falling through to additional checks after final state determination. My approach was intended to address those elements, just as a comparison, not a complete re-write, as much context was left out in an attempt to keep it simple.

To add a bit of context, there is no future condition to be added in the empty braces. The logic is simply determining if the doc object conforms to the selected filters. A filter could be null or zero depending on the state of the UI and, in either case, we consider the filter as unselected.


texts: Making a scroll function more efficient in jQuery

texts:
I have the following code, though I'm not sure it is efficient as it could be.

 $(window).scroll(function() {
    var scrollT = $(document).scrollTop();
    if (scrollT >= 180) {
        $("#primary-nav-wrapper").addClass("scroll");
        $("#primary-nav-wrapper li.front").addClass("active");

        $("#primary-nav-wrapper .search-wrapper").removeClass("active");
        $("#primary-nav-wrapper .search-field").blur();
    }
    else {
        $("#primary-nav-wrapper").removeClass("scroll");
        $("#primary-nav-wrapper .search-wrapper, #primary-nav-wrapper li.front").removeClass("active");

        $("#primary-nav-wrapper .search-field").blur();
    }
    if (scrollT >= 400) {$("a#to-top-link").addClass("active");}
    else {$("a#to-top-link").removeClass("active");}
});

Basically, what I do here is checking two if-clauses every time I scroll, but is it more resource-friendly to only check every few milliseconds? If so, how is this done? Or is it a better idea to re-write the if-else structure, e.g. if.. else if... else if... else?


texts: Matplot lib : scalling of the axes on bar plot

texts:
I am using following script to plot cluster populations using two lists contained x and y data
# calculate clusters using encore method
cluster = encore.cluster(u, select="all", superposition=False, method=encore.DBSCAN(eps=1))

# make list of population of each cluster;
cluster_sizes= [len(c) for c in cluster.clusters]
# make list of the cluster number;
cluster_numbers=[x+1 for x in range(0,len(cluster_sizes))]

# plot data
plt.bar(cluster_numbers, cluster_sizes)
plt.title('Cluster Populations')
plt.grid(True)
#plt.style.use('ggplot')
plt.savefig(f'clusters.png')
plt.close()

The problem that sometimes on the resulted bar plot the values are ranged by 0.5 along both X and Y (see the enclosed picture as the example). How I could plot only integers along the both axes? In my example graph the X should be scalled from 0 to 20 (avoiding 0.5 spacings) and the Y from 0 to 18 (thus avoiding these unused 0.5 spacings)


texts:
I'd love some pointers on how to refactor this

async function validate_request_args(req, request_type) {
    let problem_id;
    const errors = [];
    switch (request_type) {
        case "post":
            if (req.body.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                });
            } else {
                problem_id = req.body.id;
            }
            break;

        case "get":
            if (req.query.id == null) {
                errors.push({
                    msg: "Missing id of the problem",
                    param: "id"
                })
            } else {
                problem_id = req.query.id;
            }
            break;
    }
    if (errors.length === 0) {
        const problem = await models.Problem.findByPk(problem_id);
        if (problem == null) {
            errors.push({
                msg: `Problem with id ${problem_id} does not exist `,
                param: "id"
            });
        }
        return monet.Validation.success(problem)
    }
    return monet.Validation.fail(errors);
}


texts:
I have a dict of stock tickers (KEY) and a data point (VALUE; e.g. dividend yield).

I want to know which tickers have a value between a specified min and max value.

Given

data = {'KO': 1, 'WMT': 0, 'IBM': 3, 'PG': 2}
gte = 1
lte = 2

Func1

def func1(data, gte=None, lte=None):
    data_set = set(data)
    gte_set = set(filter(lambda k: data[k] >= gte, data)) if gte else data_set
    lte_set = set(filter(lambda k: data[k] <= lte, data)) if lte else data_set
    return data_set.intersection(gte_set, lte_set)

Func2

import operator
def func2(data, gte=None, lte=None):
    if gte is None and lte is None:
        return data
    #without dict data gets modified
    _data = dict(data)
    for k, v in data.items():
        if gte and operator.lt(v, gte):
                del _data[k]
        if lte and operator.gt(v, lte):
                del _data[k]
    return set(_data)

Func3

def func3(
    data,
    gte=float('-inf'),
    lte=float('inf')
):
    return set(filter(
        lambda k: gte <= data[k] <= lte,
        data
    ))

Example

func1(data, gte=gte, lte=lte) == {'PG', 'KO'}
func2(data, gte=gte, lte=lte) == {'PG', 'KO'}
func3(data, gte=gte, lte=lte) == {'PG', 'KO'}


texts: Duplicate code in day of the week event handlers

texts:
private static void OnSundayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        BinaryDataGrid c = sender as BinaryDataGrid;
        if (c != null)
        {

            if (_shouldCallBack)
            {
                if (c.Sunday.Length == 4)
                    return;
                Days day = (Days)c.dataGrid.Items[0];
                byte[] newArray = new byte[c.Sunday.Length + 1];
                newArray[0] = Convert.ToByte(0);
                c.Sunday.CopyTo(newArray, 1);
                day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);
                _sun = day.Value;
            }
            else
            {
                _shouldCallBack = true;
                c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray();
            }
        }
    }

    private static void OnMondayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {

        BinaryDataGrid c = sender as BinaryDataGrid;
        if (c != null)
        {
            if (_shouldCallBack)
            {
                if (c.Monday.Length == 4)
                    return;
                Days day = (Days)c.dataGrid.Items[1];
                byte[] newArray = new byte[c.Monday.Length + 1];
                newArray[0] = Convert.ToByte(0);
                c.Monday.CopyTo(newArray, 1);
                day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);
                _mon = day.Value;
            }
            else
            {
                _shouldCallBack = true;
                c.Monday = BitConverter.GetBytes(_mon).Reverse().ToArray().Skip(1).ToArray();
            }
        }
    }

I've got the same code for every week day, how can I generalize this so I don't have 6 duplicates of the code above?


texts: Method to determine redirect after login

texts:
I have a method that returns a URL to send a user should they pass a login.  My problem is two of these links are hard coded one of which is attempting to pass a variable to the model of that controller.  My question is two fold:

A. Is this safe
B. Is there a better way to do this without hard-coding things like this?

public class LoginViewModel
{
  public string UserId {get; set;}
  public string GetAppAccess()
  {
    using (var db = new WebContext())
    {
      var query = (from a in db.Permissions
                   join b in db.UserPermissions on a.PermissionId equals b.PermissionId
                   join c in db.Applications on a.Name equals c.AppName
                   where a.PermissionType == PermissionType.AppAccess & b.UserId == UserId
                   select c).ToList();
      switch (query.Count)
      {
        case 0:
          return "http://SERVERNAME/Tickets/Create?subject=Request%20For%20Application%20Access";
          // TODO: code ticket logic to except this argument
        case 1:
          return query[0].AppUrl;
        default:
          return "http://SERVERNAME/Dashboard/" + UserId;
      }
    }
  }
}


texts:
I have a catalogue of 56000 objects and I want to replace some columns with new values for instance replace NaN with -99 and 0 for specific columns (as you can see in the following code). Then I need to compute a value for some columns with a function which is called  get_ebv_from_map
and subtract it from some other columns and so on.

Using get_ebv_from_map function to estimate the values in the catalogue is taking too much time and I think what I did like using this loop is not very efficient.

The function is given by:

from astropy import units as u
from astropy.coordinates import SkyCoord
from scipy.ndimage.interpolation import map_coordinates
import os.path
from collections import Iterable
import pyfits as fits
def get_ebv_from_map(coordinates, interpolate=True, order=1):

    mapdir='/vol/Dust_Map/maps/'
    fname = os.path.join(mapdir, 'SFD_dust_4096_{0}.fits')

    # Parse input
    ra, dec = coordinates
    coordinates = SkyCoord(ra=ra, dec=dec, unit=(u.degree, u.degree))

    # Convert to galactic coordinates.
    coordinates = coordinates.galactic
    l = coordinates.l.radian
    b = coordinates.b.radian

    # Check if l, b are scalar
    return_scalar = False
    if not isinstance(l, Iterable):
        return_scalar = True
        l, b = np.array([l]), np.array([b])

    # Initialize return array
    ebv = np.empty_like(l)

    # Treat north (b>0) separately from south (b<0).
    for n, idx, ext in [(1, b >= 0, 'ngp'), (-1, b < 0, 'sgp')]:

        if not np.any(idx): continue
        hdulist = fits.open(fname.format(ext))
        mapd = hdulist[0].data

        # Project from galactic longitude/latitude to lambert pixels.
        # (See SFD98).
        npix = mapd.shape[0]
        x = (npix / 2 * np.cos(l[idx]) * np.sqrt(1. - n*np.sin(b[idx])) +
             npix / 2 - 0.5)
        y = (-npix / 2 * n * np.sin(l[idx]) * np.sqrt(1. - n*np.sin(b[idx])) +
             npix / 2 - 0.5)

        # Get map values at these pixel coordinates.
        if interpolate:
            ebv[idx] = map_coordinates(mapd, [y, x], order=order)
        else:
            x=np.round(x).astype(np.int)
            y=np.round(y).astype(np.int)
            ebv[idx] = mapd[y, x]

        hdulist.close()

    if return_scalar:
        return ebv[0]
    return ebv

The loop is given in below:

ABtoVEGA=[+0.77,-0.13,-0.02,+0.19,+0.49,-0.19,-0.18,-0.06,-0.06,+0.04,+0.10,+0.22,+0.27,+0.36,+0.45,+0.56,+0.50]

ZP=np.loadtxt("zero-points.offsets.asc")
Gal=np.loadtxt("photometry_galaxies_photometry.cat", dtype=None)
ra=Gal[:,1]
dec=Gal[:,2]

Av=[3.836 ,3.070,2.542,2.058,1.313, 3.466 , 3.082 , 2.882 , 2.652 , 2.367 , 2.226 , 2.066 , 1.872 , 1.652 , 1.423 , 1.298 , 1.156]
count=0
for i in range(Gal.shape[0]):
    j=0
    m=39
    while (j<len(ABtoVEGA)):
         if ((isnan(float(Gal[i,j+5]))) or (isnan(float(Gal[i,j+22])))):
            Gal[i,j+5]='-99.0'
            Gal[i,j+22]='0.0'
            count+=1
         else:
            value=get_ebv_from_map((ra[i], dec[i]), interpolate=True, order=1)
            Gal[i,j+5]=str(float(Gal[i,j+5])-ABtoVEGA[j]-ZP[j]-value*Av[j])
         j+=1
    while (m<45):
          if (math.isnan(float( Gal[i,m]))):
              Gal[i,m] = '0.0'
          m+=1

Do you have any advice on how I could make it optimal and fast?


texts:
Is there any way to make this for loop more concise or efficient? I fell like there should be a way that you can cahnge the for loop so that it is about half the size that it is know. By the way, the array list defaultArabic has the values of {1,5,10,50,100,500,1000). Also, I'm not sure if you need to know this, but the goal of this code is the convert tradition roman letter such as (I,V,X,etc) to our form of numbers. Additionally, I am not looking for a whole new for loop just a revised one, as this for loop works correctly. However, it is just really long, bulky, and repetitive.

for (c = 0; c < 15; c++)
{
    findRomans = romans.get(c);
    if (findRomans.equals("I"))
    {
        if (romans.get(c + 1).equals("I"))
        {
            arabic += defaultArabics.get(0);
        }
        else
        {
            arabic -= defaultArabics.get(0);
        }
    }
    else if (findRomans.equals("V"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c + 1).equals("V"))
        {
            arabic += defaultArabics.get(1);
        }
        else
        {
            arabic -= defaultArabics.get(1);
        }
    }
    else if (findRomans.equals("X"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c +  1).equals("V") || romans.get(c + 1).equals("X"))
        {
            arabic += defaultArabics.get(2);
        }
        else
        {
            arabic -= defaultArabics.get(2);
        }
    }
    else if (findRomans.equals("L"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c + 1).equals("V") || romans.get(c + 1).equals("X") || romans.get(c + 1).equals("L"))
        {
            arabic += defaultArabics.get(3);
        }
        else
        {
            arabic -= defaultArabics.get(3);
        }
    }
    else if (findRomans.equals("C"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c + 1).equals("V") || romans.get(c + 1).equals("X") || romans.get(c + 1).equals("L") || romans.get(c + 1).equals("C"))
        {
            arabic += defaultArabics.get(4);
        }
        else
        {
            arabic -= defaultArabics.get(4);
        }
    }
    else if (findRomans.equals("D"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c + 1).equals("V") || romans.get(c + 1).equals("X") || romans.get(c + 1).equals("L") || romans.get(c + 1).equals("C") || romans.get(c + 1).equals("D"))
        {
            arabic += defaultArabics.get(5);
        }
        else
        {
            arabic -= defaultArabics.get(5);
        }
    }
    else if (findRomans.equals("M"))
    {
        if (romans.get(c + 1).equals("I") || romans.get(c + 1).equals("V") || romans.get(c + 1).equals("X") || romans.get(c + 1).equals("L") || romans.get(c + 1).equals("C") || romans.get(c + 1).equals("D") || romans.get(c + 1).equals("M"))
        {
            arabic += defaultArabics.get(6);
        }
        else
        {
            arabic += defaultArabics.get(6);
        }
    }
}
return arabic;


texts:
My goals are:

Have 2 main domains .com and .dev for production and local installations
Have 2 main subdomains. One for the site and one of the application
Site must be public and application always to be secured.

My take on the above:

<?php
$approutes =function (){

    Route::group(['middleware' => 'auth'], function(){
        Route::get('/', 'AdminController@index');

        Route::get('profile/{user}','ProfileController@index');

        Route::post('profile/{user}/update',array('as' => 'profile.update','uses' => 'ProfileController@update'));

        Route::resource('posts','PostsController');

        Route::resource('tags','TagsController');

        Route::resource('health','HealthController');

        Route::resource('health-categories','HealthCategoriesController');
    });

    Route::controllers([
        'auth' => 'Auth\AuthController',
        'password' => 'Auth\PasswordController'
    ]);
};

$siteroutes =function (){
    Route::get('/', 'SiteController@index');
};

Route::group(['domain' => 'my.xxxx.com'],$approutes);
Route::group(['domain' => 'my.xxxx.dev'],$approutes);

Route::group(['domain' => 'www.xxxx.com'],$siteroutes);
Route::group(['domain' => 'www.xxxx.dev'],$siteroutes);


texts: Simple blog using react redux react-router

texts:
I've implemented the logic of my app, but I'm not sure whether it appropriate way or not.

Task: create a react app using redux, react-router v4 which has a page with a form for adding new post and list of posts

and a page with a detail view of one of the posts

I've added a unique id for each post with help of uuid and pass id of each post to the corresponding link(react-router-dom link) in the post list

      <Link to={props.id} className='post__header'>{props.title}</Link>

When link is clicked it passes id to the DetailView component. DetailView component takes id and seek the post with the same id in the whole state then render the post

import React from 'react';
import { connect } from 'react-redux';

let DetailView = (props) => {
  console.log(props);
  var currentPost = props.posts.find(post => post.id === props.match.params.id);

  return (

{currentPost.topic}

{currentPost.text}

  )
}

const mapStateToProps = (state) => {
  return state;
};

DetailView = connect(mapStateToProps)(DetailView);

export default DetailView;

Github link: https://github.com/LKTN/Branch/tree/dev


texts:
The following program calls a function, which prompts the user for input.  The function then returns one of three enum constants; INPUT_SUCCESSFUL, INPUT_TOOLONG, or INPUT_FAILED.  If successful, it prints the text entered by the user.  Otherwise, it prints an error message, and takes the appropriate action.

The function contains three parameters.  The first one is a constant character array, which gets passed the text that will be used to prompt the user.  The second is a character array, in which the text entered by the user will be placed.  And the third is the size of the character array.

I have the following questions...

1) Would it have been better to let the called function handle the printing of error messages, exiting the program, etc, instead of the main function?

2) Would it have been better to pass a pointer to the function so that it could allocate the appropriate memory, instead of passing it a fixed array?

3) Any potential issues with the program or improvements that can be made to the code?

The program was compiled as follows...

gcc -std=c99 -Wall -Wextra -Wpedantic main.c user_input.c

...and received only warnings about unused parameters argc and argv.  Here are the files...

main.c

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

#define MAX_STR_LEN 50

int main(int argc, char *argv[])
{
    char user_input[MAX_STR_LEN + 2]; /* +2 for newline character (\n) and terminating null character (\0) */
    input_status status;

    while (1)
    {
        status = get_user_input("Enter your name: ", user_input, sizeof(user_input));

        if (status == INPUT_FAILED)
        {
            fprintf(stderr, "Unable to read user input\n");
            exit(EXIT_FAILURE);
        }

        if (status == INPUT_TOOLONG)
        {
            fprintf(stderr, "Entry exceeds %d characters\n", MAX_STR_LEN);
            continue;
        }

        if (strlen(user_input) == 0)
        {
            fprintf(stderr, "Entry is missing\n");
            continue;
        }

        if (user_input[0] == 0x18) /* user entered Ctrl+X (^x) to cancel */
        {
            fprintf(stderr, "User cancelled\n");
            return 0;
        }

        break;
    }

    printf("User entered:  %s\n", user_input);

    return 0;
}

user_input.h

#ifndef USER_INPUT_H
    #define USER_INPUT_H

    typedef enum
    {
        INPUT_SUCCESSFUL,
        INPUT_TOOLONG,
        INPUT_FAILED
    } input_status;

    void flush_input();

    input_status get_user_input(const char *prompt, char *user_input, size_t size);

#endif

user_input.c

#include <stdio.h>
#include <string.h>
#include "user_input.h"

void flush_input()
{
    int c;

    while ((c = getchar()) != '\n' && c != EOF)
        /* skip it */ ;
}

input_status get_user_input(const char *prompt, char *user_input, size_t size)
{
    printf("%s", prompt);

    if (fgets(user_input, size, stdin) == NULL)
        return INPUT_FAILED;

    char *pNewline;
    if ((pNewline = strchr(user_input, '\n')) == NULL)
    {
        flush_input();
        return INPUT_TOOLONG;
    }

    *pNewline = '\0';

    return INPUT_SUCCESSFUL;
}


texts:
I have recently answered one question on Stack Overflow.

Problem statement:

  Input sequence:

PEACCEL

  User mutation input file:

E2R C4W E6G

  The algorithm is for an input sequence of, say, PEACCEL and mutation E2R.  We
  need to replace second character in sequence, that is, E to R, and so on for
  the combinations of mutations.

I provided this answer:

from itertools import combinations,chain
from collections import Counter
input_sequence='PEACCEL'
mutations=map(lambda x:x.strip(),open('a.txt','r').readlines())
 #['E2R', 'C4W', 'E6G']
mutation_combinations= chain.from_iterable([list(combinations(mutations,i))for i in range(1,4)])
 #[('E2R',), ('C4W',), ('E6G',), ('E2R', 'C4W'), ('E2R', 'E6G'), ('C4W', 'E6G'), ('E2R', 'C4W', 'E6G')]

for i in mutation_combinations:
    print "combination :"+'_'.join(i)
    c=Counter({})
    temp_string=input_sequence
    for j in i:
        c[j[1]]=j[2].lower()
    for index,letter in c.items():
        temp_string=temp_string[:int(index)-1]+letter+temp_string[int(index):]
    print temp_string

Output:

combination :E2R
PrACCEL
combination :C4W
PEAwCEL
combination :E6G
PEACCgL
combination :E2R_C4W
PrAwCEL
combination :E2R_E6G
PrACCgL
combination :C4W_E6G
PEAwCgL
combination :E2R_C4W_E6G
PrAwCgL

Algorithm I followed:

Read the mutation sequences like E2R.... from a file using

mutations=map(lambda x:x.strip(),open('a.txt','r').readlines())

Made the combinations of the mutations

mutation_combinations= chain.from_iterable([list(combinations(mutations,i))for i in range(1,4)])

If you have 4 mutations you want all four change the range value to 5.
For each combination I replaced them with specified character:

for j in i:
    c[j[1]]=j[2].lower()

I used the above counter to keep track of which character was to be replaced during the mutation combination.

How can I make this more efficient?  I also need to know of any valuable pointers I should know while coding.


texts: Counter with increment and decrement buttons

texts:
For my first Kotlin project, I'm implementing the Redux pattern with simple Increment and Decrement buttons and a text view to display the current value.

My main questions have to do with Kotlin and Android idioms and how I structured my code. Is the below a radical departure to how Kotlin is normally written? For example the when statement... Would you put an else clause in it instead of the return at the bottom of the function?

Does it look right to override the onStart and onStop or would it make sense to move the store.subscribe code into the onCreate? If I did that, would the GC successfully collect the activity and the text field? (The GC in general has me nervous.) Is it weird to be using so many function objects or is that acceptable in Kotlin? Any constructive criticism is also wanted.

package com.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView = findViewById(R.id.textView) as TextView

        val incrementButton = findViewById(R.id.increment_button) as Button
        incrementButton.setOnClickListener { store.dispatch(Action.INCREMENT) }

        val decrementButton = findViewById(R.id.decrement_button) as Button
        decrementButton.setOnClickListener { store.dispatch(Action.DECREMENT) }

    }

    override fun onStart() {
        super.onStart()
        unsubscriber = store.subscribe { state ->
            textView?.text = state.count.toString()
        }
    }

    override fun onStop() {
        unsubscriber?.invoke()
        super.onStop()
    }

    private var unsubscriber: (() -> Unit)? = null
    private var textView: TextView? = null
}

package com.myapplication

import com.redux.Store

enum class Action { INCREMENT, DECREMENT }

data class State(val count: Int = 0) { }

fun reducer(action: Action, state: State): State {
    when (action) {
        Action.INCREMENT -> return state.copy(count = state.count + 1)
        Action.DECREMENT -> return state.copy(count = state.count - 1)
    }
    return state
}

val store = Store<Action, State>(State(), ::reducer)

package com.redux

class Store<Action, State>(initialState: State, reducer: (action: Action, state: State) -> State) {

    fun dispatch(action: Action) {
        if (dispatching) { throw Error("Can't dispatch in the middle of a dispatch.") }
        dispatching = true
        currentState = reducer(action, currentState)
        notifySubscribers()
        dispatching = false
    }

    fun subscribe(subscriber: (state: State) -> Unit): () -> Unit {
        val id = uniqueID
        uniqueID += 1
        subscribers[id] = subscriber
        val dispose: () -> Unit = {
            subscribers.remove(id)
        }
        subscriber(currentState)
        return dispose
    }

    private var currentState = initialState
    private val reducer = reducer
    private var dispatching = false
    private var subscribers: MutableMap<Int, (state: State) -> Unit> = mutableMapOf()
    private var uniqueID = 0

    private fun notifySubscribers() {
        for (subscriber in subscribers.values) {
            subscriber(currentState)
        }
    }
}


texts:
This is a specific case in merge sort.  I'm trying to do a merge sort on an array that's created using the Java Integer class.  My implementation is slow and therefore needs some modifications for better performance.  I believe the process where I copy the original items to two new arrays over and over again is slowing it down.

How do I merge sort without copying?  The sorting must be stable and both methods should return Integer[].

private static Integer[] mergeSort(Integer[] a, int p, int q)
{
    if (a.length <= 1) return a;

    int mid = (int)Math.floor((q-p)/2);
    Integer[] left = new Integer[(mid - p) + 1];
    Integer[] right = new Integer[q - mid];
    int index = 0;

    for (int i = 0; i < left.length; i++)
    {
        left[i] = a[index++];
    }
    for (int i = 0; i < right.length; i++)
    {
        right[i] = a[index++];
    }

    left = mergeSort(left, 0, left.length-1);
    right = mergeSort(right, 0, right.length-1);
    return merge(left, right);
}

private static Integer[] merge(Integer[] a, Integer[] b)
{
    int i = 0; int j = 0; int k = 0;

    Integer[] result = new Integer[a.length+b.length];

    while (i < a.length || j < b.length)
    {
        if (i != a.length && j != b.length)
        {
            if (a[i].compareTo(b[j]) <= 0)
            {
                result[k++] = a[i++];
            }
            else
            {
                result[k++] = b[j++];
            }
        }
        else if (i < a.length)
        {
            result[k++] = a[i++];
        }
        else if (j < b.length)
        {
            result[k++] = b[j++];
        }
    }

    return result;


texts: Calculating highs, lows, and volumes of stocks

texts:
I'm trying to review and figure the issues in the above code. Any inputs to point out problems are welcome.

using namespace std;
typedef basic_string<char> string;

class   CHighLow
{
public:
    CHighLow() : nCurLow(0), nCurHigh(0) {};

    void    add(int nHigh, int nLow)
    {
        if (nHigh > nCurHigh)
            nCurHigh = nHigh;

        if (nLow < nCurLow)
            nCurLow = nLow;
    }

    int     nCurLow;
    int     nCurHigh;
};

int main(int argc, char* argv[])
{
    if (!strcmp("version", argv[1]))
    {
        cerr << "Using version 1.0 VWAPer" << endl;
        return 0;
    }

    FILE*   file = fopen(argv[2], "r");

    cerr << "Reading file" << argv[2] << endl;

    char    line[256];
    char    Stocks[1000][10];
    int     Intervals[1000];
    int     Volumes[1000];
    float   Highs[1000];
    float   Lows[1000];

    int     i = 0;
    int     sum = 0;

    while (fgets(line, 256, file))
    {
        sscanf(line, "%s %d %d %f %f",
Stocks[i], &Intervals[i],
&Volumes[i], &Highs[i], &Lows[i++]);

        cerr << Stocks[i] << endl;
        cerr << Intervals[i] << endl;
        cerr << Volumes[i] << endl;
        cerr << Highs[i] << endl;
        cerr << Lows[i] << endl;
    }

    cerr << "Calculating total volumes" << endl;

    map<std::string, int>       TotalVolumes;

    for (int s = 0; s <= i; ++s)
    {
        std::string stockname = Stocks[s];

        for (int j =0; j <= i; ++j)
        {
            if (!strcmp(Stocks[j], stockname.c_str()))
            {
                TotalVolumes[stockname] += Volumes[j];
            }
        }
    }

    cerr << "Calculating high lows" << endl;

    map<std::string, CHighLow>  HighLows;

    for (int s = 0; s <= i; ++s)
    {
        HighLows[Stocks[s]].add(Highs[s], Lows[s]);
    }

    cerr << "Writing files" << endl;

    // write file a
    for (int s = 0; s <= i; ++s)
    {
        cout << Stocks[s] << "," << Intervals[s] << "," <<
TotalVolumes[Stocks[s]] / Volumes[s] * 100 << endl;
    }

    // write file b
    map<std::string, CHighLow>::iterator itr = HighLows.begin();
    while (itr != HighLows.end())
    {
        cout << (*itr).first << "," << (*itr).second.nCurLow << "," <<
(*itr).second.nCurHigh << endl;

        ++itr;
    }

    return 1;
}


texts:
For digital electronic circuit simulation, i wanted to implement Three states. i.e High, Low and Undefined in C++.

I saw Boost::tribool, and they implement it using enum

Now for conserving some memory i have implemented it using 1 Byte Int

#ifdef _WINDOWS
typedef __int8 State;
#elif
typedef int8_t State;
#endif

const State kLow = 0;
const State kHigh = 1;
const State kUndefined = 2;

Do you see any potential problem with it?
And why would one waste 4 bytes instead of a single byte for 3 values only
Do you have a still better way?


texts: Seconds between datestimes excluding weekends and evenings

texts:
The basic idea here is that I want to measure the number of seconds between two python datetime objects. However, I only want to count hours between 8:00 and 17:00, as well as skipping weekends (saturday and sunday). This works, but I wondered if anyone had clever ideas to make it cleaner.

START_HOUR = 8
STOP_HOUR = 17
KEEP = (STOP_HOUR - START_HOUR)/24.0

def seconds_between(a, b):

    weekend_seconds = 0

    current = a
    while current < b:
        current += timedelta(days = 1)
        if current.weekday() in (5,6):
            weekend_seconds += 24*60*60*KEEP

    a_stop_hour = datetime(a.year, a.month, a.day, STOP_HOUR)
    seconds = max(0, (a_stop_hour - a).total_seconds())
    b_stop_hour = datetime(b.year, b.month, b.day, STOP_HOUR)
    if b_stop_hour > b:
        b_stop_hour = datetime(b.year, b.month, b.day-1, STOP_HOUR)

    seconds += (b - b_stop_hour).total_seconds()

    return (b_stop_hour - a_stop_hour).total_seconds() * KEEP + seconds - weekend_seconds


texts:
This is a USB related question, but the problem is not USB specific. When reading data from a USB endpoint, there are two patterns I am concerned with. Request/Response like HTTP (done over the Bulk endpoint), and Interrupt transfer where one would continuously poll the interrupt endpoint without writing data to the device.

In one particular case, there is a device that uses a request/response pattern but over the interrupt endpoint. This usually isn't a problem, but the UWP USB API does the polling for you on the interrupt endpoint and treats the incoming data as an event. So, if I want to implement a ReadAsync method, I need to await some kind of TaskCompletionSource to get the data. This is certainly not elegant but I'm looking for the least nasty way of synchronizing the context. I've used a combination of SemaphoreSlim and TaskCompletionSource here. Is there a more elegant way?

Code

private async void UsbInterruptInPipe_DataReceived(UsbInterruptInPipe sender, UsbInterruptInEventArgs args)
{
    try
    {
        await _DataReceivedLock.WaitAsync();

        var bytes = args.InterruptData.ToArray();
        _Chunks.Add(bytes);

        if (bytes != null)
        {
            Logger?.Log($"{bytes.Length} read on interrupt pipe {UsbInterruptInPipe.EndpointDescriptor.EndpointNumber}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
        }

        if (_ReadChunkTaskCompletionSource != null && _ReadChunkTaskCompletionSource.Task.Status!= TaskStatus.RanToCompletion)
        {
            //In this case there should be no chunks. TODO: Put some unit tests around this.
            //The read method wil be waiting on this
            var result = _Chunks[0];
            _Chunks.RemoveAt(0);
            _ReadChunkTaskCompletionSource.SetResult(result);
            Logger?.Log($"Completion source result set", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
            return;
        }
    }
    finally
    {
        _DataReceivedLock.Release();
    }
}

And

public async Task<byte[]> ReadAsync()
{
    try
    {
        Logger?.Log($"Read called on {nameof(UWPUsbInterfaceInterruptReadEndpoint)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);

        await _ReadLock.WaitAsync();

        byte[] retVal = null;

        try
        {
            //Don't let any datas be added to the chunks here
            await _DataReceivedLock.WaitAsync();

            if (_Chunks.Count > 0)
            {
                retVal = _Chunks[0];
                Tracer?.Trace(false, retVal);
                _Chunks.RemoveAt(0);
                Logger?.Log($"Read the first chunk {nameof(UWPUsbInterfaceInterruptReadEndpoint)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);
                return retVal;
            }
        }
        catch(Exception ex)
        {
            Logger?.Log($"Error {nameof(ReadAsync)}", nameof(UWPUsbInterfaceInterruptReadEndpoint), ex, LogLevel.Error);
            throw;
        }
        finally
        {
            _DataReceivedLock.Release();
        }

        _ReadChunkTaskCompletionSource = new TaskCompletionSource<byte[]>();

        Logger?.Log($"Data received lock released. Completion source created. Waiting for data.", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);

        //Wait for the event here. Once the event occurs, this should return and the semaphore should be released
        retVal = await _ReadChunkTaskCompletionSource.Task;

        _ReadChunkTaskCompletionSource = null;

        Logger?.Log($"Completion source nulled", nameof(UWPUsbInterfaceInterruptReadEndpoint), null, LogLevel.Information);

        Tracer?.Trace(false, retVal);
        return retVal;
    }
    finally
    {
        _ReadLock.Release();
    }
}


texts:
This a small project for a beginner, it basically generate symbols digits letters depending on the user input I want to make the code better and learn from my mistakes.
import string
import random
asklenght = 0

asku = int(input("Please choose a method:\n 1)Digits \n 2)Letters \n 3) Symbols \n 4) All \n "))
asklenght = int(input("How long do you want your password to be ?  "))

digits = string.digits
letters = string.ascii_letters
symbols = string.punctuation

if asku == 1:
    outputpass = random.choice(digits)
elif asku == 2:
    outputpass = random.choice(letters)
elif asku == 3:
    outputpass = random.choice(symbols)
else:
    outputpass = random.choice(digits)
    outputpass = random.choice(letters)
    outputpass = random.choice(symbols)

for i in range(asklenght - 1 ):
    if asku == 1:
        outputpass += random.choice(digits)
    elif asku == 2:
        outputpass += random.choice(letters)
    elif asku == 3:
        outputpass += random.choice(symbols)
    else:
        outputpass += random.choice(digits)
        outputpass += random.choice(letters)
        outputpass += random.choice(symbols)

print(outputpass)


texts:
I'm a first time user of jQuery (and a huge fan already). I am trying to make the comic picture of an xkcd page onclick to the explanation page.

Here's what I've done.

$("#comic").click(function(){
  return window.open("http://www.explainxkcd.com/wiki/index.php/" +
    document.URL.split("/")[3]);
});

Is this efficient? Is this robust? Any jQuerying tips?


texts: Applying chain responsibility with IFilter

texts:
I have an interface IFilter and more types of filters: Filter1, Filter2, Filter3; that I want to call one after the other and if the result of one is empty, then I want to stop the process. For this I have thought of:

class FiltersSequence
{
private:
    std::vector< IFilter > m_filters;

public:
    FiltersSequence();
    ~FiltersSequence();

    /**/
    ObjectToFilter execute(const ObjectToFilter& objectToFilterIn);
};

With the implementations:

FiltersSequence::FiltersSequence()
{
    m_filters.push_back(Filter3());
    m_filters.push_back(Filter2());
    m_filters.push_back(Filter1());
}

FiltersSequence::~FiltersSequence() {}

ObjectToFilter FiltersSequence::execute(const ObjectToFilter& objectToFilterIn)
{
    ObjectToFilter filterResult = objectToFilterIn;

    for (std::size_t i = 0; i < m_filters.size(); i++)
    {
        filterResult = m_filters[i].execute();
        if (filterResult.isEmpty())
        {
            return filterResult;
        }
    }

    return filterResult;
}

It should be vector of pointers, because the filters are not all the same size; so I have changed to:

std::vector< std::shared_ptr< IFilter > > m_filters;

and

m_filters.push_back(std::shared_ptr< IFilter >(new FilterX()));

I thought of something like having a map< std::string, IFilter > for being sure that the sequence is in the order that I want. What do you think of this? Is it good enough? Or this is just making it more complicated and I need just to pay attention at push_back. BTW, is this going to call them in right order (1, 2, 3)?


texts: Sliding window to solve "longest substring, no repeating chars"

texts:
Question: Longest Substring Without Repeating Characters

  Given a string, find the length of the longest substring without
  repeating characters.

  Examples:

  Given "abcabcbb", the answer is "abc", which the length is 3.

  Given "bbbbb", the answer is "b", with the length of 1.

  Given "pwwkew", the answer is "wke", with the length of 3. Note that
  the answer must be a substring, "pwke" is a subsequence and not a
  substring.

Solution:
We use a sliding window to define the current substring. In my solution, we start with head = position 0 and tail = position 0 in a way where
[H][T]a b c a b c b b and NO characters have been marked as "seen". After the first iteration, head=0, tail=1, our positioning is [H]a[T]b c a b c b b and our first character a at position 0 has been seen.

We then advance the tail and add the character seen to a hashmap hm. If we've already seen this character, we advance the head point to one position past the position the character was last seen. We are done once the tail position is equal to the length of the string.

Why I am posting here asking for feedback is that my #1 concern is that there's no proper way to define my sliding window method. How am I supposed to explain my method to an interviewer? I can't define it mathematically, as it's not [head, tail) nor is it (head, tail). What would be a way to improve my sliding window method so that it's well-defined and I can re-use this strategy every time I need to use a sliding window ?

class Solution {
    int head = 0;
    int tail = 0;
    int max = 0; // current max length

    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> hm = new HashMap<>(); // value = position of character
        int currSize = 0;

        while(tail < s.length()) {
            tail++;
            char curr = s.charAt(tail-1);
            if (!(hm.containsKey(curr) && hm.get(curr) >= head)) {
                hm.put(curr, tail-1);
                compareMax(++currSize);
            } else {
                head = hm.get(curr)+1;
                hm.put(curr, tail-1);
                currSize = tail-head;
            }
            System.out.println("head: " + head + ", tail: " + tail + ", size: " + currSize);
        }
        return max;
    }

    void compareMax(int currSize) {
        if (currSize > max) {
            max = currSize;
        }
    }
}

Output for 'abcabcbb':

head: 0, tail: 1, size: 1
head: 0, tail: 2, size: 2
head: 0, tail: 3, size: 3
head: 1, tail: 4, size: 3
head: 2, tail: 5, size: 3
head: 3, tail: 6, size: 3
head: 5, tail: 7, size: 2
head: 7, tail: 8, size: 1


texts:
Although having very little C++ experience, I was tasked to implement several statistics objects that are safe to be asynchronous accessed by different threads, that collect data in relatively small memory caches and do the math when asked. Many of those I need to write are based on averaging, so help me by inspecting  basic averaging class. I just hope to avoid any strategic errors in design of my cargo-cult code-gluing efforts.

#include <mutex>

template <typename T, int N> class Average {
    T data[N];
    int head;
    double avg;
    int itr;
    int counter;
    std::mutex _mutex;

public:

Average() : head(0), avg(0.), itr(0), counter(0) {
};

void empty() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    head = 0;
    avg = 0.;
    itr = 0;
    counter = 0;
}

int count() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    return counter;
}

void push(T value) {
    std::unique_lock<std::mutex> lock(this->_mutex);

    counter++;
    data [head] = value;
    double tmp = 0.;

    if (++head == N) {
        head = 0;

        for (int i = 0; i < N; i++) {
            tmp = tmp + data[i];
        }

        tmp = tmp / N;
        avg = (avg * itr) + tmp;
        itr += 1;
        avg = avg / itr;
    }
}

double average() {
    std::unique_lock<std::mutex> lock(this->_mutex);

    double tmp = 0.;

    if (head == 0){
        if (itr == 0) return 0.0;
        return avg;
    }

    for (int i = 0; i < head; i++) {
        tmp = tmp + data[i];
    }

    if (itr == 0) return tmp / head;

    tmp = tmp/N;
    return ((avg * itr) + tmp) / ((double)itr + (double)head/(double)N);

    }
};

As an usage example, by extending the Average class, I implemented a RunningAverage class which averages only let say last N pushed values. I got a worker pool that perform Monte Carlo simulation where it is preferred to maintain step acceptance rate 0.5+/-0.1 and when rate falls outside, I adjust model parameters. So I got something like:

#define ACCEPT_STEP 1
#define DECLINE_STEP 0

RunningAverage <float, ACC_BUFFER_LEN> global_acceptance_rate;

and thread do something like:

global_acceptance_rate.push(ACCEPT_STEP); // or
global_acceptance_rate.push(DECLINE_STEP);

So this allows me to dynamically control simulation.


texts:
I'm at the point where I am happy with the functionality of my code but I dislike how its written. It seems like I can be more modular with it but I can't seem to figure out how to improve on it without changing to much. I understand that I can probably merge both getMed Methods but they are end points in a URL which I rather keep separate. Any assistance will be greatly appreciated

private function getSIS($url, $session, Application $app)
{
    $response = "You don't have permission to access this!";

    if($app['security']->isGranted('ROLE_SUPER_ADMIN'))
    {
        //['fomservices']['sis'] is hard coded in my config dev/prod file.
        $client = new Client(['base_uri' => $app['fomservices']['sis'],]);
        //for testing
        $token = 123456;

        try {
            if (!empty($session)) {
                $response = $client->request('GET', $url.'/'.$session, [
                    'headers' => [
                        'token' => $token
                    ]
                ]);
            } else {
                $response = $client->request('GET', $url, [
                    'headers' => [
                        'token' => $token
                    ]
                ]);
            }
            return $response;
        } catch (ClientException $e) {
            $response = $e->getResponse();
            $responseBodyAsString = $response->getBody()->getContents();
            return new Response($responseBodyAsString, $response->getStatusCode());
        } catch (ServerException $e) {
            $response = $e->getResponse();
            $responseBodyAsString = $response->getBody()->getContents();
            return new Response($responseBodyAsString, $response->getStatusCode());
        } catch (BadResponseException $e){
            $response = $e->getResponse();
            $responseBodyAsString = $response->getBody()->getContents();
            return new Response($responseBodyAsString, $response->getStatusCode());
        }
    }

    return $response;
}

public function getMedAction(Application $app)
{
    $response = $this->getSIS('med', '', $app);
    if($response instanceof \GuzzleHttp\Psr7\Response)
        return $response->getBody();
    return new Response ($response);
}

public function getMedSessionAction($session, Application $app)
{
    $response = $this->getSIS('med', $session, $app);
    if($response instanceof \GuzzleHttp\Psr7\Response)
        return $response->getBody();
    return new Response ($response);
}


texts:
I coded a little implementation to encrypt and decrypt bytes with AES256 (ECB) in C#. I wanted to know if I can optimize/cleanup my code a bit more, or if it i fine like this:

using System;
using System.Security.Cryptography;
using System.Text;

namespace AES256
{
    class Program
    {

        private static string getString(byte[] b)
        {
            return Encoding.UTF8.GetString(b);
        }

        static void Main(string[] args)
        {

            byte[] data = Encoding.UTF8.GetBytes("This is just a little message to test AES.");

            byte[] key = { 7, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,
                           1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 };

            byte[] enc = Encrypt(data, key);
            byte[] dec = Decrypt(enc, key);

            Console.WriteLine("Input : {0}", getString(data));
            Console.WriteLine("Key : {0}", getString(key));
            Console.WriteLine("KeySize : {0}", 256);
            Console.WriteLine("Encrypted : {0}", getString(enc));
            Console.WriteLine("Decrypted : {0}", getString(dec));

            Console.ReadKey();

        }

        public static byte[] Encrypt(byte[] data, byte[] key)
        {
            using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
            {
                csp.KeySize = 256;
                csp.BlockSize = 128;
                csp.Key = key;
                csp.Padding = PaddingMode.PKCS7;
                csp.Mode = CipherMode.ECB;
                ICryptoTransform encrypter = csp.CreateEncryptor();
                return encrypter.TransformFinalBlock(data, 0, data.Length);
            }
        }

        private static byte[] Decrypt(byte[] data, byte[] key)
        {
            using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
            {
                csp.KeySize = 256;
                csp.BlockSize = 128;
                csp.Key = key;
                csp.Padding = PaddingMode.PKCS7;
                csp.Mode = CipherMode.ECB;
                ICryptoTransform decrypter = csp.CreateDecryptor();
                return decrypter.TransformFinalBlock(data, 0, data.Length);
            }
        }

    }
}


texts:
This code connects to COM 3 which has a broadband card and sends a command that returns the RSSI value. I use this program to see patterns in signal strength in certain areas.

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

int main()
{
    HANDLE hSerial = CreateFile("COM3",GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

    if(hSerial==INVALID_HANDLE_VALUE)
        std::cout << "Insert error message";

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);

    if (!GetCommState(hSerial, &dcbSerialParams))
        std::cout << "Insert error message";

    dcbSerialParams.BaudRate=CBR_9600;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;

    if (!SetCommState(hSerial,&dcbSerialParams))
        std::cout << "Insert error message";

    COMMTIMEOUTS timeouts={0};
    timeouts.ReadIntervalTimeout=50;
    timeouts.ReadTotalTimeoutConstant=50;
    timeouts.ReadTotalTimeoutMultiplier=10;
    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;
    if(!SetCommTimeouts(hSerial, &timeouts))
        std::cout << "Insert error message";

    while(1)
    {
        char szBuff[50+1] = {0};
        char wzBuff[14] = {"AT+CSQ\r"};

        DWORD dZBytesRead = 0;
        DWORD dwBytesRead = 0;

        if(!WriteFile(hSerial, wzBuff, 7, &dZBytesRead, NULL))
            std::cout << "Write error";

        if(!ReadFile(hSerial, szBuff, 50, &dwBytesRead, NULL))
            std::cout << "Read Error";

        std::string subString = std::string(szBuff).substr(8,3);
        std::cout << subString;

        Sleep(500);
    }

    return 0;
}


texts: Project Euler #4 - Largest Palindrome Product

texts:
Problem Statement:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

This code is in C++ 11, please review my code.

#include <iostream>
#include <math.h>

using namespace std;

int palindrom(int num);

int main()
{
    auto n1 = 999u;
    auto n2 = 999u;
    unsigned int n = 0u;

    unsigned int largest = 0;

    for (; n1>=100; n2--)
    {
        if (n2 < 100)
        {
            n1--;
            n2 = 999;
            continue;
        }

        if (palindrom(n1*n2) == n1*n2)
        {
            cout << "n1 << " << n1 << " n2 " << n2 << endl;
            cout << n1*n2;

            if (largest < n1*n2)
                largest = n1*n2;
        }
    }

    cout << "Largest" << largest << endl;

    return 0;
}

int palindrom(int num)
{
    int new_num = 0;
    int digit = 0;

    while (num != 0)
    {
        digit = num % 10;
        new_num = new_num*10 + digit;
        num /= 10;
    }

    return new_num;
}

Output (project Euler solution kept secret)

   906609


texts:
I wrote a zscore algorithm in Ruby that runs fine, but is incredibly slow when I have 8000+ entries to score. Can anyone help me figure out a way to improve my code, please?

module Enumerable
  def mean
    reduce(:+).to_f / length
  end

  def sample_variance
    sum = inject(0){ |acc, i| acc + (i - mean)**2 }
    1 / length.to_f * sum
  end

  def standard_deviation
    Math.sqrt(sample_variance)
  end

  def zscore
    if standard_deviation.zero?
      Array.new(length, 0)
    else
      collect { |v| (v - mean) / standard_deviation }
    end
  end
end

The float is giving every score an accuracy of up to 17 decimal places.  Would making it only 8 decimal places speed things up?

EDIT:
Here is an updated version of the algorithm given the advice received in this thread.

class Array
  def mean(len=self.length)
    reduce(:+).to_f / len
  end

  def sample_variance
    len = length
    m = mean(len)
    sum = reduce { |acc, i| acc + (i - m)**2 }
    sum.to_f / len
  end

  def standard_deviation
    Math.sqrt(sample_variance)
  end

  def zscore
    stdev = standard_deviation
    m = mean
    stdev.zero? ? Array.new(length, 0) : collect { |v| (v - m) / stdev }
  end
end


texts:
Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

I wrote a solution to this second problem from Project Euler, and would appreciate a review of it. Here's the code:

package Problems.Level_1;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Manish on 10/14/2015.
 * find sum of even terms of Fibonacci series whose values do not exceed four million
 */
public class Problem_2 {

    private List<Integer> generateFibonacci() {
        List<Integer> numbers = new ArrayList<>();
        int first = 1;
        int last = 2;
        numbers.add(first);
        numbers.add(last);
        int sum = 0;
        //modify for loop to limit value = 4 mil?
        //for(int i = 2; i < limit; i++)
            while(sum <= 4000000){
            sum = first + last;
            numbers.add(sum);
            first = last;
            last = sum;
        }

        return numbers;
    }

    //method to generate int array from a List of integers
    private int[] buildIntArray(List<Integer> integers) {
        int[] ints = new int[integers.size()];
        int i = 0;
        for (Integer n : integers) {
            ints[i++] = n;
        }
        return ints;
    }

    //method to calculate sum of even items in array
    private int calculateEvenSum(int[] numList){
        int result = 0;
        for(int i = 0; i < numList.length; i++) {
            if(numList[i] % 2 == 0) {
                result += numList[i];
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Problem_2 p2 = new Problem_2();

        //System.out.println("The first 10 numbers of the Fibonacci Series are: " + p2.generateFibonacci(10));
        //System.out.println("Enter the limit.");
       // int l = new Scanner(System.in).nextInt();

        List<Integer> list = p2.generateFibonacci();
        int[] numList = p2.buildIntArray(list);
        int answer = p2.calculateEvenSum(numList);

        System.out.println("The sum is: " + answer);
    }
}

Right off the bat, I get that it might not be the best idea to generate an entire Fibnoacci sequence, the sum can probably be determined without that. Then there might be things like creating and storing a List, creating and storing an array from the List, etc.

Does this solution cause too much of an unnecessary overhead?


texts:
I was trying to refactor the following code for Caesar cipher, but it feels overly complicated at the end of the refactoring. Could someone else take a look at it and let me know if I am just overdoing/making it complicated for someone trying to read the code?

My highest priority is to write readable code, so any pointers in that regard would be welcome.

module CASE_WRAP
  def cyclic_next!
    if self == 'z'
      replace 'a'
      return
    end

    if self == 'Z'
      replace 'A'
      return
    end

    self.next!
  end

  def shift(number)
    number.times { self.cyclic_next! }
    self
  end
end

class CaesarCipher
  def self.cipher(message, shift)
    CaesarCipher.new(shift: shift)
      .encrypt message
  end

  def initialize(shift: 0)
    @shift = shift
  end

  def encrypt(message)
    message.gsub(/\w/) do |character|
      character.extend(CASE_WRAP)
        .shift @shift
    end
  end
end

Find tests for this in my repo.


texts: How to make Map expendible(?) safely in java

texts:
I am building some statistic counter in Java.
Each metric could have flexible depth so the implementation should able to explore the depth when value insert or update.
So I implement like below (with Test)
public class TestRecursiveMap {

    private void recursiveRegister(Map<String, Object> target, String[] keys, int curr) {
        if(curr > keys.length -1) return;
        String currKey = keys[curr];
        if(target.containsKey(currKey)) {
            Object currVal = target.get(currKey);
            if(curr >= keys.length -1) {
                int value = (int) currVal;
                target.put(currKey, value + 1);
            } else {
                Map<String, Object> subMap = (Map<String, Object>)currVal;
                recursiveRegister(subMap, keys, curr + 1);
            }
        } else {
            if(curr >= keys.length -1) {
                target.put(currKey, 1);
            } else {
                Map<String, Object> emptyMap = new HashMap<>();
                target.put(currKey, emptyMap);
                recursiveRegister(emptyMap, keys, curr + 1);
            }
        }
    }

    // result looks like
    // {a={b={c=1}}}
    // {a={b={c=2}}}
    @Test
    public void testRecursive(){
        Map<String, Object> originMap = new HashMap<>();
        String[] keys = {"a", "b", "c"};
        recursiveRegister(originMap, keys, 0);
        System.out.println(originMap);
        recursiveRegister(originMap, keys, 0);
        System.out.println(originMap);
    }
}

The code is so unsatisfied because of

casting in recursive logic - Map<String, Object> is very flexible but need to cast object to map or integer in every level

while casting there are bunch of possibilities of exceptions

How could I implement this safe and fast?
=====================================
Use case #1.
Actually this is an api counter. When you have an API call, it will counting the mount of the request.
For instance,
/api/user/1 and /api/v1/user/1 then it will have some value like below (in JSON form)
{
    "api" : {
        "user" : {
            "1" : 1
        },
        "v1" : {
            "user" : {
                "1" : 1
            }
        }
    }

}

So the basic logic is

if there is a key in the map, it will increase the number
if not, it will assign new k,v set and the initial value is 1


texts: Dynamically configurable ZMQ filter with Flask API

texts:
I have a stream of ZMQ messages, I need to filter the right ones and save them in MongoDB. The trick is to have an option to set the filter conditions dynamically.

I have come up with this solution using multiprocessing and Flask. Basicaly I use Flask HTTP API to change the global filter_parameters dictionary given by Manager and shared with another Process that is running the zmq filter itself. So my question is - is it a good solution and what is the best practice in this regard?

from multiprocessing import Process, Manager
from flask import Flask, jsonify, request
from pymongo import MongoClient

app = Flask(__name__)
manager = Manager()
filter_parameters = manager.dict()
filter_parameters['addresses'] = ['']

def scan(q, filter_parameters):
    import zmq
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.connect("tcp://localhost:5556")
    socket.setsockopt_unicode(zmq.SUBSCRIBE, 'tx')
    client = MongoClient() # localhost
    db = client.transactions_db
    tx_collection = db.tx_collection
    while True:
        recv_str = socket.recv_string()
        recv_str = recv_str.split()
        filter(recv_str, filter_parameters, tx_collection)

def filter(recv_str, filter_parameters, tx_collection):
    if recv_str[0] == 'tx':
        if recv_str[7] == '0':
            if recv_str[2] in filter_parameters['addresses']:
                tx_collection.insert_one({'tx':recv_str}).inserted_id

p = Process(target=scan, args=(filter_parameters))
p.daemon = True
p.start()

@app.route('/zmq_buffer/set_filter_addresses', methods=["POST"])
def set_filter_addresses():
    data_jsn = request.json
    filter_parameters['addresses'] = data_jsn['addresses']
    return jsonify({'addresses':filter_parameters['addresses']}), 200

@app.route('/zmq_buffer/get_filter_addresses', methods=["GET"])
def get_filter_addresses():
    if filter_parameters['addresses']:
        resp = jsonify(filter_parameters['addresses'])
    else:
        resp = 'None'
    return resp, 200

if __name__ == '__main__':
    app.run(port=7050)
    p.terminate()


texts:
In A Tour of Go, you are given the following problem:

  In this exercise you'll use Go's concurrency features to parallelize a
  web crawler.

  Modify the Crawl function to fetch URLs in parallel without fetching
  the same URL twice.

This is the code you're given

package main

import (
    "fmt"
)

type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls []string, err error)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
    // TODO: Fetch URLs in parallel.
    // TODO: Don't fetch the same URL twice.
    // This implementation doesn't do either:
    if depth <= 0 {
        return
    }
    body, urls, err := fetcher.Fetch(url)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("found: %s %q\n", url, body)
    for _, u := range urls {
        Crawl(u, depth-1, fetcher)
    }
    return
}

func main() {
    Crawl("http://golang.org/", 4, fetcher)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
    body string
    urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
    if res, ok := f[url]; ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "http://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "http://golang.org/pkg/",
            "http://golang.org/cmd/",
        },
    },
    "http://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "http://golang.org/",
            "http://golang.org/cmd/",
            "http://golang.org/pkg/fmt/",
            "http://golang.org/pkg/os/",
        },
    },
    "http://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
    "http://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "http://golang.org/",
            "http://golang.org/pkg/",
        },
    },
}

And this is the solution I came up with

type Job struct {
    url   string
    depth int
    done  chan bool
}

func dedup(fetcher Fetcher, ch chan Job) {
    seen := make(map[string]bool)
    for job := range ch {
        if _, ok := seen[job.url]; ok || job.depth <= 0 {
            job.done <- true
            continue
        }
        seen[job.url] = true
        go Crawl(job, fetcher, ch)
    }
}

func Crawl(job Job, fetcher Fetcher, q chan Job) {
    body, urls, err := fetcher.Fetch(job.url)
    if err != nil {
        fmt.Println(err)
        job.done <- true
        return
    }
    fmt.Printf("found: %s %q\n", job.url, body)
    ch := make(chan bool, len(urls))
    for _, u := range urls {
        u := u
        go func() { q <- Job{u, job.depth - 1, ch} }()
    }
    for i := 0; i < len(urls); i++ {
        <-ch
    }
    job.done <- true
    return
}

func main() {
    done := make(chan bool, 1)
    q := make(chan Job)
    go dedup(fetcher, q)
    q <- Job{"http://golang.org/", 4, done}
    <-done
}

All jobs go through dedup's channel, so that a given URL is fetched only once. dedup kicks off a goroutine for each unique URL it sees, and the goroutine then adds URLs from that page back to the channel.

Go's way of thinking is new to me, so my main concerns are

Is it idiomatic?
Is it clear what's going on to someone who's familiar with Go?
Is buffering the channels in this way necessary (or even helpful)?


texts: Replace for loop while with apply family function in R

texts:
I have trouble with for loop, my code runs very slowly. The thing I want to do is to use function from apply family to make my codes run faster (instead of using for loopand while). Here is an example and my loop:

require(data.table)
require(zoo)

K<-seq(1,1000, by=1)
b<-c(rep(2,250), rep(3, 250), rep(4, 250), rep(5,250))
a<-c(rep(6,250), rep(7,250), rep(8,250), rep(9,250))
rf<-rep(0.05, 1000)
L<-rep(10,1000)
cap<-rep(20,1000)
df<-data.frame(K, rf, L, cap, a,b)
blackscholes <- function(S, X, rf, h, sigma) {
    d1 <- (log(S/X)+(rf+sigma^2/2)*h)/sigma*sqrt(h)
}
df$logiterK<-log(df$K)
df<-as.data.table(df)
df[,rollsd:=rollapply(logret, 250, sd, fill = NA, align='right')*sqrt(250), by=c("a", "b")]
df[,assetreturn:=c(NA,diff(logiterK)),by=c("a", "b")]
df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("a", "b")]
df[,K1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])),by=c("a","b")]

errors<-ddply( df, .(a,b), function(x) sum((x$K-x$K1)^2))
df<-as.data.frame(df)
df<-join(df, errors, by=c("a", "b"))
for ( i in 1:nrow(errors)){
    while(errors$V1[i] >= 10^(-10)) {
        df<-as.data.table(df)
        df[,K:= K1,by=c("a", "b")]
        df[,assetreturn:=c(NA,diff(log(K))),by=c("a", "b")]
        df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("a", "b")]
        df[,iterK1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])) ,by=c("a", "b")]
        df<-as.data.frame(df)
        errors$V1[i]<-sum((df[df$V1 %in% errors$V1[i],"K"]-df[df$V1 %in% errors$V1[i],"K1"])^2)
        }
    }

Any help would be appreciated.


texts:
I'm writing some code which needs to take a generic java.util.List from another source and adapt to the available functions; eg. does it support add(), set(), etc.

I'm currently just calling the functions on the list and creating a set of available operations, but I'm wondering if there's a better way than try-catch.

Current code:

import java.util.*;

import javax.swing.JPanel;

public class JListPanel<T> extends JPanel {
    private static final long serialVersionUID = 832057842976869638L;

    private static enum JLPFlag {
        ADD, REMOVE, SET;
    }

    private List<T> list;
    private Set<JLPFlag> flags = EnumSet.allOf(JLPFlag.class);

    public JListPanel(List<T> backinglist) {
        list = backinglist;
        setFlags();
    }

    private void setFlags() {
        // store the last state
        List<T> prev = Collections.unmodifiableList(list);
        boolean empty = list.isEmpty();
        try {
            if (!empty) {
                list.add(list.get(0));
            } else {
                // hope that list allows null
                list.add(null);
            }
        } catch (Exception e) {
            flags.remove(JLPFlag.ADD);
        }
        try {
            list.set(0, list.get(0));
        } catch (Exception e) {
            flags.remove(JLPFlag.SET);
        }
        try {
            list.remove(0);
        } catch (Exception e) {
            flags.remove(JLPFlag.REMOVE);
        }
        if (flags.contains(JLPFlag.REMOVE))
            list.removeAll(list);
        if (flags.contains(JLPFlag.ADD))
            list.addAll(prev);
    }
}

Edit: This is supposed to be a JPanel that contains a list that can be modified by a program and this should reflect those changes on the list display. It's not complete yet, but the ultimate goal is to have a list that can be modified by the user or programmer. It will have some buttons that will be disabled if the list doesn't support the operations, so it might not have add or remove but it might have set.

I've compiled most of the suggestions into this new function: http://pastebin.com/JPWXdFfi


texts: Getting data from the server via JSON callback and parsing the data to HTML

texts:
I'm pretty new to web development with JS and was wondering if anyone can tell me how I can improve my code. I just feel like when it comes to maintainability my code would be very difficult to update. Can someone advice on some best practices or maybe how they do it?

JavaScript

Here is a typical onready jQuery function. It calls a JSON and goes through the object with .each and parses the data to HTML and appends it the HTML DOM.

$(document).ready(function () {

    var fullday_start = '

Field 1	 Field 2	 Date 	Notes
';

    $.each(eventsData, function () {
        day_render_html_output = fullday_start;
        day_render_html_output += renderFullRow(start, end, names, this.uniqueID);

    });

    $('#output').html(day_render_html_output);
});

Here is an example/attempt of me trying to have some sense of maintainability by creating some JS functions that render outputs in HTML with given data from the JSON that's get called from onready above.

function renderFullRow(startDate, endDate, names, uniqueID) {
    var html_output = '
Day	<select id="type_' + uniqueID + '">' + names + '</select>	';
    html_output += '' + startDate + ' - ' + endDate + '	';
    html_output += '<button type="button" class="accordion-toggle btn btn-default btn-small" data-toggle="collapse" data-parent="#accordion' + uniqueID + '" href="#collapseOne' + uniqueID + '"></button>
';
    html_output += '

<button onclick="clearMsgBox(\'' + uniqueID + '\')" type="button" class="close" data-toggle="collapse" data-parent="#accordion' + uniqueID + '" href="#collapseOne' + uniqueID + '">x</button><textarea id="msg_box_' + uniqueID + '" style="width: 92%;" rows="2" placeholder="Message..."></textarea>

';
    return html_output;
}

function clearMsgBox(ebID){
    $('#msg_box_'+ebID).val('');
}

Could someone enlighten me on how to improve code like this?


texts:
I'm trying to brush up on my algorithms and data structures and wrote a fixed sized hash map assuming both key and value will be only integers. This is a significant simplification of the real case and is supposed to be so. Any comments regarding bugs, best practices, style is gladly appreciated.

#include <vector>
#include <iostream>
#include <exception>
#include <stdexcept>
#include <assert.h>
#define SIZE 10

class HashEntry {
public:
    int _k;
    int _v;
    HashEntry(int k, int v) : _k(k), _v(v) {};
};

class HashMap {
private:
    std::vector<HashEntry> buckets[SIZE];
    int hashFunc(int key);
    std::vector<HashEntry>& getBucket(int key);

public:
    bool keyExists(int k);
    HashEntry get(int k);
    bool put(int k, int v);
    bool remove(int k);
};

int HashMap::hashFunc(int key) {
    return key % SIZE;
}

std::vector<HashEntry>& HashMap::getBucket(int key) {
    if (key < 0) {
        throw std::runtime_error("key should be >= 0");
    }
    return buckets[hashFunc(key)];
}

HashEntry HashMap::get(int k) {
    std::vector<HashEntry>& bucket = getBucket(k);
    for (HashEntry entry : bucket) {
        if (entry._k == k) {
            return entry;
        }
    }
    throw std::runtime_error("Key not found");
}
bool HashMap::keyExists(int k) {
    std::vector<HashEntry>& bucket = getBucket(k);
    for (HashEntry entry : bucket) {
        if (entry._k == k) {

            // key already exists
            return true;
        }
    }
    return false;
}

bool HashMap::put(int k, int v) {
    std::vector<HashEntry>& bucket = getBucket(k);
    if (keyExists(k)) return false;
    bucket.push_back(HashEntry(k, v));
    return true;
}

bool HashMap::remove(int k) {
    std::vector<HashEntry>& bucket = getBucket(k);
    if (!(keyExists(k))) return false;
    for (auto itr = bucket.begin(); itr != bucket.end(); ++itr) {
        HashEntry entry = static_cast<HashEntry>(*itr);
        if (entry._k == k) {
            bucket.erase(itr);
            return true;
            break;
        }
    }
    return false;
}

int main() {
    HashMap map;
    for (int i=0; i < 10; ++i) {
        assert(map.put(i, i*10));
    }
    for (int i=0; i < 10; ++i) {
        assert(map.keyExists(i) == true);
    }
    assert(map.keyExists(0) == true);
    assert(map.get(0)._v == 0);
    assert(map.remove(0) == true);
    assert(map.remove(0) == false);
    assert(map.keyExists(0) == false);

    bool exceptionThrown = false;
    try {
        map.get(0);
    } catch (std::exception &e) {
        exceptionThrown = true;
    };
    assert(exceptionThrown);
    return 1;
}