texts:
Recently, I started wrapping Meshes and Transform classes into new ones, but by doing this I came upon a problem: I needed to render all primitives, or meshes with a renderer. After studying a some game engines (especially the JME3 engine), I came up with this node-based rendering. It's really not complete yet, but functional. I would like to ask you to point out any relevant changes I could make.

Entity.h

#pragma once

#include <glm/glm.hpp>
#include <vector>
#include "../render/Transform.h"

class Entity {
public:
    Entity  (
                const glm::vec3& position = glm::vec3(0.0, 0.0, 0.0),
                const glm::vec3& rotation = glm::vec3(0.0, 0.0, 0.0),
                const glm::vec3& scale = glm::vec3(1.0, 1.0, 1.0)
            )
        :
            m_transform(position, rotation, scale)
    {}
    Entity  (
                const Transform& transform
            )
        :
            m_transform(transform)
    {}

    virtual ~Entity(){}

    virtual void Render(const Shader& shader) = 0;
    virtual void Update(){}

    void SetTransform(const Transform& transform) { m_transform = transform; }
    Transform GetTransform() const { return m_transform; }

    void SetPosition(const glm::vec3& position) { m_transform.SetPos(position); }
    void SetRotation(const glm::vec3& rotation) { m_transform.SetRot(rotation); }
    void SetScale(const glm::vec3& scale) { m_transform.SetScale(scale); }
    glm::vec3 GetPosition() const { return m_transform.GetPos(); }
    glm::vec3 GetRotation() const { return m_transform.GetRot(); }
    glm::vec3 GetScale() const { return m_transform.GetScale(); }
protected:
    Transform m_transform;
};

Spatial.h:

#pragma once

#include "Entity.h"
#include "../render/Material.h"

class Spatial : public Entity
{
public:
    Spatial (
                Mesh mesh,
                const glm::vec3& position = glm::vec3(0.0, 0.0, 0.0),
                const glm::vec3& rotation = glm::vec3(0.0, 0.0, 0.0),
                const glm::vec3& scale = glm::vec3(1.0, 1.0, 1.0)

            )
        :
            Entity(position, rotation, scale),
            m_mesh(mesh),
            m_material(CreateTexture("res/images/White.png"))
    {}
    virtual ~Spatial(){}

    virtual void Render(const Shader& shader){
        m_material.Bind(shader);
        m_mesh->Render();
    }
    virtual void Update(){}

    Mesh GetMesh() const { return m_mesh; }
    void SetMesh(const Mesh& mesh) { m_mesh = mesh; }
    Material GetMaterial() const { return m_material; }
    void SetMaterial(const Material& material) { m_material = material; }
protected:
    Mesh m_mesh;
    Material m_material;
};

Node.h:

#pragma once

#include <vector>
#include <iostream>
#include <cassert>
#include "Entity.h"
#include "Spatial.h"

class Node : public Entity{
public:
    Node(){}
    ~Node(){
        m_components.clear();
    }

    void AttachChild(Entity* component){
        assert((Entity*)this != component);
        m_components.push_back(component);
    }
    void DetachAllChildren(){
        m_components.clear();
    }
    void DetachChild(unsigned index){
        m_components.erase(m_components.begin() + index);
    }

    void Render(const Shader& shader){
        for(auto it = std::begin(m_components); it != std::end(m_components); ++it){
            (*it)->Render(shader);
        }
    }

protected:
    std::vector<Entity*> m_components;
};

main.cpp:

int main(int argc, char **args){

    Node rootNode;

    Node node;

    Spatial spatial = Spatial(CreateMesh("res/models/Suzy.obj"));
    Spatial spatial2 = Spatial(CreateMesh("res/models/Suzy.obj"));

    rootNode.AttachChild(&spatial2);
    node.AttachChild(&spatial1);
    rootNode.AttachChild(node);

    ///Some kind of renderer will render here; haven't implemented that yet...
}


texts:
As practise, I implemented a BST and also the remove() method, but I figured I always have to check if the node being deleted is coming from the left child or the right child of its parent, then reset the pointers. I basically check that in all cases in my remove. Is there any way I can avoid this and make the code more readable and easier understandable by others?

removeNode = function (node, key) {

     if (key > node.key) {

         removeNode(node.rightChild, key);

     } else if (key < node.key) {

         removeNode(node.leftChild, key);

     } else { // find the node

         if (node.leftChild.key === null && node.rightChild.key === null) {

             node.parent.leftChild.key = null;

             node.parent.rightChild.key = null;

             return true;

         } else if (node.leftChild.key !== null && node.rightChild.key === null) {

             // to see the current node is the left or right child of the parent, reset the pointer
             if (node.parent.leftChild === node) {

                 node.parent.leftChild  = node.leftChild;

             } else if (node.parent.rightChild === node) {

                 node.parent.rightChild  = node.leftChild;
             }
             node.leftChild.parent = node.parent;

         } else if (node.leftChild.key === null && node.rightChild.key !== null) {

             if (node.parent.leftChild === node) {

                 node.parent.leftChild  = node.rightChild;

             } else if (node.parent.rightChild === node) {

                 node.parent.rightChild  = node.rightChild;
             }
             node.rightChild.parent = node.parent;

         } else {

             var leftMaxNode = predecessorNode(node);

             if (node.parent.leftChild === node) {

                 node.parent.leftChild  = leftMaxNode;

             } else if (node.parent.rightChild === node) {

                 node.parent.rightChild  = leftMaxNode;

             }

             leftMaxNode.rightChild = node.rightChild;
             node.rightChild.parent = leftMaxNode;

         }

         return true;
     }
 },


texts:
I want to control a motor which rotates a device over a gear.

Input values for the device are from 0 to 360 degrees. The motor should always rotate the device the shorter way around. For example, if the position is 30° and target position will be 340°, it should rotate over 0° counter clockwise.

The motor controller internally has so called qc unit system. One turnaround of the the device for example constitutes to 2938500, so there is a translation of values necessary. The internal position (in qc) could become negative or positive values like an integer.

I ended up with that code and some tests to be sure it should work. Did I catch all cases? Can I still simplify the move function?

import unittest

qc360 = 2938500

def qc2deg(qc):
    return (qc / float(qc360)) * 360.0

def deg2qc(deg):
    return int(round((deg/360.0) * qc360 ))

def move(is_qc, target_deg):
    is_deg = qc2deg(is_qc)
    diff = is_deg - target_deg

    if abs(diff) <= 180.0:
        if diff < 0:
            target_qc = is_qc + deg2qc(abs(diff))
        else:
            target_qc = is_qc + deg2qc(-diff)
    else:
        if diff < 0:
            target_qc = is_qc + deg2qc(abs(diff)-360)
        else:
            target_qc = is_qc + deg2qc(360-diff)

    return target_qc

class TestMovement(unittest.TestCase):

    def test_1qc2deg(self):
        self.assertEqual(qc2deg(qc360/2), 180)
        self.assertEqual(qc2deg(qc360+qc360/2), 360+180)
        self.assertEqual(qc2deg(-qc360/2), -180)
        self.assertEqual(qc2deg(-qc360-qc360/2), -360-180)

    def test_2deg2qc(self):
        self.assertEqual(deg2qc(180), qc360/2)
        self.assertEqual(deg2qc(360+180), qc360+qc360/2)
        self.assertEqual(deg2qc(-180), -qc360/2)
        self.assertEqual(deg2qc(-360-180), -qc360-qc360/2)

    def test_3simpleMovePositive(self):
        # Move within 180 degrees, without zero crossing
        self.assertEqual(move(0, 170), deg2qc(170))
        self.assertEqual(move(20, 90), deg2qc(90))

    def test_4simpleMoveNegative(self):
        self.assertEqual(move(20, 5), deg2qc(5))
        self.assertEqual(move(210, 170), deg2qc(170))

    def test_5wideMovePositive(self):
        # positive direction
        self.assertEqual(move(0, 190), deg2qc(-170))
        self.assertEqual(move(deg2qc(60), 350), deg2qc(-10))

    def test_6wideMoveNegative(self):
        # negative direction
        self.assertEqual(move(deg2qc(190), 0), deg2qc(360))
        self.assertEqual(move(deg2qc(350), 60), deg2qc(360+60))

    def test_7variousMoves(self):
        self.assertEqual(move(deg2qc(260), 50), deg2qc(360+50))
        self.assertEqual(move(deg2qc(260), 60), deg2qc(360+60))
        self.assertEqual(move(deg2qc(260), 70), deg2qc(360+70))
        self.assertEqual(move(deg2qc(260), 80), deg2qc(80))
        self.assertEqual(move(deg2qc(260), 90), deg2qc(90))
        self.assertEqual(move(deg2qc(260), 80), deg2qc(80))
        self.assertEqual(move(deg2qc(260), 120), deg2qc(120))

if __name__ == '__main__':
    unittest.main()


texts: Attaching a click handler in a cross-browser way

texts:
I have been attempting to have a method call, with a parameter, inside of a ternary operator to simplify some code.

Code:

 if (window.addEventListener) {
     btnArray[index].addEventListener('click', function() {
        doMassClick( btnArray[index], nameArray[index]);
     });
 } else {
     btnArray[index].attachEvent('onclick', function() {
        doMassClick( btnArray[index], nameArray[index]);
     });
 }

I was able to simplify this down to:

btnArray[index][ window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? 'click' : 'onclick', function() {
    doMassClick( btnArray[index], nameArray[index]);
});

I'd love to know how this can be simplified/cleaned up more..


texts: Template matching program to find an image within an image

texts:
The program I've made is a template matching program which finds an image within an image - where's Wally/Waldo! I've complete the program and all works fine despite being very slow (around a minute). I would appreciate some advice on how I could improve the following code. I'm happy to share the rest of the source code if anyone is interested.

        #include "Matrix.h"

    Matrix::Matrix(int sizeR, int sizeC, double val){
    M = sizeR; // Set number of rows.
    N = sizeC; // Set number of cols.
    data = new double[sizeR * sizeC];
    }

    Matrix::Matrix(int sizeR, int sizeC, double* inputData){
    M = sizeR;
    N = sizeC;

    data = new double[sizeR * sizeC]; // Set data sixe
    for (int i = 0; i < sizeR * sizeC; i++) //  input data store
    {
        data[i] = inputData[i];
    }
    }

    Matrix::~Matrix(){
    delete[] data;
    data = 0;
    }

    Matrix::Matrix(const Matrix& existingMatrix){
    M = existingMatrix.M;
    N = existingMatrix.N;

    data = new double[M * N]; // Allocate memory
    for (int i = 0; i < M * N; i++)
    {
        data[i] = existingMatrix.data[i];
    }
    }

         Matrix Matrix::getBlock(int width, int height, int r, int c, int yMove,     int xMove) const{
    int startCol = r * width;
    int startRow = c * height;
    int cols = width;
    int rows = height;
    Matrix R(rows, cols, 0.0);

    for (int i = 0; i < rows; i++) {

        for (int ii = 0; ii < cols; ii++) {

            R.setElmt(i, ii, getElmt(i + startRow + yMove, ii + startCol + xMove));
        }
        }return R;
     }

    void Matrix::setBlock(int r, int c, int yMove, int xMove, const Matrix& blockValues){
    int rows = blockValues.M;
    int cols = blockValues.N;
    int startCol = c * blockValues.N;
    int startRow = r * blockValues.M;

    for (int i = 0; i < rows; i++) // Rows
    {
        for (int ii = 0; ii < cols; ii++) //Cols
        {
            this->setElmt(i + startRow + yMove, ii + startCol +     xMove, blockValues.getElmt(i, ii));
        }
    }
}

double Matrix::getElmt(int i, int j) const{
    return data[i * N + j];
}

void Matrix::setElmt(int i, int j, double val)
{
    data[i * N + j] = val;
}

int Matrix::getCol() const{
    return N;
}

int Matrix::getRow() const{
    return M;
}

Matrix Matrix::operator-(double value){
    double val = 0;
    Matrix C(M, N, val);

    for (int i = 0; i < M; i++) // Rows
    {
        for (int j = 0; j < N; j++) // Cols
        {
            val = data[i * N + j] - value;
            C.setElmt(i, j, val);
        }
    }return C;
}

Matrix Matrix::operator*(const Matrix& B){
    double val = 0;
    Matrix C(M, N, val);

    for (int i = 0; i < M; i++) // Rows
    {
        for (int j = 0; j < N; j++) // Cols
        {
            val = data[i * N + j] * B.getElmt(i, j);
            C.setElmt(i, j, val);
        }
    }
    return C;
}

Matrix& Matrix::operator=(const Matrix& B){
    if (this == &B) {
        return *this;
    }
    else {
        delete[] data;

        M = B.getRow();
        N = B.getCol();
        data = new double[M * N];

        for (int i = 0; i < M; i++) // Rows
        {
            for (int j = 0; j < N; j++) // Cols
            {
                setElmt(i, j, B.getElmt(i, j));
            }
        }
    }
}

double Matrix::getSum() const{
    double result = 0.0;

    for (int i = 0; i < M * N; i++) {
        result += data[i];
    }
    return result;
}


texts: Create another Singleton object from a Singleton class

texts:
I want to create a singleton object of a third party caching library (ThirdPartyKVStore). But I don't want to reference this class all over the place from where I want to access the cache. To address this, I created a wrapper CacheManager which is managing the lifecycle of ThirdPartyKVStore. Does it look ok?

public class CacheManager {

     private static ThirdPartyKVStore thirdPartyCache = null;
     private static volatile CacheManager cacheManager = null;

     private CacheManager(){

     }

     public static CacheManager getConnection(CacheConfig cacheConfig) {
       if (cacheManager == null) {
         synchronized (CacheManager.class) {
           if (cacheManager == null) {
            try {
              thirdPartyCache = new ThirdPartyKVStore(cacheConfig);
              cacheManager = new CacheManager();
           } catch (Throwable e) {
            logger.error("Fn=getConnection Msg=Cache_Initialization_Error_Occurred.", e);
          }
        }
      }
     }
    return cacheManager;
    }

    public static void closeCacheConnection(){
      if(thirdPartyCache != null){
          thirdPartyCache.shutdown();
        }
    }

    public <T> T getCacheData(String key){
      T cachedObject = null;
      String cachedStr = null;

      Entry<String> e = thirdPartyCache.get(key);
      if(e != null){
        cachedStr = e.getPayload();
       }
      if (cachedStr != null) {
             TypeToken<T> typeToken = new TypeToken<T>() {};
             cachedObject = deserializeStr2POJO(cachedStr, typeToken);
     }
    return cachedObject;
    }

    public <T> void setCacheData(String key, T t){
        if (thirdPartyCache != null) {
              try {
                  Entry<String> e = new Entry.Builder<String>(new Gson()
                          .toJson(t))
                          .withVersion(DEFAULT_VERSION)
                          .withApplication(DEFAULT_APP)
                          .build();

                  thirdPartyCache.set(key, e, Integer.MAX_VALUE);
                } catch (Exception e) {
              }
          }
     }
}


texts:
This code is a revised version of implementation which asked for a advice. Original question is here: Encode message by alphabets
#include <stdio.h>
#include <stdlib.h>
#define MIN_ALPH 1
#define MAX_ALPH 26

unsigned int my_decode(unsigned int input)
{
    unsigned int count = 0;
    unsigned int ddigit;
    int i;

    //check double digit decoding
    //TODO: make macro for (num >= MIN_ALPH && num <= MAX_ALPH)
    if (input % 100 >= MIN_ALPH && input % 100 <= MAX_ALPH)
        count++;

    if (input / 10 >= MIN_ALPH && input / 10 <= MAX_ALPH)
    {
        if (input % 10 > 0)
            count++;
    }

    //check single digit decoding
    for (i=1; i <= 100; i*=10)
    {
        if (input % (i *10) / i == 0)
        break;
    }
    if (i == 1000)
        count++;

    return count;
}

int main(void)
{
    /*Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
    count the number of ways it can be decoded.
    For example, the message '111' would give 3,
    since it could be decoded as 'aaa', 'ka', and 'ak'.
    You can assume that the messages are decodable.
    For example, '001' is not allowed.*/

    printf("result: %u\n", my_decode(512));
    printf("result: %u\n", my_decode(542));
    printf("result: %u\n", my_decode(112));

}


texts:
I coded a script to print a 10-day forecast for any location to my terminal.

As I am just learning Python (coming from the PHP world - yes, I know...) and have no buddies coding in Python, I would really appreciate it if anyone could review my code and provide comments and suggestions for improving it.

For starters, I know I am missing docstrings but I left that part for later as I am still reading about it.

Not sure if I need to mention it, but lookup_by_location() and _call() are overriding methods from Weather ancestor class.

Code is also available in a git repo.

#! /usr/bin/env python
import argparse
import requests
from weather import Weather
from weather import models

class WeatherReport(Weather):
    def __init__(self, location):
        Weather.__init__(self)
        self.get_report(location)

    def get_report(self, location):
        self.show_location(location)
        [self.show_weather(day) for day in self.get_days(self.lookup_by_location(location))]

    def lookup_by_location(self, location):
        url = "%s?q=select* from weather.forecast " \
              "where woeid in (select woeid from geo.places(1) where text='%s') and u='c' &format=json" % (self.URL, location)
        results = self._call(url)
        return results

    def get_days(self, place):
        days = []
        [self.get_day(days, item['date'], item['low'], item['high'], item['text']) for item in place.forecast()]
        return days

    def get_day(self, days, date, low, high, text):
        days.append([date, int(low), int(high), text])

    def show_weather(self, day):
        from_to = "%d-%d" % (day[1], day[2])
        print " "*2 + "%s:" % (day[0]), from_to.rjust(5) + u'\u00b0' + "C -", "%s" % (day[3])

    def show_location(self, location):
        print "-" * 50
        feedback = "10-day forecast for " + location.capitalize()
        print feedback.center(50)
        print "-" * 50

    def _call(self, url):
        results = requests.get(url).json()
        if int(results['query']['count']) > 0:
            wo = models.weather_obj.WeatherObject(results['query']['results']['channel'])
            return wo
        else:
            print 'No results found.'
            quit()

if __name__ == "__main__":
    parser = argparse.ArgumentParser('tdwreport')
    parser.add_argument('-l', '--location', default="sarajevo", help='get forecast for this location')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.2')
    args = parser.parse_args()
    report = WeatherReport(args.location)


texts: Selecting filter checkboxes using Selenium

texts:
I am using Selenium Webdriver via Java. My method clicks on a filter check box (eg. make, model, etc.), that is passed in, from a modal.

When running my method in my test class, via ChromeDriver, it seems to go pretty slow and rightfully so since I am making a lot of tiny network calls for getText(). How can I optimize its performance?

public void selectFilter(String filter) {
        List<WebElement> filters = driver.findElements(selector.someWebElement());
        Map<String, WebElement> mapFilters = new HashMap();
        for (int i = 0; i < filters.size(); i++) {
            String key = filters.get(i).getText();
            WebElement value = filters.get(i).findElement(By.cssSelector("a"));
            mapFilters.put(key, value);
        }
        mapFilters.get(filter).click();
    }


texts: Closure handling in javascript / jquery ajax

texts:
I'm using this pattern (for want of a better word) repeatedly in my code to call a REST API in my javascript code. Some particulars of the code below.

I have a ConfigViewer javascript class that is responsible for creating, populating and handling events for DOM element.
This class constructor inits the DOM components, and then calls an REST API to get the data to populate these DOM components.
I need to handle the response to this API from my instance of ConfigViewer

My question is related to the way I have the getAdminDataSuccessHandler() method to return a function that is called when the REST API succeeds:  Is this the cleanest way to handle the response of the API call ?

function ConfigViewer() {
  this.createUIComponents();
  this.ajaxLoadData("/adminData", this.getAdminDataSuccessHandler());
}
ConfigViewer.prototype.getAdminDataSuccessHandler = function() {
  var self = this;
  return function(data) {
     // Handle successful data retrieval
     self.populateUICoponents(data);
  }
}
/**
 * Execute the API in ajaxy fashion.
 */
ConfigViewer.prototype.ajaxLoadData = function(url, onSuccessHandler) {
    $.ajax({
       url : url,
       success : function(jsonData, textStatus, XMLHttpRequest) {
           onSuccessHandler(jsonData);
       }
    });
}


texts: C++ String Non-Member Operator Overloading

texts:
This is a practice for operator overloading, I am well aware that some of these don't make sense. I am seeking review only on the code/practices, not the purpose.

/* (C) 2017 ZACH HILMAN
 * PROPRIETARY/CONFIDENTIAL. ALL RIGHTS RESERVED
 *
 *
 *
 *
 *
 */
#ifndef COMPUTERSCIENCE_ENHANCED_STRING_H
#define COMPUTERSCIENCE_ENHANCED_STRING_H

#include <string>

/// Remove the first occrance of rhs from lhs.
inline std::string operator-(const std::string& lhs, const std::string& rhs) {
    auto loc = lhs.find(rhs);
    if (loc != -1) return lhs.substr(0, loc) + lhs.substr(loc + rhs.size());
    return std::string();
}

inline std::string& operator-=(std::string& lhs, const std::string& rhs) {
    return lhs = operator-(lhs, rhs);
}

/// Repeat lhs rhs times.
inline std::string operator*(const std::string& lhs, unsigned long rhs) {
    std::string out;
    while (rhs --> 0) out += lhs;
    return out;
}

inline std::string& operator*=(std::string& lhs, unsigned long rhs) {
    return lhs = operator*(lhs, rhs);
}

/// Find the number of times rhs appears in lhs.
inline unsigned long operator/(const std::string& lhs, const std::string& rhs) {
    if (rhs == "") return static_cast<unsigned long>(-1);
    unsigned long out = 0;
    for (unsigned long s_loc = 0, a; s_loc < lhs.size();) {
        if ((a = lhs.find(rhs, s_loc)) != -1) ++out, s_loc = a + 1;
        else break;
    }
    return out;
}

/// Remove all occurances of rhs from lhs.
inline std::string operator%(const std::string& lhs, const std::string& rhs) {
    if (rhs == "") return lhs;
    auto out = lhs;
    std::string::size_type pos;
    while ((pos = out.find(rhs)) != std::string::npos) out = out.replace(pos, rhs.size(), "");
    return out;
}

inline std::string& operator%=(std::string& lhs, const std::string& rhs) {
    return lhs = operator%(lhs, rhs);
}

// Subtract str from STRING_CHARSET (Not done-- will eventually be all ASCII characters).
inline std::string operator~(const std::string& str) {
    static const std::string STRING_CHARSET = "";
    return operator-(STRING_CHARSET, str);
}

// Find the intersection of characters of lhs and rhs.
inline std::string operator&(const std::string& lhs, const std::string& rhs) {
    std::string out;
    for (auto c : lhs) if (rhs.find(c) != std::string::npos) out += c;
    return out;
}

inline std::string& operator&=(std::string& lhs, const std::string& rhs) {
    return lhs = operator&(lhs, rhs);
}

/// Find the union of characters of lhs and rhs.
inline std::string operator|(const std::string& lhs, const std::string& rhs) {
    std::string out;
    for (auto c : lhs) if (out.find(c) == std::string::npos) out += c;
    for (auto r : rhs) if (out.find(r) == std::string::npos) out += r;
    return out;
}

inline std::string& operator|=(std::string& lhs, const std::string& rhs) {
    return lhs = operator|(lhs, rhs);
}

/// Find the XOR of characters of lhs and rhs.
inline std::string operator^(const std::string& lhs, const std::string& rhs) {
    std::string out;
    for (auto c : lhs) if (rhs.find(c) == std::string::npos) out += c;
    for (auto r : rhs) if (lhs.find(r) == std::string::npos) out += r;
    return out;
}

inline std::string& operator^=(std::string& lhs, const std::string& rhs) {
    return lhs = operator^(lhs, rhs);
}

/// Add rhs spaces to the front of lhs.
inline std::string operator>>(const std::string& lhs, unsigned long rhs) {
    return std::string(rhs, ' ') + lhs;
}

inline std::string& operator>>=(std::string& lhs, unsigned long rhs) {
    return lhs = operator>>(lhs, rhs);
}

/// Add rhs spaces to the end of lhs.
inline std::string operator<<(const std::string& lhs, unsigned long rhs) {
    return lhs + std::string(rhs, ' ');
}

inline std::string& operator<<=(std::string& lhs, unsigned long rhs) {
    return lhs = operator<<(lhs, rhs);
}

#endif //COMPUTERSCIENCE_ENHANCED_STRING_H


texts:
Example of my method where I am chaining linq expressions based on model values provided:

public async Task<List<HistoryWorkoutExerciseModel>> GetHistoryWorkoutExerciseByFilterAsync(ChartFilterModel model)
{
    Expression<Func<HistoryWorkoutExercise, bool>> baseFilter = x => true && x.CreatedBy == model.CreatedBy;
    Expression<Func<HistoryWorkoutExercise, bool>> exerciseFilter = x => x.ExerciseId == model.ExerciseFilter;
    Expression<Func<HistoryWorkoutExercise, bool>> timeSpanFilter = x => x.HistoryWorkout.TimeTakenDate >= model.StartDate && x.HistoryWorkout.TimeTakenDate <= model.EndDate;

    if (model.ExerciseFilter > 0 && model.DateFilter == 0)
    {
        baseFilter = baseFilter.AndAlso(exerciseFilter);
    }

    if (model.ExerciseFilter == 0 && model.DateFilter > 0)
    {
        baseFilter = baseFilter.AndAlso(timeSpanFilter);
    }

    if(model.ExerciseFilter > 0 && model.DateFilter > 0)
    {
        baseFilter = baseFilter.AndAlso(timeSpanFilter).AndAlso(exerciseFilter);
    }

    return _mapper.Map<List<HistoryWorkoutExerciseModel>>(await _repository.GetAsync(baseFilter, x => x.OrderByDescending(y => y.HistoryWorkout.TimeTakenDate), "Exercise,HistoryWorkout"));
}

What's the best way to refactor this, as I am not the best fan of if conditional statements? Is there any other specific approach for this?


texts: Picking a pattern based on employee type or department

texts:
I have an if else statement like this deciding the pattern to be followed based on type or department of employee.

The if else block goes like this. I am planning to simplify the if else block to a better format.

 public static Pattern decidePattern(Employee employee) {
        try {
            if ("individual".equalsIgnoreCase(employee.getType()) {
                return new IndivualPattern();
            } else if ("multiple".equalsIgnoreCase(employee.getType()) {
                return new MultiplePattern();
            } else if ("combined".equalsIgnoreCase(employee.getType()) {
                return new CombinedPattern();
            }else if ("financial".equalsIgnoreCase(employee.getDepartment()) {
                return new FinancialPattern();
            } else if ("hr".equalsIgnoreCase(employee.getDepartment()) {
                return new HrPattern();
            } else if ("facilities".equalsIgnoreCase(employee.getDepartment()) {
                return new FacilitiesPattern();
            } else {
                return new DefaultPattern();
            }
        } catch (Exception e) {
            return new DefaultPattern();
        }
    }

All patterns are inherited from common interface. Can I break this into a simpler one?


texts: Use a data frame of functions to calculate values using specific columns in another data frame

texts:
Background

This routine is used in a package that calculates tree (as in Christmas tree) volumes for various species codes (spcd) and geographic regions. The equation forms and coefficients vary by species and region, so I have a dataframe of functions along with their respective species and region that calculate the volume based off of the height (ht) of the tree and diameter (dbh).

Data Setup

Note: In my package, this part is taken care of by other functions, this is just to create a reproducible example (please ignore the sloppyness)

I have a data frame that includes a column of functions, along with some information about "where" to apply those functions in another data frame.

The functions (in reality these are more complex):

func1 <- function(dbh,ht){dbh^2 + ht}
func2 <- function(dbh,ht){dbh^2 - ht}

The data frame (in reality this data frame is much longer):

spcd <- c(122, 122, 141, 141)
region <- c('OR_W', 'OR_E', 'OR_W', 'OR_E')

funcs_df <- data.frame(spcd, region, funcs)
funcs_df$funcs <- c("func1", "func2", "func1", "func2")

Then, I have another frame that has some information, including the spcd and region that should match the values in func_df:

spcd <- c(122, 141, 141, 122, 141, 122)
region <- c('OR_W', 'OR_E', 'OR_W', 'OR_E', 'OR_W', 'OR_W')
dbh <- c(12, 13, 15, 11, 10, 21)
ht <- c(101, 121, 100, 99, 88, 76)

tree_df <- data.frame(spcd, region, dbh, ht)

Applying the Functions

This is the part I would prefer feedback on.

First, I split the tree_df into distinct groups based on spcd and region so I can apply the functions that correspond to these distinct groups.

tree_split <- split(tree_df, list(tree_df$region, tree_df$spcd))

Then, I create an empty data frame to append to.

new_tree <- data.frame()

Next, (and this is where things get messy) I loop through each group, grab the top left cell that acts as a "key" to get the equation from the func_df and use mapply on each group (with some conditionals to handle NA values).

for (group in tree_split) {
    # Get the 'group key'
    region <- group$region[1]
    spcd <- group$spcd[1]

    # Get the equation from eqs
    eq <- funcs_df$funcs[which((funcs_df$spcd == spcd & funcs_df$region ==
          region))]

    # Convert func string into actual function
    eq <- eq[[1]]
    eq <- eval(parse(text=eq))

    # Apply the equation to each record in the group
    group$cvts <- mapply(eq, group$dbh, group$ht)

    # Append to new_tree
    new_tree <- rbind(new_tree ,group)
}

Discussion

This results in the desired output with the new cvts outputs according to each function defined in the dataframe:

  spcd region dbh  ht cvts
4  122   OR_E  11  99   22
1  122   OR_W  12 101  245
6  122   OR_W  21  76  517
2  141   OR_E  13 121   48
3  141   OR_W  15 100  325
5  141   OR_W  10  88  188

I have a few concerns with this approach:

The old adage "if you write a for-loop you are doing it wrong" seems to apply here. Is there some way I could reduce this for-loop to some sort of apply or mapply type function?
Grabbing the key from a cell (see "# Get the 'group key'" comment above) seems sloppy. Is there a way to get this 'group key' in a more formal fashion?

Other advice is, of course, welcome.


texts:
My aim to implement adjacency list correctly. After takin help from here, I have implemented it. I have tried to implement it here, but it was suggested that it is most likely adjacency matrix. Help me to improve my code. Should I add any other function for DFS.

#include <iostream>
#include <vector>

class Graph
{
   int vertex_count;
   enum Color {WHITE, GRAY, BLACK};

   struct Vertex
   {
      int id;
      Color color;
      Vertex(int _id) : id(_id),
                        color(Color::WHITE)
                        {}
   };

   struct Adj_list_node
   {
      int dest_id;
      Adj_list_node * next;
      Adj_list_node(int _dest_id) : dest_id(_dest_id),
                                    next (nullptr)
                                    {}
   };

   struct Adj_list
   {
      Adj_list_node *head;
   };
   std::vector<Vertex> vertices;
   std::vector<Adj_list> adjacent;
public:
   Graph(int);
   void add_edge(int, int);
   void depth_first_search();

private:
   void depth_first_search_visit(int);
};

Graph::Graph(int v)
{
   vertex_count = v;
   adjacent.resize(vertex_count);

   for (int i = 0; i < vertex_count; i++)
   {
       vertices.push_back( Vertex(i) );
       adjacent[i].head = nullptr;
   }
}

void Graph::depth_first_search()
{
   for (const auto& u: vertices)
   {
      if (vertices[u.id].color == WHITE)
      {
         depth_first_search_visit(u.id);
      }
   }
}

void Graph::depth_first_search_visit(int u)
{
   vertices[u].color = GRAY;
   std::cout << vertices[u].id <<" ";
   const auto& v = adjacent[u].head;
      if (vertices[v->dest_id].color == WHITE)
      {
         depth_first_search_visit(v->dest_id);
      }
   vertices[u].color = BLACK;
}

void Graph::add_edge(int src, int dest)
{
   Adj_list_node *node = new Adj_list_node(dest);
   if (adjacent[src].head == nullptr)
   {
      adjacent[src].head = node;
   }
   else
   {
      Adj_list_node *tmp = adjacent[src].head;
      while (tmp->next != nullptr)
             tmp = tmp->next;

      tmp->next = node;
   }

   //undirected graph
   node = new Adj_list_node(src);
   if (adjacent[dest].head == nullptr)
   {
      adjacent[dest].head = node;
   }
   else
   {
     Adj_list_node *tmp = adjacent[dest].head;
     while (tmp->next != nullptr)
            tmp = tmp->next;

     tmp->next = node;
   }
}

int main()
{
   Graph grp(4);
   grp.add_edge(0, 1);
   grp.add_edge(1, 2);
   grp.add_edge(2, 3);
   grp.add_edge(2, 1);
   grp.add_edge(0, 3);
   grp.depth_first_search();
   std::cout << "\n";
}


texts: Showing an image based on the battery level

texts:
I'm working on a battery indicator feature in my app, and I was wondering if there is a better way than what I am doing to check what image should be displayed when.  I am currently using if statements, but I was wondering if case statements would be a better option.

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UIDevice *device = [UIDevice currentDevice];

    //Observer for the battery level
    //Updates the percentage label and the battery icon
    if (KEY_PATH_IF_THEN(@"batteryLevel")) {
        LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];

        //shows battery image
        if (kBatteryLevelBetween(100, 100)) {
            batteryImage.image = [UIImage imageNamed:@"battery100fullycharged.png"];

        } else if (kBatteryLevelBetween(99, 81)) {
            batteryImage.image = [UIImage imageNamed:@"battery90.png"];

        } else if (kBatteryLevelBetween(80, 65)) {
            batteryImage.image = [UIImage imageNamed:@"battery75.png"];

        } else if (kBatteryLevelBetween(64, 41)) {
            batteryImage.image = [UIImage imageNamed:@"battery50.png"];

        } else if (kBatteryLevelBetween(40, 35)) {
            batteryImage.image = [UIImage imageNamed:@"battery30.png"];

        } else if (kBatteryLevelBetween(34, 15)) {
            batteryImage.image = [UIImage imageNamed:@"battery20.png"];

        } else if (kBatteryLevelBetween(14, 0)) {
            batteryImage.image = [UIImage imageNamed:@"battery10.png"];

        }
    }
}

kBatteryLevelBetween:

#define kBatteryLevelBetween(higherNum,lowerNum)    (device.batteryLevel *100 <= higherNum && device.batteryLevel *100 >= lowerNum)


texts:
I created floating input labels, however, I don't think the way I wrote the code is the best way and seems redundant. For example I'm targeting the same elements more than once in different functions and using 3 different timelines, two of which are the reverse of the other. Can anyone suggest a better way of writing this so it's more modular?

// INPUT CONTAINER
const container = $(".form-group");

// CLICK EVENT
container.on("focusin", function() {

  // TARGET ELEMENTS
  const label = $(this).find(".control-label");
  const input = $(this).find(".form-control");

  // TIMELINE INIT
  this.tl = new TimelineMax();

  // TWEEN
  this.tl.to(label, 0.25, {y: -20, fontSize: 12, ease: Power2.easeNone});

});

// FOCUSOUT EVENT
container.on("focusout", function() {

  // TIMELINE INIT
  this.tl = new TimelineMax();

  // TARGET ELEMENTS
  const input = $(this).find(".form-control");
  const label = $(this).find(".control-label");

  // VALUE CHECK
  if (!input.val()) {

    // TWEEN
    this.tl.to(label, 0.25, {y: '-11', fontSize: 16, ease: Power2.easeNone});

  }

});

// CHECK FOR PREFILLED INPUT
(function() {

  $(container).each((index, element) => {

    // console.log(element);

    // TARGET ELEMENTS
    const label = $(element).find(".control-label");
    const input = $(element).find(".form-control");

    console.log(input.val());

    if(input.val() !== "") {

      // TIMELINE INIT
      this.tl = new TimelineMax();

      // TWEEN
      this.tl.set(label, {y: -20, fontSize: 12, ease: Power2.easeNone});

    }

  });

}());


texts:
I've been writing far too many routines in JavaScript that get a record from a an object or array based off a matching property, much like jQuery does with DOM elements. Since all the good names are taken, I called it Hmm.

I went with the philosophy that if I don't need it yet, I wont provide for it.

var Hmm = (function()
{ //A snippet/library to find records in table-like JS arrays

  function getNamedValue( o , name  )
  { //Name can have dots, 'car.tire.brand.name' should get the expected
    var parts = name.split(".");
    while( parts.length && o ){
      o = o[parts.shift()];
    }
    return o;
  }

  function unique( )
  { //Assuming `this` is an array, will copy all unique entries of `this` to a returned new array
    var array = [], map = {}, json;
    this.forEach( function( value ){
      if( value instanceof Object ){
        json = JSON.stringify( value );
        if( !map[json] ){
          array.push( value );
          map[json] = true;
        }
      }
      else if( !~array.indexOf( value ) ){
        array.push( value );
      }
    });
    return array;
  }

  function Hmm( data )
  { //data could be a string -> treat as JSON, parse it
    //data could be an object, or a string that got converted to an object -> convert to array
    //data could be an array ( original or through conversion ) -> leave as is
    this.data = data instanceof Object ? data : JSON.parse( data );
    this.data = this.data instanceof Array ? this.data  : [ this.data  ];
  }

  Hmm.prototype.index = function( name )
  { //Name can have dots, 'car.tire.brand.name' should get the expected
    //Generates an index object
    var index = {} , i;

    this.data.forEach( function( value )
    {
      var key   = getNamedValue( value , name ),
          keys  = key instanceof Array ? key : [key];
      for( i = 0 ; i < keys.length ; i++ )
      {
        key = keys[i];
        index[key] = index[key] || [];
        index[key].push( value );
      }
    });
    return index;
  };

  Hmm.prototype.uniqueIndex = function( name )
  { //Create an index, point each index to the first of possible values
    var index = this.index( name );
    Object.keys( index ).forEach( function(key){
      index[key] = index[key][0];
    });
    return index;
  };

  Hmm.prototype.collect = function( name )
  { //Collect all the values for a given property name
    var values = this.data.map( function ( o ) {
      return getNamedValue( o , name );
    });
    values.unique = unique;
    return values;
  };

  Hmm.prototype.toString = function()
  { //More for jsbin than anything else
    return JSON.stringify( this.data );
  };

  return Hmm;

}());

//Some tests

var foods = [

  { name : 'potatoes' , calories : 100 , allergens : [] , storage : 'ambient' },
  { name : 'pistachio ice cream' , calories : 1000 , allergens : ['nuts','milk'] , storage : 'frozen'  },
  { name : 'chocolate ice cream' , calories : 1200 , allergens : ['milk'] , storage : 'frozen' },
  { name : '2% fat milk' , calories : 600 , allergens : ['milk'] , storage : 'chilled' }
];

var hmm = new Hmm( foods );

console.log( hmm.collect('name') );                 //Collect all names
console.log( hmm.collect('allergens') );            //
console.log( hmm.collect('allergens').unique() );
console.log( hmm.collect('allergens.0') );
console.log( hmm.collect('allergens.0').unique().sort() );
console.log( hmm.index('name') );
console.log( hmm.index('name').potatoes );
console.log( hmm.index('allergens').milk );
console.log( hmm.uniqueIndex('name') );
console.log( hmm.uniqueIndex('name').potatoes );
console.log( hmm.index('allergens') );
console.log( hmm.index('allergens.0') ); //Index on the first allergy


texts:
I wrote a logging class for several of my applications, but I have noticed that it is fairly in-efficient. Can anyone suggest improvements?

What I am looking for:

Pointers on improving efficiency
Tips for lowering the code-footprint
Suggested functional improvements

Please be as nit-picky as possible, I'd like to make this class as robust as possible.

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

class FunctionLogging
{
    private String path;
    private boolean appendToFile = false;

    public FunctionLogging(String file_path, int logLevel, boolean append_value)
    {
        path = file_path;   //used as a placeholder variable for the output path. Can be hard-coded but is preferredly configurable from properties file
        appendToFile = append_value; //Set as true when called in each class used in. true appends line to the end of the file, false overwrites file contents
    }
    public void writeToFile(int logType, String textLine) throws IOException
    {
        FileInputStream propFile = new FileInputStream("config.ini");
        Properties config = new Properties(System.getProperties());
        config.load(propFile);
        String tempLev = config.getProperty("loggingLevel");
        int logLevel = Integer.parseInt(tempLev);
        if(logType<=logLevel)
        {
            //This section is devoted to creating a timestamp of the instance when the output string is created.
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat();
            format = new SimpleDateFormat("dd-MM-yyyy|HH:mm:ss:SSSSSS|");
            String timeStamp = format.format(date);
            SimpleDateFormat app = new SimpleDateFormat();
            app = new SimpleDateFormat("dd-MM-yyyy");
            String dateApp = app.format(date);
            int id = 0;

            String[] messages = new String[4];
            messages[0]="FATAL";
            messages[1]="WARN";
            messages[2]="NOTICE";
            messages[3]="DEBUG";
            FileWriter logWriter = new FileWriter(path+dateApp+".log", appendToFile);
            PrintWriter loggerLines = new PrintWriter(logWriter);

            loggerLines.println(timeStamp+id+++"|"+messages[logType]+"|"+textLine);
            loggerLines.close();
        }
    }
}


texts: Linq to entities query for donor registrations

texts:
I'm using Linq-to-Entities for querying, and MVC.NET and C# for coding. I'm trying to generate monthly donor registry report which needs donor count, donors who signed through web,donors who registered in current month and all this is to be display per county.

private MonthlySummaryViewModel
BuildMonthlySummaryViewModel(MonthlySummarySubModel model){

// Get the bounding datetimes for the previous and lookup month

DateTime curr = new DateTime(model.Year, model.Month, 1),
prev = curr.AddMonths(-1),
next = curr.AddMonths(1);
var monthlySummary = (from county in context.Counties.AsEnumerable()
                      let query = context.DonorStatusActions.Where(x => x.Donor.CountyId == county.CountyId && x.ActionTakenOn >= prev && x.ActionTakenOn < next)

let data = query.GroupBy(x => x.Donor, x => x, (key, grp) => new {Item1 = key, Item2 = grp.OrderByDescending(y => y.ActionTakenOn).FirstOrDefault()})
                                  .Where(x => x.Item2.IsDonor && ((model.WebSignUp != "2" && x.Item2.Donor.WebSignUp == (model.WebSignUp == "1" ? true : false)) || model.WebSignUp == "2"))
                                  let registrations = data.Select(x => x.Item2)
                                  let previous = registrations.Count(x => x.ActionTakenOn >= prev && x.ActionTakenOn < curr)                                                                                let current = registrations.Count(x => x.ActionTakenOn >= curr && x.ActionTakenOn < next)
select Tuple.Create(county.Name, previous, current)).ToList();

 return new MonthlySummaryViewModel()
 {
 Month = new System.Globalization.DateTimeFormatInfo().GetMonthName(model.Month),
Year = model.Year,
WebSignUp=DropDownLists.SignUpMethodList.First(m => m.Value==model.WebSignUp).Text,CountyData = monthlySummary,
TotalPrevious = monthlySummary.Sum(x => x.Item2),
TotalReport = monthlySummary.Sum(x => x.Item3), };}


texts:
I've never participated in a codereview before and I was pointed that I should in another thread for a slow query.

var longReturnListt =await (from i in db.Inventory_Vehicles
                        join l in db.Inventory_Descriptions on new {inv = i.ID, cli = i.ClientID} equals
                        new {inv = l.InventoryID, cli = l.ClientID} into descGroup
                        from m in descGroup.DefaultIfEmpty()
                        join s in db.Settings_Exports on i.ClientID equals s.ClientID into settingGroup
                        from sg in settingGroup.DefaultIfEmpty()
                        join sl in db.Settings_Lots on new {client = sg.ClientID, lot = sg.LotID} equals
                        new {client = sl.ClientID, lot = sl.ID} into lotsGroup
                        from lg in lotsGroup.DefaultIfEmpty()

                  //      join se in db.Settings_ExportSites on new {client = lg.ClientID, lotId = i.LotID, site = siteId } equals new {client = se.ClientID, lotId = se.LotID, site = se.Site} into exportGroup
//from eg in exportGroup.DefaultIfEmpty()
                        join f in db.Inventory_Features on new {inv = i.ID, cli = i.ClientID} equals
                        new {inv = f.InventoryID, cli = f.ClientID} into invFeatGroup
                        from ifg in invFeatGroup.DefaultIfEmpty()
                        join p in db.Inventory_Photos on i.ID equals p.InventoryID into photo
                        from photos in photo.DefaultIfEmpty()
                        where
                        i.ClientID == "999995" && i.Archived != "1" && i.Holding != "1" &&
                        i.Status == "A"
                        orderby i.ID
                                           select new { i, m, sg, photoo = photo.ToList(), lg, ifg } into grouped
                                           group grouped by new { grouped.i.ID, grouped.i.ClientID } into groupedDone

                     //group photos by new {photos.InventoryID} into pg
                      select new NewType
   {
                          InventoryVehicles = (from pho in groupedDone select pho.i).FirstOrDefault(),
                          InventoryDescriptions = (from pho in groupedDone select pho.m).FirstOrDefault(),
                          SettingsExports = (from pho in groupedDone select pho.sg).FirstOrDefault(),
                      //    InventoryPhotos = (from pho in groupedDone select pho.photoo).FirstOrDefault(),
                          SettingsLots = (from pho in groupedDone select pho.lg).FirstOrDefault(),
                          InventoryFeatures = (from pho in groupedDone select pho.ifg).FirstOrDefault(),
                         // SettingsExportSites = (from pho in groupedDone select pho.eg).FirstOrDefault()
                      }).ToListAsync();
                     returnList.AddRange(longReturnListt);
                    return returnList;


texts:
#include <iterator>
#include <memory>
#include <algorithm>

template<typename RandomIt>
void sub_merge(RandomIt begin, RandomIt mid, RandomIt end) {
  // create copy of input array;
  const auto left_size = std::distance(begin, mid);
  const auto right_size = std::distance(mid, end);

  auto left = std::make_unique<typename std::iterator_traits<RandomIt>::value_type[]>(left_size);
  auto right = std::make_unique<typename std::iterator_traits<RandomIt>::value_type[]>(right_size);

  const auto left_begin = left.get();
  const auto left_end = left_begin + left_size;
  const auto right_begin = right.get();
  const auto right_end = right_begin + right_size;

  std::copy(begin, mid, left_begin);
  std::copy(mid, end, right_begin);

  // merge until one array is completed
  auto left_iter = left_begin;
  auto right_iter = right_begin;
  auto arr_iter = begin;

  while (left_iter < left_end && right_iter < right_end) {
    if (*left_iter < *right_iter) {
      *arr_iter = *left_iter;
      left_iter++;
    } else {
      *arr_iter = *right_iter;
      right_iter++;
    }
    arr_iter++;
  }

  // copy remaining array over
  std::copy(right_iter, right_end, arr_iter);
  std::copy(left_iter, left_end, arr_iter);
}

template<typename RandomIt>
void merge_sort(RandomIt begin, RandomIt end) {
  if (begin < end - 1) {
    const auto mid = begin + std::distance(begin, end) / 2;
    merge_sort(begin, mid);
    merge_sort(mid, end);
    sub_merge(begin, mid, end);
  }
}

My testing shows this to be correctly implemented, however I want to know if there is anywhere I could be more efficient. I also have no way to prove if my templates are used correctly. I also do not know which Iterator type is appropriate for this. STL uses RandomIterator so I went with that but I think InputIterator or possibly ForwardIterator would be suitable.


texts: Find position of a word in a list in Python

texts:
The aim of this program is to say which position a word is in a list. This  is just a basic version of it. I made to see if I could shorten it more than what it is currently.

position, word, word_list = 0, 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'
word_list = word_list.split(" ")
print(word_list)
if word in word_list:
    for name in word_list:
        position = position + 1
        if word == name:
            print('your word is in the list at ',position)
else:
    print('Your word is not in the sentence')


texts:
I am new to JavaScript development, so I'm seeking help in guidelines on how I can better organize my code in a better way. This is what I have for a small app I am working on:

var app = app || {};

app.p = function(){ ... };
app.q = function(){ ... };
app.r = function(){ ... };

app.init = function(){ ... };
app.onload = function(){
    if (window.applicationCache) {
        window.applicationCache.addEventListener('updateready', function() {
            // do stuff
        });
    }
};

window.addEventListener('load', app.onload);
window.addEventListener('online',app.p);

Zepto(function($){
    app.init();
    app.p();

    $('#aaaa').change(function(){
        app.q();
        app.r();
    });

});

Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?
I am using some native window.addEventListener() calls. Is it ok to keep native code, even when you have a library loaded on the page, just for the performance gain? Or does it depend on the size of codebase?  Is it ok for small enough and probably moving in a large one?
How the whole execution begins, like Zepto kickstarts init() function on document ready event and then I take it from there, is this how I should be doing it or is there a better way?

Any other suggestions welcome!


texts: Converting imperative style user input menu to functional programming style

texts:
I am currently trying to teach myself scala by rewriting projects from my intro CS class, which was taught in C++. In addition to just learning the syntax I am trying to gain understanding of how functional programming works and what is considered good functional programming style.

Below I've included both the original code, which is a simple while loop that continues looping until the user selects the 'quit' option, and my attempt at a functional equivalent. Have I done this correctly? What could be improved?

Original imperative version in C++:

int main()
{
  int option = -1;

  while (option != 3)
  {
    cout << fixed;
    cout << "Please select one of the following:" << "\n1 - one" <<
      "\n2 - two" << "\n3 - quit" << endl;
    cin >> option;
    if (option == 1)
    {
      cout << "selected 1" << endl;
    }
    else if (option == 2)
    {
      cout << "selected 2" << endl;
    }
    else if (option == 3)
    {
      cout << "selected quit.\n";
    }
    else
    {
      cout << "Sorry, that command is not recognized. ";
    }
  }
  return 0;
}

My attempt at a functional version in scala:

def menu(option: Int) {
  println("""|Please select one of the following:
             |  1 - one
             |  2 - two
             |  3 - quit""".stripMargin)
  if (option == 1) {
    println("selected 1")
    val opt = StdIn.readInt
    menu(opt)
  }
  else if (option == 2) {
    println("selected 2")
    val opt = StdIn.readInt
    menu(opt)
  }
  else if (option == 3) {
    println("selected quit")
  }
  else {
    println("Sorry, that command is not recognized")
  }
}

def main(args: Array[String]) {
  println("""|Please select one of the following:
             |  1 - one
             |  2 - two
             |  3 - quit""".stripMargin)
  val opt = StdIn.readInt
  menu(opt)
}


texts: Determine whether input-output pairs represent something that could be a proper math function

texts:
The input is read in line by line from stdin.

  Input Format

  The first line contains an integer, T, denoting the number of test
  cases. The subsequent lines describe T test cases, and the input for
  each test case is as follows:

  The first line contains an integer, N, the number of (x,y) pairs in
  the test case. The N subsequent lines each contain two space-separated
  integers describing the respective x and y values for each ordered
  pair.

  Constraints

  \$1 \le T \le 5\$
  \$2 \le N \le 100\$
  \$0 \le x, y \le 500\$

  x and y are both integers.

  Output Format

  On a new line for each test case, print  if the set of ordered
  pairs represent a valid function, or  if they do not.

  Sample Input

2
3
1 1
2 2
3 3
4
1 2
2 4
3 6
4 8

  Sample Output

YES
YES

Full problem statement

I'm looking for feedback regarding ways this could be: more concise/clean, more idiomatic Haskell, or if there are algorithmic/mathematical tricks I missed that could further simplify the computation.

import System.IO (readLn, getLine)
import Control.Monad (replicateM, mapM_, liftM)
import Data.List (nub)
import qualified Data.Map.Strict as M

data YesNo = YES | NO deriving Show

boolToYesNo :: Bool -> YesNo
boolToYesNo x = if x then YES else NO

readInt :: IO Int
readInt = readLn

tuplefy :: [a] -> (a, a)
tuplefy xs = case xs of [a, b] -> (a, b)
                        _      -> error "each item must consist of 2 values."

readPair :: [String] -> [(Int, Int)]
readPair = map $ tuplefy . map (read :: String -> Int) . words

getPairs :: Int -> IO [String]
getPairs = flip replicateM getLine

readTestCase :: Int -> IO [(Int, Int)]
readTestCase = fmap readPair . getPairs

readTestCases :: Int -> IO [[(Int, Int)]]
readTestCases = flip replicateM $ readInt >>= readTestCase

printAnswers :: Show a => [a] -> IO ()
printAnswers = mapM_ print

isSingletonSet :: Eq b => [b] -> Bool
isSingletonSet xs = case nub xs of [x] -> True
                                   _   -> False

listToMultiMap :: (Ord k, Eq k, Eq v) => [(k, v)] -> M.Map k [v]
listToMultiMap ((k, v):vs) = toMap (M.fromList [(k, [v])]) vs
    where toMap m xs = case xs of []        -> m
                                  (k0, v0):ys ->
                                      case M.lookup k0 m of Nothing -> toMap (M.insert k0 [v0] m) ys
                                                            Just v0s -> toMap (M.insert k0 (v0:v0s) m) ys

functionOrNot :: [(Int, Int)] -> YesNo
functionOrNot tuples = boolToYesNo $ foldl1 (&&) $ M.elems $ M.map isSingletonSet $ listToMultiMap tuples

main :: IO ()
main = getAnswers >>= printAnswers
    where getAnswers = (liftM . map) functionOrNot $ readInt >>= readTestCases


texts: Mergesort that has `man 3 qsort` ANSI C prototype

texts:
I have taken a look at these review questions: one, two, three and four and would still like to ask you to review my implementation of mergesort that follows the man 3 qsort prototype.

void *malloc_or_exit(size_t size) {
    void *tmp = malloc(size);

    if (tmp == NULL) {

        if (size == 0) {
            return tmp;
        }

        fprintf(
            stderr, "Failed to malloc %zu bytes: %s",
            size, strerror(errno)
        );

        exit(EXIT_FAILURE);
    }

    return tmp;
}

void mergesort0(
    void *xs, size_t n, size_t s,
    int (*cmp) (const void *, const void *)
) {
    if (n == 0 || n == 1) return;

    const size_t nlft = n / 2;
    const size_t nrgt = n - nlft;

    void *ys = (char *)xs + nlft * s;

    mergesort0(xs, nlft, s, cmp);
    mergesort0(ys, nrgt, s, cmp);

    void *const as = malloc_or_exit(n * s);
    void *const bs = (char *)as + nlft * s;
    void *const cs = (char *)as + n * s;

    memcpy(as, xs, n * s);

    void const *i = as;
    void const *j = bs;
    while (i != bs && j != cs) {
        if (cmp(i, j) <= 0) {
            memcpy(xs, i, s);
            i = (char *)i + s;
        } else {
            memcpy(xs, j, s);
            j = (char *)j + s;
        }

        xs = (char *)xs + s;
    }

    for (; i != bs; i = (char *)i + s, xs = (char *)xs + s) {
        memcpy(xs, i, s);
    }

    for (; j != cs; j = (char *)j + s, xs = (char *)xs + s) {
        memcpy(xs, j, s);
    }

    free(as);
}

#include <stdio.h>
int main() {
    int xs[] = {1, 2, 3, 4, 5};
    int ys[] = {5, 4, 3, 2, 1};
    int zs[] = {3, 1, 2, 4, 5};
    int as[] = {1, 1, 1};
    int bs[] = {3, 2, 2};

    int len = 5;

    qsort(zs, len, sizeof(int), compare_int);

    for (int i = 0; i < len; ++i) {
        printf("%d ", *(zs + i));
    } printf("\n");
}


texts:
I need to add class is_active to all div's when I click on
 and remove class if I click again. Only every div have class is_active then main div (
) have class is_active.

Please tell me if this is ok or not. I need as fast of a solution as possible. I'm also not sure using .each() is a very good idea.

I need as fast of a solution as possible. I'm not sure using if .each() is a very good idea.

$("#all-tags").click(function() {
    if ($(this).hasClass("is_active")) {
        $(".tags_cloud div").each(function() {
            $(this).removeClass("is_active");
        });
    } else {
        $(this).addClass("is_active");
        $(".tags_cloud div").each(function() {
            $(this).addClass("is_active");
        });
    }
});

$(".tags_cloud div").click(function() {
    !$(this).is("#all-tags") ? $(this).toggleClass("is_active") : true;
    var c = 0;
    $(".tags_cloud div").each(function() {
        if ($(this).hasClass("is_active") && !$(this).is("#all-tags")) {
            // some my code
        } else if (!$(this).is("#all-tags")) {
            $("#all-tags").removeClass("is_active");
            c = 1;
        }
        c == 0 ? $("#all-tags").addClass("is_active") : true;
    })
});


texts: How is my implementation of an immutable stack?

texts:
Below is my implementation of an immutable stack class.  The reverse function is trying to return a stack with all elements reversed. Is my implementation good? Maybe the reverse function can be faster?

public class ImStack<T> {

    private final T head;
    private final ImStack<T> tail;

    public ImStack ( T head, ImStack<T> tail)
    {
        this.head = head;
        this.tail = tail;
    }

    public ImStack<T> pop()
    {
        return this.tail;
    }
    public ImStack<T> push( T e)
    {
        return new ImStack<T>( e, this);
    }
    public T peek()
    {
        return this.head;
    }
    public boolean isEmpty()
    {
        if ( head == null && tail == null)
            return true;
        else return false;
    }
    public int size()
    {
        if ( isEmpty())
            return 0;
        else return 1 + tail.size();
    }
    public ImStack<T> reverse()
    {
        ImStack<T> resultStack = new ImStack<T> ( null,null);
        ImStack<T> tempStack;
        tempStack = this;
        for ( int i = 0 ; i < this.size(); i++)
        {
            resultStack = resultStack.push(tempStack.peek());
            tempStack = tempStack.pop();
        }
        return resultStack;
    }
}


texts:
I have a simple golang app in which I have two background tasks that produce data,each of them use it's own channel to signal it produced another unit of data.
I have a single consumer that needs the data form the two other background tasks as input in a 1-to-1 ratio. What I want to do,for the lack of a better term, is "Intersecting" the channels. Meaning I want to create a new channel that gets a signal every time there's a signal in one channel and then the other.
it's also worth mentioning I have a context I use to close all background gorotines to gracefully shutdown.
here is the function I wrote to do it:
func intersectChans(a <-chan bool, b <-chan bool) {
    for {
        select {
        case <-a:
            select {
            case <-b:
                c <- true
            case <-ctx.Done():
                return
            }
        case <-ctx.Done():
            return
        }
    }
}

I wonder if there is a more elegant/idiomatic way to achieve this


texts:
For our (internal) automated test project, I am writing a part where parameters can be passed to an SSIS Package before it gets executed. The tester delivers the parameter name, value and desired datatype in a table format. I get the datatype and parses it to the correct type. We assume a happy flow (when testers do something wrong, no pretty feedback is needed, they can read the exceptions).

The following code is the snippet I am not happy with:

foreach (var row in parametersTable.Rows)
{
    object value;
    if (parametersTable.ContainsColumn("DataType") && !String.IsNullOrEmpty(row["DataType"]))
    {
        string dataType = row["DataType"].ToLower();
        if ("int64".Equals(dataType))
        {
            value = Int64.Parse(row["Value"]);
        }
        else if ("datetime".Equals(dataType))
        {
            value = DateTime.Parse(row["Value"]);
        }
        else
        {
            throw new ArgumentException("DataType " + row["DataType"] + " is not supported");
        }
    }
    else
    {
        value = row["Value"];
    }

    pfe.AddParameter(row["Name"], value);
}

I think, my string manipulation and testing can be improved and I'd like to make the "test and parse" section more expandable. Maybe an Enum or an helper object where I just have to add a single value to make it work for additional datatypes.


texts:
Here is the code to a progress bar component. Is there anything that you feel I should improve to it?

If I state that the progress prop is required, is it ok NOT to check in the code that progress is not null?

import React from 'react';
import PropTypes from 'prop-types';

export default function ProgressBar({ progress, progressBarColor }) {
  const percentage = progress > 1 ? 100 : progress * 100;
  const commonStyles = 'rounded-50 h-13 lg:h-9 lgx:h-12 xl:h-13';

  return (
    <div className={`bg-grey-light relative overflow-hidden ${commonStyles}`}>
      <div className={`${progressBarColor} ${commonStyles}`} style={{ width:`${percentage}%` }}>
        &nbsp;

  );
}

ProgressBar.propTypes = {
  progress: PropTypes.number.isRequired,
  progressBarColor: PropTypes.string
};

ProgressBar.defaultProps = {
  progressBarColor: 'bg-gradient-b-turquoise-cyan'
};

I would use this progress bar to display the usage of some resource for example. Once that usage reaches a certain percentage, I would need to change the bar's color to orange for example and make it read if you have reached the limit/the maximum usage of the resource.

render() {
  let progressBarColor = 'bg-gradient-b-turquoise-cyan';
  if (progress >= 1) {
    progressBarColor = 'bg-red';
  } else if (progress >= 0.8) {
    progressBarColor = 'bg-orange';
  }

  return (

      <ProgressBar
        progress={progress}
        progressBarColor={progressBarColor}
      />

  );
}


texts: Convert a String with comma separated latitudes and longitudes to a Seq[Coordinate]

texts:
I have a function that receives a String like the following:

"-10.0 -10.0,10.0 10.0,0.0 0.0"

And needs to translate that into a Seq[Coordinate] that would look like this:

Seq(
    Coordinate(-10.0, -10.0),
    Coordinate( 10.0,  10.0),
    Coordinate(  0.0,   0.0)
)

Here is the function that I wrote to achieve this:

def toCoordinates(coordinates: String): Seq[Coordinate] = {
  val coordinatesList = coordinates.split(",")
  coordinatesList flatMap { coordinate =>
    coordinate.split("\\s+") match {
      case Array(lat:String, lon:String) => Some(Coordinate(lat.toDouble, lon.toDouble))
      case _                             => None
    }
  }
}

I see that if someone sends "foo bar" as a coordinate, my code would fail miserably, although I don't see a way to prevent this without some if conditions.

Any idea on how I can implement this check while still having functional code? Or any other tips that might be helpful for a Scala newbie.


texts: Data structure and movement for tilt maze (part 2)

texts:
This is a design data structure and movement for a tilt maze. For example, this one.

My major idea is learned from abrarisme's smart idea of using two boolean matrix to represent wall. Please refer to this link for abrarisme's smart idea (Data structure and movement for tilt maze).

I need to (1) design the data structure to represent maze and (2) also implement movement function for 4 directions.

Since it is new code and I create this new post. Appreciate for code review advice on point (1) and point (2). Thanks!

An example of right matrix and related maze,

  __ __ __ __
 |__   |__   |           [[true,  false, true,  false]
 |  |  |     |            [false, false, true,  false],
 |  |   __|  |      =>    [false, true,  false, false],
 |     |   __|            [true,  false, true,  false],
 |__|__|__ __|            [false, false, true,  false]]

right = [[True, False, True, False],
         [False, False, True, False],
         [False, True, False, False],
         [True, False, True, False],
         [False, False, True, False]]
top = [[False, False, False, False],
       [False, True, False, True],
       [True, True, True, True],
       [True, True, False, True],
        [True, True, True, False]]

def move_right (start_x, start_y):
    while start_y < len(right)-1 and right[start_x][start_y] == True:
        start_y+=1
    return (start_x, start_y)

def move_left(start_x, start_y):
    while start_y >= 1 and right[start_x][start_y-1] == True:
        start_y -= 1
    return (start_x, start_y)

def move_top(start_x, start_y):
    while start_x > 0 and top[start_x][start_y] == True:
        start_x-=1
    return (start_x, start_y)
def move_down(start_x, start_y):
    while start_x < len(top) - 1 and top[start_x+1][start_y] == True:
        start_x+=1
    return (start_x, start_y)

if __name__ == "__main__":
    (x,y) = move_right(0,0)
    print(x,y) # output, (0, 1)
    (x,y) = move_down(x,y)
    print (x,y) # output, (4, 1)
    (x, y) = move_left(x, y)
    print (x,y) # output, (4, 1)
    (x, y) = move_top(x, y)
    print (x,y) # output, (0, 1)


texts:
Please provide feedback on the correctness of this code.  It should handle older versions of IE but how far back it goes I have not determined yet.

/**************************************************************************************************
EVENTS
*/

    // ... snip

    Priv.functionNull = function () {
        return undefined;
    };

    // createEvent
    Priv.createEvent = function () {
        if (doc.createEvent) {
            return function (type) {
                var event = doc.createEvent("HTMLEvents");
                event.initEvent(type, true, false);
                $A.someKey(this, function (val) {
                    val.dispatchEvent(event);
                });
            };
        }
        if (doc.createEventObject) {
            return function (type) {
                var event = doc.createEventObject();
                event.eventType = type;
                $A.someKey(this, function (val) {
                    val.fireEvent('on' + type, event);
                });
            };
        }
        return Priv.functionNull;
    };

    Priv.proto.createEvent = function (type) {
        return Priv.createEvent.call(this, type);
    };

    Pub.createEvent = (function () {
        return function (element, type) {
            var temp = [];
            temp[0] = element;
            Priv.createEvent.call(temp, type);
        };
    }());

    // addEvent
    Priv.addEvent = (function () {
        if (win.addEventListener) {
            return function (type, callback) {
                $A.someKey(this, function (val) {
                    val.addEventListener(type, callback);
                });
            };
        }
        if (win.attachEvent) {
            return function (type, callback) {
                $A.someKey(this, function (val) {
                    val.attachEvent('on' + type, callback);
                });
            };
        }
        return Priv.functionNull;
    }());

    Priv.proto.addEvent = function (type, callback) {
        return Priv.addEvent.call(this, type, callback);
    };

    Pub.addEvent = (function () {
        return function (element, type, callback) {
            var temp = [];
            temp[0] = element;
            Priv.addEvent.call(temp, type, callback);
        };
    }());

    //remove event
    Priv.proto.removeEvent = (function () {
        if (win.removeEventListener) {
            return function (type, callback) {
                $A.someKey(this, function (val) {
                    val.removeEventListener(type, callback);
                });
            };
        }
        if (win.detachEvent) {
            return function (type, callback) {
                $A.someKey(this, function (val) {
                    val.detachEvent('on' + type, callback);
                });
            };
        }
        return Priv.functionNull;
    }());

    Priv.proto.removeEvent = function (type, callback) {
        return Priv.removeEvent.call(this, type, callback);
    };

    Pub.removeEvent = (function () {
        return function (element, type, callback) {
            var temp = [];
            temp[0] = element;
            Priv.removeEvent.call(temp, type, callback);
        };
    }());


texts:
Is there a way to make this code run faster? I have over 6000 pictures in .jpg optimized to a maximum of 40 kB. It starts quickly but after like 2000 pictures it runs way slower. The final .xlsm file is about 380 MB.

I'm using Excel 2016 with Windows 10 on a big server with 16 processors and 80 GiB RAM.

Sub Button5_Click()
With Excel.Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
.DisplayStatusBar = False
.EnableEvents = False
End With
With Worksheets
DisplayPageBreaks = False
End With
ChargeTrombinoscope
With Excel.Application
.EnableEvents = True
.DisplayStatusBar = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
With Worksheets
DisplayPageBreaks = True
End With
''''CheckImageName
End Sub

Sub ChargeTrombinoscope()
Dim Chemin As String, Fichier As String
Dim nom, nom As String
Dim splitArr() As String
Dim Ligne As Integer
Dim Largeur As Integer
Dim Hauteur As Integer
Dim h As Long, Rapport As Single
Const hDefaut = 97

Worksheets("Pix").Activate

  'Définit le répertoire contenant les fichiers
Chemin = "C:\IMAGES\"

  'Boucle sur tous les fichiers du répertoire (photos).
Ligne = 3
Columns("K:K").ColumnWidth = 40  ' défini la largeur de la colonne
Columns("H:H").ClearContents
Columns("I:I").ClearContents
For Each Sh In ActiveSheet.Shapes
   If Sh.Type = msoPicture Then 'msoPicture Then
      Sh.Delete
   End If
Next Sh

Fichier = Dir(Chemin & "*")
Do While Len(Fichier) > 0
  'Extraction nom
  splitArr = Split(Fichier, ".")
  nom = splitArr(0)
  Range("H" & Ligne).Value = CStr(nom)
  Range("H" & Ligne).NumberFormat = "@"
  Range("I" & Ligne) = "a" & Range("H" & Ligne)     ''' pour corriger le bogue des noms numériques
  'insertion de la photo dans la colonne K
  Range("K" & Ligne).Select
''  Largeur = Range("K" & Ligne).Width
''  Hauteur = Range("K" & Ligne).Height

 ActiveCell.RowHeight = 99  ' ajuste la hauteur de la ligne : 1 point = 0,035 cm

h = hDefaut
h = h - 4

  ActiveSheet.Shapes.AddPicture(Chemin & Fichier, False, True, ActiveCell.Left, ActiveCell.Top, Largeur, Hauteur).Select

With Selection.ShapeRange
    Rapport = h / Selection.Height
    AjusterImage Selection, Rapport
   .Name = Range("I" & Ligne)
End With

  'Fichier suivant
  Fichier = Dir()
  Ligne = Ligne + 1
Loop
  Range("H3").Select

With Worksheets("Pix")
   DerLig = .Range("H" & Rows.Count).End(xlUp).Row
   ActiveWorkbook.Names("PicTable").Delete
   ActiveWorkbook.Names.Add Name:="PicTable", RefersTo:="=Pix!$H$2:$H$" & DerLig
End With

End Sub

Function AjusterImage(Imag As Object, Rapport As Single)
Dim Largeur As Single
Dim Hauteur As Single

Largeur = Imag.Width
Hauteur = Imag.Height
Largeur = Largeur * Rapport
Hauteur = Hauteur * Rapport
Imag.Width = Largeur
Imag.Height = Hauteur
End Function


texts: Testing for divisibility of numbers - follow-up

texts:
(Here is the follow up question)

I had another go at trying to speed up my program described in my previous question.

JS1's answer was particulary helpful and now my code is only about 20% slower than the fastest program in the programming challange (it runs in 0,13 s and my code runs in 0,16 s). I ran the code with different tools to check how often each line was run, etc.

#include <stdio.h>
#define MAX 1000000

int main() {
  int N,n[100];
  int p[10] = {0};
  int mask[MAX] = {0};
  register int i, j, k;

  scanf("%d", &N);
  for(i=0;i<N;i++) scanf("%d", &n[i]);
  i = MAX+1;
  while(--i) {
    int maskBits = 0;
    for(j=0;j<N;j++) {if(i%n[j]==0)maskBits |= (1 << j);}
    if (maskBits == 0)
        continue;
    k=i;
    while (k>0) {p[k%10]++; k/=10;}

    for(j=1;j<10;j++) if(p[j]>0) {k=j; p[j]--; break;}
    for(j=0;j<10;j++) while (p[j]>0) {k=10*k+j; p[j]--;}
    mask[k] |= maskBits;
  }
  for(i=1;i<MAX;i++) if(mask[i]==(1<<N)-1) break;
  fprintf(stdout, "%d\n", i);
}

Again I ran the code through gcov and here is some extensive information about my program.

        -:    0:Source:talfamiljer.c
        -:    0:Graph:talfamiljer.gcno
        -:    0:Data:talfamiljer.gcda
        -:    0:Runs:1
        -:    0:Programs:1
        -:    1:#include <stdio.h>
        -:    2:#define MAX 1000000
        -:    3:
        1:    4:int main() {
        -:    5:  int N,n[100];
        1:    6:  int p[10] = {0};
        1:    7:  int mask[MAX] = {0};
        -:    8:  register int i, j, k;
        -:    9:
        1:   10:  scanf("%d", &N);
        1:   11:  for(i=0;i<N;i++) scanf("%d", &n[i]);
        -:   12:  i = MAX+1;
  1000001:   13:  while(--i) {
        -:   14:    int maskBits = 0;
  7000000:   15:    for(j=0;j<N;j++) {if(i%n[j]==0)maskBits |= (1 << j);}
  1000000:   16:    if (maskBits == 0)
   941611:   17:        continue;
        -:   18:    k=i;
   343849:   19:    while (k>0) {p[k%10]++; k/=10;}
        -:   20:
   116542:   21:    for(j=1;j<10;j++) if(p[j]>0) {k=j; p[j]--; break;}
   285460:   22:    for(j=0;j<10;j++) while (p[j]>0) {k=10*k+j; p[j]--;}
    58389:   23:    mask[k] |= maskBits;
        -:   24:  }
   102246:   25:  for(i=1;i<MAX;i++) if(mask[i]==(1<<N)-1) break;
        1:   26:  fprintf(stdout, "%d\n", i);
        -:   27:}

Something that caught my eye is that the first while loop runs 1000001. However, it should only have to run until it finds the smallest number whose permutations or itself is divisble my all the numbers in the input file.

7
164 278 293 382 483 598 23

I'd be very happy if you can help me beat the fastest program.


texts: Return Function Pointer based upon String

texts:
I have the following function that takes a string and returns a function pointer; currently its a long if-else block; thats continuing to grow this will make it difficult to maintain.

The logic of this function is repeated but the return type has changed.

typedef int (*FP)(char** params, int numberOfParams);
typedef int (*FP1)(int x);

static FP getFunction1(char* name)
{
  if(strcmp(name, "str1") == 0)
  {
      return fun1;
  }
  else if(strcmp(name, "str2") == 0)
  {
      return fun2;
  }
}

static FP1 getFunction2(char* name)
{
  if(strcmp(name, "str1") == 0)
  {
      return fun3;
  }
  else if(strcmp(name, "str2") == 0)
  {
      return fun4;
  }
}

Is there a better way that this could be refactored to remove the duplicate code?


texts: A simple function to rename columns in data frame to standardized names in R

texts:
I wrote this simple function to rename columns in a data frame to standardized names in R. This function is useful when we have a very large data set with large number of columns especially for machine learning applications.

colRename<-function(x){
  for(i in 1:ncol(x)){
    colnames(x)[i] <- paste("column",i,sep="")
  }
  return(x)
}

An example

library(quantmod)

colRename<-function(x){
  for(i in 1:ncol(x)){
    colnames(x)[i] <- paste("column",i,sep="")
  }
  return(x)
}

aapl=getSymbols("AAPL",from="2015-01-01",auto.assign=F)
head(colRename(aapl))

Result

           column1 column2 column3 column4  column5  column6
2015-01-02  111.39  111.44  107.35  109.33 53204600 105.6986
2015-01-05  108.29  108.65  105.41  106.25 64285500 102.7209
2015-01-06  106.54  107.43  104.63  106.26 65797100 102.7306
2015-01-07  107.20  108.20  106.70  107.75 40105900 104.1711
2015-01-08  109.23  112.15  108.70  111.89 59364500 108.1736
2015-01-09  112.67  113.25  110.21  112.01 53699500 108.2896


texts: Minimizing database overhead by storing additional information to the users authentication-object (Spring Security)

texts:
I am using Spring Security in order to check if a logged in user is authenticated. However, after authentication, as some actual requests come in, I would like to minimize the number of database calls as much as possible.

Hence my question: From the SecurityContextHolder I can get my hands on the User object using getPrincipal() of the Authentication object:

@PreAuthorize("isAuthenticated()")
public List<StoreDTO> getAvailableStores() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = (User)auth.getPrincipal();
    String username = user.getUsername();

    List<Store> storeList = this.storeAdminRepository.getStores(username);

    return Convert.toStoreDtoList(restaurantList);
}

Would it be "dirty", instead of setting the simple User object as principal, to use a custom object that e.g. also stores the user id from inside the database?

The way I am doing it now would require me to look up the user id first according to his name and then get the stores where user.id = store.user_id or something like that.

Assume that there are a lot of requests coming and - is this a way to minimize the overhead? Or, and this could also be true, are my concerns unfounded since the overhead is by far not that large like I am assuming here?


texts:
Would like some assistance in improving my jQuery validation code. I have some repeated code, but I am not sure how to write it in a way so that I don't have to keep repeating the same code over and over again for different variable names etc... (such as the if statement part) My goal is to make it so that I can easily apply it to any other form I create.

Here is the jsFiddle

(function($) {

    $('.commentForm').submit(function () {

        var error = 'error';

        var name = $(this).find('.name')
        nameVal = name.attr('value')
        email = $(this).find('.email')
        comment = $(this).find('textarea')
        commentVal = comment.html();

        if (!(name.val() === nameVal || name.val() === '' || name.val().length < 3) &&
            !(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) &&
            validateEmail(email.val())
           ) {
            console.log('Form is good');
            return true;
        } else {

            (name.val() === nameVal || name.val() === '' || name.val().length < 3) ? name.addClass(error) : name.removeClass(error);
            (comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) ? comment.addClass(error) : comment.removeClass(error);
            (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

            console.log('Form is BAD');
            return false;

        }

    });

    function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

}) (jQuery);


texts: Checking unique words and their abbreviations

texts:
In an attempt to solve a problem on Leetcode, I used dictionary and sets to have O(1) time complexity.
However, my speed is too slow, better than just the 5% of Python submissions.
Here is my code:

from typing import List

class ValidWordAbbr:

    def __init__(self, dictionary: List[str]):
        self.dictionary = dictionary
        self.dictionary_abbn = {}
        self.abbn_set = set()
        for key in self.dictionary:
            if len(key) <= 2:
                self.dictionary_abbn[key] = key
                continue
            abbn = '{}{}{}'.format(key[0], len(key)-2, key[-1])
            self.dictionary_abbn[key] = abbn
            self.abbn_set.add(abbn)

    def isUnique(self, word: str) -> bool:
        abbn = word if len(word) <= 2 else '{}{}{}'.format(
            word[0], len(word)-2, word[-1])
        if abbn not in self.abbn_set:
            return True
        for key in self.dictionary_abbn.keys():
            if key != word and self.dictionary_abbn[key] == abbn:
                return False
        return True

How can I improve the runtime?


texts: Recommended improvements on beginner Linked List

texts:
I know this implementation is very bare-bones, but are there any improvements I can make to it? (E.g. more pythonic, style, speed, comments).

I was considering using @property decorators a bit more, but I thought that was overkill for this example.

class Node:
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next

    def __str__(self):
        return "Node Object : val {}".format(self.value)

class LinkedList:
    def __init__(self):
        self.head = None

    @property
    def length(self):
        if self.head is None:
            return 0
        length = 1
        current = self.head
        while current.next is not None:
            current = current.next
            length += 1
        return length

    def append(self, node):
        if self.head is None:
            self.head = node
            return
        current = self.head
        while current.next is not None:
            current = current.next
        current.next = node

    def prepend(self, node):
        if self.head is None:
            self.head = node
            return
        node.next = self.head
        self.head = node

    def get(self, index):
        current = self.head
        for i in range(0, index):
            if current.next is not None:
                current = current.next
            else:
                return None
        return current

    def delete(self, val):
        if self.head.value is val:
            self.head = None
            return
        current = self.head
        while current.next is not None:
            if current.next.value is val:
                current.next = current.next.next
                return
            current = current.next


texts: Call center escalation excercise, using Chain of Responsibility pattern

texts:
This is a coding interview I found online, to be solved within 30 minutes:

  Design an OOP concept for an application where employee can dispatch their incoming phone call according to their seniority level if they are not able to solve.

I chose to use Chain of Responsibility pattern, I also used Null pattern.
Please review OOP principles and the specific design pattern implementation.

The unit test is just a code sample.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DesignPatternsQuestions
{
    [TestClass]
    public class ChainOfResponsibilityTest
    {
        [TestMethod]
        public void PhoneCallDispatchCORTest()
        {
            PhoneCallHandler gilad = new PhoneCallHandler(new LowLevel("Gilad"));
            PhoneCallHandler bonno = new PhoneCallHandler(new LowLevel("Bonno"));
            PhoneCallHandler batel = new PhoneCallHandler(new MediumLevel("Batel"));
            PhoneCallHandler daniel = new PhoneCallHandler(new HighLevel("Daniel"));
            gilad.RegisterNext(batel);
            bonno.RegisterNext(batel);
            batel.RegisterNext(daniel);

            BankPhoneCall call1 = new BankPhoneCall(1500);
            bool res = gilad.GetPhoneCall(call1);
            Assert.IsTrue(res);
        }
    }

    public interface IPhoneCall
    {
        int Budget { get; set; }
    }

    public class BankPhoneCall :IPhoneCall
    {

        public BankPhoneCall(int budget)
        {
            Budget = budget;
        }

        public int Budget { get; set; }
    }

    public interface IPhoneCallHandler
    {
        bool GetPhoneCall(IPhoneCall phoneCall);
        //the same item is able to call next Item in the chain of command
        void RegisterNext(IPhoneCallHandler employee);
    }

    public class PhoneCallHandler : IPhoneCallHandler
    {
        private IPhoneCallHandler _nextCallHandler = EndOfChainHandler.Instance;
        private Employee _employee;

        public PhoneCallHandler(Employee employee)
        {
            _employee = employee;
        }
        public bool GetPhoneCall(IPhoneCall phoneCall)
        {
            bool res = _employee.Resolve(phoneCall);
            if (!res)
            {
                //handle _nextcallHandler == null with null pattern
                return _nextCallHandler.GetPhoneCall(phoneCall);
            }
            return res;
        }

        public void RegisterNext(IPhoneCallHandler nextCallHandler)
        {
            _nextCallHandler = nextCallHandler;
        }
    }

    /// <summary>
    /// null pattern
    /// </summary>
    public sealed class EndOfChainHandler : IPhoneCallHandler
    {
        private static readonly Lazy<EndOfChainHandler> lazy = new Lazy<EndOfChainHandler>(()=> new EndOfChainHandler());
        public static EndOfChainHandler Instance { get { return lazy.Value; } }
        public bool GetPhoneCall(IPhoneCall phoneCall)
        {
            return false;
        }

        public void RegisterNext(IPhoneCallHandler employee)
        {
            throw  new InvalidOperationException("can't register next to null");
        }
    }

    public abstract class Employee
    {
        protected int _maxBudget;

        public string Name { get;set; }
        public Employee(string name, int maxBudget)
        {
            _maxBudget = maxBudget;
            Name = name;
        }

        public bool Resolve(IPhoneCall phoneCall)
        {
            return phoneCall.Budget <= _maxBudget;
        }
    }
    public class LowLevel : Employee
    {
        public LowLevel(string name)
            : base(name, 1000)
        {
        }
    }

    public class MediumLevel : Employee
    {
        public MediumLevel(string name)
            : base(name, 5000)
        {
        }
    }

    public class HighLevel : Employee
    {
        public HighLevel(string name)
            : base(name, 10000)
        {
        }
    }
}


texts:
I've been struggling with registering a plist into NSUserDefaults and I've finally got it working, though I'm not sure that its written properly. I'm hoping someone here can shine some light on this process.

My intention with this code:

I want to be able to set all of my values in a plist and essentially use that to "seed" my NSUserDefaults. My end goal is to use this as a user settings menu.

My question:

What is the correct way to register a plist into the NSUserDefaults?

I followed the example from this this post and I received compiler errors. So I started experimenting. I could only get the code from the post to work if I added setObject(dict, forKey: "defaults") first.

Once added, it seemed to render the registerDefaults line pointless as the code runs with or without it.

The lines that I am questioning are these:

userDefaults.setObject(dict, forKey: "defaults") // without this my code doesn't work

userDefaults.registerDefaults(dict as! [NSObject : AnyObject])  // with or without this code works... do I need this?

I've placed the entirety of the code below to put above lines in context. This is all of the code so you can copy it right into Xcode and it will work.

ViewController.swift

class ViewController: UIViewController {

    let userDefaults = NSUserDefaults.standardUserDefaults()

    override func viewDidLoad() {
        super.viewDidLoad()

        let prefs = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")
        let dict = NSDictionary(contentsOfFile: prefs!)
        userDefaults.setObject(dict, forKey: "defaults")                // without this code doesn't work
        userDefaults.registerDefaults(dict as! [NSObject : AnyObject])  // with or without this code works... do I need this?
        userDefaults.synchronize()

        // this just toggles the aBool value
        if let defaults = userDefaults.valueForKey("aBool") as? NSNumber {

            if defaults as NSObject == 1 {
                println("inside the conditional: \(defaults)")
                userDefaults.setValue(0, forKey: "aBool")
                userDefaults.synchronize()
                println("Setting aBool to true")
            } else {
                userDefaults.setValue(1, forKey: "aBool")
                userDefaults.synchronize()
                println("setting aBool to false")
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

Settings.plist


texts: Uploading multiple files to server with PHP and JavaScript

texts:
I wrote some code to upload multiple files to a server with PHP and JavaScript. I'm happy with the form and JavaScript, below.

<form method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple>
    <input type="submit" value="Upload File" name="submit">
</form>

<script>
    const url = 'process.php';
    const submit = document.querySelector('[type=submit]');

    submit.addEventListener('click', e => {
        e.preventDefault();

        const files = document.querySelector('[type=file]').files;
        const formData = new FormData();

        for (let i = 0; i < files.length; i++) {
            let file = files[i];

            formData.append('files[]', file);
        }

        fetch(url, {
            method: 'POST',
            body: formData
        }).then(response => {
            console.log(response);
        });
    });
</script>

I would appreciate a review of the PHP for handling the $_POST request. I tried to make it as simple as possible, but I'm not sure if there are any major security concerns I'm overlooking.

<?php
if ($_SERVER["REQUEST_METHOD"] === 'POST') {
    if (isset($_FILES['files'])) {
        $errors = [];
        $path = 'uploads/';
        $extensions = ['jpg', 'jpeg', 'png', 'gif', 'html', 'txt', 'pdf', 'doc'];

        $allFiles = count($_FILES['files']['tmp_name']);

        for ($i = 0; $i < $allFiles; $i++) {
            try {
                $file_name = $_FILES['files']['name'][$i];
                $file_tmp = $_FILES['files']['tmp_name'][$i];
                $file_type = $_FILES['files']['type'][$i];
                $file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));

                $file = $path . $file_name;

                if (!in_array($file_ext, $extensions)) {
                    throw new Exception('Extension not allowed: ' . $file_name . ' ' . $file_type . "\n");
                }

                if ($file_size > 2097152) {
                    // 2MB
                    throw new Exception('File size exceeds limit: ' . $file_name . ' ' . $file_type. "\n");
                }
                move_uploaded_file($file_tmp, $file);
            } catch (Exception $e) {
                error_log($e->getMessage(), 3, '/path/to/error_log');
            }
        }
    }
}


texts: Greedy adaptive dictionary (GAD) for supervised machine learning

texts:
For my project in machine learning supervised, I have to simplify a training-data and I have to use this technique at page 5 of the document.

Pseudocode algorithm

My code (numbers are the steps):

import numpy as np
import math
def GAD(X):
    # 1. Initialize
    l=0
    D=[]
    I=[]
    R = np.copy(X)

    # 2. repeat l=<N (look algorithm)
    while l<X.shape[0]:
        # 3. Find residual column (l1 to l2 norm ratio)
        min_eps = float('inf') # to search min initialize to infinite
        j_min   =   -1
        for j in range(R.shape[1]):
            norma1 = norma2 = 0
            for i in range(R.shape[0]):
                norma1 += abs(R[i][j])
                norma2 += (R[i][j])**2
            norma2 = math.sqrt(norma2)
            eps = norma1/norma2   # sparsity index
            if min_eps > eps and j not in I: #excludes if already inserted
                min_eps=eps
                j_min = j
        # 4. Set the l-th atom equal to normalized
        norma2 = np.sqrt(np.sum(R[:, j_min]**2, axis=0))
        atomo = R[:, j_min]/norma2
        # 5. Add to the dictionary
        if len(D) == 0:
            D = np.asarray(atomo)
        else:
            D = np.vstack((D, atomo.T))
        I.append(j_min)
        # 6. Compute the new residual
        for j in range(R.shape[1]):
            R[:, j] = R[:, j]-atomo*(atomo.T*R[:, j])
        l = l+1
    # 7. Termination (read page 6 of the document)
    return D,I

I have some doubts:

Is it a correct implementation (observe mostly steps 5 and 6 in the pseudocode algorithm)?


texts: Remapping of arrays on structs (code style)

texts:
I'm working on a piece of code that remaps a set of signals (1-D integer arrays) onto a set of multi channel samples. I hope the typedefs and the remapping clearifies what I mean. If not, please let me know.
#include <stdint.h>

#define SIGNAL_LENGTH 1024

/**
* Multiple linear input signals as read by a previous input stage
*/
typedef struct {
    // Mics inside
    int32_t micInside0[SIGNAL_LENGTH];
    int32_t micInside1[SIGNAL_LENGTH];
    int32_t micInside2[SIGNAL_LENGTH];
    int32_t micInside3[SIGNAL_LENGTH];
    // Mics aux
    int32_t micAux0[SIGNAL_LENGTH];
    int32_t micAux1[SIGNAL_LENGTH];
    int32_t micAux2[SIGNAL_LENGTH];
    int32_t micAux3[SIGNAL_LENGTH];
} InputSignals_t;

/**
* Single input struct to be passed to the following filtering stage
*/
typedef struct {
    // Mic inside 0
    int32_t micInside0a;
    int32_t micInside0b;
    int32_t micInside0Select;
    // Mic inside 1
    int32_t micInside1a;
    int32_t micInside1b;
    int32_t micInside1Select;
    // Mic inside 2
    int32_t micInside2a;
    int32_t micInside2b;
    int32_t micInside2Select;
    // Mic inside 3
    int32_t micInside3a;
    int32_t micInside3b;
    int32_t micInside3Select;
} FilterSample_t;

/**
* Map the linear input signals to interleved multi-channel filter input signals.
*/
void mapMicFilters(InputSignals_t *inputSignals, FilterSample_t filterSamples[SIGNAL_LENGTH]) {
    for(int i = 0; i < SIGNAL_LENGTH; i++) {
        FilterSample_t *filterSample = &filterSamples[i];

        // I am rather unhappy with the look of the following
        // code section where the mapping is done.

        // Mic inside 0
        filterSample->micInside0a = inputSignals->micInside0[i];
        filterSample->micInside0b = 0;
        filterSample->micInside0Select = 1;

        // Mic inside 1
        filterSample->micInside1a = inputSignals->micInside0[i];
        filterSample->micInside1b = 0;
        filterSample->micInside1Select = 1;

        // Mic inside 2
        filterSample->micInside2a = inputSignals->micInside0[i];
        filterSample->micInside2b = 0;
        filterSample->micInside2Select = 1;

        // Mic inside 3
        filterSample->micInside3a = inputSignals->micInside0[i];
        filterSample->micInside3b = 0;
        filterSample->micInside3Select = 1;
    }
}

I am rather unhappy with the look of the code section where the mapping is done.The reason for this is that the lines become very long when the signal names become more specific (therefore longer). But a line break within the statements would really mess up the readability:
filterSample->micInside0a =
    inputSignals->micInside0[i];
filterSample->micInside0b =
    0;
filterSample->micInside0Select =
    1;

Do you have any suggestions on how to format the code? In dynamic languages I would just take a hashmap with the variable names and loop through it. But I have (and want) to use C.
Thank you!


texts: Performing multiple substring replacements on a string

texts:
I have code like the following, which performs a series of replacements on a string, to convert it to its final form.

public String convertString(String string) {

String convertedString = string;

if( string.contains("something")) {
    convertedString = convertStringA(string);

    return convertedString;
} else if (string.contains("something else")) {
    convertedString = convertStringB(string);

    return convertedString;
} ...

// many more else if blocks

else if (string.contains("something else")) {
    convertedString = convertStringXXX(string);

    return convertedString;
} ...

}

How can I do it better?