texts: Entity Framework - Table structure, navigating many descendants, etc

texts:
Someone suggested to try asking this here instead of stackoverflow, so I'm taking their advice.

So I'm rewriting a dated application and trying to structure things the right way. I have a Category > Product > Part > Options basic structure, but there are multiple layers in each and I don't know how to simplify my data structure, and navigate children effectively.

I feel like it's a little complicated for e-commerce, but we have a multitude of product, part, and part options.

So just for kicks I tried to see if I could round up all the data from a top level category all the way down to the swatches for the different part options to see if an entire page could display the entire category/product line at once (I know not to do this in production). The immediate problem I ran into was including all the descendants in my LINQ queries, as there are several that require intermediary objects due to the extra columns in the relational tables. That's necessary, I understand, but it gets messy quickly as this is setup to have a potentially unlimited number of category/subcategory levels. For example:

IQueryable<Category> Categories = Context.CategoryHierarchies
    .Where(w => w.ParentCategoryId == null)
    .Where(w => w.Active == true)
    .OrderBy(o => o.Sort)
    .Select(s => s.Category)
    .Include(x => x.ParentCategories)
    .Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .Include(x => x.CategoryProducts).ThenInclude(x => x.Products)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartStyles).ThenInclude(x => x.Swatch)

    // I can follow the chain down but will need a second one to
    // get to other parts of the tree, such as product themes and the
    // two other part options, and currently this is only for the
    // current category. Doing sub categories would be ideal, but that,
    // assuming there's never more than 2 sub-category levels, still
    // triples the size of this stupid-large query.

    .Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .Include(x => x.CategoryProducts).ThenInclude(x => x.Products)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartStyles).ThenInclude(x => x.Swatch)

    // etc..

I didn't do lambas on the includes to keep things shorter for the paste. Now obviously this could go on even longer as I didn't get into the part options, but from there, I would potentially need to have 3 more lines for each level of part option, right? Like:

.Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .ThenInclude(x => x.CategoryProducts).ThenInclude(x => x.Product)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartMaterials).ThenInclude(x => x.Swatch))

.Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .ThenInclude(x => x.CategoryProducts).ThenInclude(x => x.Product)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartFinishes).ThenInclude(x => x.Swatch))

All the way down. Yikes. So for my question, when I'm loading my ViewModels into a view, and I want to access categories, products, and potentially parts, is there a better way to do this? I have a view that does a foreach on each level that I can, but it starts getting tedious real fast. Do I just load them all as separate objects in the view model and access them directly, and populated through separate queries? I'm pretty new to this and would really appreciate anyone's suggestions.

I did see the .NET Core .ThenInclude() stuff, which does look helpful, but I wasn't completely sure it would clean things up that much. It's a lot of descending.

edit: put lambdas back in. Still not a full query, but readers can use their imaginations as to how large it could potentially be for my hypothetical.


texts:
Given a string S, find the number of "unordered anagrammatic pairs"
  of substrings.

  Input Format

  First line contains T, the number of testcases. Each testcase
  consists of string S in one line.

  Output Format

  For each testcase, print the required answer in one line.

  Sample Input#00

2
abba
abcd

  Sample Output#00

4
0

In the below code I am finding all the possible sub strings and then checking all the pairs of equal length to check if they are anagrams or not.

public class Solution {
    private static int N = 26;

    private static boolean isAnagram(String a, String b) {
        int []countA = new int[N];
        int []countB = new int[N];

        for (char c : a.toCharArray()) {
            countA[c - 'a']++;
        }

        for (char c : b.toCharArray()) {
            countB[c - 'a']++;
        }

        for (int i = 0; i < N; i++) {
            if (countA[i] != countB[i]) {
                return false;
            }
        }

        return true;
    }

    private static int getPairsCount(String text) {
        int count = 0;
        int length = text.length();

        List<String> subsets = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            for (int j = 1; j <= length - i; j++) {
                subsets.add(text.substring(i, i + j));
            }
        }

        for (int i = 0; i < subsets.size(); i++) {
            for (int j = i + 1; j < subsets.size(); j++) {
                String s1 = subsets.get(i);
                String s2 = subsets.get(j);
                if (i != j &&
                    s1.length() == s2.length() &&
                    isAnagram(s1, s2)) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();

        for (int i = 0; i < N; i++) {
            System.out.println(getPairsCount(s.next()));
        }
    }
}

Questions:

I have to agree it took me a lot of time to find the above solution because I spend a lot of time into finding the linear algorithm. For this solution I think that it's \$\mathcal{O}(n^3)\$ solution which feels slow to me.

I need to know how to approach problems like these? when to know that there can't be any linear algorithm possible?


texts:
I'm working on some testing project. For some reason I think I'm doing something wrong with the architecture. I have a simple example to show what I mean.

Database class

Imports DAO
Imports System.Data.SqlClient

Public Class PatientDB

    Dim connectionString As String = "Data Source=GSABBOZMAINPC;Initial Catalog=TestDB;Integrated Security=True"

    Public Function GetAllPatientFromDB() As List(Of PatientDAO)

        Using connection As New SqlConnection(connectionString)

            Dim list As New List(Of PatientDAO)

            Dim sqlString As String = "select * from patient ;"

            Using Command As New SqlCommand(sqlString, connection)

                connection.Open()

                Using reader As SqlDataReader = Command.ExecuteReader

                    While reader.Read

                        Dim firstName As String = reader("firstnamePT").ToString()

                        Dim Name As String = reader("naamPT").ToString()

                        Dim patient As New PatientDAO(Name, firstName)

                        list.Add(patient)

                    End While

                End Using

                Return list

            End Using

        End Using

    End Function

End Class

PatientDAO

Public Class PatientDAO

    Private _name As String
    Private _lastname As String

    Sub New(naam As String, lastname As String)

        _name = naam
        _lastname = lastname

    End Sub

    Public ReadOnly Property Name As String
        Get
            Return _name
        End Get
    End Property

    Public ReadOnly Property Lastname As String
        Get

            Return _lastname

        End Get
    End Property

End Class

Patient

Imports DAO
Imports database_layer

    Public Class Patient

        Property naam As String

        Property lastname As String

        Sub New()

        End Sub

        Sub New(_naam As String, _lastname As String)

            naam = _naam

            lastname = _lastname

        End Sub

        Public Sub New(patientDAO As PatientDAO)

            naam = patientDAO.Name
            lastname = patientDAO.Lastname

        End Sub

        Public Function GetDO() As PatientDAO

            Return New PatientDAO(naam, lastname)

        End Function

        Public Function getAllPatientsInList() As List(Of Patient)

            Dim list As New List(Of Patient)
            Dim database As New PatientDB

            For Each PatientDAO As PatientDAO In database.GetAllPatientFromDB()

                Dim patient As New Patient(PatientDAO)
                list.Add(patient)
            Next

            Return list

        End Function

        Public Overrides Function ToString() As String
            Return naam + " " + lastname
        End Function

    End Class

In this example I'm using Windows form. When the form is loaded I use the following event:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim patient As New Patient

    For Each item As Patient In patient.getAllPatientsInList()

        list.Add(item)

    Next

End Sub

Should I use Dim patient As New Patient with an empty constructor like this example or should I approach this another way? And are there other suggestions you think would improve the architecture of this example?


texts: Is it fine to typecast from one implementation type to another while using an object?

texts:
I've a simple code base with few 'weapon' concrete classes which implements different contracts in order to be used by its clients.

My contracts:

public interface IWeaponPrimaryAttack
{
    void DoAttack();
}
public interface IWeaponSecondaryAttack
{
    void DoSecondaryAttack();
}
public interface IReloadable
{
    void Reload();
}

Concrete implementation or the actual weapons:

public class Katana : IWeaponPrimaryAttack, IWeaponSecondaryAttack
{
    public void DoAttack(){Console.WriteLine ("Swing");}
    public void DoSecondaryAttack() {Console.WriteLine ("Stab");}
}
public class ShotGun : IWeaponPrimaryAttack, IReloadable
{
    public void DoAttack(){Console.WriteLine ("Swing");}
    public void Reload() {//reload it}
}

Clients that uses these concrete classes:

public class PrimaryAttack
{
    private IWeaponPrimaryAttack _attack;
    public PrimaryAttack(IWeaponPrimaryAttack attack)
    {
        _attack = attack;
    }
    public void DoAttack()
    {
        _attack.DoAttack();
    }
}
public class SecondaryAttack
{
    private IWeaponSecondaryAttack _attack;
    public SecondaryAttack(IWeaponSecondaryAttack attack)
    {
        _attack = attack;
    }
    public void DoSecondaryAttack()
    {
        _attack.DoSecondaryAttack();
    }
}
public class WeaponReload
{
    private IReloadable _reloader;
    public WeaponReload(IReloadable reloader)
    {
        _reloader = reloader;
    }
    public void Reload()
    {
        _reloader.Reload();
    }
}

New of course the instantiation of concrete class only be known when the user selects one among many weapons(one among ShotGun, Katana, etc).

Let say the use has selected ShotGun as the weapon, based on the selection it might go like this:

IWeaponPrimaryAttack weapon = new ShotGun(); // get it from a factory
PrimaryAttack primaryAttack = new PrimaryAttack(weapon);
primaryAttack.DoAttack();

Now for the WeaponReload have to do a typecast here in order to use it.

WeaponReload reloader = new WeaponReload ((IReloadable)weapon);
reloader.Reload();

I have questions around it,

Should I really have to end up typecasting eventually?
Or there is a better way to handle this object creation part.
Or there is entirely a better design that I can come up with which
does not necessarily ends up in casting.
Or casting it like this is totally fine.


texts: Access View from current/corresponding ViewModel

texts:
Sometimes when developing a WPF application, I need to access a certain Window (View) from the corresponding ViewModel, to perform or fire a method like this for example:

//In the MainWindowViewModel
MainWindowView.Hide();

But that's not really easy, and even it violates MVVM because the ViewModel shouldn't know anything about the View, so I started doing this instead:

//In the MainWindowViewModel
Application.Current.MainWindow.Hide();

This becomes impractical when dealing with other Windows (Views):

//In the AnotherWindowView
Application.Current.Windows.OfType<AnotherWindowView>().First().Hide();

So I decided to make a solution, a helper class, in which, using a method, I give the ViewModel and I get back the corresponding View, using the DataContext of the View, the solution looks like this:

The Class:

public static class ViewsAccessibility
{
    public static Window GetCorresponingWindow(ViewModelBase viewModel)
    {
        var windowAccessibility = new WindowAccessibility(viewModel);
        return windowAccessibility.CorrespondanteWindow;
    }

    private class WindowAccessibility
    {
        public Window CorrespondanteWindow { get; private set; }

        public WindowAccessibility(ViewModelBase viewModel)
        {
            var windows = Application.Current.Windows.OfType<Window>();
            CorrespondanteWindow = (from window in windows
                                      where window.DataContext.Equals(viewModel)
                                      select window).First();
        }
    }
}

The use:

//In the MainWindowViewModel
ViewsAccessibility.GetCorresponingWindow(this).Hide();

Is this a good practice and does it violate MVVM or not?


texts: A Simple Media Generator with Directional Control

texts:
My goal was to have a single page display bulk amounts of media without the need to load new pages. I also wanted it to be able to load fast, so the generator uses a JavaScript array to display one item at a time. The user can move through the array backwards and forwards with the use of two buttons.
Images, video and audio can be added as strings in the following ways:

'<video controls source src="FILE.mp4" type="video/mp4"></video>',
'',
'<audio controls source src="FILE.mp3" type="audio/mpeg"></audio>',

const array = [
    '',
    '
Text\
Hello I am text
',
    '<video controls source src="FILE.mp4" type="video/mp4"></video>',
    '',
    '<audio controls source src="FILE.mp3" type="audio/mpeg"></audio>',

];
//variables
const arrayLength = array.length;
var For = -1;

function backForth(ev) {
    if(ev.target.className == "buttonS") {
        const output = document.querySelector('output');
        let increment = (ev.target.textContent == "Back" ? -1 : 1);
        For = (For + increment + arrayLength) % arrayLength;
        output.innerHTML = array[For];
        document.getElementById('counter').innerHTML = For + '&nbsp;/&nbsp;' + (arrayLength - 1);
}}
document.addEventListener('click', backForth);
backForth({target:{className: "buttonS"}});

    <output></output>

        <button class="buttonS">Back</button>

        <button class="buttonS">Forth</button>


texts: HackerRank challenge to count ways to climb a staircase, solved using Java Fork Join

texts:
I'm trying to solve Stair case recursion problem on HackerRank. The problem is to find all possible ways for a child to climb a stair case with height n given that he can jump 1, 2 or 3 steps at a time.

I'm using java Fork join to enhance performance but unfortunately it still slow.  My approach is as follows:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class RecursiveStairCase extends RecursiveTask<Integer> {

/**
 *
 */
private static final long serialVersionUID = 1L;
private Integer stairHeight;

public RecursiveStairCase(Integer stairHeight) {
    this.stairHeight = stairHeight;
}

@Override
protected Integer compute() {
    return getStairClimbPossibleWays(stairHeight);
}

static int getStairClimbPossibleWays(int stairHeight) {

    if (stairHeight < 0)
        return 0;

    if (stairHeight == 1 || stairHeight == 0)
        return 1;

    return getStairClimbPossibleWays(stairHeight - 1)
            + getStairClimbPossibleWays(stairHeight - 2)
            + getStairClimbPossibleWays(stairHeight - 3);
}

private List<RecursiveStairCase> createSubtasks() {
    List<RecursiveStairCase> subtasks = new ArrayList<RecursiveStairCase>();

    RecursiveStairCase subtask1 = new RecursiveStairCase(stairHeight - 1);
    RecursiveStairCase subtask2 = new RecursiveStairCase(stairHeight - 2);
    RecursiveStairCase subtask3 = new RecursiveStairCase(stairHeight - 3);

    subtask1.fork();
    subtask2.fork();
    subtask3.fork();

    subtasks.add(subtask1);
    subtasks.add(subtask2);
    subtasks.add(subtask3);

    return subtasks;
}

public static void main(String[] args) {
    Integer result = 0;
    long startTime = System.currentTimeMillis();
    int[] numbers = new int[] { 32, 33, 35, 36, 36 };
    for(int i=0;i<numbers.length;i++){
    result = 0;
    final RecursiveStairCase recursiveStairCase = new RecursiveStairCase(36);
    List<RecursiveStairCase> recursiveStairCases = recursiveStairCase
            .createSubtasks();
    for (RecursiveStairCase recursiveStairCaseThread : recursiveStairCases) {
        result += recursiveStairCaseThread.join();
    }
    System.out.println(result);
    }
    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    System.out.println("Consumed:" + elapsedTime);
}
}

I recorded the following test cases/time consumed pairs (which is refused by HackerRank (timed out)).

Test Case #5 {35,30,33,36,20}-->9.47 sec
Test Case #8 {32,33,35,36,36}-->15.531 sec

I need your advice to make it perform faster.


texts: Golang tool to check public repositories list in Github

texts:
Didn't post on the Codereview for a while but trying to learn Golang now and wrote my first utility a few days ago and will be glad to see what I did wrong here and what can be done better.

  This tool is used to check public repositories in out GitHub
  organization and compare such a list with another list which contains
  repositories that are allowed to be public. If any differences will be found between both lists - it will send an alarm to Slack.

I googled and tried a lot of solutions to make slices comparison but finally had to write own loop.

The main thing I'm thinking about now is to use map[] instead of two for loops and working about it now.

The main() function:

func main() {

    client := github.NewClient(nil)

    opt := &github.RepositoryListByOrgOptions{Type: "public"}
    // get our public repositories list to the repos variable
    repos, _, _ := client.Repositories.ListByOrg(context.Background(), os.Getenv("GITHUB_ORG_NAME"), opt)

    // the list of repositories that are expected to be public
    allowedRepos := strings.Fields(os.Getenv("ALLOWED_REPOS"))

    for _, repo := range repos {
        fmt.Printf("\nChecking %s\n", *repo.Name)
        if isAllowedRepo(*repo.Name, allowedRepos) {
            fmt.Printf("OK: repo %s found in Allowed\n", *repo.Name)
        } else {
            fmt.Printf("ALARM: repo %s was NOT found in Allowed!\n", *repo.Name)
            sendSlackAlarm(*repo.Name, *repo.HTMLURL)
        }
    }
}

And it uses isAllowedRepo() to check if values are identical:

func isAllowedRepo(repoName string, allowedRepos []string) bool {

    // and just iterate the repoName over the allowedRepos list
    for _, i := range allowedRepos {
        if i == repoName {
            return true
        }
    }

    return false
}

Te full code can be seen here.


texts:
I am experimenting with ECS design and I am looking for a solid way to implement a message bus for use between the different systems.
Here is a stripped-down version of my current implementation:

#include <iostream>
#include <cstdlib>
#include <functional>
#include <vector>

struct BaseEvent
{
    static size_t type_count;
    virtual ~BaseEvent() {}
};

size_t BaseEvent::type_count = 0;

template <typename EventType>
struct Event : BaseEvent
{
    static size_t type()
    {
        static size_t t_type = type_count++;
        return t_type;
    }
};

struct EventManager
{
    template <class EventType>
    using call_type = std::function<void(const EventType&)>;

    template <typename EventType>
    void subscribe(call_type<EventType> callable)
    {
        if (EventType::type() >= m_subscribers.size())
            m_subscribers.resize(EventType::type()+1);
        m_subscribers[EventType::type()].push_back(
            CallbackWrapper<EventType>(callable));
    }

    template <typename EventType>
    void emit(const EventType& event)
    {
        if (EventType::type() >= m_subscribers.size())
            m_subscribers.resize(EventType::type()+1);
        for (auto& receiver : m_subscribers[EventType::type()])
            receiver(event);

    }

    template <typename EventType>
    struct CallbackWrapper
    {
        CallbackWrapper(call_type<EventType> callable) : m_callable(callable) {}
        void operator() (const BaseEvent& event) { m_callable(static_cast<const EventType&>(event)); }
        call_type<EventType> m_callable;
    };

    std::vector<std::vector<call_type<BaseEvent>>> m_subscribers;
};

The classes are then used like so:

struct PLAYER_LVL_UP : Event<PLAYER_LVL_UP>
{ int new_level; };

struct PLAYER_HIT : Event<PLAYER_HIT>
{ int damage; };

struct COLLISION : Event<COLISSION>
{ Entity entity1; Entity entity2; };

struct PLAYER_GUI
{

    PLAYER_GUI(EventManager& em, ...) : ...
    {
        using namespace std::placeholders;

        em.subscribe<PLAYER_HIT>(
            std::bind(&PLAYER_GUI::handle_hit, this, _1);
        em.subscribe<PLAYER_LVL_UP>(
            std::bind(&PLAYER_GUI::handle_lvl_up, this, _1);
        .
        .
    }

    void handle_hit(const PLAYER_HIT& event)
    {
         // change rendering of life/player in the gui
    }

    void handle_lvl_up(const PLAYER_LVL_UP& event)
    {
        // change rendering of the lvl in the gui
    }

    ...
};

struct CollisionSystem : public System<CollisionSystem>
{
     .
     .
     void update(EventManager& em, float dt)
     {
         .
         .
         if (collides(entity1, entity2))
             em.emit(COLLISION{entity1, entity2});
     }
};

Obviously, this code snippet lacks a lot of things but at the moment I am mostly concerned with the approach taken. Specifically, I am not particularly sure about using static functions to map the event types to integers. I would really appreciate some general guidance in the right direction!


texts: Project Euler # 67 Maximum path sum II (Bottom up) in Python

texts:
This is Project Euler #67: Maximum path sum II:

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

  3
  7 4
  2 4 6
  8 5 9 3

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

  Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text
  file containing a triangle with one-hundred rows.

  NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this
  problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take
  over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

I previously posted a solution to problem 18 using a greedy algorithm, here's the optimal solution using bottom up recursion.

from time import time

def get_triangle(triangle_filename):
    """Return a list of lists containing rows of the triangle."""
    triangle = open(triangle_filename).read().split('\n')
    triangle = [[int(number) for number in row.split()] for row in triangle]
    return triangle

def maximize_triangle(triangle, start_index=-1):
    """Return the maximum triangle path sum(bottom up)."""
    if start_index == - len(triangle):
        return triangle[0][0]
    for index in range(len(triangle[start_index]) - 1):
        maximum = max(triangle[start_index][index], triangle[start_index][index + 1])
        triangle[start_index - 1][index] += maximum
    return maximize_triangle(triangle, start_index - 1)

if __name__ == '__main__':
    start_time = time()
    triangle_file = get_triangle('p067_triangle.txt')
    print(f'Maximum Path: {maximize_triangle(triangle_file)}')
    print(f'Time: {time() - start_time} seconds.')


texts:
I come from a Java background so my desire for proper unambiguous logging is strong. I prefer using the console to using some other gui widget however, in the browser I know that I can't always count on the console to exist or for it to have all the levels I might like. To remedy this I worked up the following console sanitizer and I was curious what drawbacks it might have.

function configureConsoleLog() {
    "use strict";
    var logMethods = [ 'trace', 'debug', 'log', 'info', 'warn', 'error' ], i;

    if (!window.console) {
        window.console = {log: function (args) {}}; //noop
    }

    for (i = 0; i < logMethods.length; i += 1) {
        if (!window.console[logMethods[i]]) {
            window.console[logMethods[i]] = window.console.log;
        }
    }
}

The idea is to find out if console exists and if it does try to find out which of the supported levels I need are available. The first level of fallback is to map unsupported methods to console.log. The second level is to create my own console variable and make a noop log function since I have nowhere to send the output. This approach leaves open the possibility of coming up with a different strategy if console doesn't exist but for now I'm content to ignore logging if there is no console.

As a side note I looked at several JS logging packages but all of them have the fatal drawback of obscuring original line numbers, usually by delegating to a console method which only reports the line number of the delegating statement.

Thoughts?


texts:
I am studying Clojure and functional programming.  I wrote this function to compute the centroid of a polygon specified as a vector of points, e.g. [[10 20] [0 11] [50 30]]).

Here you can read how to compute the centroid of a polygon.

Can you give me hints and suggestions on how to improve this code from a functional coding style POV?

(defn centroid [p]
  "Calcola il centroide del poligono p"
  (let [six*area     (* 6 (polygon-area p))
        n            (count p)
        first-vertex (p 0)
        polygon      (conj p first-vertex)
        x-terms      (atom [])
        y-terms      (atom [])]
     (dotimes [i n]
            (let [point_i   (polygon i)
                  point_i+1 (polygon (inc i))
                  x_i       (point-x point_i)
                  y_i       (point-y point_i)
                  x_i+1     (point-x point_i+1)
                  y_i+1     (point-y point_i+1)]
               (swap! x-terms conj (* (+ x_i x_i+1)
                                      (- (* x_i y_i+1)
                                         (* x_i+1 y_i))))
               (swap! y-terms conj (* (+ y_i y_i+1)
                                      (- (* x_i y_i+1)
                                         (* x_i+1 y_i))))))
     (make-point (/ (reduce + 0 @x-terms) six*area)
                 (/ (reduce + 0 @y-terms) six*area))))


texts:
I have a DateTime class (my own, not System.DateTime) which implements the IComparable interface.

Here is a method that takes a List<DateTime> and sorts it:

private List<DateTime> SortDateTimes(List<DateTime> dateTimes)
{
    for (int i = 0; i < dateTimes.Count; i++)
    {
        for (int j = 0; j < dateTimes.Count; j++)
        {
            if (dateTimes[i] < dateTimes[j])
            {
                var temp = dateTimes[i];
                dateTimes[i] = dateTimes[j];
                dateTimes[j] = temp;
            }
        }
    }

    return dateTimes;
}

I believe using foreach loops instead of for is suitable here, but having the following variable names drives me crazy. :D

foreach(var dateTime1 in dateTimes)
{
    foreach(var dateTime2 in datetimes)
    ...

What are your thoughts?
Thanks!


texts: Minimum Steps to One to find minimum operations to transform n to 1

texts:
I was solving this dynamic programming problem, and I was wondering if I can get any code review and feedback. You can find this problem online.

#  Coding Problem: Minimum Steps to One
#
#  Prompt:    Given a positive integer, you can perform any combination of these 3 steps:
#             1.) Subtract 1 from it.
#             2.) If its divisible by 2, divide by 2.
#             3.) If its divisible by 3, divide by 3.
#
#             Find the minimum number of steps that it takes get from N to1
#

def min_steps_to_one(n):
    work = [0, 0]

    for i in range(2, n+1):
        min_choice = work[i-1]

        if i % 3 == 0:
          divide_by_three = work[i//3]
          min_choice = min(min_choice, divide_by_three)

        if i % 2 == 0:
          divide_by_two = work[i//2]
          min_choice = min(min_choice, divide_by_two)

        work.append(min_choice + 1)

    return work[n]

I also include some test cases for Minimum Steps to One Tests

true: should return 3 for 10
true: should return 0 for 1
true: should work for large numbers PASSED: 3 / 3

def expect(count, name, test):
    if (count is None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    error_msg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception as err:
        error_msg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if error_msg is not None:
        print('       ' + error_msg + '\n')

print('Minimum Steps to One Tests')
test_count = [0, 0]

def test():
  example = min_steps_to_one(10)
  return example == 3
expect(test_count, 'should return 3 for 10', test)

def test():
  example = min_steps_to_one(1)
  return example == 0
expect(test_count, 'should return 0 for 1', test)

def test():
  example = min_steps_to_one(1334425)
  return example == 22
expect(test_count, 'should work for large numbers', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')


texts:
Question

  Suppose we have two sorts of classes

  an input class Input

  defines a type result_type
  defines set(result_type)

  an output class Output

  defines a type result_type
  defines result_type get() const
  has a number of Input classes as member variables, on which its output depends

  Given an output class and several input classes (arbitrary number),
  consider the following procedure:

  loop over each input class and call set() with an appropriate value (defined beforehand)
  call the get() on the ouput class and collect the result.

  This procedure can be seen as a call to a function taking the input's
  values as arguments an returning the output value.

  Write the functor that constructs such a variadic function in the general case.

  Constraints are: C++ (most likely C++11), arbitrary number of input
  classes of possibly different Input::result_types. Note that
  Input::result_type is not necessarily related to
  Output::result_type. Aim should first be efficiency, but there's a
  big bonus if the code is elegant and readable.

  Details: For those who wonder how Output is related to Input, one could imagine that Input has a result_type get() const method
  as well, which returns whatever you provided via set(). Output
  then has a constructor that takes various Inputs, and stores them
  (or their reference) as member variables. Output::get() then does
  some math by using the return values of its input's get() methods,
  and returns some result of type Output::result_type.

Proposed solution

#include <functional>

template <class Output, class... Inputs>
std::function<typename Output::result_type(typename Inputs::result_type...)>
make_function(const Output& output, Inputs&... inputs) {
  return[&](typename Inputs::result_type... input_vals) {
    int dummy[]{0, (inputs.set(input_vals),0)...};
    return output.get();
  };
}

The int dummy[] line is due to @ecatmur's answer.


texts:
Help me make it better.  Requirement: support arbitrary number of factors, not just 3 & 5.

(ns fizzbuzz.core
  (:use [clojure.contrib.string :only (join)]))

(def targets (sorted-map 3 "fizz" 5 "buzz" 7 "baz"))

;; match any applicable factors
(defn match [n, factors]
  (filter #(= 0 (mod n %)) factors))

(defn fizzbuzz [n]
  (let [factors (keys targets)
        matches (match n factors)]
    (if (= 0 (count matches))
      (str n)
      (reduce str (map targets matches)))))

(join ", " (map fizzbuzz (range 1 20)))


texts: Finding possible misconceptions in ColumnChart

texts:
I've written this to accomplish a specific problem, but it's too long. I've sure that it can be reduce too fit it.

I have the following model:

public class ColumnChart
{
    public virtual string type { get; set; }
    public virtual string name { get; set; }
    public virtual List<double> data { get; set; }
}

The idea of List<double> is to keep 12 values (1 per month if exists)
All these 12 values has to belong someone, so the name will keep the legend.
The type is column (not always, but in this case will make it simple).

Big Logic

// Create a List of ColumnChart's
var list = new List<ColumnChart>();

// Instantiate one object of type ColumnChart
var serie = new ColumnChart();

// Instantiate the List<double> (like my model says)
serie.data = new List<double>();

// Control the loop
int i = 0;

foreach (var element in MyDataSource)
{
   // If the serie.name don't have the current Group Name that came from my DataSource
   if (serie.name != element.GroupName)
   {
       // Isn't the first loop ?
       if (i != 0)
       {
           // Return a new empty instance of ChartColumn
           serie = NewInstance();

           // Set the legend that belong all data
           serie.name = element.GroupName;

           // Set the type of the chart
           serie.type = "column";

           // Instantiate a new List<double> (like my model says)
           serie.data = new List<double>();

           if (serie.data.Count == element.Month - 1)
           {
               serie.data.Insert(element.Month - 1, element.ValueRevenue);
           }

           // If the number of elements in my List<double> is lower then the Month.
           else
           {
               while (serie.data.Count < element.Month - 1)
               {
                   serie.data.Add(0);
               }

              serie.data.Insert(element.Month - 1, element.ValueRevenue);
            }
       }

       // Is the first loop interaction
       else
       {
            serie.name = element.GroupName;
            serie.type = "column";
            serie.data.Insert(element.Month - 1, elemento.ValueRevenue);
            i++;
        }
   }

   // The serie.name have the same current Group Name that came from my DataSource
   else
   {
       serie.data.Insert(element.Month - 1, element.ValueRevenue);
       i++;
   }

   // My i variable that control the loop is the last interaction ?
   if (i == MyDataSource.Count() - 1)
   {
       list.Add(serie);
   }
}

i = 0;

Data Source

MyDataSource
      [0]
           Month: 1
           GroupName: 'Music'
           ValueRevenue: 700.0
      [1]
           Month: 2
           GroupName: 'Music'
           ValueRevenue: 700.0
      [2]
           Month: 3
           GroupName: 'Music'
           ValueRevenue: 700.0
      [3]
           Month: 4
           GroupName: 'Music'
           ValueRevenue: 700.0
      [4]
           Month: 5
           GroupName: 'Music'
           ValueRevenue: 700.0
      [5]
           Month: 6
           GroupName: 'Music'
           ValueRevenue: 700.0
      [6]
           Month: 7
           GroupName: 'Music'
           ValueRevenue: 700.0
      [7]
           Month: 8
           GroupName: 'Music'
           ValueRevenue: 700.0
      [8]
           Month: 9
           GroupName: 'Car'
           ValueRevenue: 700.0


texts:
I'm looking for feedback on some code I've written to work as a transparent proxy.  I'm developing a web app that needs information from another web site's API, but that web site has disabled CORS and I cannot get it directly.  This was an intentional decision by the web site to encourage development of services that will benefit their larger community.

I've recently seen a lot of articles and posts about how to correctly use HttpClient to avoid a huge number of open sockets and potential performance concerns.  After reading those, I've updated my code to look like the following.

Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
       ...

        services.AddSingleton<IHttpClientService, HttpClientService>();
        services.AddScoped<IProxyService, ProxyService>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

HttpClientService's only purpose is to provide an instance of HttpClient to ProxyService:

public class HttpClientService : IHttpClientService
{
    private HttpClient _client;

    public HttpClientService()
    {
        _client = new HttpClient();
    }

    public HttpClient Client()
    {
        return _client;
    }
}

I inject HttpClientService into ProxyService:

public class ProxyService : IProxyService
{
    private readonly Uri _websiteUri;
    private readonly IHttpClientService _http;

    public ProxyService(IHttpClientService httpClient)
    {
        _websiteUri = new Uri("https://www.website.com/api/get-information");
        _http = httpClient;
    }

    public async Task<HttpResponseMessage> GetInformationAsync(string name, string sessionId)
    {

        var builder = new UriBuilder(_websiteUri);
        builder.Port = -1;

        var query = HttpUtility.ParseQueryString(builder.Query);
        query["name"] = name;

        builder.Query = query.ToString();
        string url = builder.ToString();

        var httpRequestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(url),
            Headers =
            {
                { HttpRequestHeader.Cookie.ToString(), "SESSIONID=" + sessionId }
            }
        };

        var response = await _http.Client().SendAsync(httpRequestMessage);

        return response;
    }

    ...
}

My main API calls ProxyService like this:

public class APIController : ControllerBase
{
    private readonly IProxyService _proxy;

    public APIController(IProxyService proxy)
    {
        _proxy = proxy;
    }

    [HttpGet]
    public async Task<IActionResult> GetInformation(string name, string sessionId)
    {
        using (var response = await _proxy.GetInformationAsync(name, sessionId))
        {

            if (response.IsSuccessStatusCode)
            {
                var contents = await response.Content.ReadAsStringAsync();
                return Ok(contents);
            }
            else
            {
                return NotFound();
            }
        }
    }

    ...
}

Is this an okay approach?  Do I even need to wrap the await _proxy.GetInformationAsync() call in a using block?


texts:
I started using PDO 2 days ago, but I want to know if the way I'm coding and the way I'm using it is the correct way of doing things with PDO.

Please let me know if you guys notice any security flaws or improvements in general.

Here is a function I wrote that shows updates.

function ShowRemoveUpdates() {
    ob_start();

    try {
      // connectie gegevens
      require_once('connection.php');

      // pagination
      $start  = 0;
      $limiet = 8;

      if(isset($_GET['page'])) {
        $page   = $_GET['page'];
      } else {
        $page   = 1;
      }

      // query
      $stmt = $pdo->prepare('SELECT * FROM updates ORDER BY id DESC LIMIT :start, :limiet');
      $stmt->execute(array(':start' => $start, ':limiet' => $limiet));

      //start van formulier en tabel
      echo "<form method='post' action=''>";
      echo "
";
      echo "Geplaatst door	Titel	Tekst	Tijd	";

      // while loop door resultaten van query
      if($stmt->rowCount() > 0) {
        while ($row = $stmt->fetch()) {
          $idje = $row['id'];

          echo "
";
          echo "".$row['medewerker']."	";
          echo "".$row['titel']."	";
          echo "".$row['tekst']."	";
          echo "".$row['datum']."	";
          echo "<input type=\"checkbox\" name=\"checkvakje\" id=\"checkvakje\" value=\"$idje\">	";
          echo "
";
        }
        echo "
";
        echo "<input type='submit' value='Verwijderen'>";
      } else {
        echo "Geen resultaten gevonden.";
      }

      // Verwijder update functie
      if(isset($_POST['checkvakje'])) {
        $checkvak   = $_POST['checkvakje'];
        $stmt = $pdo->prepare('DELETE FROM updates WHERE id = :checkvak');
        $stmt->execute(array(':checkvak' => $checkvak));
        header("Refresh:0");
        exit();
      }

      echo "</form>";

      // count resultaten per rij en maak pagina nummering
      $stmt = $pdo->prepare('SELECT * FROM updates');
      $stmt->execute();
      $rows = $stmt->RowCount();
      $total=ceil($rows/$limiet);

      if($page>1) {
        echo "Vorige";
      }

      for($i=1;$i<=$total;$i++)
      {
        if($i==$page) {
          echo ".$i.";
          }

        else {
          echo "- ".$i."";
        }
      }

      if($page!=$total) {
        echo " - Volgende";
      }
      // vang errors op
    } catch (PDOException $e) {
        echo "Connection failed" . $e->getMessage() . "";
    }
}


texts: About handling data from an API call through RX and Retrofit

texts:
I started using Retrofit and RxJava recently and I love it. I am working on an Android project and I am following MVP Repository pattern as specified in Android Architecture Components. I'm still learning though.

Whenever I have to make an API call, I do it like this in the Presenter:

fruitsRepository
  .getFeaturedFruits()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Observer<UniversalResponse<Fruit>>() {

    @Override
    public void onSubscribe(Disposable d) {
        compositeDisposable.add(d);
    }

    @Override
    public void onNext(UniversalResponse<Fruit> universalResponse) {

        if (view.isLost()) return;
        view.setProgressVisibility(false);

        if (universalResponse.isSessionExpired()) {

            view.onSessionExpired();
            return;
        }

        if (universalResponse.isError()) {

            if (universalResponse.isServerError()) {
                view.showErrorViewerPage(universalResponse.getServerErrorMessage());
            }

            view.showFeaturedFruitsError(universalResponse.getMessage());
            return;
        }

        List<Fruit> fruits = universalResponse.getItems();
        if (fruits != null && fruits.size() > 0) {

            view.showFeaturedFruits(fruits);
        }
        else {
            view.showNoFeaturedFruits();
        }
    }

    @Override
    public void onError(Throwable e) {

        if (view.isLost()) return;
        view.setProgressVisibility(false);

        view.showFeaturedFruitsError(e.getMessage());
    }

    @Override
    public void onComplete() {

        if (view.isLost()) return;
        view.setProgressVisibility(false);
    }
});

fruitsRepository is a Repository that can get data from local or remote source.
.getFeaturedFruits() calls retrofit internally if remote source is selected
compositeDisposable is CompositeDisposable
UniversalResponse is a class having httpStatusCode, isSuccess and List<T>
view is an implementation of UI from FeaturedFruitsContract.View

I am looking for some improvements to this. Can I reduce this somehow? If I have to make 5 different API calls, my presenter gets really bigger and repetitive. I was thinking about making an adapter for Observer I am using to subscribe.


texts:
I have this algorithm which aggregates a list of cidrs up to a provided limit based on the distance between them. It finds the closest ones and calculates the subnet to join them. The loop repeats until the limit is reached. I think there's room to improve it but I'm stuck at the moment. Any advice?

Input

limit: 9
cidrs (10):

52.1.0.0/16
52.2.0.0/16
52.3.0.0/16
52.4.0.0/16
52.5.0.0/16
52.6.0.0/16
52.7.0.0/16
52.8.0.0/16
52.9.0.0/16
52.10.0.0/16

Output

cidrs (9):

52.1.0.0/16
5̶2̶.̶2̶.̶0̶.̶0̶/̶1̶6̶
5̶2̶.̶3̶.̶0̶.̶0̶/̶1̶6̶
52.4.0.0/16
52.5.0.0/16
52.6.0.0/16
52.7.0.0/16
52.8.0.0/16
52.9.0.0/16
52.10.0.0/16
**52.2.0.0/15**

Code

public static IEnumerable<string> Aggregate(List<string> cidrs, int limit)
{
    var parsedCidrs = cidrs.Select(IPNetwork.Parse).ToArray();

    var cidr1 = parsedCidrs[0];
    var cidr2 = parsedCidrs[1];
    var minWideSubnet = IPNetwork.WideSubnet(new[] { cidr1, cidr2 });

    while (parsedCidrs.Count > limit)
    {
        foreach (var cidrA in parsedCidrs)
        {
            foreach (var cidrB in parsedCidrs)
            {
                if (cidrA != cidrB)
                {
                    var wideSubnet = IPNetwork.WideSubnet(new[] {cidrA, cidrB});

                    if (wideSubnet.Usable < minWideSubnet.Usable)
                    {
                        minWideSubnet = wideSubnet;
                        cidr1 = cidrA;
                        cidr2 = cidrB;
                    }
                }
            }
        }
        // update array
        cidrs.Remove(cidr1.ToString());
        cidrs.Remove(cidr2.ToString());
        var end = minWideSubnet.ToString();
        cidrs.Add(end);
    }

    return cidrs;
}


texts: Non-persistent storage for key-value pairs

texts:
I got an interesting interview question related to JavaScript:

  In JavaScript please create a storing function called storingFn with the following characteristics:

  Read Cafefully

  Save immutable key-values.
  The values can only be accessed by storingFn and should not be exposed in the global scope.
  It can't use Browser storage (localStorage, sessionStorage), cookies, global scope or any other object that is part of the Browser.
  The only global function for this implementation is storingFn (Ignore the assert function).
  And it doesn't matter if the key-values don't persist if you refresh the browser.

I wrote an IIFE as a solution. What do you think of it? I couldn't find any solution online, which makes this question very interesting for me.

var storingFn = (function(){
  var immObj = {};

  function set(key, value){
    // check if key already exist
    if (key in immObj){
      return false;
    }

    // it's a new key , assign it
    immObj[key]  = value;
    return true;
  }

  // verbose but looks better organize
  function get(key){
    return immObj[key];
  }

  var initStore = function(key, value){
    //console.log(immObj);
    // if value is defined
    if (typeof value != 'undefined'){
      return set(key, value);
    }
    // if value is not defined
    else {
      return get(key);
    }
  }

  return initStore;
})();

storingFn('name', 'Nic') //Should return true
storingFn('name') // Should return "Nic"'
storingFn('name', 'Robert') //Should return false


texts:
I have started to read Robert C. Martin Clean Code book.

To learn and gain more expreiences I wrote a single Log class. So I want some suggestions to improve this code..
This is a part of the Log class:

public class FileLogger : ILog
{
    private string directoryPath = string.Empty;
    private string fileName = string.Empty;

    public FileLogger(string logDirectoryPath, string logFileName)
    {
        if (string.IsNullOrEmpty(logDirectoryPath))
        {
            throw new ArgumentException(nameof(logDirectoryPath), "Write some error message...");
        }

        if (string.IsNullOrEmpty(logFileName))
        {
            throw new ArgumentException(nameof(logFileName), "Write some error message...");
        }

        this.directoryPath = logDirectoryPath;
        this.fileName = logFileName;
    }

    public void LogMessage(string message)
    {
        try
        {
            if (!string.IsNullOrEmpty(message))
            {
                if (!LogDirectoryExists(directoryPath))
                {
                    CreateLogDirectory(directoryPath);
                }

                WriteToLogFile(message);
            }
        }
        catch (Exception ex)
        {
            //Catch exception, do something...
        }
    }

    private bool LogDirectoryExists(string logDirectoryPath)
    {
        return Directory.Exists(logDirectoryPath);
    }

    private void CreateLogDirectory(string logDirectoryPath)
    {
        Directory.CreateDirectory(logDirectoryPath);
    }

    private void WriteToLogFile(string message)
    {
        using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write))
        {
            using (var logFileWriter = new StreamWriter(logFile))
            {
                logFileWriter.Write(message);
            }
        }
    }
}

I wrote 3 different function to write a message to a log. I try to use SRP and Command Query Separation, but I don't sure this is a good in this way. Maybe there are another problems with this code, example naming or variable declarations.


texts:
I want to extend the Closeable-Interface so that I can add Listeners, that get notificated when the resource is closed.

The CloseListener-API is rather simple and straight forward:

public interface CloseListener {
  public void objectWillBeClosed(CloseableObservable closeable);
  public void objectClosed(CloseableObservable closeable);
}

I found a nasty trick in a blog, that uses Java8's default methods to recreate multiple inheritance and I asked myself if it might be valid to try it for an Observable-Interface:

public interface CloseableObservable extends Closeable{

    class HiddenAndNasty{
        private static final Map<CloseableObservable, Collection<CloseListener>> allObservers = new WeakHashMap<>();

        private static final Collection<CloseListener> getObservers(CloseableObservable observable){
            synchronized (observable) {
                Collection<CloseListener> observers = allObservers.get(observable);
                if(observers == null){
                    observers = new ArrayList<>();
                    allObservers.put(observable, observers);
                }
                return observers;
            }
        }
    }

    public default void addObserver(CloseListener observer){
        HiddenAndNasty.getObservers(this).add(observer);
    }

    @Override
    public default void close() throws IOException{
        // Copy Collection to avoid concurrent modification
        Collection<CloseListener> observers = new ArrayList<>(HiddenAndNasty.getObservers(this));
        observers.forEach(observer -> observer.objectWillBeClosed(this));
        closeInternal();
        observers.forEach(observer -> observer.objectClosed(this));
    }

    /** not part of the public api, use close() instead */
    void closeInternal() throws IOException;

}

This seems to work - here is a simple example, that works:

import java.io.IOException;

public class TestAutoCloseableOnObservableCloseable {

    public static class SomeCloseableClass implements CloseableObservable{

        @Override
        public void closeInternal() throws IOException{
            System.out.println("Now I close myself");
        }

    }

    public static void main(String[] args) throws IOException {

        try(SomeCloseableClass someObject = new SomeCloseableClass()){
            someObject.addObserver(new CloseListener() {
                @Override
                public void objectWillBeClosed(CloseableObservable closeable) {
                    System.out.println("Object will be closed!");
                }
                @Override
                public void objectClosed(CloseableObservable closeable) {
                    System.out.println("Object was closed!");
                }
            });
        }// try-with-resource

    }   // main
}

It works - but it seems somehow evil to me. Very evil. Is it an Anti-Pattern?


texts:
I started learning Haskell a couple of days ago and decided to build a Caesar shift in it.

import Data.Char

shift_str :: Int -> ([Char] -> [Char])
shift_str num
         | num > 1 = \str -> shift_str_forwards (shift_str (num-1) str)
         | num == 1 = shift_str_forwards
         | num == 0 = no_shift
         | num == -1 = shift_str_backwards
         | num < -1 = \str -> shift_str_backwards (shift_str (num+1) str)

no_shift :: [Char] -> [Char]
no_shift str = str

shift_str_forwards :: [Char] -> [Char]
shift_str_forwards str = map shift_forwards str

shift_str_backwards :: [Char] -> [Char]
shift_str_backwards str = map shift_backwards str

shift_forwards :: Char -> Char
shift_forwards char
             | char == 'z' = 'a'
             | otherwise = chr (1 + ord char)

shift_backwards :: Char -> Char
shift_backwards char
              | char == 'a' = 'z'
              | otherwise = chr (ord char - 1)

However, this seems far too complex to be the right way of doing it. Any advice?


texts: Checking if an integer is a palindrome using either a string or a dict

texts:
I have solved the palindrome question on LeetCode today, but I wasn't happy with the original solution - I used strings, it worked slowly and used a lot of memory.
So I rewrote the answer using a dictionary approach instead knowing that looking up a value in a dictionary has lower time complexity than searching through a list, but the results were strange - my latest answer is much better in terms of memory use (better than 94.65% of other submissions), but it became significantly slower. As you can see in the image below, my last submission is much slower than the first, but memory use has improved a lot:

My original solution was this:
class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = str(x)

        if len(s) == 1:
            palindrome = True

        i = int(len(s)/2)

        for p in range(i):
            if s[p] != s[-(p+1)]:
                return False
            else:
                palindrome = True

        return palindrome

And the updated version is:
class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = {i:j for i,j in enumerate(str(x))}
        i = (max(s)+1)//2

        if max(s)+1 == 1:
            return True

        for p in range(i):
            if s[p] != s[max(s)-p]:
                return False
            else:
                palindrome = True

        return palindrome

Can anyone explain why the latest version is so much slower? I thought it should be faster...
What should I change to improve the speed?
EDIT:
New version based on @hjpotter comment. Now I only have 1 call to max() in the entire script and yet it's even worse - 168ms and 13.9 Mb. I don't understand what's happening here:
class Solution:
    def isPalindrome(self, x: int) -> bool:
        s = {i:j for i,j in enumerate(str(x))}
        m = max(s)
        i = (m+1)//2

        if m+1 == 1:
            return True

        for p in range(i):
            if s[p] != s[m-p]:
                return False
            else:
                palindrome = True

        return palindrome


texts: Most efficient dict filter on key tuple?

texts:
I have a dict wherein a value needs to be retrievable by any one of several keys. It seemed that making multiple dictionaries or multiple entries in a single dictionary pointing to the same value object (ref type) was more maintenance than I wanted to commit to.

I decided to use a tuple for the key. I would then use filter(...) with a lambda to determine if the given provider_lookup was in the keyed tuple. I am not concerned that a value may be duplicated across tuples (this will be guarded against as the code moves forward). Here are the two methods:

def register_block_provider(self, provider):
    block = provider()
    self.__block_providers.update({
        (block.block_id, block.name): block
    })

def get_block_provider(self, provider_lookup):
    for provider_key in filter(lambda p: (p[0], p[1]), self.__block_providers.keys()):
        if provider_lookup in provider_key:
            print("we've found the key: {key}".format(key=provider_key))
            return self.__block_providers[provider_key]

    return None

Are there specific improvements that can be made to the get_block_provider method? This works fine so I'm just asking for some feedback on the details of the implementation.


texts: Invoke callable object passing arguments in "groups of N" using C++17 fold expressions

texts:
Interactive Wandbox example

Inspired by this Stack Oveflow question, I've implemented a function that, when called with a desired arity, a callable object, and a variadic amount of arguments, calls the passed callable object forwarding the passed arguments in groups of the desired arity.

Example:

auto printAll([](auto... xy){ (std::cout << ... << xy); std::cout << " "; });

forNArgs<2> // `2` is the desired arity
(
    // `printAll` is the callable object.
    printAll,

    // Variadic arguments.
    0, 1,   2, 3,   4, 5,   6, 7
);

// ...will result in code equivalent to...

printAll(0, 1);
printAll(2, 3);
printAll(4, 5);
printAll(6, 7);

I'm trying to simplify the original code using fold expressions. This is what I have so far:

// "Third step": call `mFn` once getting the correct elements from the forwarded tuple.
template<std::size_t TIStart, typename TF, typename TTpl, std::size_t... TIs>
void forNArgsStep(TF&& mFn, TTpl&& mTpl, std::index_sequence<TIs...>)
{
    mFn(std::get<TIStart + TIs>(mTpl)...);
}

// "Second step": use a comma operator fold expression to call the "third step" `numberOfArgs / TArity` times.
template<std::size_t TArity, typename TF, typename TTpl, std::size_t... TIs>
void forNArgsExpansion(TF&& mFn, TTpl&& mTpl, std::index_sequence<TIs...>)
{
    using SeqGet = std::make_index_sequence<TArity>;
    (forNArgsStep<TIs * TArity>(mFn, mTpl, SeqGet{}), ...);
}

// "First step / interface".
template<std::size_t TArity, typename TF, typename... Ts>
void forNArgs(TF&& mFn, Ts&&... mXs)
{
    constexpr auto numberOfArgs(sizeof...(Ts));

    static_assert(numberOfArgs % TArity == 0,
        "Invalid number of arguments");

    auto&& asTpl(std::forward_as_tuple(std::forward<Ts>(mXs)...));

    // We need to "convert" the `Ts...` pack into a "list" of packs
    // of size `TArity`.

    using SeqCalls = std::make_index_sequence<numberOfArgs / TArity>;
    forNArgsExpansion<TArity>(mFn, asTpl, SeqCalls{});
}

More examples:

int main()
{
    // Prints "01 23 45 67":
    forNArgs<2>
    (
        [](auto... xy){ (std::cout << ... << xy); std::cout << " "; },

        0, 1, /**/ 2, 3, /**/ 4, 5, /**/ 6, 7
    );
    std::cout << "\n";

    // Prints "abc def ghi":
    forNArgs<3>
    (
        [](auto... xyz){ (std::cout << ... << xyz); std::cout << " "; },

        "a", "b", "c", /**/ "d", "e", "f", /**/ "g", "h", "i"
    );
    std::cout << "\n";
}

I think my perfect forwarding is incorrect.

When should I forward the tuple?
When should I forward the function?

How can I simplify the code further?

Is there any way of avoiding the two extra helper functions forNArgsExpansion and forNArgsStep?
Is there any way of avoiding the creation of a tuple? Can the arguments be forwarded in a better way?


texts:
I need a simple dispatcher implementation(invoke methods on one thread from many threads)
once you dispatch method curent thread should wait for results, so I'm thinking about something like this:

public class Dispatcher
{
    private readonly BlockingCollection<Tuple<Delegate, object[]>> runQueue = new BlockingCollection<Tuple<Delegate, object[]>>();
    private readonly BlockingCollection<object> resultQueue = new BlockingCollection<object>();
    private readonly CancellationTokenSource source = new CancellationTokenSource();
    private readonly Task task;
    public Dispatcher()
    {
        Task.Run(() =>
        {
            using (source)
            using (runQueue)
            using (resultQueue)
            {
                Debug.WriteLine("Dispatcher started with thread {0}", Thread.CurrentThread.ManagedThreadId);
                while (!source.IsCancellationRequested)
                {
                    var run = runQueue.Take(source.Token);
                    resultQueue.Add(run.Item1.DynamicInvoke(run.Item2));
                }
                Debug.WriteLine("Dispatcher ended");
            }
        });
    }

    public void Stop()
    {
        source.Cancel();
    }

    [MethodImpl(MethodImplOptions.Synchronized)]
    public object Invoke(Delegate @delegate, params object[] @params)
    {
        runQueue.Add(new Tuple<Delegate, object[]>(@delegate, @params));
        return resultQueue.Take(source.Token);
    }
}

I had test it with such code and it seems too work well ...

class Program
{
    static void Main(string[] args)
    {
        Func<int, int, int> func = (sleep, i) =>
        {
            CC.WriteLine(i, "\tTask {0} will sleep for {1}, thread {2}", i, sleep, Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(sleep);
            CC.WriteLine(i, "\tTask {0} woke up", i, sleep);
            return i; //return task number
        };
        var rnd = new Random();
        var disp = new Dispatcher();
        {
            var tasks = Enumerable.Range(0, 10).Select(i =>
                            Task.Run(() =>
                            {
                                CC.WriteLine(i, "Task {0} started, thread {1}", i, Thread.CurrentThread.ManagedThreadId);
                                CC.WriteLine(i, "Task {0} ended with {1}", i, disp.Invoke(func, rnd.Next(3, 15) * 100, i));
                            })).ToArray();
            Task.WaitAll(tasks);
            disp.Stop();
        }

        Console.ReadKey();

    }
    static class CC
    {
        public static readonly List<ConsoleColor> COLORS = Enum.GetValues(typeof(ConsoleColor)).Cast<ConsoleColor>().ToList();
        static CC()
        {
            COLORS.RemoveAt(0);
            COLORS.RemoveAt(0);
        }
        public static void WriteLine(int colorIndex, string format, params object[] args)
        {
            lock (COLORS)
            {
                Console.ForegroundColor = COLORS[colorIndex];
                Console.WriteLine(format, args);
            }
        }
    }
}

Is a BlockingCollection a good choice?
Or maybe it can be done with something simpler? (SlimSemaphore)?


texts: Find the index of a tuple in a list of tuples in Python

texts:
I'm a Python beginner.
I have the following array of unique tuples I'm playing with:
array = [(1, 2), (1, 7), (1, 5), (2, 5), (2, 7), (2, 9), (3, 4), (3, 5), (4, 5), (4, 7), (5, 8), (6, 7), (8, 9)]

I want to find the index of a given tuple (u, v) in this array. I wrote the following line which I believe can be improved, probably from removing the enumerate() to get simpler if conditions but can't figure it out...
Example for the tuple (6, 7) - Inputs are: 6 and 7
array = [(1, 2), (1, 7), (1, 5), (2, 5), (2, 7), (2, 9), (3, 4), (3, 5), (4, 5), (4, 7), (5, 8), (6, 7), (8, 9)]
# Inputs: 6 and 7
position = [i for i, tupl in enumerate(array) if (tupl[0] == 6 and tupl[1] == 7)]
print(position)
# Output: [11]


texts:
As per the instructions on this Tape Equlibrium-Codility

I've written the code

import java.util.Arrays;
public class TapeEqulibrium {
  int main(int[] array) {
    int minimumDiff = 100000;
    for (int i = 1; i < array.length; i++) {
        int differnce = Math.abs(Arrays.stream(array, 0, i).sum() - Arrays.stream(array, i, array.length).sum());
        minimumDiff = differnce < minimumDiff ? differnce : minimumDiff;
    }
    return minimumDiff;
   }
}

On submission, I have got correct answers for all test cases. But It says that the time complexity is O(n*n)and taking more than 6.00 seconds. while writing I thought that it falls under time complexity of O(n) or something (as I don't know much about that). So I need to know how to calculate the time complexity of this code.


texts: Posting data via fetch and handling network errors

texts:
I've built a login panel, which will submit an email and password via fetch/POST. And I wanted to know the best way to handle network status errors?
Reason being, as I want to inject error messages into my login panel for each state/status code.
I've written the code below, which works. But I wondered if there is a better way to write this?  For example, should my status code handling go in the catch() etc?
let url = 'www.MYAPI.com/xyz';

// post body data
let data = {
    "Username": emailAddress,
    "Password": Password,
  }

// create request object
let request = new Request(url, {
    "method": 'POST',
    "mode": 'cors',
    "credentials": 'include',
    "body": JSON.stringify(data),
    "referrerPolicy": "strict-origin-when-cross-origin",
    "headers": {
        "accept": "application/json, text/plain, */*",
        "content-type": "application/json;charset=UTF-8",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest"
    }
});

fetch(request)
.then( async (response) => {
    let data = await response.json();

    if(response.status === 200){
     // LOGIN SUCCESSFUL HERE;
        console.log("Successful log in - status: ", data);
        document.getElementById("id01").style.display = "none"; // HIDE LOGIN PANEL
    } else{
     // Rest of status codes (400,500,303), can be handled here appropriately

        // IF EMAIL ADDRESS ERROR / STATUS 502
        if (data.KnownErrorDescription === "MemberEmailDoesNotExist") {
            document.getElementById("email-error").innerHTML = "Please enter a valid email address to sign in";
        };

        // IF PASSWORD IS EMPTY / STATUS 400
        if (data.Message === "The request is invalid.") {
            document.getElementById("password-error").innerHTML = data.ModelState["request.Password"][0];
        }

        // // IF ACCOUNT LOCKED / 502
        if (data.KnownErrorDescription === "MemberAccountLocked") {
            document.getElementById("failed-sign-in-error").innerHTML = "You need to reset your password";
            document.getElementById("password-reset").style.display = "block";
        }
    };

  })
  .catch((err) => {
      console.log(err);
  })


texts: Creating a EventHandler class for buttons with different actions

texts:
I have the following code at the moment:

public void initialiseButtons() {
    this.saveNewButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            savePatientData(actionEvent);
        }
    });
    this.clearFieldsButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            TextFieldHelpers.clearInputFields(dataInputFields);

        }
    });
    this.cancelNewPatientButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            clearWorkspace();
        }
    });
    this.saveChangesButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            savePatientData(actionEvent);
        }
    });
    this.deletePatientButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            deleteExistingPatient();
        }
    });
    this.deselectPatientButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            patientListView.getSelectionModel().clearSelection();
        }
    });
    addNewButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            setupViewForEditingOrAddingPatientAction(1);
        }
    });
}

As you can see I have repeated the creation of a EventHandler numerous amount of times. Can someone guide me on how I can minimise this or is this the only way?


texts: Calculating parking fees, given start and end timestamps

texts:
Since I have just started Javascript, I am trying to solve a few problems and improve myself. I encountered such a question. I tried to do everything step by step from the question, but I do not think that my code is efficient. Can someone help me develop it?

Please code for a JavaScript function that accepts two arguments that
are; parking "date and time"(timestamp) and return "date and
time"(timestamp). At an airport for car parking, the following rules
are applied.
Parking costs;
€2 for the first 20 minutes,
rising to €4 for up to 40 minutes,
rising to €6 for up to one hour,
rising to €7 for up to two hours,
rising to €9 for up to three hours,
rising to €11 for up to four hours,
rising to €13 for 4-8 hours and
rising to €15 for 8-24 hours.
€16 for the first 24 hours and after that each additional day is
charged at €9.

Here is my code:
function msToHours(milisecond) {
        let time = milisecond;

        let hour = (time / 60000) / 60;

        return hour;
    }

    //Mins to Hours Function
    function minToHours(miniute){

        let time = miniute;

        let hr = (miniute /60);

        return hr;

    }

    //Finding the nth day Function

    function add24HR(hour, cb) {

        let arr = new Array();

        for (let i = 0; i < hour; i++) {
            if (i % 24 == 0) {
                arr.push(i)
            }
        }

        return  `Your Parking Fee is £${(arr.length*cb-cb) + 16}.(${arr.length} days)`
    }

    //Main Function

    const parkingFees = (parkingDate, returnDate) => {

        //Defining dates
        var park = new Date(parkingDate)
        var returned = new Date(returnDate);

        //Variables
        var penaltyFee = 9;
        let totalPrice;

        //Time between park and return (miliseconds)
        let totalTime = returned - park

        //MiliSeconds to Hour
        let totalPark = msToHours(totalTime);

        //Mins to Hours
        if (totalPark <= minToHours(20)) {
            return `Your parking fee is only £${2}.`
        }

        else if(totalPark > minToHours(20) && totalPark <= minToHours(40)){
            return `Your parking fee is only £${4}.`
        }

        else if(totalPark > minToHours(40) && totalPark <= minToHours(60)){
            return `Your parking fee is only £${6}.`
        }
        else if(totalPark > minToHours(60) && totalPark <= minToHours(120)){
            return `Your parking fee is only £${7}.`
        }
        else if(totalPark > minToHours(120) && totalPark <= minToHours(180)){
            return `Your parking fee is only £${9}.`
        }
        else if(totalPark > minToHours(180) && totalPark <= minToHours(240)){
            return `Your parking fee is only £${11}.`
        }
        else if(totalPark > minToHours(240) && totalPark <= minToHours(480)){
            return `Your fparking fee is only £${13}.`
        }

        else if(totalPark > minToHours(480) && totalPark < minToHours(1440)){

            return `Your parking fee is only £${15}.`
        }

        else if(totalPark > minToHours(1440) && totalPark < minToHours(2880)){

            return `Your parking fee is only £${16}.`
        }

        //if totalPark > 24 HRS

        else {

            totalPrice = add24HR(totalPark, penaltyFee)

        }

        return totalPrice;

    }

    document.querySelector("body").innerHTML = (parkingFees("5/12/2020 18:30", "5/18/2020 18:30"))


texts:
I want to make a http request, get the website content and check one specific element. Currently I'm doing it with lcurl (got explanations from a tutorial). Here is an excerpt of my code:

curl_global_init(CURL_GLOBAL_ALL);
CURL *myHandle;
CURLcode result;
struct BufferStruct output;
output.buffer = NULL;
output.size = 0;

//requested value is on this website
char* url = "https://www.somewebsite.com";

//set curl handle to write the website content into buffer
myHandle = curl_easy_init();
curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, (void*)&output);
curl_easy_setopt(myHandle, CURLOPT_URL, url);
curl_easy_perform( myHandle );

//searching for position of the requested value.
uint8_t* value_position = strstr(output.buffer, "value_description");
//copy the value (8 chars) into a buffer defined earlier
strncpy(value, value_position, 8);
//... clean up etc.

The code works. But I wonder if this is the fastest way...
Any ideas how to do it faster?

EDIT:
Okay, more explanations: I do run this program in a loop, in my program the url parameter is changing slightly every time, trying lots of websites, not just one. The content I get is plain html. I want to request and check the value on as many websites per second as possible. I hope that information is helpful :)


texts: Writting day_of_month and month_day with pointers instead of array indexing

texts:
Rewrite the routines day_of_year and month_day with pointers instead of indexing.

The exercise is quite simple, this is the solution:

int day_of_year(unsigned int year, int month, int day) {
    int leap, i;

    leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));

    if((month >= 1 && month <= 12) && ((day >= 1) && (day <= *(*(daytab + leap) + month)))) {
        for(i = 1; i < month; i++) {
            day += *(*(daytab + leap) + i);
        }

        return day;
    }

    return -1;

}

int month_day(unsigned int year, int yearday, int *pmonth, int *pday) {
    int leap, i;

    leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
    if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 365))) {

        for(i = 1; yearday > *(*(daytab + leap) + i); i++) {
          yearday -= *(*(daytab + leap) + i);
        }
        *pday = yearday;
        *pmonth = i;

        return 1;
    }
    return -1;
}

The expression (daytab + leap) is a pointer to the leap-th row and (*(daytab + leap) + i) is a pointer to the i-th element of the leap-th row.


texts:
I have done a sorting program, it works but I am new to the coding world and I would love to hear your thoughts.
    public class CorrectPlacement {

    public void placer(int... numbers) {
        System.out.println("Before : " + Arrays.toString(numbers) + " ");
        for (int i = -1; i <= numbers.length - 2; i++) {
            int min = numbers[i + 1];
            for (int number : numbers) {

                if (number <= min && indexofTheRight(number, numbers, i) > i) {
                    min = number;
                }
            }
            numbers[indexofTheRight(min, numbers, i)] = numbers[i + 1];
            numbers[i + 1] = min;
        }
        System.out.println("After : " + Arrays.toString(numbers));
    }

    public int indexofTheRight(int element, int[] array, int range) {

        for (int i = array.length - 1; i > range; i--) {
            if (array[i] == element) {
                return i;
            }
        }
        return -1;
    }
}


texts:
Problem: Given an even number (greater than 2), return two prime
  numbers whose sum will be equal to given number.

  NOTE 1:  A solution will always exist. (Goldbach's conjecture)

  Note 2: If there are more than one solutions possible, return the
  lexicographically smaller solution.

This solution becomes slower for higher order numbers. How can I optimise this code?

import math
# Function to create a list of all prime numbers uptil given number
def list_prime(A):
    primes = []  # initialise an empty list of primes
    bool_a = [True for i in range(2,A+3)]  # creates boolean list of index
    for  i in range(2, int(math.sqrt(A))+1):
        if bool_a[i]:
            for j in range( i * i, A +1 , i):  # eliminate all multiples of i*i+i, i*i+2i and so on uptil A+1
                if bool_a[j]:
                    bool_a[j] = False;

    for i in range(2,A):  # the index of reamaining bools are prime numbers
        if bool_a[i]:
            primes.append(i)

    return primes

#Function that returns two prime numbers whose sum is equal to the given number
def prime_sum(A):
    solution_set = []

    for i in (list_prime(A)):
        for j in (list_prime(A)[::-1]):
            if i + j == A:
                solution_set.append((i,j))
                break

    return min(solution_set)


texts: Detecting a loop in a Linked list using a hashset

texts:
I was wondering if detecting a loop in a linked list using a HashSet is better than using two pointers?

        HashSet<Integer> set = new HashSet<Integer>();
    LinkedListNode current = head;
    while(current != null) {
        if(current.next != null) {
            if(set.contains(current.next.data)) {
                return current.next; // this has been seen so there is a loop.
            }
            set.add(current.next.data);
        }
        current = current.next;
    }
    return null;


texts: Perl one-liner for parsing host names from ssh config file

texts:
Here is the working code (intended to be executed with perl -e '<code>' ~/.ssh/config):

Actual version:

while(<>){if(/^Host (.+)/){$_=$1;foreach $i(/([^ ]+)/g){$h{$i}=1}}}print "$_ " for keys %h;

Identical version with whitespace for reading:

while(<>) {
    if(/^Host (.+)/) {
        $_=$1;
        foreach $i(/([^ ]+)/g) {
            $h{$i}=1
        }
    }
}
print "$_ " for keys %h;

I'm sort of a perl newbie.  Is $_=$1 kosher?  Is there a straight-forward way to do this with a single regex?  Is there anything else I should be doing better here?

Example input output:

For a config file with contents like this:

Host build
    HostName build.myserver.com
Host build build.myserver.com
    User ubuntu
    IdentityFile ~/.ssh/build
Host tunnel
    LocalForward 6397 redis.production.com:6379

The output should be (order is not required, trailing space is not required but acceptable):

build build.myserver.com tunnel


texts:
I have written the following code for the Three Cards Monte game. It works as expected and returns the required output.

However when I tried to turn it in to the teacher, he keeps saying its too long.

Is there any way to shorten it but make sure it returns the same output?

import java.util.Scanner;

public class ThreeCardsMonte {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        int ace;
        int guess;

        ace = 1 + (int)(Math.random()*3);

        System.out.println("You slide up to Fast Eddie's card table and plop down your cash.");
        System.out.println("He glances at you out of the corner of his eye and starts shuffling.");
        System.out.println("He lays down three cards.");
        System.out.println("");
        System.out.println("Which one is the ace?");
        System.out.println("");
        System.out.println("##  ##  ##");
        System.out.println("##  ##  ##");
        System.out.println("1   2   3");
        guess = keyboard.nextInt();

        if ((ace == 1) && (guess == 1)) {
            System.out.println("You nailed it! Fast Eddie reluctantly hands over your winnings, scowling.");
            System.out.println("AA  ##  ##");
            System.out.println("AA  ##  ##");
            System.out.println("1   2   3");
  }
        else if ((ace == 1) && (guess != 1)) {
            System.out.println("Ha! Fast Eddie wins again! The ace was card number " +ace+".");
            System.out.println("AA  ##  ##");
            System.out.println("AA  ##  ##");
            System.out.println("1   2   3");
  }
        else if ((ace == 2) && (guess == 2)) {
            System.out.println("You nailed it! Fast Eddie reluctantly hands over your winnings, scowling.");
            System.out.println("##  AA  ##");
            System.out.println("##  AA  ##");
            System.out.println("1   2   3");
  }
        else if ((ace == 2) && (guess != 2)) {
            System.out.println("Ha! Fast Eddie wins again! The ace was card number " +ace+".");
            System.out.println("##  AA  ##");
            System.out.println("##  AA  ##");
            System.out.println("1   2   3");
  }
        else if ((ace == 3) && (guess == 3)) {
            System.out.println("You nailed it! Fast Eddie reluctantly hands over your winnings, scowling.");
            System.out.println("##  ##  AA");
            System.out.println("##  ##  AA");
            System.out.println("1   2   3");
  }
        else if ((ace == 3) && (guess != 3)) {
            System.out.println("Ha! Fast Eddie wins again! The ace was card number " +ace+".");
            System.out.println("##  ##  AA");
            System.out.println("##  ##  AA");
            System.out.println("1   2   3");
          }
     }
}


texts:
I have this script to pull data out of the Filepicker API internal. It's mostly reverse-engineering and the code seems to be ugly to me.  How can this be improved?

yesterday = (Time.now - 1.day).to_i
start_date = "08/08/2013".to_time.to_i
url = URI.parse("https://developers.inkfilepicker.com/login/")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
request = Net::HTTP::Post.new(url.request_uri)
request.set_form_data({"email" => "my@email.com", "password" => "123456"})
response = http.request(request)
cookie = response.response['set-cookie'].split('; ')[0]
uri = URI("https://developers.inkfilepicker.com/apps/XXX/stats/file?startdate=#{start_date}&enddate=#{yesterday}")
req = Net::HTTP::Get.new(uri.request_uri)
req['Cookie'] = cookie
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http|
  http.request(req)
}
stats = JSON.parse res.body
stats = stats['data']['links.created']

In case of some of you are against reverse engineering, I asked for a 'real' API to pull this data and they suggested me to do this until they provide an API.


texts: Loop for finding proper grouping brackets

texts:
I've got this piece of code that you pass a string of special characters to and an index which points to a location in this string. The code will take the index, analyze the string, and return a new index of location of the proper grouping bracket. I.e., if index = 5, and my string is ![>[*[]^[#$]%]%]$%, I will be currently at ]. Then, I need to backtrace in the string to find its matching group bracket [. To do this, I've written the following method:

public static int jump(int current, String code){
    int count = 1;
    boolean flag = false;
    if('[' == code.charAt(current)){
      current++;
      while(flag == false){
        if('[' == code.charAt(current)) count++;
        else if(']' == code.charAt(current)) count--;
        if((']' == code.charAt(current)) && (count ==0)){
          flag = true;
          break;
        }
        current++;
      }
    }

    else{
      current--;
      while(flag == false){
        if(']' == code.charAt(current)) count++;
        else if('[' == code.charAt(current)) count--;
        if(('[' == code.charAt(current)) && (count ==0)){
          flag = true;
          break;
        }
        current--;
      }
    }
    return current;
  }

But the more I look at this code the more I feel like "there's got to be a smarter way of doing it then a bunch of if-statements, a while loop, and a flag." But I'm not good enough at this point to figure out how to simplify what I've written (or the logic) into more readable, or smarter code. So I was hoping to find ways to improve this code since I find myself writing this kind of code from time to time and would like to improve the style if possible.


texts:
I'm currently implementing permissions into an application and are trying to save this onto a database using Hibernate. There are modules with commands and the permissions are also categorized using possible-null role, text channel and role+text channel.
Therefore I want to achieve the following:

You can either deny/allow modules or commands
You can allow/deny them by server, by server role, by text channel, or by server role and text channel or for a specific user
There are also general permissions, that are plain string key-value

I created the following class for it:
@Entity
public class Permission implements IPermission {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private long guildId;

    @Column
    @Enumerated(EnumType.STRING)
    private Permission.Type type; // GENERAL, GLOBAL, SERVER, ROLE, ROLECHANNEL

    @Column
    private String permissionKey;

    @Column(nullable = false)
    private long channelId;

    @Column(nullable = false)
    private long roleId;

    @Column(nullable = false)
    private long userId;

    @Column
    @Enumerated(EnumType.STRING)
    private Tribool action; // TRUE, NEUTRAl, FALSE

    @Override
    public long getId() {
        return this.id;
    }

    @Override
    public long getGuildId() {
        return this.guildId;
    }

    @Override
    public long getChannelId() {
        return this.channelId;
    }

    @Override
    public long getRoleId() {
        return this.roleId;
    }

    @Override
    public long getUserId() {
        return this.userId;
    }

    @Override
    public Optional<String> getModule() {
        if(this.permissionKey.startsWith("module.")) {
            return Optional.of(this.permissionKey.split(".")[1]);
        } else {
            return Optional.empty();
        }
    }

    @Override
    public Optional<String> getCommand() {
        if(this.permissionKey.startsWith("command.")) {
            return Optional.of(this.permissionKey.split(".")[1]);
        } else {
            return Optional.empty();
        }
    }

    @Override
    public Tribool getAction() {
        return this.action;
    }

    public static enum Type {
        GENERAL,
        GLOBAL,
        SERVER,
        ROLE,
        CHANNEL,
        ROLECHANNEL
    }

}

But I don't know if this a good way of saving it.


texts: Search/match algorithm between 2 vectors

texts:
I have 2 vectors of Facebook-like pages which are represented by an ID from 2 different users. I want to verify the number of liked pages that are similar between these 2 users.

This is my algorithm that I am using right now, which is basically a search into all rows and columns of a matrix:

for(int i = 0; i < 100; i++) {
 val = [user_like objectAtIndex:i];
 id like_user = [[val allValues] objectAtIndex:0];
 NSLog(@"like user %d is %@",i, like_user);

 for (int j = 0; j < 100; j++) {

 val2 = [friend_like objectAtIndex:j];
 id like_friend = [[val2 allValues] objectAtIndex:2];
 NSLog(@"like friend %d is %@",j, like_friend);

 if (like_user == like_friend) {
 //do something
 }

 }

 }

How can I optimize this search/match algorithm?


texts: Website with images that pan to different sides

texts:
I've just started programming with JavaScript and I am currently working on this hobby website project of mine. The site is supposed to display pages filled with product images than can be "panned" to either the left or right. Each "page" containing about 24 medium sized pictures, one page almost completely fills out an entire screen. When the user chooses to look at the next page he needs to click'n'drag to the left (for example) to let a new page (dynamically loaded through an AJAX script) slides into the view.

This requires for my JavaScript to "slide" two of these mentioned pages synchronously by the width of a screen. This results in a really low framerate. Firefox and Opera lag a bit, Chrome has it especially bad: 1 frame of animation takes approx. 100 milliseconds, thus making the animation look very "laggy".

I do not use jQuery, nor do I want to use it or any other library to "do the work for me". At least not until I know for sure that what I am trying to do can not be done with a couple of lines of self-written code.

So far I have figured out that the specific way I manipulate the DOM is causing the performance-drop. The routine looks like this:

function slide(){
this.t=new Date().getTime()-this.msBase;

if(this.t>this.msDura)
{
this.callB.call(this.ref,this.nFrames);
return false;
}

//calculating the displacement of both elements
//
this.pxProg=this.tRatio*this.t;

this.eA.style.left=(this.pxBaseA+this.pxProg)+'px';
this.eB.style.left=(this.pxBaseB+this.pxProg)+'px';

if(bRequestAnimationStatus)requestAnimationFrame(slide.bind(this));
else window.setTimeout(slide.bind(this),16);

this.nFrames++;

};

...

//starting an animation
//
slide.call({ 'eA':theMiddlePage,
'eB':neighboorPage,
'callB':theCallback,
'msBase':new Date().getTime(),
'msDura':400,
'tRatio':((0-pxScreenWidth)/400),
'nFrames':0,
'ref':myObject,
'pxBaseA':theMiddlePage.offsetLeft,
'pxBaseB':neighboorPage.offsetLeft
        });

I've noticed that when I let the AJAX script load less images into each page, the animation becomes much faster. The separate images seem to create more overhead than I have expected. Is there another way to do this?

(Reposted from Stack Overflow here)


texts: Finding whether a number of the form 1444....4 is a perfect square

texts:
Someone asked me

  We know that \$12^2 = 144\$ and that \$38^2 = 1444\$. Are there any other perfect squares in the form?

Here is my code:

public class OneFours {
public static void main(String args[]) {
    final int power_of_ten = 8;
    int num = 14;
    for (int i = 0; i <= Math.pow(10, power_of_ten); i++) {
        if (Math.pow((int) Math.sqrt(num), 2) == num) {
            System.out.println(num + " is a perfect square with root "
                    + Math.sqrt(num));
        }
        if (i % (Math.pow(10, power_of_ten) / 100) == 0)
            System.out.println("--- Progress "
                    + (int)((i / Math.pow(10, power_of_ten)) * 100) + "% complete");
        num = num * 10 + 4;
    }
}
}


texts:
I'd like to improve the readability of the following code. The aim of this code is to apply formatting to row(s) in a WinForms DataGridView based on the Priority of an item, determined either by its currentPriorityValue or its dueDate property.

Because I've got tiger striped rows in the grid I used the modulo ternary to get the background to use by default. Then test for the High or Medium priority conditions and set the rowStyles conditionally.

I refactored to use a Tuple because it seemed to tidy the code up bit and let me assign values in my conditional logic, so there was just a single call to FormatRowStyle after the if/else if/else, but in the call to FormatRowStyle I think it no longer clearly expresses what it is doing. Specifically I don't like the if/else block and I don't like the call to FormatRowStyle with the nested Tuple properties showing as Item2.Item1...

Currently this logic is at the UI level. It is a presentational decision but I feel that it should be possible to have the logic handled elsewhere and that would make it easier to test.

private void ConditionallyFormatRowsForUrgency(int rowIndex, DateTime dueDate, string currentPriorityValue)
    {
        var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;
        var rowStyles = new Tuple<int, Tuple<Color, Color, Font>>(rowIndex, new Tuple<Color, Color, Font>(defaultBackColour, Color.Black, VisualSettings.RegularFont));

        if (ToDoUrgency(currentPriorityValue, "High", dueDate, 2))
            rowStyles = new Tuple<int, Tuple<Color, Color, Font>>(rowIndex, VisualSettings.HighPriorityStyle);
        else if (ToDoUrgency(currentPriorityValue, "Medium", dueDate, 7))
            rowStyles = new Tuple<int, Tuple<Color, Color, Font>>(rowIndex, VisualSettings.MediumPriorityStyle);

        FormatRowStyle(rowStyles.Item1, rowStyles.Item2.Item1, rowStyles.Item2.Item2, rowStyles.Item2.Item3);
    }

private static bool ToDoUrgency(string currentPriorityValue, string priorityLevel, DateTime dueDate, int daysGrace)
    {
        return currentPriorityValue == priorityLevel || dueDate <= DateTime.Now.AddDays(daysGrace);
    }

private void FormatRowStyle(int rowIndex, Color backColour, Color foreColour, Font font)
    {
        dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = backColour;
        dataGridView1.Rows[rowIndex].DefaultCellStyle.ForeColor = foreColour;
        dataGridView1.Rows[rowIndex].DefaultCellStyle.Font = font;
    }


texts:
My tooltip works fine, but I need to simplify this code.

var genderSelect = {

  getGenderSelect: function () {
    if(this.val('Girl')){
      $(this).find('#girl-character').show();
      $(this).find('#boy-character').hide();
    }else if(this.val('Boy')){
      $(this).find('#boy-character').show();
      $(this).find('#girl-character').hide();
    }
  },

  init: function(){
    $('.control-label input[name="gender"]').change(
      $('#caracters').show();
      genderSelect.getGenderSelect();
  )};

};

genderSelect.init();


texts: Find two distinct subsets of a list that add up to the same value

texts:
This code should partition a list into two subsets of the given list that add up to the same number: for example [15, 5, 20, 10, 35, 25, 10] -> [15, 5, 10, 15, 10], [20, 35] would be a valid solution. I'm looking for any tips to improve code style (be more Pythonic) or performance (mainly improvements to the algorithm used, but Python-specific things are also welcome). Thanks!

from collections import Counter

def partition_into_equal_parts(l):
    '''Partitions s into two subsets of l that have the same sum.

    >>> problem = [15, 5, 20, 10, 35, 25, 10]
    >>> first, second = partition_into_equal_parts(problem)
    >>> valid_solution(first, second, problem)
    True
    '''
    total = sum(l)
    # If sum is odd, there is no way that total = sum(first) + sum(second) = 2 * sum(first)
    if total % 2:
        return
    first = subset_sum(total // 2, l)
    if first is None:
        return
    second = []
    # Fill second with items from counter
    second_counter = Counter(l) - Counter(first)
    for number, amount in second_counter.items():
        second.extend([number] * amount)
    return first, second

def valid_solution(first, second, problem):
    return sum(first) == sum(second) and Counter(first) + Counter(second) == Counter(problem)

def subset_sum(k, lst):
    '''Returns a subset of lst that has a sum of k.

    >>> sum(subset_sum(24, [12, 1, 61, 5, 9, 2]))
    24
    >>> subset_sum(53, [12, 13, 14])
    '''
    return recursive_calculate(k, sorted(lst, reverse=True), 0)

def recursive_calculate(k, lst, start):
    for idx in range(start, len(lst)):
        if lst[idx] == k:
            return [lst[idx]]
        elif lst[idx] < k:
            rest = recursive_calculate(k - lst[idx], lst, idx + 1)
            if rest is not None:
                rest.append(lst[idx])
                return rest


texts:
I need to perform some expensive calculation, such as determining a Fibonacci number:
/// Calculate the Nth Fibonacci number (inefficiently)
func fib(n: Int) -> Int {
    n > 1 ? fib(n: n-1) + fib(n: n-2) : n
}

My project contains a number value types that need to perform calculations like fib based on their properties:
struct Fibber : Hashable {
    /// The index in the sequence
    var n: Int

    /// The calculated Fibonacci number at _n_
    var fibcalc: Int { fib(n: n) }
}

It works fine. But it is slow!
class FibberTests: XCTestCase {
    func testFibCalc() {
        measure { // average: 1.291, relative standard deviation: 1.5%
            var fibber = Fibber(n: 1)
            XCTAssertEqual(1, fibber.fibcalc)
            fibber.n = 25
            XCTAssertEqual(75_025, fibber.fibcalc)
            fibber.n = 39
            XCTAssertEqual(63_245_986, fibber.fibcalc)
        }
    }
}

So I make a single global dictionary that is keyed on source code location, and contains a map from a Hashable instance to the result of some arbitrary calculation:
/// Singleton global memoization cache, keyed on source code location and input hashable
private var memoized = Dictionary<String, Dictionary<AnyHashable, Any>>()

The cache key will be something like: "function:fibcalc file:Fibber.swift line:47".
Any Hashable instance can utilize this function to perform and memoize a calculation based on the key type, and return that cached value on subsequent invocations of the same call:
extension Hashable {
    /// Caches and returns the result of the `calculation` function.
    public func memoize<T>(function: StaticString = #function, file: StaticString = #file, line: Int = #line, _ calculation: (Self) -> T) -> T {
        let cacheKey = "function:\(function) file:\(file) line:\(line)"
        let hashKey = AnyHashable(self)
        if let cached = memoized[cacheKey]?[hashKey] as? T { return cached }
        if memoized[cacheKey] == nil { memoized[cacheKey] = Dictionary() }
        let calculated = calculation(self)
        memoized[cacheKey]?[hashKey] = calculated
        return calculated
    }
}

Memoizing these expensive calculations is now very simple:
extension Fibber {
    /// The cached fib. Repeated calls on the same source instance will return the memoized result for this instance.
    var fibmemo: Int { memoize(\.fibcalc) }
}

And we get an order-of-magnitude speedup!
extension FibberTests {
    func testFibMemo() {
        measure { // average: 0.132, relative standard deviation: 299.9%
            var fibber = Fibber(n: 1)
            XCTAssertEqual(1, fibber.fibmemo)
            fibber.n = 25
            XCTAssertEqual(75_025, fibber.fibmemo)
            fibber.n = 39
            XCTAssertEqual(63_245_986, fibber.fibmemo)
        }
    }
}

Assumptions:

the Hashable key will always be a value type (this isn't currently enforceable in Swift)

Non-Issues:

Thread-safety: locking can be added to the cache later
Unbounded memory growth: memoized Dictionary will be converted to an NSCache

Valid Issues:

Duck typing: the keys are AnyHashable and the values are Any, so runtime type conversion is used (yuck)

My main question is: is this a good idea? Are there any issues with the cache key using the source location?