texts: Jump game to find minimum hops from source to destination

texts:
Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when u reach the goal in minimum number of jumps.

For example:

  Given array A = {2,3,1,1,4}
  possible ways to reach the end (index list)
  i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index 4)
  ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4)

Since second solution has only 2 jumps it is the optimum result.

A lot of input has been derived from previous review here.

public final class JumpGame {

    private JumpGame() {}

    /**
     * Returns the shortest jump path from the source to destination
     *
     * @param jump     The jump array
     * @return         Returns one of the shortest paths to the destination.
     */
    public static List<Integer> getShortestJumps(int[] jump) {
        final List<Integer> list = new ArrayList<Integer>();
        list.add(0);

        for (int i = 0; i < jump.length - 1; ) {
            int iSteps = Math.min(jump.length - 1, i + jump[i]); // iSteps is all the consecutive steps reachable by jumping from i.
            int maxStep = Integer.MIN_VALUE; // max step is one of the step in iSteps, which has the max potential to take us forward.
            /*  trying each step of iSteps */
            for (int j = i + 1; j <= iSteps; j++) {

                /* being greedy and picking up the best step */
                if (maxStep < jump[j]) {
                    maxStep = j;
                }
            }
            list.add(maxStep);
            i = maxStep; // jump to the maxStep.
        }

        return list;
    }

    public static void main(String[] args) {
        int[] a1 = {2,3,1,1,4};
        List<Integer> expected = new ArrayList<Integer>();
        expected.add(0);
        expected.add(1);
        expected.add(4);
        Assert.assertEquals(expected, getShortestJumps (a1));

        int[] a2 = {3, 1, 10, 1, 4};
        expected = new ArrayList<Integer>();
        expected.add(0);
        expected.add(2);
        expected.add(4);
        Assert.assertEquals(expected, getShortestJumps (a2));
    }

}


texts: Creating JavaScript API for first time; request review

texts:
I am creating a commercial API for the first time for responsive webpages/web applications (mobile devices).

I am new and, sadly, working alone as well as new to Javascript (long complicated story).

I was just wondering if someone from the industry could offer their professional opinion on the following format of a "get" call:

var getSample = function(params) {
//Returns Object
return $.ajax({
    url: URL + 'downloadQuadrat.php',
    type: 'GET',
    data: { 'projectID': params.pid, 'quadratID': params.qid },
    dataType: dataType
});
}

Function call:

var printList = function(lid,options,get) {
var list = $("ul#"+lid);
var promise = get(options);

promise.promise().then(
    function(response) {
        var items = response;
        list.empty();

        $.each(items, function(item,details) {
            var ul = $('<ul/>');
            ul.attr('id', lid+'_'+details.ID);
            var li = $('<li/>')
            .text(details.ID)
            .appendTo(list);
            ul.appendTo(list);

        $.each(details,function(key,value) {
                var li = $('<li/>')
                .text(key+': '+value)
                .appendTo(ul);
            });
        });
    }
);
}

Any input or guidance will be hugely appreciated.


texts: Counting distinct number of items in multiple group by query efficiently

texts:
I have the following query that counts the number of vessels in each zone for each week:

SELECT zone, DATE_FORMAT(creation_date, '%Y%u') AS date, COUNT(DISTINCT vessel_imo) AS vessel_count FROM vessel_position
WHERE zone IS NOT NULL
AND creation_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
GROUP BY zone, date;

The table has about 40 million rows. The execution plan for this is:

+----+-------------+-----------------+------------+-------+--------------------+------+---------+------+----------+----------+------------------------------------------+
| id | select_type | table           | partitions | type  | possible_keys      | key  | key_len | ref  | rows     | filtered | Extra                                    |
+----+-------------+-----------------+------------+-------+--------------------+------+---------+------+----------+----------+------------------------------------------+
|  1 | SIMPLE      | vessel_position | NULL       | range | creation_date,zone | zone | 5       | NULL | 21190904 |    50.00 | Using where; Using index; Using filesort |
+----+-------------+-----------------+------------+-------+--------------------+------+---------+------+----------+----------+------------------------------------------+

Columns vessel_imo, zone and creation_date each indexed. Primary key is the composite key (vessel_imo, creation_date).

When I look at the query profile, I can see that a large amount of time i spent doing Creating sort index.

Is there anything I can do to improve this query further?


texts: Calculate mean and standard error of a generator in Python

texts:
The goal of the following code is to calculate the mean and the standard error of vectors of randomly-generated numbers. I am looking for feedback both on the correctness of the calculation, and on its efficiency.

import numpy as np

def mean_and_stderr(num_of_iterations:int, instance_generator) -> (float,float):
    """
    Calculate the mean and standard error of the given generator.

    :param instance_generator: a function that accepts no parameters,
             and returns either a float or a numpy array.
    :param num_of_iterations: number of times to run the instance_generator.

    :return a tuple: (mean, standard_error)

    Test on a degenerate (constant) generator of numbers:
    >>> generator = lambda: 5
    >>> mean_and_stderr(100, generator)
    (5.0, 0.0)

    Test on a degenerate (constant) generator of vectors:
    >>> generator = lambda: np.array([1,2,3])
    >>> mean_and_stderr(100, generator)
    (array([ 1.,  2.,  3.]), array([ 0.,  0.,  0.]))
    """
    sum = sumSquares = None
    for i in range(num_of_iterations):
        x_i = generator()
        if sum is None:
            sum = x_i
            sumSquares = (x_i*x_i)
        else:
            sum += x_i
            sumSquares += (x_i * x_i)
    mean = sum / num_of_iterations
    variance = sumSquares / num_of_iterations - (mean*mean)
    stderr = np.sqrt(variance) / num_of_iterations
    return (mean,stderr)

if __name__=="__main__":
    generate_uniformly_random_number = np.random.random
    print(mean_and_stderr(10, generate_uniformly_random_number))
    # Typical output: (0.5863703739913031, 0.026898107452102943)
    print(mean_and_stderr(1000, generate_uniformly_random_number))
    # Typical output: (0.514204422858358, 0.0002934476865378269)

    generate_uniformly_random_vector = lambda: np.random.random(3)
    print(mean_and_stderr(10, generate_uniformly_random_vector))
    # Typical output: (array([ 0.53731682,  0.6284966 ,  0.48811251]), array([ 0.02897111,  0.0262977 ,  0.03192519]))
    print(mean_and_stderr(1000, generate_uniformly_random_vector))
    # Typical output: (array([ 0.50520085,  0.49944188,  0.50034895]), array([ 0.00028528,  0.00028707,  0.00029089]))


texts:
Quick review:

I've been writing API code which receives user input that can come as either an object or a value type - a problem outlined here.

In order to write an unknown data type to a variable, I first came up with this:

Public Sub LetSet(ByRef variable As Variant, ByVal value As Variant)
    If IsObject(value) Then
        Set variable = value
    Else
        variable = value
    End If
End Sub

called like

Dim result As Variant
LetSet result, objectOrValueType()

However an alternate approach that I've come up with is the following:

Public Property Let LetSet(ByRef variable As Variant, ByVal value As Variant)
    If IsObject(value) Then
        Set variable = value
    Else
        variable = value
    End If
End Property

called like

Dim result As Variant
LetSet(result) = objectOrValueType()

which I like because it feels closer to LetSet a = b - the ultimate goal but one that I don't believe is possible.

Both live in standard modules and are functionally equivalent - the return value of objectOrValueType() (some arbitrary function that generates the unknown data) is stored in result.

So I'm wondering which is better and is there anything I can do to improve on either approach? Any other feedback is, of course, also welcome.

NB, just to add some context, I've come across 2 use cases for this:

A buffered list; this class is drip-fed data of unknown kind from some asynchronous process, and merges it into batches of fixed size - then raises an event when a new batch is ready. Because the internal data store is constantly  being written to, I can't expose that, so I need some way to copy items to variant arrays for each batch and expose those in the event.
Overloaded arithmetic functions; I've defined some Add method that can take integers and sum them with the + operator. However I'm allowing classes to implement IAddable and define their own response to the Add method; this implementation may return an object. So I need to be able to write the result of this calculation to the return variable of the Add method.

For the former I could use a Collection and avoid the issue altogether as @Freeflow points out in their answer - but the batches are fixed size so an array makes more sense for me. For the latter, I don't see a way around using this approach, as the return type of the function is down to the user, not me.


texts: Removing duplicates from multiple arrays at once

texts:
This (working) code is supposed to return a new array that consists of elements of both arrays that were not marked as duplicates (find duplicates in both arrays, remove such elements from both arrays and create an array from the leftovers, if any)

Is there a way to simplify this function?

function diff(arr1, arr2) {
    var arr1_filtered, arr2_filtered;

    arr1_filtered = arr1.filter(function (v) {
        return arr2.indexOf(v) == -1;
    });

    arr2_filtered = arr2.filter(function (v) {
        return arr1.indexOf(v) == -1;
    });

    return arr1_filtered.concat(arr2_filtered);
}


texts: Displaying API results inside a WordPress page template

texts:
I've created a WordPress page template that calls an API using Httpful and formats the results. This is my first time using APIs on a page, so I'd like to know if this is the right direction to go in.

The code below uses information from a members API to receive the member's information and display their basic information along with a single upcoming class.

page-members.php

<?php
/**
 * The template for displaying a list of members.
 *
 * @package themename
 */

get_header();

// call from api using basic auth
require_once 'inc/httpful.phar';
$uri = "https://api.example.com/v1/accounts/KEY/members_list";
$response = \Httpful\Request::get($uri)
    ->addHeader('Authorization', 'Basic KEY')
    ->expects('application/json')
    ->send();
?>

        <?php
        $defaultImage = get_field('logo', 'option');

        // loop through api response for each member
        foreach($response->body->members as $member) :
            $memberID = $member->id;

            // if member has no id, skip member
            if (empty($memberID)) :
                continue;
            endif;

            // if member has no image, use default logo
            $memberImage   = (!empty($member->image)) ? $member->image : $defaultImage;
            $memberName    = $member->name;
            $memberTagline = $member->tagline;

            // loop through upcoming classes for each member
            foreach($member->upcoming_classes as $class) :
                $classID = $class->id;

                // if class has no id, skip class
                if (empty($classID)) :
                    continue;
                endif;

                $className = $class->name;
                $classDate = $class->date;
                $classTime = $class->start_time;
            ?>

                <a href="<?php echo site_url() . '/member/?MemberID=' . $memberID; ?>">
                    <div class="members-image" style="background: url('<?php echo $memberImage; ?>') no-repeat top center / cover;">

<?php echo $memberName; ?>

<?php echo $memberTagline; ?>

                        <?php echo $className; ?>

                        <?php echo date('m/d', strtotime($classDate)); ?> — <?php echo date('g:i a', strtotime($classTime)); ?>

                    <a class="button" href="<?php echo site_url() . '/reserve/?classID=' . $classID; ?>">Book

        <?php
        // end class loop by breaking on first upcoming class with an id
        break; endforeach; endforeach;
        ?>

<?php get_footer(); ?>

Is there anything I can do to improve this single template?


texts:
To ensure there are no naming conflicts within our project (C++) I was tasked with writing a python script to check all of our header files for any occurrences of a using namespace ... within the file. If an occurrence is found, it's appended to a list then written to a log file. It's a fairly simple script, but I feel there could be some optimizations. This script is ran whenever someone commits to the repository.

"""
Checks all the header files in our project to ensure there
aren't occurrences of the namespace string.

AUTHOR: Ben Antonellis
DATE: April 4th, 2020
"""

import os

namespace: str = "using namespace"
working_directory: str = os.path.dirname(os.path.realpath(__file__));
occurrences: list = []

for file in os.listdir(working_directory):
    formatted_file = f"{working_directory}/{file}"
    with open(formatted_file, "r") as source_file:
        for line_number, line in enumerate(source_file):
            if namespace in line and file[-3:] != ".py":
                occurrences.append(f"NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {formatted_file}")

with open("logs/log.txt", "w") as log_file:
    for line in occurrences:
        log_file.write(line)


texts: Refactor this jQuery datepicker code to be as small as possible

texts:
I am using jQuery datepicker on 2 forms on the same page.
I currently am using the following code (below), but as you can see, I am using the same parameters over again (showOn, buttonImage, buttonImageOnly, dateFormat, & constrainInput)

Is there a more efficient way to do this rather then repeating myself over and over again, over 4 methods?

$('#startdate').datepicker(
    {
        showOn: 'both',
        buttonImage: '/assets/images/calendar_symbol.png',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        constrainInput: true, // All of the above is repeated again below
        minDate: new Date(<?php echo date("Y")?>, <?php echo date("m")-1?>, <?php echo date("d")?>),
        onClose: function()
            {
                $('#enddate').val($('#startdate').val());
            }
    }
);

$('#enddate').datepicker(
    {
        showOn: 'both',
        buttonImage: '/assets/images/calendar_symbol.png',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        constrainInput: true, // All the above repeated again..
        minDate: new Date(<?php echo date("Y")?>, <?php echo date("m")-1?>, <?php echo date("d")?>)
    }
);

$('#filter_startdate').datepicker(
    {
        showOn: 'both',
        buttonImage: '/assets/images/calendar_symbol.png',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        constrainInput: true,// and again...
        onClose: function()
            {
                $('#enddate').val($('#startdate').val());
            }
    }
);

$('#filter_enddate').datepicker(
    {
        showOn: 'both',
        buttonImage: '/assets/images/calendar_symbol.png',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        constrainInput: true // and again....
    }
);

I was thinking of using a if statement to check what was clicked (#startdate or #filter_startdate), and then breaking it down like that, but unsure if this would work or how to do this.


texts: Better way to iterate through a dictionary and comparing its keys with itself

texts:
I have a dictionary with author names as keys and values of None. I want to use fuzzywuzzy to compare these author names to see if there are similar ones that I can combine.

So far I am using two dictionaries (they have the same data in both of them, and ideally I would just use one) and then using a double for loop. I want to optimize it further, and I was thinking of using Dictionary Composition, but I couldn't figure out how to get that working with my fuzzy compare logic.

import uuid
from fuzzywuzzy import fuzz

authorToDelete = {}
dictOfAllData1 = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None}
dictOfAllData2 = {'Trevor Jacobs': None, 'Josh Francis': None, 'Marcie Lank': None, 'Marcie H. Lank': None}

for key in dictOfAllData1:
    for key2 in dictOfAllData2:
        str1 = ' '.join(key.split()) #some spaces are different so I handle those here
        str2 = ' '.join(key2.split())
        ratio = fuzz.ratio(str1, str2)
        if fuzz.ratio(str1, str2) > 85 and dictOfAllData1[key] == None:
            dictOfAllData1[key] = str(uuid.uuid1())
        elif ratio > 85:
            if str1 != str2:
                authorToDelete[key2] = None
            else:
                dictOfAllData1[key] = str(uuid.uuid1())

for deleteMe in authorToDelete:
    dictOfAllData1.pop(deleteMe)

print(dictOfAllData1)

#Output is: {'Trevor Jacobs': 'edb6e3d8-3898-11ea-9b62-784f4397bfaf', 'Josh Francis': 'edb6e892-3898-11ea-9b62-784f4397bfaf', 'Marcie Lank': 'edb6eaea-3898-11ea-9b62-784f4397bfaf'}

This is the code I have so far. It works, but it takes longer than I think it should (about 4 seconds with a dictionary of ~700 keys, and about 80 seconds with a dictionary of ~2,700 keys)

My question is how can I make this more efficient? Is there a way I can use if in dict or something like that instead of my second for loop?

I originally posted this on StackOverflow


texts:
I initialized a tree using a nested hash as input, but when I recursively call Tree.new on the children, it doesn't seem to pass each child as a hash. As a pretty ugly, but working, alternative, I translated everything to arrays.

Is there a way to preserve the hash?

I'm doing this exercise using Ruby 1.9.3, so I can't use Ruby 2.0.0's to_h method.

class Tree
  attr_accessor :node_name, :children

  def initialize(arr)
    arr = arr.to_a unless arr.is_a?(Array)
    arr.flatten!
    @node_name = arr.first
    @children = []
    arr.last.each { |c| @children << Tree.new(c) }
  end

  def visit(&block)
    block.call self
  end

  def visit_all(&block)
    visit &block
    children.each { |c| c.visit_all(&block) }
  end
end

family_tree = Tree.new({'grandpa' => { 'dad' => { 'child 1' => {}, 'child 2' => {} },
                                      'uncle' => {'child 3' => {}, 'child 4' => {} } } })

family_tree.visit_all { |node| p node.node_name }


texts:
I am trying to build a simple C#/.Net console application that runs three iterations (see code below). The process runs as intended, but because of how many iterations there are, it can run upwards of 15 to 20 minutes. I intend to run through a list of nodes that would require individual simulations. Therefore requiring iterations for each node. Maybe 50 nodes.

I am wondering if there is a better method to run these iterations. I have just started reviewing Parallel.For() functions, but have not tested. And I have not seen many examples of chained Parallel.For() functions.

I am thinking the code below requires better iteration coding and a bit of multi-threading to really see an improvement in speed. Any suggestions? Is there anything glaring that looks wrong?

Here is the code:

static void Sim()
{

    OE oe = new OE(); // node-path functionality

    string ftC = "x"; // first call
    double fC = 4; // fourth call
    double tTime = 252; // days remaining
    double calendar = 365; // full calendar days
    double rate = .0065; /// interest rate
    double sC = 1; // secondary call
    double tC = 3.897; // third call

    string path = @"c:\temp\output.csv"; // export

    //tC settings
    double i;
    double nIncrement = .05;
    double nMin = 2;
    double nMax = 5;

    // sC settings
    double vi;
    double nvIncrement = .005;
    double nvMin = .10;
    double nvMax = .50;

    // time settings
    double ti;
    double ntIncrement = 5;
    double ntMin = 1;
    double ntMax = tTime + 4;
    //double ntMax = 30;

    // begin basic increments
// where I think I can find improvement in code
    for (i = (tC - nMin); i < nMax + (tC + nIncrement); i += nIncrement) // tC loop
    {
        double nP = Math.Round(i, 2);

        for (vi = (sC - nvMin); vi < (sC + nvMax) + nvIncrement; vi += nvIncrement) // sCatility loop
        {
            double nV = Math.Round(vi, 4);

            for (ti = ntMin; ti <= ntMax; ti += ntIncrement) // time loop
            {
                double nT = ti;

                double variableResult = Math.Round(oe.Solver(ftC, fC, nP, nV, nT, calendar, rate, 4), 5);

                // output code here
            }
        }

    }
}


texts: General static value required by multiple classes

texts:
I have a general value called Seed which is required to multiple class. But those class aren't dependent of the class which declare it.

class Game {
    class Settings {
       public static float Seed = 1337;
    }
}

And some class need a Seed value to work. I take the class Noise as example here.

class Noise {
    private static float _seed;
}

A solution would be to use Game.Settings.Seed to know the value into the class Noise. But what if one day I decide to take all the Noise class to use it in an other project. The code won't compile because there is probably not a Game.Settings.Seed declared in the other project obviously.

A other way would be to set as public field in the Noise class.

class Noise {
    public static float Seed;
}

So in this way, Game which know he need to use Noise class, will set Seed field before doing anything with this class.

But I don't like it too, in this case this is about a float, so that not really a problem, but what about an object that need to be declared, which means Noise class need to implement a verification about itself.

class Noise {

    private static float _seed;
    private static bool _isSeedDeclared;

    public static void SetSeed(int seed){
        _seed = seed;
        _isSeedDeclared = true;
    }

    public int GetValue(int x, int z){
        CheckSettings();
        return computedValue; //to calculate computedValue, I need Seed value
    }

    private void CheckSettings(){
        if(!_isSeedDeclared)
            throw new Exception("You have to define Seed value.");
    }
}

This solution works but I'm not pleased about it. For non-nullable type I have to define an other variable to check, for a nullable class I can compare it to null. But anyway, I don't have only one parameter and I don't have only one class. I'm looking for an better way to implement it.


texts: Avoid static initializer for lists of image and video formats?

texts:
I wrote the following code to read constants from annotations:

public class ContentUtils {
    static {
        String[] videoFormats = null;
        String[] imageFormats = null;
        try {
            Field multipartFileField = MultipartFileWrapper.class.getField("multipartFile");
            Extensions annotation = multipartFileField.getAnnotation(Extensions.class);
            imageFormats = annotation.imageFormats();
            videoFormats = annotation.videoFormats();
        } catch (NoSuchFieldException e) {
            if (imageFormats == null) {
                imageFormats = new String[]{};
            }
            if (videoFormats == null) {
                videoFormats = new String[]{};
            }
        }
        ACCEPTED_IMAGE_FORMATS = imageFormats;
        ACCEPTED_VIDEO_FORMATS = videoFormats;
    }

    public static final String[] ACCEPTED_IMAGE_FORMATS;
    public static final String[] ACCEPTED_VIDEO_FORMATS;
}

Is there a way to rewrite it better?

Or something else improve at this code?


texts: Delivery date checker for e-commerce website

texts:
I’ve made an e-commerce website where administrators can specify the number of deliveries they can make on any one day.

I’ve written a SQL statement that then finds all delivery dates, finds any matching orders on those dates, and then returns any where the remaining “slots” are greater than zero (i.e. available). The statement looks like this:

SELECT
    `id`,
    `delivery_date`,
    (SELECT COUNT(*) FROM `orders` WHERE DATE(`orders`.`created_at`) = `delivery_dates`.`delivery_date`) AS `order_count`
FROM
    `delivery_dates`
HAVING
    SUM(`delivery_limit` - `order_count`) > 0;

It works, but is this optimal? I’m not sure on the inner SELECT, and the HAVING statements.


texts: Fill a pandas dataframe (of predetermined size) with results from a similar dataframe (of size less than or equivalent to the original)

texts:
I'd like some feedback/suggestions on how to improve the following. Specifically I want to know if what I'm doing is reliable and fast, or if there is a better way to accomplish this.
The problem:
I have some dataset containing counts of sales made at different times throughout the day, across different locations/shops. Let's say there are 4 different shops contained in this data (A, B, C, D), and there are 4 different time bins in the day [0,1,2,3]. I query this and return a query dataset, but the issue I have is that for this query there may be no transactions for a certain time bin. Or there may be no transactions even for a specific shop (maybe there was a rat infestation and it closed for the day).
Nevertheless, the end result must have the same number of rows (4 locations x 4 time bins), and simply contain zeros if there were no transactions there. In other words, I want records for all possible occurrences, even if they were not returned by the query itself.
Example:
import pandas as pd

# Specify the complete list of possible time bins
max_timebins = 3
bin_nums = list(range(max_timebins + 1))

# Specify the complete list of shops
shop_ids = ['A', 'B','C','D']

# Make a dataframe for all possible results without the counts
# This is just a dataframe with an index and no columns... this feels a little strange to me but it worked...
dat = {'shop':[], 'timebin':[]}
for shop in shop_ids:
    dat['shop']+=[shop]*len(bin_nums)
    dat['timebin'] += bin_nums
df_all = pd.DataFrame(dat)
df_all = df_all.set_index(list(dat.keys()))

# Example of a result of a query
dfq = pd.DataFrame(
    {
        'shop':['A', 'A', 'A', 'A',
                'B', 'B',
                'C', 'C', 'C',
                'D'],
        'time_bins':[0,1,2,3,
                     0, 3,
                     0,2,3,
                     2],
        'counts':[100,220, 300, 440,
                  500, 660,
                  120, 340, 90,
                  400]}).set_index(['shop', 'time_bins'])

result_df = pd.concat([df_all, dfq], axis=1).fillna(0).astype(int)


texts:
I programmed a little log engine in C I plan to use in my project and maybe some others in future. I am very novice C programmer and would like to have feedback of some experienced ones on this. It's spawned over few files but I've joined them so it's easier to compile. Thank you.

#include <stdarg.h>
#include <syslog.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>

#include "config.h"

/* this is log.h */
#define TPL_IDENT PACKAGE_NAME

enum tp_log_level {
    TPL_DEBUG,
    TPL_INFO,
    TPL_ERR,
    TPL_EMERG,
};

enum tp_log_mode {
    TPLM_SYSLOG,
    TPLM_FILE,
};

void tp_log_init(int mode, int level, int fd);
void tp_log_write(int level, const char *fmt, ...);
void tp_log_close(void);
/* end of log.h */

/* function from pio.c I use */
ssize_t tp_write(int fd, const void *buf, size_t len)
{
    ssize_t ret, wlen = 0;
    const char *ptr;

    ptr = buf;
    while (wlen != len) {
        ret = write(fd, ptr, len-wlen);

        if (ret == -1)
            if (errno == EINTR)
                continue;
            else
                return -1;

        wlen += ret;
        ptr += ret;

    }
    return wlen;
}

/* start of log.c */

static int log_fd = -1;
static int log_level;
static int log_mode;

static const char *level_txt[] = {
    "DEBUG", "INFO", "ERROR", "EMERG"
};

static const int level_syslog[] = {
    LOG_DEBUG, LOG_INFO, LOG_ERR, LOG_EMERG
};

void tp_log_init(int mode, int level, int fd)
{
    assert(mode == TPLM_SYSLOG || mode == TPLM_FILE);
    assert(mode == TPLM_FILE ? fd >= 0 : 1);
    assert(level >= TPL_DEBUG && level <= TPL_EMERG);

    switch (mode) {
        case TPLM_FILE:
            log_fd = fd;
            break;
        case TPLM_SYSLOG:
            openlog(TPL_IDENT, LOG_PID|LOG_CONS, LOG_DAEMON);
            break;
    }
    log_level = level;
    log_mode = mode;
}

#define MAX_TIME_LEN 512
#define MAX_PREFIX_LEN 10
#define MAX_MSG_LEN 1024
#define MAX_POSTFIX_LEN 2

static void tp_vlog_write(int level, const char *fmt, va_list alist)
{
    int ret, len;
    time_t t;
    struct tm *tm;
    char msg[MAX_TIME_LEN+MAX_PREFIX_LEN+MAX_MSG_LEN+MAX_POSTFIX_LEN];

    assert(log_fd);
    assert(fmt);
    assert(level >= TPL_DEBUG && level <= TPL_EMERG);

    if (level < log_level)
        return;

    switch (log_mode) {
        case TPLM_FILE:

            t = time(NULL);
            tm = localtime(&t);
            if (tm == NULL)
                abort();

            len = strftime(msg, MAX_TIME_LEN, "%a, %d %b %Y %T %z", tm);
            len += snprintf(msg+len, MAX_PREFIX_LEN, " [%s] ",
                    level_txt[level]);

            ret = vsnprintf(msg+len, MAX_MSG_LEN, fmt, alist);
            if (ret >= MAX_MSG_LEN)
                len += MAX_MSG_LEN-1;
            else
                len += ret;

            snprintf(msg+len, MAX_POSTFIX_LEN, "\n");
            tp_write(log_fd, msg, len+1);
            break;

        case TPLM_SYSLOG:
#ifdef HAVE_VSYSLOG
        vsyslog(level_syslog[level], fmt, alist);
#else
        vsnprintf(msg, MAX_MSG_LEN, fmt, vl);
        syslog(level_syslog[level], "%s", msg);
#endif
            break;
    }
}

void tp_log_write(int level, const char *fmt, ...)
{
   va_list vl;

   va_start(vl, fmt);
   tp_vlog_write(level, fmt, vl);
   va_end(vl);
}

void tp_log_close(void)
{
    assert(log_fd);

    switch (log_mode) {
        case TPLM_SYSLOG:
            closelog();
            break;
        case TPLM_FILE:
            close(log_fd);
            break;
    }
}


texts:
I'm creating an RSVP-type application which will later be implemented in a mobile application I'm making. In this mobile application the user can select different events around their area and can choose whether they want to come to the event or not.
Of course in the real application the user will need to get a 5 character code and input it in order to confirm whether they are going or not. They will most likely get that code in the physical invitation or as an email. From there - the organiser can have a clean view as to who is coming and who is not.
The user can get the details of the event - such as the date, and what time it will happen, the user can also get the detail of the event organiser - such as the contact details, email, etc.
This is my first go at implementing the classes. I am looking for feedback as to how I can improve the structure and clarity of the code - I also want to obey SOLID principles to ensure the code is as good as possible.
Here is the current code:
namespace FunTest
{
    public class Location
    {
        public Location(string city, string region, string streetName, int streetNumber) => (City, Region, StreetName, StreetNumber) =
            (city, region, streetName, streetNumber);

        public string City { get; set; }
        public string Region { get; set; }
        public string StreetName { get; set; }
        public int StreetNumber { get; set; }
    }

    public static class EmailValidator
    {
        public static bool ValidateEmail(string email)
        {
            try
            {
                MailAddress address = new MailAddress(email);
                return address.Address == email;
            }
            catch
            {
                return false;
            }
        }
    }
    public class EmailAddress
    {
        private string _email;
        public string Email
        {
            get => _email;
            set
            {
                if (EmailValidator.ValidateEmail(_email))
                    _email = value;
            }
        }
    }
    public class EventOrganizer
    {
        public EventOrganizer(string firstName, string lastName, int phoneNumber) => (FirstName, LastName, PhoneNumber) =
            (firstName, lastName, phoneNumber);

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName => FirstName + LastName;

        public int PhoneNumber { get; set; }
        public EmailAddress EmailAddress { get; set; }
    }
    public class RSVPEvent
    {
        public string EventName { get; set; }
        public string EventDescription { get; set; }

        public TimeSpan StartTime { get; set; }
        public TimeSpan EndTime { get; set; }
        public DateTime Date { get; set; }

        public Location EventLocation { get; set; }
        public EventOrganizer EventOrganizer { get; set; }

        public IList<string> Attendees { get; set; }
        public IList<string> Absentees { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {

        }
    }
}


texts: Optimizing Floodfill algorithm implementation as much as possible

texts:
Actually my implementation is not working very well for big areas (I don't know why) I already created a question on Stackoverflow. But I figured out how to do it to work with an O(n) implementation (you can see what I mean here (see the fiddle I attached)).

But for some reason as I said it is not working very well on big areas.

/// <summary>
/// Floods the fill.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="target">The target.</param>
/// <param name="replacement">The replacement.</param>
public static void FloodFill<T>(this T[] source, int x, int y, int width, int height, T target, T replacement)
    where T : IEquatable<T>
{
    int i;

    source.FloodFill(x, y, width, height, target, replacement, out i);
}

/// <summary>
/// Floods the array following Flood Fill algorithm
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="target">The target to replace.</param>
/// <param name="replacement">The replacement.</param>
/// <param name="i">The i.</param>
// This was generic
public static void FloodFill<T>(this T[] source, int x, int y, int width, int height, T target, T replacement, out int i)
    where T : IEquatable<T>
{
    i = 0;
    HashSet<int> queue = new HashSet<int>();

    queue.Add(P(x, y, width, height));

    while (queue.Count > 0)
    {
        int _i = queue.First(),
            _x = _i % width,
            _y = _i / width;

        queue.Remove(_i);

        if (source[_i].Equals(target))
            source[_i] = replacement;

        for (int offsetX = -1; offsetX < 2; offsetX++)
            for (int offsetY = -1; offsetY < 2; offsetY++)
            {
                // do not check origin or diagonal neighbours
                if (offsetX == 0 && offsetY == 0 || offsetX == offsetY || offsetX == -offsetY || -offsetX == offsetY)
                    continue;

                int targetIndex = Pn(_x + offsetX, _y + offsetY, width); // This is already inverted that's why we don't use F.P(...)
                int _tx = targetIndex % width,
                    _ty = targetIndex / width;

                // skip out of bounds point
                if (_tx < 0 || _ty < 0 || _tx >= width || _ty >= height)
                    continue;

                if (!queue.Contains(targetIndex) && source[targetIndex].Equals(target))
                {
                    queue.Add(targetIndex);

                    if (Monitor.IsEntered(i))
                        ++i;
                    else
                        Interlocked.Increment(ref i);
                }
            }

        if (i > 100000)
            break;
    }
}

My main concerns are the following:

I don't know if there is a better way to debug how many iterations has the algorithm done (and if I'm getting them correctly).
I don't like to use Monitor.IsEntered (I'm not sure if this is needed).
I would like to speed-up it, but I don't know how (I think this is slow) (you can compare it with ms-paint to see differences, I know it's written on C++, but... I would like to get a significant perfomance).
Also, I don't know if there is a better way to do it (to avoid unnecesary memory consumption).


texts: Removing Dicts with Null values from Only the End of a List

texts:
Given input such as:

foos = [
    [],
    [{'a': 1}],
    [{'a': 1}, {'a': 2}],
    [{'a': 1}, {'a': 2}, {'a': None}],
    [{'a': 1}, {'a': 2}, {'a': None}, {'a': None}],
    [{'a': 1}, {'a': None}, {'a': 2}],
    [{'a': 1}, {'a': None}, {'a': 2},  {'a': None}],
    [{'a': 1}, {'a': None}, {'a': 2},  {'a': None}, {'a': None}],
]

I want a function remove_empty_end_lines that takes a list of dicts and will remove all dicts with null values that only appear at the end of the list, not in between.

for foo in foos:
    print(foo)
    print(remove_empty_end_lines(foo))
    print('\n')

[]
[]

[{'a': 1}]
[{'a': 1}]

[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]

[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]

My final solution is:

def remove_empty_end_lines(lst):
    i = next(
        (
            i for i, dct in enumerate(reversed(lst))
            if any(v is not None for v in dct.values())
         ),
        len(lst)
    )

    return lst[: len(lst) - i]

I'm not going for code golf, rather for performance and readability.

In the input I've listed above, the dicts are always a length of one, butin reality the lengths can be any amount. The lengths of each dict within a list will always be the same.


texts: Reading lines of a file into a vector of strings

texts:
I have to read from a file and store the data inside an std::vector container. The procedure of opening the file, reading and writing onto the container are enclosed in a routine: readData.

Reading and writing include the use of several std functions that may fail.
Instead of putting a try catch for each of those std function calls, I have put a try catch-all block to collect all the possible errors.
Is this a bad practice?

#include "global.h

void readData( std::vector<std::vector<std::string> >&,
                    const std::string& );

int main()
{

    std::vector<std::vector<std::string> >& table;
    std::string path = "myDataFile";

    try
    {
        readData( table, path );
        std::cout << "Done" << std::endl;
    }
    catch( const char* error)
    {
        std::cout << error << std::cout;
        return 0;
    }

    // do something with the data ...

    return 0;
}

Here is the readData implementation:

void readData( std::vector<std::vector<std::string> >& table,
                    const std::string& path)
{

    std::ifstream ifs(path);
    if (  !ifs )
        throw "Error opening file.";

    try
    {
        while ( true ){
            std::string line;
            std::getline(ifs, line);

            if(!ifs)
                break;

            std::vector<std::string> row;
            std::istringstream iss(line);
            std::copy(std::istream_iterator<std::string>(iss),
                 std::istream_iterator<std::string>(),
                 std::back_inserter(row));
            table.push_back(row);
        }
    }
    catch(...)
    {
        throw "Error reading the content of the file";
    }

}


texts: Transforming a list of two-dimensional coordinates into a flat list of relative changes

texts:
I have a little function that parse a nested list of coordinates into a flat list of compressed coordinates. By compressed coordinates, I mean that only the delta (distance) between each coordinates are stored in the list and the float coordinates are transformed in integer.

input = [[-8081441,5685214], [-8081446,5685216], [-8081442,5685219], [-8081440,5685211], [-8081441,5685214]]
output = [-8081441, 5685214, 5, -2, -4, -3, -2, 8, 1, -3]

def parseCoords(coords):
    #keep the first x,y coordinates
    parsed = [int(coords[0][0]), int(coords[0][1])]
    for i in xrange(1, len(coords)):
        parsed.extend([int(coords[i-1][0]) - int(coords[i][0]), int(coords[i-1][1]) - int(coords[i][1])])
    return parsed

parsedCoords = parseCoords(input)

As the input list is really big, is there a way to improve the function, maybe by using generators or list comprehension?


texts:
I had the idea to have a static method on an activity which creates intents that it can use. For example if I have an activity with a webview that can load html from a resource or a URL I would have 2 methods in the activity like so.

public static Intent createURLIntent(Context context, int titleId, String URL) {
    Intent intent = new Intent(context, WebViewActivity.class);
    intent.putExtra(TITLE_ID, titleId);
    intent.putExtra(URL, URL);
    return intent;
}

public static Intent createFileIntent(Context context, int titleId, String fileName) {
    Intent intent = new Intent(context, WebViewActivity.class);
    intent.putExtra(TITLE_ID, titleId);
    intent.putExtra(FILE, fileName);
    return intent;
}

The on create would look like this..

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview_activity);
    int titleId = getIntent().getIntExtra(TITLE_ID, 0);
    setTitle(getString(titleId));
    if (getIntent().hasExtra(FILE)) {
        webview.loadUrl(getIntent().getStringExtra(FILE));
    } else {
        webview.loadUrl(getIntent().getStringExtra(URL));
    }
}

Then a class that wants to open that activity would use it in this way:

    Intent intent = WebViewActivity.createURLIntent(
            context, R.string.about_title, "www.google.com");
    startActivity(intent);

Is there any problems with using this approach?


texts: Test four int of commonality in the lower four bits

texts:
The four parameters a, b, c and d can be -1 (meaning it's not set) or a random one of {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}. If they are different from -1, they are guaranteed to be distinct.

The code looks at the four least significant bits of the four ints and tests if they all have a bit in common:

1101
1110
0100
0101

have the second left bit 1.

1001
1010
0000
0001

all have the second left bit 0.

1000
0110
0101
1101

have no common bit.

The following is possible:

a = -1, b = -1, c = 15, d =  4; //sim(a, b, c, d) == 0, because at least one is -1
a = -1, b = -1, c = -1, d = -1; //sim(a, b, c, d) == 0, because all are -1
a =  9, b =  1, c =  3, d =  5; //sim(a, b, c, d) == 1, because all values have a bit in common (a & 1, b & 1, c & 1 and d & 1 are all 1)
a =  8, b =  1, c =  2, d =  4; //sim(a, b, c, d) == 0, because there is no bit that is equal for a, b, c and d

The following will never happen:

a = 1, b = 1, c = 2, d = 5; // a == b, which is guaranteed to never happen because a == b

The code is meant to be as fast as possible on x86, readability would be a plus but is not necessary.

The code:

int sim(int a, int b, int c, int d)
{
    return ((a != -1) && (b != -1) && (c != -1) && (d != -1)) &&
    ((((a & 8) == (b & 8)) && ((a & 8) == (c & 8)) && ((a & 8) == (d & 8))) ||
     (((a & 4) == (b & 4)) && ((a & 4) == (c & 4)) && ((a & 4) == (d & 4))) ||
     (((a & 2) == (b & 2)) && ((a & 2) == (c & 2)) && ((a & 2) == (d & 2))) ||
     (((a & 1) == (b & 1)) && ((a & 1) == (c & 1)) && ((a & 1) == (d & 1))));
}

Are there obvious ways to speed up the code?


texts:
I've never written a queue before and literally just took the concepts and tried to code something up. I decided to write a basic integer queue and as an example/driver I use a queue of size 5 which implements insert(), delete(), and display().

Please critique these implementations and comment if there should be any additions or modifications. The reason for the simplicity is that I'm mostly concerned that I got the concepts correct at this point. This is not the most robust queue by any means.

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

#define ERR(msg) fprintf(stderr, "%s\n", msg)
#define QUEUE_SIZE 5

static size_t const front = 0;
static size_t rear = 0;

int queue[QUEUE_SIZE];

int insert(int num);
int delete(void);
void display(void);

int main(void)
{
    insert(5);
    insert(8);
    insert(58);
    insert(9);
    insert(10);
    display();
    delete();
    display();
    delete();
    display();
    delete();
    display();
    delete();
    display();

    return EXIT_SUCCESS;
}

int insert(int num)
{
    if((rear + 1) > QUEUE_SIZE)
    {
        ERR("Queue full, cannot insert item.");
        return -1;
    }
    queue[rear++] = num;
    return 0;
}

int delete(void) // Deletes the front one
{
    if(rear == front)
    {
        ERR("Cannot delete from empty queue.");
        return -1;
    }

    size_t i;

    for(i = front; (i+1) < QUEUE_SIZE; i++)
    {
        queue[i] = queue[i+1];
    }
    rear--;
    return 0;
}

void display(void)
{
    size_t i;
    for(i = front; i < rear; i++)
    {
        printf("%d\t", queue[i]);
    }
    putchar('\n');
    return;
}


texts: Determining expiration date based on list of months in which to refresh

texts:
I have a list of months in which users are required to update some data. I want to determine at what date they should have updated their data. They must update in March, May and August. If today is March, I want to get back the 1st of March. If today is February, I want to get back last year's August. In reality the list wouldn't be hardcoded.

I do have some working code, but I wonder if there is a simpler / more elegant of writing this (the GetCheckDate method).

using System;
using System.Collections.Generic;
using System.Linq;

internal class Program
{
    private static void Main()
    {
        var listOfMonths = new List<int?> {3, 5, 8};
        Console.WriteLine(GetCheckDate(listOfMonths,
            new DateTime(2014, 2, 1))); // expect 2013-08-01
        Console.WriteLine(GetCheckDate(listOfMonths,
            new DateTime(2014, 3, 1))); // expect 2014-03-01
        Console.WriteLine(GetCheckDate(listOfMonths,
            new DateTime(2014, 7, 1))); // expect 2014-05-01
        Console.WriteLine(GetCheckDate(null,
            new DateTime(2014, 7, 1))); // expect 2013-07-1
        Console.WriteLine(GetCheckDate(new List<int?>(),
            new DateTime(2014, 7, 1))); // expect 2013-07-1
    }

    private static DateTime GetCheckDate(IEnumerable<int?> listOfMonths,
        DateTime curDate)
    {
        DateTime result = curDate.AddYears(-1);
        if (listOfMonths == null) return result;
        listOfMonths = listOfMonths.ToList();
        if (!listOfMonths.Any()) return result;

        listOfMonths = listOfMonths.OrderByDescending(m => m).ToList();
        var greatestSmallerThan =
            listOfMonths.FirstOrDefault(m => m <= curDate.Month)
            ?? listOfMonths.FirstOrDefault(m => m > curDate.Month);
        result = new DateTime(
            greatestSmallerThan.Value <= curDate.Month
                ? curDate.Year : curDate.Year - 1, greatestSmallerThan.Value, 1);

        return result;
    }
}


texts:
In my Rails app, I have two classes each with the same enum for status. Code climate is complaining about duplication.

class Enrolment < ActiveRecord::Base
  has_many :enrolment_presentations
  has_many :presentations, through: :enrolment_presentations

  enum status: {
    'Pending' => 1,
    'Suspended' => 2,
    'Cancelled' => 3,
    'Pass' => 4,
    'Fail' => 5,
    'DPR' => 6,
    'Unknown' => 7,
    'Enrolled' => 8
  }
end

class EnrolmentPresentations < ActiveRecord::Base
  belongs_to :enrolment
  belongs_to :presentation

  enum status: {
    'Pending' => 1,
    'Suspended' => 2,
    'Cancelled' => 3,
    'Pass' => 4,
    'Fail' => 5,
    'DPR' => 6,
    'Unknown' => 7,
    'Enrolled' => 8
  }
end

How would you go about removing this duplication?


texts: PHP library that can use different authentication mechanisms

texts:
I am making a library which can use different auth mechanisms. I have abstracted the code within an interface:

interface Authenticable
{
    public function getName(): string;

    /**
     * Based on auth type, return the right format of credentials to be sent to the server
     *
     * @param Authenticable $credentials
     * @return mixed
     */
    public function encodedCredentials(): string;
}

One of the possible methods to use this is Plain.php:

class Plain implements Authenticable
{
    protected $name = 'PLAIN';
    protected $options;

    public function __construct(Options $options)
    {
        $this->options = $options;
    }

    public function encodedCredentials(): string
    {
        $credentials = "\x00{$this->options->getUsername()}\x00{$this->options->getPassword()}";
        return XML::quote(base64_encode($credentials));
    }

    public function getName(): string
    {
        return $this->name;
    }
}

And when initializing auth methods I am using this part of code

public function getAuthType()
{
    if (!$this->authType)
        $this->authType = new Plain($this->options);

    return $this->authType;
}

which is initializing Plain if no other method was previously given.

What I am wondering here is: should I forward $username and $password to Plain so that I could decouple it from Options class (since those are the only two fields needed in the class)?

On the other hand, that is what Options class is all about. Besides username and pass, it also holds host, port, logger and resource setters and getters, and few helper methods


texts:
I've written this MySQL database class for my Java application and I'd just like some feedback on it before moving onto making my next class.

The idea here is that I have a simple properties file which stores the hostname, username, password, and database name. I then connect to the database (if possible) and return the Connection.

Although I am not really sure what should happen if the properties file doesn't exist, or the MySQL connection fails, should I return Connection which would be null, throw a new exception, or re-throw the existing exception?

package app;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Database {

    private String hostname;
    private String database;
    private String username;
    private String password;
    private Connection conn;

    public Connection getConnection() {

        if(conn == null) {

            try {

                System.out.println("Getting properties file...");
                Properties prop = new Properties();
                InputStream input = Database.class.getResourceAsStream("database.properties");
                prop.load(input);
                this.hostname = prop.getProperty("hostname");
                this.database = prop.getProperty("database");
                this.username = prop.getProperty("username");
                this.password = prop.getProperty("password");
                input.close();

            } catch (IOException ex) {

                // Error Reading Properties File
                ex.printStackTrace();

            } finally {

                if (this.database != null) {

                    try {
                        System.out.println("Connecting to database...");
                        Class.forName("com.mysql.jdbc.Driver");
                        conn = DriverManager.getConnection("jdbc:mysql://" + this.hostname + "/" + this.database + "?user=" + this.username + "&password=" + this.password);

                    } catch (SQLException ex) {

                        // Error Connecting to Database
                        ex.printStackTrace();

                    } catch (ClassNotFoundException ex) {

                        // Error Connecting to Database
                        ex.printStackTrace();

                    }

                }

            }

        }

        return conn;

    }

}


texts: JSON loader with event bus, cache, and session

texts:
I have an Android application which needs to retrieve JSON files from a server and then display the information in my app. To accomplish this I have the following architecture:

The main activity adds a job to the job queue requesting certain information from the server.
The job gets run, retrieving the specified information and caching it in case the same request is made again in the future.
The job on completion adds an event containing the information to the event bus.
The event bus then relays the event back to the main activity which renders the information.

While I was developing other parts of the application I simply provided the job queue, event bus and cache via constants, i.e.

public class Dependencies {
  public static final JobQueue JOB_QUEUE = new JobQueue();
  public static final EventBus EVENT_BUS = new EventBus();
  public static final Cache CACHE = new Cache();
}

I knew at some point I wanted to use dependency injection (via the Dagger 2 library) to improve the style and make my code more modular and testable. I have now begun the process of migrating my code over to this style but I am discovering some problems. Here is my new code (some parts omitted):

public class MainActivity extends Activity {

  @Inject EventBus mEventBus;
  @Inject JobQueue mJobQueue;
  @Inject Cache mCache;

  private Session mSession;

  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
    * Dagger 2 injection
    * */
    ((MyApplication) getApplication()).getDependenciesComponent().inject(this);

    final HttpUser httpUser = new HttpUser("xxxxxx@xxxxxxxx.com", "xxxxxxxx");
    startSession(httpUser);
  }

  @Override
  protected void onResume() {
    super.onResume();
    mEventBus.register(this);
  }

  @Override
  protected void onPause() {
    super.onPause();
    mEventBus.unregister(this);
  }

  @Subscribe
  public void onSessionStarted(final SessionStartedEvent sessionStartedEvent) {
    final boolean didExceptionOccur = sessionStartedEvent.didExceptionOccur();
    if(didExceptionOccur) {
      final Throwable throwable = sessionStartedEvent.getThrowable();
      handleSessionStartFailedThrowable(throwable);
    }else {
      mSession = sessionStartedEvent.get();
      loadTasks(mSession);
    }
  }

  @Subscribe
  public void onTasksLoaded(final TasksLoadedEvent tasksLoadedEvent) {
    final boolean didExceptionOccur = tasksLoadedEvent.didExceptionOccur();
    if(didExceptionOccur) {
      final Throwable throwable = tasksLoadedEvent.getThrowable();
      handleLoadTasksFailed(throwable);
    }else {
      final Task[] tasks = tasksLoadedEvent.get();
      final String taskArrayStr = Arrays.toString(tasks);
      Log.i(TAG, "tasks loaded: " + taskArrayStr);
      setTasksOnFragments(tasks);
    }
  }

  private void startSession(final HttpUser httpUser) {
    final Job startSessionJob = new StartSessionJob(this, mEventBus, httpUser);
    mJobQueue.addJobInBackground(startSessionJob);
    Log.d(TAG, "added start session job to job queue");
  }

  private void loadTasks(final Session Session) {
    final Job loadTasksJob = new LoadTasksJob(this, mEventBus, mCache, session);
    mJobQueue.addJobInBackground(loadTasksJob);
    Log.d(TAG, "added load tasks job to job queue");
  }

}

My primary focus here is on the job objects. Whereas before I would simply access the job queue, event bus, and cache from the static singletons, I now have to inject those dependencies into their constructors. As you can see for the "load tasks" job

final Job loadTasksJob = new LoadTasksJob(this, mEventBus, mCache, session);

I now have a four argument constructor, whereas before it was only two. I have read in "Clean Code" that a 4-arg constructor is an abomination and typically a sign you need to refactor your code. Is this the case here, am I doing something wrong structuring my code in this way?


texts: Reading a Bitmap from disk on a separate thread on Android

texts:
I want to defer the reading of a bitmap to another thread. I'm mainly concerned about concurrency issues since I'm kind of green on that subject, so I would like to know if this code has any potential flaws.

public class SomeActivity extends Activity {

    Bitmap threadBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new BitmapTask().execute();
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(threadBitmap != null) {
                    // Assume bitmap has loaded and do something with it here
                }
            }

        });
    }

    public class BitmapTask extends AsyncTask<Void, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bitmap = null;
            InputStream in = null;

            try {
                in = getAssets().open("mybitmap.png");
                bitmap = BitmapFactory.decodeStream(in);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            threadBitmap = result;
        }

    }

}


texts: Using RestTemplate for HTTP request timeout

texts:
I am using RestTemplate to make an HTTP call to one of my service and I would like to have timeout for my HTTP Request:

public static String getResponse(final String url) {

    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
    String response = restTemplate.getForObject(url, String.class);

    // return response

}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(2000);
    factory.setConnectTimeout(2000);
    return factory;
}

(I came up with this after reading this.)

Is this an efficient way of using RestTemplate along with ClientHttpRequestFactory? Since with this for each call, it will make a new RestTemplate object. Earlier, I was not using any timeout for RestTemplate so I declared RestTemplate as static final.

private static final RestTemplate restTemplate = new RestTemplate();

public static String getResponse(final String url) {

    String response = restTemplate.getForObject(url, String.class);

    // return response

}

I am not sure what is the right way of using RestTemplate along with ClientHttpRequestFactory. Should they both be declared as static?


texts:
I've just begun creating my first user class. First, I need some clarifications.

Am I using try and catch correctly?

To clarify, the way I would be instantiating this object is like so:

try{
    $loggedInUser = new LoggedIn/User($email,$password,$useragent);
    $_SESSION['user'] = $loggedInUser;//now session holds user object
    die(json_encode('type'=>'success'=>'message'=>'account_fetch_view'));
}
catch(Exception $e) {
    unset($_SESSION['user']);
    die(json_encode(['type'=>'error','message'=>$e]));
}

Looking at my class, will I be able to do this as I've anticipated? If not, should I just construct it as I used to do (i.e. manually from the login processing script)?

namespace LoggedIn;
class User {
    public $email      = NULL;
    public $hash       = NULL;
    public $user_id    = NULL;
    public $user_agent = NULL;
    public $sign_in    = NULL;
    public $csrf_token = NULL;
    public $btc_addr   = NULL;
    public $throttle   = NULL;
    public $last_ajax  = NULL;
    public $verified   = NULL;
    public $reputation = NULL;

    function __construct($e_mail,$p_word,$u_agent)
    {
        if($this->check_pass($p_word) === true && $this->check_email($e_mail) === true)
        {
            $result = $this->fetch_details($e_mail,$p_word);
            if($result !== false && is_array($result) === true)
            {
                $this->email      = $result['u_email'];
                $this->hash       = $result['u_pass'];
                $this->user_id    = $result['u_id'];
                $this->user_agent = $u_agent;
                $this->sign_in    = time();
                $this->csrf_token = $this->csrf_create($this->sign_in,$this->hash);
                $this->btc_addr   = $result['u_addr'];
                $this->throttle   = 0;
                $this->last_ajax  = ($this->sign_in - 5);
                $this->verified   = $result['u_verified'];
                $this->reputation = $this->fetch_rep($this->user_id);
            }else{
                throw new Exception('Invalid Username or Password');
            }
        }
    }

    private function csrf_create($timestamp,$hash)
    {
            return hash('sha256', str_shuffle(openssl_random_pseudo_bytes(4) . $hash . $timestamp));
    }
    private function fetch_details($e_mail,$p_word)
    {

    }
    private function check_email($e_mail)
    {

    }
    private function check_pass($p_word)
    {

    }

    public function log_out()
    {

    }

    public function bid($amount,$auction)
    {

    }

    public function buy_now($amount,$auction)
    {

    }

    private function fetch_rep($u_id)
    {

    }
}


texts:
I decided to make a program that calculates change, based on an input. My code is extremely long, and I would like to know how I can fix this.

def make_change(amount)
  values = []
  coins = []
  hash = {}
  if amount >= 50
    coins.push(:H)
    values.push(amount / 50)
    amount = amount % 50
    if amount % 50 >= 25
      coins.push(:Q)
      values.push(amount / 25)
      amount = amount % 25
      if amount % 25 >= 10
        coins.push(:D)
        values.push(amount / 10)
        amount = amount % 10
        if amount % 10 >= 5
          coins.push(:N)
          values.push(amount / 5)
          amount = amount % 5
          if amount % 5 >= 1
            coins.push(:P)
            values.push(amount / 1)
          end
        end
      end
    end
  elsif amount >= 25
    coins.push(:Q)
    values.push(amount / 25)
    amount = amount % 25
    if amount % 25 >= 10
      coins.push(:D)
      values.push(amount/10)
      amount = amount % 10
      if amount % 10 >= 5
        coins.push(:N)
        values.push(amount/5)
        amount = amount % 5
        if amount % 5 >= 1
          coins.push(:P)
          values.push(amount/1)
        end
      end
    end
  elsif amount >= 10
    coins.push(:D)
    values.push(amount / 10)
    amount = amount % 10
    if amount % 10 >= 5
      coins.push(:N)
      values.push(amount / 5)
      amount = amount % 5
      if amount % 5 >= 1
        coins.push(:P)
        values.push(amount / 1)
      end
    end
  elsif amount >= 5
    coins.push(:N)
    values.push(amount / 5)
    amount = amount % 5
    if amount % 5 >= 1
      coins.push(:P)
      values.push(amount / 1)
    end
  elsif amount >= 1
    coins.push(:P)
    values.push(amount / 1)
  else
    coins = []
    values = []
  end
  Hash[coins.zip(values)]
end

Examples

make_change(42) should result in
   => {:Q => 1, :D => 1, :N => 1, :P => 2

make_change(91) should result in
   => {:H => 1, :Q => 1, :D => 1, :N => 1, :P => 1


texts:
You are given an array of n+2 elements. All elements of the array are in range 1 to n. All elements occur once except two numbers, which occur twice. Your task is to find the two repeating numbers.

My solution is:

t=int(input()) #number of test cases
for _ in range(t):
    n=int(input()) # no. of array elements
    l=[int(x) for x in input().split()]  #array elements
    for i in range(1,n-1):
        if l.count(i)==2:  # using count function to count the elements
            print(i,end=' ')
    print()

How can I improve it?  Currently, it shows time limit exceeded on hackerrank.


texts: Is a Timer the best way to achieve recursive in Android?

texts:
I'm changing the Viewpager items programmatically using mViewPager.setCurrentItem(position); with a regular interval of time recursively. Please tell me if this is the best way to achieve this or if there are any problems with my code.

    ViewPager mViewPager ;
    mViewPager = (ViewPager) findViewById(R.id.viewpager);

    Timer timer = new Timer();
    timer.schedule(new UpdateTimeTask(backgroundimages.length), 1, 5000);

    private class UpdateTimeTask extends TimerTask {
        int mLength = 0;

        public UpdateTimeTask(final int length) {
            this.mLength = length;
        }

        public void run() {
            mViewPager.post(new Runnable() {
                @Override
                public void run() {
                    if (mViewPager.getCurrentItem()+1 < mLength) {
                        Updateviewpager(mViewPager.getCurrentItem() + 1);
                    } else {
                        Updateviewpager(0);
                    }
                }
            });
        }
    }

    public void Updateviewpager(int position) {
        mViewPager.setCurrentItem(position);
    }


texts: Capture worksheet formulas in VBA format

texts:
I had been searching for a simple way to capture worksheet formulas in VBA format. I came up with a solution below, which I wanted to share.

With any luck this could be useful to someone down the road. Suggestions for improvement are welcome.

Public Const vbQuadrupleQuote As String = """""" 'represents 2 double quotes for use in VBA R1C1 formulas ("")
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')

Sub CaptureFormulas()  'simplifies the capturing of worksheet formulas in VBA format

'Peter Domanico, May 2017

'Steps:

'(1) place this script in your personal macro workbook
'(2) open Immediate Window in VBA (Control + G)
'(3) run this script and follow prompts
'(4) a With statement containing formulas for your selection will be printed to the Immediate Window
'(5) you can use this With statement in any script

Dim ws As String
Dim rng As Range
Dim MyString As String
Dim MyColumn As Variant
Dim MyRow As Variant
Dim LastRow As String
Dim MyRange As String
Dim MyFormula As String

'set worksheet string
ws = "Activesheet" 'change this as needed

'error handling
On Error GoTo OuttaHere

'select range
Set rng = Application.InputBox("Select range to capture", ": )", Type:=8)

'determine formula type
MyQuestion = MsgBox(Prompt:="Fill formulas to last row?", _
            Buttons:=vbYesNo, Title:="???")

Debug.Print "Dim ws as Worksheet" 'change this as needed
Debug.Print "Set ws = Activesheet" 'change this as needed
Debug.Print "LastRow = ws.Cells(Rows.Count,1).End(xlUp).Row" 'change this as needed
Debug.Print "With ws" 'change this as needed

For Each rng In rng
    MyColumn = rng.Column
    CurrentRow = rng.Row
    Select Case MyQuestion
        Case vbYes
            LastRow = "LastRow"
        Case vbNo
            LastRow = CurrentRow
    End Select
    MyRange = ".Range(.Cells(" & CurrentRow & "," & MyColumn & "),.Cells(" & LastRow & "," & MyColumn & "))="
    MyFormula = rng.FormulaR1C1
    MyFormula = Replace(MyFormula, vbDoubleQuote, vbQuadrupleQuote)
    MyString = MyRange & vbDoubleQuote & MyFormula & vbDoubleQuote
    Debug.Print MyString
Next rng

Debug.Print "End With"

MsgBox "See Immediate Window in VBA", vbInformation, ": )"

OuttaHere:
End Sub


texts:
I've been writing code to get the frequencies of elements of an array. The code works, but it uses a lot of "old style" C constructs, some of which I feel should be changed to more C++-like features, but I don't know exactly which way would be best. In general, I feel that a lot of the code could be improved to be more elegant.

The first two functions, remdups and freq, are helper functions for getFrequencies, which is "facade" of the API.

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

template <class T> void remdups(T *arr, size_t *n)
{
    for (size_t i = 1; i < *n; ) {
        if (arr[i] == arr[i-1]) {
            memmove(arr + i - 1, arr + i, (*n-i) * sizeof (T));
            --*n;
        } else
            ++i;
    }
}

int *freq(const int *arr, size_t n, size_t *outN)
{
    int *freq = new int[n], cnt;

    for (size_t i = *outN = 0; i < n; ++i) {
        freq[i] = -1;
        cnt = 1;
        for (size_t j = i + 1; j < n; ++j) {
            if (arr[i] == arr[j]) {
                ++cnt;
                freq[j] = 0;
            }
        }
        if (freq[i] != 0) {
            freq[i] = cnt;
            ++*outN;
        }
    }

    // remove duplicate frequency entries
    remdups<int>(freq, outN);
    return freq;
}

std::vector<std::pair<int, size_t>> getFrequencies(std::vector<int> arr)
{
    size_t n = arr.size(), newSize;
    int *freqs = freq(&arr[0], n, &newSize);

    // remove duplicate values from the array
    remdups(&arr[0], &newSize);

    std::vector<std::pair<int, size_t>> ret;

    for (size_t i = 0; i < newSize; ++i)
        ret.push_back(std::pair<int, size_t> { arr[i], freqs[i] });

    delete []freqs;
    return ret;
}

Example driver code:

int main()
{
    std::vector<int> v = { 5, -3, -3, -3, -2, 0, 0 };
    auto freqs = getFrequencies(v);

    printf("%8s %8s\n", "Elem.", "Freq.");
    for (auto it = freqs.cbegin(); it != freqs.cend(); ++it)
        printf("%8d %8zu\n", it->first, it->second);
}


texts: Shorter way of writing my displayError() function?

texts:
Is there a way I can write this function with less code?

jQuery

function displayError(display, string, xhr) {
    var args = arguments;
    var $error = $("div#error");
    var visible = $error.is(":visible");

    if(args.length == 1 && typeof display === "boolean" && display == false) {
        if(visible) {
            $error.slideUp();
        }
    } else if(args.length == 2 && typeof display === "boolean" && display == true && typeof string == "string") {
        if(visible) {
            $error.fadeOut(function () {
                $(this).html('(!) '+string).fadeIn();
            });
        } else {
            $error.html('(!) '+string).slideDown();
        }
    } else if(args.length == 3 && typeof display === "boolean" && display == true && typeof string == "string" && typeof xhr === "object") {
        if(visible) {
            $error.fadeOut(function () {
                $(this).html('('+xhr.status+") "+string).fadeIn();
            });
        } else {
            $error.html('('+xhr.status+") "+string).slideDown();
        }
    }
}

Based on Marco's answer I came up with this:

function displayError(display, string, xhr) {
    var $error = $("div#error");
    var errVisible = $error.is(":visible");
    var errStatus = typeof xhr === "object" ? xhr.status : "!";
    var errMsg = '(' + errStatus + ") " + string;

    if(display) {
        if(errVisible) {
            $error.fadeOut(function() {
                $(this).html(errMsg).fadeIn();
            });
        } else {
            $error.html(errMsg).slideDown();
        }
    } else {
        $error.slideUp();
    }
}


texts: Is there a way to optimize this graphics/bitmap drawing code in C#?

texts:
I am not doing anything fancy so not sure if there are any tricks to make it faster.
It's a progress bar where I draw some numeric text on top. I only draw 1 pixel height image and then resize it. But not sure if there are better ways.
Here is the code:
    void DrawProgressBar ( PictureBox pb, int ratio, bool reverse, params string [ ] percentages )
    {
        Color color1 = this.DarkRed;
        Color color2 = this.DarkGreen;

        if ( reverse )
        {
            color1 = this.DarkGreen;
            color2 = this.DarkRed;
        }

        Bitmap bmp = new Bitmap ( 100, 1 );
        using ( Graphics g = Graphics.FromImage ( bmp ) )
        using ( SolidBrush brush = new SolidBrush ( color1 ) )
            g.FillRectangle ( brush, 0, 0, 100, 1 );

        for ( int i = 0 ; i < ratio ; ++i )
            bmp.SetPixel ( i, 0, color2 );

        Bitmap result = new Bitmap ( pb.Width + 2, pb.Height );
        Graphics g2 = Graphics.FromImage ( result );

        g2.InterpolationMode = InterpolationMode.NearestNeighbor;
        g2.DrawImage ( bmp, 0, 0, result.Width, result.Height + 23 );

        StringFormat strformat = new StringFormat ( );
        strformat.Alignment = StringAlignment.Center;
        strformat.LineAlignment = StringAlignment.Center;

        SolidBrush br = new SolidBrush ( Color.White );

        if ( percentages.Length > 1 )
        {
            decimal nratio = ratio / 100.0m;

            int w = ( int ) ( result.Width * nratio );
            Rectangle rect = new Rectangle ( 0, 0, w, result.Height );
            Rectangle rect2 = new Rectangle ( w, 0, ( int ) ( result.Width - w ), result.Height );

            if ( ratio > 5 )
                g2.DrawString ( percentages [ 0 ], this.dataListView.Font, br, rect, strformat );

            if ( 100 - ratio > 5 )
                g2.DrawString ( percentages [ 1 ], this.dataListView.Font, br, rect2, strformat );
        }
        else
        {
            Rectangle rect = new Rectangle ( 0, 0, result.Width, result.Height );
            g2.DrawString ( percentages [ 0 ], this.dataListView.Font, br, rect, strformat );
        }

        pb.Image = result;
    }


texts:
Here is a program that I've wrote to extract JPEGs from a file.  It reads a file that contains the image data and separates it into individual images.

import hashlib

inputfile = 'data.txt'
marker = chr(0xFF)+chr(0xD8)

# Input data
imagedump = file(inputfile, "rb").read()

imagedump = imagedump.split(marker)

count=0
for photo in imagedump:
    name = hashlib.sha256(photo).hexdigest()[0:16]+".jpg"
    file(name, "wb").write(marker+photo)
    count=count+1
    print count

The script names the identified images with their SHA256 digest, and all of the photos that it finds will be dumped into the current directory.

Here's how I test the script to see if it is working correctly:

Type cd ~/images/
create the folder mkdir test
dump some JPEGs into a singe file in the directory cat *.jpg > ./test/data.txt
cd test and put the script into the current directory
run the script python extract.py, and the JPEGs will be dumped into the current folder

How can I improve my script's performance?  Are there any problems with its operation?  The script does not know when an image ends; just when a new one starts.  Could this cause problems?


texts:
I am learning C++ and SFML so I want to know if I am laying my code out neatly and if my code is efficient. I know this is not a full game yet but I want to know if I am on the right tracks.

#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"

#include <iostream>

class Paddel {
    int speed = 3;
    sf::Vector2f border;
    sf::Vector2f size;
    sf::Vector2f position;
    sf::Vector2f screenSize;
public:
    sf::RectangleShape shape;

    Paddel(sf::Vector2f screenSize,int player)
    {
        this->screenSize = screenSize;
        this->size = sf::Vector2f(20,100);
        this->border = sf::Vector2f(8,6);

        if(player == 1)
            this->position = border;
        else if(player == 2) {
            position.x = (screenSize.x - size.x) - border.x;
            position.y = border.y;
        }

        this->shape.setSize(this->size);
        this->shape.setPosition(this->position);
    }

    void moveUp()
    {
        this->position.y -= this->speed;
        if(this->position.y < this->border.y)
            this->position.y += this->speed;
        this->shape.setPosition(this->position);
    }

    void moveDown()
    {
        this->position.y += this->speed;
        //100 - (600 + 5)
        if(this->position.y > (this->screenSize.y - this->border.y) - this->size.y)
            this->position.y -= this->speed;
        this->shape.setPosition(this->position);
    }
};

using std::cout;
using std::endl;

int main()
{
    sf::Vector2f screenSize(800,600);
    sf::RenderWindow Window(sf::VideoMode(screenSize.x,screenSize.y),"Ping Pong");
    Window.setFramerateLimit(60);
    Window.setVerticalSyncEnabled(true);

    Paddel playerOne(screenSize,1);
    Paddel playerTwo(screenSize,2);

    const sf::Time TimePerFrame = sf::seconds(1.f/60.f);
    sf::Clock clock;
    sf::Time timeSinceLastUpdate = sf::Time::Zero;
    sf::Time elapsedTime;

    bool play = true;

    while(Window.isOpen())
    {
        Window.clear();
        sf::Event Event;

        while(Window.pollEvent(Event))
        {
            if(Event.type == sf::Event::Closed)
                Window.close();
        }

        elapsedTime = clock.restart();
        timeSinceLastUpdate += elapsedTime;
        if(play){
            if(timeSinceLastUpdate > TimePerFrame){
                if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
                {
                    playerOne.moveUp();
                }
                if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
                {
                    playerOne.moveDown();
                }

                if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                {
                    playerTwo.moveUp();
                }
                if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                {
                    playerTwo.moveDown();
                }

                if(sf::Keyboard::isKeyPressed(sf::Keyboard::P))
                    play = false;
            }

            Window.draw(playerOne.shape);
            Window.draw(playerTwo.shape);

            Window.display();
        }
    }
}


texts: Deal three Poker hands of five cards each in Python

texts:
I'm a beginner at coding who recently started learning Python, and I think I have grasped the basics. Now I'm working on my first "proper" project in Python.

The problem is to have the program:

Generate a standard Poker deck of 52 cards (no Jokers)
Shuffle said deck
Deal five (5) cards to three (3) hands/"players" (can be altered when calling the 'deal' function)
Analyse the three hands individually for possible Poker hands in each

the analysis must be able to detect at least:

Two pairs
Straight
Flush
Straight Flush
(no harm in detecting any of the other Poker hands as well)

Print all three hands and their respective results/analyses

I've managed 1-3, but stalled at 4 and plan to continue with 4-5 later, but first I want to hear your thoughts on my code so far!

I managed to find several somewhat similar programs all over the Internet, of which I extracted many parts to my own program. I had to make a few adjustments here and there, as none of the existing programs had the exact same approach as mine, but this was a good thing in terms of my learning curve. In case you find a part of your own code in mine, consider it admiration, for I'm truly grateful for all the help and examples I've received from more seasoned coders' work.

My code:

import random

class Card(object):
    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    # Implementing build in methods so that you can print a card object
    def __unicode__(self):
        return self.show()
    def __str__(self):
        return self.show()
    def __repr__(self):
        return self.show()

    def show(self):
        if self.value == 1:
            val = "Ace"
        elif self.value == 11:
            val = "Jack"
        elif self.value == 12:
            val = "Queen"
        elif self.value == 13:
            val = "King"
        else:
            val = self.value

        return "{} of {}".format(val, self.suit)

class Deck(object):
    def __init__(self):
        self.cards = []
        self.build()

    # Display all cards in the deck
    def show(self):
        for card in self.cards:
            print(card.show())

    # Generate 52 cards
    def build(self):
        self.cards = []
        for suit in ['Hearts', 'Clubs', 'Diamonds', 'Spades']:
            for val in range(1,14):
                self.cards.append(Card(suit, val))

    # Shuffle the deck
    def shuffle(self, num=1):
        random.shuffle(self.cards)

    # Deal n cards to n players
    def deal(self, n_players, n_cards):
        self.hands = [self.cards[i:n_players*n_cards:n_players] for i in range(0, n_players)]

# Test making a Card
# card = Card('Spades', 6)
# print card

# Making a Deck
myDeck = Deck()
myDeck.shuffle()
#myDeck.show() # Print the shuffled deck if needed, to show it is actually shuffled
               # and that the cards are dealt from top of the deck and not randomly

myDeck.deal(3,5) #(No. of hands, no. of cards dealt per hand)
print(*myDeck.hands, sep = '\n')

Please do let me know what you think of the code in general, and if you think there is a more efficient way to have the cards dealt so that they are also easier to analyse later. All help is much appreciated!


texts: VBA Excel substitute function for multiple conditions at once

texts:
I use the SUBSTITUTE() function in my VBA code.
In Excel formula, we can nest it as shown in the thread below:
https://stackoverflow.com/questions/22313965/how-can-i-combine-multiple-nested-substitute-functions-in-excel/22314382
How can we do it in VBA Excel code?
How can I make my code smarter?
  For Each cell In rng
  cell = WorksheetFunction.Substitute(cell, " ", "  ", 25)
  cell = WorksheetFunction.Substitute(cell, " ", "  ", 24)
  cell = WorksheetFunction.Substitute(cell, " ", "  ", 23)
  Next


texts:
I have a table that looks like this

Directory nvarchar(max)
Extension nvarchar(10)
Length bigint

I also have another table that provides the type of file (lookup table)
extension nvarchar(10)
FileType nvarchar(50)

That being said I have a correlated subquery I wanted to migrate to a sproc that takes in the levels from the root and gives you back the directories and their file types at that specific level.  There are about 400k rows in the main table and about 800 extensions in the lookup table.

The query is this:

declare @levelsFromRoot as int = 7
--declare @auditName as varchar(max) = 'Aetna'

select
    ef.Type,
    sf.Directory,
    (select count(distinct part)
     FROM dbo.vwAuditView
     cross APPLY dbo.SplitPath( substring([Directory],1,LEN([Directory])

                        -CHARINDEX('\',REVERSE([Directory]))) ,'\') AS Results
                                where Directory = sf.Directory) as [LevelsFromRoot]
from dbo.FS02V_SourceFiles sf
inner join dbo.ExtensionFix ef
    on sf.Extension = ef.Extension
Where (select count(distinct part)
     FROM dbo.vwAuditView
     cross APPLY dbo.SplitPath( substring([Directory],1,LEN([Directory])

                        -CHARINDEX('\',REVERSE([Directory]))) ,'\') AS Results
                                where Directory = sf.Directory) = @levelsFromRoot
order by Directory asc

The cross apply section in the subquery counts the levels in each path starting from the root.  you should be able to pass in how many levels from the root and pass back a list of directories at that level and their corresponding file types.  This query has already been running 25 minutes.  It is returning data to me.  Is there anything I can do to improve this one?  I'm fairly new at correlated subqueries and figure I am doing something wrong here.

For clarity the view looks like this:

select    Directory
        --, ef.Extension
        , ef.Type
        , sum(Length) as [Size - Bytes]
from dbo.FS02V_SourceFiles sf
INNER JOIN dbo.ExtensionFix ef
    on sf.Extension = ef.Extension
group by ef.type, Directory


texts: What do you think of my regex for URL validation?

texts:
I would like you to review my regex.  It's suppose to recognize common URLs like:

http://www.google.com
http://www.sub1.sub2.google.com
https://www.google.com
http://www.google.com/path1/path2
http://www.google.com/path1/path2/
http://www.google.com/path1/path2/a=b&c=d
http://www.google.com/path1/path2/a=b&c=d/

var url = new RegExp("^(?:https?:\/\/)?(?:[-a-z0-9]+\\.)+[-a-z0-9]+(?:(?:(?:\/[-=&?.#a-z0-9]+)+)\/?)?$");


texts:
I often need to return empty collections.
One of those days I wrote the following to return a cached instance:

public static class Array<T>
{
    // As a static field, it gets created only once for every type.
    public static readonly T[] Empty = new T[0];
}

I didn't know about Enumerable<T>.Empty() maybe it didn't exist back then. Although I know now, I still use this one.

There are still many functions in BCL that need an array instead of IEnumerable<T>, IList<T> or IReadOnlyList<T>. And array implements all of these so it can be used anywhere.

// All these variables share the same array's reference.
string[]            empty1 = Array<string>.Empty;
IEnumerable         empty2 = Array<string>.Empty;
IEnumerable<string> empty3 = Array<string>.Empty;

What do you think about this class?
Can you see any other advantages/disadvantages of it over Enumerable<T>.Empty()?

And about implementation:
Do you think making the caching using a static field would cause any problem?

Edit: Array class now has a static, generic Empty method, essentially deprecating this implementation.


texts:
I have the Repository below, but I have noticed that there is a recurrent pattern try / catch which does not seem to be that clean, is there a better way to achieve or to extract that sort logic elsewhere?

public class FlightRepository : IFlightRepository
{
    private readonly FlightManagerDbContext _context;

    public FlightRepository(FlightManagerDbContext context)
    {
        _context = context;
    }

    public Result CreateFlight(Flight flight)
    {
        try
        {
            var tmp = _context.Flight.FirstOrDefault(f => f.Code == flight.Code);
            if (tmp != null)
                return Result.Conflict($"Flight {flight.Code} already exists");
            _context.Flight.Add(flight);
            _context.SaveChanges();
            return Result.Ok("Flight successfully saved");
        }
        catch (Exception e)
        {
            return Result.Fail(new List<string>() {$"An error occured, {e.Message}"});
        }
    }

    public Result UpdateFlight(Flight flight)
    {
        try
        {
            var tmp = _context.Flight.FirstOrDefault(f => f.Code == flight.Code);
            if (tmp == null)
                return Result.NotFound($"Flight { flight.Code} not found");

            var toUpdate = _context.Flight.First(f => f.Code == flight.Code);
            toUpdate.Distance = flight.Distance;
            toUpdate.DepartureLatitude = flight.DepartureLatitude;
            toUpdate.DepartureLongitude = flight.DepartureLongitude;
            toUpdate.DepartureName = flight.DepartureName;
            toUpdate.DepartureTime = flight.DepartureTime;
            toUpdate.ArrivalLatitude = flight.ArrivalLatitude;
            toUpdate.ArrivalLongitude = flight.ArrivalLongitude;
            toUpdate.ArrivalName = flight.ArrivalName;
            toUpdate.ArrivalTime = flight.ArrivalTime;
            toUpdate.ConsumptionPerKm = flight.ConsumptionPerKm;
            toUpdate.TakeOffEffort = flight.TakeOffEffort;
            toUpdate.FlightTime = flight.FlightTime;
            toUpdate.FuelNeeded = flight.FuelNeeded;

            _context.SaveChanges();

            return  Result.Ok($"Flight {flight.Code} successfully updated");
        }
        catch (Exception e)
        {
            return Result.Fail(new List<string>() {$"An error occured, {e.Message}"});
        }
    }

    public Result<Flight> SelectFlight(string code)
    {
        try
        {
            var flight = _context.Flight.FirstOrDefault(f => f.Code == code);
            if (flight == null)
                return Result<Flight>.NotFound($"Flight {code} not found");
            return  Result<Flight>.Ok(flight);
        }
        catch (Exception e)
        {
            return Result<Flight>.Fail(new List<string>(){$"An error occured, {e.Message}"});
        }
    }

    public Result<List<Flight>> SelectFlights()
    {
        try
        {
            return Result<List<Flight>>.Ok(_context.Flight.Any()
                ? _context.Flight.ToList()
                : new List<Flight>());
        }
        catch (Exception e)
        {
            return Result<List<Flight>>.Fail(new List<string>() {$"An error occured,{e.Message}"});
        }
    }
}


texts: Is this a proper use of a services project and an ASP.NET MVC controller?

texts:
I'm a little unsure as to what code belongs in the services and what belongs in the controllers.

Lets say I'm creating a website that requires a fine grained level of permissions (e.g. a user has permissions based on their user level (if they're currently logged in) determining whether they can view, edit, add entities and each entity has it's own set of requirements).

The process is pretty much the same for all entities:

Get the current user, either a registered one or an anonymous one
Get the requested entity

Check that it is not null
Check it isn't locked by the system

Check that the user has permissions to view/edit on the entity, as well as all parent entities

So, what should go where?

Right now, my controller makes a call to the service to get the entity and passes in the user (or null for anonymous).

The service makes a call to the repository which gets the entity by the id. Then it makes sure that the user has permission to view it. The code is basically:

// Controller
public ActionResult Get(int id)
{
    string error;
    var entity = EntityService.Get(id, GetUser(), out error);
    if(entity == null)
      // Display error
    else
      // Display entity
}

// Service
public Entity Get(int id, User user, out string error)
{
   var entity = Repository.Get(id);
   // null check
   // permissions check
   // if it passes, return the entity, otherwise assign error and return null
}

I don't really like this way of doing it because if I need to do something like redirect the user or display a custom view, I can't just return an error string, I need an enum or something to tell me exactly why the Get failed so I can handle the case properly. Plus (and I'm not sure if this is actually considered a bad thing) whatever is going on in the services method is hidden from the controller.

Any suggestions on a better design?


texts:
I am working an a more meaningful way to print objects in VBA.  The desired result should look something like this.

Console.PrintLine List.Create(1, 2, 3)
List(1, 2, 3)

The concept is that objects implementing an IPrintable interface are printed as their ToString property.  Primitive data types are printed as is

Console.PrintLine "a"
a

And other objects are represented as "TypeName(&ObjPtr)"

Console.PrintLine New Collection
Collection(&150653720)

But the issue that is gunking up my design is that I want nested objects to represent themselves

Console.PrintLine List.Create(1, List.Create(), New Collection)
List(1, List(), Collection(&150653384))

My solution is to use an auxiliary helper methods, located in a standard module called cast, which in a way provides a default implementation of IPrintable

Public Function ToString(ByVal x As Variant) As String

    Dim result As String

    If TypeOf x Is IPrintable Then
        result = x.ToString
    ElseIf IsObject(x) Then
        result = DefaultObjectToString(x)
    Else
        result = CStr(x)
    End If

    ToString = result

End Function
Private Function DefaultObjectToString(ByVal x As Object) As String

    DefaultObjectToString = ObjectToString(x, cast.CArray(Array("&" & ObjPtr(x))))

End Function
Public Function ObjectToString(ByVal o As Object, ByRef members() As Variant, _
        Optional ByVal delim As String = ", ") As String

    Dim stringMembers() As String
    If LBound(members) <= UBound(members) Then
        ReDim stringMembers(LBound(members) To UBound(members))
    End If

    Dim i As Long
    For i = LBound(members) To UBound(members)
        stringMembers(i) = ToString(members(i))
    Next i

    ObjectToString = TypeName(o) & "(" & Join(stringMembers, delim) & ")"

End Function

I would want this to be located in the IPrintable class but that must be empty to use it as an interface.

Now any method that is printing the objects can just use cast.ToString like console does

Public Sub PrintLine(Optional ByVal x As Variant)

    If IsMissing(x) Then
        Debug.Print vbNullString
    Else
        Debug.Print cast.ToString(x)
    End If

End Sub

Also here is how List implements IPrintable (ToArray is just an array version of the list.)

Public Property Get ToString(Optional delim As String = ", ") As String

    ToString = cast.ObjectToString(Me, ToArray, delim)

End Property
Public Property Get IPrintable_ToString() As String

    IPrintable_ToString = ToString()

End Property

If I had a BinaryTree object it would look like this.

Public Property Get ToString() As String

    ToString = cast.ObjectToString(Me, Array(LeftTree, RightTree), ", ")

End Property


texts: Would you utilise "Using" on a member which is going to be added to a list?

texts:
I have an interface and a concrete class which I am using in the code below:

    /// <summary>
    /// Converts a DataSet read from the DB to a list of objects of a type
    /// TemplatePart.
    /// </summary>
    /// <param name="templatePartDataSet">DataSet containing the information.
    /// </param>
    /// <returns>List of unprocessed TemplateParts.</returns>
    private static List<ITemplatePart> DataSetToTemplatePart(DataSet templatePartDataSet)
    {
        var rawTemplateParts = new List<ITemplatePart>();
        foreach (DataTable table in templatePartDataSet.Tables)
        {
            var tableName = table.ToString();

            foreach (DataRow row in table.Rows)
            {
                if (string.IsNullOrEmpty(
                    row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName)))
                {
                    continue;
                }

                // THE LINE RELATED TO MY QUESTION.
                var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row);
                rawTemplateParts.Add(rawTemplatePart);
            }
        }
        return rawTemplateParts;
    }

TemplatePart is a simple class with 4 properties with the definition of:

{
    public class TemplatePart : ITemplatePart
    {
        #region Creator

        internal static TemplatePart CreateTemplatePart(DataTable table, DataRow row)
        {
            return new TemplatePart
            {
                PartName = row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName),
                BasePart = row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart)
            };
        }

        #endregion // Creator

        #region Public Properties

        public string PartName { get; set; }
        public string BasePart { get; set; }
        public double? PriceDom { get; set; }
        public double? PriceInt { get; set; }

        #endregion // Public Properties
    }
}

and the ITemplatePart as:

namespace PriorityPriceGenerator2.Model.TemplatePart
{
    interface ITemplatePart
    {
    }
}

of course the interface hasn't been implemented completely. And also the concrete class doesn't have the IDisposable yet.

Would you prefer (/if it's necessary or even totally wrong) to do such thing in the marked line.

using (var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row))
    rawTemplateParts.Add(rawTemplatePart);

And why? I want to know what happens to a member added to the list which is in the Using. Would it get destroyed and recreated in the List? Would it get destroyed because of using after I am done with the List ?

And please,
let me know if you see any other issues.