texts: SQL query C++ code (My first C++ application)

texts:
I would really welcome some advice, and notes about my code. I am a long time Python user, and some days ago i decided i should try C++. So a couple of days passed, and i wrote my first application which has a practical use. I still find C++ very complicated (my current perspective is over complicated) but i can clearly say it is faster then my same python implementation.

The code:

/*
 * File:   main.cpp
 * Author: gerdos
 *
 * Created on October 10, 2016, 4:23 PM
 */

#include <string>
#include <iostream>
#include <unistd.h>
#include <list>
#include <vector>
#include <algorithm>

#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/resultset_metadata.h>

using namespace sql;
using namespace std;

int main(int argc, char* argv[]){
    int opt;
    vector<string> column_name_list;

    // Shut GetOpt error messages down (return '?'):
    opterr = 0;

    // Retrieve the options:
    while ( (opt = getopt(argc, argv, "F:")) != -1 ) {  // for each option...
        if (opt == 'F'){
            column_name_list.insert(column_name_list.end(), string(optarg));
        }
    }
    string queries;
    for (unsigned i = 1; i < argc; i++){
        if (string(argv[i]) != "-F" && find(column_name_list.begin(), column_name_list.end(), argv[i]) == column_name_list.end()){
            queries += "'" + string(argv[i]) + "',";
        }
    }

    string columns;
    for (unsigned i = 0; i < column_name_list.size(); i++){
        columns += column_name_list[i] + ",";
    }
    columns.erase(columns.size()-1);
    queries.erase(queries.size()-1);

    try{
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;

        driver = get_driver_instance();

        con = driver->connect("sql_adress", "user", "nope"); // Join a server
        con->setSchema("database_name"); // Use a database

        stmt = con->createStatement();
        res = stmt->executeQuery(string("select " + columns + " from table_name where accession in (" + queries + ")"));

        sql::ResultSetMetaData *res_meta = res -> getMetaData();
        int cols = res_meta -> getColumnCount();
        if (res->rowsCount() == 0){
            cout << "Query not found!" << endl;
            return 0;
        }
        while (res->next()) {
            for (unsigned i = 1; i <= cols; i++){
                cout << res->getString(i) << endl;
            }
        }
        delete res;
        delete stmt;
        delete con;
    }
    // No idea about this part yet, copied it from a tutorial
    catch (sql::SQLException &e){
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }
    return 0;
}


texts: Storing products in MongoDB with support for sorting by their number of followers

texts:
I'm loading products via an infinite scroll in chunks of 12 at a time.

At times, I may want to sort these by how many followers they have.

Below is how I'm tracking how many followers each product has.

Follows are in a separate collection, because of the 16mb data cap, and the amount of follows should be unlimited.

follow schema:

var FollowSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
    },
    product: {
        type: mongoose.Schema.ObjectId,
        ref: 'Product'
    },
    timestamp: {
        type: Date,
        default: Date.now
    }
});

Product that is followed schema:

var ProductSchema = new mongoose.Schema({
    name: {
        type: String,
        unique: true,
        required: true
    },
    followers: {
        type: Number,
        default: 0
    }
});

Whenever a user follows / unfollows a product, I run this function:

ProductSchema.statics.updateFollowers = function (productId, val) {
    return Product
        .findOneAndUpdateAsync({
            _id: productId
        }, {
            $inc: {
                'followers': val
            }
        }, {
            upsert: true,
            'new': true
        })
        .then(function (updatedProduct) {
            return updatedProduct;
        })
        .catch(function (err) {
            console.log('Product follower update err : ', err);
        })
};

My questions about this:

Is there a chance that the incremented "follower" value within product could hit some sort of error, resulting in un matching / inconsistent data?
Would it be better to write an aggregate to count followers for each Product, or would that be too expensive / slow?

Eventually, I'll probably rewrite this in a graphDB, as it seems better suited, but for now — this is an exercise in mastering MongoDB.


texts:
I put together an asynchronous map function for Swift's Array using Grand Central Dispatch. It's called with a transform closure, a dispatch_queue_t (optional), and a completion closure. The transform closure is passed an item from the array and a callback closure which should be called with the result of the transform. When the completion closure is called, it will be passed a new array with the transformed items in the same order as the original array.

Simple example:

Array(1...10).map({
    (num, callback) in
    // Just to show the transform can perform an asynchronous action
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        callback(num * 2)
    }
}) {
    results in
    println(results)
}

Outputs:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

By default, the transform closure is dispatched to the DISPATCH_QUEUE_PRIORITY_LOW global queue for each item, but a different queue can be passed in if need be.

I'm looking for:

A general code review
Anything that could take more advantage of Swift or GCD

extension Array {
    // Convenience function which passes the global DISPATCH_QUEUE_PRIORITY_LOW queue as the transformQueue
    public func map<U>(transform: (T, U -> ()) -> (), withCompletionHandler completionHandler: [U] -> ()) {
        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
        map(transform, onQueue: queue, withCompletionHandler: completionHandler)
    }

    public func map<U>(transform: (T, U -> ()) -> (), onQueue tranformQueue: dispatch_queue_t, withCompletionHandler completionHandler: [U] -> ()) {
        let transformGroup = dispatch_group_create()
        let dataSyncQueue = dispatch_queue_create("array.asyncMap.dataSync", DISPATCH_QUEUE_SERIAL)
        var results: [U?] = [U?](count: count, repeatedValue: nil)

        // Nested function to dispatch the transform; mainly here to capture index from the for loop below
        func performTransform(index: Int) {
            let item = self[index]
            dispatch_group_enter(transformGroup)
            dispatch_async(tranformQueue) {
                transform(item) {
                    result in
                    dispatch_sync(dataSyncQueue) {
                        results[index] = result
                    }
                    dispatch_group_leave(transformGroup)
                }
            }
        }

        for index in (0..<count) {
            performTransform(index)
        }

        dispatch_group_notify(transformGroup, tranformQueue) {
            var unwrappedResults: [U]? = nil

            // This dispatch_sync doesn't seem to be technically needed since all the transforms should have finished at this point
            dispatch_sync(dataSyncQueue) {
                // Force unwrap the values in the results array
                unwrappedResults = results.map({ item in item! })
            }

            completionHandler(unwrappedResults!)
        }
    }
}


texts:
As a beginner in C programming, I decided to write a function words that, given an unsigned integer n, puts the English representation in words of n into the character array dest.

This code is quite difficult to follow due to its complexity. If I hadn't written this code, it would take me a good while to understand it fully. What can I do to improve readability and reduce the unnecessary complexity?

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

const char *digits[] = { "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine " };
const char *tens[] = { "ten ", "twenty ", "thirty ", "forty ", "fifty ", "sixty ", "seventy ", "eighty ", "ninety " };
const char *teens[] = { "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " };
const char *hundreds[] = { "thousand ", "million ", "billion " };

char *strprep(const char *prefix, char *dest)
{
    char *temp = strdup(dest);
    sprintf(dest, "%s%s", prefix, temp);
    free(temp);
    return dest;
}

void words(unsigned int n, char *dest)
{
    unsigned int l, r, m, d = 0, t = 0;
    char d_cpy[16];

    while(n)
    {
        r = n % 10;
        n = (n - r) / 10;
        m = d % 3;

        if(d && !m)
        {
            if(r || n % 100)
            {
                strprep(hundreds[t], dest);
            }

            t++;
        }

        if(r)
        {
            switch(m)
            {
                case 0:
                    if(n % 10 != 1)
                    {
                        strprep(digits[r - 1], dest);
                    }
                    break;
                case 1:
                    if(l && r == 1)
                    {
                        strprep(teens[l - 1], dest);
                    }
                    else
                    {
                        strprep(tens[r - 1], dest);
                    }
                    break;
                case 2:
                    strcpy(d_cpy, digits[r - 1]);
                    strprep(strcat(d_cpy, "hundred "), dest);
            }
        }

        l = r;
        d++;
    }

    if(!strlen(dest))
    {
        strcpy(dest, "zero");
    }
}

To provide some context, words() is called in main() (defined in the same file):

#include <limits.h>

int main(int argc, char *argv[])
{
    char *last;
    unsigned long int n;

    if(argc != 2)
    {
        puts("incorrect number of arguments!");
        printf("usage: %s [integer]\n", argv[0]);
        return -1;
    }

    n = strtoul(argv[1], &last, 10);

    if(*last || !(*argv[1]) || n > UINT_MAX)
    {
        puts("first argument must be a valid integer");
        return -1;
    }

    char buf[256];
    puts(words((unsigned int)n, buf));
}


texts:
I have an algorithm that is painfully slow if I use 'pure' mutexes. That's because most of the critical sections are short and far shorter than the work to sleep a thread. However, it is also slower to allow the occasional long critical section cause long spins in other thread(s). This class is intended to provide a balance. The balance here is compile-time fixed. What would be interesting is an adaptive strategy for tuning the spin time.

#include <atomic>
#include <condition_variable>
#include <mutex>
///A hybrid lock making a number of spin attempts
///and then entering a wait before retrying.
///<remarks>Implemented to be interface swappable
///with std::mutex.</remarks>
template<unsigned SPIN_LIMIT>
class hybrid_lock {
public:
    typedef unsigned spin_count_type;
    typedef void *native_handle_type;

    inline void lock() {
        spin_count_type limit(0);
        for (;;) {
            if (!this->mFlag.test_and_set(std::memory_order::memory_order_acquire)) {
                return;
            }
            if (limit >= SPIN_LIMIT) {
                break;
            }
            ++limit;
        }
        std::unique_lock<std::mutex> guard(this->mMutex);
        this->mCondition.wait(guard, [this]() {
            return !this>mFlag.test_and_set(
               std::memory_order::memory_order_acquire
            );
        });
    }

    inline bool try_lock() {
        return !this->mFlag.test_and_set(
            std::memory_order::memory_order_acquire
        );
    }

    inline void unlock() {
        this->mFlag.clear(std::memory_order::memory_order_release);
        this->mCondition.notify_one();
    }

    ///Returns the address of the flag backing the lock.
    ///<remarks>The return value may not be compatible with
    ///std::mutex.</remarks>
    ///<returns>The address of the flag
    ///backing the spin-lock.</returns>
    inline native_handle_type native_handle() {
        return static_cast<native_handle_type>(&this->mFlag);
    }

    inline hybrid_lock(void) {
        mFlag.clear();
    }
private:
    std::atomic_flag mFlag;//The actual lock object.
    std::mutex mMutex;//Used to synchronize sleeping threads.
    std::condition_variable mCondition;

    hybrid_lock(const hybrid_lock&) = delete;
    hybrid_lock& operator=(const hybrid_lock&) = delete;
};


texts:
I've been teaching myself Python over the last few weeks, I have an interest in cryptography, codes, etc. so I figured starting a Morse code translator  would be a good project. I know my variable names could be different, it's not really encrypting, decrypting, etc. I'm mostly looking for advice on how I can make the code cleaner and where I can be more efficient.
I think my biggest problem is not really knowing how to handle the inputs in a while loop like I usually would. The problem I had was that I couldn't check if the input was 'e' or 'd' so it just got really wonky.
Areas I know I could improve:

Add input loop
The if, elif, else for the action
Make 'sound' an actual boolean value
Find the actual sound time for the dit and dah but that's not really a code issue

# Started: 08/17/2020
# Finished: 08/17/2020
# Takes an input message and outputs the message in morse code
# Keys taken from 'https://en.wikipedia.org/wiki/Morse_code'

from playsound import playsound
import time

# Dictionary that holds each letter and it's corresponding value
dict = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--',
        'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..',
        '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
        ' ': '/', '.': '.-.-.-', ',': '.-.-', '?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.', '(': '-.--.', ')': '-.--.-',
        ':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.', '$': '...-..-', '@': '.--.-.'}

outputMessage = ""               # Holds our output message

# Sounds
sound = 'False'
dit = 'dit.wav'
dah = 'dah.wav'

def Encrypt(message):

    output = ''

    for char in message:
        if char in dict:
            output = output + dict[char]
            output = output + ' '

    return output

def Get_Key(val):
    for key, value in dict.items():
        if val == value:
            return key

def Decrypt(message):

    output = ''

    letters = message.split(' ')

    for letter in letters:
        temp = Get_Key(letter)
        output = output + temp

    return output

def Get_Inputs():
    # Get Inputs
    inputString = input('Enter a message to start.\n')
    action = input('(E)ncrypt or (D)ecrypt?\n')

    # Format Inputs
    message = inputString.lower().strip()
    action = action.lower().strip()

    return message, action

def Play_Sound(message):

    for char in message:
        if char == '.':
            playsound(dit)
        elif char == '-':
            playsound(dah)
        elif char == ' ':
            time.sleep(0.15)
        elif char == '/':
            time.sleep(0.30)

message, action = Get_Inputs()

if action == 'e' or action == 'encrypt':
    outputMessage = Encrypt(message)
elif action == 'd' or action == 'decrypt':
    outputMessage = Decrypt(message)
else:
    print('Error!')

print(outputMessage)

print('')
sound = input('Play sound? (T)rue / (F)alse\n')
if sound.lower().strip() == 't' or sound.lower().strip() == 'true':
    Play_Sound(outputMessage)


texts:
I'm using Express 4 to provide routes to HTML/Jade files, and as well to provide an API.

I want to separate routes from server file, and go even further- separate API from WWW. My code now looks like this:

server.js

//================== ROUTES ======================================

require('./routes/api')(app, express);  //all api routes go in ./routes/api.js file
require('./routes/web')(app, express);  //all website routes go in ./routes/web.js file

apiroutes:

//================================== routes for API ====================================
module.exports = function(app, express) {
    'use strict';
    var api = express.Router();

    api.get('/somget', function(req, res) {
        res.send('some json');
    });

    // init api route. all api routes will begin with /api
    app.use('/api', api);

}

pages routes (both main template and partials):

//================================== routes for index and partials================================

module.exports = function(app, express) {
    'use strict';
    var router = express.Router();

    router.get('/', function(req, res) {
        res.render('index');
    });

    router.get('/partials/:name', function (req, res) {
        var name = req.params.name;
        res.render('partials/' + name);
    });

    //apply router
    app.use('/', router);

};

Is it okay to pass both app and express?

It works, but I'm not sure if such solution may have some bad impact on app and routing -passing both app and express to two functions.


texts: SQL Stored Procedure Get Distinct and Update

texts:
The idea is to show how many times a user (by EmployeeID) is in the TblTableList and then update the TblTableStatusCount

I have been learning Fetch this week so wanted to ensure I have gone down the right path and this is a small database, can/should I use this for any size?

Code:

USE [database]
        GO

        SET ANSI_NULLS ON
        GO
        SET QUOTED_IDENTIFIER ON
        GO
        Alter PROCEDURE [dbo].[spSummary]
            -- Add the parameters for the stored procedure here

        AS

        BEGIN

        DECLARE @StatusTotal AS Int
        DECLARE @Status0 AS Int
        DECLARE @Status1 AS Int
        DECLARE @Status2 AS Int
        DECLARE @Status3 AS Int

        --Cursor to loop through
        DECLARE @EmployeeID  AS NvarChar(10);
        DECLARE propCurs CURSOR FOR
        SELECT  EmployeeID FROM [TblTableList]

        --Open Loop Code
        OPEN propCurs;
        FETCH NEXT FROM propCurs INTO @EmployeeID
        WHILE @@FETCH_STATUS = 0
        --Now do repeated code

          BEGIN

         --   SELECT @StatusTotal = COUNT(ID) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID
            --SELECT @Status0 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '0'
            --SELECT @Status1 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '1'
            --SELECT @Status2 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '2'
            --SELECT @Status3 =  COUNT(DISTINCT(ID)) FROM [TblTableCountFrom] WHERE EmployeeID = @EmployeeID AND CurrentAlertStatus = '3'

        with cnt as (
           SELECT
             1 as cntAll
             , case WHEN CurrentAlertStatus = '0' then 1 else 0  end as cnt1
             , case WHEN CurrentAlertStatus = '1' then 1 else 0  end as cnt2
             , case WHEN CurrentAlertStatus = '2' then 1 else 0  end as cnt3
              , case WHEN CurrentAlertStatus = '3' then 1 else 0  end as cnt4
           from [TblTableCountFrom] where EmployeeID = @EmployeeID
        )
        SELECT @StatusTotal = sum(cntAll),
          @Status0  = sum(cnt1),
          @Status1  = sum(cnt2),
          @Status2  = sum(cnt3),
          @Status3  = sum(cnt4)
          FROM cnt;
            -- Check if ID Exists

            --HERE NEED TO CHECK IF EXISTS OR SHOULD I WIPE THE TABLE AT THE START?
            IF EXISTS (SELECT EmployeeID FROM [TblTableCount] WHERE @EmployeeID = EmployeeID)

                UPDATE [TblTableCountFrom]Count
                SET StatusTotalCount = @StatusTotal, Status0 = @Status0, Status1 = @Status1, Status2 = @Status2, Status3 = @Status3
                WHERE EmployeeID = @EmployeeID
              Else
                INSERT INTO [TblTableCount]
                (EmployeeID, StatusTotalCount, Status0, Status1 , Status2, Status3) VALUES (@EmployeeID, @StatusTotal,@Status0, @Status1, @Status2,@Status3 )

            END

            -- Now we bookend the loop code

            FETCH NEXT FROM propCurs INTO @EmployeeID

        END

        --Tidy up and close loop code
        CLOSE propCurs;
        DEALLOCATE propCurs;


texts: Elastic Beanstalk configuration using ebextensions container_commands combining leader_only and test

texts:
For our Django app running on AWS Elastic Beanstalk, we use a web-server/worker setup. The same code is deployed to the web-server and worker environments, and environment-specific configuration is achieved with .ebextensions config files, using the test option for container_commands, among other things.

Now there are some container commands we would like to execute only during deployment or environment-creation (so we use leader_only: true, see bottom), but, in addition, they should never be executed on the worker environment.

The latter could be achieved using the test option, but that cannot be used not in combination with leader_only, according to the docs:

  ... A command can be leader-only or have a test, but not both (leader_only takes precedence).

Now, to work around this, we do something like the following, in .ebextensions/foo.config:

option_settings:
  aws:elasticbeanstalk:application:environment:
    ENV_NAME: '`{ "Ref" : "AWSEBEnvironmentName" }`'  # get the current environment name

container_commands:
  0100_set_flag_if_instance_is_leader:
    command: touch /tmp/is_leader  # create empty file
    leader_only: true
  0200_execute_command_on_leader_only_but_never_on_worker:
    command: foo bar
    test: '[[ $ENV_NAME != "worker" && -e /tmp/is_leader ]]'

where ENV_NAME contains the environment name, which is automatically retrieved with the help of option_settings (see docs).

Note that the config file is in YAML format and the commands and tests execute in a shell (I assume bash, since the extended test construct [[ works, but could not find any specifics in the AWS docs).

As I am not an expert, I would really appreciate your comments on the following points:

The solution above works, but is this the simplest way to do it?
Are there any compelling reasons not to use this kind of set-up?
I tried setting a variable instead of creating a file (in command 0100), but the variable does not appear to persist between container commands. Is there some way to achieve this? (I tried to export, but that didn't help. Is each container command executed in a separate shell, or how does this work?)

Some general background from the AWS docs:

  You can use leader_only to only run the command on a single instance, or configure a test to only run the command when a test command evaluates to true. Leader-only container commands are only executed during environment creation and deployments, while other commands and server customization operations are performed every time an instance is provisioned or updated. Leader-only container commands are not executed due to launch configuration changes, such as a change in the AMI Id or instance type.


texts: Verifying requirements before deleting a user-parent-student-school relationship

texts:
I am new to node, after I finished my APIs I realized that all of them are a mess, and are a callback hell, this forced me to learn about promises, now it was all good until I faced an API that has condition with more than possible function, my question is how to do nested promises, my code is about a parent object who has a user attached to it, when delete route is called there are many conditions:

If this parent has children attached to it it shouldn't be deleted
If there are no children,

This parent is in more than one school, the school_id is removed from the school id of the parent object and the user object attached to it
If this parent has no children and only one school_id it should be removed and the user attached also should be removed

The code looks like this and it's 100% functional. I am trying to apply promises and make my code better.

router.post('/delete',Validation, function (req, res) {
var school_id = req.body.schoolId;
var parent_id = req.body.selected[0];

Student.findOne({parent_ids:parent_id},function(err,parentF){
    if(err){
        console.log(err);
        res.json({status:"error",message:"an error occurred"});
        return
    }else if(parentF){
        res.json({status:"error", message:"you can not delete a parent who has students associated with it"});
        return;
    }else{
        Parent.findOne({_id:parent_id},function(err,parent){
            if(err){
                console.log(err);
                res.json({status:"error",message:"an error occurred"});
                return;
            }else{
                if(parent.school_id.length>1){
                    var a = parent.school_id.indexOf(school_id);
                    parent.school_id.pop(a);
                    parent.save(function(err,parent){
                        if(err){
                            console.log(err);
                            res.json({status:"error",message:"an error occurred"});
                            return;
                        }else{
                            User.findOne({refid:parent_id},function(err,user){
                                if(err){
                                    console.log(err);
                                    res.json({status:"error",message:"an error occurred"});
                                    return;
                                }else {
                                    user.school_id.pop(a);
                                    user.save(function(err) {
                                        if(err){
                                            console.log(err);
                                            res.json({status:"error",message:"an error occurred"});
                                            return;
                                        }else{
                                            res.json({status: "success", message: "parent removed"});
                                            return;
                                        }
                                    });
                                }
                            });
                        }
                    });
                }else{
                    Parent.remove({_id: parent_id}, function (err) {
                        if (err) {
                            res.json({status: "error", message: err.message});
                        } else {
                            User.remove({refid:parent_id},function(err){
                                if (err) {
                                    res.json({status: "error", message: "parent user wasn't deleted"});
                                    return;
                                }else{
                                    res.json({status: "success", message: "parent data successfully deleted"});
                                    return;
                                }
                            });

                        }
                    });
                }
            }
        });
    }
});
   });


texts: Pickling cars with simple management system in Python

texts:
This is my first Python program (before that I've been just poking around with the interpreter itself). I took this opportunity to do some user input and play around with pickle.

I tried to made a system that reads input from the user (a car's name, year of launch and price), and then gives the power of exporting or importing it to an external file.

Is there any way to make this looks better (something that bothered me was my printing function and my super simple regex)? Is there any way that I can make this more pythonic? I've read many articles with this "pythonic" idea, and as I'm moving from Java, I'm afraid I might be losing something.

Made with python 3 in mind.

Example of input is:

  add

  Mitsubishi Eclipse

  1999

  1300.00

Here is the code.

import re
import pickle

class Car():
    def __init__(self, carName = None, year = None, cost = None):
        self.carName = carName if carName is not None else "undefined"
        self.year = year if year is not None else "undefined"
        self.cost = cost if cost is not None else "undefined"

cars = []
canImport = True #can only import if has already exported before or at program start

def addNewCar():
    """ Reads input from user and adds a new car to the current collection of cars.
        Year/Cost numeric validation are deliberately ommited """

    usr_input = input("Enter the car's name : (protip: if can enter the whole object by typing name/year/cost)\n-> ")
    match = re.search(r"\w+/\w+/\w+", usr_input)
    if match:
        name, year, cost = splitCarAttributes(match)
    else:
        name = usr_input
        year, cost = getCarAttributes()
    cars.append(Car(name, year, cost))

def splitCarAttributes(attributes):
    return attributes.group(0).split("/")

def getCarAttributes():
    year = input("Enter the car's launching year:\n-> ")
    cost = input("Enter the car's cost:\n-> ")
    return year, cost

def printCars():
    for i, car in enumerate(cars):
        print("Car #{:d}\n{{\n\tname:{:s}\n\tyear:{:s}\n\tcost:{:s}\n}}\n---\n".format(i+1, car.carName, car.year, car.cost))

def importCars():
    if not canImport
        print("You don't have anything to import.\n\n")
        return

    fileObject = open('cars', 'rb')
    importedCars = pickle.load(fileObject)
    for car in importedCars:
        cars.append(car)
    canImport = False
    printSuccess()

def exportCars():
    fileObject = open('cars', 'wb')
    pickle.dump(cars, fileObject)
    cars = [] # clears cars
    canImport = True
    printSuccess()

def printSuccess():
    print("\n\n--- Great success!\n\n")

def main():
    opt = ""
    while (opt != "exit" and opt != "q"):
        opt = input("Would you like to:\n- import all data\n- export all data\n- print all cars\n- add a new car to the collection?\n-> ").lower()
        if opt == "import":
            importCars()
        elif opt == "export":
            exportCars()
        elif opt == "add":
            addNewCar()
            printSuccess()
        elif opt == "print":
            printCars()

if __name__ == '__main__':
    main()

Edit: I just realized I'm calling printSuccess() in different contexts. Not gonna change the code now, just a heads up to clarify that I should move all to main() and maybe do some exception handling, but that's no the point right now.


texts:
I am trying to create an evaluator in Kotlin for the Mastermind game which compares two strings and tells how many letters and letters on the right position they share.

I was hoping to get some comments on how I can improve the code below in any way. Many thanks in advance!

fun String.masterCompare(otherString:String): Pair<Int, Int>? {

    // If the two strings are not equal in size, return null
    if (length != otherString.length)
        return null

    var letters : Int = 0  // The number of letters the two strings have in common
    var positions: Int = 0 // The number of shared letters that are in the same index
    var other = otherString // A mutable string copy of the argument string

    // Get number of shared indexes (positions)
    for ((index, c) in withIndex()){
        if (c == otherString[index]) {
            positions++
        }
    }

    // Check if a char in this string exists in the other. If so, increment letters and delete the char from the other string (so that it's not rechecked)
    for (c in toList()){
        if (other.contains(c)){
            letters++
            other = other.replace(c.toString(), "")
        }
    }

    return letters to positions
}

fun main(args: Array<String>) {
    println("ABCD".masterCompare("AFCH"))    // 2,2
    println("AAAA".masterCompare("AFCH"))    // 1,1
    println("ABCD".masterCompare("ABCD"))    // 4,4
    println("ABCD".masterCompare("DCBA"))    // 4,0
    println("ABCDP".masterCompare("DCBA"))   // null
}


texts:
I have written this sample code to fetch a web page in C++ using libcurl. Please review it.

#include <iostream>
#include <iostream>
#include <string>
#include <exception>

extern "C"
{
#include <curl/curl.h>
#include <stdlib.h>
}

//Exception class for curl exception

class CurlException : std::exception
{
public:
   CurlException(std::string message):m_message(message) {  }
   CurlException(CURLcode error)
   {
      m_message = curl_easy_strerror(error);
   }
   const char* what() throw()
   {
      return m_message.c_str();
   }
   ~CurlException() throw() { }

private:
   std::string m_message;
};

//A tiny wrapper around Curl C Library

class CppCurl
{
public:
   CppCurl(std::string url) throw (CurlException)
   {
      m_handle = curl_easy_init();
      if ( m_handle == NULL )
         throw CurlException("Unable to initialize curl handler");
      if ( url.length() == 0 )
         throw CurlException("URL can't be of zero length");
      m_url = url;
   }

   std::string Fetch() throw (CurlException)
   {
      SetOptions();
      SendGetRequest();
      return m_data;
   }

   ~CppCurl() throw()
   {
      curl_easy_cleanup(m_handle);
   }

private:

   void SetOptions() throw (CurlException)
   {
      CURLcode res;

      //set the url
      res = curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
      if ( res != CURLE_OK)
         throw CurlException(res);

      //progress bar is not require
      res = curl_easy_setopt(m_handle, CURLOPT_NOPROGRESS, 1L);
      if ( res != CURLE_OK )
         throw CurlException(res);

      //set the callback function
      res = curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION,
                              CppCurl::WriteDataCallback);
      if ( res != CURLE_OK )
         throw CurlException(res);

      //set pointer in call back function
      res = curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, this);
      if ( res != CURLE_OK )
         throw CurlException(res);

   }

   void SendGetRequest()
   {
      CURLcode res;
      res = curl_easy_perform(m_handle);
      if ( res != CURLE_OK )
         throw CurlException(res);
   }

   static size_t WriteDataCallback(void *ptr, size_t size,
                                    size_t nmemb, void* pInstance)
   {
      return (static_cast<CppCurl*>(pInstance))->write_data(ptr, size, nmemb);
   }

   size_t write_data(void* ptr, size_t size, size_t nmemb)
   {
      size_t numOfBytes = size * nmemb;

      char *iter = (char*)ptr;
      char *iterEnd = iter + numOfBytes;

      //while ( iter != iterEnd )
      //{
      //   cout<<*iter;
      //   iter ++;
      //}

      m_data += std::string(iter, iterEnd);

      return numOfBytes;
   }

   CURL *m_handle;
   std::string m_url;
   std::string m_data;

};

int main()
{
   try
   {
      CppCurl ob("http://kodeyard.blogspot.in/");
      std::cout<<ob.Fetch();
      std::cout<<std::endl;
   }
   catch ( CurlException e)
   {
      std::cerr<<"Exception thrown..."<<std::endl;
      std::cerr<<e.what()<<std::endl;
   }

   return 0;

}

This is also here in the blog.


texts: Function to censor single word in a sentence

texts:
The following function censors a single word of choice in a sentence with asterisks, regardless of how many times the word appears. How can I further simplify this code?

def censor(text,word):
  text_list = text.split()
  for i in range(0,len(text_list)):
    if text_list[i] == word:
      text_list[i] = '*' * len(text_list[i])
    else:
      continue
  return" ".join(text_list)


texts: Bringing content from other pages without refreshing the entire page

texts:
I wrote my first AJAX script that brings content from other pages without refreshing the entire page.  I just want to see if improvements can be added to it, or if I'm doing something not recommended.

$(function(){
    // content container content loader
    $("#nav-tabs-list a").click(function() {
        var page = this.hash.substr(1);
        //$("#sidebar-content-container").html(""); // displays content only after fully loaded
        $.get("content/" + page + ".php", function(gotHtml) {
            $("#content-container").html(gotHtml);
        });
    });
    if ( location.hash ) {
        $("a[href="+location.hash+"]").click();
    } else {
        $("#nav-tabs-list a").click();
    }

    // sidebar content loader
    $("#sidebar-container #sidebar-tabs-container a").click(function() {
        var page = this.hash.substr(1);
        //$("#sidebar-content-container").html(""); // displays content only after fully loaded
        $.get("content/sidebar-content/" + page + ".php", function(gotHtml) {
            $("#sidebar-content-container").html(gotHtml);
        });
    });
    if ( location.hash ) {
        $("a[href="+location.hash+"]").click();
    } else {
        $("#sidebar-container #sidebar-tabs-container a").click();
    }
});


texts: Merge sort implementation weirdly faster than system sort

texts:
I wrote the following functions to merge sort an array of Comparables. It seems to work well (I am testing the output to make sure it is sorted). It takes about 2.5 sec for 10 million randomly generated strings. However, when I use the system sort by calling Arrays.sort(), it takes about 18 seconds. Why this huge discrepancy?

private static void merge(Comparable[] a, Comparable[] aux, int low, int mid, int high) {
    int i = low;
    int j = mid;
    for (int k = low; k <= high; k++) {
        aux[k] = a[i];
    }
    for (int k = low; k <= high; k++) {
        if (i < mid) {
            if (j > high) {
                a[k] = aux[i++];
            } else {
                if (aux[i].compareTo(aux[j]) <= 0) {
                    a[k] = aux[i++];
                } else if (aux[i].compareTo(aux[j]) > 0) {
                    a[k] = aux[j++];
                }
            }
        } else {
            a[k] = aux[j++];
        }
    }
}

private static void mergesort(Comparable[] a, Comparable[] aux, int start, int end) {
    int N = end - start + 1;
    if (N < 2) return;
    int lo = start;
    int mid = start + N/2;
    int hi = end;
    mergesort(a, aux, lo, mid-1);
    mergesort(a, aux, mid, hi);

    merge(a, aux, lo, mid, hi);
}

private static void msort(Comparable[] a) {
    int N = a.length;
    if (N < 2) return;
    Comparable[] aux = new Comparable[N];
    //System.arraycopy(a, 0, aux, 0, N);
    mergesort(a, aux, 0, N - 1);
}

private static boolean isSorted(Comparable[] a) {
    int N = a.length;
    if (N < 2) return true;
    for (int i = 1; i < N; i++) {
        if (a[i-1].compareTo(a[i]) > 0) {
            return false;
        }
    }
    return true;
}

private static String createRandString(int lo, int hi) {
    int len = myrandgen.uniform(lo, hi+1);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        char ch = (char) myrandgen.uniform(97, 123);
        sb.append(ch);
    }
    return sb.toString();
}

private static void sortTester(int inputSize) {
    String[] s = new String[inputSize];
    for (int i = 0; i < inputSize; i++) {
        String t = createRandString(5,15);
        s[i] = t;
    }
    long start = System.currentTimeMillis();
    //Arrays.sort(s);
    msort(s);
    long end = System.currentTimeMillis();

    if (isSorted(s)) {
        System.out.println("Good Sort.");
        System.out.printf("Time taken: %d for %d elements.\n", end - start, inputSize);
    } else {
        System.out.println("Bad Sort.");
    }
}
/**
 * Unit tests merge sort.
 */
public static void main(String[] args) {
    sortTester(10000000);
}


texts:
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.

  Not all numbers produce palindromes so quickly. For example,

349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337

  That is, 349 took three iterations to arrive at a palindrome.

  Although no one has proved it yet, it is thought that some numbers,
  like 196, never produce a palindrome. A number that never forms a
  palindrome through the reverse and add process is called a Lychrel
  number. Due to the theoretical nature of these numbers, and for the
  purpose of this problem, we shall assume that a number is Lychrel
  until proven otherwise. In addition you are given that for every
  number below ten-thousand, it will either (i) become a palindrome in
  less than fifty iterations, or, (ii) no one, with all the computing
  power that exists, has managed so far to map it to a palindrome. In
  fact, 10677 is the first number to be shown to require over fifty
  iterations before producing a palindrome: 4668731596684224866951378664
  (53 iterations, 28-digits).

  Surprisingly, there are palindromic numbers that are themselves
  Lychrel numbers; the first example is 4994.

  How many Lychrel numbers are there below ten-thousand?

This is my solution:

from datetime import datetime

candidates = []

def reverse(number):
    ''' Returns the reverse order of an integer,
        for example: reverse(123) returns the integer 321 '''
    number = str(number)
    return int(number[::-1])

def is_lychrel(number):
    ''' Returns True if 'number' is a lychrel candidate,
        but works only with numbers from 1 to 10000 '''
    iterated = number + reverse(number)
    for i in range(25):
        rev_iterated = reverse(iterated)
        if iterated != rev_iterated:
            iterated = iterated + rev_iterated
        else:
            return False
    return True

if __name__ == '__main__':

    start_time = datetime.now()

    for number in range(10001):
        if is_lychrel(number):
            candidates.append(number)

    time = datetime.now() - start_time # To get the time of the calculation

    print('In {} were found {} lychrel candidates'.format(time, len(candidates)))
    print(' '.join(map(str, candidates)), 'are candidates.')
    suml = input('Press ENTER to close ')

On my PC (with Intel Atom 2GHz), I got it with .4 seconds.  Could you offer suggestions on making it run faster?


texts:
I have a stateful object on which I'd like client code to be able to register many event handlers. These handlers have different signatures—they usually accept the originating object and some piece of data relevant to the event.

public class StatefulObject {
  @FunctionalInterface
  private interface Callback {
    void call(Object... args);
  }

  private enum Event {PLACEMENT, FILL, CANCEL, ERROR /* etc... */}
  private final Map<Event, List<Callback>> callbacks = new HashMap<>();

  public StatefulObject onPlacement(Consumer<StatefulObject> placementCallback) {
    callbacksFor(Event.PLACEMENT).add(args -> placementCallback.accept((StatefulObject) args[0]));
    return this;
  }

  public StatefulObject onError(BiConsumer<StatefulObject, Exception> errorCallback) {
    callbacksFor(Event.ERROR).add(args -> errorCallback.accept((StatefulObject) args[0], (Exception) args[1]));
    return this;
  }

  // ... etc

  private List<Callback> callbacksFor(Event event) {
    List<Callback> callbacksList = callbacks.getOrDefault(event, new ArrayList<>());
    callbacks.put(Event.ERROR, callbacksList);
    return callbacksList;
  }
}

My idea here is that (i) I shouldn't have many Lists/Arrays of callbacks and (ii) I shouldn't have unchecked casts. Instead of declaring a Map<Event, Object> and then casting the returned Object to List<BiConsumer<StatefulObject, Exception>>, for example, I thought it would be better to have a generic Callback and then cast the individual arguments.

Is this pattern reasonable, or is it unclear? Access is obviously restricted to just this class.

Thanks for your opinions!


texts:
I have a piece of code that does what I need. But it looks complicated and messy for what it does. Is there a simpler way to look up the member CIN unqiuely without having a create a sub-query?

Get the unique items from DATA (often it has hundreds of duplicate ID), but each ID has their own service date. Sometimes a ID has 20-30 service date in the input.
Lookup their member ID from a different table
Sometimes there are 2-3 member ID for each Personal ID
Join it back together with original

I am using SAS Enterprise Guide 6.1, thanks!

/* Look up the member ID using Personal ID*/
PROC SQL;
CREATE TABLE WORK.MemberID AS
SELECT c.PersonalID,
    c.SBSID,
    c.SITEID,
    d.DateOfService FORMAT=MMDDYY10.,
    INTNX('month', d.DateOfService, 0, 'END') AS EndOfMonth FORMAT=MMDDYY10.,
    d.RateCode,
    d.TCN,
    d.ClaimAmount FORMAT=DOLLAR10.2
/* Get every Membmer ID associated with the Personal Number*/
FROM SASUSER.DATA d
    RIGHT JOIN (
    /*****************************************************/
    /* Subquery 2: to Match the PersonalID with MemberID */
        SELECT PersonalID,
            MEMBERID AS SBSID,
            SITEID
        FROM DW_SOME_TABLE b INNER JOIN (
        /****************************************************/
        /* Subquery 1: Select only the distinct Personal ID */
            SELECT DISTINCT PersonalID
            FROM SASUSER.DATA
            WHERE PersonalID is not null
        ) a
        /* End of Subquery 1*/
        /****************************************************/
        ON (a.PersonalID = b.CINNUMBER)
        WHERE (b.SITEID = '0001')
    ) c ON (c.PersonalID = d.PersonalID)
    /* End of Subquery 2*/
    /*****************************************************/
ORDER BY c.PersonalID;
QUIT;


texts: Find a list of Windows Services by given criteria

texts:
My goal is to implement a method, which finds a list of Windows Services that match given set of criteria:

SearchString: A search string
SearchServiceBy: Could be ServiceName or DisplayName
SearchOption: Could be Equals, Contains, StartsWith, EndsWith or Regex
SearchServiceType: Could be SingleService or GroupOfServices

private List<ServiceController> GetServices()
{
    var allServices = ServiceController.GetServices().ToList();
    var resultList = new List<ServiceController>();

    switch (SearchOption)
    {
        case SearchOption.Equals:
            if (SearchServiceBy == SearchServiceBy.ServiceName)
            {
                resultList = allServices.Where(s => s.ServiceName.Equals(SearchString)).ToList();
            }
            else if (SearchServiceBy == SearchServiceBy.DisplayName)
            {
                resultList = allServices.Where(s => s.DisplayName.Equals(SearchString)).ToList();
            }
            break;

        case SearchOption.Contains:
            if (SearchServiceBy == SearchServiceBy.ServiceName)
            {
                resultList = allServices.Where(s => s.ServiceName.Contains(SearchString)).ToList();
            }
            else if (SearchServiceBy == SearchServiceBy.DisplayName)
            {
                resultList = allServices.Where(s => s.DisplayName.Contains(SearchString)).ToList();
            }
            break;

        case SearchOption.StartsWith:
            if (SearchServiceBy == SearchServiceBy.ServiceName)
            {
                resultList = allServices.Where(s => s.ServiceName.StartsWith(SearchString)).ToList();
            }
            else if (SearchServiceBy == SearchServiceBy.DisplayName)
            {
                resultList = allServices.Where(s => s.DisplayName.StartsWith(SearchString)).ToList();
            }
            break;

        case SearchOption.EndsWith:
            if (SearchServiceBy == SearchServiceBy.ServiceName)
            {
                resultList = allServices.Where(s => s.ServiceName.EndsWith(SearchString)).ToList();
            }
            else if (SearchServiceBy == SearchServiceBy.DisplayName)
            {
                resultList = allServices.Where(s => s.DisplayName.EndsWith(SearchString)).ToList();
            }
            break;

        case SearchOption.Regex:
            var pattern = new Regex(SearchString);

            if (SearchServiceBy == SearchServiceBy.ServiceName)
            {
                resultList = allServices.Where(s => pattern.IsMatch(s.ServiceName)).ToList();
            }
            else if (SearchServiceBy == SearchServiceBy.DisplayName)
            {
                resultList = allServices.Where(s => pattern.IsMatch(s.DisplayName)).ToList();
            }
            break;

        default:
            throw new ArgumentException("Unknown SearchOption: {0}", SearchOption.ToString());
    }

    if (SearchServiceType == SearchServiceType.SingleService
        &&
        resultList.Count > 1)
    {
        resultList = new List<ServiceController> { resultList.FirstOrDefault() };
    }

    return resultList;
}

Is there any better way to implement this?

There is no additional complex logic around the method invoke. The use case is simple: Wix Toolset Custom Action passes required parameters to the method, gets a list of services match the given criteria. So these services could be started/stopped further.


texts: Logic for an init function in email parser

texts:
I am writing an email parser and cannot decide how much logic should be included in the __init__ function. I know that a constructor should make the object ready for use, but are there best practices?

I've added several statements to my constructor:

def __init__(self, message):
    assert isinstance(message, basestring)

    parsed_message = email.message_from_string(message)

    if self._is_email(parsed_message):
        self.email_obj = parsed_message
        email_payload = parsed_message.get_payload()
        self.valid_urls = self._find_valid_urls(email_payload)
        # ... some other stuff like looking for keywords etc.

What do you consider the most pythonic way:

Should I create a simple email object which possesses several methods that extract and return keywords, included URLs etc?
Do you consider it better to process all this information in the __init__ method and putting all results in object variables?


texts: Count how many times a value is greater than or equal to the median of previous D elements

texts:
I am self-studying algorithms and data structures. So, bear with me if the code I've written isn't stellar or interpretation is accurate.

Essentially, the problem (which I took from HackerRank) requires counting the number of times an element in an array is greater than or equal to two times the median of the subarray containing the past D elements.

For instance, suppose you have an array of [2,3,4,2,3,6,8,4,5]. And, the window is D = 5.

Starting value to compare against the median of the subarray is 6. So, you
look at the median of the subarray, [2,3,4,2,3], which is 3. Then, you multiply the median by 2, which is 6, and since the 2 x median value satisfies the condition, you would increment a counter by 1. You continue this procedure all the way to the last element of the array.

So, here's the code I have written thus far:

import sys

def activityNotifications(expenditure, d):
    """ Worst-case: O( n^2 * logn ) """
    num_of_trans = len(expenditure) - 1
    count = 0
    for i in range(d,num_of_trans):
        prev_trans = sorted(expenditure[i-d:i])
        if d % 2 == 0:
            left_i = (d - 1) // 2
            right_i = left_i + 1
            median = prev_trans[left_i] + prev_trans[right_i]
        else:
            median = prev_trans[d - 1]
        if expenditure[i] >= median:
            count += 1
    return count

if __name__ == "__main__":

    expenditures = [[2,3,4,2,3,6,8,4,5],[1,2,3,4,4]]
    d = 4

    for record in expenditures:
        result = activityNotifications(record, d)
        print(result)

The approach works, but I am afraid that the code is poorly optimized. If my understanding of asymptotic complexity of this algorithm is correct, I believe it's \$O(n ^ 2 * log(n))\$. Is there any way I can reduce the complexity down to \$O(n)\$ or even better \$O(log(n))\$?

** Update (01/11/18) **

Based on Austin Hasting's suggestion, I revised my code to utilize bisect functions to avoid sorting at every new window. Essentially, the first window is sorted. Then, after the median of the sorted array is computed, bisect finds the position of the leftmost element of the window in the sorted array. Based on the position, the element within the sorted array is deleted. Finally, the next element is added onto the sorted array using bisect once again. Based on the procedure I have outlined, here's my new code:

def median(a, d):
    if (d % 2) != 0:
        return a[d // 2]
    else:
        half = d // 2
        return (a[half] + a[half - 1]) / 2

def activityNotifications_bisect(expenditure, d):
    """ Worst-case: O( n ) """

    frauds = 0
    window = sorted(expenditure[:d])
    for p, i in enumerate(expenditure[d:]):
        if i >= median(window, d) * 2:
            frauds += 1
        del window[bisect_left(window, expenditure[p])]
        insort_left(window, i)
    return frauds

Theoretically speaking, the code appears to be an improvement. However, when I tested the performance of my old code versus the new using timeit with 1 million executions, I was surprised to see that the old code completing at 5.35 seconds beats the new one by 2.1 seconds. I am perplexed about what's preventing my new code from performing better than the old one. Any additional tips would be incredibly helpful!


texts: Lower the volume of my computer over time in Python

texts:
I wrote a program to gradually lower the volume of my computer when I go to sleep so I can fall asleep with TV or music on.  This was my first time using argparse and I feel like there should be a cleaner way to deal with default values of optional arguments.  Any other feedback of course also welcomed.

import vol
from time import sleep
from subprocess import call, check_output
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--delay", help="time (in minutes) until volume begins to lower", type=int)
parser.add_argument("-m", "--minutes_until_mute", help="time (in minutes) to set the volume to mute", type=int)
a = parser.parse_args()
minutes_until_mute = a.minutes_until_mute if a.minutes_until_mute else 30
delay = a.delay if a.delay else 0
sleep(delay*60)
current_volume = check_output(['osascript', '-e', 'set ovol to output volume of (get volume settings)'])

for i in range(minutes_until_mute):
    percent_of_volume = (-1.0/(minutes_until_mute**2))*(i**2) + 1 #quadratic function with maximum at (0, 100%) and crossing at (minutes_until_mute, 0)
    new_volume = int(float(current_volume) * percent_of_volume)
    call(["vol", "out", str(new_volume)])
    call(["vol", "info"])
    sleep(60)

call(["vol", "mute"]) #rounding errors mean we don't get exactly to 0


texts:
My application is a bit slow. I believe this is because .clearRect is one of the more intensive events in my application so far. However I also draw an image on top of the screen (as background) at the top of each loop, like this:

function redraw(){
  ctx.save();
  ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
  ctx.drawImage(background,0,0,canvas.clientWidth,canvas.clientHeight);

  var i=0,l=objects.length;
  while(i<l){
    objects[i].redraw();
    i++
  }
  ctx.restore();
}

I'd like to improve the speed of this code. Would removing the .clearRect call be a good way to optimize performance? Or will this clog up memory?


texts: Web scraping news articles with Beautiful Soup

texts:
It's been nearly a year I've been working with C++ and now I am diving in Python and its libraries and frameworks. I am currently creating a website for my portfolio that gathers news articles from a wide range of news websites. I am using Django framework for web development and the Beautiful Soup library for web scraping.

This is currently my Django views.py file, where all the web scraping happens:

from django.shortcuts import render

import urllib.request
from bs4 import BeautifulSoup
import re

# More websites will be added below.
URLS = ["https://www.theguardian.com/uk/rss", "http://rss.cnn.com/rss/edition.rss"];

class Brick:
    """
    Class to represent each article in a news website. 1 brick = 1 news article.
    """
    def __init__(self, title="Untitled", link="#", description="No description",
                 img_url="#", creator="No creator", date="No Date"):
        self.title = title;
        self.link = link;
        self.description = description;
        self.img_url = img_url;
        self.creator = creator;
        self.date = date;

def strip_html(raw_html):
    """
    Strips any HTML tags within a string.
    (I know that this is not safe, but I would like to practice regular expressions).
    """
    pattern = re.compile(r"<.*?>");
    return pattern.sub("", raw_html);

def shorten(cleaned_html):
    """
    If the description of an article is too long, let's cut it
    to only 50 characters.
    """
    new_string = "";

    index = 0;
    for c in cleaned_html:
        if index < 100:
            new_string += cleaned_html[index];

        index += 1;

    new_string += "...";
    return new_string;

# Create your views here.
def news_list(request):
    """
    View that will redirect to the home template that shows the full list
    of articles.
    """

    unformatted_xmls = [];

    formatted_xmls = [];

    group_of_items = [];

    for URL in URLS:
        with urllib.request.urlopen(URL) as file_object:
            unformatted_xmls.append(file_object.read());

    for unf_xml in unformatted_xmls:
        formatted_xmls.append(BeautifulSoup(unf_xml, "xml"));

    for form_xml in formatted_xmls:
        group_of_items.append(form_xml.find_all("item"));

    bricks = [];

    for item_group in group_of_items:
        for item in item_group:
            b = Brick();
            b.title = item.find("title").get_text();
            b.link = item.find("link").get_text();
            b.description = shorten(strip_html(item.find("description").get_text())) if item.find("description") is not None else "No description.";
            b.img_url = item.find("media:content").get("url") if item.find("media:content") is not None else "No media.";
            b.creator = item.find("dc:creator").get_text() if item.find("dc:creator") is not None else "No creator.";
            b.date = item.find("dc:date").get_text() if item.find("dc:date") is not None else "No date.";
            bricks.append(b);

    return render(request, "news/list.html", {"bricks": bricks});

As I am new to web scraping and web development in general, would you mind giving me your tips and opinions about this code? Would you recommend any good practices? Are these libraries and frameworks strongly recommended for this purpose?


texts: Dynamic memory management for a class hierarchy of geometric shapes

texts:
The task was to write function that compare areas of two random generated geometric shapes (circle, square, rectangle) using base class with virtual function.

Am I doing it right in terms of memory management?
Will my figures generated inside generateRandomShape() by new Square() etc. last in memory outside this function untill I manually delete them?

#include <iostream>
#include <cstdlib>
#include <ctime>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>

#define M_PI       3.14159265358979323846

class Shape {
public:
    virtual float area() = 0;
};

class Square : public Shape {
protected:
    float sideA;

public:
    Square(float sideA) : sideA(sideA) {}
    float area() { return sideA * sideA; }
};

class Circle : public Shape {
protected:
    float radius;

public:
    Circle(float radius) : radius(radius) {}
    float area() { return M_PI * radius * radius; }
};

class Rectangle : public Shape {
protected:
    float sideA, sideB;

public:
    Rectangle(float sideA, float sideB) : sideA(sideA), sideB(sideB) {}
    float area() { return sideA * sideB; }
};

void compareAreasOffigures(Shape* a, Shape* b){
    if (a->area() == b->area()) {
        std::cout << "Areas of two shapes are equal." << std::endl;
    }
    else if (a->area() > b->area()) {
        std::cout << "Area of first Shape is bigger." << std::endl;
    }
    else {
        std::cout << "Area of second Shape is bigger." << std::endl;
    }
}

Shape * generateRandomShape() {
    int Shape;
    Shape = rand() % 3;

    switch (Shape)  {

        case 0: {
            int sideA = rand() % 100;
            std::cout << "Square was generated, side: " << sideA << std::endl;
            return new Square(sideA);
            break;
        }

        case 1: {
            int sideA = rand() % 100;
            int sideB = rand() % 100;
            std::cout << "Rectangle was generated, side A: " << sideA << " side B: " << sideB << std::endl;
            return new Rectangle(sideA, sideB);
            break;
        }
        case 2: {
            float radius = rand() % 100;
            std::cout << "Circle was generated, radius: " << radius << std::endl;
            return new Circle(radius);
            break;
        }
        default: return NULL;
    }
}

int main(void){

    srand(time(0));

    std::vector<Shape*> shapes;

    shapes.push_back(generateRandomShape());
    shapes.push_back(generateRandomShape());

    compareAreasOffigures(shapes[0], shapes[1]);

    for (auto v : shapes) { delete v; } //cleanup
    shapes.clear();

    return EXIT_SUCCESS;
}


texts: Encrypt data before sending it to server in a way that makes it unreadable to anyone except the user who sent it

texts:
I don't have any experience in cryptography and I've written some crypto code that seem to be working, but I'm not sure if it safe and if the tools and methods I used are right.

Objective

Make it possible to store data (JSON) on remote server without this server being able to read it in plaintext.

My Approach

Upon registration, don't send the real user password to the server, use Argon2 hash of the real password instead. In my understanding, it should be pretty hard for a server to infer the real password based on Argon2 hash and without salt.
Use sha256(email + password) to create deterministic salt. It allows users to log in from other devices and still pass password validation. In my understanding, deterministic salt doesn't make the resulting "API password" weaker.
Using the password and salt, create an "API password" (Argon2(password, salt))
Use API password to sign up. Server would only know the derived password and not the original one (entered and known by the user).
Create another Argon2 hash and use it as a key to AES-encrypt the JSON payload (AES-256/CBC/Pkcs).
Attach IV and random salt to encrypted payload. All of that is necessary to decrypt the payload later.
Push the resulting data to back end server.

Code

use argon2::{self, Config};
use sha2::{Digest, Sha256};

use crypto::{ symmetriccipher, buffer, aes, blockmodes };
use crypto::buffer::{ ReadBuffer, WriteBuffer, BufferResult };

use rand::{ Rng };

fn main() {
    // Step 1: Generating "password" that will be used for API sign up
    let email = "foo@bar.com";
    println!("Email: {}", email);
    let password = "foobar";
    // Never leaves client
    println!("Password: {}", password);
    let mut sha_hasher = Sha256::new();
    sha_hasher.input(format!("{}{}", email, password));
    let salt = sha_hasher.result();
    let argon_config = Config::default();
    let password_hash = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
    println!("Password hash (full): {}", password_hash);
    let password_hash_parts: Vec<&str> = password_hash.split("$").collect();
    let password_hash = password_hash_parts[5];
    // will be used for API sign up
    println!("Password hash (short): {}", password_hash);

    // Step 2: Encrypting some JSON client side
    let payload = "[{ name: \"Secret Name\" }]";
    println!("Original payload: {}", payload);
    let encrypted_payload = encrypt_payload(&payload, &password);
    let decrypted_payload = decrypt_payload(encrypted_payload, &password);
    println!("Decrypted payload: {}", decrypted_payload);

    // Step 3: Pushing encrypted payload to server
    // (omitted, out of scope of review)
}

fn encrypt_payload(payload: &str, password: &str) -> Vec<u8> {
    let salt = rand::thread_rng().gen::<[u8; 16]>();
    let argon_config = Config::default();
    let key = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
    let iv = rand::thread_rng().gen::<[u8; 16]>();
    let encrypted_bytes = encrypt(payload.as_bytes(), key.as_bytes(), &iv).ok().unwrap();
    let encrypted_bytes : Vec<u8> = salt.iter().chain(&iv).chain(&encrypted_bytes).cloned().collect();
    encrypted_bytes
}

fn decrypt_payload(encrypted_payload: Vec<u8>, password: &str) -> String {
    let salt = &encrypted_payload[0..16];
    let iv = &encrypted_payload[16..32];
    let encrypted_message = &encrypted_payload[32..];
    let argon_config = Config::default();
    let key = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
    let decrypted_message = decrypt(&encrypted_message[..], key.as_bytes(), &iv).ok().unwrap();
    String::from_utf8(decrypted_message).unwrap()
}

Full code (Rust crate)

Here is the full code with encrypt/decrypt boilerplate based on this example:

crypto.tar.gz


texts:
I'm trying to write a simplistic Monte Carlo simulator to predict asset prices. For example, if something has an initial value of 50 and an historic daily standard deviation of 2, what are the odds it will be 40, 40-50, 50-60 or greater than 60 in 25 days?

import random

start = 50
sd = 2
days = 25
bins = [40,50,60]

iterations = 1000
results = [0] * (len(bins) + 1)

GAUSS = True # distribution can be gaussian or lognormal

for _ in range(iterations):
    mc = start
    for _ in range(days):
        if GAUSS:
            mc += random.gauss(0, sd)
        else:
            if random.randint(0,1):
                mc += random.lognormvariate(0, sd)
            else:
                mc -= random.lognormvariate(0, sd)
        if mc <= 0: # prices can't go below 0
            mc = 0

    for n, bin in enumerate(bins): # bin the iteration
        if mc < bin:
            results[n] += 1
            break
    else:
        results[-1] += 1

final = [100 * r / float(iterations) for r in results]
print(final)


texts:
I use the following method to scan and index video files and pass data to an array. I get video file duration, file name, files size.
Is there any better method, or do I need to improve?
public static void load_Directory_Files(File directory) {
    File[] fileList = directory.listFiles();
    if(fileList != null && fileList.length > 0){
        for (int i=0; i<fileList.length; i++){
            if(fileList[i].isDirectory()){
                load_Directory_Files(fileList[i]);
            } else {
                String name = fileList[i].getName().toLowerCase();
                for (String extension: Constant.videoExtensions){
                    //check the type of file
                    if(name.endsWith(extension)){
                        Constant.allMediaList.add(fileList[i]);
                        String FileName = fileList[i].getName();
                        String size = Function.humanReadableByteCountSI(fileList[i].length());
                        String duration = Function.getDurationFF(fileList[i].getAbsolutePath());
                        String folderName = fileList[i].getParentFile().getName();
                        String path = fileList[i].getAbsolutePath();
                        Log.d(TAG, "load_Directory_Files: "+ duration + "" +size + "" + FileName);
                        Constant.allMediaListWithModel.add(new AllVideoModel(FileName, path, folderName, size, duration));
                        //when we found file
                        break;
                    }
                }
            }
        }
    }
}

public static String getDurationFF(String absolutePathThumb) {
    try{
        FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
        retriever.setDataSource(absolutePathThumb);
        String time = retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
        long timeInMillisec = Long.parseLong(time);
        return convertMillieToHMmSs(timeInMillisec);
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}

@SuppressLint("DefaultLocale")
public static String convertMillieToHMmSs(long millie) {
    long seconds = (millie / 1000);
    long second = seconds % 60;
    long minute = (seconds / 60) % 60;
    long hour = (seconds / (60 * 60)) % 24;
    if (hour > 0) {
        return String.format("%02d:%02d:%02d", hour, minute, second);
    } else {
        return String.format("%02d:%02d" , minute, second);
    }
}

@SuppressLint("DefaultLocale")
public static String humanReadableByteCountSI(long bytes) {
    if (-1000 < bytes && bytes < 1000) {
        return bytes + " B";
    }
    CharacterIterator ci = new StringCharacterIterator("kMGTPE");
    while (bytes <= -999_950 || bytes >= 999_950) {
        bytes /= 1000;
        ci.next();
    }
    return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}

The above method works but it takes time to scan and index. So how can I reduce indexing time?
public static String[] videoExtensions = {".mp4",".ts",".mkv",".mov",
        ".3gp",".mv2",".m4v",".webm",".mpeg1",".mpeg2",".mts",".ogm",
        ".bup", ".dv",".flv",".m1v",".m2ts",".mpeg4",".vlc",".3g2",
        ".avi",".mpeg",".mpg",".wmv",".asf"};


texts: Dynamic programming with Project Euler #18

texts:
I just wanted to get an opinion on my dynamic-programming Haskell implementation of the solution to Project Euler problem 18.

The Problem:

  By starting at the top of the triangle below and moving to adjacent
  numbers on the row below, the maximum total from top to bottom is 23.

  $$\begin{array}{ccc}
  &   &   & \color{red}{3} \\
  &   & \color{red}{7} &   & 4 \\
  & 2 &   & \color{red}{4} &   & 6 \\
8 &   & 5 &   & \color{red}{9} &   & 3 \\
\end{array}$$

  That is, 3 + 7 + 4 + 9 = 23.

  Find the maximum total from top to bottom of the triangle below:

                            75
                          95  64
                        17  47  82
                      18  35  87  10
                    20  04  82  47  65
                  19  01  23  75  03  34
                88  02  77  73  07  63  67
              99  65  04  28  06  16  70  92
            41  41  26  56  83  40  80  70  33
          41  48  72  33  47  32  37  16  94  29
        53  71  44  65  25  43  91  52  97  51  14
      70  11  33  28  77  73  17  78  39  68  17  57
    91  71  52  38  17  14  91  43  58  50  27  29  48
  63  66  04  68  89  53  67  30  73  16  69  87  40  31
04  62  98  27  23  09  70  98  73  93  38  53  60  04  23

  NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67 is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method!

My code:

--Find the maximum total from top to bottom of the triangle below
import Data.Array
import System.Environment (getArgs)
import Control.Applicative ((<$>))

main :: IO()
main = do
  path <- head <$> getArgs
  triangle <- read_triangle path
  putStrLn $ show $ max_path triangle (tri_size triangle) 1

tri_size :: Array Int (Array Int Int) -> Int
tri_size triangle = case bounds triangle of
  (s, f) -> (f - s) + 1

--the triangle in this case is a 2d array
--(similar to how pascal's triangle is mathematically described)
--read the tree
read_triangle :: FilePath -> IO (Array Int (Array Int Int))
read_triangle fp = (tri . reverse . lines) <$> readFile fp
  where
    tri lines = listArray (1, length lines) (map row lines)
    row line = listArray (1, length $ nums line) (nums line)
    nums = map (read :: String -> Int) . words

--OPT(r,i) = v_ri + max(OPT(r-1,i), OPT(r-1,i+1))
--OPT(N,i) = v_ri
max_path :: Array Int (Array Int Int) -> Int -> Int -> Int
max_path triangle row index = (opt!row)!index
  where opt = listArray (1,row) $ (triangle!1 : map f [2..row])
    f r = listArray (1,rsize r) $ map (g r) [1..(rsize r)]
    g r i = triangle!r!i + max (opt!(r-1)!i) (opt!(r-1)!(i+1))
    rsize r = tsize - r + 1
    tsize = tri_size triangle

Where can I cut down on repetition/is there anything I could include to make this more concise/readable? Does anything I do show a general misunderstanding of stuff like monads or Haskell's laziness?


texts:
I want to make my API unavailable to every client who doesn't have the token to access. This means the Android app will send a client as Android and token as token string in the header with keys client and token.

Now in middleware, I am checking it with my table fields to pass through authorization. If both match, then I will authorize and if don't then it will send a 403 response.

I am aware of Passport but it is not what I am looking for. In fact, consider it as a first layer of security and then use Passport as a second layer of security to authorize the API.

Is this code correct?

As I am not so familiar with Laravel - Middleware I just want to get some feedback from experts whether the code I have written is accurate and up to the standard. If not, I would appreciate your suggestion and help to make it better.

Middleware

namespace App\Http\Middleware;

use App\ApiToken;
use Closure;
use function response;

class ApiAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle( $request, Closure $next ) {

        if ( $this->checkToken( $request ) ) {
            return $next( $request );
        }

        return response()->json( [ 'error' => 'Unauthorized' ], 403 );

    }

    public function checkToken( $request ) {

        $client = $request->header( 'client' );
        $token  = $request->header( 'token' );

        $checkToken = ApiToken::where( 'client', $client )
                              ->where( 'token', $token )->first();

        return $checkToken;
    }
}

API Route

I am fetching results from the ApiToken table just to check:

Route::get('/', function(Request $request) {
    return ApiToken::all();
})->middleware('apiAccess');

Optimized with Muhammad Nauman's answer here

public function checkToken( $request ) {

    $client = $request->header( 'client' );
    $token  = $request->header( 'token' );

    return ApiToken::where( 'client', $client )
                          ->where( 'token', $token )->exists();
// Nicer, and it will return true and false based on the existence of the token and client.
}


texts: Checking if an element sastifying a condition in a list comes before another of a different condition

texts:
This is for Java 6 and uses Guava.

It's a little ugly and I'm worried I missed some obvious way to do it a lot better.

If there is more than one element satisfying either condition I am saying it's false because the condition I am checking should be unique among the list.
If and only if the one element satisfying condition1 is in the list with a lower index than the one element satisfying condition2 should this return true.

condition1 and condition2 will never both be true for the same element.

private static <T> boolean isItemWithConditionBeforeAnother(Predicate<T> condition1, Predicate<T> condition2, List<T> list)
{
    if (Collections2.filter(list, condition1).size() != 1 || Collections2.filter(list, condition2).size() != 1)
    {
        return false;
    }
    boolean found1 = false;
    for (T t: list)
    {
        if (!found1)
        {
            if (condition1.apply(t))
            {
                found1 = true;
            }
            else if (condition2.apply(t))
            {
                return false;
            }
        }
        else
        {
            if (condition2.apply(t))
            {
                return true;
            }
        }
    }
    return false;
}


texts: Procedural function for prepared MySQL statements in PHP

texts:
I'm refactoring procedural code, switching to prepared MySQL statements using mysqli_query(). I do understand writing OO would be better, but it's out of scope for this task.

Use the below function as follows:

list($result, $numrows, $err) = my_mysqli_stmt($db_handler, $query, $params);

Returns array with three values, $result, $numrows and $err.

$result is either false on error, or contains empty or multi-dimensional array.

$numrows returns number of affacted rows, number of returned rows or 0 on error.

$err returns mysqli_error() or mysqli_stmt_error() error.

function my_dbstmt($handler, $query, $params=array())
    {
    $stmt = mysqli_prepare($handler, $query);

    if($stmt===false)
        {
        return array(false, 0, mysqli_error($handler));
        }

    //First two parameter of mysqli_stmt_bind_param
    $refarg = array($stmt, array2typestring($params));

    //create array of parameters' references
    foreach ($params as $key => $value)
        {
        $refarg[] = &$params[$key];
        }

    if(!empty($params))
        {
        //bind parameters with dynamic length
        call_user_func_array("mysqli_stmt_bind_param", $refarg);
        }

    $exec = mysqli_stmt_execute($stmt);

    if($exec===false)
        {
        return array(false, 0, mysqli_stmt_error($stmt));
        }

    $result = mysqli_stmt_get_result($stmt);

    if($result===false)
        {
        //not a result, but successfully executed
        $numrows = mysqli_stmt_affected_rows($stmt);
        return array(true, $numrows, null);
        }
    else
        {
        mysqli_stmt_store_result($stmt);

        $data = array();

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
            $data[] = $row;
            }

        $numrows = count($data);
        return array($data, $numrows, null);
        }
    }

For completeness (detail of above referenced function:

function array2typestring($array)
    {
    $types = array();

    foreach ($array as $key => $value)
        {
        $types[] = 's';
        }

    $types = implode('', $types);
    return $types;
    }

Example usage:

$db_handler = mysqli_connect("p:$dblocal", $dbuser, $dbpass) or die();
$query = "SELECT title FROM books WHERE id=?";
$params = array($bookid);
list($result, $numrows, $err) = my_dbstmt($db_handler, $query, $params);

Result:

$result holds multi-dimensional array with books' title (just one in this case). $numrows is 1. $err is null.

Catching errors would work as follows:

if($result===false) {print("Error finding book")}
elseif($numrows==0) {print("Book not found")}
elseif($numrows>0) {print("Book found")}


texts:
I'm experimenting with text editing with fabricjs objects and have the following code that works but that I'd like reviewed. My writing feels really clunky to me for some reason and as I'm new to handlers I'm sure what to change if anything?

function addHandler(id, fn, eventName) {
  document.getElementById(id)[eventName || 'onclick'] = function() {
    var el = this;
    if (obj = canvas.getActiveObject()) {
      fn.call(el, obj);
      canvas.renderAll();
    }
  };
}

function setStyle(object, styleName, value) {
  if (object.setSelectionStyles && object.isEditing) {
    var style = { };
    style[styleName] = value;
    object.setSelectionStyles(style);
  }
  else {
    object[styleName] = value;
  }
}

function getStyle(object, styleName) {
  return (object.getSelectionStyles && object.isEditing)
    ? object.getSelectionStyles()[styleName]
    : object[styleName];
}

// underline
addHandler('underline', function(obj) {
  var isUnderline = (getStyle(obj, 'textDecoration') || '').indexOf('underline') > -1;
  setStyle(obj, 'textDecoration', isUnderline ? '' : 'underline');
});

// bold
addHandler('bold', function(obj) {
  var isBold = (getStyle(obj, 'fontWeight') || '').indexOf('bold') > -1;
  setStyle(obj, 'fontWeight', isBold ? '' : 'bold');
});

// italic
addHandler('italic', function(obj) {
  var isItalic = (getStyle(obj, 'fontStyle') || '').indexOf('italic') > -1;
  setStyle(obj, 'fontStyle', isItalic ? '' : 'italic');
});


texts:
I have a small "plugin system" (I'm not sure this is the right name). It allow you to store objects (plugins), and then call some methods from each of them. With this approach we have absolutely no overhead on iterating/object pass/callback call.

// Need this SET, because in C++11 auto can only be static const.
// And we may need to change them later.
#ifndef SET
    #define SET(NAME, VALUE) decltype(VALUE) NAME = VALUE
#endif

Plugin1 plugin1(param1, param2);
Plugin2 plugin2(param1, param2);
Plugin3 plugin3(param1, param2);

SET(plugins, std::forward_as_tuple(           // Pay attention here. We store &&, not objects
    plugin1,
    plugin2,
    plugin3
));

Then, when I need to call some function from each of plugins, or do something with each of them, I iterate through plugins at compile time (I check this with generated asm code, and it just calls or even inline do_it, without anything else) and call the callback function (I'm not showing iterate code here; it's trivial):

struct Call{
    float k=0;

    template<typename T, int Index>        // lambda function not efficient than this. Tested -O2 clang, gcc 4.8
    inline void do_it(T &&t){
        std::cout << "value = " <<t << " ; " << "id = " << Index << std::endl;
    }
};

And if I need to do something with a specific plugin, I just directly use plugin1, plugin2, and plugin3. No need to call std::get<>. Plus the IDE highlights available plugins when you type them.

Is it ok to store rvalue references on objects, or I have to store objects directly in my tuple?

Like this:

SET(plugins, std::tuple(
    Plugin1(param1, param2),
    Plugin2(param1, param2),
    Plugin3(param1, param2)
));

When I iterate, I pass a plugin as a usual reference:

struct Call{
    float k=0;

    template<typename T, int Index>        // lambda function not efficient than this. Tested -O2 clang, gcc 4.8
    inline void do_it(T &t){
        std::cout << "value = " <<t << " ; " << "id = " << Index << std::endl;
    }
};

With this approach we have additional move constructor calls for each element in the tuple. The previous version is free.

I ask about this because I previously read about data locality and now I worry about how data are placed in memory.


texts:
Given 2 lists of tuples limits and speeds, both have the format of [(speed1, time1), (speed2, time2)]. My goal is to write a function to check whether the there is a period of time that the speed exceeds the limit (Return True if exceeds).
For example, Given limits = [(50,100), (30, 20)], speeds = [(30, 80), (10, 30), (40, 10)], return True.

The example inputs imply that during the first 100 miles, the speed limit is 50. In the 101-120 mile, speed limit is 30. Since in the speeds list, the last 10 miles have speed 40 > 30, so we return True.

We can assume the inputs are valid, so the limits and speeds list always start and end at the same time.

Can I have some pointers on the correctness and how the code can be refactored?

def speed_check(limits, speeds):
  i, j = 0, 0
  prev_limit_range, prev_speed_range = 0, 0
  while j < len(speeds) and i < len(limits):
    if limits[i][0] < speeds[j][0]:
      return True
    if limits[i][1] + prev_limit_range < speeds[j][1] + prev_speed_range:
      prev_limit_range += limits[i][1]
      i += 1
    elif limits[i][1] + prev_limit_range > speeds[j][1] + prev_speed_range:
      prev_speed_range += speeds[j][1]
      j += 1
    else:
      prev_limit_range += limits[i][1]
      prev_speed_range += speeds[j][1]
      i += 1
      j += 1

  return False

assert speed([(30, 15), (55, 20)], [(30, 15), (55, 20)]) == False
assert speed([(30, 15), (55, 20)], [(30, 14), (65, 20)]) == True


texts: Best way to optimize multiple search on Lists java

texts:
Anyone could help me to optimize this block of code, I already did a bit improvement but since I'm really bad with this kind of algorithms this all I've done so far. Much appreciate if you can explain the improvement.

This basically fill a bus (k is the number of seats on the bus) if all seats are filled save the last index of the person who gets into the bus.

p is a list of persons waiting the bus (each person has patience limit) q is a list of time the bus will take to arrive.

Example;

k=2
p={1,4,2,5}
q={1,4}

On the first time bus will arrive in time 1 so person 1 and 2 will fill the bus and index of person will be saved in a list (r={2}).

On the second time bus will arribe in time 4, person 1 and 3 leave person 2 and 4 fill the bus (r={2,4}).

If the bus can't be filled then the number saved in the list is 0.

public static List<Integer> busFilled(int k, List<Integer> p, List<Integer> q) {

    List<Integer> busSeats = new ArrayList<>();

    // Sort the times of bus arrival
    Collections.sort(q);

    // Loop each bus arrival
    for(int time : q) {
        // If person patience < time set the patience to 0
        for (int i=0; i<p.size()-1; i++) {
            if (p.get(i) < time) {
                p.set(i, 0);
            }
        }

        int aux = 0;
        // Loop each person patience
        for (int i=0; i<=p.size()-1; i++) {
            // If person patience > 0 count
            if ( p.get(i) > 0) {
                aux++;
            }

            // If aux = bus seats add the last number(index) of person who filled the bus
            if (aux == k) {
                busSeats.add(i+1);
                break;
            // If i == total persons in queue set 0
            } else if (i==p.size()-1){
                busSeats.add(0);
            }
        }
    }
    return busSeats;
}


texts:
I implemented a binary search algorithm using recursion in Java
package com.soloworld.binarysearch;

/**
 *
 * @author soloworld
 */
public class BinarySearch {

   private int[] array;

    public BinarySearch(int[] array) {
        this.array = array;
    }

    public int recursivesearch(int[] array,int startindex,int endindex,int key) {
        if(endindex>0) {
            int middle =(startindex+ endindex)/2;
            System.out.println("middle "+middle);
            if(array[middle]== key) return middle;
            else if (key <array[middle]) {
                return recursivesearch(array, startindex, middle-1, key);
            } else if(key > array[middle]) {

               return recursivesearch(array, middle+1, endindex, key);
            }
        }
        return -1;
    }

}

it worked, all i want to know is have  i done it in correct way or there any way to optimize this


texts: Bash script that counts the characters, frequency, and percentage of letters in Spanish sonnets

texts:
This script will be used to analyze a lot of old Spanish sonnets. I have tested it thoroughly and all seems to be working perfectly. However, I want to make sure I am not missing some detail because I certainly want accurate results. For the math part it does not round up if the last decimal place is above five. I asked the person I am writing it for, and he said that did not matter for his purposes.

My operating system is Debian 9. I am glad to receive any feedback or comments.

Usage:

script sonnet.txt

Sample text:

  Sancho Panza es aquéste, en cuerpo chico, pero grande en valor,
  ¡milagro extraño! Escudero el más simple y sin engaño que
  tuvo el mundo, os juro y certifico.

Output:

Carácteres          Frecuencia          Porcentaje
i                   6                   04.87%
e                   17                  13.82%
a                   10                  08.13%
o                   14                  11.38%
u                   7                   05.69%

b                   0                   0
c                   7                   05.69%
d                   3                   02.43%
f                   1                   00.81%
g                   3                   02.43%
h                   2                   01.62%
j                   1                   00.81%
k                   0                   0
l                   5                   04.06%
m                   4                   03.25%
n                   8                   06.50%
p                   4                   03.25%
q                   2                   01.62%
r                   9                   07.31%
s                   8                   06.50%
t                   4                   03.25%
v                   2                   01.62%
w                   0                   0
x                   1                   00.81%
y                   2                   01.62%
z                   1                   00.81%
ñ                   2                   01.62%
Carácteres: 27  Total: 123  Total: 100%

Script:

#!/bin/bash

# Check for argument.
if [ -z "$1" ]; then
    echo "Script needs an argument."
    exit 1
fi

# Create output file name.
fname=${1%.*}.tsv

# Clear if output file already exists.
echo -n > "$fname"

# Get all alpha characters and cut new line characters.
chars=$(grep -io '[a-z]' "$1" | tr -d '\n')

# Count total alpha characters.
chars_total=$(echo -n "$chars" | wc -m)

# Get all consonants except for ñ.
consonants=$(echo {a..z} | sed 's/[ieaou] //g')

# Set long tab length.
tabs 20

# Echo header.
echo -e "Carácteres\tFrecuencia\tPorcentaje" | tee -a "$fname"

# Get letter name. Count all instances of letters including accented letters. Calculate the percent for each letter. Echo data to table.
for ltr in 'i|í' 'e|é' 'a|á' 'o|ó' 'u|ú|ü' $consonants ñ; do
    ltr_name="${ltr:0:1}"
    ltr_count=$(echo -n "$chars" | grep -Eoi "$ltr" | tr -d '\n' | wc -m)
    ltr_percent=$(echo "scale=4; $ltr_count/$chars_total" | bc | tr -d \. | sed 's/..$/.&%/')
    echo -e "$ltr_name\t$ltr_count\t$ltr_percent"
    if [ "$ltr_name" == "u" ]; then echo | tee -a "$fname"; fi
done | tee -a "$fname"

# Echo footer.
echo -e "Carácteres: 27\tTotal: $chars_total\tTotal: 100%" | tee -a "$fname"


texts: Simple text-to-binary converter written in C++

texts:
I am learning C++ on my own and was hoping for some feedback on this simple text-to-binary converter. The program runs and I haven't encountered any errors with it yet. Any input is welcome.

#include <iostream>
#include <string>
#include <bitset>

using namespace std;

int main()
{
char letter = ' ', playAgain = 'y';
string word = " ";

cout << "\t**Text To Binary Convertor**\n\n";

while (playAgain == 'y'){

    cout << "Please enter a character, word, or phrase: ";

    getline (cin, word, '\n');

    cout << "\nThe binary value for " << word << " is \n";

    for (unsigned int wordPosition = 0; wordPosition < word.size(); ++wordPosition){

        letter = word[wordPosition];

        bitset <8> binary(letter);

        cout << binary;
        }

    cout << "\n\nWould you like to try again? (y/n)";

    cin >> playAgain;

    if (playAgain != 'y'){
        cout << "\n\nExiting program.";
        playAgain = 'n';
        }
        cin.ignore();
}

return 0;
}


texts:
I'm new with Ruby and am trying to improve my coding skills.  This program gets personal information for three people, and then prints them.

It works, but I'm sure it's not the best and certainly not the fanciest way to do it.

I was hoping to get some advice here on how to do it faster/shorter/better/smarter...It is really hard to improve without knowing your mistakes.

The code:

# Define a person with name, age, origin
class Person
  def input(count)
    puts "Hi, let\'s create three new Person. Start with number #{count}"
    puts "What\'s your name?"
    @name = gets
    @name = @name.delete("\n")
    puts "How old are you?"
    @age = gets
    @age = @age.delete("\n")
    puts "Where are you from?"
    @origin = gets
    @origin = @origin.delete("\n")
    puts "I summarize! You are #{@name} and #{@age} years old from #{@origin}"
    puts "Is that correct? \nEnter \"0=Yeah\" or \"Nah\""
    @antwort = gets
    if @antwort.to_i == 0
      puts "Sweet #{@name}, let us get to the next one"
      person_return = [@name, @age,@origin]
      return person_return
    else
      puts "Get off. Let us try again"  # How to go retry?
    end
  end
end

person_one = Person.new
var_person_one = person_one.input(1)
puts "Press Enter for next Person\n"
gets

person_two = Person.new.input(2)
var_person_two = person_two
puts "Press Enter for next Person\n"
gets

person_three = Person.new.input(3)
var_person_three = person_three

p var_person_one
p var_person_two
p var_person_three

Output:

Hi, let's create three new Person. Start with number 1
What's your name?
Kevin
How old are you?
29
Where are you from?
Hamburg
I summarize! You are Kevin and 29 years old from Hamburg
Is that correct?
Enter "0=Yeah" or "Nah"
0
Sweet Kevin, let us get to the next one
Press Enter for next Person

Hi, let's create three new Person. Start with number 2
What's your name?
Steven
How old are you?
22
Where are you from?
London
I summarize! You are Steven and 22 years old from London
Is that correct?
Enter "0=Yeah" or "Nah"
0
Sweet Steven, let us get to the next one
Press Enter for next Person

Hi, let's create three new Person. Start with number 3
What's your name?
Mike
How old are you?
33
Where are you from?
Tampa,FL
I summarize! You are Mike and 33 years old from Tampa,FL
Is that correct?
Enter "0=Yeah" or "Nah"
1
Get off. Let us try again
["Kevin", "29", "Hamburg"]
["Steven", "22", "London"]
nil


texts: Map client application's DTO to service-proxy's DataContract

texts:
My idea is to not not expose/use service's Proxy everywhere throughout the application, rather exercising all service communications(using client Proxy) from a single class. To achieve this I have created below class: -

namespace MyOrganization.EventSender
{
    using MyOrganization.EventSender.DTOs;
    using MyOrganization.EventSender.Proxy;
    using MyOrganization.EventSender.Utilities;
    using log4net;
    using Newtonsoft.Json;
    using System;
    using System.ServiceModel;
    using System.ServiceProcess;

    /// <summary>
    /// The User Session Detail Sender
    /// </summary>
    public class SessionDataSender : ISessionDataSender
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SessionDataDTO _sessionDataDTO;

        public SessionDataSender(SessionDataDTO sessionDataDTO)
        {
            _sessionDataDTO = sessionDataDTO;
        }

        public bool Send()
        {
            try
            {
                Proxy.MessageProcessorProxy.SessionDetails sd = new Proxy.MessageProcessorProxy.SessionDetails();
                sd.ChangeTime = _sessionDataDTO.ChangeTime;
                sd.ChangeType = _sessionDataDTO.ChangeType;
                sd.Username = _sessionDataDTO.Username;
                sd.SessionId = _sessionDataDTO.SessionId;

                log.Info($"Sending SessionEvent [{sd.ChangeType}] to Web-Srver.");

                var client = new Proxy.MessageProcessorProxy.MessageProcessorClient();
                var response = client.LogEventDetails(sd);

                Proxy.ProxyFactory.CloseProxy(client as ICommunicationObject);

                log.Info($"Web-Server Response: [{response.ResponseMessage}]. Reference: [ {JsonConvert.SerializeObject(sd)} ] ");

                return true;
            }
            catch (Exception ex)
            {
                log.Error($"Exception: [{ex.ToString()}]");

                return false;
            }
        }
    }
}

Now, my questions are: -

Is it good to map every DTOs into Proxy's DataContract? As my this class will grow with more service calls with different DTOs.
How this class should be architect so that it doesn't violate SRP/Design-patterns?


texts:
This is a quick script I whipped up to collapse some folder trees down to individual folders. The specific situation that arose was my formerly-itunes collection (it's currently organized Music\artist\album\songs.(mp3|m4a) and I'd really prefer it to be Music\artist\song.(mp3|m4a)).

#!/usr/bin/ruby

require 'optparse'
require 'pp'
require 'fileutils'

### parsing command line options via optparse, nothing to see here
options={}
optparse = OptionParser.new do|opts|
  opts.on('-h', '--help',
          'Display this screen') do
    puts opts
    exit
  end
  opts.on('-t', '--type a,b,c',
          Array, 'Specify filetypes to flatten out (defaults to mp3,m4a)') do|t|
    options[:types] = t
  end
end
optparse.parse!

### the setup (ideally, this would be in a `let` statement)
origin = Dir.pwd
if not options[:types]
  options[:types] = ["mp3", "m4a"]
end

### the actual work
ARGV.each do |target|
  FileUtils.cd("#{origin}/#{target}")
  options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\;`}
  `find -depth -type d -empty -exec rmdir {} \\\;`
end
FileUtils.cd(origin)

Am I doing anything eye-stabbingly wrong? Is there a better way of handling any of the above?

Specifically, I suspect that I could replace the find calls with native Ruby methods, but I can't see how without complicating it significantly. I also suspect that there's a better way of writing FileUtils.cd("#{origin}/#{target}"), but a cursory reading of Dir doesn't reveal anything. Any tips?

#!/usr/bin/ruby

require 'optparse'
require 'pp'
require 'fileutils'

### parsing command line options via optparse
options={:types => ["mp3", "m4a"]}
optparse = OptionParser.new do|opts|
  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
  opts.on('-t', '--type a,b,c', Array, 'Specify filetypes to flatten out (comma separated, defaults to mp3,m4a)') do|t|
    options[:types] = t
  end
end
optparse.parse!

### the actual work
ARGV.each do |target|
  FileUtils.cd(target) do
    options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\;`} ##move all matched files into [target]
    `find -depth -type d -empty -exec rmdir {} \\\;` ##recursively delete all empty folders in [target]
  end
end

options is now initialized beforehand rather than being checked after .parse!
using the block option on FileUtils.cd
removed useless final cd back
tried the glob option, but it just errors without continuing if it hits a matched file in target (ie. one that needs to stay where it is). This seems to happen when I pass :force => TRUE too. The find call notes such files, but still flattens what it can. The glob route also doesn't seem to be case-insensitive.