texts:
I found this answer on stackoverflow:

https://stackoverflow.com/questions/18087088/using-arrow-buttons-to-scroll-window-horizontally#answer-18088332

and customized it.

It is designed to be a "navbar" for my admins. The boxes will have things like "Users" with a picture on it. It will be implemented in angular, but I thought I'd try to get it working with jquery first.

function initAdminNavBar() {

  var scrollHandle = 0,
    scrollStep = 30; //speed
  var parent = $("#adminNavRow");

  //set the width of the parent dynamically
  var elemWidth = $($('.contentBlock')[0]).outerWidth(true);
  var numOfElems = $('.contentBlock').length;
  var parentWidth = elemWidth * numOfElems;
  //set parent width
  $('.con').css('width', parentWidth);

  //need this number for the right buffer / scrolling... number of pixels needed to be added to the div to keep going
  var magicNumber = numOfElems * 24;

  //Start the scrolling process
  $(".panner").on("mouseenter", function() {
    var modifier = 1;
    if ($(this).data('direction') == 'right') {
      modifier = -1;
    }
    $(this).addClass('active');
    startScrolling(modifier, scrollStep);
  });
  //Kill the scrolling
  $(".panner").on("mouseleave", function() {
    stopScrolling();
    $(this).removeClass('active');
  });
  //Actual handling of the scrolling
  function startScrolling(modifier, step) {
    if (scrollHandle === 0) {
      scrollHandle = setInterval(function() {
        var currentPosition = parseInt($('.con').css('left'));
        var canScroll = true;

        if (modifier > 0) {
          canScroll = canScrollLeft();

        } else {
          canScroll = canScrollRight();
        }
        if (canScroll) {
          $('.con').css('left', (currentPosition + scrollStep * modifier));
        }
      }, 10);
    }
  }

  function stopScrolling() {
    clearInterval(scrollHandle);
    scrollHandle = 0;
  }

  function canScrollRight() {
    return (parseInt($('.con').css('left')) >= (-parseInt($('.con').css('width')) - magicNumber) / 2);

  }

  function canScrollLeft() {
    return (parseInt($('.con').css('left')) < 0);
  }

}

initAdminNavBar();
.adminMenu {
  overflow: hidden;
  height: 270px;
}
.vp {
  position: relative;
  overflow: hidden;
  height: 100%;
  max-width: 100%;
  outline: medium none;
  direction: ltr;
}
.con {
  position: relative;
  top: 0px;
  left: 0px;
  /*todo: set this dynamically with jquery: */
  /*width: 1086px;*/
}
.contentBlock {
  height: 250px;
  width: 250px;
  background: lightsalmon;
  float: left;
  margin: 10px;
}
.panner {
  border: 1px solid black;
  display: block;
  position: absolute;
  width: 20px;
  height: 250px;
  top: 20px;
}
.active {
  color: red;
}
#panLeft {
  left: 0px;
}
#panRight {
  right: 0px;
}

Users

Charts

Imagine these are links with pictures in them...

4

5

 Left
  Right

Fiddle:
https://jsfiddle.net/2zxuwbu8/


texts: Initializing a tile-like map such that the edges are marked with an 'X'

texts:
I've been messing around with arrays as I'm learning them currently in my book and they gave the idea of a chess board using for loops alongside multidimensional arrays to give them individual values which you can therefore print out.

However, I thought of the old console RPG games from way back and wanted to simply add a border around the array so it prints any 0 || 19 value as an X. The code does work however, is there a way of making it more efficient by using if statements or by created a switch statement that reads the current loop variable and change that array value to a 1 for fill or leave it 0 to blank the "tile".

#include <iostream>

using namespace std;

int main()
{
    int rpgLevelGrid[20][20];

    //Co-od decleration
    for (int i = 0; i < 20; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            switch (i)
            {
            case 0: case 19:
                rpgLevelGrid[i][j] = 1;
                break;
            default:
                rpgLevelGrid[i][j] = 0;
                break;
            }

            switch (j)
            {
            case 0:
                rpgLevelGrid[i][j] = 1;
                break;
            case 19:
                rpgLevelGrid[i][j] = 1;
                break;
            }
        }
    }

    for (int i = 0; i < 20; i++)
    {
        for (int j = 0; j < 20; j++)
        {
            switch (rpgLevelGrid[i][j])
            {
            case 1:
                cout << "X";
                break;
            default:
                cout << "-";
            }
        }
        cout << endl;
    }
}


texts:
I wrote a quick timer function that depends on the beepr package to provide the sound effect at the end of the time.  I've never used a while-loop before, so I don't know if there's a more elegant way to write this (i.e., one that doesn't require repeating the same line of code twice?).  I'd appreciate knowing if there is a better way:

timer <- function(interval, units) {
require(beepr)
t0 <- Sys.time()
stopwatch <- round(as.double(difftime(Sys.time(), t0, u = units)))
while(stopwatch < interval){
  stopwatch <- round(as.double(difftime(Sys.time(), t0, u = units)))
  }
beep(2)
}

timer(5, "secs")


texts: Synchronous and asynchronous behavior for client

texts:
I am working on a project in which I am supposed to make synchronous and asynchronous behavior of my client.

The customer will call our client with a userId and we will construct a URL from that userId and make an HTTP call to that URL and we will get a JSON string back after hitting the URL. And after we get the response back as a JSON string, we will send that JSON string back to our customer.

In this case, I need to have synchronous and asynchronous methods.  Some customers will call the executeSynchronous method to get the same feature and some customers will call our executeAsynchronous method to get the data back.

Interface:

public interface Client {

    // for synchronous
    public String executeSynchronous(final String userId);

    // for asynchronous
    public Future<String> executeAsynchronous(final String userId);
}

SmartClient which implements the Client interface:

public class SmartClient implements Client {

    ExecutorService executor = Executors.newFixedThreadPool(5);

    // This is for synchronous call
    @Override
    public String executeSynchronous(String userId) {

        String response = null;
        Future<String> handle = getHandle(userId);

        try {
            response = handle.get(500, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {

        }

        return response;
    }

    // This is for asynchronous call
    @Override
    public Future<String> executeAsynchronous(String userId) {

        return getHandle(userId);

    }

    private Future<String> getHandle(String userId) {
        Future<String> future = null;

        Task task = new Task(userId);
        future = executor.submit(task);

        return future;

    }
}

Simple class which will perform the actual task:

class Task implements Callable<String> {

    private final String userId;

    public Task(String userId) {
        this.userId = userId;
    }

    public String call() throws Exception {

        String url = createURL(userId);

        // make a HTTP call to the URL
        RestTemplate restTemplate = new RestTemplate();
        String jsonResponse = restTemplate.getForObject(url, String.class);

        return jsonResponse;
    }

    // create a URL
    private String createURL(String userId) {
        String generateURL = somecode;

        return generateURL;
    }
}

Is this the correct and efficient way of doing this problem?
How about the exception handling?
Do I need any other catch blocks at any places?


texts:
This code simulates a polygon (say a triangle) with a person at each vertex, every person is looking at the next adjacent vertex/person. They all start moving towards each other with a constant velocity "trying to chase other". I could not understand this conceptually so I created an applet in Java to help me understand it in physics.

package test;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;

public class ChasePolygon extends Applet {

    public void paint(Graphics g) {
        final int radius = 200;
        final float velocity = 0.001f;
        final int sides = 6;
        final float theta = (float) (2 * Math.PI / sides);
        final int centerX = 200, centerY = 200;
        ArrayList<Float[]> vertices_loc = new ArrayList<Float[]>(sides);
        for (int i = 0; i < sides; i++) {
            final float pX = (float) (centerX + radius * Math.cos(i * theta));
            final float pY = (float) (centerY + radius * Math.sin(i * theta));
            vertices_loc.add(new Float[] { pX, pY });
        }
        Graphics2D g2 = (Graphics2D) g;
        GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, sides);
        polyline.moveTo(vertices_loc.get(0)[0], vertices_loc.get(0)[1]);
        for (int i = 0; i < sides; i++) {
            polyline.lineTo(vertices_loc.get(i)[0], vertices_loc.get(i)[1]);
        }
        polyline.lineTo(vertices_loc.get(0)[0], vertices_loc.get(0)[1]);
        g2.draw(polyline);
        int delta_T = (int) Math
                .floor((radius * Math.sin(theta / 2) / velocity));
        ArrayList<GeneralPath> g_p = new ArrayList<GeneralPath>(sides);
        for (int i = 0; i < sides; i++) {
            g_p.add(new GeneralPath(GeneralPath.WIND_EVEN_ODD, delta_T));
            g_p.get(i).moveTo(vertices_loc.get(i)[0], vertices_loc.get(i)[1]);
        }
        for (int i = 0; i < delta_T; i++) {
            for (int j = 0; j < sides; j++) {
                float dX = 0, dY = 0;
                if (j != sides - 1) {
                    dX = vertices_loc.get(j + 1)[0] - vertices_loc.get(j)[0];
                    dY = vertices_loc.get(j + 1)[1] - vertices_loc.get(j)[1];
                } else {
                    dX = vertices_loc.get(0)[0] - vertices_loc.get(j)[0];
                    dY = vertices_loc.get(0)[1] - vertices_loc.get(j)[1];
                }
                vertices_loc.get(j)[0] += dX * velocity;
                vertices_loc.get(j)[1] += dY * velocity;
                g_p.get(j).lineTo(vertices_loc.get(j)[0],
                        vertices_loc.get(j)[1]);
            }
        }
        for (int i = 0; i < sides; i++) {
            g2.draw(g_p.get(i));
        }

    }
}

Here is the sample output:

\$\hskip1.25in\$

Improvements could be (not necessarily these but any you consider):

Better way/s to do certain things, specific to programming only (not to my algorithm).
My first attempt with Java graphics/Swing etc. so any advice/hints etc.
Performance. Yes, it's slow; try running it.
It restarts when I change applet size.
Fix applet size, etc. as you wish.


texts: How to know when I need to use get/set and when not?

texts:
I have read several articles using Google, but I somehow do not really get what they do, and when it is needed. Below I'll give 2 pieces of code, in one using get/set and in the other without, and they both work (at least in this example).

Example 1

public class Example
{
    public int number;
}

class Program
{
    static void Main(string[] args)
    {
        Example example = new Example();

        example.number = 5;

        Console.WriteLine(example.number);
        Console.ReadKey();
    }
}

Example 2

public class Example
{
    private int number;
    public int Number
    {
        get { return number; }
        set { number = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Example example = new Example();

        example.Number = 5;

        Console.WriteLine(example.Number);
        Console.ReadKey();
    }
}

I've added a piece of real code below so it may be improved and perhaps shown examples on these accessors.

// Main
public class Asteroid
{
    Random random = new Random();

    public Texture2D texture;
    public Vector2 position, origin;
    public float rotationAngle;
    public int speed;
    public Rectangle boundingBox;
    public bool isVisible;
    public float randomX, randomY;

    // Constructor
    public Asteroid(Texture2D newTexture, Vector2 newPosition)
    {
        position = newPosition;
        texture = newTexture;
        speed = 4;
        randomX = random.Next(0, 750);
        randomY = random.Next(-600, -50);
        isVisible = true;
    }

    // Load Content
    public void LoadContent(ContentManager Content)
    {

    }

    // Draw
    public void Draw(SpriteBatch spriteBatch)
    {
        if (isVisible)
            // spriteBatch.Draw(texture, position, Color.White);
            spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f);
    }

    // Update
    public void Update(GameTime gameTime)
    {
        // Set bounding box for collision
        boundingBox = new Rectangle((int)position.X - (texture.Width / 2), (int)position.Y - (texture.Height / 2), texture.Width, texture.Height);

        origin.X = texture.Width / 2;
        origin.Y = texture.Height / 2;

        // Update Movement
        position.Y = position.Y + speed;

        if (position.Y >= 950)
        {
            isVisible = false;
        }

        // Rotating Asteroid
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        rotationAngle += elapsed;
        float circle = MathHelper.Pi * 2;
        rotationAngle = rotationAngle % circle;
    }
}


texts:
My game engine uses the following broadphase collision detection algorithm:
internal void SweepAndPrune()
{
    // First: order all objects from left to right on the x-axis:
    IOrderedEnumerable<GameObject> axisList = _gameObjects.OrderBy(x => x.LeftRightMost.X);

    // loop through all objects:
    for(int i = 0; i < axisList.Count(); i++)
    {
        // For each object, iterate over all the subsequent objects in the list
        // and find out if there are overlaps on the x-axis:
        for(int j = i+1; j < axisList.Count(); j++)
        {
            GameObject a = axisList.ElementAt(i);
            GameObject b = axisList.ElementAt(j);
            if(b.Left > a.Right)
            {
                // if their is no overlap, then the rest will not overlap as well.
                // might as well stop the inner loop here:
                break;
            }
            // if there is an overlap, add A to B's list
            // and B to A's list of potential collisions.
            // [every object's list of collision candidates is
            // cleared before the next frame]
            a._collisionCandidates.Add(b);
            b._collisionCandidates.Add(a);
        }
    }
}

The problem is, this algorithm slows down the performance by a lot if there are > 50 objects on screen.
Also, the list of GameObject instances (_gameObjects) needs to get sorted another time per frame because I need to order the objects by their distances from the camera (background objects need to get rendered first because of transparency!).
Is there anything I can do to speed things up?


texts: Program to shorten URL and decode it back to get original URL

texts:
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

My approach:

import java.util.HashMap;
import java.util.Random;
import java.lang.StringBuilder;

public class Codec {

     //HashMap to store the longUrl and the randomly generated string
     HashMap<String,String> urlMap = new HashMap<>();

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        Random rand = new Random();
        int urlLen = 6;
        char [] shortURL = new char[urlLen];
        String randChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

        for(int i = 0; i < urlLen; i++ )
            shortURL[i] = randChars.charAt(rand.nextInt(randChars.length()));

        StringBuilder sb = new StringBuilder("http://tinyurl.com/");
        sb.append(new String(shortURL));
        System.out.println(sb);

        urlMap.put(sb.toString(),longUrl);

        return sb.toString();

    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {

            return urlMap.get(shortUrl);

    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

With regards to the above code, I have the following questions:

Is there a better approach to do this question?
Can I decrease the number of lines or variables used in the program?
Can I improve the space and time complexity of the program?

Reference


texts: Place arithmetic signs in correct order to get the number

texts:
Given a list of numbers, place signs + or - in order to get the
  required number.

  If it's possible then return true, otherwise return false

  [1, 2, 3, 4, 5, 7]; 12 -> true, because 1 + 2 + 3 + 4 - 5 + 7 = 12

  [5, 3]; 7 -> false, because 5 + 3 != 7 and 5 - 3 != 7

I came up with the following brute force solution:

public static boolean trueOrNot(int number, List<Integer> numbers) {
        boolean found = false;
        int i = 0;
        while (!found && i < (1 << numbers.size())) {
            int tmpResult = 0;
            for (int j = 0; j < numbers.size(); j++) {
                int num = numbers.get(j);
                if ((i & (1 << j)) > 0) {
                    num = -num;
                }
                tmpResult += num;
            }
            found = tmpResult == number;
            i++;
        }
        return found;
}

Basically, I took for consideration binary representations of numbers 0000, 0001, 0010...2^n and iterate over every bit, thus getting all possible combinations. 0 is a + sign and 1 is - sign.
Then I calculate temporal result and once it is equal to the sought number I break out from loop.

Time complexity: O(2n)
Space complexity: O(1)

I just wondering is there any more effective solution with the help of Dynamic Programming, for example?

Feedback for the current solution?


texts: Trie - code review request for improvement

texts:
Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

public class Trie {

    private static final int ASCII = 256;

    private TrieNode root;

    public Trie () {
        root = new TrieNode();
    }

    private static class TrieNode {
        TrieNode[] alphabets;
        char ch;
        String word;
        String meaning;

        public TrieNode() {
            this.alphabets = new TrieNode[ASCII];
        }

        public TrieNode (char ch) {
            this.alphabets = new TrieNode[ASCII];
            this.ch = ch;
        }
    }

    public void add (String word, String meaning) {
        TrieNode node = root;
        char[] ch = word.toCharArray();

        for (char c : ch) {
            if (node.alphabets[c] == null) {
                node.alphabets[c] = new TrieNode(c);
            }
            node = node.alphabets[c];
        }
        node.word = word;
        node.meaning = meaning;
    }

    public String getMeaning (String word) {
        TrieNode node = root;
        char[] ch = word.toCharArray();

        for (char c : ch) {
            node = node.alphabets[c];
            if (node == null) {
                return null;
            }
        }
        return node.meaning;
    }

    /**
     * Deletes all its children, but does not delete itself.
     */
    public void prune (String string) {
        TrieNode node = root;
        char[] ch = string.toCharArray();

        for (char c : ch) {
            node = node.alphabets[c];
            if (node == null) {
                return;
            }
        }
        node.alphabets = new TrieNode[ASCII];
        return;
    }

    public void print() {
        printWhole(root);
    }

    private void printWhole(TrieNode node) {
        if (node == null) {
            return;
        }
        if (node.word != null) {
            System.out.println("Word: " + node.word + " Meaning: " + node.meaning);
        }
        for (int i = 0; i < ASCII; i++) {
            printWhole(node.alphabets[i]);
        }
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.add("mouse", "rat");
        trie.add("cop", "police");
        trie.add("cope", "endure");

        System.out.println("Expected rat, Actual: " + trie.getMeaning("mouse"));
        System.out.println("Expected police, Actual: " + trie.getMeaning("cop"));
        System.out.println("Expected endure, Actual: " + trie.getMeaning("cope"));
        System.out.println("Expected null, Actual: " + trie.getMeaning("co"));

        trie.print();

        trie.prune("cop");

        System.out.println("Expected police, Actual: " +trie.getMeaning("cop"));
        System.out.println("Expected null, Actual: " +trie.getMeaning("cope"));

        trie.print();
    }
}


texts:
I am designing a Stock Currency application and for that, I created a database.
I searched for my question  here  first but the answerer told me to ask the same question here.
flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Stock_Data(db.Model):
    __tablename__ = 'stock_datas'
    # Column names start with capital letter for convention to use data easier (for now)
    id = db.Column(db.Integer(), primary_key=True)
    Date = db.Column(db.DateTime, nullable=False)
    Open = db.Column(db.Float(), nullable=False)
    High = db.Column(db.Float(), nullable=False)
    Low = db.Column(db.Float(), nullable=False)
    Currency_Close = db.Column(db.Float(), nullable=False)
    Volume = db.Column(db.Integer(), nullable=False)

    # Foreign Key
    stock_id = db.Column(db.Integer, db.ForeignKey('stocks.id'))

    # Foreign Attribute To Reach
    stock = db.relationship('Stock', backref='Stock_Data', primaryjoin='Stock_Data.stock_id==Stock.id', lazy=True)

class Stock(db.Model):
    __tablename__ = 'stocks'
    id = db.Column(db.Integer(), primary_key=True)
    symbol = db.Column(db.String(10), unique=True)
    name = db.Column(db.String(50), unique=True)
    sector = db.Column(db.String(10), nullable=True)
    currency = db.Column(db.String(3), nullable=False)

class Parity_Data(db.Model):
    __tablename__ = 'parity_datas'
    id = db.Column(db.Integer(), primary_key=True)
    Parity_Close = db.Column(db.Float())
    Date = db.Column(db.DateTime, nullable=False)

    # Foreign Key
    parity_id = db.Column(db.Integer, db.ForeignKey('parities.id'))

    # Foreign Attribute To Reach
    parity = db.relationship('Parity', backref='Parity_Data', primaryjoin='Parity_Data.parity_id==Parity.id', lazy=True)

class Parity(db.Model):
    __tablename__ = 'parities'
    id = db.Column(db.Integer(), primary_key=True)
    parity_name = db.Column(db.String(8), unique=True)

I created this database design all classes are in separate files. Sotck is related to Stock_Data (1-N) and Parity is related to Parity_Data (1-N) as seen.
I am creating a connection between Stock and Parity by
string_stock = 'APPL'
stock = session.query(Stock).filter(Stock.symbol == str(string_stock).upper()).first()
stock_data = session.query(Stock_Data).filter(Stock_Data.stock_id == stock.id).all()
parity = session.query(Parity).filter(Parity.parity_name.endswith(stock.currency)).first()
parity_data = session.query(Parity_Data).filter(Parity_Data.parity_id==parity.id).all()

By this method, I can fetch all stock_data and parity_data separately. However, when I try to merge stock_data and parity_data I get two lists and cannot be merged.
After that, I tried
data_joined_on_time = session.query(Stock_Data).join(Parity_Data, Stock_Data.Date == Parity_Data.Date).all()
dir(session.query(Stock_Data).join(Parity_Data, Stock_Data.Date == Parity_Data.Date).all()[0])

This method joins data but the attributes:
['Currency_Close',
'Date',
'High',
'Low',
'Open',
'Volume',
'class',
'delattr',
'dict',
'dir',
'doc',
'eq',
'format',
'ge',
'getattribute',
'gt',
'hash',
'init',
'init_subclass',
'le',
'lt',
'mapper',
'module',
'ne',
'new',
'reduce',
'reduce_ex',
'repr',
'setattr',
'sizeof',
'str',
'subclasshook',
'table',
'tablename',
'weakref',
'_decl_class_registry',
'_sa_class_manager',
'_sa_instance_state',
'id',
'metadata',
'query',
'query_class',
'stock',
'stock_id']
There is nothing about Parity_Data part.
My question consists of two parts:

I could not think of another way for my database design.Is my database design incorrect?
Is there a way to merge those two (stock_data and parity_data) by SQLAlchemy? I would like to filter first and join after it.
If there is no way I will merge them on pandas dataframe but firstly I want to try it on SQLAlchemy.


texts: Summarizing the score of a personality quiz

texts:
This function takes a list of questions and list of answers provided by the user.

The list of answers is always a list of booleans (for true and false) and the list of questions takes the following form:

{
  quadrant: Number
}

If the user answers "true" to a question then they gain a point towards that quadrant. (Think of it like a personality test). If they answer false, nothing happens.

The quadrants are arranged along two axes like this:

Q1 | Q4
---+---
Q2 | Q3

The X axis is called "Warmth" and the Y axis is called "Dominance".

This function aims to calculate which quadrant you are in given your answers. If you are on a boundary, it returns an array with the quadrants that you span. If there is a 4-way tie, Quadrant 4 is assumed.

It looks very messy and difficult to read. How could I improve it? I'd specifically like to pull the whole thing into a reduce function if I can to avoid the nasty if/else tree at the end.

calculateResult = (questions, answers) => {
    const res = _.zip(questions, answers)
      .filter(x => x[1]) // Only get correct answers
      .map(x => x[0].quadrant) // Pluck the quadrant number
      .reduce(
        (res, x) => {
          if (x == 1 || x == 4) {
            res.dominance++;
          } else {
            res.dominance--;
          }

          if (x == 3 || x == 4) {
            res.warmth++;
          } else {
            res.warmth--;
          }
          return res;
        },
        {
          dominance: 0,
          warmth: 0
        }
      );

    if (res.dominance > 0) {
      if (res.warmth > 0) {
        return [4];
      } else if (res.warmth < 0) {
        return [1];
      } else {
        return [1, 4];
      }
    } else if (res.dominance < 0) {
      if (res.warmth > 0) {
        return [3];
      } else if (res.warmth < 0) {
        return [2];
      } else {
        return [2, 3];
      }
    } else {
      if (res.warmth > 0) {
        return [3, 4];
      } else if (res.warmth < 0) {
        return [1, 2];
      } else {
        return [4];
      }
    }
};

Test Cases

The "questions" parameter pretty much always looks the same. (The program pulls 3 questions from each quadrant)

var questions = [
  { quadrant: 1 },
  { quadrant: 1 },
  { quadrant: 1 },
  { quadrant: 2 },
  { quadrant: 2 },
  { quadrant: 2 },
  { quadrant: 3 },
  { quadrant: 3 },
  { quadrant: 3 },
  { quadrant: 4 },
  { quadrant: 4 },
  { quadrant: 4 }
];

The "answers" parameter is always a list of booleans denoting true/false. Here are some test cases from my test suite.

const answersForQuadOne = [ // Should return [ 1 ]
  true,
  true,
  true,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  false
];

const answersOnBoundary = [ // Boundary should return [ 1, 2 ]
  true,
  true,
  true,
  true,
  true,
  true,
  false,
  false,
  false,
  false,
  false,
  false
];


texts:
This class is part of a utility that reads lines from a set of nonblocking file descriptors, blocking only when there are no complete lines to emit.

class NonblockingLineBuffer:
    def __init__(self, fd, encoding):
        self.fd  = fd
        self.enc = encoding
        self.buf = bytearray()

    def absorb(self):
        while True:
            try:
                block = os.read(self.fd, 8192)
            except BlockingIOError:
                return

            if block:
                self.buf.extend(block)
            else:
                self.is_open = False
                # We don't close the file here because caller
                # needs to remove the fd from the poll set first.
                return

    def emit(self):
        def emit1(chunk):
            self.emitted_this_cycle = True
            return (self.fd, chunk.decode(self.enc).rstrip())

        buf = self.buf
        self.emitted_this_cycle = False
        while buf:
            r = buf.find(b'\r')
            n = buf.find(b'\n')
            if r == -1 and n == -1:
                if not self.is_open:
                    yield emit1(buf)
                    buf.clear()

            elif r == -1 or r > n:
                yield emit1(buf[:n])
                buf = buf[(n+1):]

            elif n == -1 or n > r:
                yield emit1(buf[:r])
                if n == r+1:
                    buf = buf[(r+2):]
                else:
                    buf = buf[(r+1):]

        self.buf = buf
        if not self.is_open:
            self.emitted_this_cycle = True
            yield (self.fd, None)

This question is specifically about emit, which is complicated, confusing, and might not be as efficient as it could be.  Please suggest ways to make it less complicated and/or confusing, and more efficient.

(I know it could be much simpler if it didn't need to reimplement universal newline handling, but that is unfortunately a requirement from the larger context.)

(If there's something in the standard library that does some or all of the larger task, that would also be a welcome answer.)


texts: Caesar Cipher in Haskell, on every other character

texts:
I'm learning Haskell, and I tried to do an exercise which it is an implementation of the Caesar Cipher method.

The problem asks for cipher a text which it is in lower case and can contain characters from 'a' to 'z' without numbers, uppercase letters, symbols etc.., only lower case letters.

If the letter it is in an even position inside the message, I need to change for itself but in upper case. Example 'a' will be 'A'

If the letter is in an odd position inside the message, I need to change it by an other letter "n" positions next in the alphabet by the original one.
Example 'a' will be 'd' if "n" is equal to 3

Important thing, the alphabet needs to be circular, so, after z, will be the 'a'

So you call the function with a text and a number "n" for example: alfabet 3
The result will be: AoFdBhT.

This is my personal implementation, I checked it, and works fine, but I think maybe it is not a very good implementation, and I would like some advice to improve it.

caesarCipher :: String -> Int -> String
caesarCipher = caesarCipherAux [] 0

caesarCipherAux :: String -> Int -> String -> Int -> String
caesarCipherAux codedMessage _ [] _ = codedMessage
caesarCipherAux codedMessage pos (xs:s) n =
if even (pos) then
    caesarCipherAux (codedMessage++[toUpper xs]) (pos+1) s n
else
    caesarCipherAux (codedMessage++ [cipher xs n]) (pos+1) s n

cipher :: Char -> Int -> Char
cipher xs n
| xs == 'x'='a'
| xs == 'y'='b'
| xs == 'z'='c'
| otherwise = [xs..'z'] !! n


texts: Advent Of Code 2017 Day 4 (part 2) in Functional Programming (FP)

texts:
I wanted to practice functional programming (FP) without using any library but using vanilla JavaScript only. So I took a problem from Advent of Code (the 2nd part of Day 4)

You can only access the 2nd part if you type in the solution for the 1st part: 466 or look at my solution for part 1

  --- Part Two --- For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words
  that are anagrams of each other - that is, a passphrase is invalid if
  any word's letters can be rearranged to form any other word in the
  passphrase.

  For example:

  abcde fghij is a valid passphrase.
  abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word.
  a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word.
  iiii oiii ooii oooi oooo is valid.
  oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word. Under this new system policy, how
  many passphrases are valid?

My solution in FP:

const INPUT =
`pphsv ojtou brvhsj cer ntfhlra udeh ccgtyzc zoyzmh jum lugbnk
spjb xkkak anuvk ejoklh nyerw bsjp zxuq vcwitnd xxtjmjg zfgq xkpf
...
juo pmiyoh xxk myphio ogfyf dovlmwm moevao qqxidn`;

const get = input => input.split('\n');
const countDuplicate = words => words.reduce((acc, word) => {
  return Object.assign(acc, {[word]: (acc[word] || 0) + 1});
}, {});
const onlyUniqueWords = phrases => {
  const words = phrases.split(' ');
  const duplicateWords = countDuplicate(words);
  return !Object.values(duplicateWords).some(w => w > 1);
};
const sortWords = words => words.map(word =>  word.split('').sort().join(''));
const noAnagrams = phrases => {
  const words = phrases.split(' ');
  const sortedWords = sortWords(words).sort().join(' ');
  return onlyUniqueWords(sortedWords);
};
const phrasesWithNoAnagrams = get(INPUT)
.filter(noAnagrams);
console.log("solution ", phrasesWithNoAnagrams.length);

Is there a better way to write it in FP with pure JavaScript, i.e. no additional FP library? Any other improvement suggestions are welcomed.


texts: Catching Errors in Factory Method with express.js

texts:
My express.js application uses a lot of promises for interacting with a variety of services. Instead of including try/catch with each one, I've setup a fail safe factory method for all my express controllers. This should only be called when an unexpected error occurred. For example, 404 when trying a public API. I'm skeptical about how useful this is or if there is a much easier way to do this. Also looking for any other comments on this code or question.
//index.ts

import * as Express from 'express';
import { Auth } from '../class/Auth';

/**
 * Handler for async static functions recognizing that errors
 * should always be sent to the error handler. This is where
 * our error stone drops. This will eventuall replace go().
 * @param  callback function to be run
 * @return function for express to run
 */
function $(callback:Function):Function {
  return async (req:Express.Request, res:Express.Response, next:Express.NextFunction) => {
    try {
      await callback(req, res, next);
    } catch(e) {
      console.error("Something strange occurred",e);
      res.status(500).render('error', {
        error: "An internal error has occurred",
        errorCode: 500
      });
    }
  }
}

/**
 * Controller to log the user in
 * @param  req Express Request
 * @param  res Express Response
 */
function async loginController(req:Express.Request, res:Express.Response) {
  // verify parameters
  if(!(req.body['username'] && req.body['password'])){
    return res.status(400).end("Please include username and password");
  }

  var user = await Auth.login(req.body['username'], req.body['password']);

  if (user) {
    var authToken = Auth.generateAuthToken(user);
    res.json({
      authToken:authToken
    });
  } else {
    return res.status(401).end("Wrong username or password");
  }
}

var app = Express();
app.post('/api/login', $(loginController));
app.listen(8080);

// Auth.ts

import { User } from './User';

/**
 * Authentication base class
 */
export class Auth {
  /**
   * Log user in
   * @param email
   * @param password
   * @returns user logged in. Returns null if user is not found or authentication fails
   */
  public static async login(email:string, password:string):Promise<User> {
    var response = await fetch("example.com/api/login", {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: email
        password: password
      })
    });

    if(response.ok){
      return await response.json() as User;
    }

    // password or username was wrong
    if(response.status == 401){
      return null;
    }

    // an unknown error occurred
    throw Error(response.status);
  }

  /**
   * Generate AuthToken
   * @param user
   * @return token
   */
  public static generateAuthToken(user:User):string {
    return jwt.sign({ userid: user.id }, process.env.SECRET, {
      expiresIn: process.env.JWT_EXPIRY
    });
  }
}

```


texts: Write a procedure stream-limit that finds

texts:
From SICP:

  Exercise 3.64.  Write a procedure
  stream-limit that takes as arguments a
  stream and a number (the tolerance).
  It should examine the stream until it
  finds two successive elements that
  differ in absolute value by less than
  the tolerance, and return the second
  of the two elements. Using this, we
  could compute square roots up to a
  given tolerance by

(define (sqrt x tolerance)
  (stream-limit (sqrt-stream x) tolerance))

I wrote this answer:

(define (stream-limit s tol)
  (if (stream-null? s)
      (error "End of stream found before limit reached:" tol)
      (let* ((a (stream-car s))
             (b (stream-car (stream-cdr s)))
             (diff (abs (- a b))))
        (if (> tol diff) b (stream-limit (stream-cdr s) tol)))))

Can it be improved?


texts: Hacker Rank: Counting names with prefix matches using a trie

texts:
Practicing hacker rank questions and would love some feedback on how I could perform optimizations on a Trie.
This code will add a bunch of names into a trie and then when asked will turn how many names belong to a partial match. eg.

jenn, jennifer, george, jenny

partial => jen
return => 3

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication1
{
    class Solution
    {
        static void Main(String[] args)
        {
            int N = Int32.Parse(Console.ReadLine());
            string[,] argList = new string[N, 2];
            for (int i = 0; i < N; i++)
            {
                string[] s = Console.ReadLine().Split();
                argList[i, 0] = s[0];
                argList[i, 1] = s[1];
            }

            Trie trie = new Trie();

            for (int i = 0; i < N; i++)
            {
                switch (argList[i, 0])
                {
                    case "add":
                        trie.add(argList[i, 1]);
                        break;
                    case "find":
                        Console.WriteLine(trie.find(argList[i, 1]));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    class Trie
    {
        private readonly Trie[] _trieArray = new Trie[26];
        private int _findCount = 0;
        private bool _data = false;
        private char _name;
        private int _occurances = 0;

        public void add(string s)
        {
            s = s.ToLower();
            add(s, this);
        }

        private void add(string s, Trie t)
        {
            char first = Char.Parse(s[0].ToString());
            int index = first - 'a';

            if (t._trieArray[index] == null)
            {
                t._trieArray[index] = new Trie {_name = first};
            }

            if (s.Length > 1)
            {
                add(s.Substring(1), t._trieArray[index]);
            }
            else
            {
                t._trieArray[index]._data = true;
            }

            t._trieArray[index]._occurances++;
        }

        public int find(string s)
        {
            s = s.ToLower();
            find(s, this);

            int ans = _findCount;
            _findCount = 0;
            return ans;
        }

        private void find(string s, Trie t)
        {
            if (t == null)
            {
                return;
            }
            if (s.Length > 0)
            {
                char first = Char.Parse(s[0].ToString());
                int index = first - 'a';
                find(s.Substring(1), t._trieArray[index]);
            }
            else
            {
                _findCount = t._occurances;
            }
        }

    }
}


texts:
I have written a class and spec for testing my class. Can anyone determine whether or not this is a correct and good spec?

Class:

module Sitemap
=begin
Class Name: Cities
Function: This class is responsible for getting the data to create the sitemap
for each country according to cities.
=end
  class City
    attr_accessor :country_version, :directory, :country_host, :locale
    def initialize(country_version, directory, country_host,locale)
      @country_version = country_version
      @directory = directory
      @country_host = country_host
      @locale = locale
    end

    def get_data
      ::City.find_each(:conditions => {:country_version_id => @country_version.id}) do |city|
        I18n.locale=(@locale)
        yield entry(city)
      end
    end

    private
    def entry(city)
      {
        :loc => ActionController::Integration::Session.new.url_for(:controller => 'cities', :action => 'show', :city_name => city.name, :host => @country_host.value),
        :changefreq => 0.8,
        :priority => 'monthly',
        :lastmod => city.updated_at
      }
    end
  end
end

Spec:

require File.join(File.dirname(__FILE__), "/../spec_helper" )
module Sitemap
  describe City do

    before :all do
    @city = City.new :country_version, :directory, :country_host, :locale
    end

    describe "#new" do
      it "takes four parameters and returns a City object" do
        @city.should be_an_instance_of City
      end
    end

    describe "#country_version" do
      it "returns the correct country version" do
        @city.country_version.should eql :country_version
      end
    end

    describe "#directory" do
      it "returns the correct filepath" do
        @city.directory.should eql :directory
      end
    end

    describe "#country_host" do
      it "returns the correct country host" do
        @city.country_host.should eql :country_host
      end
    end

    describe "#locale" do
      it "returns the correct locale for translation" do
        @city.locale.should eql :locale
      end
    end

    describe "#get_data" do
      it "returns collections for xml entries" do
        @city.get_data.should eql ::City
      end
    end

  end
end


texts: Is it a good style to run external commands in Python?

texts:
I have lots of external shell commands to run.

So I gave every command a name and then run it.

tar_report_cmd = 'zip -r  {0} {1} '%(report_file, _export_dir)
exec_proc(tar_report_cmd)
mv_report_cmd = "mv {0} {1}".format(report_file,report_dir)
exec_proc(mv_report_cmd)

But it looks sort of redundant and not beautiful.

Is there any better practice to replace my way?

def exec_proc(cmd_str):
    results = os.popen(cmd_str).read()
    return results


texts: Counting integers that are within intervals

texts:
I am looking for a more efficient way than bruteforcing my way through in the following problem in python 3.

Problem statement:

Input:

An array of n integers, scores, where each score is denoted by scores_j
An array of q integers, lowerLimits, where each lowerLimits_i denotes
the lowerLimit for score range i.
An array of q integers, upperLimits, where each upperLimits_i denotes
the upperLimit for score range i.

Output: A function that returns an array of Q integers where the value at each index i denotes the number of integers that are in the inclusive range [lowerLimits_i, upperLimits_i].

Constraints:

1 ≤ n ≤ 1e5
1 ≤ scores_j ≤ 1e9
1 ≤ q ≤ 1e5
1 ≤ lowerLimits_i ≤ upperLimits_i ≤ 1e9

Example:
Given scores= [5, 8, 7], lowerLimits = [3, 7], and upperLimits = [9, 7]
I want to check how many of the integers are contained in each interval (inclusive). In this examples: intervals are [3,9] and [7,7], and the result would be [3, 1].

My code looks like this:

def check(scores, lowerLimits, upperLimits):
   res = []
   for l, u in zip(lowerLimits, upperLimits):
       res.append(sum([l <= y <= u for y in scores]))
   return res
if __name__ == "__main__":
   scores= [5, 8, 7]
   lowerLimits = [3, 7]
   upperLimits = [9, 7]

   print(check(scores, lowerLimits, upperLimits))


texts: Elegant way to alter datasets with explicit filters

texts:
I would like to write a small helper to filter datasets. Each dataset is a dictionary and some filters I want to apply are common to all the datasets.

That my needs, I wrote this following pattern:

class Dataset(dict):
    """Just a regular dictionary that can be filtered using filters."""
    _filters = []
    def add_filter(self, filter):
        self._filters.append(filter)

    def apply_filters(self):
        for f in self._filters:
            f(self)

class Filter(object):
    """A callable class that filter a dictionary with the _filter method""".
    def __init__(self, keys, **kwargs):
        self.keys = keys
        self.kwargs = kwargs

    def __call__(self, dictionary):
        """Filter a dictionary."""
        self._filter(dictionary)

    def _filter(self, dictionary):
        """Must be overloaded."""
        pass

class PassTrough(Filter):
    pass

class DropIfEmpty(Filter):
    def _filter(self, dictionary):
        for k in self.keys:
            if not dictionary.get(k):
                dictionary.pop(k)

class MoveInSubkey(Filter):
    def _filter(self, dictionary):
        d = dictionary[self.kwargs['subkey']] = dict()
        for k in self.keys:
            d[k] = dictionary[k]
            dictionary.pop(k)

ds = Dataset({'foo': 42, 'bar': 23, 'min': 0, 'max': 100, 'empty': None})

ds.add_filter(PassTrough([]))
ds.add_filter(DropIfEmpty(['empty']))
ds.add_filter(MoveInSubkey(['min', 'max'], subkey='range'))

ds.apply_filters()

Is that implementation ok, overkill, or should I turn myself to an existing data-filtering-engine that I don't know the existence yet?

Later on, I would like to use a more complex definition for my Dataset class where the filters I want to apply can be initially set like this:

class Foo(DataReader):
    __datasource__ = 'meta/foo.yml'
    __filters__ = [
        DropIfEmpty('foo', 'bar'),
        FilterThis('baz'),
        MoveInSubkey('range', ('min', 'max')),
    ]


texts: Idiomatic way to mutate array while using Swift dispatch groups

texts:
When keeping track of various pieces of information in a variable when using a dispatch group, I've fallen into a pattern of protecting the variable using a serial queue, and then ultimately notifying on that queue to do something with the final value. Is there a more idiomatic way to protect things?

Here's an example of what I mean that can be run in a Playground:

import Foundation

func uploadAll() {
    func mockUpload(_ delay: TimeInterval, _ queue: DispatchQueue = DispatchQueue(label: "mockUpload", attributes: .concurrent), block: @escaping () -> Void) {
        let deadline = DispatchTime.now() + delay
        queue.asyncAfter(deadline: deadline, execute: block)
    }

    let resultQueue = DispatchQueue(label: "resultQueue")
    var results: [Int] = []

    let group = DispatchGroup()

    for i in 0..<5 {
        group.enter()
        mockUpload(TimeInterval(Int.random(in: 1...3))) {
            resultQueue.async {
                results.append(i)
                group.leave()
            }
        }
    }

    group.notify(queue: resultQueue) {
        print("results: \(results)")
        DispatchQueue.main.async {
            // And maybe do something on the main queue...
        }
    }
}

uploadAll()

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true


texts: JavaScript syntax: bucketing based on days (today, yesterday and past)

texts:
I am trying to create three buckets of objects. Today, yesterday and past. I am wondering can the following be done in a more concise way in pure JavaScript without any libraries?
const [todayBucket, yesterdayBucket] = [0, 1].map(offset =>
  recordings.filter(({ createdOn }) =>
    moment(createdOn).isSame(moment().add(-offset), 'day'),
  ),
);
const pastBucket = recordings.filter(
  recording => ![...todayBucket, ...yesterdayBucket].includes(recording),
);


texts:
The program below is about finding the values below the percentage and splitting them into five different output files. This works great for small input data files. But when I am trying to run it for a big data it takes ages to compute. Any suggestions on optimizing the program so that I can get fast computation?

#seperate by col 5
import numpy as np
import os
import re
import math
import csv
import sys
import time
import multiprocessing
from scipy import stats

curdir = 'Tools/'
inputdir = 'input/'
filename = 'input'
outputdir = 'output/'

def seperate(filename):
    print "Begin seperating File: %s" % filename
    dtype = np.dtype([('id1',str,12),('id2',str,12),('c1',int),('c2',int),('c3',float)])
    data = np.loadtxt(curdir + inputdir + filename,dtype=dtype)
    col = 'c3'
    col_data = np.array(data[:][col])
    cache = {}
    def get_per(per):
            if(cache.has_key(per)):
                return cache.get(per)
            else:
                r = 100 - stats.percentileofscore(col_data,per)
                cache[per] = r
                return r
    o1 = file(curdir + outputdir+ filename + '_0_20','w')
    o2 = file(curdir + outputdir+ filename + '_20_40','w')
    o3 = file(curdir + outputdir+ filename + '_40_60','w')
    o4 = file(curdir + outputdir+ filename + '_60_80','w')
    o5 = file(curdir + outputdir+ filename + '_80_100','w')
    for line in data:
        per = get_per(line[col])
        output_format = "%s %s %d %d %.1f\n"
        output_data = (line['id1'],line['id2'],line['c1'],line['c2'],line['c3'])
        if per>=0 and per < 20:
            o1.write(output_format % output_data)
        elif per>=20 and per<40:
            o2.write(output_format % output_data)
            pass
        elif per>=40 and per<60:
            o3.write(output_format % output_data)
            pass
        elif per>=60 and per<80:
            o4.write(output_format % output_data)
            pass
        elif per>=80 and per<=100:
            o5.write(output_format % output_data)
            pass
    o1.close()
    o2.close()
    o3.close()
    o4.close()
    o5.close()

    print "Finish seperating File: %s" % filename

ps = []
print "Reading Files"
for parent,dirNames,fileNames in os.walk(curdir+inputdir):
    if fileNames:
        #multi_process
        print fileNames
        for fileName in fileNames:
            m = re.match(r'^(?!\.)',fileName)
            if m:
                ps.append(multiprocessing.Process(target=seperate,args=(fileName,)))

#runing by multiple processes
for p in ps:
    p.start()
for p in ps:
    p.join()


texts: Select data from csv and make associative array

texts:
I've got a .csv file with ZIP codes containing the city and its sub-districts

67401,City 1,district_a
67401,City 2,district_b
67401,City 3,district_c
67401,City 3,district_d
67401,City 3,district_e
67401,City 3,district_f
67401,City 3,district_g
67401,City 3,district_h
67401,City 3,district_i
67401,City 3,district_j
67401,City 3,district_k
67401,City 3,district_l
67401,City 3,district_m
67401,City 3,district_n
67401,City 3,district_o
67401,City 3,district_p
67401,City 3,district_q
67401,City 3,district_r
67401,City 3,district_s
67401,City 4,district_t
67401,City 5,district_u

67501,City 6,district_v
67501,City 7,district_w
67501,City 8,district_x
67501,City 8,district_y
67501,City 8,district_z

And I need to put it in an array, where I can select/search by the zip code (67401, 67501, etc.) and return these results as an associative array in this format, so I can populate a select control.

For example I want to look-up all the Cities and its districts with zip code 67401 I need this result:

"City 1" => [
    district_a => district_a
],
"City 2" => [
    district_b => district_b
],
"City 3" => [
    district_c => district_c
    district_d => district_d
    district_e => district_e
    district_f => district_f
    district_g => district_g
    district_h => district_h
    district_i => district_i
    district_j => district_j
    district_k => district_k
    district_l => district_l
    district_m => district_m
    district_n => district_n
    district_o => district_o
    district_p => district_p
    district_q => district_q
    district_r => district_r
    district_s => district_s
],
"City 4" => [
    district_t => district_t
],
"City 5" = [
    district_u => district_u
]

Right now I've got this working code, but I'm sure there has to be a simpler way to achieve it.

<?php
$zipcode = '67401';

$a = file("zip.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$a = array_map(function ($i) {return explode(',', $i); }, $a);
$a = array_filter($a, function ($i) use ($zipcode) { return $i[0] == $zipcode; });

$b = [];
$i = 0;
foreach ($a as $key => $value) {
    $b[$i++] = [
        'city' => $value[1],
        'district'  => $value[2],
    ];
}

$c = [];

foreach($b as $key => $item) {
   $c[$item['city']][$key] = $item;
}

ksort($c, SORT_REGULAR);

$d = [];
foreach($c as $key => $value) {
    $subarray = [];
    foreach($value as $s_key => $s_val) {
        foreach($s_val as $ss_key => $ss_val) {
            $subarray[$ss_val] = $ss_val;
        }
    }
    $d[$key] = $subarray;
}

$myresult = $d;
?>


texts:
https://leetcode.com/problems/find-pivot-index/
Question:

Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

My answer:
import java.util.HashMap;

class Solution {
    public int pivotIndex(int[] nums) {
        int runningTotal = 0;
        HashMap<Integer, Integer> resultsMap = new HashMap<Integer, Integer>();
        int numLength = nums.length;
        //run through backwards so leftmost index is returned
        for(int i = numLength -1; i >= 0; i-- ){
            int neededTotal = runningTotal*2 + nums[i];
            resultsMap.put(neededTotal, i);
            runningTotal += nums[i];
        }
        Integer resultIndex = resultsMap.get(runningTotal);
        if(resultIndex == null){
            return -1;
        }else{
            return resultIndex;
        }
    }
}

The suggested answer on leetcode instead runs through the array to get the total sum, then runs through again to find the appropriate element - and on leetcode submission my answer comes back as slower.
However, when I've tried a quick micro-benchmark for myself, it seems as if using the hashmap, in my version, is quicker on average than running through the array twice.
I messed up the benchmark - why is my version so much slower?
Suggested leetcode answer:
public class ListPivot {
    public int pivotIndex(int[] nums) {
        int sum = 0, leftsum = 0;
        for (int x: nums) sum += x;
        for (int i = 0; i < nums.length; ++i) {
            if (leftsum == sum - leftsum - nums[i]) return i;
            leftsum += nums[i];
        }
        return -1;
    }
}


texts: Atomic fixed-size parallel std::vector wrapper

texts:
I'm in need of a simple wrapper for a fixed-size std::vector that can ensure atomic insertion.

Since my only real problem is with atomic insertion and I know beforehand the amount of entries it will have, I don't need any other parallelism related feature.

I am happy to have the initial allocation (std::vector::resize) run from the main thread, so it shouldn't need anything fancy.

Although there are great, free to use parallel vectors available, I think that my particular use case, being fixed size shouldn't require any fancy library (e.g. TBB).

I was thinking about something along these lines:

template <typename T>
class AtomicFixedSizeVector {
public:

    // a bunch of passthrough methods here...

    inline void reserve(size_t count) {
        m_data.resize(count);
        //m_data.reserve(count);
    }

    inline void push_back(const T& entry) {
        size_t index = m_count.fetch_add(1, std::memory_order_relaxed);
        m_data[index] = entry;
    }

    // I don't think I need this at all, but just in case
    inline size_t size()const {
        return m_count.load(std::memory_order_relaxed);
    }

private:
    std::vector<T> m_data;
    std::atomic<size_t> m_count;
};

It needs to be a wrapper to std::vector since the other parts of code take one.

I thought I'd ask this question as my knowledge of atomics is rather limited, and although it seems ok when executed, it's hard to tell if it's actually going well or I'm being lucky multiple times in a row.

Another question that I have is if I can trust std::vector::reserve to do the allocation on the spot or if it's implementation-dependent. I'm asking because if it allocates on the spot I don't need to override the behavior of std::vector::size and can use a passthrough wrapper there, too.

Please note that this is not a premature optimization but rather a post-mortem one, my insertion could be parallelized but only if it ends up adding onto a single block of entries.

This std::vector block of entries will only store uint32_t in case it helps.

Edit:

The current use case is to insert from multiple threads, but this was designed knowing beforehand that by the time the data is accessed, the threads will have been joined.

There is an upper limit on the amount of values to be inserted so the vector will be preallocated before insertion.


texts: Finding the candidate with the majority of ballots

texts:
I am doing a code wars problem and so far I have managed to loop through a collection to find the "winner" (defined by the String that appears more than collection.size()/2). However, my code times out and isn't efficient enough. How can I make this more efficient?

import java.util.List;

public class BallotsCounter1 {
    static String winner;
    static String current;
    static int count;

     public static String getWinner(final List<String> listOfBallots) {
         int totalSize = listOfBallots.size();
         count = listOfBallots.size()/2;
         if (listOfBallots.isEmpty() == true){
             return null;
         } else {
             for (int i = 0; i < listOfBallots.size(); i++){
                 int running = 0;
                 current = listOfBallots.get(i);
                 for (int j = 0; j < listOfBallots.size(); j++){
                     if (listOfBallots.get(i) == listOfBallots.get(j)){
                         running++;
                     }
                 }
                 if (running > count){
                     count = running;
                     winner = current;
                 }
             }
         }
         if (count > (listOfBallots.size()/2)){
             return winner;
         } else {
             return null;
         }

     }
}


texts: Call a text-editor from within a Python script to get user input

texts:
Motivation

I'd like to know how integrate the use of text editors (e.g. emacs, vim, etc.) into command-line Python programs.

Features

I'd like to be able to do the following:

Call a text editor from within a program in order to edit a file or buffer
Regain control after the text editor exits
Use temporary files, i.e. don't leave anything lying around after the program exits
Prepopulate the file or buffer with data
Get the edited text back for use in the program

Implementation

I wrote a small module named callvim.py (betraying my preferred choice of text editor) which creates a temporary file, populates it with some text, opens it with a text editor (defaults to vim), and prints the modified text:

#!/usr/bin/env python
# -*- encoding: ascii -*-
"""callvim.py

Demonstrates calling a text-editor (e.g. Vim) from within a Python script,
including passing input to the editor and reading output from the editor.
"""

import tempfile
import os
from subprocess import call

# Get the text editor from the shell, otherwise default to Vim
EDITOR = os.environ.get('EDITOR','vim')

# Set initial input with which to populate the buffer
initial_message = "Hello world!"

# Open a temporary file to communicate through (`tempfile` should avoid any filename conflicts)
#
# NOTE: Don't autodelete the file on close!
#       We want to reopen the file incase the editor uses a swap-file.
#
with tempfile.NamedTemporaryFile(suffix=".tmp", delete=False) as tf:

    # Write the initial content to the file I/O buffer
    tf.write(initial_message)

    # Flush the I/O buffer to make sure the data is written to the file
    tf.flush()

    # Open the file with the text editor
    call([EDITOR, tf.name])

# Reopen the file to read the edited data
with open(tf.name, 'r') as tf:

    # Read the file data into a variable
    edited_message = tf.read()

    # Output the data
    print(edited_message)


texts: A* in Clojure - trickier than I expected

texts:
While working through some coding puzzles to brush up on Clojure, I encountered the need to use A* on some search problems.  I tried to implement it from first principles/memory and that didn't go well, so I looked for existing implementations and found two (Joy of Clojure and cgrand's) but they were a little difficult to follow (for me) so I attempted to create my own.  In the end it actually looks pretty close to cgrand's implementation.

I think this works as expected (using an example from here to verify), but just wanted to post to see if anybody can point out any glaring omissions / oversights.  I've implemented this before in Python but it turned out to be quite different without using mutation.

The only issue I see is that I generate neighbors before testing whether I've already seen the node, so there is some inefficiency there. I couldn't figure out a good way to avoid this since my neighbor generation / filtering occurs in one step during the recursive call, whereas in languages allowing mutability you would process each child separately and you can test if it exists in the visited set each time.

(defn a-star-search
 [start neighbor-func goal? remain-cost path-cost]
  (loop [q (conj (sorted-set) [0 start])
         cost-so-far {start 0}
         came-from   {start nil}]
    (if-let [[node-cost node :as node-state] (first q)]
      (if (goal? node)
          (reverse (take-while (complement nil?) (iterate came-from node)))
          (let [neighbors (neighbor-func node)
                prev-node (came-from node)
                prev-cost (cost-so-far node)
                cheaper (remove #(< (cost-so-far % Double/POSITIVE_INFINITY)
                                    (+ prev-cost (path-cost node %)))
                                neighbors)
                new-nodes (map #(vector (+ prev-cost
                                           (path-cost node %)
                                           (remain-cost %)) %)
                               cheaper)]
            (recur (into (disj q node-state) new-nodes)
                   (->> cheaper
                        (map #(vector % (+ prev-cost (path-cost node %))))
                        (into cost-so-far))
                   (into came-from (map (juxt identity (fn [_] node)) cheaper)))))
      "no more neigbors")))

(def graph {:s {:a 1 :b 4}
            :a {:b 2 :c 5 :g 12}
            :b {:c 2}
            :c {:g 3}})

(def h-vals {:s 7 :a 6 :b 2 :c 1 :g 0})

 (a-star-search :s
             #(-> % graph keys)
             #(= :g %)
             h-vals
             (fn [from to] (get-in graph [from to])))


texts: opening a text file and building a dictionary

texts:
Need to write a function that takes an open file as the only parameter and returns a dictionary that maps a string to a list of strings and integers.

each line in the text will have a username, first name, last name, age, gender and an e-mail address. The function will insert each person's information into a dictionary with their username as the key, and the value being a list of [last name, first name, e-mail, age, gender].

basically what im trying to do is open a text file that contains this:

           ajones Alice Jones 44 F alice@alicejones.net

and return something like this:

          {ajones: ['Jones', 'Alice', 'alice@alicejones.net', 44, 'F']}

so far i have done this, but is there any other easier way?

def create_dict(file_name):
    '''(io.TextIOWrapper) -> dict of {str: [str, str, str, int, str]}

    '''
    newdict = {}
    list2 = []
    for line in file_name:
        while line:
            list1 = line.split() #for a key, create a list of values
    if list2(0):
        value += list1(1)
    if list2(1):
        value += list1(2)
    if list2(2):
        value += list1(3)
    if list2(3):
        value += list1(4)
    newdict[list1(0)] = list2

    for next_line in file_name:
        list1 = line.split()
        newdict[list1(0)] = list1
    return newdict

def helper_func(fieldname):
    '''(str) -> int
    Returns the index of the field in the value list in the dictionary
    >>> helper_func(age)
    3
    '''

    if fieldname is "lastname":
        return 0
    elif fieldname is "firstname":
        return 1
    elif fieldname is "email":
        return 2
    elif fieldname is "age":
        return 3
    elif fieldname is "gender":
        return 4


texts:
Word Wrap problem in short:

  Given n words and a line length, break the words into lines in such a manner that minimizes the sum of the costs of all the lines. Consider the cost of each line being (free space in the line)^2.

I'm supposed to implement an algorithm with \$O(n)\$ time complexity and \$O(n^2)\$ space complexity. The way I see mine is \$O(n^2)\$ in time and \$O(n^3)\$ in space, but when looking for better solutions I found people describing the same procedure I followed as  \$O(n)\$ and \$O(n^2)\$. For example, here and in the full description of the problem linked above.

Are they simply ignoring the cost of calculating the penalty cost of each line (they call it "badness" and I "cost")? Because inside their main \$O(n^2)\$ loop they call the badness function that contains a \$O(n)\$ loop inside. Am I supposed to take into account only the cost of the dynamic programming part? If not, what am I doing effectively different? How could I improve it?

using namespace std;

// all vectors start to be filled in 1
void solve(vector<string> words, int line_width){
    int i, j, k;
    int n = words.size() - 1;  // number of words
    int opt[n+1]; // opt[j] = min cost for a text ending in words[j]
    int cost[n+1][n+1]; // cost[i][j] cost of adding a line from words[i] to words[j]
    int parent[n+1]; // parent[j] = i means that the optimal line ending in j starts in i

    // fills cost
    for(i = 1; i <= n; ++i){
        for(j = i; j <= n; ++j){
            int filled = j-i; // number of spaces added between words i and j
            for(k = i; k <= j; ++k){
                filled += words[k].length();
            }
            if(filled > line_width){
                cost[i][j] = INF; // if such a line is not possible
            } else {
                cost[i][j] = (line_width - filled) * (line_width - filled);
            }
        }
    }

    // fills opt
    opt[0] = 0;
    for(j = 1; j <= n; ++j){
        opt[j] = INF;
        for(i = 1; i <= j; ++i){
            if(opt[i-1] + cost[i][j] < opt[j]){
                opt[j] = opt[i-1] + cost[i][j];
            }
        }
    }

    // prints solution backwards (because of the order 'parent' was filled)
    int end = n;
    string solution = "";
    while(end > 0){
        solution = words[end] + '\n' + solution;
        for(i = end - 1; i >= parent[end]; --i){
            solution = words[i] + ' ' + solution;
        }
        end = parent[end] - 1;
    }
    cout << solution;
}


texts:
I am creating a GUI library to better learn C++ and wanted to see if there is anything to improve/simplify.

And I also wanted to be able to call an event of a parent and then for it to iterate all its children and those children to iterate their children and so forth, but I did not want to have a foreach loop in every subclass thus the IterateEvents loop. Is there a better way?

#pragma once

#include <functional>
#include <memory>
#include <vector>

#include <iostream>

namespace bui {
    class Element {
    public:
        int x = 0;
        int y = 0;
        int width = 0;
        int height = 0;
        Element* parent;
        std::function<void(void)> function;

        std::vector<Element*> children;

        Element(int x, int y, int width, int height, Element* parent) {
            this->x = x;
            this->y = y;
            this->width = width;
            this->height = height;

            if (parent != nullptr) {
                parent->children.push_back(this);
            }
        }

        ~Element() {

        }

        template <typename T>
        bool pointInElement(T x, T y) {
            return (x > this->x && y > this->y && x < this->x + this->width && this->y < this->y + this->height);
        }

        virtual void Event() = 0;
        virtual void Draw() = 0;

        void IterateEvents() {
            this->Event();
            for (auto &i : children) {
                i->Event();
            }
        }
    };

    extern std::vector<Element*> TopLevelWindows;

    class TopLevelWindow : public Element {
    public:
        TopLevelWindow(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
            TopLevelWindows.push_back(this);
        }

        void Event() {
            std::cout << "TopLevelWindow\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~TopLevelWindow() {

        }
    };

    class Window : public Element {
    public:
        Window(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
        }

        void Event() {
            std::cout << "Window\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~Window() {

        }
    };

    class Button : public Element {
    public:
        Button(int x, int y, int width, int height, Element* parent) : Element(x, y, width, height, parent) {
        }

        void Event() {
            std::cout << "Button\n";
        }

        void Draw() {
            //Draw stuff
        }

        ~Button() {

        }
    };
}


texts: Finding the duplicate with an array with 1,000,000 integers between 1 and 1,000,000

texts:
I recently had an interview and got to phase 2 which is a coding assessment. One of the questions was:

  Given an array with 1,000,000 integers between 1 and 1,000,000, one integer is in the array twice. Find the duplicate.

I failed the interview and was wondering what improvements do I need.

/// <summary>
/// Assuming that there is no space constraint,
/// I used a HashSet to find the duplicate.
/// If the duplicate is found, assign that number as the return value
///
/// </summary>
/// <param name="givenArray">1,000,000 sized array containing ints between 1 - 1000000</param>
/// <returns>The duplicate number</returns>
public static int findDuplicate(int[] givenArray)
{
    // This hashset will be filled with non duplicated numbers.
    HashSet<int> nonDuplicateContainer = new HashSet<int>();
    int duplicate = -1;

    for (int i = 0; i < givenArray.Length; i++)
    {
        if (!nonDuplicateContainer.Add(givenArray[i])) {
            duplicate = givenArray[i];
            break;
        }
    }

    return duplicate;
}

Test:

/// <summary>
/// Testing with the correct duplicated number
/// </summary>
[TestMethod()]
public void FindDuplicateTestCorrectGivenDuplicate()
{
    int[] testArray = InitializeOneMillionSizedArray(106500);

    int testDuplicateNumber = BlueWolfSolutions.findDuplicate(testArray);

    Assert.AreEqual(106500, testDuplicateNumber);
}

/// <summary>
/// Testing with the incorrect duplicated number
/// </summary>
[TestMethod()]
public void FindDuplicateTestWrongGivenDuplicate()
{
    int[] testArray = InitializeOneMillionSizedArray(453234);

    int testDuplicateNumber = BlueWolfSolutions.findDuplicate(testArray);

    Assert.AreNotEqual(25, testDuplicateNumber);
}


texts:
Problem:

  Given a square or rectangular matrix, print its element in spiral
  order.

  For example, if input matrix is this:

    1    2   3   4
    5    6   7   8
    9   10  11  12
    13  14  15  16

  Output should be:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

This code assumes a matrix of 6X5. I do feel it can look more elegant or functional. I want to get rid of vars.

import scala.util.Random

object MatrixSpiral extends App {
  val matrix = Array.fill(6)(Array.fill(5)(Random.nextInt(10)))
  matrix foreach (row => println(row.mkString(",")))

  var rows = 6
  var cols = 5
  var r = 0
  var c = 0
  var startR = 0
  var startC = 0

  println
  while (r < rows && c < cols) {
    for (i <- c until cols) {
      c = i; print(matrix(r)(i) + " ")
    }
    r += 1
    for (j <- r until rows) {
      r = j; print(matrix(j)(c) + " ")
    }
    c -= 1
    for (k <- c to startC by -1) {
      c = k; print(matrix(r)(k) + " ")
    }
    r -= 1
    for (l <- r to startR + 1 by -1) {
      r = l; print(matrix(l)(c) + " ")
    }

    rows -= 1
    cols -= 1
    c += 1
    startR = r
    startC = c
  }

}


texts: Tough List Comprehension Split Letters and Numbers

texts:
So, another challenge from my professor. I've finished it, but wanted to get some feedback, and see how other people might work this problem.

  Assume you have a string, such as "Hello 34215 World 5620 From 384 Bloomington"

  Use list comprehension to separate the words from the numbers, and the numbers from the words. Then order the numbers from smallest to largest. Print out these words and numbers separated by a "|". The output for the example given above would be:

>>>
Hello World From Bloomington | 012233445568

The challenge is to write the code in two lines, one of the lines being the definition of the string.

This is what I wrote:

string = "Hello 34215 World 5620 From 384 Bloomington"
print str(" | ".join(["".join([letter for letter in string if letter.isalpha() or letter.isspace()]), "".join(sorted([num for num in string if num.isdigit()]))])).replace("  ", " ")

It works! The output is identical to the output displayed. But, I'd love to hear feedback about how this is done, or if there are any pieces of redundant code, etc. I don't use lambda, map, set, etc. nor do I import any libraries, but if you find that there is a way to do it with any of those pieces, feel free to share!


texts: Simple LRU cache with an expiration time

texts:
How can I improve the performance of the code below?

package utils.session;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * A very simple LRU cache implementation, used for our server side session
 * management.
 * </p>
 *
 * @author royguo@abcdefg.com
 */
public class SessionCache {
  private static ConcurrentHashMap<String, Entry> cache = new ConcurrentHashMap<>();

  static class Entry {
    private final Object value;
    private final Long expiration;
    private Long lastUseTime;

    public Entry(Object value, Long expiration) {
      this.value = value;
      this.expiration = expiration;
      this.lastUseTime = System.currentTimeMillis();
    }

    public boolean isExpired() {
      return (lastUseTime + expiration) < System.currentTimeMillis();
    }

    public Object getValue() {
      return this.value;
    }

    public void updateUseTime() {
      this.lastUseTime = System.currentTimeMillis();
    }
  }

  static {
    /**
     * Scan our LRU cache every 30 minutes, remove expired keys.
     */
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
            for (String key : cache.keySet()) {
              if (cache.get(key).isExpired())
                cache.remove(key);
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(30));
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }).start();
  }

  /**
   * Put a new object into cache, and speicify its expiration time. Everytime we
   * get the object from cache, its expiration time would be updated.
   */
  public static void put(String key, Object value, Long expiration) {
    cache.put(key, new Entry(value, expiration));
  }

  /**
   * Get instance from cache, no need to be thread-safe.
   */
  public static Object get(String key) {
    Entry entry = cache.get(key);
    if (!entry.isExpired()) {
      entry.updateUseTime();
      return entry.getValue();
    } else {
      cache.remove(key);
      return null;
    }
  }
}


texts:
I have tested all the cases of how a line could be

vertically
horizontally
has a slope that's positive or less than 1

The function works, but I would like it reviewed, such as if there are overflows, etc.

// Draw line using DDA Algorithm
void Graphics::DrawLine( int x1, int y1, int x2, int y2, Color&color )
{

    float xdiff = x1-x2;
    float ydiff = y1-y2;
    int slope  = 1;
    if ( y1  == y2  )
    {
        slope = 0;
    }
    else if (  x1 == x2 )
    {
        slope = 2; // vertical lines have no slopes...
    }
    else
    {
        slope = (int)xdiff/ydiff;
    }

    if ( slope <= 1 )
    {
        int startx = 0;
        int endx   = 0;
        if ( x1 > x2 )
        {
            startx = x2;
            endx   = x1;
        }
        else
        {
            startx = x1;
            endx   = x2;
        }

        float y = y1; // initial value
        for(int x = startx; x <= endx; x++)
        {
            y += slope;
            DrawPixel(x, (int)abs(y), color);
        }
    }

    else if ( slope > 1 )
    {
        float x = x1; // initial value
        for(int y = y1;y <= y2; y++)
        {
            x += 1/slope;
            DrawPixel((int)x, y, color);
        }

    }

}


texts:
dynamic_pointer_cast is only implemented for std::shared_ptr, I need it for unique pointers.
The wrinkle is that dynamic_casting a pointer could fail (yield nullptr), what to do in that case? I decided that in that case i would like the original pointer to remain intact. So i have implemented the following:
template< typename T, typename S >
inline std::unique_ptr<T> dynamic_pointer_cast(std::unique_ptr<S>&& ptr_)
{
    T* const converted_ptr = dynamic_cast<T*>(ptr_.get());
    if (!converted_ptr)
        // cast failed, leave input untouched, return nullptr
        return nullptr;

    // cast succeeded, clear input, return casted ptr
    ptr_.release();
    return std::unique_ptr<T>(converted_ptr);
}

Testing code:
#include <memory>
int main(int argc, char **argv)
{
    std::unique_ptr<Base> basePtr = std::make_unique<Derived1>();
    // this should fail, basePtr should remain non-empty, return should be empty
    auto deriv2Ptr = dynamic_pointer_cast<Derived2>(std::move(basePtr));
    // this should succeed, basePtr should become empty, return should be non-empty
    auto deriv1Ptr = dynamic_pointer_cast<Derived1>(std::move(basePtr));

    return 0;
}

Is this safe? Does the interface make sense? For the latter question: I decided to take an R-value ref so users have to write std::move, denoting pointer will be emptied. But then it may not if the cast fails... Normal ref is the other option, but then its less clear at the call site that the unique_ptr will likely be cleared.


texts:
Is it a bad idea to use the notfound callback like this? If so, why not? (bad scope/closure? I'm a noob node.js dev.)
Is it a bad idea to use the saveCallback callback like this? I have a feeling it's dangerous, but I don't want to declare saveCallback before queryCallback as save happens after query.

create: function(registerDetails, found, notfound) {

    var query = db.User
        .findOne({ username: registerDetails.username });

    var queryCallback = function(err, user) {
        if (user != null) found(user);
        else {
            var newUser = new db.User();
            newUser.username = registerDetails.username;
            newUser.password = registerDetails.password;
            newUser.save(saveCallback);
        }
    };

    var saveCallback = function(err, user) {
        notfound(user);
    };

    query.exec(queryCallback);
},

What's a more elegant way of writing this so that

// 1) don't nest like crazy.
.exec(function(){
    if () {
        newUser.save(function(){
            notfound(); // really? because we know node.js will ever chain 2 callbacks max. </sarcasm>
        }
    }

// 2) don't make people read "down and back up"
var saveCallback = function() {
    // Dejavu... I've been here before...
};
var queryCallback = function() {
    saveCallback(); // Back from last line, ohhhhh this is what saveCallback used for. Go back up.
};
query.exec(queryCallback); // Ohhhhh so that's what it's used for. Now go back up and read what it does.


texts: Duplicated code in web service consumption

texts:
I have a set of classes that abstract away calls to a set of web services. I have 6 classes in this particular group, 4 of which contain a simple function that, while small, is still duplicated. What happens is that if some exception or business rule violation happens in the service, they package it up as a fault object in the response. Otherwise, the fault object is null. As a result, the functions simply check to see if that object is not null and, if so, take the reason provided and throw an exception up the chain. So in one class, it might look like

private void ThrowIfContainsFault(AlphaResponse response)
{
    if (response.Fault != null)
    {
        throw new WhateverException(response.Fault.reasonText);
    }
}

And then the other classes, the response object will be of a different type, but the Fault property is the same and the block of code is the same.

private void ThrowIfContainsFault(BravoResponse response)
private void ThrowIfContainsFault(CharlieResponse response)
private void ThrowIfContainsFault(DeltaResponse response)

(Note: These class names are changed for readability, there is no common ancestor for these response objects.)

My first thought is that I could simply change the functions to receive the Fault object directly and forget the response object, and that's valid. But my overall concern is that while these methods literally do the same thing, the classes themselves are not particularly related, so introducing a common base hierarchy for a single (protected) method does not strike me as a suitable fit.

Here's my throwaway thought that I'm not even sure I like:

Define an empty interface that each class can "implement," then define an extension method against that interface.

internal interface IFaultThrower
{
}

internal static class IFaultThrowerExtension
{
    internal static void ThrowIfNotNull(this IFaultThrower thrower, Fault fault)
    {
        if (fault != null)
        {
            throw new WhateverException(fault.reasonText);
        }
    }
}

This would allow the related classes to get rid of their own private methods and invoke this common one.

 // this.ThrowIfContainsFault(response);
 this.ThrowIfNotNull(response.Fault);

Again, not sure I like it, but I'm also not sure I like the same general idea creeping into multiple classes, either.


texts: Pandas replace rare values in a pipeline

texts:
A common preprocessing in machine learning consists in replacing rare values in the data by a label stating "rare". So that subsequent learning algorithms will not try to generalize a value with few occurences.
Pipelines enable to describe a sequence of preprocessing and learning algorithms to end up with a single object that takes raw data, treats it, and output a prediction. scikit-learn expects the steps to have a specific syntax (fit / transform or fit / predict). I wrote the following class to take care of this task so that it can be run inside a pipeline. (More details about the motivation can be found here: pandas replace rare values)
Is there a way to improve this code in term of performance or reusability ?
class RemoveScarceValuesFeatureEngineer:

    def __init__(self, min_occurences):
        self._min_occurences = min_occurences
        self._column_value_counts = {}

    def fit(self, X, y):
        for column in X.columns:
            self._column_value_counts[column] = X[column].value_counts()
        return self

    def transform(self, X):
        for column in X.columns:
            X.loc[self._column_value_counts[column][X[column]].values
                  < self._min_occurences, column] = "RARE_VALUE"

        return X

    def fit_transform(self, X, y):
        self.fit(X, y)
        return self.transform(X)

And the following can be appended to the above class to make sure the methods work as expected:
if __name__ == "__main__":
    import pandas as pd

    sample_train = pd.DataFrame(
        [{"a": 1, "s": "a"}, {"a": 1, "s": "a"}, {"a": 1, "s": "b"}])
    rssfe = RemoveScarceValuesFeatureEngineer(2)
    print(sample_train)
    print(rssfe.fit_transform(sample_train, None))
    print(20*"=")

    sample_test = pd.DataFrame([{"a": 1, "s": "a"}, {"a": 1, "s": "b"}])
    print(sample_test)
    print(rssfe.transform(sample_test))


texts: Function to set nested property by dot-path, like _.set

texts:
As part of a Stack Overflow answer, I whipped up a quick example implementation of a function to set a nested property of an object using a dot notation string. The goal was to show how that could work in a small amount of clean code:

function set (object, property, value) {
  if (typeof property === 'string') property = property.split('.')
  if (property.length > 1) {
    set(object[property[0]], property.slice(1), value)
  } else {
    object[property[0]] = value
  }
}

// Usage:
set(object, 'position.x', 1)

I could have used property.shift() but I wanted to not make the function unnecessarily non-pure and I think that mutating the array would also have made the code harder to follow.

This caused me to get the following comment:

  That own-rolled version has potential prototype pollution problems, has a time complexity problem, and can cause a stack overflow. – Ry-

To which I responded:

  Can you elaborate on the prototype pollution and time complexity? Is the latter about the repeated slice? Regarding stack overflow it's of course true but we'd have to have an insanely long property path, I'm trading that chance for simplicity.

  This version also doesn't check for existence of sub-paths obviously, so yes I could do for example set(something, { length: 123 }, x) or set(something, { slice: 'oh no' }, x) and such and it would crash, but it would also crash on set(something, 'nonexisting.abc', x) at the moment – CherryDT

I then decided to remove the code for the time being and instead open this question here, because I'd be interested to get more feedback about that but the SO question is not the right location for it.

So, I'd be happy to hear your thoughts about it.

EDIT: I realize now, the prototype pollution issue is in case of property being untrusted input, I could write set(something, '__proto__.toString', 'yikes') for example, right? Still, I'd be interested in any other feedback too, now that we are already at it.


texts: Too many JavaScript sort functions to accomplish the same type of sorting

texts:
You can see each list item has multiple attributes data-whatever. The user will choose from a dropdown box on how things should be sorted and the appropriate method is called. Is eval() the most appropriate choice for this or is there a better way?

$('#sort-options').change(function() {
    var sortType = $(this).val();
    var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
    var $listItems = $('li', $selectedList);

    //Sort
    var sortFunction = null;
    switch (sortType) {
    case 'custom':
        $listItems.sort(sortCustom);
        break;
    case 'breed':
        $listItems.sort(sortBreed);
        break;
    case 'hatch':
        $listItems.sort(sortHatch);
        break;
    case 'laid':
        $listItems.sort(sortLaid);
        break;
    default:
        $listItems.sort(sortCustom);
    }

    //Empty UL
    $selectedList.empty();
    //Repopulate UL
    $.each($listItems, function(index, $listItem) {
        $selectedList.append($listItem);
    });
    });

    function sortCustom(a, b) {
    return $(a).attr('data-sort-order') - $(b).attr('data-sort-order');
    }

    function sortBreed(a, b) {
    return $(a).attr('data-breed') - $(b).attr('data-breed');
    }

    function sortHatch(a, b) {
    return $(a).attr('data-hatch') - $(b).attr('data-hatch');
    }

    function sortLaid(a, b) {
    return $(a).attr('data-laid') - $(b).attr('data-laid');
    }

    //Force initial sort
    $('#sort-options').trigger('change');
}


texts: Fast "index of minimum" for distances to points on single thread

texts:
The problem in simple words: I have three arrays of double values (x-, y- and z-coordinates) and need to find the index of the point which has minimum distance to a reference points. I do not need the actual value of this distance. If the minimum distance is not unique, any index where its value occurs may be returned.

I will be using this function for determining the squared distance between points:

double distSqr(double xa, double ya, double za,
               double xb, double yb, double zb)
{
    double X = xa - xb;
    double Y = xa - xb;
    double Z = xa - xb;

    return X * X + Y * Y + Z * Z;
}

Taking the square root in the final step will not be necessary.

First of all, consider a "naive" implementation where you simply compare the "current" value to all other values, exchanging the "current" value if a smaller value is found:

// Take the three arrays of x-, y-, and z-coordinates filled with arbitrary values.
#define SIZE 20

double cx[SIZE];
double cy[SIZE];
double cz[SIZE];

int min_naive(double x, double y, double z)
{
    double minDist = distSqr(x, y, z, cx[0], cy[0], cz[0]);
    int minIndex = 0;

    for (int i = 1; i < SIZE; i++)
    {
        double d = distSqr(x, y, z, cx[i], cy[i], cz[i]);
        if (d < minDist)
        {
            minDist = d;
            minIndex = i;
        }
    }

    return minIndex;
}

// Finally, determin the index, e.g.
int minInd = min_naive(0, 0, 0);

This does not seem like an optimal solution to me, especially since it might not be fast enough if the loop has to run over all distances where only one comparison happens at each step. Obviously, sooner or later all distances have to be calculated.
Next, I came up with a better solution that first calculates all distances and then compares them in a loop in such a way, that each loop halves the number of possible distances left.
I hoped that the compiler might auto-vectorize this function, instead of using a simple loop over all points, but I have not checked that yet.

This is the code I came up with:

void cmpmv(int lower, int upper, int *inds, double *dists)
{
    double a = dists[lower];
    double b = dists[upper];

    if (a > b)
    {
        inds[lower] = inds[upper];
        dists[lower] = b;
    }
}

int min_better(double kax, double kay, double kaz)
{
    double dists[SIZE];
    int inds[SIZE];
    for (int i = 0; i < SIZE; i++)
    {
        dists[i] = distSqr(kax, kay, kaz, nncx[i], nncy[i], nncz[i]);
        inds[i] = i;
    }

    int div, mod;
    int s = SIZE;
    while (s > 1)
    {
        div = s / 2;
        mod = s % 2;

        for (int i = 0; i < div; i++)
            cmpmv(i, i + div, inds, dists);
        if (mod == 1)
            cmpmv(0, s - 1, inds, dists);

        s = div;
    }

    return inds[0];
}

(Note that this must differentiate the cases where SIZE and later s are not a multiple of 2.)

Are there maybe even better and especially faster ways to implement this?

There are two restrictions:

I only have one thread available.
I have to use arrays/pointers.


texts:
The problem I am referring to is here

So basically it's about shifting an array of ints 1 position to the left and relocating the lost first int in the start of the array to the last position at the right:

\$\mathrm{shiftLeft}(\{6, 2, 5, 3\}) → \{2, 5, 3, 6\}\$

\$\mathrm{shiftLeft}(\{1, 2\}) → \{2, 1\}\$

\$\mathrm{shiftLeft}(\{1\}) → \{1\}\$

Please feel free to review the code below:

public int[] shiftLeft(int[] nums) {
    for(int i = 0, start = 0; i < nums.length; i++)
    {
        if(i == 0)
            start = nums[i];
        if(i == (nums.length -1))
        {
            nums[i] = start;
            break;
        }
        nums[i] = nums[i + 1];
    }
    return nums;
}

Also I would like to get rid of the variable start and try to solve it only using the loop iterator i, any suggestions are welcome.


texts:
I have set alert dialog on textview's onclicklistener, and there I have added some items using array adapter. Now what I want to do is check if the user selects an item from the alert dialog and clicks on submit. It should submit, otherwise not. But as per my if I select or not it displays message fill the details.

 boolean isSetDay = false;
 sp3=(TextView)findViewById(R.id.daydates);
 btnsubmit=(Button)findViewById(R.id.btnreg);

 final String[] items = new String[] {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
 adapter123 = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_dropdown_item, items);

 sp3.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View w) {
      new AlertDialog.Builder(RegistrationForm.this)
      .setTitle("Select Day")
      .setAdapter(adapter123, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            sp3.setText(adapter123.getItem(which).toString());
            isSetDay=true;

          dialog.dismiss();
        }
      }).create().show();
    }
  });
     btnsubmit.setOnClickListener(new OnClickListener()
  {

 @Override
 public void onClick(View v)
 {
    if(emailtext.getText().toString().trim().length() > 0 &&   passtext.getText().toString().trim().length() > 0 && confirmpass.getText().toString().trim().length() > 0 && username.getText().toString().trim().length() > 0 && firstname.getText().toString().trim().length() > 0 && lastname.getText().toString().trim().length() > 0 && isSetDay==true && isSetMonth==true &&    isSetYear==true && isSetPro==true)
{
isSetDay=false;
isSetMonth=false;
isSetYear=false;
isSetPro=false;
new AttemptLogin().execute();

}

  else
 {
    Toast.makeText(getApplicationContext(), "Fill the details", Toast.LENGTH_LONG).show();
 }
  break;
 }
 });


texts:
This code checks if string has correct format for passing to struct. Correct format needs to be [123456789'\t'First Name'\t'Last Name'\t'City]. I didn't know how to enter tabs, so I used '\t'. I use them to separate different word blocks so e.g. first and middle name can be read to a first name in struct.

I wrote alternative version as well (in comments). Which one is more preferable?
How is the correct form to write nested ternary operator

int checkString(char *string, int len)
{

    char *ch;
    int flag = FALSE;
    int i = 0;

    ch = string;

    i = 0;
    /*
    while (ch[i] && ch[i] != '\t') {
        if (isdigit(ch[i])) {
            if (++i == len) {
                flag = ch[i] == '\t' ? TRUE : FALSE;
            }
        } else { ch++; }
    }
    */

    /* ID code needs to be 11 digits */
    for (i = 0; ch[i] && ch[i] != '\t';
        isdigit(ch[i]) ?
        flag = ++i == len ?             // while true
        ch[i] == '\t' ? TRUE : FALSE    // while true
        : FALSE
        : *ch++);

    /* Three tabs is correct */
    if (flag) {
        for (i = 0; ch[i];
        ch[i] == '\t' ?
        flag = ++i == 3 ? TRUE : FALSE
        : *ch++);
    }

    return flag;
}


texts:
My code currently doesn't insert data into MySQL fast enough. However I don't know how to measure the current speed.
def insert():
      mycursor = mydb.cursor()
      plik = input(":::")
      agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")
      sql = "INSERT INTO wyciek (nick, ip) VALUES (%s, %s)"
      for row in agefile:
            mydb.commit()
            data = row.split(':')
            val = (data[0].replace("\n",""), data[1].replace("\n", ""))
            mycursor.execute(sql, val)
      agefile.close()