texts: Checking conditions before allowing a play button to become visible

texts:
I have this code to check a couple conditions before allowing a play button to become visible. Is there anything to do to consolidate this code?

var isNodeWebkit = (typeof process == "object"); // check if using node app
var downloadURL = 'https://www.microsoft.com/getsilverlight/get-started/install/'; // setup download URL variable
var isEncoding = false; // setup isEncoding variable

if (!Silverlight.isInstalled("1.0")) { // check if silverlight is installed
    $('.playbtn').hide();
    $('.videoposter').append('<button class="installbtn" />');
    if (isNodeWebkit) {
        $('.installbtn').on('click', function () { // open silverlight download externally
            require('nw.gui').Shell.openExternal(downloadURL);
            var win = require('nw.gui').Window.get();
            win.close(); return false;
        });
    } else {
        $('.installbtn').click(function () { // open silverlight download in new tab
            window.open(downloadURL, '_blank');
        });
        $(window).focus(function () {
            if (Silverlight.isInstalled("1.0")) {
                $('.installbtn').remove();
                $('.playbtn').show(); checkEncodingFunc();
            } else if (!Silverlight.isInstalled("1.0")) {
                $('.installbtn').remove(); $('.videoposter').append('<button class="installbtn" />');
                $('.playbtn').hide(); $('.encodingbtn').hide();
            }; ;
        });
    };
} else if (Silverlight.isInstalled("1.0")) {
    $(window).focus(function () { // after installing show play button
        if (!Silverlight.isInstalled("1.0")) {
            $('.playbtn').hide(); $('.installbtn').remove(); $('.encodingbtn').remove();
            $('.videoposter').append('<button class="installbtn" />');
            $('.installbtn').click(function () { // open silverlight download in new tab
                window.open(downloadURL, '_blank');
            });
        } else {
            $('.installbtn').remove();
            $('.playbtn').show();
        };
        if (Silverlight.isInstalled("1.0") && isEncoding == true) { checkEncodingFunc(); };
    });
};

var encodeTimer = setInterval(function () { if (isEncoding == true) { checkEncodingFunc(); }; }, 60000);
if (Silverlight.isInstalled("1.0")) { checkEncodingFunc(); };

function checkEncodingFunc() { // check if video is encoding
    $.ajax({
        url: 'video/',
        statusCode: {
            200: function () { // if video is found display play button
                if (isEncoding == true) {
                    $('.encodingbtn').remove();
                    $('.playbtn').show();
                    isEncoding = false;
                };
            },
            204: function () { // if video is encoding display encoding button
                if (Silverlight.isInstalled("1.0")) {
                    isEncoding = true;
                    $('.playbtn').hide(); $('.encodingbtn').remove();
                    $('.videoposter').append('<button class="encodingbtn" />');
                };
            }
        }
    });
};


texts: Project Euler #4 - Finding the largest palindrome that is the product of two three-digit numbers.

texts:
This is my attempt at the 4th problem on Project Euler:

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>

using namespace std;

int palindromeCheck(int pp) {
    int temp = pp;
    string palindrome = std::to_string(pp);

    auto it1 = palindrome.begin();
    auto it2 = palindrome.end() - 1;

    while (it2 - it1 >= 1) {
        if (*it1 == *it2) {
            ++it1;
            --it2;
        }
        else {
            return 0;
        }
    }
    return 1;
}

int main()
{
    int highestPalindrome = 0;
    for (int x = 100; x <= 999; x++) {
        for (int y = 100; y <= 999; y++) {
            int newDigit = x * y;
            int paliCheck = palindromeCheck(newDigit);
            if (paliCheck == 1) {
                if (newDigit > highestPalindrome) {
                    highestPalindrome = newDigit;
                }
            }
        }
    }
    std::cout << highestPalindrome;
}

I'm trying to get better at both C++ and problem-solving so any help/tips are appreciated.


texts: Find the longest ascending subarray from a given array

texts:
I have following task, form a given array, I want the longest ascending array.
I will give you an example

int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,31,32};

will return array of {1,2,3,4,5} - that is the largest sequence of ascending numbers in the given array.

Below is the sample code:

int[] a = {19,12,13,1,2,3,4,5,14,23,24,25,26,27,31,32};
        List<Integer> longestArray = new ArrayList<Integer>();
        List<Integer> currentArary = new ArrayList<Integer>();
        for (int i = 1; i < a.length; i++) {
            if(currentArary.isEmpty()) {
                currentArary.add(a[i-1]);
            }
            if (a[i]-1 == a[i-1]) {
                currentArary.add(a[i]);
            } else {
                if(longestArray.size()<currentArary.size()) {
                    longestArray.clear();
                    longestArray.addAll(currentArary);
                }
                currentArary.clear();
            }
        }
        System.out.println(longestArray);

Any feedback received on this method is more than welcome.


texts: Reduce the length of words in a sentence

texts:
This function's goal is to reduce the length of a sentence to exactly max_length characters by cutting each word in the sentence to a length of minimum 4 characters, if cutting each word to 4 characters isn't enough the the sentence is returned anyway.
All sentences are free of special characters and words are separated by spaces.
Here is the function:

def cut_everything(sentence, max_length):
    """
    reduces each word in sentence to a length of 4

    :type sentence: string
    :param sentence: the sentence to cut
    :type max_length: int
    :param max_length: the length to which the sentence will be reduced
    """
    words = sentence.split()
    for index, word in enumerate(words):
        word_length = len(word)
        if word_length > 4:
            to_cut = len(sentence) - max_length
            to_keep = word_length - to_cut
            if to_keep < 4:
                to_keep = 4
            words[index] = word[:to_keep]
            sentence = ' '.join(words)
            if len(sentence) <= max_length:
                break

    return sentence

My main concern for this review is performance, but any readability comment is appreciated


texts:
I'm struggling to integrate a jquery-ui slider widget into my Meteor app. The idea is to have a slider value in a Mongo collection and the slider needs to be reactive (automatically synced between clients). I've achieved this and it works but the implementation is not very elegant and clean. It's quite hard to maintain, test and extend such code. I've achieved this via Tracker.autorun and jquery slider slide handle (_.throttle is used to limit mongo update interval).

I'm new to Meteor, and it's awesome, but so far couldn't find better way to implement this (which I bet exists):

Live example

Slider = new Meteor.Collection("Slider");

if (Meteor.isClient) {
    Template.slide.rendered = function() {
        var handler = _.throttle(function(event, ui) {
            var val = Slider.findOne({});
            Slider.update({ _id: val._id }, {$set: {slide: ui.value}});
        }, 50, { leading: false });

        if (!this.$('#slider').data('uiSlider')) {
            $("#slider").slider({
                 slide: handler
            });
        }

        Tracker.autorun(function() {
            var slider = Slider.findOne({});
            if (slider) {
                this.$('#slider').data('uiSlider').value(slider.slide);
            }
        });
    };
}

//seed Collection
if (Meteor.isServer) {
    if (Slider.find().count() == 0) {
        Slider.insert({
            slide: 20
        });
    }
}

HTML

jquery-ui slider test

   {{> slide}}

<template name="slide">

</template>


texts:
I created a class to run a certain number of tasks in parallel in the browser.  The constructor takes an array of inputs, a function that takes a single input and returns a promise, and a count of the number of tasks to run in parallel.  This is for doing some web scraping so I don't want to create a hundred ajax requests and wait for them to all complete with Promise.all, besides worrying about a timeout or failure I don't want to thrash the connections to a server (jsfiddle):

// run 5 at a time, calling func on each element of delays array
let par = new Parallel(delays, func, 5);
par.run().then(results => { ... });

It runs all the items and resolves if there were no errors, or rejects if there were any errors.  The results array contains each result or error from a reject.  Is there a better way?

class Parallel {

  constructor(inputs, func, count) {
    this.inputs = inputs;
    this.func = func;
    this.count = count;
    this.index = 0;
    this.active = 0;
    this.enabled = true;
    this.hadError = false;
  }

  cancel() {
    this.enabled = false;
  }

  run() {
    this.start = performance.now();

    return new Promise( (resolve, reject) => {
      this.results = [];

      let checkDone = () => {
        if (this.active === 0 && (this.index >= this.inputs.length || (!this.enabled))) {
          this.end = performance.now();
          if (this.hadError)
            reject(this.results);
          else
            resolve(this.results);
          return true;
        }
      }

      let setAndCheck = (index, result) => {
        this.active--;
        this.results[index] = result;
        queue();
      }

      let handleOne = (index, input) => {
        this.active++;
        this.func(input)
        .then(result => setAndCheck(index, result))
        .catch(err => {
          this.hadError = true;
          console.log('Error with input:', input);
          console.error(err);
          setAndCheck(index, err);
        });
      }

      let queue = () => {
        if (checkDone()) return;
        while (this.enabled && (this.active < this.count) && this.index < this.inputs.length) {
          let index = this.index;
          let input = this.inputs[index];
          this.index = this.index + 1;
          handleOne(index, input);
        }
      }

      queue();
    });
  }
}

let totalDelay = 0;
let func = (delay) => new Promise(resolve => setTimeout(() => resolve(delay), delay));
let delays = [];
for (var i = 0; i < 20; i++) {
 let d = Math.random() * 1000 + 500;
 delays.push(d);
  totalDelay += d;
}

let start = performance.now();
let par = new Parallel(delays, func, 5);
par.run().then(results => {
 var total = results.reduce((acc, val) => acc + val, 0);
  var actual = performance.now() - start;
  document.body.innerHTML = `

totalDelay: ${totalDelay.toFixed(2)}

actual: ${actual.toFixed(2)}

`;
});


texts:
To learn Python, I have implemented a function that creates a k-d tree from a list of 2-d Points. I would like to refer to this question where i asked about the k-d tree in C. However, the Python code takes about 14 seconds for 1 million points. So my question is, are there optimizations that I can apply to my code to improve the performance?

  @staticmethod
  def build(bins, dimension=2, splittingAxis=0):
    if not bins:
      return
    splittingAxis = splittingAxis % dimension
    if splittingAxis == 0:
      bins.sort(key=lambda p: p.x)
    if splittingAxis == 1:
      bins.sort(key=lambda p: p.y)
    median = len(bins) // 2
    leftBin = build(bins[:median], splittingAxis + 1)
    rightBin = build(bins[median + 1:], splittingAxis + 1)
    return KdNode(bins[median], leftBin, rightBin, splittingAxis)

The KdNode is defined as follows :

 class KdNode(object):
    def __init__(self, currentBin=None, leftBin=None, rightBin=None, splittingAxis=0):
      self.currentBin = currentBin
      self.leftBin = leftBin
      self.rightBin = rightBin
      self.splittingAxis = splittingAxis


texts:
I have just written a solution to the following problem:

  We all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input and great code!

I would like suggestions on how I can make my solution less complicated and if there is a more efficient way to solve the problem.

Here is my implementation.  I have tried to implement a binary search strategy to solve the problem.

public class Guesser
{
    private List<int> _possibleAnswers = new List<int>();
    private bool _isCorrectNumber = false;
    private bool _higher = false;
    private int _numberOfGuesses = 0;
    private int _answer;

    public Guesser(int min, int max)
    {
        for (var i = min; i <= max; i++)
            _possibleAnswers.Add(i);
    }

    public void Guess()
    {
        while (!_isCorrectNumber)
        {
            var middleOfAnswers = _possibleAnswers.Max() - (_possibleAnswers.Count / 2);

            Console.WriteLine("Is the number {0}?", middleOfAnswers);

            var hint = Console.ReadLine().ToLower();

            _isCorrectNumber = hint.Equals("yes");

            if (_isCorrectNumber)
            {
                _answer = middleOfAnswers;
                continue;
            }

            _higher = hint.ToLower().Equals("higher");

            if (_higher)
            {
                var count = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers)) + 1;
                _possibleAnswers.RemoveRange(0, count);
            }
            else
            {
                var startIndex = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers));
                var count = _possibleAnswers.FindIndex(guess => guess.Equals(_possibleAnswers.Max())) - startIndex + 1;

                _possibleAnswers.RemoveRange(startIndex, count);
            }
            _numberOfGuesses++;
        }
        Console.WriteLine("The number was {0} and it took me {1} guess{2}",
            _answer, _numberOfGuesses, _numberOfGuesses > 1 ? "es" : string.Empty);
    }
}

Any suggestions on how I can improve this would be great.  I'd also like to know if I have understood the concept behind a binary search and implemented it correctly.


texts: Simple yet efficient integer-to-object dictionaries?

texts:
Sometimes I need an NSDictionary-like object that maps a few integers (non-negative) to objects. At first glance, NSMutableArray is great for this, provided that the indexes aren't too high so I came up with a quick category to allow holes in an array:

@implementation NSArray (FoundationAdditions)

-(id) objectAtCheckedIndex:(NSUInteger) index {
    if(index >= self.count) {
        return nil;
    } else {
        id result =  [self objectAtIndex:index];
        return result == [NSNull null] ? nil : result;
    }
}

@end

@implementation NSMutableArray (FoundationAdditions)

-(void) setObject:(id) object atCheckedIndex:(NSUInteger) index {
    NSNull* null = [NSNull null];
    if (!object) {
        object = null;
    }

    NSUInteger count = self.count;
    if (index < count) {
        [self replaceObjectAtIndex:index withObject:object];
    } else {
        if (index > count) {
            NSUInteger delta = index - count;
            for (NSUInteger i=0; i<delta;i++) {
                [self addObject:null];
            }
        }
        [self addObject:object];
    }
}

@end

Is there a better/easier/simpler way to do this? Preferably using something that's pre-existing in the Cocoa stack. Yes I know STL has some pretty good containers in this area, but mixing-in C++ just for this is overkill.


texts:
I have a custom exception hierarchy in C++ to detect unexpected cases in a library I am implementing. The base exception class inherits from std::exception and all other exception classes derive from this base class.

The header file for the base exception class is as follows:

#ifndef LibException_H_
#define LibException_H_

#include <exception>

class LibException : public std::exception
{
  public:
  // Sets member_err to err
  LibException(const char* err);

  virtual ~LibException() throw ();

  // Returns member_err.
  virtual const char* what() const throw();

  protected:
  // A description of the error. Should probably set this to private.
  const char* member_err;

  private:
};

#endif

And here is the header file for one of the derived classes, which is supposed to catch any process related error (I am spawning multiple processes within C++ in the source code, and I am using this class there for error handling):

#ifndef ProcessException_H_
#define ProcessException_H_

#include "Includes/LibException.H"

class ProcessException : public LibException
{
  public:
  enum Reason
  {
    NETWORK,
    IO,
    OTHER,
  };

  // Calls superclass(err) and sets the two member variables
  ProcessException(const char* err, Reason reason,
      const char* process_command);

  virtual ~ProcessException() throw ();

  // Returns a char* pointer to the reason.
  //
  // E.g. NETWORK = "NETWORK"
  // @return: <const char*> member_reason.
  const char* getReasonChar() const throw();

  // Returns a char* pointer to the spawned process' command (e.g. "ls -a").
  //
  // @return: member_command.
  const char* getCommand() const throw();

  protected:

  private:
  Reason member_reason;
  const char* member_command;
};

So one would invoke an error case for the derived class above by writing throw ProcessException("Process exited unexpectedly", ProcessException::NETWORK, process_command); where process_command is the string representation for a certain process (e.g. ls -a).

Does this implementation make sense? How can the above design be improved?

Edit: Moreover I have another exception class called ParseException (very similar to the derived class above) which is thrown when a parser that is parsing a file or a command from the shell fails unexpectedly. I have read that such errors are better handled via assert statements because they don't represent "exceptional" cases. Could anyone please comment on this?


texts: Simple command line parser/dispatcher in Rust

texts:
I've written a very simple command line parser/dispatcher library. This is an extension of a previous review, which I've refactored, found here. Basically, a user can add functions to a Cmdr struct, then invoke them using a &str. I've made the library generic so that a user can define their own Result<T, E> to be returned from the functions added to Cmdr.

I appreciate any and all comments, especially those related to Rust best practices. One thing that slightly irks me is that I'm not sure that Cmdr should be living in the root lib.rs file. But, if I move it to say, cmdr.rs, my namespace would be something stupid like cmdr::cmdr::Cmdr, as my root directory is also named cmdr. Anyway, behold.

cmd.rs

pub struct Cmd<T, E> {
    pub name: String,
    pub invocation: Box<FnMut() -> Result<T, E>>,
}

impl<T, E> Cmd<T, E> {
    pub fn new<F: 'static + FnMut() -> Result<T, E>>(invoke_str: &str, invocation: F) -> Cmd<T, E> {
        Cmd {
            name: String::from(invoke_str),
            invocation: Box::new(invocation),
        }
    }

    pub fn invoke(&mut self) -> Result<T, E> {
        (self.invocation)()
    }
}

lib.rs

pub mod cmd;
use cmd::Cmd;

pub struct Cmdr<T, E> {
    cmds: Vec<Cmd<T, E>>,
}

impl<T, E> Cmdr<T, E> {
    pub fn new() -> Cmdr<T, E> {
        Cmdr { cmds: Vec::new() }
    }

    pub fn add<F: 'static + FnMut() -> Result<T, E>>(&mut self, name: &str, cmd: F) {
        self.cmds.push(Cmd::new(name, cmd));
    }

    pub fn invoke(&mut self, cmd_name: &str) -> Option<Result<T, E>> {
        let cmd_to_invoke = self.cmds.iter_mut().find(|cmd| cmd.name == cmd_name);
        if let Some(cmd) = cmd_to_invoke {
            Some(cmd.invoke())
        } else {
            None
        }
    }
}

mod tests {
    #[test]
    fn cmdr() {
        let mut cmdr: super::Cmdr<&str, &str> = super::Cmdr::new();
        cmdr.add("test1", || Ok("test1 executed."));
        cmdr.add("test2", || Ok("test2 executed."));

        // Good commands.
        let test1_msg = cmdr.invoke("test1").unwrap().expect("Error in test1.");
        assert!(test1_msg == "test1 executed.", "Incorrect test1 message.");
        let test2_msg = cmdr.invoke("test2").unwrap().expect("Error in test2.");
        assert!(test2_msg == "test2 executed.", "Incorrect test2 message.");

        // Bad command.
        if let Some(_) = cmdr.invoke("ghost") {
            assert!(false, "Non-existent command somehow returned Some().");
        }
    }
}

Some plans for the future are to...

Enable the library to actually utilize FnMut closures. The framework is in place, but I currently don't have a strong enough grasp of lifetimes to implement this.
Add sub-commands and command flags. It will be an interesting exercise in using the ? operator to propagate errors.
Document the code in a Rusty style. I haven't delved in to code based doc tags, as of yet.
Eventually, this will be a front end for a DHCP client/server package I'd like to implement in Rust. I may also release it on crates.io, if it matures into something worthwhile.


texts:
I have written a simple app that adds gitignore files to the current working directory - it does this by reading files hosted on GitHub and then saving them (currently Go, Python and Visual Studio gitignores).

I am a relatively new programmer and mainly code in C# and have written this app in Go. I would be very grateful for any feedback on how I can make any improvements to this code.

Usage:

A user can execute the following to save a Go gitignore to the current working directory (provided the binary is in the user's path):

$ ggi go

App structure:

app_root/
    main.go
    models/
        constants.go

main.go

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "strings"

    "GGI/models"
)

var template string
var url string

func main() {
args := os.Args[1:]
if len(args) != 1 {
    showGgiInfo()
}
if len(args) == 1 {
    template = args[0]
    if gitIgnoreExists() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("gitignore already exists, overwrite? (Y / N): ")
        text, _ := reader.ReadString('\n')
        text = strings.ToLower(strings.Trim(text, " \r\n"))

        if strings.Compare(text, "y") == 0 {
            downloadAndSave(template)
        } else {
            os.Exit(1)
        }
    } else {
        downloadAndSave(template)
    }
}
}

func showGgiInfo() {
    fmt.Println("GGI is a tool for installing gitignore templates.")
    fmt.Println("")
    fmt.Println("Usage:")
    fmt.Println("   ggi [parameter]")
    fmt.Println("")
    fmt.Println("Gitignore templates available:")
    fmt.Println("")
    fmt.Println("   Go      go")
    fmt.Println("   Python      py")
    fmt.Println("   Visual Studio   vs")
    fmt.Println("")
    fmt.Println("Example:")
    fmt.Println("   ggi vs (Visual Studio)")
    os.Exit(0)
}

func gitIgnoreExists() bool {
    pwd, err := os.Getwd()

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    f := pwd + "\\.gitignore"

    if _, err := os.Stat(f); err == nil {
        return true
    }
    return false
}

func downloadAndSave(template string) {
    setURL(template)
    resp, err := http.Get(url)
    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        fmt.Println("Error")
    } else {

        var write []byte
        write = append(write, body...)
        err = ioutil.WriteFile(".gitignore", write, 0644)
        if err != nil {
            fmt.Print("Error")
        } else {
            fmt.Println(".gitignore added!")
        }
    }
}

func setURL(template string) {
    template = strings.ToLower(template)
    switch template {
    case "go":
        url = constants.Go
    case "py":
        url = constants.Python
    case "vs":
        url = constants.VisualStudio
    default:
        showGgiInfo()
        os.Exit(0)
    }
}

constants.go

package constants

const (
    Go           = "https://raw.githubusercontent.com/github/gitignore/master/Go.gitignore"
    Python       = "https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore"
    VisualStudio = "https://raw.githubusercontent.com/github/gitignore/master/VisualStudio.gitignore"
)


texts: Controller making request to an external API

texts:
I'm starting on a new node/express backend and really want to keep everything clean and well tested. My previous project got a bit out of hand (in terms of test coverage and highly coupled code). So I'm going slow this time :-)

To be brief, this function currently sends a request to an API that responds with JSON data. It's a time based API (live results from football games) so I'm making use of some mocking tools so I don't have to spend my sunday afternoon's testing my app !

At the moment the function only returns a JSON object. Up next I want to serialise this to a database (Mongo probably).

Here's v0.1 of the controller:

function getFixture(cb){
  var url = "http://football-api.com/api/?Action=today&APIKey=" + secrets.APIKey + "&comp_id=1204";
  async.waterfall([
    function(callback){
      request.get(url, function(err, response, body){
        if (err) return callback(err);
        if (response.statusCode === 200) {
          var parsedJSON = JSON.parse(body);
          callback(null, parsedJSON);
        } else {
          var errorMsg = "Error in response with code: " + response.statusCode;
          callback(null, errorMsg);
        }
      });
    }
  ], cb)
}

module.exports = getFixture;

I'll include my tests below however they take a lot of space so I'll keep writing here. To be frank I'm still pretty hazy with exactly what's going on with the callbacks in node. So apologies from the outset if there are any obvious errors.

I've used async.waterfall from the get-go since I anticipate having another function that will save this parsedJSON object to a database, which naturally can only occur after the request/response cycle is complete.

Some context: this function will not be matched with a route. Instead it'll be hooked up to a cron job that will run once a Friday to get the scheduled matches for the weekend. So performance isn't really an issue, more so error handling and so on.

I'm starting to ramble, here are the tests (they all pass):

/* Module dependencies */
var nock = require('nock'),
  should = require('should');

/* Local dependencies */
var getFixture = require('../../controllers/api/fixture'),
  secrets = require('../../config/secrets'),
  jsonData = require('../mockData');

describe('Todays matches :controller', function() {

  describe('request/response life cycle', function() {
    it('sends a successful request', function (done) {
      var api = nock('http://football-api.com')
                  .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                  .reply(200, {});

      getFixture(function (err, result) {
        should.not.exist(err);
        done();
      });
    });

    it('correctly handles an error response', function (done) {
      var api = nock('http://football-api.com')
                  .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                  .reply(500, {});

      getFixture(function (err, result) {
        result.should.equal("Error in response with code: 500");
        done();
      });
    });
  });

  describe('Parsing JSON response', function() {
    it('stores the response in result', function (done) {
      var api = nock('http://football-api.com')
                  .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                  .reply(200, jsonData.match_array);

      getFixture(function (err, result) {
        result.should.not.be.empty;
        done();
      });
    });

    it('is done correctly (attributes match)', function (done) {
      var api = nock('http://football-api.com')
                  .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                  .reply(200, jsonData.match_array);

      getFixture(function (err, result) {
        var expectedMatchId = jsonData.match_array.matches[0].match_id;
        var actualMatchId = result.matches[0].match_id;

        actualMatchId.should.equal(expectedMatchId);
        done();
      });
    });

  });
});


texts:
I have a small little function in a VB6 codebase:

Public Function GetEquivalentCode(Optional ByVal code As String) As String

    If IsMissing(code) Or code = vbNullString Then code = m_GlobalCode

    Dim result As String

    If StringStartsWith("ABC", code) Then
        result = "ABC2013"
    Else
        result = code
    End If

    GetEquivalentCode = result

End Function

The implications of this function are massive, so before I deployed it I wrote a small test to ensure it returns the correct/expected value in all cases:

Public Sub GetEquivalentCodeTest()

    Dim result As String

    m_GlobalCode = "ABC2013"
    result = GetEquivalentCode
    Debug.Assert result = "ABC2013"

    m_GlobalCode = "ABC2014"
    result = GetEquivalentCode
    Debug.Assert result = "ABC2013"

    m_GlobalCode = "ABC2013A"
    result = GetEquivalentCode
    Debug.Assert result = "ABC2013"

    m_GlobalCode = "XYZ2013"
    result = GetEquivalentCode
    Debug.Assert result = "XYZ2013"

    m_GlobalCode = "SOMETHING ELSE"
    result = GetEquivalentCode
    Debug.Assert result = "SOMETHING ELSE"

    m_GlobalCode = vbNullString
    result = GetEquivalentCode
    Debug.Assert result = vbNullString

    Debug.Print "GetEquivalentCodeTest: Passed."

End Sub

Running this method from the immediate pane prints GetEquivalentCodeTest: Passed., and if I tweak it to make it fail, it breaks at the assertion that evaluates to False.

Is this the best way to write automated tests in VB6?

Colleagues call me a "purist" - I take it as a compliment. The thing is, without this test method, the mere fact that you give "ABC2014" to the function and it returns "ABC2013" can (will) be a major WTF for anyone maintaining this code in 2 years' time (including myself); the way I see it, these tests document what the [funky] business rules are.

Is there a way to write the test so as to make the business rules even more obvious?


texts: Get the most frequent number and least frequent duplicate in array

texts:
This code gets the most frequent number and least duplicate number in an array.  How can I optimize it and improve its performance?

public class X {

public static String findMin(String[] numbers, int counter) {
int count = 0;
String elements = "";
for (String tempElement: numbers) {
  int tempCount = 0;
  for (int n = 0; n < numbers.length; n++) {
    if (numbers[n].equals(tempElement)) {
      tempCount++;
      if (tempCount > counter) {
        count = 0;
        break;
      }
      if (tempCount > count) {
        elements = tempElement;
        //  System.out.println(elements);
        count = tempCount;
      }
    }
  }
  if (count == counter) {
    return elements;
  }
}
if (count < counter) {
  return "";
}
return elements;
}

public static void main(String[] args) {
String[] numbers = "756655874075297346".split("");
String elements = "";
int count = 0;
for (String tempElement: numbers) {
  int tempCount = 0;
  for (int n = 0; n < numbers.length; n++) {
    if (numbers[n].equals(tempElement)) {
      tempCount++;
      if (tempCount > count) {
        elements = tempElement;
        //  System.out.println(elements);
        count = tempCount;
      }
    }
  }
}
String x = "";
int c = 2;
do {
  x = findMin(numbers, c++);
} while (x == "");

System.out.println("Frequent number is: " + elements + " It appeared " + count + " times");

System.out.println("Min Frequent number is: " + x + " It appeared " + (c - 1) + " times");
}
}


texts: Rabin Karp algorithm improvement for string contains A to Z only

texts:
I have made some improvement to Rabin Karp algorithm when the source and pattern only contain the characters from A to Z. The improvement is, I use base 26 for hashing (as there are total 26 characters). In this case, when the hashes match, there is no need to compare the actual string contents (since there are no hash collisions).

Below is my code in Python 2.7, any advice on code efficiency improvement (in terms of algorithm complexity perspective), bugs or code style is appreciated.

Source code in Python 2.7,

def rabin_karp_match(source, pattern):
    base = 26
    p_hash = 0
    s_hash = 0
    for i in pattern:
        p_hash = p_hash * base + ord(i)-ord('A')
    for j,v in enumerate(source):
        if j < len(pattern) - 1:
            s_hash = s_hash * base + ord(v)-ord('A')
            continue
        s_hash = s_hash * base + ord(v)-ord('A')
        if s_hash == p_hash:
            return j - len(pattern)+1
        s_hash = s_hash - (ord(source[j-len(pattern)+1]) - ord('A')) * base ** (len(pattern) - 1)
    return -1

if __name__ == "__main__":
    print rabin_karp_match('GACGCCA','CGC')
    print rabin_karp_match('GATACCCATCGAGTCGGATCGAGT', 'GAG')
    print rabin_karp_match('FOOBARWIDGET', 'WIDGETS')


texts: Update multiple records with Entity Framwork

texts:
I am wondering what the best way to update multiple records with Entity Framework is.
This is how I normally do it, and it does work:

    private static void SetNcprpCodesAsComplete(string[] ncprpCodes)
    {
        using (var ent = new Data.Entities())
        {
            var query = from ba in ent.BuildingAssessments
                        where ncprpCodes.Contains(ba.NcprpCode)
                        select ba.TabletAssessment;
            foreach (var ta in query) ta.Complete = true;
            ent.SaveChanges();
        }
    }

This query should also work (is one better than the other)

      var query = from ta in ent.TabletAssessments
                  where ncprpCodes.Contains(ta.BuildingAssessment.NcprpCode)
                  select ta;

Another way could be looping through the string[], attaching and updating. Is it possible to attach when doing a multi table query like this?


texts:
This is a single page HTML/CSS layout. This is my first ever code and I know it's not perfect, but I would love for someone with a lot more experience to let me know of my mishaps.

<!DOCTYPE HTML>

    <link type="text/css" rel="stylesheet" href="dereke.css"/>
    <title>

    </title>

Ohio State Buckeyes

Home

|

About Us

|

Contact Us

Ohio State is the best college in the United States! 2016

CSS

.Header {
    width: calc(100%-16px);
    height: 150px;
    border-radius: 5px;
}
.Header p {
    color: white;
    margin-top: -5px;
    width: 600px;
    font-size: 70px;
}
.MidBody {
    background-color: #141414;
    width: 100%;
    height: 850px;
    margin-top: 10px;
    border-radius: 5px;
    position: relative;
    display:block;

}
.footer {
    bottom: 0;
    height:50px;
    width: 100%;
    margin-top: 10px;
    border-radius: 5px;
    clear:both;
    position:relative;
    text-align:center;
    color: white;
}
#leftbody {
    width: 49%;
    height: 425px;
    left: 0;
    margin-top: 3px;
    margin-left: 3px;
    position: relative;
    z-index: 1;
    border-radius: 5px;
    float:left;
}
#leftbody img {
    width: 490px;
    height: 420px;
    border-radius: 5px;
    margin-top: 2px;
    margin-left: 2px;
}
#rightbody {
    background-color: #F1F1F1;
    width: 49%;
    height: 425px;
    margin-top: 3px;
    margin-right: 3px;
    position: relative;
    z-index: 1;
    border-radius: 5px;
    float:right;
}
#lowerbody {
    width: 100%;
    height:auto;
    left:0;
    right:0;
    margin-left: auto;
    margin-right: auto;
    postion: relative;
    display: inline-block;
    text-align:center;
}
#lowerbody img {
    position:relative;
    border-radius: 5px;
    margin-left: auto;
    margin-right: auto;
}
body {
    background-color: black;
}
li {
    display: inline;
    padding: 1px;
    text-decoration: underline;
}
#navbar {
    width: 350px;
    color: #F8F8F2;
    font-family: Arial Black;
    margin: -35px;
    text-align: left;
    line-height: 10px;
}
#noUD {
    text-decoration: none;
}
#logo img {
    margin-top: -150px;
    margin-right: 50px;
    width: 15%;
    height: 15%;
    float: right;
}


texts: Finding the number of boxes that can fit into a truck using JavaScript

texts:
<!DOCTYPE html>
<html>
<script>

  ////////////////////////////
 // Code by Zachary Holmes //
////////////////////////////

// This program determines the number of boxes that can fit into the back of a truck

// Declaring box size in centimetres, and converting it into metres
var boxHeight = prompt("What is the height of your box in centimetres?") / 100;
var boxWidth = prompt("What is the width of your box in centimetres?") / 100;
var boxLength = prompt("What is the length of your box in centimetres?") / 100;

// Declaring truck size in metres
var truckHeight = prompt("What is the height of your truck in metres?");
var truckWidth = prompt("What is the width of your truck in metres?");
var truckLength = prompt("What is the length of your truck in metres?");

// Declaring variables used in equation
var totalHeight = (truckHeight / boxHeight) | 0;
var totalWidth = (truckWidth / boxWidth) | 0;
var totalLength = (truckLength / boxLength) | 0;

// Calculations
var boxNumber = totalHeight * totalWidth * totalLength;

// Output answer
if (boxNumber = 1)
 {
  alert("You can fit up to" + " " + boxNumber + " " + "box into the truck");
 }
else
 {
  alert("You can fit up to" + " " + boxNumber + " " + "boxes into the truck");
 }

</script>
</html>


texts:
Assignment from here

  Q6. Define a function shuffle that takes a list with an even number of elements (cards) and creates a new list that interleaves the elements of the first half with the elements of the second half:

def card(n):
    """Return the playing card type for a positive n <= 13."""
    assert type(n) == int and n > 0 and n <= 13, "Bad card n"
    specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'}
    return specials.get(n, str(n))

def shuffle(cards):
    """Return a shuffled list that interleaves the two halves of cards.

    >>> suits = ['♡', '♢', '♤', '♧']
    >>> cards = [card(n) + suit for n in range(1,14) for suit in suits]
    >>> cards[:12]
    ['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
    >>> cards[26:30]
    ['7♤', '7♧', '8♡', '8♢']
    >>> shuffle(cards)[:12]
    ['A♡', '7♤', 'A♢', '7♧', 'A♤', '8♡', 'A♧', '8♢', '2♡', '8♤', '2♢', '8♧']
    >>> shuffle(shuffle(cards))[:12]
    ['A♡', '4♢', '7♤', '10♧', 'A♢', '4♤', '7♧', 'J♡', 'A♤', '4♧', '8♡', 'J♢']
    >>> cards[:12]  # Should not be changed
    ['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
    >>> repeated(shuffle, 8)(cards) == cards
    True
    """
    assert len(cards) % 2 == 0, 'len(cards) must be even'
    "*** YOUR CODE HERE ***"

Solution:

def card(n):
    """Return the playing card type for a positive n <= 13."""
    assert type(n) == int and n > 0 and n <= 13, "Bad card n"
    specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'}
    return specials.get(n, str(n))

def shuffle(cards, index = 1, incr = 0):
    """Return a shuffled list that interleaves the two halves of cards.

    >>> suits = ['♡', '♢', '♤', '♧']
    >>> cards = [card(n) + suit for n in range(1,14) for suit in suits]
    >>> cards[:12]
    ['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']
    >>> cards[26:30]
    ['7♤', '7♧', '8♡', '8♢']
    >>> shuffle(cards)[:12]
    ['A♡', '7♤', 'A♢', '7♧', 'A♤', '8♡', 'A♧', '8♢', '2♡', '8♤', '2♢', '8♧']
    """
    assert len(cards) % 2 == 0, 'len(cards) must be even'
    if index > (len(cards) // 2):
        element = cards.pop((len(cards) // 2) + incr)
        cards.insert(index, element)
        return cards
    else:
        element = cards.pop((len(cards) // 2) + incr)
        cards.insert(index, element)
        return shuffle(cards, index + 2, incr + 1)

Can I improve this solution?


texts: Initializing a controller that uses Selenium

texts:
I've outsourced the setup functions from my class to another file, I outsourced initDriver from the class PortalController to the class SeleniumUtility.

Before:

class PortalController extends Controller
{
    protected $driver = NULL;

    const URL_GOOGLE = 'https://www.google.com';
    const SELENIUM_SERVER_ADDRESS = 'http://localhost:4444/wd/hub';
    const DRIVER_TIMEOUT = 5000;

    /**
    *   Initialize Driver
    * As you can see I am using `initDriver` to initialize the protected property `$driver`.
    */
    public function initDriver()
    {
        if ($this->driver === NULL) {

            $this->driver = RemoteWebDriver::create(self::SELENIUM_SERVER_ADDRESS, DesiredCapabilities::firefox(), self::DRIVER_TIMEOUT);
        }
    }

    public function main()
    {
        $this->initDriver();

        //start firefox and open google
        $this->driver->get(self::URL_GOOGLE);
    }

...

}

After:

PortalController

use App\Http\Utility\SeleniumUtility As Selenium;

class PortalController extends Controller
{
    protected $driver = NULL;

    const URL_GOOGLE = 'https://www.google.com';

    public function main()
    {
        if ($this->driver === NULL) {
            $this->driver = Selenium::initDriver(array($this, "driver"));
        }

        //start firefox and open google
        $this->driver->get(self::URL_GOOGLE);
    }
...

}

SeleniumUtility

class SeleniumUtility
{
    const SELENIUM_SERVER_ADDRESS = 'http://localhost:4444/wd/hub';
    const DRIVER_TIMEOUT = 5000;

    /**
    *   Initialize Driver
    *   @return RemoteWebDriver
    */
    public static function initDriver($thisObj)
    {
        return RemoteWebDriver::create(self::SELENIUM_SERVER_ADDRESS, DesiredCapabilities::firefox(), self::DRIVER_TIMEOUT);
    }
...
}

But I am not sure if this is the right way, it feels dirty.
I also now have to do the check if ($this->driver === NULL) { in PortalController, If i do the check in initDriver then I get:

Call to a member function get() on null on the line where I try to open the browser with google $this->driver->get(self::URL_GOOGLE);

I appreciate any feedback on how to improve this if it is possible.


texts: Finding odd and even digits from an integer

texts:
I was given a task:

  Given any integer - write a program, which:

  finds all digits of the integer
  writes odd and even digits from the integer
  finds the biggest even and smallest odd digit
  writes the biggest possible number that can be formed by rearranging the odd digits
  writes the smallest possible number that can be formed by rearranging the even digits

I have written this code, but I am wondering if I can somehow get it written shorter than this:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    long a,s=0,s1=0;
    int b,n=0,n1=0,k=0;
    int d[10],nl[10];
    int c=0;
    int i=0,j=0;
    for (i=0; i<10; i++)
    {
        d[i]=0;
        nl[i]=0;
    }
    cout<<"Write a number: "<<endl;
    cin>>a;
    i=0;
    while(a!=0) {
        b=a%10;
        a=a/10;
        if(b%2!=0) {
            d[i]=b;
            i++;
        }
        else {
            nl[k]=b;
            k++;
        }
    }
    n=i;
    n1=k;
    cout<<n1<<" even numbers "<<n<<" odd numbers "<<endl;
    cout<<" Odd numbers not ranged array"<<endl;
    for(i=0; i<n; i++)
        cout<<d[i]<<" ";
    cout<<endl;
    cout<<" Even numbers not ranged array"<<endl;
    for(i=0; i<n1; i++)
        cout<<nl[i]<<" ";
    cout<<endl;
    c=0;
    for(i=0; i<n; i++)
    {
        for(j=0; j<n; j++)
        {
            if(d[i]>d[j])
            {
                c=d[i];
                d[i]=d[j];
                d[j]=c;
            }
        }
    }
    cout<<" Odd numbers ranged array"<<endl;
    for(i=0; i<n; i++)
        cout<<d[i]<<" ";
    cout<<endl;
    cout<<"Min odd number "<<d[n-1]<<endl;
    c=0;
    for(i=0; i<n1; i++)
    {
        for(j=0; j<n1; j++)
        {
            if(nl[i]<nl[j])
            {
                c=nl[i];
                nl[i]=nl[j];
                nl[j]=c;
            }
        }
    }
    cout<<" Even numbers ranged array"<<endl;
    for(i=0; i<n1; i++)
        cout<<nl[i]<<" ";
    cout<<endl;
    cout<<"Max even number "<<nl[k-1]<<endl;
    for(i=0; i<n; i++)
    {
        s=s*10+d[i];
    }
    for(i=0; i<n1; i++)
        s1=s1*10+nl[i];
    cout<<"Max odd digits' number "<<s<<endl;
    cout<<"Min odd digits' number "<<s1<<endl;
    return 0;
}


texts: Code for movement controller of the player in Unity

texts:
I am writing code for games in Unity. I should write the part very often and would like to know the flaws of the piece of code. It seems like everything is fine, but nevertheless I feel that some parts may be wrong. I am interested whether my style of coding is good or bad and would like to hear from someone who see my code for the first time whether he or she understands it or not.

Here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementController : MonoBehaviour
{
    private enum Turned
    {left, right};
    private Turned turned;

    public float walkingSpeed, runningSpeed, currentSpeed;
    public Transform playerTransform;
    public PlayerAnimationController playerAnimationController;
    public SpriteRenderer playerSpriteRenderer;

    void Start ()
    {
        initializeNeededForMovementVariables();
    }

    private void initializeNeededForMovementVariables()
    {
        turned = Turned.left;
    }

    void Update ()
    {
        moveHorizontallyAndAnimateMovementIfNecessary();

    }

    private void moveHorizontallyAndAnimateMovementIfNecessary()
    {
        float moveHorizontallyValue = Input.GetAxis("Horizontal");
        if (moveHorizontallyValue == 0)
        {
            playAnimationOfBeingIdle();
            return;
        }

        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
        { currentSpeed = runningSpeed; }
        else
        { currentSpeed = walkingSpeed; }

        conductHorizontalTranslationOfThePlayer(moveHorizontallyValue);
        flipFacingIfNecessary(moveHorizontallyValue);
        playAnimationOfHorizontalMovement();
    }

    private void playAnimationOfBeingIdle()
    {
        playerAnimationController.beingOnlyIdling();
    }

    private void playAnimationOfHorizontalMovement()
    {
        if (currentSpeed == walkingSpeed)
        { playerAnimationController.beingOnlyWalking(); }
        else if(currentSpeed == runningSpeed)
        { playerAnimationController.beingOnlyRunning(); }
    }

    private void flipFacingIfNecessary(float moveHorizontallyValue)
    {
        if (moveHorizontallyValue > 0 && turned == Turned.left)
        {
            toggleFlipXOnPlayerRenderer();
            turned = Turned.right;
        }
        else if(moveHorizontallyValue < 0 && turned == Turned.right)
        {
            toggleFlipXOnPlayerRenderer();
            turned = Turned.left;
        }
    }

    private void toggleFlipXOnPlayerRenderer()
    {
        playerSpriteRenderer.flipX = !playerSpriteRenderer.flipX;
    }

    private void conductHorizontalTranslationOfThePlayer(float moveHorizontallyValue)
    {
        transform.Translate(moveHorizontallyValue * currentSpeed, 0, 0);
    }
}

Will appreciate any attention and comments. If this question is not appropriate for the site and should be in game overflow, please, move it there.


texts: Python Find the N adjacent digits in the 1000-digit number that have the greatest product


texts: Skip input to next line, for reading serialized objects

texts:
I was de-serializing objects that had an extra newline that needed to be removed before getting the next object.

#ifndef THORSANVIL_UTIL_H
#define THORSANVIL_UTIL_H

// Removed headers for   getDist() and getRandomContainerIterator()
// We already reviewed those two.
#include <iostream>

namespace ThorsAnvil
{
    namespace Util
    {

// Removed getDist() and getRandomContainerIterator()
// We already reviewed those two.

class IgnoreUntilNewLine
{
    public:
        friend std::istream& operator>>(std::istream& stream, IgnoreUntilNewLine& /*data*/)
        {
            stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            return stream;
        }
};

class SkipEmptyLineToEnd
{
    public:
        friend std::istream& operator>>(std::istream& stream, SkipEmptyLineToEnd& /*data*/)
        {
            std::string     emptyLine;
            std::getline(stream, emptyLine);
            if (!emptyLine.empty()) {
                stream.setstate(std::ios::badbit);
            }
            return stream;
        }
};

    }
}

#endif

Simplified Example for usage:

namespace TU = ThorsAnvil::Util;
struct Example1
{
     int    x;
     int    y;
     std::string  line; // Always one line with no "\n"
     void swap(Example1& other) noexcept {/*Stuff*/}

     friend std::ostream& operator<<(std::ostream& stream, Example1 const& data)
     {
         // Note putting a new line here
         // to make the Serialized object more readable.
         // The actual object was a bit more complicated and
         // I really wanted to make it readable.
         return stream << data.x << " " << data.y << "\n"
                       << data.line << "\n";
     }
     friend std::istream& operator>>(std::istream& stream, Example1& data)
     {
         Example1  tmp;
         if (stream >> tmp.x >> tmp.y)
         {
             stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
             if (std::getline(stream, tmp.line)) {
                 data.swap(tmp);
             }
         }
         return stream;
     }
};

I thought the above read was a bit cumbersome and hard to read. Thus the two types above. This means I can re-write the read operation as:

     friend std::istream& operator>>(std::istream& stream, Example1& data)
     {
         TU::IgnoreUntilNewLine ignoreNewLine;
         Example1               tmp;

         if ((stream >> tmp.x >> tmp.y >> ignoreNewLine) && std::getline(stream, tmp.line)) {
             data.swap(tmp);
         }
         return stream;
     }


texts: Nested Deck class design and implementation

texts:
Previous review of this project:

Deck and Card classes and member-accessing with one header

I'm nearly finished with my deck of cards project, and this time I made changes to hide the Card class by nesting it in the Deck class.  I'm still getting correct results when displaying the deck.  However, I do now realize that I can no longer maintain Card objects outside the class.  Instead, I have to call Card deal() with a Deck object in order to retrieve a Card, and I cannot store that Card anywhere.

Does this render my design ineffective for this purpose?  If so, how else can I maintain Cards outside the class while still preventing the user from directly constructing a Card?  Would a private constructor (with Card un-nested from Deck) be a better option?

Deck.h

#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <array>

class Deck
{
private:
    class Card
    {
    private:
        char rank;
        char suit;
        unsigned value;

    public:
        Card::Card() : value(0), rank(' '), suit(' ') {}
        Card::Card(char r, char s, unsigned v) : rank(r), suit(s), value(v) {}
        bool operator<(const Card &rhs) const {return (value < rhs.value);}
        bool operator>(const Card &rhs) const {return (value > rhs.value);}
        bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
        bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
        friend std::ostream& operator<<(std::ostream &out, const Card &aCard);
        friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
            {return out << '[' << aCard.rank << aCard.suit << ']';}
    };

    static const unsigned VALUES[13];
    static const char RANKS[13];
    static const char SUITS[4];
    static const unsigned MAX_SIZE = 52;
    std::array<Card, MAX_SIZE> cards;
    int topCardPos;

public:
    Deck();
    void shuffle();
    Card deal();
    unsigned size() const {return topCardPos+1;}
    bool empty() const {return topCardPos == -1;}
    friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};

#endif

Deck.cpp

#include <algorithm>
#include "Deck.h"

const unsigned Deck::VALUES[13] = {1,2,3,4,5,6,7,8,9,10,10,10,10};
const char Deck::RANKS[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
const char Deck::SUITS[4] = {'H','D','C','S'};

Deck::Deck() : topCardPos(-1)
{
    for (unsigned rank = 0, value = 0; rank, value < 13; ++rank, ++value)
    {
        for (unsigned suit = 0; suit < 4; ++suit)
        {
            topCardPos++;
            cards[topCardPos] = Card(RANKS[rank], SUITS[suit], VALUES[value]);
        }
    }

    shuffle();
}

void Deck::shuffle()
{
    topCardPos = MAX_SIZE-1;
    std::random_shuffle(&cards.front(), &cards.back()+1);
}

Deck::Card Deck::deal()
{
    if (empty())
    {
        std::cerr << "\nDECK IS EMPTY\n";
        Card blankCard;
        return blankCard;
    }

    topCardPos--;
    return cards[topCardPos+1];
}

std::ostream& operator<<(std::ostream &out, const Deck &aDeck)
{
    for (unsigned iter = aDeck.size(); iter--> 0;)
    {
        out << "\n" << aDeck.cards[iter];
    }

    return out;
}


texts: ReentrantReadWriteLock lock upgrade method

texts:
I have a question about lock upgrading.Specifically what bothers me is between readlock.unlock() and following writelock.lock()...
I am providing a nearly complete implementation for a sample cache.I just omitted actual loading of cached data from database.

I appreciate if you can review the code and share your thoughts. I tried to express my concern in the java comments . My question is how to correctly synchronize in order to avoid rechecking the cache in load cache.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class JavaRanchSampleCache {

    private ConcurrentHashMap<String, ReentrantReadWriteLock> refreshLocks = new ConcurrentHashMap<String, ReentrantReadWriteLock>();
    private ConcurrentHashMap<String, HashMap<String, String>> cacheData = new ConcurrentHashMap<String, HashMap<String, String>> ();

    public  HashMap<String, String> getCachedData(String cacheKey)
    {
        ReentrantReadWriteLock lock = refreshLocks.get(cacheKey);

        if(lock==null)
        {
            lock=new ReentrantReadWriteLock();
            ReentrantReadWriteLock previous=refreshLocks.putIfAbsent(cacheKey, lock);
            if(previous!=null)//null means no previous lock object,first time usage
                lock=previous;
        }

        //we have a safe lock at this point
        try
        {
            lock.readLock().lock();//read the cached item for correspoding cacheKey
            HashMap<String, String> cachedItem=cacheData.get(cacheKey);
            if(cachedItem==null)//it is not cached yet.Load to cache on first request
            {
                cachedItem=loadItemExpensive(cacheKey);
            }

            return cachedItem;//return the cached item.

        }
        finally
        {
            lock.readLock().unlock();
        }

    }

    private HashMap<String, String> loadItemExpensive(String cahceKey)
    {
        ReentrantReadWriteLock lock = this.refreshLocks.get(cahceKey);
        HashMap<String, String> cachedItem=null;
        try
        {
             /*these two lines are for lock upgrading
             * BUT what happens if another thread interacts between line1 and line2
             * I mean after the readlock is relased,some OTHER thread might gain the writelock
             * before this thread and perform loaddata and update cache operation.
             * So should I check the cache once more to see if some other thread
             * has updated the cache? I 'feel' that I should,but it is ugly,i need some clever way.
             */
            lock.readLock().unlock();//line1
            lock.writeLock().lock();//line2

            /*omitted load data from some expensive store such as database or remote server*/

            return  cachedItem;
        }
        finally
        {
            lock.readLock().lock();//writelock owner can grant readlock immediately.
            lock.writeLock().unlock();//lock released
        }
    }

}


texts: Create a template class for same algorithm different type of member variable

texts:
I want a template class that defines the same algorithms, but can work on different type of data stored in a member variable.
The exact type of data ideally depends only on a single template parameter.
I don't want run time polymorphism (like have an argument of a pointer to base class that can accept all derive class).

Below is my current solution using variadic template. Is there a simpler/better way?

#include <vector>
class Data1 {
public:
    Data1(int size, int stride)
            : _v(size*stride), _size(size), _stride(stride) {}
    int& operator[](int id) {return _v[id*_stride];}
    const int _size;
private:
    const int _stride;
    std::vector<int> _v;
};

class Data2 {
public:
    Data2(int size) : _v(size), _size(size) {}
    int& operator[](int id) {return _v[id];}
    const int _size;
private:
    std::vector<int> _v;
};

template <typename Data, typename... Data_arg>
class Base_template {
public:
    Base_template(Data_arg...data_arg): _data(data_arg...) {}
    void set_all() {
        for (int i = 0; i < _data._size; ++i) _data[i] = _val;
    }
protected:
    int _val;
    Data _data;
};

class Thing1 : public Base_template<Data1, int, int> {
public:
    Thing1(const int size)
            : Base_template(size, 3) {
        this->_val = 1;
    }
};
class Thing2 : public Base_template<Data2, int> {
public:
    Thing2(const int size)
            : Base_template(size) {
        this->_val = 10;
    }
};

int main() {
    Thing1 t1(100);
    t1.set_all();
    Thing2 t2(10);
    t2.set_all();
}

Notes:

I use variadic template because the data needs to be initialize.
In the simple example above Data2 actually can be replaced by data1 with a stride of 1. But in the actually code, this is not the case.


texts: Using homogeneous coordinates to rotate an image

texts:
Currently, I have this code snippet, but it's a little bit slow:

% input image
input_matrix = imread('placa.bmp');
[rows cols] = size(input_matrix);

% rotation
degree = 30;
radians = (pi * degree) / 180;
theta = radians;

% output matrix
t_matrix = input_matrix;
t_matrix(t_matrix == input_matrix) = NaN;

% transformation matrix
T = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 1; 0 0 1];

% loop over each input_matrix coordinate
for n = 1:numel(input_matrix)

    % current coordinate
    [x y] = ind2sub([rows cols], n);

    % transpose
    v = [x y 1]';

    % homogeneous coordinate
    v = T*v;

    % transponse again
    v = v';

    % only integer values
    a = floor(v(1));
    b = floor(v(2));

    if a > 0 && b > 0

        % replace in t_matrix
        t_matrix(a,b) = input_matrix(x,y);
    end
end

% get only a part of t_matrix
t_matrix = t_matrix(1:rows, 1:cols);

figure; imshow(input_matrix); % original image
figure; imshow(t_matrix)

How can I improve it?

Condition: keep using this matrix:

% transformation matrix
T = [cos(theta) -sin(theta) 0; sin(theta) cos(theta) 1; 0 0 1];


texts: Is this a fast implementation of reversing a string?

texts:
I thought of this algorithm today. It seems fast, but how can I know?

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

/*
 * Reverse a string
 * the caller has to free dynamic memory allocated
 */
char *mon_string_rev(char *string)
{
    char *out = malloc ( strlen(string) + 1 );

    assert(out);

    int len = strlen(string);

    int i;

    int counter = 0;

    int iterations = 0;

    while(1) {
        if(len < 0) break;
        // important to only start counting after
        // determing that the loop will continue
        ++iterations;
        for(i = 0; i < len; i++) {
            // if this is the last character
            // push it onto the output string
            if(i == (len - 1)) {
                out[counter] = string[i];
                counter++;
            }
        }
        len--;
    }
    out[counter] = '\0';

    printf("Total iterations: %d\n", iterations);

    return out;

}

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

    if(argc < 2) {
        fprintf(stderr, "Usage: %s <string>", argv[0]);
        exit(1);
    }

    char *str = mon_string_rev(argv[1]);

    printf("%s\n", str);

    free(str);

    return !1;

}


texts: Leetcode - First Unique Character in a String

texts:
Given a string, find the first non-repeating character in it and
  return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

  Note: You may assume the string contain only lowercase letters.

My solution

public class FirstUniqueCharacter {

    public int firstUniqChar(String s) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

        for (char c : s.toCharArray()) {
            if (Objects.isNull(map.get(c))) {
                map.put(c, 1);
            } else {
                int count = (Integer) map.get(c);
                map.put(c, ++count);
            }
        }

        for (Map.Entry e : map.entrySet()) {
            int value = (int) e.getValue();
            Character c = (Character) e.getKey();
            if (value == 1) {
                return s.indexOf(c);
            }
        }

        return -1;
    }
}

The statistics shows it’s still slower than 60% of the solutions submitted in terms of speed and space. How can I improve it?  Any comments regarding code readibility are most welcome.


texts: Detecting connected acyclic through Tarjan strongly connected components variant

texts:
I want to verify that a given directed graph is connected and acyclic (DAG). I have implemented a modification of the Tarjan's strongly connected components algorithm in imperative style (as the original).

Every suggestion to improve simplicity, readability and suitable use of F# constructs will be wellcome.

Note: the current algorithm returns the value for acyclic property for the first cluster in disconnected graphs. I'm ok with that. Once I know it is not DAG I no need to analyze it further. But with this in mind I suppose the algorithm could be improved.

open System.Collections.Generic

type GraphKind = {
        acyclic : bool;
        connected : bool
    }

 let kindOfGraph getChildren v numNodes =

    let stack = Stack<_>()
    let visited = Dictionary<_,int * int>(HashIdentity.Structural)
    let discovered = HashSet<_>(HashIdentity.Structural)
    let sccs = ref 0
    let order = ref 0

    let rec scc getChildren v =

        stack.Push (v)
        visited.Add(v, (!order, !order))
        incr order

        let vindex, vlink = visited.[v]

        getChildren v
        |> List.map (fun w ->
            if not <| visited.ContainsKey w then
                scc getChildren w
                visited.[v] <- (vindex, min vlink (snd visited.[w]))
            else if not <| discovered.Contains w then
                visited.[v] <- (vindex,min vlink (fst visited.[w]))
        ) |> ignore

        let idx, lnk = visited.[v]

        if idx = lnk then

            let rec getscc (s : Stack<_>) root =
                let w = s.Pop()
                discovered.Add w |> ignore
                match w with
                | x when x = root -> ()
                | _ -> getscc s root

            getscc stack v
            incr sccs

    scc getChildren v
    {
        acyclic = (!sccs = !order);
        connected = (!order = numNodes)
    }

And some tests using FsUnit and NUnit

open NUnit.Framework
open FsUnit

[<TestFixture>]
type ``kind of graph`` () =

let aTree = function
| 1 -> [2; 3]
| 2 -> [4; 5]
| _ -> []

let aTriangle = function
| 1 -> [2]
| 2 -> [3]
| 3 -> [1]

let aConnectedAcyclic = function
| 1 -> [2; 3]
| 2 -> [4; 5; 6]
| 4 -> [7]
| 6 -> [8; 9]
| 3 -> [10; 11; 13]
| 10 -> [9; 12]
| 11 -> [13]
| _ -> []

let aDisconnectedAcyclic = function
| 1 -> [2; 3]
| 4 -> [5]
| _ -> []

let aDisconnectedCyclic = function
| 1 -> [2]
| 2 -> [3]
| 3 -> [1]
| 4 -> [5]
| _ -> []

let aSingleNode = function | _ -> []

[<Test>] member x.
    ``given a tree`` () =
        kindOfGraph aTree 1 5 |> should equal { acyclic = true; connected = true}

[<Test>] member x.
    ``given a connected triangle`` () =
        kindOfGraph aTriangle 1 3 |> should equal { acyclic = false; connected = true}

[<Test>] member x.
    ``given a connected acyclic graph`` () =
        kindOfGraph aConnectedAcyclic 1 13 |> should equal { acyclic = true; connected = true}

[<Test>] member x.
    ``given a single node`` () =
        kindOfGraph aSingleNode 1 1 |> should equal { acyclic = true; connected = true}

[<Test>] member x.
    ``given a disconnected acyclic graph`` () =
        kindOfGraph aDisconnectedAcyclic 1 5 |> should equal { acyclic = true; connected = false}

 [<Test>] member x.
    ``given a disconnected cyclic graph`` () =
        kindOfGraph aDisconnectedCyclic 1 5 |> should equal { acyclic = false; connected = false}


texts:
I wrote this middleware for express enabling developers to require certain parameters the easy way. How good is this approach? Can you call this quality code? Is everything OK, or is something missing?

Github

Package: NPM

function getMissingPrams(reqParams, requiredParamsArray) {
  //handling errors
  if (!reqParams)
    return new Error('send reqParams for the first argument')
  if (!(requiredParamsArray instanceof Array))
    return new Error('you must be using array for the second argument')
  if (requiredParamsArray.length < 1)
    return new Error('not found Required parameters')

  //Assigning body keys to array optimizing performance
  const reqParamsArray = Object.keys(reqParams);
  //extracting the missing paramerters
  const missedParams = requiredParamsArray.filter(param => !reqParamsArray.includes(param))
  //here's the array of missedParams
  return missedParams;
}


texts: What changes, if any, are required to make the following Perl eval bullet proof?

texts:
eval {
    # here is put some code that may throw exception
    1;  # Why is the "1;" here ?
} or do {
   my $error = $@;
   # Handle error.
};

Does the following style protect against $@ not being set
correctly ?
What does the following "1;" protect against?
Is the "or do{" better than the saying "if ($@){ " ? If so, why?


texts: Sorting array with respect to two properties

texts:
I'm sorting with respect to Width and Length. However, Width has the significance precedence, so Length is only vital if Width is exactly equal (both are integers). The comparison method I've implemented as shown below. Is this a neat trick with doubling the most significant value's comparer or is there a better way?

  List<Thing> things = thingsDictionary.Select(thing
    => thing.Value).ToList();
  things.Sort((first, second)
    => 2 * first.Width.CompareTo(second.Width)
       + first.Length.CompareTo(second.Length));


texts: Uploading multiple images to Google Cloud Storage using Node.js

texts:
I am no JavaScript expert, and I have managed to hack together a node.js script that does exactly what I want it to do: upload images contained within a folder to Google Cloud Storage for a Firebase project, and then return the public access URLs. Given that I have limited experience with node.js combined with GC Storage, please advise me on any issues that running this code over approximately 200 images in the folder may cause.

var fs = require('fs');
const {Storage} = require('@google-cloud/storage');

const projectId = 'XXXXXXX';

//Creates a client
const storage = new Storage({
    projectId: projectId,
    keyFilename: 'auth.json'
  });

// Reference the bucket
var bucket = storage.bucket('XXXXXXX.appspot.com');

//This reads the folder where the images are stored
fs.readdir('ImagesToUpload', (err, files) => {

    if( err ) {
        console.error( "Could not read the directory.", err );
        process.exit( 1 );
    }

    files.forEach(function( file, index ) {

        var filePath = 'ImagesToUpload/'

        console.log(file)

        // Upload a local file to a new file to be created in the bucket
        bucket.upload(filePath += file, (err, file) => {
            if (err) { return console.error(err); }
            let publicUrl = `https://firebasestorage.googleapis.com/v0/b/${projectId}.appspot.com/o/${file.metadata.name}?alt=media`;
            console.log(publicUrl);
        });
    })
})


texts:
Recently I wrote some code to take two arrays of data and create a title. Each array could have 0-n elements. However, the multiple if statements seem messy to me. Is there a nicer way to do this? Perhaps one that harnesses the power of jQuery better?

var campaign_names = data["campaign_names"];
var list_names = data["list_names"];
var title;

if (campaign_names && campaign_names.length > 1) {
  campaign_names = campaign_names.join(", ");
} else if (campaign_names) {
  campaign_names = campaign_names[0];
}

if (list_names && list_names.length > 1) {
  list_names = list_names.join(", ");
} else if (list_names) {
  list_names = list_names[0];
}

if (campaign_names && list_names) {
  title = campaign_names + " & " + list_names;
} else if (campaign_names) {
  title = campaign_names;
} else if (list_names) {
  title = list_names;
}


texts:
I was making a library program for trying to practice C++. I wanted to use a vector to store all the books, the books being a struct to hold the general things the books would have.

struct Book
{
    string  bookName; // book's name
    string  bookAuthor; // book's author
    string  bookID; // a random generated string
    int     bookType; // what type of book
};

The books in the library would be stored in a vector. To find one of these books I used a function that takes in a bookId parameter and uses it to find the book.

Book LibrarySystem::LocateBook(string bookId)
{
    /* May not be the fastest search algorithm */

    for (int i = 0; i <= mBooks.size(); i++)
    {
        Book result = mBooks[i];
        if (bookId == mBooks[i].bookID)
        {
            return result;
        }

        else
        {
            cout << "FAILED TO FIND " + bookId << endl;
        }
    }
}

This works but I was wondering if it could be faster. Looking at it, I am going through it one by one checking if the bookId is equal to the one provide in the parameter which seems slow.

I did do a small test to check if it all worked. I created a function:

string LibrarySystem::BookDataOutput(string bookId)
{
    Book book = LocateBook(bookId);
    string data =
        "Book author: " + book.bookAuthor + "\n" +
        "Book name: " + book.bookName + "\n" +
        "Book type: " + to_string(book.bookType) + "\n" +
        "Book Id: " + book.bookID;
    return data;
}

Which outputs a single string with all the book's information. It uses LocateBook to find the the book with the bookId.

I run in main:

int main(int args, char* argv[])
{
    /* Seed the random generator */
    srand(time(NULL));

    LibrarySystem library;

    library.RegisterBook("Test1", "Test1", BOOK_TYPE::Adult, "test1");

    cout << library.BookDataOutput("test1") << endl;

    cin.get();
}

and the output is:

Book author: Test1
Book name: Test1
Book type: 5
Book Id: test1

Which matches all the information I provided.


texts: Optimize "nearest" Element query prototype

texts:
I have devised a recursive function to grab the "nearest" element. This is a bit different than Element.closest, because instead of traversing just the immediate parent(s); it traverses up but checks left-right-up-down.
Is there a more efficient check for siblings that I am missing?

if (Element.prototype.nearest === undefined) {
  const nearest = (el, selector) => {
    if (el == null) return undefined;
    const prev = el.previousElementSibling;
    if (prev?.matches(selector)) return prev;
    const next = el.nextElementSibling;
    if (next?.matches(selector)) return prev;
    const parent = el.parentElement;
    if (parent?.matches(selector)) return parent;
    const relative = parent.querySelector(selector);
    if (relative) return relative;
    return nearest(el.parentElement, selector);
  };
  Element.prototype.nearest = function(selector) {
    return nearest(this, selector);
  };
}

const handleClick = (e) => {
  const btn = e.target;
  console.log(btn.nearest('.child'));
  console.log(btn.nearest('.grand-parent'));
  console.log(btn.nearest('#child-1'));
}

document.querySelectorAll('.btn').forEach(btn =>
  btn.addEventListener('click', handleClick));
.parent {
  display: flex;
}

      <button class="btn">
        Click
      </button>

      <button class="btn">
        Click
      </button>


texts:
I am trying to solve the below mentioned problem from HackerEarth.

Although the results are fine, the code takes extraordinarily long time to run execute. I am pretty sure the problem is because of the nested loops, and I am working on it.

I would like to know:

How can this code be optimized to run within 1 sec?
What are the general programming principles to optimize your execution time, say while writing embedded applications with time constraints.

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char * argv[])
{
   int testcase;
   cin >> testcase;
   int Number[10000];
   for(int i = 0; i < testcase ; i++)
   {
      cin >> Number[i];
   }

   float numerator, denominator,result;
   //float myArr[100000];
   vector<float> myArr;

   for(int i = 0; i < testcase ; i++)
   {
      for(int j = 1; j <= Number[i] ; j++)
      {
         for(int k = 1; k <= Number[i] ; k++)
         {
            numerator = j;
            denominator = k;
            //cout << numerator << denominator << endl;
            if(numerator < denominator)
            {
               result = numerator/denominator;
               //cout << result << endl;
               bool found = false;
               for(int x=0; x < myArr.size() ; x++)
               {
                  if(result == myArr[x])
                  {
                     found = true;
                     break;
                  }
               }
               if(found == false)
               {
                  myArr.push_back(result);
               }
            }
         }
      }
      cout << myArr.size() << endl;
      myArr.clear();
   }

   return 0;
}


texts: Making a minishell in C. How to improve error control with feoh and ferror?

texts:
I've written this minishell but I'm not sure I'm making a correct control of the errors. Could you give me some advice?

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

#define LINE_LEN  50
#define MAX_PARTS  50

int main ()
{
char* token;
char str[LINE_LEN];
char* arr[MAX_PARTS];
int i,j;
bool go_on = true;

while (go_on == true){
    printf("Write a line:('quit' to end) \n $:");
    fgets(str, LINE_LEN, stdin);

    if (str==NULL) {
        goto errorfgets;
    } else {
        size_t l=strlen(str);
        if(l && str[l-1]=='\n')
            str[l-1]=0;

        i=0;
        /* split string into words*/
        token = strtok(str, " \t\r\n");
        while( token != NULL )
        {
            arr[i] = token;
            i++;
            token = strtok(NULL," \t\r\n");
        }

        fflush(stdin);

        /* check if the first word is quit*/
        if (strcmp(arr[0],"quit")==0)
        {
            printf("Goodbye\n");
            go_on = false;
        } else {

            for (j=0; j < i; j++){
            printf("pajaritos por aqui'%s'\n", arr[j]);
            }
        }
    }
}

return 0;
errorfgets:
    printf("fgets didn't work correctly");
    return -1;
}


texts: Faster Tridiagonal Matrix Multiplication

texts:
I have a function that I've been trying to make faster that computes \$XA + B\$, where \$A \in \mathbb{R}^{n \times n}\$ is a tridiagonal matrix, and \$X, B \in \mathbb{R}^{m \times n}\$. In the code, the lower, main, and upper diagonals are represented by dl, dm, du. The naive implementation of this is,
/* Compute BA + X where A is tridiagonal shape (n, n), B, X are matrices shape (m, n) */
void dgtaxmt(const double *dl, const double *dm, const double *du,
             const double *x, const double *b, double *out,
             const unsigned int n, const unsigned int m, double *temp)
{
    int i, j, ii;

    for (i = 0; i < m; i++){
        ii = i * n;
        temp[ii] = (x[ii] * dm[0]) + (x[ii + 1] * dl[0]) + b[ii];
        for (j = 1; j < n - 1; j++){
            temp[ii + j] = ((x[ii + j - 1] * du[j - 1]) + ((x[ii + j] * dm[j]) + ((x[ii + j + 1] * dl[j]) + b[ii + j])));
        }
        temp[ii + j] = (x[ii + j] * dm[j]) + (x[ii + j - 1] * du[j - 1]) + b[ii + j];
    }
    // store the transpose of temp into out
    // otrans(temp, out, m, n, 16);

}

Note that all of the pointers use the restrict keyword, but I left them out for readability. My attempts at increasing performance include tiling and using AVX intrinsics in hopes that not having to reload dl, dm, du would speed up the code, but it actually made it a lot slower. Is there anyway to vectorize this function in an efficient manner? Clang doesn't report any vectorization, and the assembly code it generates is using the xmm registers, but only the first value. Could there be a different order of operations that would allow better re-usage of data that's been previously loaded?
EDIT Here is the attempt I made with AVX intrinsics
void dgtaxmt_avx(const double *dl, const double *dm, const double *du,
                 const double *x, const double *b, double *out,
                 const unsigned int n, const unsigned int m, double *temp)
{
    // idx is for "rolling" values in vector to left by one index
    const __m256i idx = _mm256_set_epi32(1, 0, 7, 6, 5, 4, 3, 2);
    __m256d dl_vec, dm_vec, du_vec, bn, xnm1, xn, xn1, tmp4;
    __m128d tmp2;

    unsigned int i, j, ii;
    const unsigned int r = ((n - 2) & (-4)) + 1;

    for (i = 0; i < m; i++){
        ii = i * n;
        temp[ii] = (x[ii] * dm[0]) + (x[ii + 1] * dl[0]) + b[ii];
        for (j = 1; j < r; j += 4){
            dl_vec = _mm256_loadu_pd(&dl[j - 1]);
            dm_vec = _mm256_loadu_pd(&dm[j]);
            du_vec = _mm256_loadu_pd(&du[j]);
            bn     = _mm256_loadu_pd(&b[ii + j]);

            xnm1  = _mm256_loadu_pd(&x[ii + j - 1]);
            tmp2  = _mm_loadu_pd(&x[ii + j + 3]);
            xn1   = _mm256_set_m128d(tmp2, _mm256_extractf128_pd(xnm1, 1));

            // use permutations to avoid doing extra loads
            xn   = (__m256d)_mm256_permutevar8x32_ps((__m256)xnm1, idx);
            tmp4 = (__m256d)_mm256_permutevar8x32_ps((__m256)xn1,  idx);
            tmp2 = _mm256_extractf128_pd(tmp4, 0);
            xn   = _mm256_insertf128_pd(xn, tmp2, 1);

            tmp4 = _mm256_fmadd_pd(du_vec, xn1, bn);
            tmp4 = _mm256_fmadd_pd(dm_vec, xn, tmp4);
            tmp4 = _mm256_fmadd_pd(dl_vec, xnm1, tmp4);

            _mm256_storeu_pd(&out[ii + j], tmp4);
        }
        for (j = r; j < n - 1; j++){
            temp[ii + j] = ((x[ii + j - 1] * du[j - 1]) + ((x[ii + j] * dm[j]) + ((x[ii + j + 1] * dl[j]) + b[ii + j])));
        }
        temp[ii + j] = (x[ii + j] * dm[j]) + (x[ii + j - 1] * du[j - 1]) + b[ii + j];
    }

    otrans(temp, out, m, n, 16);
}


texts:
I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.
However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way.

I know this isn't a big deal but I am curious to see what you guys might suggest for this :)
What do you think is the best possible way to remove this redundancy?

private int GetOleFromHTML(string stringRep)
{
    Color c;
    if (string.IsNullOrWhiteSpace(stringRep))
    {
        c = Color.FromArgb(224, 224, 224);
    }
    else
    {
        try
        {
            c = ColorTranslator.FromHtml(stringRep);
        }
        catch
        {
            c = Color.FromArgb(224, 224, 224);
        }
    }

    return ColorTranslator.ToOle(c);
}


texts:
I've written a method to obtain an IEnumerable from a start point, end point and step. Similar to Enumerable.Range() but for doubles and not fixed step.

public static IEnumerable<double> InclusiveRange(double start, double end, double step = 1)
    {
        while (start <= end)
        {
            yield return start;
            start += step;
        }
    }

Am I missing something, or there is a better approach?


texts: A function that updates JSON disk object

texts:
So I have created this function that will add a disk if needed and it takes a disk and a size as inputs. The idea is that I need to update data.disks with a few properties. Disk is called from an external request and it follows the pattern of "disk1", "disk2" and so on. Looking at it there are a few hard-coded values and some that are null. However I left them on purpose to show the structure of data.disk for the next person that might read it or modify it. Because of this it looks verbose and I don't really like it all that much.
Do you see a way to make this function more readable/better in any way?

function addDisk(disk, size) {
    var diskNumber = disk.slice(-1);
    var diskLabel = "Hard disk " + diskNumber;
    var diskIndex = diskNumber - 1;

    //Updating JSON data object
    data.disks[diskIndex] = {
        "componentTypeId" : "com.vmware.csp.iaas.blueprint.service",
        "componentId" : null,
        "classId" : "Infrastructure.Compute.Machine.MachineDisk",
        "typeFilter" : null,
        "data" : {
            "capacity" : size,
            "custom_properties" : null,
            "id" : null,
            "initial_location" : "",
            "is_clone" : false,
            "label" : diskLabel,
            "storage_reservation_policy" : "",
            "userCreated" : true,
            "volumeId" : diskIndex
        }
    }
    log(diskLabel + " has capacity of: " + size + " GBs");
}


texts:
From SICP:

  Exercise 3.18.  Write a procedure that
  examines a list and determines whether
  it contains a cycle, that is, whether
  a program that tried to find the end
  of the list by taking successive cdrs
  would go into an infinite loop.
  Exercise 3.13 constructed such lists.

I wrote the following (revised) solution:

(define (has-cycle? l)
  (define (rec nodes-visited remains)
    (define (leaf? node) (not (pair? node)))
    (define (have-seen? node)
      (define (rec rest)
        (if (null? rest) #f
             (or (eq? (car rest) node)
                 (rec (cdr rest)))))
      (rec nodes-visited))
    (cond
      ((leaf? remains) #f)
      ((have-seen? remains) #t)
      (else
       (or (rec (cons remains nodes-visited) (car remains))
           (rec (cons remains nodes-visited) (cdr remains))))))
  (rec '() l))

(define (last-pair x)
  (if (null? (cdr x))
      x
      (last-pair (cdr x))))

(define a '(a b c))
(has-cycle? a)
(set-car! (last-pair a) a)
a
(has-cycle? a)

(define b '(a b c))
(set-car! b (last-pair b))
b
(has-cycle? b)

(define c '(a b c d))

(set-car! (cddr c) (cdr c))
c
(has-cycle? c)

(define d (cons 'z a))
d
(has-cycle? d)

(define e '(a b c d e))
e
(has-cycle? e)

How can it be improved?

  Exercise 3.19.  Redo exercise 3.18
  using an algorithm that takes only a
  constant amount of space. (This
  requires a very clever idea.)

I'm not sure how to fulfill this requirement so far.


texts: Optimizing string replacement program that uses recursion

texts:
I have the following string replacement program for a string of size 256:

I am replacing the string

  "\'"

with the string

  &apos;

Please suggest any modifications if needed or any mistake I have done.

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

int replace_str(char *SrcStr, char *SubStr, char *RepStr, char *FinalStr )
{

    static char buffer[256]="";
    char *TempStr= NULL;
    char *Tmp2 = malloc(250);
    memset(Tmp2,0,256);

    int ret = 0;

    TempStr = strstr(SrcStr, SubStr);

    if ( TempStr )
    {
        memcpy(Tmp2,TempStr,strlen(TempStr));

        strncpy(buffer, SrcStr, TempStr-SrcStr);

        buffer[TempStr-SrcStr] = '\0';
        sprintf(buffer+(TempStr-SrcStr), "%s%s", RepStr, Tmp2+strlen(SubStr));

        puts(buffer);
        free(Tmp2);
        ret = replace_str(buffer, SubStr, RepStr, FinalStr);
    }
    else
    {

        memcpy(FinalStr, buffer , strlen(buffer));

    }
    return ret;
}

int main(void)
{
    char *str1 = malloc(256);
    memset(str1, 0 ,256);
    memcpy(str1, "pra\'dipta\'kumar\'rout",strlen("pra\'dipta\'kumar\'rout"));

    char str2[10] = "&apos;";
    char str3[3] = "\'" ;
    char buff[256] ={0};

    replace_str(str1, str3, str2,buff);

    puts(buff);

    return 0;
}


texts:
After seeing this post on StackOverflow, I thought I'd try it out. What I have now is a diamond shape with numbers like this:

    1
   212
  32123
 4321234
543212345
 4321234
  32123
   212
    1

My code looks like this:

int i, j, k, n = 6, l = 3, o = 2;
for (i = 1; i <= 5; i++)
{
    for (k = n; k >= 1; k--)
    {
        Console.Write(" ");
    }
    n--;
    for (j = i; j >= 1; j--)
    {
        Console.Write(j);
    }
    o = 2;
    for (j = 1; j < i; j++)
    {
        Console.Write(o);
        o++;
    }
    Console.WriteLine();
}
for (i = 4; i >= 1; i--)
{
    for (k = l; k >= 1; k--)
    {
        Console.Write(" ");
    }
    l++;
    for (j = i; j >= 1; j--)
    {
        Console.Write(j);
    }
    o = 2;
    for (j = i; j > 1; j--)
    {
        Console.Write(o);
        o++;
    }
    Console.WriteLine();
}
Console.Read();

I don't think this is a nice solution for this task. Is there any nicer and shorter way to solve this without using that many loops?


texts:
I have developed Mockingbird a mocking framework for c++, it depends on function injection, here is the code from the repository:
/*
 *  Mockingbird is a simple and a powerful mocking framework for c++.
 *  Copyright (c) Mouaz Chamieh April 2021.
 *  Distributed under the MIT License. Please refer to the LICENSE file at:
 *  https://github.com/muazsh/Mockingbird
 */

#pragma once
#ifndef MOCKINGBIRD
#define MOCKINGBIRD

#define START_MOCK(MockingClass, MockedClass)\
class MockingClass : public MockedClass {\
 public:

#define INJECTION_SET(FuncName, Substitute)\
private:\
template<class T>\
class FuncName##Class {\
public:\
FuncName##Class():m_func((T)Substitute){}\
T m_func;\
};\
FuncName##Class<decltype(Substitute)> m_##FuncName##Class;\
mutable int m_##FuncName##CallCounter = 0;\
public:\
void Inject##FuncName(decltype(Substitute) sub){\
m_##FuncName##Class.m_func = sub;}\
int Get##FuncName##CallCounter(){return m_##FuncName##CallCounter;}

#define FUNCTION(FuncName,ReturnType, Signature, Substitute, .../*signature variables*/)\
INJECTION_SET(FuncName, Substitute)\
ReturnType FuncName Signature override\
{ m_##FuncName##CallCounter++;\
return m_##FuncName##Class.m_func(__VA_ARGS__);}

#define CONST_FUNCTION(FuncName,ReturnType, Signature, Substitute, .../*signature variables*/)\
INJECTION_SET(FuncName, Substitute)\
ReturnType FuncName Signature const override\
{ m_##FuncName##CallCounter++;\
return m_##FuncName##Class.m_func(__VA_ARGS__);}

#define OVERLOAD_INJECTION_SET(FuncName, Substitute, overloadedMethodNumber)\
private:\
FuncName##Class<decltype(Substitute)> m_##FuncName##Class##overloadedMethodNumber;\
mutable int m_##FuncName##overloadedMethodNumber##CallCounter = 0;\
public:\
void Inject##FuncName(decltype(Substitute) sub){\
m_##FuncName##Class##overloadedMethodNumber.m_func = sub;}\
int Get##FuncName##overloadedMethodNumber##CallCounter(){return m_##FuncName##CallCounter;}

#define FUNCTION_OVERLOADING(FuncName,ReturnType, Signature, Substitute, overloadedMethodNumber, .../*signature variables*/)\
OVERLOAD_INJECTION_SET(FuncName, Substitute, overloadedMethodNumber)\
ReturnType FuncName Signature override\
{ m_##FuncName##overloadedMethodNumber##CallCounter++;\
return m_##FuncName##Class##overloadedMethodNumber.m_func(__VA_ARGS__);}

#define CONST_FUNCTION_OVERLOADING(FuncName,ReturnType, Signature, Substitute, overloadedMethodNumber, .../*signature variables*/)\
OVERLOAD_INJECTION_SET(FuncName, Substitute, overloadedMethodNumber)\
ReturnType FuncName Signature const override\
{ m_##FuncName##overloadedMethodNumber##CallCounter++;\
return m_##FuncName##Class##overloadedMethodNumber.m_func(__VA_ARGS__);}

#define END_MOCK(MockingClass)\
};

#endif // !MOCKINGBIRD

and here is an example on how it works:
Assume you have the following class Foo and you need to mock:
struct MyStruct{
    int x, y;
};

class Foo{
public:
    virtual const MyStruct CreateMyStruct(int x, int y) { return MyStruct{ x,y }; }
};

Then you write a testing fixture only once for the whole project:
const MyStruct CreateMyStructDummy(int x, int y) { return MyStruct{0,0}; }

START_MOCK(FooMock, Foo)
FUNCTION(CreateMyStruct, const MyStruct, (int x, int y), &CreateMyStructDummy, x, y)
END_MOCK(FooMock)

Then in the tests you write the desired substitute for example:
const MyStruct CreateMyStructSubstitute(int x, int y) { return MyStruct{ x + 10, y + 10 }; }

and inject it like:
FooMock fooMock;
fooMock.InjectCreateMyStruct(CreateMyStructSubstitute); // Mocking function injection.
auto created = fooMock.CreateMyStruct(5,5);
EXPECT_EQ(created.x, 15);
EXPECT_EQ(created.y, 15);

The code is in the file Mockingbird.hpp and totally depends on macros, it is short and straightforward, I ask for reviewing the code on github here, thanks.


texts: Strategy pattern instances based on enums

texts:
I have a view which takes a DataPresenterStrategy instance to retrieve the proper text out of some data:

public interface DataPresenterStrategy {

    String getDisplayString(Data data);

    String getUnit();
}

public class DistanceStrategy implements DataPresenterStrategy {

    @Override
    public String getDisplayString(Data data) {
        return data.getDistance();
    }

    @Override
    public String getUnit() {
         return "m";
    }
}

public class PowerStrategy implements DataPresenterStrategy {

    @Override
    public String getDisplayString(Data data) {
        return data.getPower();
    }

    @Override
    public String getUnit() {
         return "W";
    }
}

Based on some enum, I know which DataPresenterStrategy to create:

enum DataPresenterStrategyType { DISTANCE, POWER }

DataPresenterStrategy toStrategy(StrategyType type) {
    switch(type) {
        case DISTANCE:
            return new DistanceStrategy();
        case POWER:
            return new PowerStrategy();
    }
}

Obviously, this is simplified. In my actual code I have 25 of those Strategy classes.
Is there a better way to do this DataPresenterStrategy instance creation?

Usage in views:

public interface DataPresenter {
    void setDataPresenterStrategy(DataPresenterStrategy strategy);
}

public class DataView implements DataPresenter {

    private DataPresenterStrategy mDataPresenterStrategy;

    @Override
    public void setDataPresenterStrategy(DataPresenterStrategy strategy) {
        mDataPresenterStrategy = strategy;
    }

}

public class MyApplication {

    private DataPresenter[] mDataPresenters;

    public void setDataPresenterStrategy(int dataPresenterIndex, DataPresenterStrategyType type) {
        switch (type)
          /* (...) */
    }

}

setDataPresenterStrategy(int, DataPresenterStrategyType) is called when a user selects an item from a spinner:

class MyOnItemSelectedListener implements OnItemSelectedListener {

    private int mPresenterIndex;

    public OnItemSelectedListener(int presenterIndex) {
        mPresenterIndex = presenterIndex;
    }

    void onItemSelected(int which) {
         setDataPresenterStrategy(mPresenterIndex, DataPresenterStrategyType.values()[which];
    }

}


texts:
I'm learning how to use Python with the Raspberry Pi. I successfully followed the tutorial for how to have a Python script run on the Pi to check for new email and turn on an LED if any new messages are in an inbox. I wanted to give myself a challenge by adding a feature to blink a secondary LED to indicate the number of waiting messages. I played around for a while and got a script working, but would like to know if I implemented this correctly.

Am I using threading correctly? Is there an easier way to check a feed every n seconds, and if new messages are present, then continually run blink() until the next feed check?

#!/user/bin/env python

from threading import Thread, Event
from time import sleep
import feedparser
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
BLUE_LED = 17
BIG_LED = 23
GPIO.setup(BLUE_LED, GPIO.OUT)
GPIO.setup(BIG_LED, GPIO.OUT)

USERNAME = "user@gmail.com"
PASSWORD = "gzvioCNiAvFvKoqY"

class Repeat(Thread):
    def __init__(self,delay,function,*args,**kwargs):
        Thread.__init__(self)
        self.abort = Event()
        self.delay = delay
        self.args = args
        self.kwargs = kwargs
        self.function = function
    def stop(self):
        self.abort.set()
    def run(self):
        while not self.abort.isSet():
            self.function(*self.args,**self.kwargs)
            self.abort.wait(self.delay)

def blink(count):
    for x in range(0, count):
        print "blink", x + 1
        GPIO.output(BLUE_LED, True)
        sleep(.25)
        GPIO.output(BLUE_LED, False)
        sleep(.25)
    sleep(1) #pause between blinks

try:
    while True:

        print "Starting b"
        b = Repeat(1,blink,0)
        b.start()
        big_led = 0

        print "---> ---> Checking feed"
        messages = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])

        if messages >= 1:
            # turn on big LED
            print "Turning on Big LED"
            GPIO.output(BIG_LED, True)
            big_led = 1
            print "There are", messages, "unread email messages"
            b = Repeat(1,blink,messages)
            b.start()
        else:
            print "There are no new messages"
            if big_led == 1:
                print "Turning off Big LED"
                GPIO.output(BIG_LED, False)

        sleep(60) # check the feed every minute for new mail
        print "Stopping b"
        b.stop()
        b.join()
except (KeyboardInterrupt, SystemExit):
    b.stop()
    b.join()
    GPIO.cleanup()
    print 'Program Stopped Manually!'
    raise


texts: Basic Makefile to create .expected files

texts:
I wrote a simple Makefile to build .expected files and compare them. It works as expected and I was wondering it would be great if I could get some feedback. More specifically if I followed all conventions and if it can be improved upon. This is my first Makefile.

# Relative path
RELATIVE_PATH=..
APSSCHED=$(RELATIVE_PATH)/bin/apssched
EXAMPLES=$(RELATIVE_PATH)/examples
BASE=.:$(RELATIVE_PATH)/base:$(EXAMPLES)
FLAGS=-DCOT
CASES=simple-binding1 simple-binding2 simple-binding3

# Generate output and store it in a file
%.output: $(EXAMPLES)/%.aps
    $(APSSCHED) $(FLAGS) -p $(BASE) $(basename $<) > $@

# Copy actual output as expected
%.expected: %.output
    cp -f $< $@

# Compare actual output with expected
.PHONY: %.compare
%.compare: %.output
# maybe there is a better way without using basename ...
    diff $(basename $@).expected $<

# Generate and verify all outputs
.PHONY: all
all: $(addsuffix .compare,$(CASES))

# Regenerate expected output
.PHONY: build.expected
build.expected: $(addsuffix .expected,$(CASES))

.PHONY: clean.expected
clean.expected:
    -rm -f *.expected


texts: Changing the background color when a link is clicked

texts:
What I'm trying to do is to change the background color when a link is clicked (in this case a list item). When it is no longer clicked, it should revert back to its normal color.

I was able to get this to work via the jQuery addClass and removeClass methods, but this seems to be hardcoding it.

jsFiddle

$(document).ready(function() {
    $(".nav > li:first-child").click(function(){
      $(this).addClass("highlighted");
      $(".nav > li:nth-child(2), .nav > li:nth-child(3), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:nth-child(2)").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(3), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:nth-child(3)").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(2), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:last-child").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(2), .nav > li:nth-child(3)").removeClass("highlighted");
    });
});


texts:
On my application, I have a JavaScript cycle that updates tag contents on my page regularly:

<script type="text/javascript">
    var players = [];
    players.push($('#p0'));
    players.push($('#p1'));
    players.push($('#p2'));
    players.push($('#p3'));
    i=0;
    /*
     * cycle through the players.
     */
    function cyclePlayer() {
        players[i].parents(".card-header").addClass('border-success');
        players[i].load('play.php?p='+i);
        i = ++i % players.length;
        $('#deck').load('play.php?deck=1');
        $('#pile').load('play.php?pile=1');
        $('#feedback').load('play.php?feedback=1');
    }
    PlayerLoop = setInterval('cyclePlayer()', 1500 );

    $("#stop").click(function(){
        clearInterval(PlayerLoop);
    });

    $('#reset').click(function() {
        $('#deck').load('play.php?reset=1');
        location.reload();
    });
</script>

The server code that is being called looks like this:

<?php
require '../vendor/autoload.php';

session_start();

use Svc\Myapp\FrontHandler;

$myApp = new FrontHandler();

if (isset($_GET['p']) && !isset($_SESSION['winner'])) {
    echo $myApp->playerTurn();
}

if (isset($_GET['deck'])) {
    echo $myApp->deckUpdate();
}

if (isset($_GET['pile'])) {
    echo $myApp->pileUpdate();
}

if (isset($_GET['feedback'])) {
    echo $myApp->feedbackUpdate();
}

Is this production quality code? Is there a way to refactor it to improve it?