texts: Refactor Coffee Script to fire on page load instead of change

texts:
I have a Rails app where I'm trying to select a list of facilities based on what region is selected in a form.  So far, I've implemented group_collection_select to do this as well as a bit of CoffeeScript.

It works when creating a new record and selecting a region.  The behavior being to only show facilities listed for the selected region.  What does not work is when editing a record, selecting the facilities shows all of the facilities grouped by region instead of constraining the facilities to the selected region.

If I select another region and then select the original reason, the proper list of facilities show up.

I'd like to learn how to refactor the CoffeeScript to where when editing the record the function is fired both on load and on change.

Here's what my code looks like:

calls.js.coffee

jQuery ->
  facilities = $('#call_transfer_from_id').html()

  $('#call_region_id').change ->
    region = $('#call_region_id :selected').text()
    options = $(facilities).filter("optgroup[label=#{region}]").html()

    if options
      $('#call_transfer_from_id').html(options)
    else
      $('#call_transfer_from_id').empty()

region.rb

has_many :facilities

facility.rb

attr_accessible :region_id
belongs_to :region

_form.html.erb excerpt

 <%= f.label :region %>
  <%= f.collection_select(:region_id, Region.all, :id, :area, {:include_blank => true}, {:class => 'select', required: true}) %>
  <%= f.label :Transfer_From %>
  <%= f.grouped_collection_select :transfer_from_id, Region.order(:area), :active_facilities, :area, :id, :facility_name, {include_blank: true}, class: 'select' %>

If my question and examples are not clear, please let me know and I'll be happy to edit.


texts:
So I recently had a practical exam in which I was told to execute a function of a menu oriented matrix operation program using classes. The code I made was supposedly wrong as I hadn't used classes the way they have to be used. Can anybody help me rectify the error here. I'm a noob (less than 2 months into C++) so please pardon any nooby mistakes.

 #include <iostream>
    using namespace std;
    class matrix3
    {
        int a[10][10],b[10][10],c[10][10],d[10][10],e[10][10],f[10][10],x,y,i,j;
        public :
            void values();
            void transpose();
            void sum();
            void diff();
    };
    void matrix3::values()
    {
        cout << "Enter the rows   "; cin >> x;
        cout << "Enter the columns   "; cin >> y;
        cout << "Enter elements of first matrix\n\n";
        for (i=1; i<=x; i++)
        {
            for ( j=1; j<=y; j++)
            {
                cin >> a[i][j];
            }
        }
        cout << "Enter elements of second matrix\n\n";
        for (i=1; i<=x; i++)
        {
            for (j=1; j<=y; j++)
            {
                cin >> c[i][j];
            }
        }
    }
    void matrix3::sum()
    {
        cout << "Sum of Matrices 1 and 2 is\n";
        for (i=1; i<=x; i++)
        {
            for ( j=1; j<=y; j++)
            {
                e[i][j]=a[i][j]+c[i][j];
                cout << e[i][j] << "";
            }
            cout << endl;
        }

    }
    void matrix3::diff()

    {
    cout << "Difference of Matrices 1 and 2 (1-2) is\n";
        for (i=1; i<=x; i++)
        {
            for ( j=1; j<=y; j++)
            {
                f[i][j] = a[i][j]-c[i][j];
                cout << f[i][j] << "";
            }
            cout << endl;
        }
    }
    void matrix3::transpose()
    {
        cout << "transpose of the matrix is\n";
        for ( i=1; i<=x; i++)
        {
            for ( j=1; j<=y; j++)
            {
                b[i][j] = a[j][i];
                cout << b[i][j] << "";
            }
            cout << endl;
        }
        cout << "Transpose of the second matrix is\n";
        for ( i=1; i<=x; i++)
        {
            for ( j=1; j<=y; j++)
            {
                d[i][j] = c[j][i];
                cout << b[i][j] << "";
            }
            cout << endl;
        }
    }
    int main()
    {
        int input;
        char ch;
        matrix3 m;
        m.values();
        do
         {
        cout << "Enter your choice\n";
        cout << " 1. Sum of 1 and 2\n" << " 2. Difference of 1 and 2\n" << " 3. Transpose of both 1 amd 2\n";
        cin >> input;
        switch (input)
        {
            case 1:
                m.sum();
                break;

            case 2:
                m.diff();
                break;

            case 3:
                m.transpose();
                break;
        }
        cout << "\nDo another y/n?";
        cin >> ch;
        }
        while (ch!= 'n');
        cout << "\n";
        system ("pause");
    return 0;
    }


texts: Optimization - open excel file from VB.NET using interop

texts:
I have a simple app, which is something like a launcher for my macro enabled excel workbook. I made it for easier distribution, to be able to check if excel installed and also to make it look and behave like a standalone application.

I am using Office Interop which, according to MS, has many performance issues. But still, have you got any idea what I could improve to perform faster?

Imports System.Threading
Imports Microsoft.Win32
Imports Microsoft.Office.Interop.Excel

Module Module1
Public Sub Main()
    On Error GoTo ErrorHandler
    Dim singleInstance As Boolean = False
    Dim mutex As New Mutex(True, My.Application.Info.AssemblyName,
    singleInstance)
    Dim excelKey As RegistryKey = Registry.ClassesRoot.OpenSubKey("Excel.Application")
    Dim excelInstalled As Boolean = If(excelKey Is Nothing, False, True)
    If excelInstalled = True And singleInstance = True Then
        SplashForm.Show()
        Dim MyAppPath As String = My.Application.Info.DirectoryPath
        Dim ExcelFilePath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Správce rozpisů 2019\" & "Rozpis1.xlsb")

        If Not IO.File.Exists(ExcelFilePath) Then
            Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis1.xlsb")
            If IO.File.Exists(ExcelfileBackupPath) Then
                My.Computer.FileSystem.CopyFile(ExcelfileBackupPath, ExcelFilePath, True)
                Call Open(ExcelFilePath)
            Else
                SplashForm.Close()
                ErrorForm.ShowDialog()
                End
            End If
        Else
            Call Open(ExcelFilePath)
        End If
        SplashForm.Close()
    ElseIf excelInstalled = False Then
        SplashForm.Close()
        CompatibilityErrorForm.ShowDialog()
    ElseIf singleInstance = False Then
        MsgBox("Správce rozpisů je již spuštěn.", vbInformation, "Aplikace je již spuštěna")
    End If
    Exit Sub
ErrorHandler:
    MsgBox("Při spouštění Správce rozpisů došlo k chybě.", vbCritical, "Došlo k chybě")
    Resume Next
End Sub

Sub Open(openThis As String)
    Dim xls As Application = New Application With {
        .WindowState = XlWindowState.xlMaximized
    }
    Dim workbook As Workbook = xls.Workbooks.Open(openThis)
    xls.Visible = True
End Sub
End Module


texts:
This is a follow up to my previous post.
I've used a BCrypt library to create a key from the passed in password.  I then separated out the salt from the hash.  The encryption is done using the salt concatenated to the hash, but only the hash is returned to the user.  The salt is prepended to the encrypted data.
The key(salt + hash) is used to create a 512 bit hash using SHA3512. Each byte of data is XOR'ed with a byte of the key and a byte of the new hash.  This byte of the hash is replaced by being XOR'ed with the byte of the key.  When the end of the hash is reached, this byte array with all new values is then hashed and used for the next 64 bytes of data.
The Decryption separates out the salt and combines it with the passed in key to create the original hash and continue with the original encryption steps.
using System.Text;
using System.Linq;
using System.Collections.Generic;
using SHA3.Net;
using BCrypt.Net;

class Cipher
{
    public static IEnumerable<byte> Encrypt(string password, IEnumerable<byte> data,out string key)
    {
        if (password == null)
        {
            password = "";
        }
        if (data == null)
        {
            data = new byte[] { 0 };
        }
        var hash = MakeKey(password);
        key = new string(hash, 22, 31);
        string salt = new string(hash, 0, 22);
        return GetBytes(data, key,salt);
    }
    public static IEnumerable<byte> Decrypt(IEnumerable<byte> data, string key)
    {
        if (data == null)
        {
            data = new byte[] { 0 };
        }
        return GetBytes(data, key);
    }
    static IEnumerable<byte> GetBytes(IEnumerable<byte> data, string key, string salt = "")
    {
        int saltLength = 0;
        if(salt == "")
        {
            salt = new string(data.Take(22).Select(x => (char)x).ToArray());
            saltLength = 22;
        }
        else
        {
            foreach(char c in salt)
            {
                yield return (byte)c;
            }
        }
        key = $"{salt}{key}";
        var hash = Sha3.Sha3512().ComputeHash(Encoding.UTF8.GetBytes(key));
        int i = 0;
        foreach (var b in data.Skip(saltLength))
        {
            //modulo 64
            int hashIndex = (int)(((uint)i << 26) >> 26);
            if (i > 0 && hashIndex == 0)
            {
                hash = Sha3.Sha3512().ComputeHash(hash);
            }
            byte offset = (byte)key[i % key.Length];
            var retVal = (byte)(b ^ offset ^ hash[hashIndex]);
            hash[hashIndex] ^= offset;
            ++i;
            yield return retVal;
        }
    }

    static char[] MakeKey(string password) => BCrypt.Net.BCrypt.HashPassword(password).Skip(7).ToArray();
}

Here's what the encrypted data can look like:
{86, 110, 68, 77, 68, 75, 46, 116, 73, 99, 50, 53, 114, 57, 89, 47, 109, 70, 88, 105, 114, 117, 233, 83, 221, 231, 216, 45, 118, 223, 227, 185, 170, 177, 131, 154, 240, 170, 72, 192, 182, 112, 149, 208, 102, 235, 252, 156, 127, 189, 255, 240, 203, 152, 142, 189, 140, 64, 166, 196, 13, 254, 138, 159, 229, 199, 80, 80, 113, 162, 137, 87, 216, 59, 81, 140, 123, 199, 211, 75, 43, 62, 11, 3}


texts:
jQuery plugin for a form. Looking for constructive criticism on my code. Thanks in advance!

// form.js
// splashinn

var Form = function(options) {

    options = options || {};

    this.url = options.url;
    this.$fields = $(options.fields);
    this.$status = $(options.status);
    this.$submit = $(options.submit);
    this.$form = options.form || 'form';
    this.rFields = {
        required: /[^.*]/,
        nodigit: /^[^0-9]+$/,
        email: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
    };
    this.required = [
        this.rFields.nodigit,
        this.rFields.email,
        this.rFields.required,
        this.rFields.required
    ];
    this.errors = ['Please enter a valid name.', 'Please enter a valid email address.', 'You must enter a subject.', 'No message? But I wanted one :('];
}

Form.prototype.init = function init() {

    this.$submit.click($.proxy(function(e) {
        this.process(e);
    }, this));

};

Form.prototype.process = function process(e) {

    var filled = true;

    e.stopImmediatePropagation();
    e.preventDefault();

    this.$fields.each($.proxy(function(i, element) {

        var $element = $(element);

        if (!$element.val().match(this.required[i])) {

            $element.focus();
            this.update(this.errors[i], true);
            filled = false;
            return false;
        }
    }, this));

    filled && this.submit($(this.$form).serialize());
};

Form.prototype.update = function update(message, isError) {

    if (isError && this.$status.hasClass('error')) {

        this.$status.addClass('error')
            .text(message);

        setTimeout($.proxy(function() {
            this.$status.removeClass('shake');
        }, this), 500);
    } else {
        this.$status.fadeOut();

        setTimeout($.proxy(function() {
            this.$status.text(message)
                .fadeIn();

            if (isError) {
                this.$status.removeClass('shake')
                    .addClass('error');
            } else {
                this.$status.removeClass('error info')
                    .addClass('success');
            }
        }, this), 500);
    }
    return this;
};

Form.prototype.submit = function submit(data) {

    $.ajax({
        type: 'POST',
        url: this.url,
        data: data,
        success: $.proxy(function(msg) {
            this.$fields.fadeOut();
            this.$status
                .empty()
                .append('
Nice one! The form has been sent to the server...
')

            $(this.$submit)
                .animate({
                left: '-=500px',
                opacity: 0,
            }, 300);
        }, this)
    });
};

Creating a new form:

var exampleForm = new Form({
    url: mailUrl,
    fields: 'form input, form textarea',
    status: '#status',
    submit: '#submit'
})

exampleForm.init()

Pass in:

The url to send the form data too
The form fields all encapsulated in one string seperated by commas in the correct order of validation rules.
Selector string where you want the status message to go
The submit selector. This element will actually submit the form


texts: Join two collections by date with no duplicate

texts:
Data

I have 4 Collection objects of the following kind:

dates1=(12/01/02, 15/01/03, 17/01/03, 25/04/04...)
dates2=(15/02/02, 17/06/07, 10/05/10, ...)
numbers1 = (3,5,2,7,...)
numbers2 = (1,-3,-1,...)

The rules of the game are:

dates1 will always have the same length of numbers1, dates2 will always have the same length of numbers, but dates1 is not necessarily as long as dates2.
The dates into the two dates collections are always growing within the same collection, but not necessarily the first date of dates1 will be before the first date of dates2.

Problem in words

I would like to create a "merged" collection of these two. In particular,

The datesTot collection will have to contain only one date for each record. So, for example, if both "dates1" and "dates2" contain the 14/01/13, then this date will appear in the collection only once.
The numbersTot collection will have to contain the sum of the two "numbers" collection in case the date is a duplicate, otherwise only the single value.

For example:

numbers1 = (1,3,4)
numbers2 = (4,7,12)
dates1 = (13/01/14, 14/01/15, 16/01/17)
dates2 = (12/01/14, 14/01/15, 18/01/17)

will result in the following:

datesTot = (12/01/14, 13/01/14, 14/01/15, 16/01/17, 18/01/17)
numbersTot = (4, 1, 10, 4, 12) '<-- where 10 is the sum of 7+3, because they both are on 14/01/15

What I have tried so far

I have tried to stretch the human logic described above in a code:

Determining with which date the joint collection should start:

Do While (dates1Index <= dates1Index.Count) And (dates2Index <= dates2Index.Count)
If dates1(dates1Index) < dates2(dates2Index) Then '<-- to put in a while loop with some conditions check
    datesTot.Add dates1(dates1Index)
    numbersTot.Add numbers1(dates1Index)
    dates1Index = dates1Index + 1
ElseIf dates1(dates1Index) > dates2(dates2Index) Then
    datesTot.Add dates2(dates2Index)
    numbersTot.Add numbers2(dates2Index)
    dates2Index = dates2Index+1
Else
    datesTot.Add dates1(dates1Index)
    numbersTot.Add numbers1(dates1Index) + numbers2(dates2Index)
    dates1Index = dates1Index + 1
    dates2Index = dates2Index + 1
End If
Loop

The idea, hence, is to keep on looping through the elements like this with the separate indexes, by adding some controls (for the collections lengths) and once reached the shortest collection's length, keep on adding all the others of the longest collection.

My question

The more I look at this method, the less I'm convinced. It's heavy, dirty and (in my opinion) not the best algorithm ever. Is there any built in for collections in VBA to join the elements without duplicates and sort them (I've not found anything in the docs) hence? Or in general, how should I design my code to accomplish this purpose in a flexible way?


texts:
For reasons unknown I've recently taken up generating word squares, or more accurately double word squares. Below you can see my implementation in Python, in about 40 lines. The code uses this word list. It takes around 10ms for dim=2 (2x2 word squares) and around 13 seconds for dim=3 (3x3 squares). For dim=4 it explodes to something like 3.5 hours in cpython, and causes a MemoryError in pypy. For dim=20 and dim=21 it returns 0 solutions in a few seconds, but for dim=18 and dim=19 it causes a MemoryError in both pypy and cpython.

So, I am looking for improvements that will allow me to explore values of dim >4, but also to explore ways of solving the MemoryErrors for the values <20. Small improvements of a few %, improvements in how things are expressed, as well as large improvements in the algorithm are all welcome.

import time
start = time.clock()

dim = 3 #the dimension of our square
posmax = dim**2 #maximum positions on a dim*dim square

words = open("word.list").read().splitlines()
words = set([w for w in words if len(w)==dim])
print 'Words: %s' % len(words)

prefs = {}
for w in words:
    for i in xrange(0,dim):
        prefs[w[:i]] = prefs.get(w[:i], set())
        prefs[w[:i]].add(w[i])

sq, options = ['' for i in xrange(dim)], {}

for i in prefs:
    for j in prefs:
        options[(i,j)] = [(i+o, j+o)
            for o in prefs[i] & prefs[j]]

schedule = [(p/dim, p%dim) for p in xrange(posmax)]

def addone(square, isquare, position=0):
    if position == posmax: yield square
    else:
        x,y = schedule[position]
        square2, isquare2 = square[:], isquare[:]

        for o in options[(square[x], isquare[y])]:
            square2[x], isquare2[y] = o
            for s in addone(square2, isquare2, position+1):
                yield s

print sum(1 for s in addone(sq, sq[:]))

print (time.clock() - start)


texts: Determining if a set of 2d vectors is a valid function

texts:
My idea was to take in the function and perform a self cross product so that I could check every pair against every other pair. I'm new to Haskell so this solution is probably rough.

My question is, is there a better way to emulate a nested for loop rather than a cross product? Also, is there any way to collapse my ugly valid and valid' into one clean function?

valid :: [(Int, Int)] -> Bool
valid f = valid' $ [(x,y) | x <- f, y <- f]

valid' :: [((Int,Int),(Int,Int))] -> Bool
valid' [] = True
valid' (((x,y),(x1,y1)):xs) = valid' xs && if x == x1 then (if y == y1 then True else False) else True


texts:
I have written this code to sort a list of numbers, in increasing order.

It is a combination of quick sort, insertion sort, and merge sort. I make the first element of the list a pivot, then I go through the list. If a number is less than or equal to the pivot, I "insert" the number in its appropriate position in the left list. Otherwise, it is inserted into right list. After I reach the end of the list I simply merge the left and right lists, since they are already sorted.

I would like to know the time complexity of this sorting method. I believe the best case scenario is \$O(n)\$. What would be the average time?

#lang racket

(define (merge-lists l1 l2)
  (cond ((null? l1) l2)
        ((null? l2) l1)
        ((<= (car l1) (car l2))
         (cons (car l1) (merge-lists (cdr l1) l2)))
        (else
         (cons (car l2) (merge-lists l1 (cdr l2))))))

(define (insert elem lst)
  (if (or (null? lst) (<= elem (car lst)))
      (cons elem lst)
      (cons (car lst) (insert elem (cdr lst)))))

(define (quick-sorter lst)
  (if (null? lst)
      '()
      (let ((pivot (car lst)))
         (letrec ((iter (lambda (l left-l right-l)
                          (cond ((null? l)
                                 (merge-lists left-l right-l))
                                ((<= (car l) pivot)
                                 (iter (cdr l) (insert (car l) left-l) right-l))
                                (else
                                 (iter (cdr l) left-l (insert (car l) right-l)))))))
           (iter (cdr lst) '() '())))))


texts:
I've just written a recursive matrix multiplication and I want to know my mistakes or problems. Is there a better way doing this?

public static double[,] Multiply(double[,] a, double[,] b, int rowA,int colA,int rowB,int colB, double[,] c)
{
    double[,] result = new double[a.GetLength(0), b.GetLength(1)];

    if (c != null)
        result = c;

    result[rowA, colB] += a[rowA, colA] * b[rowB, colB];

    colA += 1;
    rowB += 1;
    if (colA >= a.GetLength(1))
    {
        colA = 0;
        rowB = 0;
        rowA += 1;
        if(rowA >= a.GetLength(0))
        {
            rowA = 0;
            colB += 1;
        }
    }

    if (colB >= b.GetLength(1))
        return result;

    return Multiply(a, b, rowA, colA, rowB, colB, result);
}

Edit:
The rowA, colA variables are the indices for the element of the first matrix which is multiplied by the [rowB, colB] element of the second matrix.
Then we increase colA and rowB so we can multiply the next elements of the matrices.

When the colA reaches the end of the matrix (it is obvious that rowB has also reached the end of the second matrix) we reset them to 0 and move to the next row of the first matrix. when we reach the last row of the first matrix we move to the next column of the second matrix by increasing colB by 1; We then set rowA to 0 so that the multiplication begins from the first row of the first matrix again.

Finally, if colB exceeds the end column of the second matrix we have finished multiplying and we return our result.

Edit 2:

public static double[,] Multiply(double[,] a, double[,] b, int rowA,int colA,int rowB,int colB, double[,] c)
{
    double[,] result;
    if (c != null)
        result = c;
    else
        result = new double[a.GetLength(0), b.GetLength(1)];

    result[rowA, colB] += a[rowA, colA] * b[rowB, colB];

    colA += 1;
    rowB += 1;
    if (colA >= a.GetLength(1))
    {
        colA = 0;
        rowB = 0;
        rowA += 1;
        if(rowA >= a.GetLength(0))
        {
            rowA = 0;
            colB += 1;
        }
    }

    if (colB >= b.GetLength(1))
        return result;

    return Multiply(a, b, rowA, colA, rowB, colB, result);
}


texts:
#include "stdafx.h"
#include <exception>
#include <string>
#include <sstream>
#include <iostream>
#include <atomic>
template <typename T>
class Singleton
{
    //thread safe atomic variable to check whether client is creating more than  one instance
    static std::atomic_flag flag ;
public:
    static T& getinstance()
    {
        //I am delibreatly allocating it on heap so that I would not worry about its time of deinitilization
        //static variable initialization is thread safe
        static T * t = new T();
        return *t;
}
    //exception class- kept it as Internal
    class SingletonException : public std::runtime_error
    {
    public:
    SingletonException(const std::string& exString) :std::runtime_error(exString)
        {

        }
    };
protected:
    Singleton()
    {
        if (flag.test_and_set())
        {
        std::ostringstream  ex;
            ex << "More than one object of Singleton class " << typeid(T).name();
            throw SingletonException(ex.str());
        }
    }
    ~Singleton()
    {
    }
private:
        Singleton(const Singleton&) = delete;
        Singleton& operator= (const Singleton&) = delete;
        Singleton(Singleton&&) = delete;
        Singleton& operator= (Singleton&&) = delete;
};
template <typename T>
std::atomic_flag  Singleton<T>::flag;
class Myclass: Singleton<Myclass>
{
    public:
        Myclass()
        {
        }
public:
    friend Singleton<Myclass>;
};
int main()
{
try
    {
        Singleton<Myclass>::getinstance();
        Myclass obj;
        Singleton<Myclass>::getinstance();
    }
    catch (const Singleton<Myclass>::SingletonException& ex)
    {
        std::cout << ex.what();
    }
    getchar();
    return 0;
}

Few points:

I am inheriting it so that I can mark delete copy/move operations, but inheritance is mandatory
This template class should be kept as friend class of client class
If more than one object is created then it will throw exception provided client has inherited from it.

It is more like code review. But do you think it is really thread safe GOOD singleton.


texts: CakePHP 2.x Custom PagesController & Routing

texts:
I want to direct all requests that haven't got a valid controller action to my custom page controller.

I.e. I want /pages/new & /users/login etc to work correctly, but a request for /foo or /foo/bar should be directed to /pages/display/$path.

The following code works, but I'm pretty certain I'm not doing something the right way(tm).

// In app/Config/routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'displayHome'));

$controllerList = App::objects('controller');
foreach ($controllerList as $controller) {
    $contstr = substr($controller, 0, strlen($controller)-10);
    $contstr = Inflector::tableize($contstr);
    if($contstr != 'app') {
        Router::connect('/'. $contstr, array('controller'=>$contstr));
        Router::connect('/'. $contstr .'/:action', array('controller'=>$contstr));
        Router::connect('/'. $contstr .'/:action/*', array('controller'=>$contstr));

        // FIXME: Check if admin routing is set
        Router::connect('/admin/'. $contstr, array('controller'=>$contstr, 'admin'=>true));
        Router::connect('/admin/'. $contstr .'/:action', array('controller'=>$contstr, 'admin'=>true));
        Router::connect('/admin/'. $contstr .'/:action/*', array('controller'=>$contstr, 'admin'=>true));
    }
}

Router::connect('/**', array('controller'=>'pages', 'action'=>'display'));

Would someone please be able to review this and tell me if this is okay/horribly wrong?


texts:
My aim is to assign a color to each workday in a week. So if a user enters a day as a str, then I can know which color it should have.

Because colors and workdays are fixed, I make them as enum.Enum instance.

Is enum.Enum a proper choice for colors and workdays?
To link day and color, I choose dictionary for weekday_color. Is there a better choice?

from enum import Enum

class WeekDay(Enum):
    MONDAY = 'Monday'
    TUESDAY = 'Tuesday'
    WEDNESDAY = 'Wednesday'
    THURSDAY = 'Thursday'
    FRIDAY = 'Friday'

class Color(Enum):
    RED = 'Red'
    GREEN = 'Green'
    BLUE = 'Blue'

weekday_color = {
    WeekDay.MONDAY: Color.RED,
    WeekDay.TUESDAY: Color.GREEN,
    WeekDay.WEDNESDAY: Color.BLUE,
    WeekDay.THURSDAY: Color.GREEN,
    WeekDay.FRIDAY: Color.RED,
}

def main():
    today_input = 'Monday'
    today = WeekDay(today_input)
    today_color = weekday_color[today]
    print(today)
    print(today_color)

if __name__ == '__main__':
    main()


texts:
I would like to write a function that computes a cartesian product of two tuples in C++17 (the tuples can be of type std::tuple or std::pair, or any other type that can be used with std::apply). The tuples can be of different types and sizes, and the resulting std::tuple has to contain all std::pairs of elements, where the first element of a pair is from the first tuple, and the second element is from the second tuple. The function must be suitable for use in a constexpr context.

My approach is to use std::apply to effectively convert a tuple to a parameter pack, and then to recursively apply a generic lambda to it to build the result. Because a lambda cannot be explicitly recursive, I pass a reference to it to itself as an additional parameter self.

#include <functional>
#include <tuple>
#include <utility>

template<class X, class Y>
constexpr auto cartesian_product(const X& tx, const Y& ty) {
    if constexpr (std::tuple_size_v<X> == 0) return std::make_tuple();
    else return std::apply([&](const auto& ... ys) {
        return std::apply([&](const auto& ... xs) {
            const auto recursive = [&](
                const auto& self,
                const auto& arg, const auto& ... args)
            {
                if constexpr (sizeof...(args) == 0)
                    return std::make_tuple(std::make_pair(arg, ys)...);
                else return std::tuple_cat(
                        std::make_tuple(std::make_pair(arg, ys)...),
                        self(self, args...));
            };
            return recursive(recursive, xs...);
        }, tx);
    }, ty);
}

// Test
constexpr auto x = std::make_tuple('a', 2);
constexpr auto y = std::make_tuple(true, std::optional<long>{});
constexpr auto result = cartesian_product(x, y);

static_assert(result == std::make_tuple(
    std::make_pair('a', true),
    std::make_pair('a', std::optional<long>{}),
    std::make_pair(2,   true),
    std::make_pair(2,   std::optional<long>{})));

I would appreciate any comments or suggestions how to simplify or improve this code.

Update: A generalization to an arbitrary number of factors in the cartesian product (the components of the result are now tuples rather than pairs):

#include <functional>
#include <tuple>
#include <utility>

constexpr std::tuple<std::tuple<>> cartesian_product() {
    return {{}};
}

template<class X, class ... Y>
constexpr auto cartesian_product(const X& tx, const Y& ... ty) {
    if constexpr (std::tuple_size_v<X> == 0) return std::make_tuple();
    else return std::apply([&](const auto & ... tuples) {
        return std::apply([&](const auto & ... xxs) {
            const auto recursive = [&](
                const auto& self,
                const auto& x, const auto& ... xs)
            {
                    auto tuple = std::make_tuple(
                        std::tuple_cat(std::make_tuple(x), tuples)...);
                    if constexpr (sizeof...(xs) == 0) return tuple;
                    else return std::tuple_cat(std::move(tuple), self(self, xs...));
            };
            return recursive(recursive, xxs...);
        }, tx);
    }, cartesian_product(ty...));
}

constexpr auto x = std::make_tuple('a', 2);
constexpr auto y = std::make_tuple(true, std::optional<long>{});
constexpr auto z = std::make_tuple(1L);
constexpr auto result = cartesian_product(x, y, z);
static_assert(result == std::make_tuple(
    std::make_tuple('a', true, 1L),
    std::make_tuple('a', std::optional<long>{}, 1L),
    std::make_tuple(2,   true, 1L),
    std::make_tuple(2,   std::optional<long>{}, 1L)));

I do not like std::make_tuple(x) part, but do not see a better way to prepend an element to a tuple.


texts:
I have created the below code which works for me, but I feel there might be a better way to accomplish this in a new Pythonic way or better Python syntactic way.

Code snippet:

bondCheck.py

#!/usr/bin/python
# Port bonding checker.
# cat /proc/net/bonding/bond0

import sys
import re

def usage():
        print '''USAGE: %s [options] [bond_interface]

Options:
        --help, -h      This usage document

Arguments:
        bond_interface  The bonding interface to query, eg. 'bond0'. Default is 'bond0'.
''' % (sys.argv[0])
        sys.exit(1)

# Parse arguments
try:
        iface = sys.argv[1]
        if iface in ('--help', '-h'):
                usage()
except IndexError:
        iface = 'bond0'

# Grab the inf0z from /proc
try:
        bond = open('/proc/net/bonding/%s' % iface).read()
except IOError:
        print "ERROR: Invalid interface %s\n" % iface
        usage()

# Parse and output
active = 'NONE'
Link = 'NONE'
slaves = ''
state = 'OK'
links = ''
bond_status = ''
for line in bond.splitlines():
        m = re.match('^Currently Active Slave: (.*)', line)
        if m:
                active = m.groups()[0]

        m = re.match('^Slave Interface: (.*)', line)
        if m:
                s = m.groups()[0]
                slaves += ', %s' % s

        m = re.match('^Link Failure Count: (.*)', line)
        if m:
                l = m.groups()[0]
                links += ', %s' % l

        m = re.match('^MII Status: (.*)', line)
        if m:
                s = m.groups()[0]
                if slaves == '':
                        bond_status = s
                else:
                        slaves += ' %s' % s
                if s != 'up':
                        state = 'FAULT'

print "%s: %s (%s), Active Slave: %s, PriSlave: %s (%s), SecSlave: %s (%s), LinkFailCountOnPriInt: %s, LinkFailCountOnSecInt: %s"  % (iface, state, bond_status, active, slaves.split(',')[1].split()[0], slaves.split(',')[1].split()[1], slaves.split(',')[2].split()[0], slaves.split(',')[2].split()[1], links.split(',')[1], links.split(',')[2])

Code Returned Result:

$ ./bondCheck.py
bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LinkFailCountOnPriInt:  0, LinkFailCountOnSecInt:  0

Edit:

Bond config

cat /proc/net/bonding/bond0
Bonding Mode: fault-tolerance (active-backup)
Primary Slave: ens3f0 (primary_reselect always)
Currently Active Slave: ens3f0
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 2500
Down Delay (ms): 300
Slave Interface: ens3f0
MII Status: up
Speed: 20000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 5a:19:bb:00:00:48
Slave queue ID: 0
Slave Interface: ens3f1
MII Status: up
Speed: 20000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 5a:19:bb:00:00:49
Slave queue ID: 0


texts: Finding the first and last IP in an IP range string

texts:
I'm very new to python and scripting in general. I've come up with the following function to find the first and last IP when an IP range string is inputted. I want to only use base Python (and not download any libraries essentially).

Example:

genRange("1.2.3.*"):
Start IP = 1.2.3.0
End IP = 1.2.3.255

genRange("1.*"):
Start IP = 1.0.0.0
End IP = 1.255.255.255

genRange("1.2.3.4"):
Start IP = 1.2.3.4
End IP =
NotRange

This seems very hardcoded to me, because it really is. Is there a a better way to do this that is obvious/jumps out at you?

I still need to handle invalid input.

def genRange(ipRangeString):
    startIP = ""
    endIP = ""
    if '.' in ipRangeString:
        ipV = 4
    if ':' in ipRangeString:
        ipV= 6
    if ipV == 4:
        parts = ipRangeString.split(".")
        i = 0
        for item in parts:
            if item != "*":
                if 0 <= int(item) <= 255:
                    if (i<=3):
                        startIP = startIP + item + '.'
                        if (i==3): startIP = startIP[:-1]
                    i+= 1
            else:
                tempSIP = startIP
                endIP = startIP
                while (i<=3):
                    endIP = endIP + "255"
                    startIP = startIP  + "0"
                    if (i<3):
                        endIP = endIP + '.'
                        startIP = startIP + '.'
                    i+= 1
    print "Start IP = ", startIP
    print "  End IP = ", endIP
    if not (endIP):
        print "NotRange"


texts: Election vote-counting, result-posting chatbot

texts:
In preparation for the end of Code Review's 2015 election, I've built a simple bot to get the election votes, run OpenSTV on them, and post the result to a chatroom. I'm using this Python implementation of STV and ManishEarth's ChatExchange.

import getpass
import logging
import os
import time
import urllib
import sys
from subprocess import call

import ChatExchange.chatexchange
from ChatExchange.chatexchange.events import MessageEdited

logging.captureWarnings(True)

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

logging.basicConfig(level=logging.CRITICAL)

if 'ChatExchangeU' in os.environ:
    email = os.environ['ChatExchangeU']
else:
    email = raw_input("Email: ")
if 'ChatExchangeP' in os.environ:
    password = os.environ['ChatExchangeP']
else:
    password = getpass.getpass("Password: ")
client = ChatExchange.chatexchange.Client('stackexchange.com', email, password)

raw_input(bcolors.BOLD + bcolors.OKGREEN + "Connection good." + bcolors.ENDC + bcolors.BOLD + " [Enter] to proceed getting results for " + sys.argv[1] + " election #" + sys.argv[2] + "..." + bcolors.ENDC)

urllib.urlretrieve ("http://" + sys.argv[1] + "/election/download-result/" + sys.argv[2], "votes.blt")

result = os.popen("python runElection.py MeekSTV votes.blt").read()

os.remove("votes.blt")

result_indented = ""

for string in result.splitlines():
    result_indented = result_indented + "    " + string + "\n"

print result_indented

winners_line = ">" + result_indented.splitlines()[-1]

okay_to_post = raw_input("Okay to post? ")
if okay_to_post.lower() == "y":
    sandbox = client.get_room(sys.argv[3])
    sandbox.send_message(winners_line)
    sandbox.send_message(result_indented, False)

    time.sleep(40)

I run it from the command line like so:

python StackElectChat.py <site> <election number> <chatroom id>

For example, running this:

python StackElectChat.py serverfault.com 2 17251

Would take the results from Server Fault's second election and post it to Chatroom #17251.

Some concerns:

I don't like how I'm doing colors for it (taken from this Stack Overflow answer), is there a built in way?
okay_to_post.lower() seems like a hack - is there a built in way to check for an affirmative answer to a request?
I don't like how I iterate over every line to add code formatting (four spaces) to the chat message


texts:
This is the task I was given after completing my program. I don't have a clue what procedures and functions are to be honest. Therefore I have no clue on how to break down my program into different elements of it.

#paint calculator

RoomWidth = 0
RoomHeight = 0
RoomTotal = 0
RoomPaint = 0

RoomWidth = float(input("Enter the room width, it must be between 1m-25m: "))
RoomHeight = float(input("Enter the room height, it must be between 2m-6m: "))
if ((RoomWidth <=25 and RoomWidth >=1) and (RoomHeight <=6 and RoomHeight >=2)):

    RoomTotal = ((RoomWidth * RoomHeight)*4)

    PaintSelection = str (input("Please choose from a selection of paints: 'Luxury', 'Standard', or 'Economy'."))
    if PaintSelection == "Luxury":
        RoomPaint = RoomTotal * 1.45
    elif PaintSelection == "Standard" :
        RoomPaint = RoomTotal * 1.00
    elif PaintSelection == "Economy" :
        RoomPaint = RoomTotal * 0.45

    UndercoatAnswer = str (input("Would you like to use an undercoat? Y/N: "))
    if UndercoatAnswer == "Y":
        UndercoatingCost = (RoomTotal * 0.5)
    elif UndercoatAnswer == "N":
        UndercoatingCost = 0

    TotalCost = RoomPaint + UndercoatingCost
    print ("The total cost of painting this room is £",TotalCost,)

else:
    print ("Invalid input")


texts:
The following working function seems a bit hacky to me as it has been pieced together from a handful of (probably poorly written) online tutorials, and I want to know if there is a better (or more standard) way to approach this.

/***
 * GET HTTP Operation
 *
 * @param   request Request URI
 * @return  Element Root Element of XML Response
 */
protected Element get(String request) {

    HttpURLConnection connection = null;

    Element rootElement;

    try {

        URL url = new URL(this.baseUrl + request);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        BASE64Encoder enc = new sun.misc.BASE64Encoder();
        String userpassword = this.username + ":" + this.password;
        String encodedAuthorization = enc.encode( userpassword.getBytes() );
        connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
        connection.setRequestProperty("Content-type", "application/xml");
        connection.setRequestProperty("Accept", "application/xml");

        InputStream responseStream = connection.getInputStream();

        //--- Parse XML response InputStream into DOM

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(responseStream);

        rootElement = doc.getDocumentElement();

    } catch(Exception e) {

        System.out.print(e.toString());
        rootElement = null;

    } finally {

        if(connection != null) {
            connection.disconnect();
        }

    }

    return rootElement;
}

I am a Java novice and am especially unclear on proper try/catch usage.

I am creating a Java Wrapper for an REST API and this is a small piece of that puzzle.  You can click here to see a bigger picture of the project as a whole.


texts: JavaScript function for to find a defined element within a nested array

texts:
Following task:
You've got an array which contains parts. Parts can contain subparts. Subparts can contain further subparts and so on.

For example:

computer

   cpu

   hardDisc

   graphicsCard

      graphicsCardCpu

      graphicsCardRam

Let's suppose I have a correct structure where every part has a unique id. Such a structure would be assured.

I've made this function which retrieves a part with a given id from the above described structure.

// Example structure
var structure = [
  {
    id : 1,
    name : 'firstLevelOne',
    category : 'alpha',
    subParts : null,
  },
  {
    id : 2,
    name : 'firstLevelTwo',
    category : 'beta',
    subParts : [{
      id : 6,
      name : 'secondLevelOne',
      category : 'alpha',
      subParts : null
    }],
  },
  {
    id : 3,
    name : 'firstLevelThree',
    category : 'alpha',
    subParts : [{
      id : 7,
      name : 'secondLevelTwo',
      category : 'gamma',
      subParts : [{
        id : 8,
        name : 'thirdLevelOne',
        category : 'beta',
        subParts : [ {
          id: 11,
          name : 'fourthLevelOne',
          category : 'alpha',
          subParts : null
        }]
      },
                  {
                    id : 10,
                    name : 'secondLevelFour',
                    category : 'beta',
                    subParts : null
                  }]
    }],
  },
  {
    id : 4,
    name : 'firstLevelFour',
    category : 'gamma',
    subParts : [{
      id : 9,
      name : 'secondLevelThree',
      category : 'alpha',
      subParts : null
    }],
  },
  {
    id : 5,
    name : 'firstLevelFive',
    category : 'beta',
    subParts : null,
  }
];

// #### Let's try this out ...
var part = getPart(4, structure);

for (var i in part) {
  console.log(part[i]);
}

console.log('\n');

part = getPart(11, structure);

for (var i in part) {
  console.log(part[i]);
}

console.log('\n');

part = getPart(8, structure);

for (var i in part) {
  console.log(part[i]);
}
// ############################

// The actual function ...
// Retrieves the object from
// the storage-array.
function getPart(id, arr) {
  var ret = null;
  var i;

  if (!id || !arr) return ret;

  for (i = 0; i < arr.length; i++) {
    if (arr[i]['id'] === id) {
      return arr[i];
    } else {
      if (arr[i]['subParts']) {
        ret = getPart(id, arr[i]['subParts']);

        if (ret) return ret;
      }
    }
  };

  return ret;
}

Are there weak points? Could the function be improved?


texts: Excel VBA - searching PDF using FindText three times per doc

texts:
It takes a very long time for some files to be searched. I need to do this with 1000+ PDFs. It seems to be held up during the FindText operation. Any suggestions?

Sub pdfSearch()

Dim acroApp As Object, acroDoc As Object
Dim searchString1 As String, searchString2 As String, searchString3 As String
Dim filePath As Variant
Dim i As Long

Sheet3.Range("A4:C999999").ClearContents
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
i = 4
searchString1 = Sheet3.Range("b1").Value
searchString2 = Sheet3.Range("c1").Value
searchString3 = Sheet3.Range("d1").Value
For Each filePath In Sheet2.Range("a1:a25")
    Debug.Print (filePath.Row)
    Set acroApp = CreateObject("AcroExch.App")
    Set acroDoc = CreateObject("AcroExch.AVDoc")
    If acroDoc.Open(filePath.Value, "") = -1 Then
        If acroDoc.FindText(searchString1, 0, 0, 1) = -1 Then
            Sheet3.Cells(i, 2).Value = searchString1
            Sheet3.Cells(i, 3).Value = filePath.Value
            i = i + 1
        End If
        If acroDoc.FindText(searchString2, 0, 0, 1) = -1 Then
            Sheet3.Cells(i, 2).Value = searchString2
            Sheet3.Cells(i, 3).Value = filePath.Value
            i = i + 1
        End If
        If acroDoc.FindText(searchString3, 0, 0, 1) = -1 Then
            Sheet3.Cells(i, 2).Value = searchString3
            Sheet3.Cells(i, 3).Value = filePath.Value
            i = i + 1
        End If
    Else:
        MsgBox "PDF not found"
    End If
    acroDoc.Close 0
    Set acroDoc = Nothing
    Set acroApp = Nothing
Next filePath

Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub


texts:
I have a grid which allows a user to enter a new Grid item. If the grid item exists or the tb is empty it displays the error. Here's the code I came up with.

Can anybody think of a cleaner or more efficient way of doing so?  Thinking about it now, I guess I could have done it all in one function, and placed InsertTrack() in the else condition of DoesTrackExist and register the script in the if statement.

 private void InsertTrack()
   {
       if (DoesTrackExist(txtEventTracks.Text))
       {
           using (EMSEntities db = new EMSEntities())
           {
               EventTrack newEventTrack = new EventTrack()
               {
                   TrackName = txtEventTracks.Text
               };
                   db.EventTracks.Add(newEventTrack);
                   db.SaveChanges();
           }
       }
       else
       {
          ScriptManager.RegisterStartupScript(Page, typeof(Page), "Error", "alert('Track name cannot be duplicate or empty')", true);
       }
   }
   private bool DoesTrackExist(string txtValue)
   {
       using (EMSEntities db = new EMSEntities())
       {
           var context = from x in db.EventTracks
                         where x.TrackName.Contains(txtEventTracks.Text)
                         select x;

           if (context.Any() || txtEventTracks.Text == "")
           {
               return false;
           }
           else
           {
               return true;
           }
       }
   }


texts:
I'm working on an interview code sample in Javascript, which is not my first language.  The task is simple enough:  Given a webpage with a variety of images, allow the users to add comments.  The code to generate and manage the images was given to me; my task was to build out comment.js and comments.controller.js.  Everything works and I'm happy with it, but since JS is not my first choice I don't know if there's any glaring errors I'm missing.  Please be as nitpicky as possible.

Most of my code is in the following two files.  The rest can be viewed at https://github.com/paulnicholsen27/flatiron but I do not need feedback on any of those (I didn't write them)--it just may be helpful to run the entire program rather than piecemeal.  I don't know how you brave altrusitic wizards operate most effectively.

comment.js

function Comment(imageId, text) {
    this.id = this.constructor.all.length;
    this.imageId = imageId;
    this.text = text;
    this.constructor.all.push(this);
}

Comment.all = [];

Comment.prototype.buildCommentEl = function() {
    return $(`<li id='comment-${this.id}'>${this.text}</li>`);
}

comments.controller.js

class CommentsController {
  constructor() {
    this.$addCommentForm = $('.add-comment')
  }

  init() {
    $(".add-comment").each((index, element) => {
        element.addEventListener("submit", this.addCommentFormListener);
    })
  }
}

CommentsController.prototype.addCommentFormListener = function(e){
    e.preventDefault();
    var image = $(this).closest(".image");
    var imageId = Number(image.find("ul").attr("data-id"));
    var commentForm = $(this).find('input[name="comment-description"]')
    var commentContents = commentForm.val();
    if (commentContents.length) {
       var newComment = new Comment(imageId, commentContents);
       CommentsController.render(newComment);
       commentForm.val("");  // reset comment form
    }
}

CommentsController.render = function(newComment){
    var imageId = newComment.imageId;
    var image = Image.all.find(image => image.id === Number(imageId));
    image.comments.push(newComment);
    var commentList = $(`#comments-${imageId}`);
    var commentEl = newComment.buildCommentEl();
    commentList.append(commentEl);
}


texts: topological sorting to find the pre-requisite for courses

texts:
Solving this problem:

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

I have used topological sorting to solve this problem. So, for every node I am calculating in-degree and picking the lowest node whose in-degree is zero. This will be the first node and who doesn't have any prerequisite. After that I am decrementing the child node in-degree and then repeating the same process until i am out of nodes.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class Course_Schedule_II_210 {

    public static void main(String[] args) {
        int[][] arr = {};
        int totalCourse = 0;
        int[] totalCourseInOrder = findTotalCourseInOrder(totalCourse, arr);

        for (int i=0; i < totalCourseInOrder.length; i++) {
            System.out.println("The totalCourseInOrder element is : "+totalCourseInOrder[i]);
        }
    }

    private static int[] findTotalCourseInOrder(int totalCourse, int[][] arr) {

        HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
        int[] a1 = new int[totalCourse];
        int var = 0;

        for (int i=0; i < arr.length; i++) {
            int[] a = arr[i];
            int k = a[1];
            int v = a[0];
            if (!map.containsKey(k)) {
                map.put(k, new ArrayList<Integer>());
            }
            map.get(k).add(v);
            a1[v]++;
        }
        for (int j=0; j < a1.length; j++) {
            if (a1[j] == 0) {
                var = j;
                break;
            }
        }

        return findOrderInSeries(map, a1, var, totalCourse);
    }

    private static int[] findOrderInSeries(HashMap<Integer, ArrayList<Integer>> map, int[] a1, int var, int totalCourse) {

        int[] arr1 = new int[totalCourse];
        Queue<Integer> queue = new LinkedList<Integer>();

        int index = 0;
        for (int i = 0; i < a1.length; i++) {
            if (a1[i] == 0) {
                queue.add(i);
                arr1[index++] = i;
            }
        }
        while (!queue.isEmpty()) {
            int firstElement = queue.poll();
            if (map.get(firstElement) != null) {
                for (int ar : map.get(firstElement)) {
                    a1[ar]--;
                    if (a1[ar] == 0) {
                        queue.offer(ar);
                       arr1[index++] = ar;
                    }
                }
            }
        }
        for (int i = 0; i < a1.length; i++) {
            if (a1[i] != 0) {
                return new int[0];
            }
        }
        return arr1;
    }

}


texts: Converting an array to IF() statement using EVAL()

texts:
I'm trying to build an interface for building if statements for a project I'm working on, and I've came to a conclusion that the best option for my use case is to use EVAL().

Can anyone break my code, inject anything or find a better solution for this specific task, that I might be missing?

Here's the code on a sandbox.

I tried my best to leave comments on the important bits, and here's the code in case this sandbox link is broken in the future:

<?
error_reporting(E_ERROR | E_PARSE);

//Change one of those values to test the if statement
$vars['testvar1'] = 1;
$vars['testvar2'] = 0;

//What to run trough the if statement
// [AND\OR, VAR_NAME\TEXT,         "OPERATOR",  VAR_NAME\TEXT
$if = [
   ["",     ["var" => "testvar1"], "==",        ["text" => "1"]],
   ["AND",  ["var" => "testvar2"], "==",        ["text" => "1"]],
];

//Builds the statement
foreach ($if as $k => $v) {
  $first[$k] = $vars[$v[1]['var']] ?? $v[1]['text'];
  $second[$k] = $vars[$v[3]['var']] ?? $v[3]['text'];

  $st .= " $v[0] \$first[$k] $v[2] \$second[$k] ";
}

//Shows the generated statement
echo "if($st)\n";

//Evaluates the statement
eval("if($st) { \$ok = 1; } else { \$ok = 0; }");

//Shows if True or False
echo $ok;


texts:
I'm learning c++ and I know some algorithms and data structures. I was wondering what is the best way to do merge sort for a vector in c++.
// will write a program for merge sort
/* steps:
 * have an array of size n call it A
 * divide A into left and right halves L and R
 * call merge sort on the two halves now L' and R'
 * now merge the two halves into B (the sorted version of A)
 */
/* the merging algorithm:
 * the merging algorithm is a "two finger algo"
 * where an element of L' is compared with each elt of R' until the elt in R' is less
 * we then take this element and put it into our sorted array, B
 */
#include <iostream>
#include <vector> // will use the vector class  to make things like list slicing very easy

using namespace std;
void merge_sort(vector<int> &arr);
void merge(vector<int >&left, vector<int> &right, vector<int> &results);

int main() {
    vector<int> my_vector{10, 30, 50, 40};
    merge_sort(my_vector);

    for (int i: my_vector)
        cout << i << ',';
    return 0;
}

void merge_sort(vector<int> & arr) {
    if (arr.size() <= 1) return;

    int mid = arr.size() / 2;
    vector<int> left(arr.begin(), arr.end() - mid);
    vector<int> right(arr.begin() + mid, arr.end());

    merge_sort(left);
    merge_sort(right);
    merge(left, right, arr);
}
void merge(vector<int> &left, vector<int> &right, vector<int> &results)
{
    int L_size = left.size();
    int R_size = right.size();
    int i = 0, j = 0, k = 0;
    // two finger algorithm
    while (j < L_size && k < R_size)
    {
        if (left[j] < right[k]) {
            results[i] = left[j];
            j++;
        }
        else {
            results[i] = right[k];
            k++;
        }
        i++;
    }
    while (j < L_size) {
        results[i] = left[j];
        j++; i++;
    }
    while (k < R_size) {
        results[i] = right[k];
        k++; i++;
    }
}
```


texts: Hangman game, with the number of guesses depending on the word length

texts:
This is an interactive game between the computer and the player, where the computer chooses a word and the user has to guess the letters in that word.

The computer provides certain number of guesses to the user.

Below is my code:

import random
import string

def load_words():
    print "Loading word list from file..."
    inFile = open("words.txt", 'r', 0)
    line = inFile.readline()
    wordlist = line.split()
    print "  ", len(wordlist), "words loaded."
    return wordlist

wordlist = load_words()

def choose_word(wordlist):
    return random.choice(wordlist)

def avail_letters(guesses,guess):
    return guesses.replace(guess,'')

def fill_blank(random_word,blank,guess):
    blank_new=''
    for i,l in enumerate(random_word):
        if l==guess:
            blank_new+=guess
        else:
            blank_new+=blank[i]
        #print blank_new
    return blank_new

def hangman():
    random_word=choose_word(wordlist)
##    print random_word
    len_word=len(random_word)
    print "I am thinking of a word that is ",len_word," letters long."
    print "-------------"
    no_of_guesses=len_word*2
    guesses=string.ascii_lowercase
    guess=''
    blank="_"*len_word
    while no_of_guesses:
        print "You have ",no_of_guesses," guesses left."
        guesses=avail_letters(guesses,guess)
        print "Available letters: ",guesses
        guess=raw_input("Please guess a letter: ")
        if guess in random_word and guesses:
            blank=fill_blank(random_word,blank,guess)
            print "Good guess: ",blank
        else:
            print "Oops! That letter is not in my word: ",blank
        no_of_guesses-=1
        print "-------------"
        if blank==random_word:
            print "Congratulations, you won!"
            break;
    else:
        print "Sorry, you lose!"


texts: Determine if a String has a mirroring head and tail

texts:
Problem statement:

  Given a string, look for a mirror image (backwards) string at both the
  beginning and end of the given string. In other words, zero or more
  characters at the very begining of the given string, and at the very
  end of the string in reverse order (possibly overlapping). For
  example, the string "abXYZba" has the mirror end "ab".

Examples:

mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"

Below is my solution to the problem in java:

public String mirrorEnds(String string) {
    final int len = string.length();
    final int half = len / 2;
    String result = "";

    for (int i = 0; i < half; i++) {
        if (string.charAt(i) != string.charAt(len -1 -i)) {
            break;
        } else {
            result += string.substring(i, i + 1);
        }
    }
    return result.length() == half ? string : result;
}

Is it safe to say that in terms of time complexity the solution is optimal already? Any other review comments are also welcome.


texts:
I am learning Python, and would like to learn how to make this code simpler and easier to read.

Things I am hoping to learn:

What variables might be appropriate?
How can I make it simpler?
Is there any way to make it more efficient?
What can be put into functions without sacrificing readability?

import random
yn = raw_input("Do you wanna build a mathman? y/n ")
if yn == "n":
    exit()

else:
    while yn =="y":
        x =int( random.choice(range(1,100)))
        y =int( random.choice(range(1,100)))
        a = str(x)
        b = str(y)
        s = 0
        xy = x * y
        print "What is " + a  + " x " + b + "?"
        ua = int(raw_input("What is the answer? "))
        while ua != xy:
            print "You are wrong, try again "
            ua = int(raw_input("Try again- "))
            s = s - 1
        yn = raw_input("You are correct, would you like to go again? y/n ")
        s = s + 1
        t = str(s)
    print "Your score is " + t


texts:
I'd really appreciate if I could get some feedback on the following code with regard to security, efficiency and possible uncaught errors. Personally I feel the printAndCleanString and friendlyLookup functions combined are very messy but I don't know how to fix them.

In particular I would love feedack on how to more cleanly and efficiently return strings.

#include <stdio.h>
#include <malloc.h>
#include <mem.h>

struct bstNode {
    int val;
    struct bstNode *left;
    struct bstNode *right;
};

void insert(struct bstNode **head, int val);

int lookup(struct bstNode **node, int val);

void printDFS(struct bstNode *head);

char *friendlyLookup(struct bstNode **node, int val);

void printAndCleanString(char *string);

int main() {
    struct bstNode *bstTree = NULL;
    insert(&bstTree, 8);
    insert(&bstTree, 5);
    insert(&bstTree, 98);
    insert(&bstTree, 2);
    insert(&bstTree, 15);
    insert(&bstTree, 65);
    insert(&bstTree, 15);
    printDFS(bstTree);
    printf("\n");
    printAndCleanString(friendlyLookup(&bstTree, 1));
    printAndCleanString(friendlyLookup(&bstTree, 65));
}

void insert(struct bstNode **head, int val) {
    if (*head == NULL) {
        *head = malloc(sizeof(struct bstNode));
        if (*head == NULL) {
            printf("malloc failed!");
            return;
        }
        (*head)->val = val;
        (*head)->left = NULL;
        (*head)->right = NULL;
        return;
    }

    if (val < (*head)->val) {
        return insert(&(*head)->left, val);
    } else {
        return insert(&(*head)->right, val);
    }
}

void printDFS(struct bstNode *head) {
    if (head->left != NULL) printDFS(head->left);
    printf("%d ", head->val);
    if (head->right != NULL) printDFS(head->right);
}

int lookup(struct bstNode **node, int val) {
    if (*node == NULL) {
        return -1;
    }
    if ((*node)->val == val) {
        return val;
    }
    if (val < (*node)->val) {
        return lookup(&(*node)->left, val);
    } else {
        return lookup(&(*node)->right, val);
    }
}

char *friendlyLookup(struct bstNode **node, int val) {
    int result = lookup(node, val);
    char resultString[256];
    char numberString[256];
    sprintf(numberString, "%d", val);
    if (result > -1) {
        sprintf(resultString, " is present in the bst\n");
    } else {
        sprintf(resultString, " is not present in the bst\n");
    }
    char *resultPointer = malloc(strlen(resultString) + strlen(numberString) + 1 * sizeof(char));
    if (resultPointer == NULL) {
        printf("Malloc error!");
        return NULL;
    }
    sprintf(resultPointer, "%s%s", numberString, resultString);
    return resultPointer;
}

void printAndCleanString(char *string) {
    printf(string);
    free(string);
}


texts: Encrypting messages using the XOR operation

texts:
recently I've started to learn Clojure. I came up with an easy programming problem, described by this C code:

int main() {
    const int N = 5;
    const int M = 12;

    uint8_t small[N] = { 1, 2, 3, 4, 5 };
    uint8_t big[M];

    memset(big, 0xff, M);

    for(size_t i = 0; i < M; ++i) {
        big[i] ^= small[i % N];
    }

    for(size_t i = 0; i < M; ++i) {
        printf("%02x", big[i]);
        if(i != M - 1)
            printf(" ");
    }

    printf("\n");
    return 0;
}

In other words: I have two arrays. One is a bigger one (my "message" - "big"), and second one is shorter (my "key" - "small"). I would like to encrypt my message with my key, by using the XOR operation. The encryption would perform a bit XOR of every byte from message array with a corresponding byte from the key array. Since the key is shorter than the message, when the key's index will go out of bounds, it should be started from the beginning again.

The message I would like to encrypt is 12 * 255:

255 255 255 255 255 255 255 255 255 255 255 255

And my key is:

1 2 3 4 5

I've came up with this Clojure program:

(defn perform-xor []
  (let [bigmap (repeat 12 0xFF) xorkey [1 2 3 4 5] n (count bigmap)]
    (map (fn [o] (bit-xor (o 0) (o 1)))
         (map vector bigmap (take n (cycle xorkey))))))

(defn get-string-output []
  (interpose
    " "
    (map (fn [b] (format "%02x" b))
         (perform-xor))))

(defn -main [& args]
  (do
    (doseq [strings (get-string-output)]
      (print strings))
    (println)))

I assume it can be written with less lines, and with more Clojure-like approach. Could anyone please tell me what can be done more in the "spirit" of Clojure?


texts: ForEachAsyncSemaphore asynchronously processing tasks but enable fast fail

texts:
I know this has been done many times before, but this is my existing code taken from a sample I found to async process a list of tasks. I've seen Task.Run in use before in many examples, but I'm assuming that in most cases, the workload will be IO bound and therefore the Task scheduler is not clever enough to know whether to grab a thread pool thread rather than use TaskCompletionSource.
I also wanted the below extension method to fast fail, that is if there are 50 items being processed I want the whole thing to fail if just one task encounters an exception. I use a Task.Delay as a "marker" task to signal the whole batch to finish.  Is the below a good implementation and if so how can it be improved upon?
  public static async Task ForEachAsyncSemaphore<T>(this IEnumerable<T> items,
                                                      Func<T, Task> func,
                                                      int dop,
                                                      CancellationToken ct)
    {
        Exception capturedException = null;

        var childCts = new CancellationTokenSource();
        var linkedTokens = CancellationTokenSource.CreateLinkedTokenSource(ct, childCts.Token);

        using (var semaphore = new SemaphoreSlim(dop))
        {
            var cancellationTask = Task.Delay(Timeout.Infinite, linkedTokens.Token);
            var tasks = items.Select(async item =>
            {
                await semaphore.WaitAsync(linkedTokens.Token);

                try
                {
                    await func(item);
                }
                catch (Exception ex)
                {
                    capturedException = ex;
                    childCts.Cancel();
                }
                finally
                {
                    semaphore.Release();
                }

            }).ToArray();

            // Use cancellation task as signal to exit early if unexpected exception
            await Task.WhenAny(Task.WhenAll(tasks), cancellationTask);

            if (capturedException != null)
            {
                throw capturedException;
            }
        }


texts:
I wrote this code to check the even numbers from the List. After finding even number I twice the even numbers with the help of Map and then find the sum of each even number after making it double by use of the reduce method.

import java.util.Arrays;
import java.util.List;

public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

System.out.println(
numbers.stream()
        .filter(e -> e % 2 == 0)
        .map( e -> e * 2)
        .reduce(0, Integer::sum));
}


texts: Trimming strings in non-contiguous spreadsheet ranges

texts:
This code is tested and works, but I am needing some guidance on simplifying these loops with non-contiguous ranges. I was thinking an array might be better, but I haven't had enough experience with Arrays to know where to start with one. Any guidance would be greatly appreciated.

Dim r As Range
Dim v
For Each r In JHACheck.Range("M7:M32")
    v = r.Value
    If v <> "" Then
        If Not r.HasFormula Then
            r.Value = Trim(v)
        End If
    End If
Next r

For Each r In JHACheck.Range("M35:M41")
    v = r.Value
    If v <> "" Then
        If Not r.HasFormula Then
            r.Value = Trim(v)
        End If
    End If
Next r

For Each r In JHACheck.Range("R35:R41")
    v = r.Value
    If v <> "" Then
        If Not r.HasFormula Then
            r.Value = Trim(v)
        End If
    End If
Next r


texts:
I am creating a class which should contain all the methods related to Prime numbers. Now in that I have to implement a method isPrime() to check the primality of a number. I have to implement that in two ways one that uses the Sieve of Erastosthene and one that uses the standard for looping. The class should be made in such a way that If I use a specific constructor to instantiate it then it should use the sieve algorithm. If I use the other constructor then it should use the standard way of finding primality (through looping). Now I made this implementation keeping conceptual affinity in mind. I have made inner classes to implement both the types of implementations. Is this is the best way to do this, or should I use separate classes?

import java.util.Arrays;

/**
 * Class for Prime Number related methods.
 */
public class PrimeNumber {

    private PrimeAbstract primeNumber;

    /**
     * If you want the class to use sieve of erastosthene as the
     * base algorithm then you need to use this constructor. You need to pass the
     * limit till which you want the sieve to be initialized as the method parameter.
     * @param limit
     */
    public PrimeNumber(int limit) {
        this.primeNumber = new PrimeNumberWithSieve(limit);
    }

    /**
     * If you want the class to use the classic way of finding out the primality
     * of a number. By classic we mean for looping.
     */
    public PrimeNumber(){
        this.primeNumber = new PrimeNumberClassic();
    }

    /**
     * Returns if a number is prime or not.
     * @param number
     * @return boolean
     */
    public boolean isPrime(int number){
        return primeNumber.isPrime(number);
    }

}

/**
 * abstract class of prime number object
 */
abstract class PrimeAbstract {

    public abstract boolean isPrime(int number);
}

/**
 * This class uses sieve of erastothene as the base
 * algorithm for finding out the primality of a natural number.
 */
class PrimeNumberWithSieve extends PrimeAbstract {

    boolean[] sieve;

    public PrimeNumberWithSieve(int limit){
        sieve = limit<1000?new boolean[1001]:new boolean[limit+1];
        Arrays.fill(sieve, true);
        sieve[0]=sieve[1]=false;
        for (int i=2;i<sieve.length;i++) {
            if(sieve[i]) {
                for (int j=2;i*j<sieve.length;j++) {
                    sieve[i*j]=false;
                }
            }
        }
    }

    /**
     * This method returns if a number is prime or not.
     * It uses the sieve of erastothene method to figure this out.
     * The sieve is declared in the class and initialized on instantiating
     * the class.
     * @param number
     * @return
     */
    public boolean isPrime(int number){
        return sieve[number];
    }
}

/**
 * This class uses standard for looping for finding out the primality of a number.
 */
class PrimeNumberClassic extends PrimeAbstract{

    public PrimeNumberClassic(){
    }

    /**
     * This method returns if a number is prime or not.
     * It uses the classical style of for looping through all the numbers
     * till the sqaure root of the number.
     * @param number
     * @return
     */
    public boolean isPrime(int number) {
        if (number%2==0) return false;
        for(int i=3;i*i<=number;i+=2) {
            if(number%i==0)
                return false;
        }
        return true;
    }

}


texts:
Built my first script and its function is to solve simple derivative questions. How can I improve this code? This is my first time posting.

#This is Simple Derivative Solver
 def derivative():
     print("This program will give you the first derivative.")
     input("Press ENTER to continue...")
     cf=int(input("Enter the coefficient of the term..."))
     exp=int(input("Enter the exponent of the term..."))
     if exp==1 and cf==1:
        print("The answer is", 1)
     elif exp<0 and cf<0:
        print("The answer is:", abs(exp*cf), "x^", (exp-1))
     elif exp>0:
        print("The answer is:", exp*cf, "x^", (exp-1))
     elif exp==0:
        print("The answer is:", 0)
     elif exp<0:
        print("The answer is:", abs(exp*cf), "x^", (exp-1))
     elif cf==0:
        print("The answer is:", 0)
     elif cf<0:
        print("THe answer is:", cf*exp, "x^", (exp-1))
derivative()


texts:
Very simple square root calculator. I am sure it's terrible and can be made much better.
I feel it's way too many lines.
import random

## ask user for a number to find sq root for
num1 = input("Please enter number for which we'll find sq root:\n")

## generate a random number and test it
randomNum1 = random.randint(1,9)
print("Random number is " + str(randomNum1))

ranMul1 = 0

while True:
  if float(ranMul1) == float(num1):
    print("square root of " + str(num1) + " is " + str(randomNum1))
    break
  else:
    randomNum1 = round((float(randomNum1) + (float(num1)/float(randomNum1))) / 2, 4)
    ranMul1 = round(randomNum1 * randomNum1,4)
    print("Trying number " + str(randomNum1))
    continue


texts:
I've been trying my hand at some simple problems on the website topcoder.com. I've been able to solve most of the problems I've tried so far in the Easy/Medium section, but I'm scoring very low. The points are based on running time and the amount of memory used by the program AFAIK.

This is a quick piece of code that I submitted and scored around 75/200, I was just wondering what sort of things I should be avoiding or looking out for in order to write more efficient code?

Quick summary of the problem at hand:

  Start with an array of test scores, calculate average and add new test scores of 10/10 to the array until the average is 9.5 or higher.

public class AimToTen{
    public static int need( int[] marks ){
        double average = 0, total = 0;
        int extras = 0;

        for( int x : marks )
            total += x;

        average = total / marks.length;

        if( average >= 9.5 )
            return 0;

        while( average < 9.5 ){
            extras++;
            total += 10;

            average = total / ( marks.length + extras );
        }

        return extras;
    }
}


texts: How to re-factor a common String comparison

texts:
Code below is scattered all over the code base :

if (StringUtils.contains(manager.getName, "custom")){

}

It just checks if an object attribute contains a predefined String and if it does, enter condition.

Is there a more elegant way of achieving above, perhaps using an enum?


texts: ASP.NET WebAPI `In` Validation Attribute

texts:
I've created custom validation attribute that will be used to validate model. It allows me to specify values that are valid for specific field.
Here is my code:

public sealed class InAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "{1} is invalid value for {0}.";

    private readonly int[] testArray;
    private int _toTest;

    public InAttribute(int[] @in) : base(DefaultErrorMessage)
    {
        if (!@in.Any())
        {
            throw new ArgumentNullException("in");
        }

        testArray = @in;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, _toTest);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            return new ValidationResult("" + validationContext.DisplayName + " cant be null");
        }
        _toTest = Convert.ToInt32(value);
        if (!testArray.Contains(_toTest))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }
}

Then I can use it like so:

public class RequestHelpBindingModel
{
    [Required]
    [In(new []{1,3,4,7},ErrorMessage = "{1} is invalid value.")]
    [Display(Name = "Typ")]
    public int Type { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }
}

I'd like to get review on this.

My questions are:

Is it build right?
If there are places to optimize please let me know.


texts: Write directory new entries to file periodically, keeping the ones that existed in the past

texts:
Some backup Bash script on my machine copies a specific directory entries filenames into a text file. Entries that no longer exist have to be kept (entries added during a previous run).

The script makes sure that entries which still exist will not be inserted twice in the backup file using sort and uniq.

local file=~/bar-entries.txt
touch "$file" "${file}_"
find ~/foo/bar -maxdepth 1 -type d \! -name bar | cat <"$file" - | sort | uniq > "${file}_"
mv "${file}_" "$file"

Can this code be optimized? Like can this scenario be achieved without relying on a temporary file? Any other improvement is welcome.


texts: How to implement a dynamic temperature conversion method based on given enums?

texts:
I am making some basic temperature conversion methods, and I want the end result to look something like this:

double celsius = TemperatureConvert.convert(10, Temperature.FAHRENHEIT, Temperature.CELSIUS);
// Where 'Temperature' is an enum with three values: FAHRENHEIT, CELSIUS, and KELVIN
// This mehtod is read logically as "convert 10 degrees fahrenheit to celsius"

Originally, I thought that the best approach was to have some private methods inside TemperatureConvert to do the conversion for me. I quickly discovered I was wrong. I want to make this method dynamic, so I used my Google Fu and found this answer. If you don't want to read it, the answers basically tell OP about the ability to have an abstract method in the enum class, and then have each enum override it.

I am having some trouble figuring out the best approach. Here are the two possibilities I came up with:

Create two abstract methods, convertA() and convertB(). Have convertA() convert to the unit that is first in alphabetical order, and have convertB() convert the other unit. In the TemperatureConvert.convert() method, I can figure out what method to use by comparing the enum name. This also brings up an issue if the same unit is passed into the convert() method, as there is no method to do any conversion. However, no conversion is needed so that might not be a problem.
Create three abstract methods, convertToCelsius(), convertToFahrenheit(), and convertToKelvin(). Use a switch statement to decide which method to use.


texts:
I have a JavaScript function to categorize data by their "styles" attribute, and store the key-"unicode" pair.

Here's my current code:

function processMetadata(metadata) {
    let regular = {}, solid = {}, brands = {}
    for (let icon in metadata) {
        let styles = metadata[icon].styles
        let codePoint = metadata[icon].unicode
        if (styles.includes('regular')) {
            regular[icon] = codePoint
        }
        if (styles.includes('solid')) {
            solid[icon] = codePoint
        }
        if (styles.includes('brands')) {
            brands[icon] = codePoint
        }
    }
    return {regular, solid, brands}
}

However, CodeClimate keeps complaining about

  Function processMetadata has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.

I want to resolve this issue, but I'm not aware of any way to further reduce the complexity without reducing the performance of this code. The following snippet does reduce the cognitive complexity to under 5 but at the expense of performance (3+3 loops instead of 1) and extra dependency:

function processMetadata(metadata) {
    let regular = _.pickBy(metadata, icon => icon.styles.includes('regular'))
    regular = _.mapValues(regular, icon => icon.unicode)
    let solid = _.pickBy(metadata, icon => icon.styles.includes('solid'))
    solid = _.mapValues(solid, icon => icon.unicode)
    let brands = _.pickBy(metadata, icon => icon.styles.includes('brands'))
    brands = _.mapValues(brands, icon => icon.unicode)
    return {regular, solid, brands}
}

Is there any way I can achieve this without having a significant impact on the performance?


texts:
I am trying to model a domain of metrics for use in a BI application.  I recently read the Designing with Types series, and felt that it could be useful, so I wanted to give it a try.  What I'm not sure is if I'm trying too hard....

The metrics are application-defined, meaning they are finite and won't change during runtime.  A dozen metrics would probably be a lot.
New metrics will be introduced as the application grows
A user will be selecting which metrics they want to use, and the application has to take that and go "do stuff", like building a query to the backend store (MongoDB, in this case).
There may be application logic associated with metrics that I would like enforced through pattern matching so that when I introduce a new metric, I want the compiler to tell me that I need to do some work.

Here's what I have:

type Metrics =
  | Revenue
  | Volume
  | PriceAsp
  with
    member m.FormatGroupings =
      match m with
        | Revenue -> [("revenue", """$sum: { "$Amount" }" """)]
        | Volume  -> [("volume", """$sum: { "$Quantity" }" """)]
        | PriceAsp -> List.append Revenue.FormatGroupings Volume.FormatGroupings

    member m.FormatProjections =
      match m with
        | Revenue -> [("revenue", "$revenue")]
        | Volume -> [("volume", "$volume")]
        | PriceAsp -> [("priceAsp", """ $divide: ["$revenue", "$volume"]  """)]

let buildQuery groupBy (metrics:Metrics list) =
  let concatenate f =
    let x = metrics
            |> List.collect f
            |> List.map (fun m -> sprintf "{%s: %s}" (fst m) (snd m) )
    System.String.Join(",", x)

  let groupings = concatenate (fun m -> m.FormatGroupings)
  let projections = concatenate (fun m -> m.FormatProjections)

  sprintf """{$group: {_id: {%s: "$%s"}}, %s}, $project: {%s}}""" groupBy groupBy groupings projections

With examples of usage:

buildQuery "foo" [Revenue; Volume]  //Simple
buildQuery "foo" [PriceAsp]         //Compound

Note that PriceAsp is "made up of" both Revenue and Volume.

Please provide any general comments.  Some specific questions I have are:

Have the business rules for the metric calculations be embedded within the types
Show that some metrics are built off of other metrics (for example, PriceAsp), and enforce the explicit relationship.  Above, we see that PriceAsp is made up of Revenue and Volume because it's in that list.  But it would be better to make it enforced explicitly through typing.
There are formatting rules around an "instance" of a specific metric.  For example, when Revenue is shown to a user, it should be rounded to the nearest whole dollar, with thousand separators and a currency symbol (ex:  $1,234,567).
Is there an elegant way (using List.fold, perhaps) for doing what String.Join does?  String.Join is just so convenient...

A base metric would look like this (no $project):

{
  $group: {
    _id: {
      foo: "$Foo"
    },
    revenue: { $sum: "$Amount" }
  }
}

A compound metric may look like this:

{
  $group: {
    _id: {
      foo: "$Foo"
    },
    revenue: { $sum: "$Amount" },
    volume: { $sum: "$Quantity" }
  },
  $project: {
    priceAsp: { $divide: ["$revenue", "$volume"] }
  }
}


texts: collecting.py module for working with Tweepy

texts:
I have a module collection.py that functions as a tool to collect tweets using tweepy. It has two classes : Authentication and Collection.

Authentication class will create an object that acts as a starting point to collect data from twitter. An instance of this will the an argument for Collection.

Collection class will create a 'collection' object, it has different methods on how to collect the data, by Collect_object.collect(method = ...), through home_timeline, through Cursor(api.home_timeline, ....), and also through user_timeline.

I would like to know how to design better, and using better techniques. (for functionality, readability, compactness, and becoming a library)

Below are the code and usage example.

collection.py:

import tweepy
from tweepy import OAuthHandler
import numpy
import datetime

class Authentication(object):

    def __init__(self, consumer_key, consumer_secret, access_token, access_secret):

        self.consumer_key = consumer_key
        self.consunmer_secret = consumer_secret
        self.access_token = access_token
        self.access_secret = access_secret

        self.auth = OAuthHandler(consumer_key, consumer_secret)
        self.auth.set_access_token(access_token, access_secret)
        self.api = tweepy.API(self.auth)

class Collection(object):

    def __init__(self, auth_object):

        self.auth_object = auth_object
        self.api = self.auth_object.api
        self.collection = []

    def collect_home(self, method = 'Default', n = 20, **kwargs):

        if method == 'Default':

            public_stats = self.api.home_timeline()

        if method == 'Cursor':

            public_stats = tweepy.Cursor(self.api.home_timeline, **kwargs).items(n)

        self.stats = [stat for stat in public_stats]
        self.collection.extend(self.stats)

        date = datetime.datetime.now()
        time = date.timetuple()
        year = time.tm_year
        month = time.tm_mon
        day = time.tm_mday
        hour = time.tm_hour
        mnt = time.tm_min
        time_string = 'hour_min_{}_{}_date_{}_{}_{}'.format(\
            str(hour), str(mnt), str(day), str(month), str(year))
        self.time_collected = time_string;

        return self.stats, self.time_collected

    def collect_user(self, username, n = 20, **kwargs):

        user_stats = tweepy.Cursor(self.api.user_timeline, \
                                   screen_name = username, **kwargs).items(n)

        self.stats = [stat for stat in user_stats]
        self.collection.extend(self.stats)

        date = datetime.datetime.now()
        time = date.timetuple()
        year = time.tm_year
        month = time.tm_mon
        day = time.tm_mday
        hour = time.tm_hour
        mnt = time.tm_min
        time_string = 'hour_min_{}_{}_date_{}_{}_{}'.format(\
            str(hour), str(mnt), str(day), str(month), str(year))
        self.time_collected = time_string;

        return self.stats, self.time_collected

    def save(self, *args, **kwargs):
        numpy.save(*args, **kwargs)

Usage example :

consumer_key = '...............................'
consumer_secret = '...............................'
access_token = '...............................'
access_secret = '..............................'

Init = Authentication(consumer_key, consumer_secret, access_token, access_secret)
Collect = Collection(Init)

Collect.collect_user('Reuters', n = 50)
Collect.collect_user('anbarief', n = 50)

data = Collect.collection


texts:
We just finished working on a Database project in Java Netbeans. We added the feature Import which will import the database record of one user to a text file.

String IMPORT_QUERY =
    "SELECT pe.entry_id ID, pe.entry_account ACCOUNT, pe.entry_username USERNAME, pe.entry_password PASSWORD, pe.entry_category CATEGORY FROM password_entries pe JOIN accounts a ON a.user_id = pe.user_id WHERE username = ? AND password = ?";
    try {
        PrintWriter writer = new PrintWriter("D:\\Users\\mandu\\Documents\\NetBeansProjects\\PasswordVault\\src\\PasswordList.txt", "UTF-8");
        String location = "C:\\\\Users\\\\mandu\\\\Documents\\\\NetBeansProjects\\\\PasswordVault\\\\src";
        pstmt = conn.prepareStatement(IMPORT_QUERY);
        pstmt.setString(1, LogInFrame.username.getText());
        pstmt.setString(2, LogInFrame.password.getText());
        res = pstmt.executeQuery();
        writer.println("ACCOUNT" + "\t\t|\t" + "USERNAME" + "\t\t\t|\t" + "PASSWORD" + "\t\t\t|\t" + "CATEGORY" + "\t\t|\t\n");
        writer.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
            while(res.next()){
                entryAccount = res.getString("ACCOUNT");
                entryUsername = res.getString("USERNAME");
                entryPassword= res.getString("PASSWORD");
                entryCategory = res.getString("CATEGORY");
                writer.println(entryAccount + "\t\t\t|\t" + entryUsername + "\t\t\t|\t" + entryPassword + "\t\t\t|\t" + entryCategory + "\t\t\t|\t\n");
            }
                writer.println();
                writer.println();
                writer.println("++++++++++++++++++++++WARNING!++++++++++++++++++++++");
                writer.println();
                writer.println("FILE ADDRESS: " + location);
                writer.println();
                writer.println("Please COPY the FILE ADDRESS above and DELETE the 'PasswordList.txt' file AFTER you COPY you RECORDS.");
                writer.println();
                writer.println("TO AVOID SOMEONE FROM COPYING YOUR RECORDS.");
                writer.close();
            JOptionPane.showMessageDialog(null,"\nData Imported!","Prompt:", JOptionPane.INFORMATION_MESSAGE);
            OpenFile();
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null,"\nFile not found. Please check the file location.","Error x203", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        JOptionPane.showMessageDialog(null,"\nUnsupported Encoding. Please check the Target file.","Error x204:", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    } catch(SQLException | HeadlessException ex){
        JOptionPane.showMessageDialog(null,"\nError occured while communicating with the server.","Error x205", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,"\nError occured in getting input.\nPlease try again.\n","Error x206:", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    }

}

Any ideas/opinions about the code, or is there any way to get the columns aside from getString()? Did I violate some rules with regards to error checking?


texts:
I need to process rabbitmq messages with golang with worker style,
is this correct way to process rabbitmq messages with golang?

package main

import (
    "log"
    "github.com/streadway/amqp"
)

func main() {
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    for _, q := range []string{"q1", "q2", "q3"} {
        go RunFetcher(q, conn, 3, 50)

    }

    select {}
}

func RunFetcher(queueName string, conn *amqp.Connection, workers, qos int) {
    ch, err := conn.Channel()
    if err != nil {
        log.Println(err.Error())
        return
    }

    ch.Qos(qos, 0, false)
    defer ch.Close()
    msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
    if err != nil {
        log.Println(err.Error())
        return
    }

    for index := 0; index < workers; index++ {
        go func() {
            for d := range msgs {
                // process message
                d.Ack(false)
            }
        }()
    }

    select {}
}


texts:
This is another pretty basic class I wrote for a library as I hate the way the default StringBuilder in .NET works.

Essentially, I wanted to have the + operator, as well as implicit conversions to strings. (Rather than needing .ToString() all the time.)

It's pretty small and simple, so there may not be a lot to critique.

Also, before you say "just inherit StringBuilder and extend it", it's sealed.

///
/// This wraps the .NET StringBuilder in a slightly more easy-to-use format.
///
public class ExtendedStringBuilder
{
    private StringBuilder _stringBuilder;

    public string CurrentString => _stringBuilder.ToString();

    public int Length => _stringBuilder.Length;

    public ExtendedStringBuilder()
    {
        _stringBuilder = new StringBuilder();
    }

    public ExtendedStringBuilder(int capacity)
    {
        _stringBuilder = new StringBuilder(capacity);
    }

    public ExtendedStringBuilder Append(string s)
    {
        _stringBuilder.Append(s);

        return this;
    }

    public ExtendedStringBuilder Append(char c)
    {
        _stringBuilder.Append(c);

        return this;
    }

    public ExtendedStringBuilder Append(object o)
    {
        _stringBuilder.Append(o);

        return this;
    }

    public static ExtendedStringBuilder operator +(ExtendedStringBuilder sb, string s) => sb.Append(s);

    public static ExtendedStringBuilder operator +(ExtendedStringBuilder sb, char c) => sb.Append(c);

    public static ExtendedStringBuilder operator +(ExtendedStringBuilder sb, object o) => sb.Append(o);

    public static implicit operator string(ExtendedStringBuilder sb) => sb.CurrentString;

    public override string ToString() => CurrentString;

    public string ToString(int startIndex, int length) => _stringBuilder.ToString(startIndex, length);
}

I didn't implement all the overloads of the .Append method (yet) or the + variants of them.

This can literally be used in the exact same manner as the .NET StringBuilder, or you can use += or + instead of .Append, and you can implicitly convert it to a string.


texts:
I have been using SwiftyJSON to create my models of Object in Swift.
But recently, I moved to CoreData for saving the objects locally.
I am new to CoreData and want to know the best practices I should follow for creating the model.

Here's what I have created to update and get User's data (after getting the JSON from webservice)

Core Data Model

import Foundation
import CoreData
import SwiftyJSON

@objc(User)
public class User: NSManagedObject {

var authToken : String!

class func addUser(fromJSON json: JSON?, inManagedObjectContext managedObjectContext: NSManagedObjectContext?) -> User? {

    if var json = json { //unwrapping
        let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext!)
        let newUser = NSManagedObject(entity: entityDescription!, insertInto: managedObjectContext) as! User

        json = json["user"]
        newUser.authToken = json["auth_token"].stringValue
        newUser.email = json["email"].stringValue

        managedObjectContext?.perform({
            _ = try? newUser.managedObjectContext!.save()
        })
        return newUser
    }
    return nil
}

class func getUser(inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> User? {
    // Initialize Fetch Request
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

    // Create Entity Description
    let entityDescription = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext)

    // Configure Fetch Request
    fetchRequest.entity = entityDescription

    if let result = try? managedObjectContext.fetch(fetchRequest) {
        return result.first as? User
    } else {
        return nil
    }
}

class func updateUser(fromJson json : JSON?, inManagedObjectContext managedObjectContext: NSManagedObjectContext) {
    let user = getUser(inManagedObjectContext: managedObjectContext)

    if var json = json {
        json = json["user"]
        user?.name = json["name"].stringValue
        user?.email = json["email"].stringValue
    }

    managedObjectContext.perform({
        _ = try? managedObjectContext.save()
    })
}

}

Here's how I used to create model before I was using Core Data:

Previous Model

import Foundation
import SwiftyJSON

class User : NSObject, NSCoding{

var email : String!
var name : String!

/**
 * Instantiate the instance using the passed json values to set the properties values
 */
init(fromJson json: JSON!){
    if json == nil{
        return
    }
    email = json["email"].stringValue
    name = json["name"].stringValue
}
}

Although the code is working, I am not sure if this is the right way to do it.
How should I actually create the model with CoreData? And how should I call them from ViewControllers? I tried reading tutorials, but they help on getting started but not on how to use them in bigger projects.


texts: Pixel interpolation (binning?) algorithm

texts:
I am trying to write up a pixel interpolation (binning?) algorithm (I want to, for example, take four pixels and take their average and produce that average as a new pixel). I've had success with stride tricks to speed up the "partitioning" process, but the actual calculation is really slow. For a 256x512 16-bit grayscale image I get the averaging code to take 7s on my machine. I have to process from 2k to 20k images depending on the data set. The purpose is to make the image less noisy (I have used median filter and various other in-built filters, but it was suggested that I should try pixel binning also).

import numpy as np
from numpy.lib.stride_tricks import as_strided
from scipy.misc import imread
import matplotlib.pyplot as pl
import time

def sliding_window(arr, footprint):
    """ Construct a sliding window view of the array"""
    t0 = time.time()
    arr = np.asarray(arr)
    footprint = int(footprint)
    if arr.ndim != 2:
        raise ValueError("need 2-D input")
    if not (footprint > 0):
        raise ValueError("need a positive window size")
    shape = (arr.shape[0] - footprint + 1,
             arr.shape[1] - footprint + 1, footprint, footprint)
    if shape[0] <= 0:
        shape = (1, shape[1], arr.shape[0], shape[3])
    if shape[1] <= 0:
        shape = (shape[0], 1, shape[2], arr.shape[1])
    strides = (arr.shape[1]*arr.itemsize, arr.itemsize,
               arr.shape[1]*arr.itemsize, arr.itemsize)

    t1 = time.time()
    total = t1-t0
    print "strides"
    print total

    return as_strided(arr, shape=shape, strides=strides)

def binning(w,footprint):

    #the averaging block
    #prelocate memory
    binned = np.zeros(w.shape[0]*w.shape[1]).reshape(w.shape[0],w.shape[1])
    #print w
    t2 = time.time()
    for i in xrange(w.shape[0]):
        for j in xrange(w.shape[1]):
            binned[i,j] = w[i,j].sum()/(footprint*footprint + 0.0)

    t3 = time.time()
    tot = t3-t2
    print tot

    return binned

Output:
5.60283660889e-05
7.00565886497

Is there some built-in/optimized function that would to the same thing I want, or should I just try and make a C extension (or even something else)?

Here is the additional part of the code just for completeness, since I think the functions are the most important here. Image plotting is slow, but I think there is a way to improve it for example here.

for i in range(2000):
    arr = imread("./png/frame_" + str("%05d" % (i + 1) ) + ".png").astype(np.float64)
    w = sliding_window(arr,footprint)
    binned = binning(w,footprint)
    pl.imshow(binned,interpolation = "nearest")
    pl.gray()
    pl.savefig("binned_" + str(i) + ".png")

What I am looking for could be called interpolation. I just used the term the person who advised me to do this used. Probably that is the reason why I was finding histogram related stuff!

Apart from the median_filter, I tried generic_filter from scipy.ndimage but those did not give me the results I wanted (they had no "valid" mode).