vendredi 30 avril 2021

Is VIPER really helpful in android development?

I see in some jobs posts they require an android developer who works using VIPER, so I tried to read and learn about it and started with this tutorial which the only good one I found, there are a few tutorials which I found about VIPER, but at the end of the mentioned tutorial, the writer said it's hard to implement the Router layer which is a base layer of VIPER and after a while of making the tutorial he found this library which could apply this layer finally. But I ask what the key in this layer to make me use it? isn't MVVM good or Even MVI and why I need a router layer or even a 3rd party library to implement this layer? isn't a navigation jetpack is a great tool for that? did I miss something?

Functional patterns and classifications

I'm developing a data processing pipeline "factory". In order to think, organize, and search about the computation components it would be useful to have some concepts and vocabulary to characterize and classify functions based on characteristics of their inputs and/or outputs.

Otherwise put, I'm looking for a vocabulary to develop a taxonomy of functional design patterns.

I'll list some of my own notes, as a matter of example, but feel that there's probably well established ways of describing functional patterns.

For example, I can characterize functions based on the number of inputs and outputs

  • simple function: Single input and output
  • sink: function with no output (or null output)

The nature or kind of their inputs or outputs:

  • sequencers: Functions that take a sequence/stream as an input
  • boolean: functions that return True or False

Some characteristic/feature of what the function does with the input (or relationship between input and output):

  • sorter: takes a sequence of items and outputs a sequence of the same size, but arranged in a specific manner
  • filter: takes an sequence of items and outputs a subsequences, e.g. positive_numbers_only([1,-2,3,-4,3]) -> [1,3,3])
  • filter_decider: takes a single output and outputs a boolean (interpreted as take/do_not_take, e.g. is_positive(x) -> x>0)
  • flattener: takes a nested structure and outputs a flat version of the same, without loosing any information (example [[1,2,3],[4,5]] -> [1,2,3,4,5])
  • aggregator: takes a sequence and outputs an object that involved every element of the sequence, but with a reduction of information (example, sum, mean, unique_values...)

What is the best regex for including the entire first number after a square root?

Sorry for the butchered title. I am attempting to create a calculator and need to find the first number (including negative and decimals) in a number of different cases.

One particularly difficult case includes square roots. Currently, it doesn't include anything past the first number. It is supposed to include the entire number.

Pattern for first number: "[0-9]\\d*(\\.\\d+)?(?=.*(\\-)?[0-9]\\d*(\\.\\d+)?)"

Ex."√10" returns 1 instead of 10.

Any help is appreicated! Thanks for reading this far.

create a html file with the output of a program (python)

I have to write a program which reads from keyboard some info then creates a HTML file and a JSON file through Factory method design pattern. I have a uml diagram for help click here for image Ignore the class TextFile

This is how I started

from abc import ABCMeta, abstractmethod


class File(metaclass=ABCMeta):

    def __init__(self, title, author, paragraphs):
        self.title = title
        self.author = author
        self.paragraphs = paragraphs

    @abstractmethod
    def read_file_from_stdin(self):
        pass

class HTMLFile(File):
    def read_file_from_stdin(self):
        self.title = input("Enter the title: ")
        self.author = input("Enter the author")
        number_paragraphs = input("Enter the no of paragraphs:")
        self.paragraphs = input("Enter the paragraphs:")

    def print_html(self):
        print("<html>")
        print("<title>" + self.title + "</title")
        print("</html>")


class JSONFile(File):
    def read_file_from_stdin(self):
        self.title = input("Enter the title: ")
        self.author = input("Enter the author")
        number_paragraphs = input("Enter the no of paragraphs:")
        self.paragraphs = input("Enter the paragraphs:")

    def print_json(self):
        pass


class FileFactory:
    def factory(file_type):
        if file_type == "HTMLFile":
            return HTMLFile("Some title", "Some author", "Some paragraphs")
        if file_type == "JSONFile":
            return JSONFile("Some title", "Some author", "Some paragraphs")
        print("Invalid type")
        return -1

if __name__ == '__main__':
    choice = input("Enter the type of file:")
    file = FileFactory.factory(choice)
    file.read_file_from_stdin()
    file.print_html()


My question is about printer methods from each class. I guess I should print the file after its creation right? But how do I create a html file with my output?

Also, in the uml diagram, the method factory from FileFactory returns a File but the File class is abstract and I get an error. How to return just HTMLFile/JSONFile without parameters? If I write just return HTMLFile() for example, I get error because it needs the arguments title, author and paragraphs.

When to use type erasure in Swift?

There are already a lot of questions on how to do type erasure in Swift, and I've seen type erasure often described as an important pattern for working with protocols with associated types and generic types.

However, it seems to me like needing type erasure is often symptomatic of design problems — you're inherently "throwing away" type information (i.e. to put a value in a container or to pass it to a function), which often ultimately needs to be recovered later on anyway through verbose and brittle downcasting. Perhaps what I don't understand is the use case for a "type" like AnyHashable—PATs/protocols with self can only be used as generic constraints because they aren't reified types, which makes me wonder what compelling reasons there are to want to reify them.

In short, when is it a good idea to use type erasure in Swift? I'm looking for some general guidelines on when to use this pattern, and possibly examples of some practical use cases where type erasure is preferable to its alternatives.

How to avoid services in DtoMappers layer

Good day, I have a Spring Boot based backend , we are using own library to convert JPA entities to Dto's (library works based on reflection). The problem is , we inject service layer directly to some mappers. Let's say I have a UserEntity and UserDto. UserDto has a field called avatar and avatars are stored in S3. So in order to build a UserDto we are using the code like this.

@Component
class UserMapper {

 @Inject
 S3Service s3Service;

 public UserDto toDto(UserEntity entity){
     UserDto dto = new UserDto();
     BeanUtils.copy(entity,dto);
     dto.setAvatar(s3Service.getAvatarByUser(entity));

}

}

I don't like this approach because Mapper mustn't know anything about Service layer . However this mapper is used by other mappers as well. In case I want to return an OrderDto, it has a nested UserDto so OrderDto calls UserMapper internally. Are there any best practices for Mappers to be service free ?

So far I tried the following.

  1. Store avatar in ThreadLocal cache. When controller calls a service to get a user, service will store user's avatar in the ThreadLocal, and then Mapper will get it from ThreadLocal cache. Disadvantage - it's hard to test it and requires me to make Mocks
  2. Create a separate POJO called UserWithAvatar that stores UserEntity entity;String avatar and create a mapper for UserWithAvatar instead of UserEntity. Disadvantage - as I said this mapper will be used by OrderMapper and order mapper takes OrderEntity with nested UserEntity instead of UserWithAvatar

Dynamically add before/after logic to a class

I have a generic class that holds logic for running queries against a database. I want to be able to add "before" and "after" queries to the actual queries.

For instance, say I have a class that holds some UPDATE TABLE logic on the database, and I want to run before that query something that changes the session parameters, and reverts them upon finish.

Thing is, these classes are reusable, and I want to be able to parametrize these before/after queries (So a class can choose them upon instantiation)

class UpdateTableBasedOnStuff(QueryRunner):
    # Query runner holds logic to running the built queries
    def __init__(self, ...):
        ...

    def build_queries(self, table, condition):
        query = create_query_from_params(table, fields_to_update, condition)
        return [query]

So one query might want to run this thing with a user "ADMIN" and another with the user "APP", and another query might want to SET some session variables before running this. So there's some form of reusability I'd like to incorporate here, but I'm not sure what's the best approach.

Generally I'd consider the best approach the one that will let me simply pass parameters for these. e.g:

_ = UpdateTableBasedOnStuff(...,user="APP")

But I suppose there are merits to this approach as well, so having something like this might suit too:

_ = UpdateTableBasedOnStuff(...,before="SET USER = \"APP\"", after="...")

Generally I'd be glad if anyone can shed some light about the situation, and recommendations I haven't thought of.

Several things I've considered:

  1. Having optional before/after methods for the base class.
  2. Decorators, but this is a bit limiting, since I want these to be dynamic upon instantiation
  3. Utilizing context managers, but I do not see a viable way to add this to our current design.

Thank you for any form of help :)

Polymorphic reference type

I have this simple piece of code (Command pattern) that doesn't work as expected.

Usually a polymorphic type would work when it's manipulated by either a pointer or a reference. So if Command is an interface and m_command is a reference, then SetCommand should work for different concrete types of Command (eg, CommandLightOn and CommandGarageDoorOpen) ? It turns out not the case. Once SimpleRemote is instantiated with CommandLightOn, the SetCommand has completely no effect. In this example, attempt to change the underlying object to CommandGarageDoorOpen has no errors, but no effect either.

It works fine if m_command in SimpleRemote is changed to pointer type. So the question is why reference type fails to work in this case?

class SimpleRemote
{
public:
    SimpleRemote( Command& command ) : m_command{ command } {}

    void SetCommand( Command& command )
    {
        m_command = command;  //<-- broken
    }

    void ButtonPressed()
    {
        m_command.execute();
    }

private:
    Command& m_command;
};

Output:

Light is on

Light is on #<-- expect that it prints "Garage door is up"

Full code of this example (simple Command pattern):

#include <iostream>
using std::cout;

class Light
{
public:
    void On()
    {
        cout << "Light is on\n";
    }

private:
};

class GarageDoor
{
public:
    void Up()
    {
        cout << "Garage door is up\n";
    }

private:
};


// the Command interface
class Command
{
public:
    virtual void execute() = 0;
};


class CommandLightOn : public Command
{
public:
    CommandLightOn( Light light ) : m_light{ light }{}

    void execute() override
    {
        m_light.On();
    }   

private:
    Light m_light;
};


class CommandGarageDoorOpen : public Command
{
public:
    CommandGarageDoorOpen( GarageDoor door ) : m_door{door} {}  

    void execute() override
    {
        m_door.Up();
    }

private:
    GarageDoor m_door;
};


class SimpleRemote
{
public:
    SimpleRemote( Command& command ) : m_command{ command } {}

    void SetCommand( Command& command )
    {
        m_command = command;
    }

    void ButtonPressed()
    {
        m_command.execute();
    }

private:
    Command& m_command;
};


int main()
{
    Light light;
    CommandLightOn light_on( light );

    SimpleRemote remote( light_on );
    remote.ButtonPressed();

    GarageDoor door;
    CommandGarageDoorOpen door_open( door );
    remote.SetCommand( door_open );
    remote.ButtonPressed();
}

singleton is design-pattern or anti-pattern?

Some programmers believe singleton It is anti-pattern

I believe singleton is a design-pattern but some articles and programmers disagree

Why? with reason

Is this refactoring code correct for storing photos?

I am working on a project, the previous programmer used this method to save photos, videos, etc.

 if (empty($data['large_image'])) {
$large_image = $article->large_image;} else {
if ($request->hasFile('large_image')) {
    //uploads
    $cover_img_large = $data['cover_img_large'];
    //echo '<pre>'; print_r($cover_path);die;
    if (file_exists($cover_img_large)) {
        unlink($cover_img_large);
    }
    $image_path = $data['large_image'];
    $extension = $image_path->getClientOriginalExtension();
    $New_path = rand(111111, 999999999) . '.' . $extension;
    $path_path = 'upload/articles' . '/' . 'large' . '/';
    $large_image = $path_path . $New_path;
    if (!File::isDirectory($path_path)) {
        File::makeDirectory($path_path, $mode = 0777, true, true);
    }
    Image::make($image_path)->resize(800, 460)->save($large_image);
    //upoload
}}

I intend to use this method, which is close to the structure of the strategy design pattern.

interface Image{
public function image($model,$nameInput,$path);}

class saveArticle implements Image{

private $local_path="upload/articles/";

public function image($model,$nameInput,$path){
    $request = new Request();
    $data = $request->all();
    $path = $this->local_path.$path.'/';

    if (empty($data[$nameInput])) {
        return $model->large_image;
    } else {
        if ($request->hasFile($nameInput)) {
            $image_path = $data[$nameInput];
            $extension = $image_path->getClientOriginalExtension();
            $New_path = rand(111111, 999999999) . '.' . $extension;
            $name_image = $path . $New_path;
            if (!File::isDirectory($path)) {
                File::makeDirectory($path, $mode = 0777, true, true);
            }
            Image::make($image_path)->resize(800, 460)->save($name_image);
            return $name_image;
        }

    }
}}

When I use this method, I have a very simple time to use it and like the following code, I can store information with only one line.

$article = Article::find(1);
$save = new saveArticle();
$save->image($article,'image_large','large');

I have an easier task to develop the code and I can use the same method to add a movie or podcast and just add a new interface. What is your opinion? Do you think this is the right way? Thank you for guiding me. Your comments are valuable to me.

jeudi 29 avril 2021

What would you do if you wanted to put 3 icons in the navbar of an iOS app?

I have an iOS app and I need to add 3 icons to the navbar, however, when the user scrolls the screen, the 3 icons take up so much room in the navbar that the page title (which would move to the top center of the navbar) gets truncated to only a few letters on an SE (320px width).enter image description here

I also feel that 3 icons is too much for the navbar on iPhone and I have never seen it doe before.

Does anyone have a solution or example of a screen they have designed or have seen that deals with this dilemma?

I had thought about the ol' Ellipsis but Settings and Action Sheet shouldn't be inside an Ellipsis. Thanks

enter image description here

Azure Function - What Aggregation Pattern to Use?

We have the following scenario:

  1. Json Messages queued on Service Bus (they'll not all come together, will be during a specific period e.g. b/w midnight and 1 AM)

  2. We need a Function that reads the message, transforms it to a flat format and then appends that to a file

  3. File will eventually need to be sent to a Target System once the exit condition hits.

Now for this function that reads from Service Bus, I can think of 3 options.

  1. An ordinary stateless function, reads the data, creates a file as AppendBlob in Storage (if it doesn't exist) and writes (appends) data to it

  2. A singleton Function that gets triggered on first message being received on Service Bus and then receives all the subsequent messages until a time based exit condition hits, creates the file in Append Blob and keeps on appending data to it.

  3. Durable Function Aggregator pattern, I just had a quick read through it but not sure if that can be used in my scenario?

Looking for suggestions on how best to implement this scenario using Azure Functions that is reliable and doesn't run into concurrency issues, b/w we are on the latest version of Functions, so should be able to use all the latest features.

which design pattern should i follow to develop retail shopping application in flutter?

I am new to flutter application development I am confused with different design patterns and which design pattern and what state management solution should I follow that will be easy for me to understand and scale my retail shopping flutter application easily.

Task Consumer microservice architecture flow

enter image description hereI'm trying to re-building Task Consumer microservice which has below task

  • Consume rabbitMQ
  • Call to API as per need and add or update database
  • Insert initial set up data which will be used by API/UI independently.

I'm not sure whether initial set up data needs to be in Taskconsumer service or I should move it to API . API has access to DB by EFramework code first approach. So might needs to just move my DML/DDL queries to Data access layer which can be triggered by API ? .

what Initial set up data do

  1. creation of indexes on the same table which are used by API
  2. Insert Enums, Types etc which is neccessary to run the App etc.

Any suggestion/comments are welcome.

Thanks

How to setup an application to read an API and display the results in a different format in a minimal way?

I am trying to develop an application that needs to make a call to an API. Get the results and show them in a prettier format on a UI.

How my application accomplishes that right now is;

  • Call the API.
  • Deserialize the response to a c# object.
  • Check the response object if a date field is filled, check the date field on a table in my database.
  • If the API response has the date and my table doesn't, I update the date on my database.

I am aware this is very coupled to the API response and the way I save it in my database. My database table is not in the same structure as the API response because I don't want to show the data I get from the API as it is.

What is the best way to achieve this result? How to store the data from the API to make this system clean and less coupled? What are some tools I can use to achieve this? (I currently use c#/.Net, SQL Server and Angular)

A very vague question, but open to any ideas, opinions. Will be updating the question to make it more clear.

How to design this same as image using HTML.and css

how to design like that's same using HTML and css

Using Python, I am trying to print patter where each subsequent column is squared

Here is the pattern I am trying to print:

1
2 4
3 9 27
4 16 64 256
5 25 125 625 3125

Here is what I have so far, and I am stuck at this point.

for rows in range(1,5+1):
    for columns in range(rows):
        columns= (rows)**rows
        print(columns , end=' ')
    print('')

Thanks for helping a newbie!

Decoupling 'game' logic from React/front end frameworks

I was recently working on implementing battleship into react. My hang-up with getting the project done was that I really want to make the logic of battleship framework-agnostic. I don't want to have to write the 'game' in react. I want to write the game in JS, and have react handle the UI. But I'd love the ability to implement the game into another UI framework, or even a CLI.

Is this thinking butting heads with react as a framework? Or should I write some sort of event handler (observer pattern, etc.) that updates the state in react to integrate the game?

I've seen a lot of 'tutorials' about doing things like, making tic-tac toe in react, but they all tie the game logic itself INTO react. Am I just stuck in an OOP or MVC thought pattern (and not thinking in 'flux')? Does anyone have any thoughts on decoupling logic like this from react?

Ghci pattern matching/printing int list

The code outputs only the 1st element of the Int list, How can I get it to print the whole list?

Code

Call Function

Output

Call function from member class A in member class B

I have a C++ project where a set of settings are calculated by making use of a function inside another member class. In this case the other class is a motor with values acceleration time and speed. The motor class also has a member function that calculates the motion time with input distance.

The settings class should be able to calculate the motion time for different distance inputs and use/store these values. The distance value is known to the settings class but the acceleration time and speed are known to the motor class

Below is a minimum working example of my current solution. At the moment I pass the entire motor class by reference to the settings class so that it has access to "CalculateTime(double distance)". It works but I'm not sure if this is the best solution, I would like to design it according to object oriented best practices.

One possible alternative I can imagine is placing the same "CalculateTime(double distance)" function inside the settings class and then pass the acceleration time and speed values from the motor class to the Settings function (via main.cpp, making it appear a bit messy maybe?).

I have searched for similar questions but I'm having a hard time nailing the keywords to use. Especially for design pattern questions such a this one. One interesting thread I found was this one:

Communication between objects in C++

Here they talk about connectors and interfaces but I must admit I'm not qualified to judge if this case requires such a solution.

main.h

    #pragma once
        
    class Motor
    {
    public:
        Motor();
        ~Motor();
    
        double CalculateTime(double distance);
    
    private:
        double a;
        double v;
    };
    
    
    class Settings
    {
    public:
        Settings(Motor& motorRef);
        ~Settings();
    
        void CalculateTotalTime();
        double GetTotalTime();
    
    private:
        Motor& motor;
        double totalTime_;
        double distance_;
        int steps_;
    };

main.cpp

#include "main.h"
#include <iostream>


Motor::Motor() :
    a(10.0),
    v(0.5) {}

Motor::~Motor() {}

double Motor::CalculateTime(double distance) {
    return a * v * distance;
}


Settings::Settings(Motor& motorRef) :
    motor(motorRef),
    totalTime_(0.0),
    distance_(2.0),
    steps_(100) {}

Settings::~Settings() {}

void Settings::CalculateTotalTime() {
    for (int i = 0; i < steps_; i++)
    {
        totalTime_ += motor.CalculateTime(distance_);
    }
}

double Settings::GetTotalTime() {
    return totalTime_;
}


int main()
{
    Motor A;
    Settings B(A);

    B.CalculateTotalTime();
    std::cout << B.GetTotalTime();

    return 0;
}

extending class and its data member

I have a class A that has a data member data of type base_data. I would like to extend A to B by inheritance, but at the same time extend A::data to a derived type derived_data.

One possible design for that is to declare A as a template class, accepting as parameter the type of A::data.

struct base_data {
};

struct derived_data : public base_data {
};

template <class DataType = base_data>
struct A {
    DataType data;
};

struct B : public A<derived_data> {
};

The problem with this design is that, strictly speaking, B is not derived from A<>, hence functions that involve an A<> object would not compile with a B type. Example:

void f(A<>&&) { }
void f(const A<>&) { }

A x, y;
f(x);
f(std::move(y));
B xB, yB;
f(xB); // Error
f(std::move(yB)); // Error

One workaround is to declare f as template function

template <class T>
void f(A<T>&&) { }
template <class T>
void f(const A<T>&) { }

This however has the drawback that f can be called with any A<T>, which may not be desirable.

Another approach would be to constraint the argument of f to be either A<> or B

template <typename T, class = std::enable_if_t<std::is_same_v<T, A<>> || std::is_same_v<T, B>>>
void f(const T& a) { }

template <typename T, class = std::enable_if_t<std::is_same_v<T, A<>> || std::is_same_v<T, B>>>
void f(A<>&& a) { }

This is also not very elegant. Essentially, the part of a code that contains functions using A now must know that it could also use a sort-of-derived class B, perhaps defined elsewhere. Also, if there are many of such functions, one has to modify all of them to template functions as above. And if another sort-of-derived class C is added, one has to update all declarations of f and similar.

A third option would be to provide explicit conversions from B to A<>

template <class DataType = base_data>
struct A {
    DataType data;
    A() { }
    A(B&&) { }
    A(const B&) { }
};

But again, this implies that the code of A must know its sort-of-descendant B. Even worse, the copy conversion A(const B&) may be expensive and defies the simple idea that a const reference can bind to a derived class, without additional overhead.

Is there a good/better design pattern for this problem?

mercredi 28 avril 2021

How to initialize builder class members with dummy values while calling cls.builder.param().build()

I need to initialize my builder class members with some Dummy values while calling .param()

@Builder
public class MyQuery {
       private String param1;
       private String param1;
       private String param1;
       private String param1;
       ...
       private String param100;
}

When I call the builder class like below, I want them to be initialized with some dummy value(or empty string) and the rest should be null. If I use the LOMBOK builder, it has to be initialized with some value as .param1("some string"). Is there any library which can help me here.

    MyQuery query = MyQuery.builder()
            .param1()
            .param2()
            .param3()
            .build();

What's a good design for enforcing changing rules on cards in a board game? [closed]

I'm trying to code Star Trek The Dice Game. The basic concept is you roll dice, which become different types of crew (Science, Medical, Command, Engineer, etc...) and you can "spend" crew to take actions (heal people, transport people, raise/lower shields, cause the ship to travel, repair the hull, etc...).

The game has event and development cards. Event cards are bad things (like the ship takes damage, an action can't be used, you need more crew to raise shields, etc...). Development cards are good things (hull repairs fix extra hull, raise shields for free, heal fixes two people, etc...).

I'm struggling to determine how to enforce the card's rules as they enter and leave play. My concerns are two-fold:

  1. Not all rules are boolean. The rules engines I've run across seem to always assume boolean rules; an object meets the rule or doesn't. While some of the rules are boolean (ex: did the player provide enough crew to repair the hull), others aren't (ex: healing fixes an additional person).

  2. One approach might be to have booleans in different objects which track the rules in play. For instance, an HealPersonAction class that tracks if costs went up, if an extra person is healed, etc... But that means the rules knowledge is distributed across the game and I'd need messages or an observer to inform every affected object as cards enter or exit play. My instinct is encapsulating rules logic within the cards is a wiser way to go, especially since it becomes easier to change the rules later by just changing the card.

Is there a recommended design or pattern to address the problem of game cards modifying the rules in various ways?

design patterns (builder) / attribute error

I want to create simple applications using builder and prototype patterns to build different houses.

(1) Modifying the program, I added the name self._builder.name() attribute to the create_house method, which sets the name of the house for us. However, unexpectedly gets an error: AttributeError: 'House1' object has no attribute 'name'. I have no idea why this is happening since I think I have defined everything correctly.

    class Director():
    def __init__(self, builder):
        self._builder = builder

    def create_house(self):
        self._builder.name()
        self._builder.create_new_house()
        self._builder.add_basement()
        self._builder.add_rooms()
        self._builder.add_roof()

    def get_house(self):
        return self._builder.house


class Builder():

    def __init__(self):
        self.house = None

    def create_new_house(self):
        self.house = House()


class House1(Builder):
    def add_name(self):
        self.house.name = 'house1'

    def add_basement(self):
        self.house.basement = 'with basement'

    def add_roof(self):
        self.house.roof = 'wood roof'

    def add_rooms(self):
        self.house.rooms = 3


class House2(Builder):
    def add_name(self):
        self.house.name = 'house2'

    def add_basement(self):
        self.house.basement = 'no basement'

    def add_roof(self):
        self.house.roof = 'brick roof'

    def add_rooms(self):
        self.house.rooms = 5

class House():

    def __init__(self):
        self.name = None
        self.basement = None
        self.roof = None
        self.rooms = None

    def __str__(self):
        return 'Building: {} {}, {}, and {} room'.format(self.name, self.basement,
                                                           self.roof, self.rooms)


builder = WoodHouse()
director = Director(builder)
director.create_house()
house = director.get_house()
print(house)

(2) by the way, I will ask if I can improve (write less) the process of calling "building" a house. I mean this code, if I create, for example, 3 such houses, I have to repeat it, which is, however, quite unreadable and inconvenient.

builder = WoodHouse()
    director = Director(builder)
    director.create_house()
    house = director.get_house()
    print(house)

Decorator or Chain of responsibility

My application has a scheduled (weekly) task to populate different attributes of an object. This application will be multi tenant which means, for each tenant, the application might have to populate different/subset attributes. To meet this requirement, I want to choose the right design pattern for my scheduled job. Two design patterns are under active consideration.

  1. Decorator
  2. Chain of responsibility

The main difference that I could find between these patterns is that, in the former the object gets pass through each class in the pipeline whereas in the latter only one class in the pipeline will act on the object.

For decorator, I would create separate class for each attribute whereas for chain of responsibility, I would create separate class for each tenant. Is my understanding correct?

enter image description here

ps :: If my understanding is correct, I would prefer decorator.

Constructing objects in a symfony Entity php

I'm trying to create a form with different types composed out of different elements. I'm confused as to what i'm able to add into a entity class.

I don't want https://symfony.com/doc/current/forms.html, just information on this more simplistic example

<?php

namespace App\Entity;

use App\Repository\FormTypeRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=FormTypeRepository::class)
 */
class FormType
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $type;

    public function getId(): ?int
    {
        return $this->id;
    }

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

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getType(): ?string
    {
        return $this->type;
    }

    public function type(): void
    {
        /*@todo*/
    }
}

Could the type function be used to instantiate objects? Or should this be a factory or some other Design Pattern and used within a service?

interface FormTypeInterface {
  method();
}


public function type(): ?FormTypeInterface
{
  $type = $this->getType();
  if (class_exists($type)) return;
  return new $$type;
}

Where should I add the code for the interface and concrete classes? Or should I even do it that way.

service mock

class Service {
  public function handle() {
    $formTypeEntity = /* ... */
    $type = SomeFactory::make($formTypeEntity);
  }
}

Is the Target interface really necessary in adapter design pattern?

I saw a code example online that uses adapter pattern as: enter image description here enter image description here enter image description here

if you look at the HR system, the employee information in the form of string array and the ProcessSalary method of the Third Party Billing System wants to data in List. So, the HR System cannot call directly to the Third Party Billing System because List and string array are not compatible. So we use adapter pattern, the full code is:

namespace AdapterDesignPattern
{
    public interface ITarget
    {
        void ProcessCompanySalary(string[,] employeesArray);
    }
}



namespace AdapterDesignPattern
{
    public class EmployeeAdapter : ThirdPartyBillingSystem, ITarget
    {
        public void ProcessCompanySalary(string[,] employeesArray)
        {
            string Id = null;
            string Name = null;
            string Designation = null;
            string Salary = null;

            List<Employee> listEmployee = new List<Employee>();

            for (int i = 0; i < employeesArray.GetLength(0); i++)
            {
                for (int j = 0; j < employeesArray.GetLength(1); j++)
                {
                    if (j == 0)
                    {
                        Id = employeesArray[i, j];
                    }
                    else if (j == 1)
                    {
                        Name = employeesArray[i, j];
                    }
                    else if (j == 1)
                    {
                        Designation = employeesArray[i, j];
                    }
                    else
                    {
                        Salary = employeesArray[i, j];
                    }
                }

                listEmployee.Add(new Employee(Convert.ToInt32(Id), Name, Designation, Convert.ToDecimal(Salary)));
            }

            Console.WriteLine("Adapter converted Array of Employee to List of Employee");
            Console.WriteLine("Then delegate to the ThirdPartyBillingSystem for processing the employee salary\n");
            ProcessSalary(listEmployee);
        }
    }
}

// Cilent
namespace AdapterDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] employeesArray = new string[5, 4] 
            {
                {"101","John","SE","10000"},
                {"102","Smith","SE","20000"},
                {"103","Dev","SSE","30000"},
                {"104","Pam","SE","40000"},
                {"105","Sara","SSE","50000"}
            };
            
            ITarget target = new EmployeeAdapter();  <-------why not just use new EmployeeAdapter() directly?
            Console.WriteLine("HR system passes employee string array to Adapter\n");
            target.ProcessCompanySalary(employeesArray); 
        }
    }
}

I just don't understand one thing, is ITarget interface really necessary? Why not just get rid of it, then the client can do this:

namespace AdapterDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] employeesArray = new string[5, 4] { ... };
            Console.WriteLine("HR system passes employee string array to Adapter\n");
            new EmployeeAdapter().ProcessCompanySalary(employeesArray);
        }
    }
}

so that we can call ProcessCompanySalary on EmployeeAdapter instance directly?

Appropriate python design pattern

I believe I am facing a subclass explosion problem and would love some guidance..

Let's say we have a major class 'Fruit' derived from Food. Subclasses include Red,Green and Blue Apple. They all have their specific actions that they can do, but are in fact very similar. Current implementation is as follows:

class Fruit(Food):
    def __init__(self, **kwargs):
        super(Food, self).__init__(**kwargs)
        self.version = VERSION

@subclass 
class GreenApple(Fruit):
    def __init__(self, **kwargs):
        super(GreenApple, self).__init__(**kwargs)
        self.position = 0
    
    def jump(self):
        self.position += 10

    ...
@subclass
class RedApple(Fruit):
    def __init__(self, **kwargs):
        super(RedApple, self).__init__(**kwargs)
        self.pieces = 1

    def explode(self):
        self.pieces *= 2
    ... 
@subclass
class BlueApple(Fruit):
    def __init__(self, **kwargs):
        super(BlueApple, self).__init__(**kwargs)

    ...

All three apple classes are very similar and there exists conversion between them (i.e. an event can turn an Apple in to any other Apple subclass). But without a conversion GreenApple can only jump, RedApple can only explode and BlueApple can't do anything yet.

So... what I would like to know is, what kind of implementation would be better? This is of course a part of a larger project, but I tried to simplify it, just to make things clearer.

I was thinking of something like this, but I am afraid I will end up with tons of 'if' statements, which is not pretty either. Any help would be much appreciated.

class Fruit(Food):
    def __init__(self, **kwargs):
        super(Food, self).__init__(**kwargs)
        self.version = VERSION

@subclass 
class Apple(Fruit):
    def __init__(self, **kwargs, type):
        super(Apple, self).__init__(**kwargs)
        self.type = type # red/green/blue
        self.position = 0
        self.pieces = 1
    
    def jump(self):
        if self.type == 'green':
            self.position += 10

    def explode(self):
        if self.type == 'red':
            self.pieces *= 2
    
    def convert(self, type):
        self.type = type

mardi 27 avril 2021

Implementation of Mailbox in C

I have a client program which reads the data from the server and then gives the data to the application.I need to design such that application program and client program have to decoupled though they might belong to the same executable.So, I tried to simulate something like a dpm layer in between.For that I implemented a queue with a buffer element void** data so that I am able to store any type of data that is passed.

typedef struct QueueStruct {
    int size;
    int head;
    int tail;
    void** data;
} Queue;

I implemented functions memory_read and memory_write to read and write to the buffer.The client program calls the memory_write function and puts the data into the buffer and the application reads the latest data from the buffer by calling the memory_read function.I am able to achieve this much. Now I want to improve this design and implement mailbox in place of FIFO. This is what I want to acheive:

  1. Once the client writes the packet to the buffer in dpm file(queue is implemented in this file), I need to inform the application that the new data is available.
  2. Then the application reads the packet and then gives an acknowledgement to the dpm file that the data is read. So the data now can be discarded.
  3. To hide the shared memory in dpm and only give access to memory_read and memory_write functions.

I am not using any microcontroller so I do not know how to generate interrupts in simple C program to inform the application that new data is available and how to provide acknowledgement back .Should threads be created for client program and application program to decouple them? I read about named pipes and shared memory implementation in C.Are these the best ways to implement mailbox?Or there are any other better approaches available.

Edit : To read about mailbox design http://tool-support.renesas.com/autoupdate/support/onlinehelp/csp/V4.01.00/CS+.chm/Coding-RI600V4.chm/Output/MAILBOX.html

Command Design Pattern VS Callback in JS/TS

I read a lot of examples in the internet with the same idea that not to hardcode some action you use a command.

Example

Let's say you are developing a fancy UI kit. You are of course developing something that needs to be reused, so if you build a Button component, you want it to be able to execute any action, you don't want to hard-code one.

Assuming i don't need an undo mechanism when should i prefer command over callbacks?

A real World Example for MVVM

Like the Restaurant Example Used to explain MVC, is there any real-world Example to Explain MVVM architecture? Like what are the exact Role for Model, View, and ViewModel?

How to avoid downcasting in composite pattern

I use a composite pattern to represent a mechanical network, which describes the mechanical behavior of a material, see e.g. the Maxwell-Wiechert model, a spring in parallel with n Maxwell Elements. A maxwell element iteslf is a spring in series with a damper. The mechanical network is composed dynamically at runtime. To this end, I have derived Spring, MaxwellElement, and ParallelConnection from a common base class Component:

struct Component {
    virtual void add_component (Component* ) { }
    virtual Tensor<2> stress (const Tensor<2> &strain) const = 0;
    virtual ~Component () = default;
};

struct Spring : Component {    
    Tensor<2> stress (const Tensor<2> &strain) const override {return {};};
};

struct SpecialSpring : Spring {

    Tensor<1> principal_stresses (const Tensor<1> &strain_eigenvalues) const {return {};};
};

struct ParallelConnection : Component {

    void add_component (Component* c) override {components.emplace_back(c);}
    Tensor<2> stress (const Tensor<2> &strain) const override {
        Tensor<2> s; 
        for (const auto& c : components)
            s += c->stress(strain);
        return s;
    };
    std::vector<std::unique_ptr<Component>> components;
};

struct MaxwellElement : Component {

    Tensor<2> stress (const Tensor<2> &strain) const override {
        auto special_spring = dynamic_cast<SpecialSpring*>(spring.get());
        if (special_spring) {
            const auto ps = special_spring->principal_stresses (eigenvalues(strain));
            // Some cheap calculations using ps.
            return {}; // <- meaningful result
        } else {      
            const auto s = spring->stress (strain);
            // Some expensive calculations using s. 
            return {}; // <- meaningful result
        }   
    };    

    virtual void add_component (Component* c) {
        if (!spring)
            spring.reset(dynamic_cast<Spring*>(c));
        assert (spring);
    }

    std::unique_ptr<Spring> spring;
};

The goal is to compute the stress response of a material, represented by the network, for a given strain tensor (both are symmetric). Under certain assumptions, the computation within MaxwellElement::stress(const Tensor<2>&) can be significantly sped up by using the principal stresses, i.e. the eigenvalues of the stress tensor (and the corresponding eigenvectors, which has been neglected for simplicity, see this paper if you are interested in the theory). Lets assume that SpecialSpring fulfills these assumptions, but in general, Spring doesn't.

live demo of current implementation.

What really bothers me with my current implementation, is that I have to manually downcast to SpecialSpring in order to access SpecialSpring::principal_stresses(const Tensor<1> &). Of course, I could add a virtual function Component::get_type() to check whether I am dealing with a SpecialSpring, but I haven't done this here to keep the code short.

Now, I am thinking about using a Visitor like this

struct SpringVisitor {

void visit (const Spring* s) {
    result = s->stress (strain);
}
void visit (const SpecialSpring* s) {
    result = s->principal_stresses (eigenvalues(strain));
}

Tensor<2> strain;
std::variant<Tensor<1>, Tensor<2>> result;
}

Based on std::variant::index(), I can choose the correct algorithm. However, I still fells like a bad design.

Is there any better way to achieve what I have described above?

Is my current implementation the problem itself and I am dealing with sort of an XY problem?

Weird C++ design pattern: Class inheritance via include files

I came across a C++ coding pattern that is so weird that I'd really like to know where it comes from. Some classes (base classes, no ancestors) need to share certain functionality. Normally you would implement this as an ancestor class (a template if need be) from which those classes inherit which need the functionality.

Here, the programmer chose to pack the required method and data member declarations into a separate file and include this file in midst of the class declaration. They even #define'd a symbol to the name of the class being defined before the #include line. This created declarations like this:

class CMyStructure
{
public:
  CMyStructure();
  ~CMyStructure();

  __int64 m_SomeData;
  double m_SomeOtherData;

  #define DEFINE_CLASS CMyStructure
  #include "include_definitions.h"
  #undef DEFINE_CLASS
};

The included code made use of the DEFINE_CLASS symbol.

The same pattern is repeated in the implementation file, where a different file is included which defines some methods.

Does this pattern have a name? Where does it come from?

(A warning to C++ newbies: Don't use this pattern!)

Thanks, Hans

Running multiple ML pipelines with almost the same code base

I have the task of running multiple different Python ML models/pipelines(a/b test with small changes in data processing stage ). Pipelines are with almost the same code base(data processing stage)

The architecture of my application is as follows:

  1. pub/sub model with RabbitMQ
  2. 1 publisher push messages to multiply queues
  3. multiple subscribers consume data from queues
    enter image description here I have the following solutions in mind:
  • repeat/rewrite code for each ML pipeline
  • write and deploy subscribers from different git branches
  • some any solutions?

Which solution is optimal in terms of support and code duplication?

lundi 26 avril 2021

How to dynamically choose Repository object

I have this structure:

class BaseCategory {}

class Category1 : BaseCategory {}
class Category2 : BaseCategory {}
class Category3 : BaseCategory {}
.....
class Category50 : BaseCategory {}

Clients call the API passing catType like category1, category2,... and the API does the following(Repository in if/else statements):

List<Category> categories;
if(catType == "category1")
  categories = Repository<Category1>.GetAll();
else if(catType == "category2")
  categories = Repository<Category2>.GetAll();
else if(catType == "category3")
  categories = Repository<Category3>.GetAll();
else if(catType == "category4")
  categories = Repository<Category4>.GetAll();
return categories;

one of approaches could be using dynamic type which makes the first call very slow and I'll lose strong typing.

My other approach is using a dictionary with key: cateType and value: RepositoryTypeX. And I don't want to use reflection.

I wonder is there any better way to achieve this.

Design pattern that handles multiple steps

So I have a complicated onboarding process that does several steps. I created a class that handles the process but I've added a few more steps and I'd like to refactor this into something a bit more manageable. I refactored to use Laravel's pipeline, but feel this may not be the best refactor due to the output needing to be modified before each step.

Here is an example before and after with some pseudo code.

before
class OnboardingClass {
    public $user;
    public $conversation;

    public function create($firstName, $lastName, $email){

        // Step 1
        $user = User::create();
        
        // Step 2
        $conversation = Conversation::create(); // store information for new user + existing user
        
        // Step 3
        $conversation->messages()->create(); // store a message on the conversation

        // Step 4
        // Send api request to analytics
        
        // Step 5
        // Send api request to other service

        return $this;
    }
}
after
class OnboardingClass{
    public $user;
    public $conversation;

    public function create($firstName, $lastName, $email){
        $data = ['first_name' => $firstName, ...]; // form data

        $pipeline = app(Pipeline::Class);
        
        $pipeline->send($data)
            ->through([
                CreateUser::class,
                CreateNewUserConversation::class,
                AddWelcomeMessageToConversation::class,
                ...
            ])->then(function($data){
                // set all properties returned from last class in pipeline.
                $this->user = $data['user'];
                $this->conversation = $data['conversation'];
            });

        return $this;
    }
}

Now within each class I modify the previous data and output a modified version something like this

class CreateUser implements Pipe {
    public function handle($data, Closure $next) {
        // do some stuff
        $user = User::create():
    
        return $next([
            'user' => $user,
            'other' => 'something else'
        ]);
    }
}

In my controller I am simply calling the create method.

class someController() {
    public function store($request){
        $onboarding = app(OnboardingClass::class);
        $onboarding->create('John', 'Doe', 'john@example.com');
    }
}

So the first pipe receives the raw form fields and outputs what the second pipe needs to get the job done in its class, then the next class outputs the data required by the next class, so on and so forth. The data that comes into each pipe is not the same each time and you cannot modify the order.

Feels a bit weird and I'm sure there is a cleaner way to handle this.

Any design pattern I can utilize to clean this up a bit?

Guidance on architecting an Blazor App for Background Processes

I am looking for direction on how to approach this. This is a personal project of mine to learn more about web technologies since the last time I touched this stuff was when Macromedia was still in business.

I have two programs. Both are .NET CORE 3.1 and written in C#.

  • Email console app
  • Blazor server-side single page web app

The Email console app runs every 15 minutes to check to see if a Google Gmail account received any new emails. If it does certain meta data from the emails will be parsed and stored in a SQL database. Yes, I know I don’t have to poll the email every 15 minutes since Google has push support.

The Blazor web app is just an HTML table where individual table cells get updated based on SQL database changes in a real-time fashion. You can think of this table as a dashboard of sorts.

Right now both programs run on my system.

Now, my question is:

If I wanted to get rid of the Email console app and replace its functionality in the Blazor web app what libraries or techniques would I use to have a background service automatically poll the Gmail account every 15 minutes. I am quite proficient with C# but when it comes to web stuff I am still a noob so I am just looking for stuff to research to learn more. Unsure if a Microservice will make sense.

Thank you for any suggestions. Eventually, my plan it to host this Blazor web app in Microsoft Azure for my personal usage.

Design paradigm for PyTorch - SSADM, OOD

I have been developing a PyTorch model for a university project. In the thesis structure that the university has given me, they have mentioned a design paradigm. Structured systems analysis & design method and object-oriented design.

My question is that in Pytorch we have classes for the model, loss function, training, testing, and other classes like utils, Is that make the design paradigm of the project OOD? We have created objects for model and loss functions in the training class. just importing a util class to the training class makes an inheritance? The use of different classes for the model and the loss function and using them in training class can be called as abstraction?

Thank you!

Software Design and Atchitecture

Which design pattern will be applicable to a website where user can change the theme of a page. enter image description here

Modeling variables state over time

I'm trying to model my business in Java so I can run simulations and find optimal inputs etc. The concept I'm struggling with is how to model an objects state over time. For example imagine we have a class called Farm, it has some variables which remain constant such as area & location etc. But over that Farm's lifetime we will have different lengths of grass, sometimes we will cut the grass for hay etc. There are also different types of grass we can put in which will grow at different rates at different times of year etc. My question is how to create a class for this. If I wanted to get the grass height on date x and compare it to the grass height on date y, how would you set up your class to do so? Are there any patterns related to this implementation?

My initial thought was to create another class Timeline which would essentially hold an object for every day in a list then when it comes to run the program, the Farm class works it's way through that list to build it's model. However, it's been very complicated to implement and I feel there is a much better way to go about it.

dimanche 25 avril 2021

Java simplifying a repetitive code snippet to a function within ActionListener

I am wondering what is an elegant and effective way of simplifying the following snippet of code. Since I have many more buttons and their mechanics all behave in the same way, the symmetry of the methods, and the alternation from color.green -> color.red suggests there may exist a way of simplifying this down to a function?

I have been scratching my head on this design problem for a while, the way I am coding it seems definitely wrong and cumbersome.

GameFrame Class

public class GameFrame extends JFrame{

// (...)
static void initializeComponents(GameFrame frame, GamePanel GamePanel) {

// (...)
ArrayList<JGradientButton> buttons = new ArrayList<JGradientButton>();
Collections.addAll(buttons, b1,b2,b3,b4,b5);
for(JGradientButton button : buttons) {
            button.addActionListener(new ActionListener() {
                
                @Override
                public void actionPerformed(ActionEvent e) {
                    if(button == b1) {
                        GamePanel.b1Pressed();
                        
                    } else if (button == b2) {
                        GamePanel.b2Pressed();

                        if(GamePanel.removeFlag) {
                            button.color = Color.green;
                        } else {
                            button.color = Color.red;
                        }
                        button.repaint();
                        
                    } else if (button == b3) {
                        GamePanel.b3Pressed();  

                        if(!GamePanel.collisionFlag) {
                            button.color = Color.green;
                        } else {
                            button.color = Color.red;
                        }
                        button.repaint();
                     } else if (button == b4) {
                        GamePanel.b4Pressed();
                        if(!GamePanel.electricFlag) {
                            button.color = Color.green;
                        } else {
                            button.color = Color.red;
                        }
                        button.repaint();
                
                     } else {
                        GamePanel.b5Pressed();
                        if(!GamePanel.gravityFlag) {
                            button.color = Color.green;
                        } else {
                            button.color = Color.red;
                        }
                        button.repaint();
                     }
                } 
            });
        }
// (...)

}

I am unsatisfied with the above method since I have many buttons and the code for them alternating takes up easily ~100 lines of code. The symmetry of alternation suggests to me that there might exist a better approach for this design.

I have tried writing a function that takes the buttons list but the fact that we are overriding with actionPerformed confuses me a lot, and I don't know if there actually exists a way of simplifying this.

How to change the output pattern? [closed]

//#include "stdafx.h"
#include <iostream>
using namespace std;
float r1;
float r2;
float area1;
float area2;
float redarea;
#define pi 3.142


int main()
    {
    cout << "Insert value of radius 1" << endl;
    cin >> r1;
    cout << "Insert value of radius 2" << endl;
    cin >> r2;
    area1 = pi * r1 * r1;
    area2 = pi * r2 * r2;
    redarea = area1 - area2;
    cout << "Area of red shaded region" << endl;
    cout << redarea;

    return 0;

    }

Hey guys I have a question about C++. Here I have done a code for the Lab Activity 2 coding but when Lab activity 3 need me to change the output pattern into a specific pattern, may I know how to change it and the solution about it. Here I will attach my original coding for Lab Activity 2.

Question pattern needed

Using actions on React without a Dispatch function is correct?

I'm implementing Redux on React and it's currently working, but I'm not sure if it's correct. I have a redux folder with 3 files: actions, reducers and store.

Actions has this code:

export const SETTER_USER = "SETTER_USER"

export const setterUserAction = ({ email, username, role, lastVideo }) => ({
  type: SETTER_USER,
  payload: { email, username, role, lastVideo }
})

I'm calling this action from the component, this is the code on the component:

import React, { useState, useEffect } from "react";
import { connect } from 'react-redux'
import { setterUserAction } from '../../redux/actions'
...

const Login = ({ navigation, user, setUser }) => {
...
}

const mapStateToProps = state => ({
  user: state.user
})

const mapDispatchToProps = ({
  setUser: setterUserAction
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)

I used to have the action inside the component, which I can imagine is not ideal. So I moved it to an actions.js file. But now I'm not using a dispatch function, which feels weird as dispatch is part of the whole pattern. So, what do you think? Is this correctly implemented? Or it's just working by luck?

Database comparison with Larvavel Framework, is my conncept correct?

I am using the MVC framework from Laravel. My goal is to compare records from at least two different database servers and tell which data is missing. To do this, I need to establish at least two connections to the different servers under Laravel. Do I have to create this connection under Model to do the SQL queries with the controller? If I have created these connections under Model, is it possible to join the tables from the models with the controller? Can anyone recommend me an example or good documentation on how to build two models with different database connections? Are there even better software architecture patterns I can consider than MVC?

samedi 24 avril 2021

Hard-coding & Redundant Code in Psycopg2 / PostgreSQL?

I am currently following a course on data engineering, and am a bit dumbfound by the examples and exercices provided in the data modeling section:

Everything is hardcoded and "copy-paste" rules the place...

Here is a brief example:

try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (1, "Amanda", "Sam", 2000, "Rubber Soul"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)

try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (1, "Amanda", "Sam", 2000, "Let it Be"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (2, "Toby", "Sam", 2000, "My Generation"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (3, "Max", "Bob", 2018, "Help!"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)
    
try: 
    cur.execute("INSERT INTO music_store2 (transaction_id, customer_name, cashier_name, year, albums_purchased) \
                 VALUES (%s, %s, %s, %s, %s)", \
                 (3, "Max", "Bob", 2018, "Meet the Beatles"))
except psycopg2.Error as e: 
    print("Error: Inserting Rows")
    print (e)

I must confess that, at first sight, I can't help but think that this is really poorly written, hard to maintain code and that using variables and loops instead would be much better.

However, remembering that I can sometime be an ignorant and arrogant simpleton, I step back and refrain from jumping to conclusion.

Could it be that this actually is standard practice ?

Could all this hard coding and copy-pasting be here for a good reason ?

Many thanks in advance for your comments

Designing shared ownership of a USB handle in Rust

During implementation of a low-level USB driver in Rust, I've bumped into a design problem. I have the following components that need to play together:

MyDriver high-level API

A high-level public API which serves as the main entry point for driver calls:

pub struct MyDriver {
    device_handle: MyDeviceHandle,
    device_type: Box<dyn DeviceType>
}

Device Handle

The device handle wraps around the rusb DeviceHandle and implement some driver-specific logic around libusb calls.

extern crate rusb;

use rusb::{DeviceHandle, GlobalContext};

pub struct MyDeviceHandle {
    usb_handle: DeviceHandle<GlobalContext>
}

Common Library Functions

Most common functions are handled easily just by passing them to the USB handle:

impl MyDriver {
    pub fn foo(self) {
        self.usb_handle.handle_foo();
    }
}

Device-specific Functions

This is where things get tricky. Some library functions depend on the active device found at runtime. So I created a common trait for that, and the crux is that each DeviceType also requires access to MyDeviceHandle in order to implement its logic.

impl DeviceType for DeviceA {
    pub fn goo(self, usb_handle: &MyDeviceHandle) {
        usb_handle.one_thing();
    }
}

impl DeviceType for DeviceB {
    pub fn goo(self, usb_handle: &MyDeviceHandle)
        usb_handle.other_thing();
    }
}

Currently the only way to have MyDeviceHandle available to each DeviceType is to pass a reference to it in each implemented function.

Is there a nice way to have a struct that has some shared ownership of MyDeviceHandle that can be instantiated upon construction and then re-used from each function?

Repository pattern practical use cases and implementation in node.js

Can someone please explain what’s the use of this pattern with example?

All I'm confused is that I can have database instance wherever I want and I have flexibility to do anything by it, am I wrong? specially is

How can I create a single repo with code for multiple lambda functions?

I'd like to create an API using API Gateway, with multiple Lambda functions to handle the requests (rather than one single monolithic lambda function).

Is there a best practice for defining & building multiple lambda function handlers in the same project repository?

How do I use DI with many different implementations of an interface with a generic type?

I am trying to create an aggregator that can loop through several implementations of an interface (IContentReader) with a generic type that is constrained to another interface (IContent). Each implementation of the IContentReader will use a different implementation of the 'IContent` interface. This does not appear to work with DI. I am kind of at a loss as to how to do this.

My requirements will expand over time to include new games each with their own readers and content. How can I make this an DI friendly solution?

Here is the interface with the generic type:

public interface IContentReader<TContent> where TContent: IContent
{    
    IList<TContent> Content { get; }

    void Read(string file);
}

Content interface:

public interface IContent
{
    int Id { get; }
}

This is an example of the aggregator that will loop through the implementations:

public class ContentReaderAggregator : IContentReaderAggregator
{
    private readonly IEnumerable<IContentReader<IContent>> _readers;


    public ContentReaderAggregator(IEnumerable<IContentReader<IContent>> readers)
    {
        _readers = readers;
    }


    public void Read(string file)
    {
        foreach (var reader in _readers)
            reader.Read(file);
    }
}

An example implementation of a type of content and a reader:

public class Game1Content : IContent
{
    public int Id { get; set; }
}

public class Game1ContentReader : IContentReader<Game1Content>
{
    public IList<Game1Content> Content { get; }
    
    public void Read(string file)
    {
        //Read implementation code
    }
}

The compiler error I get when I try to create a collection of the IContentReader implementations is CS1503

I understand this conversion error for the most part, so I'm more asking what I am doing wrong from a philosophical/design pattern point of view.

getting context under which your task is working with discord.py and asyncio

I have code that looks like this

bot = commands.Bot(command_prefix='!')

@bot.command(name="nv", description='For when you wanna get notional value')
async def getNotional(ctx):
    """Gets notional value of account"""
    await ctx.send("getNotionalValueOfAcct()")

@bot.command(name="delta", description='For when you wanna get beta weighted delta v spy')
async def getBetaWeightedDelta(ctx):
    """Gets delta"""
    await ctx.send("getBetaWeightedDelta()")

@bot.command(name="kill", description='For when you wanna kill the program')
async def killProgram(ctx):
    """kills running gram"""
    await ctx.send("program is being killed")
    bot.loop.stop()
    bot.loop.close()
    sys.exit()

bot.loop.create_task(something())
bot.run(TOKEN)

I want while im in the function something to be able to understand i'm working under the bot context so that i can send a message based on certain events on the code. Is this possible? I really would rather not pass bot through every function in the program

Sum of pairs from list: memoization, design optimalization

From a list of integers and a single sum value, I have to return the first two values in order of appearance that adds up to the sum. source of the task

I think the most optimal way to scan the list is:

  1. index 0, index 1
    
  2. index 0,          index 2
    
  3.          index 1, index 2
    
  4. index 0,                   index 3
    
  5.         index 1,           index 3
    
  6.                   index 2, index 3
    

and so on. Am I right so far?

Then I used memoization to cut numbers appearing more than twice.

The code I wrote is functional but times-out on the more advanced tests. Here it is:

def sum_pairs(ints, s):
d={}
n2_index = 0
d[ints[0]] = 1
while True:
    n2_index += 1
    if ints[n2_index] not in d.keys():
        d[ints[n2_index]] = 0
        
    if d[ints[n2_index]] == 2:
        if n2_index == len(ints)-1:
            return None
        continue
    for n1_index in range (0, n2_index):

        if ints[n1_index] + ints[n2_index] == s:
            return [ints[n1_index], ints[n2_index]]
    
    d[ints[n2_index]] += 1
    
    if n2_index == len(ints)-1:
        return None

I would appreciate it greatly if you could help me understand my mistake/mistakes and how to approach this kind of task. Cheers!

Create different request objects dynamically

Is it possible to create different objects dynamically from a superset object. For example:

SuperSet Object:

class Z { // some attributes }

class A {
      String a, m, f, c;
      int x,y,z;
      Z z;
}

Child Objects required to be created dynamically from A:

class B {
      String b; // mapped with value of a of A
      String d; // mapped with value of m of A
      int a; // mapped with value of x of A
      int b; // mapped with value of y of A
}

class C {
      String y; // mapped with value of f of A
      String z; // mapped with value of c of A
      int z; // mapped with value of z of A
      Z b; // mapped with value of z of A
}

I would like to create such different child classes having different members which are subset of parent class A.

I know the normal way of creating skeleton class for each child object wanted and then map with values from superset object. Instead is there a way to map different parent class member values to child objects members dynamically.

Is it worthy to use adapter design pattern instead of making changes in existing interface or classes?

I was going through adapter design pattern, and found we can allow us to collaborate with incompatible interface.

Now suppose, I found this example on stackoverflow.

public interface IWetherFinder {
    public double getTemperature(String cityName);
}

class WeatherFinder implements IWetherFinder{
   @Override
   public double getTemperature(String cityName){
     return 40;
   }
}

interface IWeatherFinderClient
{
   public double getTemperature(String zipcode);
}  

public class WeatherAdapter implements IWeatherFinderClient {

    @Override
    public double getTemperature(String zipcode) {

        //method to get cityname by zipcode 
        String cityName = getCityName(zipcode);

        //invoke actual service
        IWetherFinder wetherFinder = new WeatherFinder();
        return wetherFinder.getTemperature(cityName);
    }

    private String getCityName(String zipCode) {
        return "Banaglore";
    }
}

Now in this case can't we add one more method to existing interface something Like below.

public interface IWetherFinder {
    public double getTemperature(String cityName);
    public double getTemperatureByZipcode(String zipCode);
}

class WeatherFinder implements IWetherFinder{
   @Override
   public double getTemperature(String cityName){
    // some logic to get temp by city
     return 40;
   }
  
    
   @Override
   public double getTemperatureByZipcode(String zipCode){
    String city = getCityName(zipCode);
   //some logic to get the temp by city name
     return 40;
   }
   

   private String getCityName(String zipCode) {
        return "Banaglore";
    }

}

triangle side by side in C++

i wrote this code

#include <iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=2*n+1;j++)
            if(j>=n-i+2&&j<=n+i)
                cout<<'*';
            else
                cout<<' ';
        cout<<endl;

    }
}

And now I want to control how many triangles are side by side to each other, how can I do that?

For example when i choose 3 triangles with 5 rows and output this

     *         *         *
    ***       ***       ***
   *****     *****     *****
  *******   *******   *******
 ********* ********* *********

And i choose 2 or 4 triangles or more with optional rows like that output the triangles printed side by side Thank you.

vendredi 23 avril 2021

Inheritance of decorator pattern

In decorator pattern, an abstract class implements an interface and a concrete class(decorator) extends the abstract class. What happens to the functionality of the pattern if the concrete class directly implements the interface instead of inheriting it through an abstract class?

What are the state of the art python frameworks/libs to learn code from?

Reading well designed and well written code is an excellent way of learning from the best programmers out there.

I am looking for a recommendation of some python codebase that is:

  • written in pythonic idiomatic way
  • not too cryptic / hacky
  • not too domain specific
  • not over-engineered

The standard library is obviously a good example, but can you recommend some other packages? I am sure there is a lot of projects in PyPI worth the time. Any suggestions?

Class Factory for classes with constructors that require different set of arguments

I am trying to perform a Class Factory (maybe not the right term to use here, not 100% sure) in which the constructors of the different classes to be instantiated through this factory may potentially have different arguments in their constructors, like so:

module.py

class A:
    def __init__(self, a=None):
        pass

    def run(self):
        pass

class B:
    def __init__(self, a=None, b=None):
        pass

    def run(self):
        pass

class C:
    def __init__(self, a=None, b=None, c=None):
        pass

    def run(self):
        pass

The problem that I am facing is how to handle the different types of arguments for the different classes to be instantiated. In the code below, if I instantiate the class with unexpected arguments we will get an exception. I know that using kwargs could solve this, but the problem using kwargs is that the list of arguments become implicit and thus the signature of the function does not fully explain what the function needs. The last example in the code below attempts to filter the incoming arguments based on the arguments of the class constructor. This would be a possible solution I think, but I was wondering if there was a design pattern or technique that could help me achieve this in a cleaner way?

example.py

import inspect
import module

# Runs OK
runner_class_name = 'C'
runner_class = getattr(module, runner_class_name)
runner_class(a=1, b=2, c=3)


# Runs KO, throws TypeError: "__init__() got an unexpected keyword argument"
runner_class_name = 'A'
runner_class = getattr(module, runner_class_name)
runner_class(a=1, b=2, c=3)


# Runs OK
runner_class_name = 'A'
runner_class = getattr(module, runner_class_name)
constructor = getattr(runner_class, '__init__')
args = inspect.getfullargspec(constructor).args
incomig_args = {'a':1, 'b':2, 'c':3}
safe_args = {k:incomig_args[k] for k in args if k in incomig_args}
runner = runner_class(**safe_args)

Thanks for any insight you could give!

problem with printing stars in 'S' pattern

I have some problems with my code...

I want to get this pattern: Sshape but with my code I'm getting this one:

ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
oooo
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo
oooo
oooo
oooo
ooooooooooooooooo
ooooooooooooooooo
ooooooooooooooooo

I can't figure it out by myself...

    for col in range(17):
        if row == 0 or (row>0 and row<3):
            print("o", end='')
        elif row>5 and row<=8:
            print("o", end='')
        elif row == 14 or (row > 11 and row < 14):
            print("o", end='')
        elif ((row ==3 or row ==4 or row ==5) and col<4):
            print("o", end='')
        elif ((row ==9 or row ==10 or row ==11) and col>=13):
            print("o", end='')

    else:
        print(" ", end=" ")


    print()

How to handle multipe if statements and cases that uses the same object in java?

I have a question of how to best order your code when using multiple if statements that uses the same object in their logic.

I am customizing column values in a table where depending on the columnId a different logic will be applied to extract the value for that specific column.

Given that I have three different columns namned "Column 1", "Column 2" and "Column 3" where both "Column 1" and "Column 3" use a customized object called obj in their logic whereas "Column 2" doesn't.

What is the best approach to order the if statements and where should I create my object? I've added three different cases, which one is best and why? Another better solotuion?

Thanks in advance!

// Case 1
public Object getColumnValue(String columndId) {
    if (columndId.equals("Column 1") || columndId.equals("Column 3")) {
        customObject obj = new customObject();
        if (columndId.equals("Column 1")) {
            // do something with the custom object
        } else if (columndId.equals("Column 3") ||) {
            // do something else with the custom object
        }
    } else if (columndId.equals("Column 2")) {
        // do something without the custom object
    } else {
        return null;
    }
}

// Case 2
public Object getColumnValue(String columndId) {
    customObject obj = new customObject();
    if (columndId.equals("Column 1") {
        // do something with the custom object
    } else if (columndId.equals("Column 2")) {
        // // do something without the custom object
    } else if (columndId.equals("Column 3")) {
        /// do something with the custom object
    } else {
        return null;
    }
}

// Case 3
public Object getColumnValue(String columndId) {
    if (columndId.equals("Column 1") {
        customObject obj = new customObject();
        // do something with the custom object
    } else if (columndId.equals("Column 2")) {
        // // do something without the custom object
    } else if (columndId.equals("Column 3")) {
        customObject obj = new customObject();
        /// do something with the custom object
    } else {
        return null;
    }
}

How to use polymorphism to create GUI classes from Model classes

I have the following situation.

  • model classes A, B, C implements general interface Model M
  • gui classes G_A, G_B, G_C implements general interface GUI G

The models are generated from an XML structure. The GUI classes should be generated from the models. How to do it in an elegant way?

I could check the type of the model (instanceof/switch) and create the GUIs, but in this way I don't take advantage of polymorphism and when a new GUI is introduced I have to complete the check/switch. Do you have a better suggestion?

jeudi 22 avril 2021

React JS - How to move method from a component which consumes context, to another module

I need to consume Context API within modules (not components).

In my app, when a user logs in, I store his data in a context (just to sync his data between components).

Storing this data in other place, and not in the state of a Context, is not the best option to synchronize the data between all the routes of my app.

I also have my "API" to connect with the server and make things like "getContent", "getMessage"... Until now, I was passing a "parse callback" (just to parse the server responses) to the "API" methods.

function ComponentA() {
     const parseContent = (contentDoc) => {
           // get current user data from context (the component is a consumer)
           // parse the data
     }

     ...
          const content = await api.getContent(contentId, parseContent)...
     ...
}

function ComponentB() {
     const parseMessage = (contentDoc) => {
           // get current user data from context (the component is a consumer)
           // parse the message data...
           // if the message has "content", then parse the content (same as parseContent) 
     }

     ...
          const messages = await api.getMessages(messageId, parseMessage)...
     ...
}

As you can see, this is something that makes me duplicating code. Because "parseContent" is can perfectly be used inside "parseMessage"

Now, I am trying to move the "parsers" methods to other modules, but some of these methods needs to consume the current user data (which is in a context). Something which makes my idea impossible to implement.

Is it common to pass "parse" callbacks to api methods in React? (Honestly, for me, this seems shitty coding) Is there any way to consume the context within a module? Any ideas?

Thank you.

How can I represent an infinite loop in a sequence diagram?

Can I say the number of iterations is (1..*)? or put a condition as [true]? How do I do this? This is to let a user attempt to login an infinite number of times.

Can someone explain what is this HeapQueue data structure and why designed it

https://learn.unity.com/project/2d-platformer-template

Have been struggling on studying this unity tutorial project. Generally speaking I am confused about the method names that are used here.

Also, I researched the algorithm of sift up and sift down but the code here seems opposed to the normal heap concept. Although there are annotation I can't fully understand this pop method.

    public class HeapQueue<T> where T : IComparable<T> {
    List<T> items;

    public int Count { get { return items.Count; } }

    public bool IsEmpty { get { return items.Count == 0; } }

    public T First { get { return items[0]; } }

    public void Clear() => items.Clear();

    public bool Contains(T item) => items.Contains(item);

    public void Remove(T item) => items.Remove(item);

    public T Peek() => items[0];

    public HeapQueue()
    {
        items = new List<T>();
    }

    public void Push(T item)
    {
        //add item to end of tree to extend the list
        items.Add(item);
        //find correct position for new item.
        SiftDown(0, items.Count - 1);
    }

    public T Pop()
    {

        //if there are more than 1 items, returned item will be first in tree.
        //then, add last item to front of tree, shrink the list
        //and find correct index in tree for first item.
        T item;
        var last = items[items.Count - 1];
        items.RemoveAt(items.Count - 1);
        if (items.Count > 0)
        {
            item = items[0];
            items[0] = last;
            SiftUp();
        }
        else
        {
            item = last;
        }
        return item;
    }


    int Compare(T A, T B) => A.CompareTo(B);

    void SiftDown(int startpos, int pos)
    {
        //preserve the newly added item.
        var newitem = items[pos];
        while (pos > startpos)
        {
            //find parent index in binary tree
            var parentpos = (pos - 1) >> 1;
            var parent = items[parentpos];
            //if new item precedes or equal to parent, pos is new item position.
            if (Compare(parent, newitem) <= 0)
                break;
            //else move parent into pos, then repeat for grand parent.
            items[pos] = parent;
            pos = parentpos;
        }
        items[pos] = newitem;
    }

    void SiftUp()
    {
        var endpos = items.Count;
        var startpos = 0;
        //preserve the inserted item
        var newitem = items[0];
        var childpos = 1;
        var pos = 0;
        //find child position to insert into binary tree
        while (childpos < endpos)
        {
            //get right branch
            var rightpos = childpos + 1;
            //if right branch should precede left branch, move right branch up the tree
            if (rightpos < endpos && Compare(items[rightpos], items[childpos]) <= 0)
                childpos = rightpos;
            //move child up the tree
            items[pos] = items[childpos];
            pos = childpos;
            //move down the tree and repeat.
            childpos = 2 * pos + 1;
        }
        //the child position for the new item.
        items[pos] = newitem;
        SiftDown(startpos, pos);
    }
}

}

This is how the pop method is used on the tick method in another class

enter image description here

How to represent polymorphic pattern when designing mongo db schema using a collection-relationship diagram

I'm designing a schema for mongo db to support app data modeling using a collection-relationship diagram that is widely used in official mongo db modeling documentation and tutorials. In some collections, I decided the best approach is to use Polymorphic Pattern.

As a simple fictional example, consider I want to embed profile information into a users collection. From the business domain, I know it exists two types of profiles: reader and administrator. Each profile shares some data fields, but also has different fields.

Applying the polymorphic pattern, a reader profile could be represented in a document like:

{
 _id: "<ObjectId>",
 email: "reader@email.com",
 ...
 profile: {
   type: "reader",
   name: "Reader's Name",
   total_reads: 1000,
   ...
 }
}

And an administrator profile could be represented in a document like:

{
 _id: "<ObjectId>",
 email: "administrator@email.com",
 ...
 profile: {
   type: "administrator",
   name: "Administrator's Name",
   total_edits: 100,
   ...
 }
}

As you can see, it implies in two differents profile subdocuments structure depended on type field.

How I represent this polymorphic pattern when designing a schema using a collection-relationship diagram?

Do you create a service to share a single function between components?

When I have a single function that isn't part of a collection of functions that serve the same purpose I don't bother creating a Service for it.

I just have a separate helper.ts file that holds those functions.

I was just wondering how others solve that problem

Creating a tree with specific depth and children

I am trying to generate a random tree using the composite pattern design. The tree must have a specified depth, and each node in the tree must have a specified number of children. In the node class, I have a List<> structure, which holds all the children of that particular node. I have attached the composite class with just the relevant code: (Note, componentNode is the interface of the composite pattern, a componentNode can be either a compositeNode or a leafNode, which is why the List<> holds componentNode).

class compositeNode implements componentNode
{
    //a compositeNode holds a list of other components inside of it 
    List<componentNode> components = new ArrayList<componentNode>();

    String name;

    public compositeNode(String inName)
    {
        name = inName;
    }

    public List<componentNode> getList()
    {
        return components;
    }

    public void addComponent(componentNode newComponent)
    {
        components.add(newComponent);
    }

    public String getName()
    {
        return name;
    }

}

This is my attempt at generating the tree:

    public static void treeGeneration()
    {
        int numChildNodes = 2;
        int treeDepth = 2;
        //getRandomNumber(1,5); 
        compositeNode tree = new compositeNode("Root");
        compositeNode currNode = tree;
        compositeNode currDepth;        

        for (int x=0; x<numChildNodes; x++)
        {
            compositeNode node = new compositeNode(generateName());
            tree.addComponent(node);
        }

        List<componentNode> treeList = tree.getList();
        Iterator<componentNode> iterTree = treeList.iterator();

        
        while(iterTree.hasNext())
        {
            currNode = (compositeNode) iterTree.next();//iterate through the children of the root node
            for (int i=1; i<treeDepth; i++)//accessing the child nodes so depth is 1
            {
                for (int x=0; x<numChildNodes; x++)
                {       
                    compositeNode newNode = new compositeNode(generateName());
                    currNode.addComponent(newNode);//add newly created nodes to the 
                }
                List<componentNode> currList = currNode.getList();
                Iterator<componentNode> iterList = currList.iterator();//iterate through the newly created nodes to add nodes to them 
                currNode = (compositeNode) iterList.next();
            } 
        }

The issue in my code is that the specified depth is only reached for the FIRST node of each list. For example, this is what the tree looks like when I execute it with a depth of 3, with each node having 2 children:

                         Root
                      /       \ 
                  Node1         Node2 
                 /     \        /     \
              Node3   Node4   Node7   Node8
             /    \          /     \
          Node5  Node6      Node9  Node10

As you can see node4 and node8 do not have any children, when I need them to have children. I understand the issue in my code is because once I have reached the end of the for loop where I am iterating until I reach the depth, it moves onto the next node. However, I have no clue as to how I am supposed to fix it. I have been stuck on this problem for hours now, any help will be appreciated. Thanks :)

Avoid if and switch statement and more generic approach

I want to avoid the use of "if" and "switch" statements which deal with specific cases and instead taking a more generic approach.

Requirement: Based on a number of requirements which are detailed below, the status of an Order may be determined to be "Confirmed", "Closed" or "AuthorisationRequired".

Inputs:

IsRushOrder: bool
OrderType: Enum (Repair, Hire)
IsNewCustomer: bool
IsLargeOrder: bool

Outputs:

OrderStatus: Enum (Confirmed, Closed, AuthorisationRequired)

Requirements (Applied in priority order from top to bottom):

-Large repair orders for new customers should be closed
-Large rush hire orders should always be closed
-Large repair orders always require authorisation
-All rush orders for new customers always require authorisation
-All other orders should be confirmed

==========================================================================================

One way i could think of implementing withoud using IF is by populating OrderStatus in collection and querying using LINQ This implementaion will get complicated quickly as we add more statuses.

public class OrderStatusAnalyzer
{
    protected static List<OrderStatus> OrderStatuses;

    public OrderStatusAnalyzer()
    {
        OrderStatuses = OrderStatusCollection.Get();
    }

    public string GetOrderStatusTypeByOrderInput(OrderInput orderInput)
    {
        var orderStatusTypes = from orderStatus in OrderStatuses
                               where orderStatus.IsNewCustomer == orderInput.IsNewCustomer
                                     && orderStatus.IsLargeOrder == orderInput.IsLargeOrder
                                     && orderStatus.IsRushOrder == orderInput.IsRushOrder
                                     && orderStatus.OrderType == orderInput.OrderType
                               orderby orderStatus.Priority ascending
                               select orderStatus.OrderStatusType;

        var statusTypesList = orderStatusTypes.ToList();
        var orderStatusType = !statusTypesList.Any() ? "VehicleRepairOrder.Order.AllOtherOrders" : statusTypesList[0];

        return orderStatusType;
    }
}
public static class OrderStatusCollection
{
    public static List<OrderStatus> Get()
    {
        // Note:
        // 1) If we have to avoid referencing null, then we can populate the data with probabilities. Populating data with probabilities will become hard Maintain as we add more status   
        // 2) this is also violating O(Open for extension and closed for modification) of SOLID principle 
        // 3) instead of passing null, if you pass actual unit test will fail
        var orderStatuses = new List<OrderStatus>
        {
            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = true, OrderType = OrderTypeEnum.Repair,
                IsRushOrder = null,
                Priority = 1, OrderStatusType = "VehicleRepairOrder.Order.LargeRepairNewCustomerOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = null, OrderType = OrderTypeEnum.Hire, IsRushOrder = true,
                Priority = 2, OrderStatusType = "VehicleRepairOrder.Order.LargeRushHireOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = true, IsNewCustomer = null, OrderType = OrderTypeEnum.Repair,
                IsRushOrder = null,
                Priority = 3, OrderStatusType = "VehicleRepairOrder.Order.LargeRepairOrder"
            },

            new OrderStatus
            {
                IsLargeOrder = null, IsNewCustomer = true, OrderType = OrderTypeEnum.Any, IsRushOrder = true,
                Priority = 4, OrderStatusType = "VehicleRepairOrder.Order.AllRushNewCustomerOrder"
            },

        };

        return orderStatuses;
    }
}