texts: User input function keep looping until valid filename entered

texts:
The following function is basically asking the user to input a file name for a file that the calling program is going to do something with.  If the user enters an invalid file name, I want the program to loop back and give them another chance.  The code works, but is this the proper way to accomplish this?  Also, are there other errors that could get triggered that I should deal with?

def get_filename(file_type):
    while True:
        print('enter ' + file_type + ' filename: ')
        filename = input()
        print(filename)
        try:
            with open(filename, 'r') as f:
                my_file = f.read()
            return my_file
        except FileNotFoundError:
            print('No such file.  Check file name and path and try again.')

x = get_filename('TEMPLATE')
print(x)


texts:
I've created a wrapper for the SimpleCrypt library that allows to easily encrypt/decrypt a string.

The application is used this :

//To encrypt
python encryptor.py file_name -e

//To decrypt
python encryptor.py file_name -d

Basically, to encrypt, I read the file, encrypt it and create a new file with the extension .enc, so that it's obvious (to me) it's been encrypted.

I'm not looking for a super secure application, I'm tutoring and when I leave my laptop alone I wouldn't want students to check their future exams or stuff like that. So it's more of a small project for my own fun, that protects files from non IT people.

I think I've covered every cases (Permission denied, file doesn't exist, wrong password etc).

I think the code could look better, but I'm mostly interested in knowing if I missed some bug I'm not aware of (As I said, I tested the application to the best of my knowledge) or if there are some Python basics that I missed.

  encryptor.py

import sys
import os.path
import getpass
import simplecrypt

ReadMode = "r"
WriteMode = "w"
EncryptArg = "-e"
DecryptArg = "-d"
PermissionDenied = 13
FileDoesNotExist = 2

def main():
    if not len(sys.argv) == 3:
        print "Incorrect number of arguments."
        print "Expected file-path encrypt/decrypt"
        exit(1)

    filepath = sys.argv[1]
    encrypt_or_decrypt = sys.argv[2]

    if not (encrypt_or_decrypt == EncryptArg or encrypt_or_decrypt == DecryptArg):
        print "2nd argument provided is invalid, expected -e or -d, received : " + encrypt_or_decrypt
        exit(1)

    requires_encryption = encrypt_or_decrypt == EncryptArg

    try:
        stream = open(filepath, ReadMode)
        file_content = stream.read()
        stream.close()

        if requires_encryption:
            password = getpass.getpass("Password to decrypt : ")
            encrypted_content = simplecrypt.encrypt(password, file_content)

            write_stream = open(filepath + ".enc", WriteMode)
            write_stream.write(encrypted_content)
            write_stream.close()
        else:
            if not filepath[-4:0] == ".enc":
                print "File was not encrypted using this application. Expected .enc format."
                exit(1)

            decrypted_content = None
            try:
                password = getpass.getpass("Password : ")
                decrypted_content = simplecrypt.decrypt(password, file_content)
            except simplecrypt.DecryptionException:
                print "Password is invalid."
                exit(1)

            write_stream = open(filepath[:-4], WriteMode)
            write_stream.write(decrypted_content)
            stream.close()

        os.remove(filepath)

    except IOError, ioError:
        if ioError.errno == PermissionDenied:
            print "You do not have permission to access this file. Consider using sudo"
        elif ioError.errno == FileDoesNotExist:
            print "File does not exist."
        else:
            raise ioError

        exit(1)

if __name__ == '__main__':
    main()


texts:
This code is a page scraper using HtmlAgilityPack that creates a DOM document upon construction and allows for node manipulation afterward.

HtmlAgilityPack uses XPath Selectors for selecting nodes.

An example use case would look like:

var me = new PageScraper("http://codereview.stackexchange.com/users/62429/quill", Console.WriteLine);
var usernameNode = me.FetchNode("//h2[@class=user-card-name]");
var username = PageScraper.FetchNodeText(usernameNode);

This is the PageScraper class, the only class in the Scraper namespace so far.

The reason I pass in an Action is so that I can attach log messages to a Forms list box.

using System;
using System.Net;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace Scraper
{
    public class PageScraper
    {
        private readonly HtmlDocument _document;
        public Action<string> Print { get; set; }
        public PageScraper(string url, Action<string> print)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("url is empty");
            }
            Print = print;
            WebClient webClient = new WebClient();
            Print("downloading page");
            string urlWithoutNewLineCharacters = StripNewLineCharactersAndSpaces(url);
            string html = webClient.DownloadString(urlWithoutNewLineCharacters);
            _document = new HtmlDocument();
            _document.LoadHtml(html);
            Print("loading page");
        }
        public HtmlNodeCollection FetchLinks()
        {
            Print("fetching links");
            return _document.DocumentNode.SelectNodes("//a[@href]");
        }

        public HtmlNodeCollection FetchNodes(string selector)
        {
            Print("fetching nodes");
            return _document.DocumentNode.SelectNodes(selector);
        }

        public HtmlNode FetchNode(string selector)
        {
            Print("fetching node");
            return _document.DocumentNode.SelectSingleNode(selector);
        }

        public static string FetchNodeText(HtmlNode node)
        {
            if (node != null && node.InnerText != null)
            {
                return node.InnerText;
            }
            return string.Empty;
        }
        public static string FetchNodeHref(HtmlNode node)
        {
            if (node != null && node.Attributes["href"].Value != null)
            {
                return node.Attributes["href"].Value;
            }
            return string.Empty;
        }
        private static string StripNewLineCharactersAndSpaces(string str)
        {
            return Regex.Replace(str, @"\t|\n|\r| |\s+", string.Empty);
        }
    }
}


texts:
To practice my C, I've written a small function in C to display an integer as an 8-bit binary number. Please let me know how to improve this function, and other C-style coding conventions. Thanks!
/**
 * Converts an integer to binary.
 *
 * @param num Integer to convert.
 *
 * @return c-string.
**/
const char* to_binary(int num) {

    static char binary[10];
    binary[0] = '0';
    binary[1] = 'b';

    int value = 128;
    int number = num;

    for (int i = 2; i < 10; i++) {
        if (number - value >= 0) {
            binary[i] = '1';
            number = number - value;
        } else {
            binary[i] = '0';
        }
        value = value / 2;
    }

    return binary;

}

And here's how you call it:
int main() {

    const char* result = to_binary(146);

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

}


texts: Do I need to remove these event listeners?

texts:
The following ActionScript code just downloads and attempts to parse some JSON from an API service. Inside the method I have defined a cleanUp() function, just to remove 2 event listeners.

I think these event listeners will be garbage collected anyway though, so is it worth it? I would prefer to just use 2 anonymous functions for the listeners.

private function sendRequest(cmd:String, params:Object = null) :Promise{

    var d:Deferred = new Deferred(),
        vars:URLVariables = new URLVariables('cmd=' + cmd),
        req:URLRequest = new URLRequest(),
        loader:URLLoader = new URLLoader();

    if(params){
        for(var paramKey:String in params){
            vars[paramKey] = params[paramKey];
        }
    }

    req.url = url;
    req.requestHeaders = [new URLRequestHeader('Accept', 'application/json')];
    req.method = URLRequestMethod.POST;
    req.data = vars;

    function onComplete(e:Event) :void{
        var res:Object;

        try{
            d.resolve(JSON.parse(e.target.data));
        }
        catch(err:Error){
            d.reject(err);
        }
        finally{
            cleanUp();
        }
    }

    function onError(err) :void{
        d.reject(err);
        cleanUp();
    }

    function cleanUp() :void{
        loader.removeEventListener(Event.COMPLETE, onComplete);
        loader.removeEventListener(IOErrorEvent.IO_ERROR, onComplete);
    };

    loader.addEventListener(Event.COMPLETE, onComplete);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onError);

    loader.load(req);

    return d.promise;
};


texts: Setting up a development environment - 2

texts:
This is the new code after following the advice from here:

Setting up a development environment

General feedback is requested.  Also, should I be using $() or () for my sub-shell.  What is the difference.

#
#
#
# Divider - configures bash, git, grunt, sublime and chrome
#
#
#

user1=foo

config_bash() {
    rm ~/.bash_profile
    ln -sf ~/root/config/bash/login.sh ~/.bash_profile
    source ~/.bash_profile
    echo "Bash configured."
}
config_git() {
    local a
    if [ $# -eq 0 ]
    then
        a="client"
    fi

    if [ $# -eq 1 ]
    then
        a="$1"
    fi

    if [ $# -gt 1 ]
    then
        a="$1"
        echo "Git-tooo many arguments"
    fi

    git config --global user.name "$a"
    git config --global user.email "$a@$a.com"

    git config --global push.default matching
    git config --global core.editor "subl"

    git remote add godaddy $user1@arcmarks.com:~/root.git
    git remote add heroku https://git.heroku.com/frozen-dusk-2587.git
    echo "Git configured."
}
config_grunt() {
    sudo npm install -g grunt-cli
    mkdir -p ~/root_install/grunt
    ln -sf ~/root/config/grunt/package.json ~/root_install/grunt/package.json
    ln -sf ~/root/config/grunt/Gruntfile.js ~/root_install/grunt/Gruntfile.js
    (cd ~/root_install/grunt; npm install)
    cd ~/root
    echo "Grunt configured."
}
config_sublime_2() {
    ln -sf /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
    rm -rf ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User
    ln -sf ~/root/config/sublime ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User
    echo "Sublime configured."
}
reset_sublime_2() {
    rm -rf ~/Library/Application\ Support/Sublime\ Text\ 2
}
config_chrome(){
    chmod 0444 ~/Library/Application\ Support/Google/Chrome/Default/History
    echo "Chrome configured."
}
config_all() {
    config_bash
    config_git
    config_grunt
    config_sublime_2
    config_chrome
    list
}
list(){
    local bash=$(which bash) git=$(which git) grunt=$(which grunt) subl=$(which subl)
    local node=$(which node)  heroku=$(which heroku)
    echo "****"
    echo "Your bash executble is here: $bash."
    echo "Your git executble is here: $git."
    echo "Your grunt executble is here: $grunt."
    echo "Your sublime executble is here: $subl."
    echo "Your node executble is here: $node."
    echo "Your heroku executble is here: $heroku."
    echo "****"
}


texts: Replacing elements from a list and its sublists

texts:
Write a procedure substitute that takes three arguments: a list, an old word, and a new word. It should return a copy of the list, but with every occurrence of the old word replaced by the new word, even in sublists. For example:
> (substitute ’((lead guitar) (bass guitar) (rhythm guitar) drums) ’guitar ’axe)
((lead axe) (bass axe) (rhythm axe) drums)

source
The argument "l" is the list that would be evaluated, I just don't know what name is appropriate because the word "list" is already a procedure. Subl will evaluate the items that are lists.
Please review my code.
(define (substitute l old new)
    (if (null? l) '()
        (let ((head (car l))
            (tail (cdr l))
            (subl (lambda (x) (substitute x old new))))
            (cond ((list? head) (cons (subl head) (subl tail)))
            ((equal? head old) (cons new (subl tail)))
            (else (cons head (subl tail)))))))

How is my use of let and lambda? Did I manage data abstraction correctly? How can I make this code better and faster?


texts: Move an element up / down an array in Javascript

texts:
I have an array called list bound to the current application scope $scope that is a user order-able list of UI components. When clicking the up / down arrays these functions are responsible for moving the element by re-inserting it in the correct place.

$scope.moveUp = function(index)
{
    if (index === 0) {
        return;
    }
    $scope.list.splice(index - 1, 0, $scope.list.splice(index, 1)[0]);
};

$scope.moveDown = function(index)
{
    if (index === $scope.list.length - 1) {
        return;
    }
    $scope.list.splice(index + 1, 0, $scope.list.splice(index, 1)[0]);
};


texts:
I have following in Windows Forms .NET 3.5

It works fine for csv with records less than 10,000 but is slower for records above 30,000.
Input csv  file can can any records between 1 - 1,00,000 records

Code currently used :

/// <summary>
        /// This will import file to the collection object
        /// </summary>
        private bool ImportFile()
        {
            try
            {

                String fName;
                String textLine = string.Empty;
                String[] splitLine;

                // clear the grid view

                accountsDataGridView.Rows.Clear();

                fName = openFileDialog1.FileName;

                if (System.IO.File.Exists(fName))
                {
                    System.IO.StreamReader objReader = new System.IO.StreamReader(fName);

                    do
                    {
                        textLine = objReader.ReadLine();
                        if (textLine != "")
                        {
                            splitLine = textLine.Split(',');
                            if (splitLine[0] != "" || splitLine[1] != "")
                            {
                                accountsDataGridView.Rows.Add(splitLine);
                            }
                        }
                    } while (objReader.Peek() != -1);
                }
                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The process cannot access the file"))
                {
                    MessageBox.Show("The file you are importing is open.", "Import Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }

                return false;
            }

        }

Sample Input file :

18906,Y
18908,Y
18909,Y
18910,Y
18912,N
18913,N

Need some advice on optimizing this code for fast reads & view in grid.


texts: Is this how to implement MVP and ICommand patterns in WinForms?

texts:
I'm learning about the MVP and ICommand design patterns as I'd like to use them in my own projects.  I've cobbled this very simple WinForm application together to hopefully demonstrate that I'm using the patterns in the right way.

I was wondering if someone who is more familiar with both patterns could eye ball this project I stuck on GitHub to check that I'm at least heading in the right direction.  https://github.com/sulphy/PatternExample

The project simply consist of a view, its associated presenter and a message box command that I attach to a button on the view.  The objects are instantiated in program.cs.

Program.cs

  var formObject = new ExampleView();
  var commandObject = new SimpleMessageBoxCommand(formObject);
  var presenterObject = new ExamplePresenter(formObject, commandObject);
  Application.Run(formObject);

ExampleView.cs

  public partial class ExampleView : Form, IExampleView
    {
        public ExampleView()
        {
            InitializeComponent();
        }

        public Button SubmitButton()
        {
            return this.btnSubmit;
        }

        public TextBox ViewTextBox()
        {
            return this.txtFreetext;
        }

        public void SetViewTitle(string titleText)
        {
            this.Text = titleText;
        }
    }

    public interface IExampleView
    {
        Button SubmitButton();
        TextBox ViewTextBox();
        void SetViewTitle(string titleText);
    }

ExamplePresenter:

 public class ExamplePresenter
    {
        private IExampleView exampleView;
        private ICommand command;

        public ExamplePresenter(IExampleView exampleView, ICommand command)
        {
            this.exampleView = exampleView;
            this.command = command;

            exampleView.SetViewTitle( "An Example Form");

            exampleView.SubmitButton().Click += new EventHandler(SubmitButton_OnClick);
        }

        public void SubmitButton_OnClick(object sender, EventArgs e)
        {
            command.Execute();
        }
    }

SimpleMessageBoxCommand.cs

  public class SimpleMessageBoxCommand : ICommand
    {
        private IExampleView exampleView;

        public SimpleMessageBoxCommand(IExampleView exampleView)
        {
            this.exampleView = exampleView;
        }

        public void Execute()
        {
            var textString = exampleView.ViewTextBox().Text;
            MessageBox.Show(textString);
            exampleView.ViewTextBox().Focus();
        }
    }


texts: Add 1 to an integer represented as an array of digits

texts:
Problem Statement

This is another LeetCode question I came across, where I need to add 1 to a number.

The number is represented as an integer array where each index position is a digit and therefore a number from 0-9. There are no leading zeros except for the number 0 itself.
The index position 0, that is arr[0] represents the MSB and the index position n-1, that is
arr[n-1] represents the LSB.

Thus, we need to add one to the LSB and return the number as an integer array. Here is the code which I wrote (it got accepted, passed all test cases) :

class Solution
{
    public int[] plusOne(int[] digits)
    {
        int carry = 0,
        len = digits.length;

        int i = len - 1;

        if (len == 0)
            return digits;

        if (len == 1 && digits[0] < 9)
        {
            digits[0] += 1;
            return digits;
        }

        if (len == 1 && digits[0] == 9)
        {
            digits[0] = 0;
            digits = resize(digits, 2);
            return digits;
        }

        do
        {
            digits[i] += 1;

            if (digits[i] == 10)
            {
                digits[i] = 0;
                carry = 1;
            }
            else
            {
                carry = 0;
                return digits;
            }

            i--;
        }
        while (carry == 1 && i > -1);

        if (carry == 1)
        {
            digits = resize(digits, len + 1);
            carry = 0;
        }

        return digits;
    }
    private int[]  resize(int[] arr, int size)
    {
        int[] copy = new int[size];
        int i;

        copy[0] = 1;

        for (i = 1; i < size; i++)
            copy[i] = arr[i-1];

        return copy;
    }
}

Analysis

Running Time : O(n) in the worst case
Total Space  : O(n) in the worst case
Worst Case   : When adding 1 to a m-digit number results in an (m+1) digit number
(eg. 999 + 1 = 1000)

Questions

Is there a better way to solve this problem? (I mean, a different but more efficient algorithm than mine)
I got a performance of only 29% with this solution no matter how many times I submitted the code, so definitely my algorithm is inefficient
Instead of using a resizing array, should I be using an array list if I want better performance?
Can ArrayList handle the overflow condition better than resizing array?
Should I be using the resizing array technique at all?
Is it less efficient?
Is O(n) the best possible running time for the problem?
I don't see how we can do it O(log n) or less.

Further Notes

Here is a link to the Github repository which has the above code with more comments: PlusOne.java


texts: Handling null arguments in a factory class

texts:
I have a Factory class that gives out instances of ResponseImpl class. It accepts one Destination class and up to four Source classes. At least one of the four Source classes should be not null.

So, instead of asking calling program to pass nulls in the arguments to Factory class, I have overloaded the method to accept at least one up to four Source classes. But, something tells me that this way of doing it is not a good idea. Although this works, I feel like this can be handled better.

Could you let me know how to make the following piece of code better?

public static Response initResponse(final Destination destination, final Source1 source1) {
    return initResponse(destination, source1, null, null, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2) {
    return initResponse(destination, source1, source2, null, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3) {
    return initResponse(destination, source1, source2, source3, null);
}

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {
    try {
        if(source1 == null && source2 == null && source3 == null && source4 == null) {
            throw new ABODataException("Atleast one source has to be not null");
        }
        return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);
    } catch (Exception e) {
        throw new ABODataException("Unable to instantiate Response:"+e.getMessage());
    }
}


texts: Efficient way to remove duplicate strings after adding their key values

texts:
How can I remove duplicate strings from a std::vector<std::pair<std::string,int>> after adding the int members of the pair and sorting them by their string members?

For example:

abc   4
abc   3
xy    1
xyzw  12
xy    4
abc   14

should produce the result:

abc   21
xyzw  12
xy    5

I have actually used std::vector<Mystruct> as the data structure, with:

struct Mystruct
{
    string s;
    int e;
};

and sorted them with respect to their string values and linearly iterated by adding the keys and removing duplicates, and again sorted according to their key values and ended up getting Time Limit Exceeded.

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
#define ull unsigned long long
struct vec
{
    string s;
    ull e;
};
bool compare(vec v1, vec v2) {
    return v1.s < v2.s;
}
bool comparenum(vec v1, vec v2) {
    return v1.e < v2.e;
}
int main() {
    int q;
    cin >> q;
    string ss;
    ull ee;
    vector<vec> v(q);
    for (int i = 0; i<q; i++) {
        cin >> ss >> ee;
        v[i].s = ss;
        v[i].e = ee;
    }
    sort(v.begin(), v.end(), compare);
    for (int i = 0; i < v.size() - 1; i++) {
        if (v[i + 1].s == v[i].s) {
            v[i].e = v[i].e + v[i + 1].e;
            v.erase(v.begin() + i + 1);
            i--;
        }
    }
    sort(v.begin(), v.end(), comparenum);
    for (vec vv : v) {
        cout << vv.s << " " << vv.e << endl;
    }
    return 0;
}


texts: Test if a key-value pair exists in nested object in Typescript

texts:
I wrote a function to check if a nested object contains the key-value pair matched as parameter as following.
eq:
const obj ={
   "a":{
      "b":{
         "c1":["1","2"],
         "c2":"3"
      },
      "b2":"values",
      "b3": {"c5": "v"},
   },
   "a2":["v1","v2"],
   "a3":"v1"
}
checkNestedObjectByKeyValue(obj, "a3", "v1") // true
checkNestedObjectByKeyValue(obj, "a3", "v2") // false
checkNestedObjectByKeyValue(obj, "a2", ["v1","v2"]) // true
checkNestedObjectByKeyValue(obj, "a3", "v1") // true
checkNestedObjectByKeyValue(obj, "b3", {"c5": "v"}) // true

function checkNestedObjectByKeyValue(
  obj: Record<string, any>,
  objKey: string,
  objValue: string | Array<string>
): boolean {

  if (typeof obj !== 'object') return false;
  if (obj.hasOwnProperty(objKey)) {

    return JSON.stringify(obj[objKey]) === JSON.stringify(objValue)
  }
  for (const value of Object.values(obj)) {
    if (checkNestedObjectByKeyValue(value, objKey, objValue)) return true
  }
  return false
}


texts: Converting a binary string to hexadecimal using Rust

texts:
Once again, I am reinventing the wheel here to understand the fundamentals of rust. In a previous question I requested feedback on my function that performed a hexadecimal to binary conversion. In this snippet, I am seeking some constructive feedback on converting from binary to hexadecimal.

fn main() {

    let hexadecimal_value = convert_to_hex_from_binary("10111");
    println!("Converted: {}", hexadecimal_value);
}

fn convert_to_hex_from_binary(binary: &str) -> String {
    let padding_count = 4 - binary.len() % 4;

    let padded_binary = if padding_count > 0 {
        ["0".repeat(padding_count), binary.to_string()].concat()
    } else {
        binary.to_string()
    };

    let mut counter = 0;
    let mut hex_string = String::new();
    while counter < padded_binary.len() {
        let converted = to_hex(&padded_binary[counter..counter + 4]);
        hex_string.push_str(converted);
        counter += 4;
    }

    hex_string
}

fn to_hex(b: &str) -> &str {
    match b {
        "0000" => "0",
        "0001" => "1",
        "0010" => "2",
        "0011" => "3",
        "0100" => "4",
        "0101" => "5",
        "0110" => "6",
        "0111" => "7",
        "1000" => "8",
        "1001" => "9",
        "1010" => "A",
        "1011" => "B",
        "1100" => "C",
        "1101" => "D",
        "1110" => "E",
        "1111" => "F",
        _ => "",
    }
}


texts: Entity Framework - Add or Update Parent Entity with Children

texts:
This code saves an DomainEntityRecord (parent) and DomainEntityDetailRecords (child), and it works. It feels odd that I get the record from the DB, then remove the entities that don't exist in the domain model version, then when I save, I save (AddOrUpdate) the domain entities, and not the EF version. Maybe this is the right way?

public void Handle(SaveDomainEntity message)
{
  var domainEntityRecord = mapper.Map<DomainEntityRecord>(message);

  var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
    .Where(x => x.Id == domainEntityRecord.Id)
    .Include(x => x.DomainEntityDetailRecords)
    .SingleOrDefault();

  if (existingDomainEntity != null)
  {
    // Delete detail records that no longer exist.
    foreach (var existingDetail in existingDomainEntity.DomainEntityDetailRecords.ToList())
    {
      if (domainEntityRecord.DomainEntityDetailRecords.All(
        x => x.DetailId != existingDetail.DetailId))
      {
        dbContext.Set<DomainEntityDetailRecord>().Remove(existingDetail);
      }
    }
  }

  dbContext.Set<DomainEntityRecord>().AddOrUpdate(domainEntityRecord);

  domainEntityRecord.DomainEntityDetailRecords.ForEach(
    record => dbContext.Set<DomainEntityDetailRecord>().AddOrUpdate(record));

  dbContext.SaveChanges();
}


texts: Data item prototype in a Javascript data structure where object instance functions see own data

texts:
I'm working on a complex Javascript application which includes its own data structure. The previous version's data structure was rather chaotic, and I'm looking to replace it with something where:

Every data item is an object which is (effectively) an instance of a class, which imposes a common structure including default values
Where possible, functions which set or get the data in a data item are taken out of the controller logic and attached to the data item class prototype

The problem I'm trying to solve by introducing this structure is, lots of messy and inconsistent 'model' style logic buried deep in 'controller' style functions, which has led to inconsistency, type errors, missing data errors, duplicated logic, etc.

Here's an example which uses the exact same approach I'm taking to defining and accessing instances (but the contents of data structure itself is simplified, since my question is about the way it's defined and accessed). I know that Javascript doesn't exactly have object 'classes' the way other languages do, and I've read about approximating them using prototypes, but I may be doing it wrong. In particular:

Do I need an init() function? Seems fine without one.
Is this a robust approach to the instance object accessing its own data? Can I rely on this within the attached function always being the instance's own data each time the function is called? Or should I be prepared to use call() or wrap calls in an anonymous function, or set it as a variable like that or self?
Is this a good way to give a class of objects default values? Note that this application already uses jQuery for other non-negotiable reasons, hence $.extend, and namespacing is already covered
I put the defaults object in the prototype so it's not redefined each time a new instance is created. Am I right in thinking this is a better practice than defining it within the function?
My actual application isn't about currencies, so please don't comment on the business logic. The code for setting the class is taken straight from my actual application draft, but I did swap the actual parameters and functions with simpler examples (if I hadn't, the explanation of the parameters and purpose of the functions would be longer than the rest of this question combined, and I'd need tonnes of non-relevant code to give a working example)

var dataItem = function(values){
  // Initiate new instance
  $.extend(this,this.defaults,values);
};

dataItem.prototype.defaults = {
  // Structure & defaults for each data item
  value: 0.0,
  currency: 'USD'
};

dataItem.prototype.formatCurrency = function(){
  // Simple example of a 'getter' function
  var formatted = '';
  switch(this.currency) {
    case 'GBP':
      formatted = '£';
    break;
    case 'USD':
    case 'CAD':
    case 'AUD':
      formatted = '$';
    break;
  }
  return formatted+this.value.toFixed(2)+' '+this.currency;
};

// Some simple usage examples

var expenses = new dataItem({
  value: 199.5,
  currency: 'GBP'
});

var canadaIncome = new dataItem({
  currency: 'CAD'
})

var taxes = new dataItem({
  value: 60
})

document.write( expenses.formatCurrency() + ' : ' + canadaIncome.formatCurrency() + ' : ' + taxes.formatCurrency() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>


texts: Downloading images from websites by CSS selector

texts:
I wrote a small node.js module for downloading images from websites by CSS selector. I'd like to know what my mistakes are and how I can correct them. The code works correctly and was linted with jshint, but I'd like to get notes on readability and performance.

Here is the Github repo.

var Download = require('download');
var cheerio = require('cheerio');
var request = require('request');
var path = require('path');
var url = require('url');

// download image and save into dest
function downloadImgByUrl(url, dest) {
    new Download({mode: '755'})
        .get( url )
        .dest( dest )
        .run(function (err, file) {
            if (err) console.log(err);
        });
}

// download images by selector
function downloadImgsBySelector(url, dest, callback, selector) {
    request({ 'url': url },
      function (error, response, body) {
          if (error) {
              console.error(error);
              return;
          } else {
              // create page from response body
              var $ = cheerio.load(body);

              if (  !selector ) selector = 'img';

              // get images by selector
              var images = $(selector);

              // if no images found show message
              if ( !images.length ) console.log('There aren\'t any images by selector ', selector);

              images.each(function() {

                  // get src attribute
                  var imgSrc = $(this).attr('src');

                  // if path is relative transform to absolute
                  if ( !isPathAbsolute(imgSrc) ) {
                      imgSrc = transformPathToAbsolute(url, imgSrc);
                  }

                  // download image and save into dest
                  downloadImgByUrl(imgSrc, dest);
              });

              // invoke callback
              if ( typeof callback === 'function' ) callback();
          }
      }
    );
}

// check if path is absolute
function isPathAbsolute(path) {
    return path.charAt(0) != "#"               &&
        path.charAt(0) != "/"                  &&
        ( path.indexOf("//") == -1             ||
        path.indexOf("//") > path.indexOf("#") ||
        path.indexOf("//") > path.indexOf("?")
    );
}

// transform relative path to absolute
function transformPathToAbsolute(base, relativePath) {
    base = path.parse(base).dir;
    return url.resolve(base, relativePath);
}

// export
module.exports = downloadImgsBySelector;


texts: Factory design pattern with music classes

texts:
I found a definition of the factory design pattern as:

  Define an interface for creating an object, but let the subclasses decide which class to instantiate.

I understood the first part "defining interface for creation an object", but I am not able to understand the second part of "let subclasses decide which class to instantiate".

Is the following example a correct implementation of factory design pattern? If yes, please help to me to understand second part of definition with respect to the example.

        #include <iostream>
    using namespace std;

    enum genre_e{ROCK,POP, REGGAE, INVALID};

    /*Base Class*/
    class Music {
    public:
     virtual void song() = 0;
    };

    /*Derived class Rock from Music*/
    class Rock: public Music
    {
    public:
     void song()
     {
      cout<<"Nirvana: Smells like a teen spirit\n";
     }
    };

    /*Derived class Pop from Music*/
    class Pop: public Music
    {
    public:
     void song()
     {
      cout<<"Michael Jackson: Billie Jean\n";
     }
    };

    /*Derived class Reggae from Music*/
    class Reggae: public Music
    {
    public:
     void song()
     {
      cout<<"Bob Marley: No woman, No cry\n";
     }
    };

    /*Factory Class*/
    class MusicFactory
    {
    public:
     /*Factory Method*/
     Music *getMusic(genre_e genre)
     {
      Music *music = NULL;

      /*Logic based on Genre*/
      switch(genre)
      {
      case ROCK:
       music = new Rock();
       break;
      case POP:
       music = new Pop();
       break;
      case REGGAE:
       music = new Reggae();
       break;
      default:
       music = NULL;
       break;
      }
      return music;
     }
    };

    int main()
    {
     /*Create factory*/
     MusicFactory *musicFactory = new MusicFactory();

     /*Factory instantiating an object of type ROCK*/
     Music *music = musicFactory->getMusic(ROCK);

     cout<<"Song: ";
     if(music)
      music->song();
     else
      cout<<"Wrong selection dude/dudette !!";
    }


texts: Project Euler 6: Difference between sum of squares and square of sum

texts:
I've created a (very) simple solution for Project Euler problem 6:

  Project Euler Problem 6: Sum square difference

  The sum of the squares of the first ten natural numbers is,

  $$ 1^2 + 2^2 + ... + 10^2 = 385 $$

  The square of the sum of the first ten natural numbers is,

  $$ (1 + 2 + ... + 10)^2 = 55^2 = 3025 $$

  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \$3025 − 385 = 2640\$.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Solution:

   \$25164150\$

To solve this in F# was pretty simple: I simply declared a function square which would multiply an x by itself, then a function which would run through a list of numbers and add the square of the sum of them, and subtract the sum of the squares of each.

let square x =
    x * x

let calcDiffSquareSumFromSumSquares list =
    (list |> List.sum |> square) - (list |> List.sumBy square)

printfn "Solution to Project Euler 6: %i" (calcDiffSquareSumFromSumSquares [ 1 .. 100 ])

On this one, I'm particularly curious if there's a functional way to run through the list only once, calculate the total sum, and calculate the squares of sums so that I wouldn't need to use two sum methods.


texts: Codechef Deforestation problem: Finding maximum rope length between trees

texts:
Here is the CodeChef page to the problem.  Given N trees, each at x-position x with height T, string a rope between two trees Ti and Tj such that:

A rope connecting the tops of the trees is at 45 degrees from the x-axis
The rope does not pass through any other trees
The length of the rope, minus the total height reduction by cutting trees, is maximized
Trees Ti and Tj themselves are not cut

Here is my code that need to process 100 × 250,000 data in less than 3 seconds (I don't know the exact spec of the running machine).  As I'm quite new to coding, what can I improve or change to make it faster, and more optimized?

// codechef_deforestation.cpp : définit le point d'entrée pour l'application console.
//

#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <ctime>

int main()
{
    clock_t startTime = clock();
    //Read input
    freopen("C:\\somepath\\input.in", "r", stdin);
    freopen("C:\\somepath\\output.out", "w", stdout);
    int t;
    std::cin >> t;
    //std::cout << t << std::endl;
    for (int i = 0; i < t; i++)
    {
        double result = -1;
        int n;
        std::cin >> n;
        //std::cout << t << std::endl;
        std::vector <int> x, h;
        x.resize(n);
        h.resize(n);
        //chargement des données
        for (int j = 0; j < n; j++)
        {
            std::cin >> x[j] >> h[j];
            //std::cout << x[j] << h[j] << std::endl;
        }
        //calcul
        for (int j = 0; j < n; j++)
        {
            for (int k = j+1; k < n; k++)
            {
                //std::cout << "k : " << k << std::endl;
                int diff_x = x[k] - x[j];
                int diff_h = h[k] - h[j];
                if (diff_x == diff_h) //si 45 deg
                {
                    double res_int = sqrt(diff_x*diff_x + diff_h* diff_h);
                    for (int l = j + 1; l < k; l++)
                    {
                        //std::cout << "l : " << l << std::endl;
                        if (h[l] > x[l])
                        {
                            res_int = res_int - (h[l] - x[l]);
                        }
                    }
                    if (res_int > result)
                    {
                        result = res_int;
                    }
                }
            }
        }
        std::cout << std::setprecision(6) << std::fixed << result << std::endl;
        x.clear();
        h.clear();
    }
    clock_t testTime=clock();
    std::cout << testTime - startTime;
    return 0;
}

The freopen() function needs to stay.


texts: Incremental Sieve of Eratosthenes using iterators

texts:
I am in the process of learning Rust and am still having some issues with borrowing and ownership. I find myself trying to borrow mutable references that are already borrowed as immutable references etc...

I noticed that when I try to iterate over the primes without owning them, I encounter issues trying to modify the composites hash map. I was able to get around this by calling to_owned on the vector. Is this the right way to handle this?

I also see that when I build the code, I get warnings about unused code for warning: struct is never constructed: 'Sieve' and warning: method is never used: 'new', am I constructing them incorrectly?

use std::collections::HashMap;

struct Sieve {
    composites: HashMap<u64, Vec<u64>>,
    x: u64,
}

impl Sieve {
    fn new() -> Sieve {
        Sieve {
            composites: HashMap::new(),
            x: 2,
        }
    }
}

impl Iterator for Sieve {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        let x = self.x;
        self.x = self.x + 1;
        match self.composites.get(&x) {
            Some(numbers) => {
                for _num in numbers.to_owned() {
                    self.composites
                        .entry(x + _num)
                        .and_modify(|v| v.push(_num))
                        .or_insert(vec![_num]);
                }
                self.composites.remove(&x);
                self.next()
            }
            None => {
                self.composites.insert(x * x, vec![x]);
                Some(x)
            }
        }
    }
}

fn main() {
    let mut sieve = Sieve::new();

    println!("{:?}", sieve.next()); // 2
    println!("{:?}", sieve.next()); // 3
    println!("{:?}", sieve.next()); // 5
    println!("{:?}", sieve.next()); // 7
}

Here is the code on the Rust playground.

I previously posted a version of the Sieve of Eratosthenes using experimental Rust features, this made it difficult to get feedback on. I have refactored the code to use iterators


texts: Tower of Hanoi: graphical representation of optimal solution

texts:
I wrote a program to show graphically the solution of the problem of the Tower of Hanoi. Here is a video of an example run.

The logic of the solving is taken from StackOverflow (see links in docstring), I wrote the part dealing with the graphics, so review is most welcome on the graphical part that I wrote.

The code is pretty simple, tested and documented, so no further introduction is needed.

# -*- coding: utf-8 -*-
import doctest
import time
import pygame

SPACE_PER_PEG = 200

def hanoi(pegs, start, target, n):
    """
    From stackoverflow:
      http://stackoverflow.com/questions/23107610/towers-of-hanoi-python-understanding-recursion
      http://stackoverflow.com/questions/41418275/python-translating-a-printing-recursive-function-into-a-generator

    This function, given a starting position of an hanoi tower, yields
    the sequence of optimal steps that leads to the solution.

    >>> for position in hanoi([ [3, 2, 1], [], [] ], 0, 2, 3): print position
    [[3, 2], [], [1]]
    [[3], [2], [1]]
    [[3], [2, 1], []]
    [[], [2, 1], [3]]
    [[1], [2], [3]]
    [[1], [], [3, 2]]
    [[], [], [3, 2, 1]]

    """
    assert len(pegs[start]) >= n, 'not enough disks on peg'
    if n == 1:
        pegs[target].append(pegs[start].pop())
        yield pegs
    else:
        aux = 3 - start - target  # start + target + aux = 3
        for i in hanoi(pegs, start, aux, n-1): yield i
        for i in hanoi(pegs, start, target, 1): yield i
        for i in hanoi(pegs, aux, target, n-1): yield i

def display_pile_of_pegs(pegs, start_x, start_y, peg_height, screen):
    """
    Given a pile of pegs, displays them on the screen, nicely inpilated
    like in a piramid, the smaller in lighter color.
    """
    for i, pegwidth in enumerate(pegs):

        pygame.draw.rect(
            screen,
            # Smaller pegs are ligher in color
            (255-pegwidth, 255-pegwidth, 255-pegwidth),
            (
              start_x + (SPACE_PER_PEG - pegwidth)/2 , # Handles alignment putting pegs in the middle, like a piramid
              start_y - peg_height * i,         # Pegs are one on top of the other, height depends on iteration
              pegwidth,
              peg_height
            )
        )

def visual_hanoi_simulation(number_of_pegs, base_width, peg_height, sleeping_interval):
    """
    Visually shows the process of optimal solution of an hanoi tower problem.
    """
    pegs = [[i * base_width for i in reversed(range(1, number_of_pegs+1))], [], []]
    positions = hanoi(pegs, 0, 2, number_of_pegs)

    pygame.init()
    screen = pygame.display.set_mode( (650, 650) )
    pygame.display.set_caption('Towers of Hanoi')

    for position in positions:
        screen.fill((255, 255, 255))
        for i, pile in enumerate(position):
            display_pile_of_pegs(pile, 50 + SPACE_PER_PEG*i, 500, peg_height, screen)
        pygame.display.update()
        time.sleep(sleeping_interval)

    pygame.quit()

if __name__ == "__main__":
    doctest.testmod()
    visual_hanoi_simulation(
        number_of_pegs = 4,
        base_width = 30,
        peg_height = 40,
        sleeping_interval = 0.5
    )
    visual_hanoi_simulation(
        number_of_pegs = 8,
        base_width = 20,
        peg_height = 30,
        sleeping_interval = 0.2
    )


texts: Find the largest sum of any slice inside an array

texts:
This is the 26th exercise I solved from Codility. It scores 100%. I think I improved a lot since I started with this lessons, around 2 months ago, but still every post I made had things to be improved. What do you think about this code?

  Task description

  A non-empty array A consisting of N integers is
  given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a
  slice of array A. The sum of a slice (P, Q) is the total of A[P] +
  A[P+1] + ... + A[Q].

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given an array A consisting of N integers, returns the maximum
  sum of any slice of A.

  For example, given array A such that:

  A[0] = 3  A[1] = 2  A[2] = -6 A[3] = 4  A[4] = 0 the function should
  return 5 because:

  (3, 4) is a slice of A that has sum 4, (2, 2) is a slice of A that has
  sum −6, (0, 1) is a slice of A that has sum 5, no other slice of A has
  sum greater than (0, 1). Write an efficient algorithm for the
  following assumptions:

  N is an integer within the range [1..1,000,000]; each element of array
  A is an integer within the range [−1,000,000..1,000,000]; the result
  will be an integer within the range [−2,147,483,648..2,147,483,647].

[PS: I'll upvote suggestions about sites that can help me get better at databases that follow a similar approach to codility]

using System;

class Solution {
    public int solution(int[] A) {
        var lastAddend = 0;
        var accumulator = 0 ;
        var maxSliceSum = A.Length > 0 ? A[0] : 0 ;
        foreach(var addend in A)
        {
            var maxLastPair = Math.Max(addend, lastAddend + addend);
            accumulator = maxLastPair > accumulator + addend ? maxLastPair : accumulator + addend;
            maxSliceSum = Math.Max(maxSliceSum, accumulator);
            lastAddend = addend;
        }
        return maxSliceSum;
    }
}


texts: Determine whether a vector intersects the up or down unit vector

texts:
I wrote an if statement that checks if an iteratively altered vector "crosses" the up vector (0,1,0) or the down vector (0,-1,0).

if ((lastDiff.x() > 0 && diff.x() < 0 && lastDiff.z() >= 0 && diff.z() <= 0) ||
    (lastDiff.x() < 0 && diff.x() > 0 && lastDiff.z() >= 0 && diff.z() <= 0) ||
    (lastDiff.x() > 0 && diff.x() < 0 && lastDiff.z() <= 0 && diff.z() >= 0) ||
    (lastDiff.x() < 0 && diff.x() > 0 && lastDiff.z() <= 0 && diff.z() >= 0) ||
    (lastDiff.z() > 0 && diff.z() < 0 && lastDiff.x() >= 0 && diff.x() <= 0) ||
    (lastDiff.z() < 0 && diff.z() > 0 && lastDiff.x() >= 0 && diff.x() <= 0) ||
    (lastDiff.z() > 0 && diff.z() < 0 && lastDiff.x() <= 0 && diff.x() >= 0) ||
    (lastDiff.z() < 0 && diff.z() > 0 && lastDiff.x() <= 0 && diff.x() >= 0))

I feel like there is a simpler or better way to implement this if guard but I can't find it.


texts: Convert object with 'long.property.name' property to object tree

texts:
I want to transform such object from:

foo = {
    42: 'foo',
    'a.b.c[0].42': 'bar',
    'a.b.c[0].43': 'zet',
    'a.d.c[0].42': 'baz'
}

To:

bar = {
    42: 'foo',
    'a.b.c[0].42': 'bar',
    'a.b.c[0].43': 'zet',
    'a.d.c[0].42': 'baz',
    a: {
        b: {
            c: [{
                42: 'bar', 43: 'zet'
            }]
        },
        d: {
            c: [{
                42: 'baz'
            }]
        }
    }
}

I have written implementation, but it looks ugly.
Do anybody know how to improve the function below?
We use lodash in my project so that can help with basic operations.

function convertToTree(rowObjectData) {
  function it(object) {
      return _.reduce(object, function (finalObjectData, value, key) {
          var pathParts = key.match(/(.+?)\.(.+)/);

          if (pathParts) {
              delete finalObjectData[key];

              var deepObject = {},
                  containerObject = {},
                  arrayMatch = pathParts[1].match(/(.*)\[(.)]$/);

              deepObject[pathParts[2]] = value;

              if (arrayMatch) {
                  containerObject[arrayMatch[1]] = [];
                  containerObject[arrayMatch[1]][arrayMatch[2]] = it(deepObject);
              } else {
                  containerObject[pathParts[1]] = it(deepObject);
              }

              finalObjectData = _.defaultsDeep(finalObjectData, containerObject);
          }

          return finalObjectData;
      }, object);
  }

  return _.assign(_.cloneDeep(rowObjectData), it(_.cloneDeep(rowObjectData)));
}

var object = {
    42: 'foo',
    'a.b.c[0].42': 'bar',
    'a.b.c[0].43': 'zet',
    'a.d.c[0].42': 'baz'
};

console.log(convertToTree(object));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>


texts:
I'm looking at porting a simple logger I wrote a while back in Python to a language which would result in less runtime overhead from logging.

As an informal benchmark, I try to log a message, including the current time, 10,000,000 times to a given file, and to record the time.

The original Python version, under CPython 3.6.0 clocks in at about 2m06s on an Intel Core i7-3615QM CPU @ 2.30GHz, with logging to a file as well as STDOUT, but with STDOUT redirected to /dev/null (constant refreshing of my terminal emulator window with new output causes noticeable overhead).

Run under PyPy 2.7.12, that time is nearly halved to 1m10s.

A trivial C port does the same thing in about half a second with -O3 and a near-identical algorithm (which IMO is a pretty spectacular improvement, and realistically, not the type of performance I can aim for in most other languages AFAIK)

What I'm concerned about is a Haskell port I've been trying to get to run faster than Python:

module Main where

import Control.Monad.Writer
import Data.List hiding (repeat)
import Data.Time (getCurrentTime)
import Data.Time.Format (formatTime)
import System.IO hiding (putStrLn)
import System.Locale (defaultTimeLocale)

data Color = GREEN | BLUE | YELLOW | RED | PURPLE | RESET
instance Show Color where
    show GREEN  = "\x1b[32m"
    show BLUE   = "\x1b[34m"
    show YELLOW = "\x1b[33m"
    show RED    = "\x1b[31m"
    show PURPLE = "\x1b[35m"
    show RESET  = "\x1b[0m"

data MessageLevel = OK | INFO | WARN | FAIL | CRIT
instance Show MessageLevel where
    show OK     = "  OK  "
    show INFO   = " INFO "
    show WARN   = " WARN "
    show FAIL   = " FAIL "
    show CRIT   = " CRIT "

splotch :: MessageLevel -> String
splotch OK   = (show GREEN)  ++ "  ⬢  " ++ (show RESET)
splotch INFO = (show BLUE)   ++ "  ⬢  " ++ (show RESET)
splotch WARN = (show YELLOW) ++ "  ⬢  " ++ (show RESET)
splotch FAIL = (show RED)    ++ "  ⬢  " ++ (show RESET)
splotch CRIT = (show PURPLE) ++ "  ⬢  " ++ (show RESET)

buildMessage :: MessageLevel -> String -> IO String
buildMessage lvl msg = do
    now <- getCurrentTime
    return $ (show now) ++ " || [" ++ (show lvl) ++ "]" ++ (splotch lvl) ++ msg

slog :: MessageLevel -> String -> Handle -> IO ()
slog lvl msg f = (buildMessage lvl msg) >>= (hPutStrLn f)

bench1 = do
    f <- openFile "log.txt" AppendMode
    replicateM_ 10000000 $ slog OK "Hello, world!" f
    hClose f

main = bench1

Long story, short, this generates output which includes:

Picosecond-precise time (which isn't a requirement; second-precise is enough);
The log level;
A colored icon making it easier to recognize the log level at a glance; and
The log message.

After implementing some revision suggestions from the comments, this code can match Python's performance, but doesn't surpass it.

My primary concerns with my code are:

That picosecond-precise time is reducing how often memoization is performed

I've tried using second-resolution time, which would make this a true port of the basic Python functionality, but Haskell's datetime facilities seem fairly contrived to me

That I'm using a non-optimal way of sharing the file Handle between functions
That the benchmarking function itself could be inducing overhead
That I'm missing some places where pure and impure computations can be separated

I'm trying to avoid using the Writer monad because in the use cases for this logger, the output of computations inducing a logger call wouldn't need to be passed down the pipeline.

What changes can I introduce into this code to improve its performance in the benchmark I described?


texts: Count number of isosceles triangles in a set of points

texts:
Given a set of points, what is the number of isosceles triangles that can be formed with the combinations of all points in the set?

It is certain that 3 collinear points never exists in the set.

#include <stdio.h>

typedef unsigned long long llu;

typedef struct {
    llu x,y;
}point_t;

inline llu distance_p(point_t &p1,point_t &p2)
{
    return (p2.x - p1.x)*(p2.x - p1.x) + (p2.y - p1.y)*(p2.y - p1.y);
}

int main(void){
    llu n;
    point_t ps[1000];
    while (scanf("%llu",&n), n) {
        for (int i = 0; i < n; ++i)
            scanf("%llu %llu",&ps[i].x,&ps[i].y);

        llu ans = 0;
        for (llu i = 0,a,b,c; i < n; ++i) {
            for (llu j = i + 1; j < n; ++j) {
                for (llu k = j + 1; k < n; ++k) {
                    a = distance_p(ps[i], ps[j]);
                    b = distance_p(ps[j], ps[k]);
                    c = distance_p(ps[k], ps[i]);

                    //at least two side equals
                    if(a == b || b == c || c == a){
                        ++ans;
                    }
                }
            }
        }
        printf("%llu\n",ans);
    }
}

But this is slow: \$O(n^3)\$. How can I improve my code?


texts:
I have a class named Employee and another (reg_employee) that instantiates the former class.
I want to know if this code can be improved.
class Employee:

    def __init__(self):
        self.Name = ''
        self.Id = 0
        self.Age = 0
        self.company = 0
        self.title = ''
        self.Level = 0
        self.xp = 0.0
        self.Tasks = []
        self.Projects = []

    def setname(self, name):
        self.Name = name

    def setage(self, age):
        self.Age = age

    def setcompany(self, company):
        self.company = company

    def setxp(self, lvlup):
        self.xp = lvlup

import Employee

class reg_employee:

    def __init__(self):
        self.employees = []

    def read_info(self, name, age, company):
        e = Employee.Employee()
        e.Name = name
        e.Age = age
        e.company = company
        self.employees.append(e)


texts: Implementing a SQL like structure in Python, changing values

texts:
I am implementing a SQL-like datbase system in python, and so I needed to implement a value changing function, but what I ended up with seems very convoluted.

Here is code relevant to the value changing:

def _get_primary_rowval(self):
    idx = 0
    for n in self.def_column:
        if n.is_primary:
            return idx
        idx += 1

def _get_row_val_by_ident(self, ident):
    idx = 0
    idents = []
    for n in self.def_column:
        if n.identifier == ident:
            return idx
        idents.append(n.identifier)
        idx += 1
    raise AttributeError("No Columns have the identifier given.  Identifier given: {0}, Identifiers Possible: {1}".format(ident, idents))

def change_val(self, col_ident, new_val, primary_value):
    for n in self.rows:
        if n.contents[self._get_primary_rowval()] == primary_value:
            n.contents[self._get_row_val_by_ident(col_ident)] = new_val

Here is the code for the Row and Column Classes:

class TableObject(object):

    def __init__(self, ident):
        self.identifier = ident

class Column(TableObject):

    def __init__(self, ident, arg_type, primary = False):
        super().__init__(ident)
        self.arg_type = arg_type
        self.is_primary = primary

    def check_type(self, applicant_object):
        if type(applicant_object) == self.arg_type:
            return True
        else:
            return False

class Row(TableObject):

    def __init__(self, contents):
        self.contents = []
        for n in contents:
            self.contents.append(n)

    def get_contents(self):
        return self.contents

I was wondering if there was a better/more Pythonic way to do this.


texts: LockBox TwoFish string encryption and decryption

texts:
I'm using TurboPower LockBox for the first time, and using the TwoFish algorithm to first encrypt a password, and later retrieve the password by decrypting the generated hash.

I would like to know if the approach that I'm using is good, and if there are any pitfalls to avoid. Its a simple use case for my application to store and later retrieve a mail server password.

This is the code I'm using:

// Steve Faleiro 2016-03-06
uses uTPLb_CryptographicLibrary, uTPLb_Codec;

function TwoFish_ENC(const AString: String): String;
var
  CryptoLib: TCryptographicLibrary;
  Codec: TCodec;
  encryptedStr: String;
begin
  CryptoLib := TCryptographicLibrary.Create(nil);
  Codec := TCodec.Create(nil);
  try
    Codec.CryptoLibrary := CryptoLib;
    Codec.StreamCipherId := 'native.StreamToBlock';
    Codec.BlockCipherId := 'native.Twofish';
    Codec.ChainModeId := 'native.CBC';

    Codec.Reset;
    Codec.Password := '56410AD2-9DD6-4B8C-9D2F-5DE7A7F7085E';
    Codec.EncryptString(AString, encryptedStr, TEncoding.UTF8);
  finally
    CryptoLib.Free;
    Codec.Free;
  end;

  Result := encryptedStr;
end;

function TwoFish_DEC(const AString: String): String;
var
  CryptoLib: TCryptographicLibrary;
  Codec: TCodec;
  decryptedStr: String;
begin
  CryptoLib := TCryptographicLibrary.Create(nil);
  Codec := TCodec.Create(nil);
  try
    Codec.CryptoLibrary := CryptoLib;
    Codec.StreamCipherId := 'native.StreamToBlock';
    Codec.BlockCipherId := 'native.Twofish';
    Codec.ChainModeId := 'native.CBC';

    Codec.Reset;
    Codec.Password := '56410AD2-9DD6-4B8C-9D2F-5DE7A7F7085E';
    Codec.DecryptString(decryptedStr, AString, TEncoding.UTF8);
  finally
    CryptoLib.Free;
    Codec.Free;
  end;

  Result := decryptedStr;
end;

Is it good enough? If not, is there any way to improve it?


texts: What would be the idiomatic F# way to write optional parameters?

texts:
In the context of a library to generate random credit card, it would be nice to let the user the possibility to set some optional options on some cards. Lets take Visa. Two lengths are available: 13 or 16 digits.
In C# a common implementation would be:
enum VisaLengthOptions
{
    Thirteen,
    Sixteen
}

public static string GenerateVisa(VisaLengthOptions length = VisaLengthOptions.Sixteen) {
    if (length == VisaLengthOptions.Thirteen) return "4000000000001";
    if (length == VisaLengthOptions.Sixteen) return "4000000000000001";
    return "";
}

Since F# does not support optional parameter (for currying and simplicity reason (note that it could be done since ocaml did it)). What would be the most idiomatic way to write this in F#?
Here is a guess:
type VisaLengthOptions =
    | Thirteen = 0
    | Sixteen = 1

let constructVisa length =
    match length with
    | VisaLengthOptions.Thirteen -> "4000000000001"
    | VisaLengthOptions.Sixteen -> "4000000000000001"
    | _ -> ""

let generateVisa () = constructVisa VisaLengthOptions.Sixteen

So there are no optional parameter and have two functions cant have the same name even with different signatures. What wrong with this snippet?
We want our library to have a Truly Discoverable API. So we would like to avoid having two different name for basically the same logic. Should we follow the map and map2 and goes generateVisa and generateVisa2? or like map and mapi and goes generateVisa and generateVisaL? Is there a one true F# way?
A good example in the .net world is Split.


texts:
I have create a functioning automated traffic light sequence using an array and if statements. It all work correctly but I am wondering if there is anything more I can do to improve my code without changing to structure or way it works, so without the use of dictionaries, etc.

<!DOCTYPE html>

 <title> Traffic Light</title>

Traffic Light

 <canvas id="myCanvas" width="200" height="300"
 style="border:1px solid #000000;">
 Your browser does not support the HTML5 canvas tag.
 </canvas>

 <button onclick="changelight()">Click</button>


texts: Extracting key information from a directory of XML files

texts:
I have written some VBA to loop through a directory of 15,000 XML files and extract key information from these files into Excel - this is unbearably slow. Can someone please assist me in optimising the module?

Sub ImportXMLtoList()
 Application.DisplayAlerts = False
 Application.ScreenUpdating = False
 oldStatusBar = Application.DisplayStatusBar
 Application.DisplayStatusBar = True

 Dim myDir As String
 Dim StrFile As String
    StrFile = Dir("\\Ntsydfsp152\shared\Temp\Lucsan\LMIG\Output\XML\SBL\Staging\")
    myDir = "\\Ntsydfsp152\shared\Temp\Lucsan\LMIG\Output\XML\SBL\Staging\"
    myFile = "LMIG_List_XML_Files.xlsm"

 'clear sheet1
 Sheets(1).Range("a2:g30000").Clear
 x = 2

 Do While Len(StrFile) > 0

 Application.StatusBar = StrFile & " Row: " & x
    Sheets(1).Cells(x, 1).Value = StrFile
    Workbooks.OpenXML Filename:=myDir & StrFile, LoadOption:=xlXmlLoadImportToList
    temp2 = ActiveWorkbook.Sheets(1).Range("g2")
    temp3 = ActiveWorkbook.Sheets(1).Range("e2")
    temp4 = ActiveWorkbook.Sheets(1).Range("ak3")
    temp5 = ActiveWorkbook.Sheets(1).Range("av4") & "/" & ActiveWorkbook.Sheets(1).Range("ax4") & "/" & ActiveWorkbook.Sheets(1).Range("aw4") & "/" &     ActiveWorkbook.Sheets(1).Range("ay4")

    ActiveWorkbook.Close

    Sheets(1).Cells(x, 2) = temp2
    Sheets(1).Cells(x, 3) = temp3
    Sheets(1).Cells(x, 4) = temp4
    Sheets(1).Cells(x, 5) = temp5
    x = x + 1

    StrFile = Dir
 Loop

 Application.DisplayAlerts = True
 Application.ScreenUpdating = True
 Application.StatusBar = False
 Application.DisplayStatusBar = oldStatusBar

End Sub


texts: Simple calculator implemented with lambdas

texts:
I was searching for a way to exercise the Java 8 concepts I've been learning, especially pertaining to Lambdas. Incidentally, I hadn't used any swing in a while and wanted a refresher. This is the result of these two pursuits.

import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class EquationCalculator {
    static interface Equation {
        double compute(double val1, double val2);
    }

    public static void main(String[] args) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> new EquationCalculator());
    }

    public EquationCalculator() {
        JFrame frame = new JFrame("Basic Operations");
        JPanel panel = new JPanel(new GridLayout(1, 3));
        JTextField first = new JTextField("2");
        JTextField second = new JTextField("3");
        JComboBox<String> calculate = new JComboBox<>();

        calculate.addItem("Sum");
        calculate.addItem("Difference");
        calculate.addItem("Product");
        calculate.addItem("Quotient");
        calculate.addItem("Exponent");
        calculate.addActionListener(
            e -> JOptionPane.showMessageDialog(
                null, "The result is " +
                calculate(
                    String.valueOf(calculate.getSelectedItem()),
                    Double.parseDouble(first.getText()),
                    Double.parseDouble(second.getText())
                ),
                "Result", JOptionPane.INFORMATION_MESSAGE
            )
        );

        panel.add(first);
        panel.add(second);
        panel.add(calculate);

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static double calculate(String operation, double val1, double val2) {
        Equation add = (alpha, beta) -> alpha + beta;
        Equation subtract = (alpha, beta) -> alpha - beta;
        Equation multiply = (alpha, beta) -> alpha * beta;
        Equation divide = (alpha, beta) -> alpha / beta;
        Equation exponentiate = (alpha, beta) -> Math.pow(alpha, beta);

        switch(operation) {
            case "Sum":
                return add.compute(val1, val2);
            case "Difference":
                return subtract.compute(val1, val2);
            case "Product":
                return multiply.compute(val1, val2);
            case "Exponent":
                return exponentiate.compute(val1, val2);
        }
        return divide.compute(val1, val2);
    }
}

I recognize it's simple, and I can imagine there's likely a bit of "learned how to use a hammer...everything looks like a nail" going on, but I'd nonetheless appreciate any pinpointing good design choices vs poor ones and where I could improve.


texts:
There is HTML that triggers the code below I want to disallow executing the script more than once per 24 hours. I wanted this script to store the last visit time in a table against the user ID in a database, then do a time calculation and back them out until the 24 hour expiry time.

<?php
//Input correct values into this section
$dbhost = '888888';
$dbuser = '888888';
$dbpass = '888888';
$dbname = '888888';
$dbtable = 'redeem';
$dbtable2 = 'playersthatvoted';
//------------------------------------
$input = 'diamond 12';
$player = $_POST['Player'];
$time = time();
if(!isset($_COOKIE['24Hourvote'])){
   //---- This is the connection
   $conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ('Error: ' . mysql_error());
   mysql_select_db($dbname);
   $query1 = "INSERT INTO `".$dbname."`.`".$dbtable."` (`player`, `item`) VALUES ('".$player."', '".$input."')";
   $query2 = "INSERT INTO `".$dbname."`.`".$dbtable2."` (`player`, `time`) VALUES ('".$player."', '".$time."')";
   mysql_query($query1);
   mysql_query($query2);
   $query= 'SELECT `player` FROM `playersthatvoted` ASC LIMIT 0, 10 ';
   $result = mysql_query($query);
   mysql_close($conn);
   echo 'Done! Type /redeem in-game to get your diamonds.';
   $ip=@$REMOTE_ADDR;
   setcookie ("24Hourvote",$ip,time()+86400,'/',true,…
} else {
   echo 'You have already voted today! Come back later...'; }
?>


texts:
I have written Java code that finds the frequency of the occurrence of a word in a sentence.  It is working fine.  The only thing I want to do is to optimize this code.

String str = "I am a Boy I am a";
        String[] splitStr = str.split(" ");
        int count = 0;
        List<String> list = new ArrayList<>();
        for(String s:splitStr){
            if(!list.contains(s)){
                list.add(s);
            }
        }
        for(int i=0;i<list.size();i++){
            for(int j=0;j<splitStr.length;j++){
                if(list.get(i).equals(splitStr[j])){
                    count++;
                }
            }
            System.out.println("Occurrence of " + list.get(i) + " is " + count + " times.");
            count=0;
        }


texts: Vue.js Stoplight app - Dynamically changing classes on elements

texts:
I recently started delving into Vue.js, and decided to try my hand at some custom class/style bindings, so I made a small app that's supposed to cycle through each "light" of a stoplight (red, yellow, green, red, etc.).

My Vue instance has a data property count, which is initially set to 0, and I also have a setInterval callout that is to increments the count every one second.

Each "light" in the stoplight has a Bootstrap button class associated with it (btn-danger for red, btn-warning for yellow, and btn-success for green), and each class becomes "active" based on some modulus arithmetic against my Vue instance's count.

I'm wondering if perhaps I could be handling the change in these classes more efficiently, but am not sure what could be done.

Here is my current code:

var app = new Vue({
  el: '#app',
  data: {
    count: 0,
    styleObject: {
      display: 'block',
      width: '30px',
      margin: '0',
      borderRadius: '50px',
      border: '1px solid black'
    }
  }
});

setInterval(function() {
  app.count = app.count + 1;
}, 1000);
#light {
  background-color: yellow;
  display: inline-block;
  border: 2px solid black;
  margin: 10px;
  padding: 5px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

    <input type='button' id='red' :class='["btn", (count % 3 === 0) && "btn-danger"]' :style='styleObject' />

    <input type='button' id='yellow' :class='["btn", (count % 3 === 1) && "btn-warning"]' :style='styleObject' />

    <input type='button' id='green' :class='["btn", (count % 3 === 2) && "btn-success"]' :style='styleObject' />


texts:
I made a little script that takes images and averages / aligns them.

The script grew and now I have different options bound to the program, it can calculate the average for RGB or gray scale pictures and can create test data set to check if it works on different machines.

At the beginning I define the help message, yet isn't there a better way to store it?

def main(argv):
    help_message  = "---------------- HELP ----------------\n"
    help_message += "Usage:\n"
    help_message += "pythong main_avg.py -d path/to/folder/ -cd -cdrgb -avg -avgrgb -graph\n"
    help_message += "  -d | --directory: path to any directory, the program will generate the dataset, or calculate the average in the folder.\n"
    help_message += "  -cd: creates gray scale dataset.\n"
    help_message += "  -cdrgb: creates rgb scale dataset.\n"
    help_message += "  -avg: calculates the alignment and average of the picture in greyscale mode.\n"
    help_message += "  -avgrgb: calculates and outputs a rgb average, needs the data from -avg.\n"
    help_message += "  -graph: calculates and outputs the movement and angles graphs, needs the data from -avg.\n"
    help_message += "  -s: sound at the end of process.\n"
    help_message += "  -h, --help: prints this.\n"

Then I print the starting script, just because

    path, name, ext = get_pathname(argv[0])
    print("Script:", name + ext, "started")

Then I process the arguments

    # get the arguments
    opts = argv[1:]

    folder = ""
    create_dataset = False
    create_rgb_dataset = False
    avgerage_gray = False
    average_rgb = False
    produce_graphs = False
    sound_of_silence = False

    if len(opts) == 1 and opts in ('-h', '--help'):
        print(help_message)
    else:
        nopt = 0
        while nopt < len(opts):
            opt = opts[nopt]
            if opt in ("-d", "--directory"):
                try:
                    nopt += 1
                    folder = opts[nopt]
                except IndexError:
                    pass
            if opt == "-cd":
                create_dataset = True
            if opt == "-cdrgb":
                create_rgb_dataset = True
            if opt == "-avg":
                avgerage_gray = True
            if opt == "-avgrgb":
                average_rgb = True
            if opt == "-graph":
                produce_graphs = True
            if opt == "-s":
                sound_of_silence = True
            nopt += 1

The program checks if one option is chosen, and if so it start the subroutine.

    inopt = [create_dataset, create_rgb_dataset, avgerage_gray, average_rgb, produce_graphs]

    if isdir(folder):
        if all(opt == False for opt in inopt):
            print("No options chosen")
            print("")
            print(help_message)
        if create_dataset:
            run_create_test_dataset(folder)

        if create_rgb_dataset:
            run_create_rgb_dataset(folder)

        if avgerage_gray:
            run_average_gray(folder)

        if average_rgb:
            run_average_rgb(folder)

        if produce_graphs:
            run_produce_graphs(folder)

        if sound_of_silence:
            import winsound
            Freq = 2500 # Set Frequency To 2500 Hertz
            Dur = 1000 # Set Duration To 1000 ms == 1 second
            winsound.Beep(Freq,Dur)
    else:
        print("-d option is not a folder")
        print("")
        print(help_message)

Is the first time I build a argumented main, so I would love any suggestions!


texts:
This is my first model RSpec test:

require 'spec_helper'

describe CashFlow do
  context 'DB Fields' do
    it { should have_db_column :amount_cents }
    it { should have_db_column :amount_currency }
    it { should have_db_column :user_id }

    it { should have_db_column :target_date }
    it { should have_db_column :created_at }
    it { should have_db_column :updated_at }
  end

  context 'Associations' do
    it { should belong_to :user }
    it { should have_and_belong_to_many :tags }
  end

  context 'Validation' do
    it { should validate_presence_of :amount_cents }
    it { should validate_numericality_of :amount_cents }
    it { should ensure_exclusion_of(:amount_cents).in_array([0,]) }

    it { should validate_presence_of :amount_currency }
    it { should validate_presence_of :target_date }

    it { should validate_presence_of :user }
  end

  context 'Scopes' do
    subject { CashFlow }

    context 'Incoming/Outcoming flows' do
      let(:incoming_cash_flows) { 4.times.map { create :cash_flow } }
      let(:outcoming_cash_flows) { 4.times.map { create :cash_flow, negative: true } }

      it 'should be able to return all and only incomings cash_flows' do
        expect(subject.incoming).to include *incoming_cash_flows
        expect(subject.incoming).not_to include *outcoming_cash_flows
      end

      it 'should be able to return all and only outcomings cash_flows' do
        expect(subject.outcoming).to include *outcoming_cash_flows
        expect(subject.outcoming).not_to include *incoming_cash_flows
      end
    end

    context 'Past/Future flows' do
      [-1, nil, 1].each do |num|
        _threshold = num ? Date.today + num.year : nil

        let(:threshold) { _threshold }
        let(:future_cash_flows) { 4.times.map { create :cash_flow, threshold: threshold } }
        let(:past_cash_flows) { 4.times.map { create :cash_flow, past: true, threshold: threshold } }

        it "should be able to return all and only past cash_flows with #{_threshold || 'current date (default)'} threshold" do
          expect(subject.past(threshold)).to include *past_cash_flows
          expect(subject.past(threshold)).not_to include *future_cash_flows
        end

        it "should be able to return all and only future cash_flows with #{_threshold || 'current date (default)'} threshold" do
          expect(subject.future(threshold)).to include *future_cash_flows
          expect(subject.future(threshold)).not_to include *past_cash_flows
        end
      end
    end
  end

  it 'should save specified currency' do
    %w(GEL RUB USD EUR).each do |currency|
      cash_flow_id = create(:cash_flow, currency: currency).id

      cash_flow = CashFlow.find(cash_flow_id)
      expect(cash_flow.amount.currency).to eq currency
    end
  end
end

Model:

class CashFlow < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :tags

  monetize :amount_cents, with_model_currency: :amount_currency

  validates_presence_of :user, :target_date, :amount_cents, :amount_currency
  validates_exclusion_of :amount_cents, in: [0, ]

  scope :incoming, -> { where 'amount_cents > 0' }
  scope :outcoming, -> { where 'amount_cents < 0' }

  scope :past, lambda { |date = nil | where 'target_date < ?', date || Date.today}
  scope :future, lambda { |date = nil | where 'target_date > ?', date || Date.today}
end

Factory:

FactoryGirl.define do
  factory :cash_flow do
    association :user

    ignore do
      negative false
      past false
      threshold nil
      currency 'USD'
    end

    after :build do |cash_flow, evaluator|
      sign = evaluator.negative ? -1 : 1
      cash_flow.amount = Money.new((rand(10000) + 1) * sign, evaluator.currency || currency)

      sign = evaluator.past ? -1 : 1
      cash_flow.target_date = (evaluator.threshold || Date.today) + ((rand(60 * 24 * 30) + 1) * sign).minutes
    end
  end
end

What can you tell me about its readability, flexibility and coverage fullness?

I use factory girl, shoulda and money gems.


texts:
The objective is to get a list of number and then switch the last person surname with the first person surname; when I type '$' it do the changes and finish the program! (POINTERS and DYNAMIC ALLOCATION).
I have to use pointers and dynamic allocation, my code is nice, but I know that it can be better.
How can I start to identify parts of my code that could be extracted to functions?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char ***names=NULL;
        int i, j, k, letter, totalNames, auxInt;
        int *wordsbyname= NULL;
        char *auxWord;
        i=j=k=0;

        do
        {
                names=realloc(names, (i+1)*sizeof(char**));
                names[i]=NULL;
                wordsbyname=realloc(wordsbyname, (i+1)*sizeof(int));
                j=0;
            do
            {
                names[i]=realloc(names[i],(j+1)*sizeof(char*));
                names[i][j]=NULL;
                k=0;
                    do{
                        letter=getchar();
                        names[i][j]=realloc(names[i][j], (k+1)*sizeof(char));
                        names[i][j][k]=letter;
                        k++;
                    }while ((letter!= 10) && (letter!=32) && (letter!=36));
                    names[i][j][k-1]='\0';
                    j++;
            }while((letter!= 10)&&(letter!=36));
            wordsbyname[i]=j;
            i++;
        }while (letter!=36);
        totalNames=i;
        printf("\n");

        for(i=0;i<totalNames/2;i++){
            auxInt=totalNames-i-1;
            auxWord=malloc(sizeof(char)*(strlen(names[i][wordsbyname[i]-1])+1));
            strcpy(auxWord,names[i][wordsbyname[i]-1]);
            names[i][wordsbyname[i]-1]=realloc(names[i][wordsbyname[i]-1], sizeof(char)*strlen((names[auxInt][wordsbyname[auxInt]-1])+1));
            strcpy(names[i][wordsbyname[i]-1],names[auxInt][wordsbyname[auxInt]-1]);
            names[auxInt][wordsbyname[auxInt]-1]=realloc(names[auxInt][wordsbyname[auxInt]-1],sizeof(char)*(strlen(auxWord)+1));
            strcpy(names[auxInt][wordsbyname[auxInt]-1],auxWord);
            free (auxWord);
        }

        for(i=0 ; i<totalNames; i++){
            for (j=0; j<wordsbyname[i];j++){
                printf("%s ", names[i][j]);
                free(names[i][j]);
            }
            free(names[i]);
            printf("\n");
        }
    free(wordsbyname);
    free(names);

    return 0;
}


texts: Fire analytics tag based on message event from window

texts:
I have some code that checks to see what event data is being passed back from two different media players. The first player sends back play button clicked, but the second player sends back the data I want but it's I have to parse it and read it to see if it matches play and startPosition === 0.

Wondering if there is a better way to check both the players to see what data is being passed in. What I have just feels dirty.

function handleWindowMessage (e) {
    var originalEventData = e.originalEvent.data;

    if (originalEventData === 'play button clicked') {
        _gaq.push('_trackEvent', 'Video', 'Played');
    }

    try {
        var parsedData = JSON.parse(originalEventData).data;

        if (parsedData && parsedData[0] === 'play' && parsedData[1].startPosition === 0) {
            _gaq.push('_trackEvent', 'Video', 'Played');
        }
    }
    catch (ignore) {}
    finally { return; }
}

$(window).on('message', handleWindowMessage);


texts: Trying to do Type-Driven Development in F#

texts:
I've been wanting to try out F# for some real world programming so I decided to try rewriting a program that is being used at work.

It can be reduced to a few steps:

Get report templates.
In this step I query a DB and get some templates for reports
Update data that the reports are working on.
In this step I query some banking services and save our data on our DB
Generate new reports.
In this step I call a stored procedure that generates a new report

I'm trying to do this outside in and have been using Mark Seemann's blog and Scott Wlaschin's guide as a guide and this is what I've got so far:

module Helpers =
let getValuesInListOfOptions list =
    List.choose (fun x ->
                    match x with
                    | Some value -> Some value
                    | _ -> None ) list
module PaymentVelocityReports =
open System;
open Helpers;

type ReportTemplateName = string

type ReportTemplate = {
    Id: int
    GroupId: int
    ReportOwnerSSN: string
    Name: ReportTemplateName
    Description: string
    Enabled: bool
    DayOfMonthToRun: int
    DateFrom: DateTime
    DateTo: DateTime option
    UpdateData: bool}

type Claimant = {
    Id: decimal
    Ssn: string
}

type BankingService = {
    Id: decimal
    ClaimantId: decimal
    Bank: string
    Username: string
    Password: string
    Enabled: bool
}

type ClaimantTemplates ={
    ReportTemplates: ReportTemplate list
    Claimant: Claimant
    BankingServices: BankingService list
}

let updateClaimantData saveNewGiros saveNewPayments (dateFrom: DateTime) (dateTo: DateTime) (bankingServices: BankingService list) =
    List.iter (fun x -> saveNewGiros dateFrom dateTo x) bankingServices
    List.iter (fun x -> saveNewPayments dateFrom dateTo x) bankingServices

let updateData updateClaimantData (claimantTemplates: ClaimantTemplates) : ReportTemplateName list =
    if List.exists (fun x -> x.UpdateData) claimantTemplates.ReportTemplates then
        let minDate = List.map (fun x -> x.DateFrom) claimantTemplates.ReportTemplates |> List.min
        let maxDateWithNone = List.map (fun x -> x.DateTo) claimantTemplates.ReportTemplates |> List.max
        let maxDateWithoutNone = List.map (fun x -> x.DateTo) claimantTemplates.ReportTemplates |> getValuesInListOfOptions |> List.max

        match maxDateWithNone with
            | None -> updateClaimantData minDate DateTime.Today claimantTemplates.BankingServices
            | _ -> updateClaimantData minDate maxDateWithoutNone claimantTemplates.BankingServices

    List.map (fun x -> x.Name) claimantTemplates.ReportTemplates

let getClaimantTemplates data createClaimantTemplate : ClaimantTemplates list =
    data |> List.map createClaimantTemplate

//The root of the program
let generateReports (getClaimantTemplates: unit -> ClaimantTemplates list) (updateData: ClaimantTemplates -> ReportTemplateName list) (createReport: ReportTemplateName -> unit) =
    getClaimantTemplates () |> List.map updateData |> List.concat |> List.map createReport |> ignore

I'm at the point where the updateClaimantData and getClaimantTemplates require data access and the createReport function that generateReports needs is also a data access function.

I was hoping to get some criticism to see if I'm on the right track. I'm both new to the language and functional languages as well.


texts: Number of zeroes at the end of a factorial

texts:
I was working with this problem, which is to find the number of zeros at the end of any factorial.

Here's my solution:

#include<bits/stdc++.h>
using namespace std;
int main(){

    int numCases,num,zeroCount=0,mulFive,temp,i=0;
    cout<<numeric_limits<int>::max()-1000000000<<endl;
    cin>>numCases;
    int solutionArray[numCases];
    temp=numCases;
    while(numCases--)
    {
         zeroCount=0;
         cin>>num;
         mulFive=5;
         while(num/mulFive!=0)
         {
             zeroCount=zeroCount+ (num/mulFive);
             mulFive=mulFive*5;
         }
         solutionArray[i]=zeroCount;
         i++;
         //cout<<zeroCount;
    }
    for(int k=0;k<temp;k++)
        cout<<solutionArray[k]<<endl;

    return 0;
}

This is the most basic code that I could come up with. How should I make it more efficient using the same logic?  Perhaps I should use different logic?


texts: Generate all possible unique combinations of positive numbers these have sum equal to N

texts:
This is my function to generate all possible unique combinations of positive numbers these have sum equal to N.
For example:

If the input is 4

The output should be: [ '4', '1+3', '1+1+2', '1+1+1+1', '2+2' ]

You can try it online here
const f=n=>{ // n is a positive number
  if(n==0) return ["0"]
  if(n==1) return ["1"]
  if(n==2) return ["0+2", "1+1"]
  const result = [n+"+0"]
  for(let i=n-1; i>=n/2|0; i--){
    for(const x of (f(n-i) || [])) {
      for(const y of (f(i) || [])) {
        result.push(y + "+" + x)
      }
    }
  }

  // Remove duplicated records
  const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
  return [...new Set(map)]
}

//Testing
a=f(8)
console.log(a)

My approach is using recursion, it works like that:

If I can find all possible unique combinations of positive numbers these have sum equal to N.

Then I can find all possible unique combinations of positive numbers these have sum equal to N + 1.

For example:

If all possible unique combinations of positive numbers these have sum equal to 3 are: ["3", "1+2", "1+1+1"] and all possible unique combinations of positive numbers these have sum equal to 2 are ["2", "1+1"]

Then for 4 it should be:

4 + 0 or 4

All possible unique combinations of combinations of positive numbers these have sum equal to 3 and 1

// for 3 it's combinations is
["3", "1+2", "1+1+1"]
// for 1 it is
["1"]

All possible unique combinations of combinations of positive numbers these have sum equal to 2 and 2,

// for 2 it's combinations is
["2", "1+1"]

And I only do the loops to the integer of n/2  to avoid duplicatings.
Could you please help me to review it?

const f=n=>{ // n is a positive number
  if(n==0) return ["0"]
  if(n==1) return ["1"]
  if(n==2) return ["0+2", "1+1"]
  const result = [n+"+0"]
  for(let i=n-1; i>=n/2|0; i--){
for(const x of (f(n-i) || [])) {
  for(const y of (f(i) || [])) {
    result.push(y + "+" + x)
  }
}
  }

  // Remove duplicated records
  const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
  return [...new Set(map)]
}

//Testing
a=f(8)
console.log(a)


texts:
I am working on improving my bash environment. I have added the following function to my ~/.bashrc in order to facilitate modifying my PATH as well as removing duplicate entries from my PATH which may occur from sourcing ~/.bashrc again.

# $1 the path to be added as an absolute path
# $2 a boolean for whether the path should be prepended. default: false
# $3 the path variable to add to
function addToPath {
    # ${!3} dereferences $3 to use the value the variable refers to. For example $3=PATH would give $PATH
    if [ -z ${3+x} ]; then TMP_PATH="$PATH"; TMP_NAME="PATH"; else TMP_PATH="${!3}"; TMP_NAME="$3"; fi
    if [ ! -d $1 ]; then echo "WARNING: Added $1 to $TMP_NAME but $1 doens't seem to exist"; fi

    case ":$TMP_PATH:" in # Add trailing :'s to cover first and last entries
        *":$1:"*)
            ;; # Exists Already
        *)
            case true in
                $2)
                    TMP_PATH="$1:$TMP_PATH"
                    ;;
                *)
                    TMP_PATH="$TMP_PATH:$1"
                    ;;
            esac
            ;;
    esac

    # Remove potential wrapping ":" chars
    TMP_PATH=${TMP_PATH#":"}
    TMP_PATH=${TMP_PATH%":"}
    if [ -z ${3+x} ]; then export PATH="$TMP_PATH"; else export $3="$TMP_PATH"; fi
}

And then, to build my path and remove duplicates I use the following code.

# Set up basic PATH variable
addToPath /usr/local/bin
addToPath /usr/bin
addToPath /usr/sbin
addToPath /bin
addToPath /sbin

# Remove duplicates from path
NEW_PATH=""
IFS=':' read -r -a path_array <<< "$PATH"
for element in "${path_array[@]}"
do
    addToPath $element false NEW_PATH
done
export PATH=$NEW_PATH


texts:
I'm an advanced C# programmer learning F#. As an exercise I'm porting a function that calculates the check digit of a US ABA (routing) number. Here are 2 C# implementations:

int CalcCheckDigit(string rt)
{
    var s = new[]{3,7,1,3,7,1,3,7}
        .Zip(rt, (m,d) => m * int.Parse(d.ToString()))
        .Sum();

    return (int)Math.Ceiling(s / 10.0) * 10 - s;
}

int CalcCheckDigitOldSchool(string rt)
{
    int[] mults = new[]{3,7,1,3,7,1,3,7};
    int s = 0;
    for (int i = 0; i < mults.Length; i++)
    {
        int digit = int.Parse(rt[i].ToString());
        s += digit * mults[i];
    }

    double nextMultOfTen = Math.Ceiling(s / 10.0) * 10;
    return (int)nextMultOfTen - s;
}

And here's my crack at it with F#:

let calcCheckDigit rt =
    let s =
        rt
        |> Seq.zip [3;7;1;3;7;1;3;7]
        |> Seq.map (fun (a,b) -> a * int(string b))
        |> Seq.sum |> float
    int (ceil (s / 10.0) * 10.0 - s)

How might the F# version be improved?


texts: Should I unpack a Maybe with maybe or pass value around

texts:
I'm beginning (for the third time in 5 years) to learn Haskell and decided to do a "More or less" console game (game pick a random number, you then have to guess which).
First the code, then my question :
import System.Random
import Text.Read(readMaybe)

main :: IO ()
main = do
  gen <- getStdGen
  let maxSecret = 1000
  let (secret, newGen) = randomR (1,maxSecret) gen :: (Int, StdGen)

  -- putStrLn $ show secret
  let oracle = compareToSecret secret
  askForNumber oracle 1 (1, maxSecret)

data Guess = SecretIsLess | SecretIsMore | Win deriving (Show)

askForNumber :: (Int -> Guess) -> Int -> (Int, Int) -> IO ()
askForNumber oracle tries range = do
  let (min, max) = range
  putStrLn $ "Guess the number between " ++ (show min) ++ " and " ++ (show max) ++ " !"
  guessInput <- getLine
  let guess = readMaybe guessInput :: Maybe Int

  case (oracle) <$> guess of
            Just SecretIsMore -> do
                  putStrLn "Guess more !"
                  askForNumber oracle (tries+1) (maybe min id guess, max)
            Just SecretIsLess -> do
                  putStrLn "Guess less !"
                  askForNumber oracle (tries+1) (min, maybe max id guess)
            Just Win -> do
                  putStrLn "You win !"
                  putStrLn $ "It took you " ++ (show tries) ++ " tries."
                  return ()
            Nothing -> do
                  putStrLn "That is not a number"
                  askForNumber oracle tries range

compareToSecret :: Int -> Int -> Guess
compareToSecret secret guess
  | secret > guess = SecretIsMore
  | secret < guess = SecretIsLess
  | secret == guess = Win

I'd like to improve that code to make it idiomatic and learn in the process.
I made a choice : at first I had
compareToSecret :: Int -> Int -> (Guess, Int)
and in the case of I had something like
Just (SecretIsMore, newmin) -> do askForNumber oracle (tries+1) (newmin, max)
Do you think it's better to kind of unpack with maybe there or to pass the value around and keep it pure ? Or is there another solution ?


texts: SqlCommand ExecuteReaderAsync helper method

texts:
The following helper method executes commands asynchronously and returns a Task<IEnumerable<T>> where T is a type that receives the row information from the SqlDataReader rows. All works fine.

    public static async Task<IEnumerable<T>> CommandExecuteReaderAsync<T>(SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, IEnumerable<SqlParameter> parameters, CancellationToken token, int commandTimout)
    {
        using (var command = new SqlCommand(commandText, conn, trans))
        {
            command.CommandTimeout = commandTimout;
            command.Parameters.AddRange(parameters.ToArray());
            command.CommandType = commandType;
            using (var sr = await command.ExecuteReaderAsync(token))
            {
                var dc = new System.Data.Linq.DataContext(conn);

                return dc.Translate<T>(sr).ToList();
            }
        }
    }

However, I'm not happy with my current approach of creating a new DataContext and using it's Translate<T> method.

Is there a better approach as the creation of the DataContext seems a bit excessive?


texts: Java number sorting algorithm - remove ugly break

texts:
I have written a little number sorting algorithm that puts a random array of integers into ascending order, my code is below and it is working fine. However there is the very ugly and unsatisfying break at lines 42 to 44. I would love some advice on how to get rid of that. I had to put this break in there to prevent overflow errors when the index goes into negative numbers. I am sure I can avoid this by looking at the algorithm from another angle but at the moment I just cant see it.

package algorithms;

import java.util.Arrays;

/**
 * This class will place any list of numbers in numerical order
 * @author Richard
 *
 */
public class SortNumbers {

/**
 * This method will take a random set of numbers and
 * place them in numerical order
 * @param args
 */
public static void main(String[] args) {
    //create array
    int[] numbers = new int[]{9,8,7,6,5,4,3,2,1,10,11,15,14};

    //find length of array to control loop
    int length = numbers.length-1;

    //do not exceed length of array in loop
    for (int outer = 0; outer<length; outer++){

        //reset second counter
        int inner = 0;

        //keep looping while two consecutive numbers are not in order
        while (numbers[outer+inner]>numbers[outer+inner+1]) {

            //swap numbers that are not in order
            int temp = numbers[outer+inner];
            numbers[outer+inner] = numbers[outer+inner+1];
            numbers[outer+inner+1] = temp;

            //decrement and see if numbers need swapped again
            inner--;

            //break on negative index to prevent overflow error
            if (outer+inner<0) {
                break;
            }
        }
    }
    //convert finished array to string and print
    System.out.println(Arrays.toString(numbers));

}

}


texts:
I'm new to PDO, and I want to make sure I made this in the correct way. This way is working, but I have a feeling it's unclean.

I have this input:

$query = $handler->query('SELECT * FROM content WHERE id=1');
while($r = $query->fetch()) {
?>

    <form action="<?php echo BASE_URL ?>admin/edit_process.php?edit_about" method="post" autocomplete="off" id="contact_form" name="contact_form" role="form">

          Izmeni sadržaj sa početne strane:
          <textarea class="form-control" id="message" name="message" required="" rows="6"><?php echo $r['edit_about']; ?></textarea>

          <button class="btn btn-success float-right" type="submit" name="submit">Sačuvaj</button>

    </form>

<?php
}

Then it goes to this:

if(isset($_REQUEST['edit_about'])){
    if(!$user->isLoggedIn()){ Redirect::to(''.BASE_URL.''); }
  if(!$user->hasPermission('admin')) { Redirect::to(''.BASE_URL.''); }
    if(Input::exists()){
        try{
      $message = $_POST['message'];
      $sql = "UPDATE `content` SET `edit_about` = :message WHERE `id` = 1";
      $query = $handler->prepare($sql);
      $query->execute(array(
          ':message' => $message
      ));
            Redirect::to(''.BASE_URL.'index');
        }catch(Exception $e){
            die($e->getMessage());
        }
    }
}

And this is the output:

<?php
$query = $handler->query('SELECT * FROM content WHERE id=1');
while($r = $query->fetch()) {
    echo $r['edit_about'];
}
?>