mercredi 30 septembre 2020

how to implement scala decorator pattern ? How to make use of traits correctly? Is there a easier way?

example scenario have an object on which i need to perform operations at runtime namely multiply,add

trait sample{}
class ObjectToBeOperatedOn extends sample{}
class OperationDecorator extends sample{
 this: sample=>// Is using this correct
}
class AddOperation extends OperationDecorator{}

How to make a text file to be the "database" in a Spring Rest Application?

I´m developing a Jokenpo Game using React with Spring Rest, but I can´t have a database to store all the information needed(create and delete moves, create and delete players).

I don´t know the best practice of development, or if there is some design pattern on how to store that kind of information. I know there is the folder src/main/resources where maybe I can store a text file there and thought about on the startup of the api it loads that file with the begin of the game, maybe, and after changing it during the game.

Trying to be more clear: I just would like to know the simplest way of storing information without being a database inside of a Spring Rest application. I really appreciate any helps. Thanks.

Print the following pattern for the given number of rows

Pattern for n=5

1    2   3    4   5
11   12  13   14  15
21   22  23   24  25
16   17  18   19  20
6    7    8   9   10

I have to print this pattern for n= any integer can anyone please help me with it. Thank you in advance

So this was my attempt:

n = int(input())
upper = int(n/2)+1
lower = n - upper 
start_i_lower = 0

for i in range(0, upper):
     if i != 0: 
     i = i + i
start = n*i + 1
end = start + n

for j in range(start, end):
    print(j, end =" ");
start_i_lower = i
print()

start_i_lower -= 1;

for i in range(0, lower):
    if(n%2 == 0):
      start_i_lower -= 1

start = n*(start_i_lower-1) + 1
end = start + n

for j in range(start, end):
    print(j, end =" ");
start_i_lower -= 1

print() 

How to implement interface dependent on Action and Func? Action implementation returns nothing while Func returns

I need to implement an interface to implement strategy pattern in C#.

One step would be to CreateRetryInvocationContext and second would be to execute.

Second step can be of two types ) i.e. Func or Action. Retry operation could return a value or might returns void.

So, I already have two concrete implementation for this ( i.e. RetryOperationWithResult and RetryOperarationWithoutResult ). Both of implementations are implementing 'Execute' method. But the problem is WithResult needs to return and other one dont need. How can I persue with this? Which way I can arrange interfaces to have better orchestration and less burden on client side. Kind of balanced and well testable implementation on both ends.

Here is my proposed Class hierarchy :

 public class RetryOperationWithResult<T> : IRetryProcessor<T>
{
    private Func<List<object>, T> _action;

    public RetryOperationWithResult(Func<List<object>, T> action)
    {
        _action = action;
    }

    public T Execute(RetryOperationContext retryOpContext)
    {
        T result = default(T);
        try
        {
            //Retry logic 
            //
        }
        catch(Exception ex)
        {

        }

        return result;
    }
}

and the other for Action implementation. Of course following doesn't get compiled.

class RetryOperationWithOutResult : IRetryProcessor<void>
{
     public void Execute(RetryOperationContext retryOpContext)
     {
         throw new NotImplementedException();
     }
}

What languages & technologies are best for a community website development? [closed]

I'm seeking for some guidance for a solid start in a website project :)

I'm a fresh CS graduate and currently want to try and build a community website that will include a few 'bulletin board' based pages, such as:

  • Apartment rents
  • Second handed furniture sales
  • Classes, courses & private teachers
  • Activities

and so on...

*The website will require a registration to use it. And all users can post their announcements.

My questions are:

  • What technologies should I use? maybe Django?
  • What database would be considered best for this use? lets say for a few thousand users.
  • Is there a designated design pattern for it?

Do you have an idea what would be the best combination for this use?

Thank You!

How to handle multi-users in sqflite Flutter

I build an application using Flutter and implemented my DB with sqflite,
I'm using Firebase only as my authentication (login screen).

The problem occur in the next scenario:

Lets say a User open the application for the first time and preform the registration after that he goes and login into the application. now the DB is created and the user add some items ,after adding those item the user logout and preform registration with different email then goes and login. and get access to the previous User that added the items before.

Possible solutions to implement:

  1. Delete DB when user logout (not really recommended)
  2. Using the Firebase auth token meaning saving the token or the email in each item that saves and extract data that only use the same token or email.
  3. Use firebase DB and let him handle the mess. (wanted to avoid this to prevent chargers)

If you have any ideas how to handle multi users in sqflite will be glad to see some code example. as mentioned my DB is working and the application working my problem is implementing multi users approach.

Angular Service & parent-child Component Communication

Which is the preferred approach when using depdency injection and multiple component?

Option1: Angular parent component talks with service (DI) for data and passing the data to child components?

Option2: All child component and parent component talk to the service for data ?

mardi 29 septembre 2020

Use a one controller to handle multiple models

I designed a permission system to my laravel application, but i have a doubts about design controllers, i can make a one controller to manage role, module and relations, or the best method is create a single controller to each model?

Structure:

table permission (role,module relation)
table permission_role
table permission_module (route/controller it can be accessed)

Usage:

role [Developer] can access module [code]
role [Revisor] can access module [code, deploy]

What is the best way to map assignment values with a variable amount of conditions

I am having trouble coming up with the terms to even search for solutions to a problem

I would like to move away from nested if/else statements and an iffy DB design to solve for a problem of selecting values for assignment. Values have any number of conditions for assignment:

user -

location code:12, country:us, state:fl, client code:12, Program Code:120, Job Family: agent

mapping -

Location Code,  Country,    State,  Client Code,    Program Code,   Job Family
*               US          *       *               *               agent
*               US          *       12              *               *
12              US          FL      12              120             *
12              US          FL      12              *               agent

For our current implementation our solution is to match based off of the highest total number of matches. In the above example, the user matches all 4. The latter 2 each have 5 matches, so the result is whichever entry in the database was created first. I have been searching for a while and figured I'd come here and see if anyone can help point me in the direction of a pattern to solve this.

How to write SOLID code with the Factory Method pattern?

I am studying Design Patterns and I am having some troubles with the implementation of the Factory Method.

The code written is based on these 2 articles:

My code: github

The program receives a message and how it should log in a string format ("MEMORY", "FILE", ...) and a factory method is responsible for choosing which class to implement.

Problem

If the factory method is responsible for choosing which class to implement, this responsibility should be inside of the class, like this:

    class LoggerFactory
    {
        public ILogger CreateLogger(string loggerMedium) 
        {
            return loggerMedium switch
            {
                "MEMORY" => new InMemoryLogger(),
                "FILE" => new FileLogger(),
                "DB" => new DBLogger(),
                "REMOTE" => new RemoteServiceLogger()
            };
        }
    }

What if I have an enourmous list of loggers? Everytime I need to add a logger, I have to edit this factory class, adding a new condition. It can become a huge switch case violating the Open/Closed principle.

Trying to remove this switch/case statement, my factory now has a dictionary and two methods:

  • RegisterLogger (responsible for adding the classes into the dictionary)
  • CreateLogger (returns the registered object, associated with the input string)
    class LoggerFactory : ILoggerFactory
    {
        private readonly Dictionary<string, Func<ILogger>> loggers;

        public LoggerFactory()
        {
            loggers = new Dictionary<string, Func<ILogger>>();
        }

        public ILogger this[string loggerMedium] => CreateLogger(loggerMedium);

        public ILogger CreateLogger(string loggerMedium) => loggers[loggerMedium]();

        public void RegisterLogger(string loggerMedium, Func<ILogger> factoryMethod)
        {
            if (string.IsNullOrEmpty(loggerMedium)) return;
            if (factoryMethod is null) return;

            loggers[loggerMedium] = factoryMethod;
        }
    }

and at the startup, with dependency injection I register the loggers:

        _serviceProvider = new ServiceCollection()
                .AddSingleton<ILoggerFactory>(_ =>
                {
                    // Logic here to register loggers, so that it is possible to extend the factory without modifying it
                    // OCP (open/closed principle)
                    LoggerFactory factory = new LoggerFactory();

                    factory.RegisterLogger("MEMORY", () => new InMemoryLogger());
                    factory.RegisterLogger("FILE", () => new FileLogger());
                    factory.RegisterLogger("DB", () => new DBLogger());
                    factory.RegisterLogger("REMOTE_SERVICE", () => new RemoteServiceLogger());

                    return factory;
                })
                .BuildServiceProvider();
  1. By adding the RegisterLogger method I also added one more responsibility to the factory. Does that violates the Single Responsibility Principle?
  2. I don't think that the logic to register new loggers should really be at the startup. Is it clean?
  3. How keep it clean if the logic to choose which class to implement is really complex and can't be solved by registering in a dictionary?

What is the best way to handle different layouts for landscape and portrait mode with one fragment in android studio?

I am writing an android app with java and have a fragment which must show absolutely different layouts in landscape and portrait orientations. Of course I know how to check the device orientation, but there are many initialization works that I must do in landscape case, and absolutely different initialization works in portrait case. And I do not want my code to become a heap of chaotic code with if- else statements. So I want to ask from experienced developers: What kind of code pattern must I use to handle different layouts in one fragment, maximally separate the two initialization codes, and still don't be forced to deal with a tonn of bugs? I remind that I use Java.

I've been researching on when to use factory pattern and when dependency injection and some of the answers don't make sense to me

I've been working on a legacy system and we want to cut the cord and modernize everything. For that purpose I have started researching patterns that solve some of the problems we had in the old system. There are plenty of threads here on the topic of factory pattern vs dependency injection but the answer don't always make sense to me.

Answers tend to either suggest that DI is more modern or flexible or that factory pattern still has its place, it is just used for different situations. Or even that both aren't mutually exclusive and can be implemented at the same time. Either way DI is usally made out to be more flexible. If you want to make changes you have more work to do with the factory pattern. I guess that depends on the kind of change you want to make, but to the typical scenarios I can think of it is the opposite.

Assume I'm looking for a solution for making phone calls. We might test different telephone systems and within those telephone systems different APIs. Now let's say phone functionality is integrated in several different projects and modules. If we want to switch to a different API or a new phone system with DI we have to find each project that uses the phone interface and instantiate it with a different object. So I have to find all the projects that use the interface and change at least one line code in each. If I use a factory however I can just change the Method that gets me an instance to get me an instance of the new class. One line for every single project.

In short, with DI each project would have to be updated every time a new interface is to be used but with a factory only one method needs to change. Moreover, if i want a different instance for a specific project I could just use an optional parameter. Like "GetPhoneApi("StarfaceTest")"

I never see this cited as an advantage in all the discussions, which makes me wonder if I am missing something? What exactly makes DI more flexible then?

Design pattern for methods with totally different implementations

There are a lot of writings about the difference between these design patterns: Template method, Factory method and Bridge design pattern. Anyway I have difficulty to select the right one for this context. I want to define same methods but with a different implementation based on the platform. I am tempted to use the Template method but there aren't shared implementation.

class diagram

lundi 28 septembre 2020

OOP design pattern for kmeans clustering (python)

I am trying to figure out a appropriate design pattern for my problem.

I have a single data source for many malls that I am querying and then applying preprocessing to convert them into desired features.

Then I am filtering these features for each of the mall and then applying kmeans to each of these malls separately.

I have written my code for a single mall for now by filtering by features for this mall.

I wanted to ask for some direction for a appropriate design pattern to implement my kmeans across all the malls by training my kmeans separately for each mall.

Also should I preprocess all the features for all malls together in a separate Preprocess class or should I do it globally and pass it into my class structures as an input?

I am a data scientist but don't have much background in OOP patterns. Kindly forgive me if it's a relatively trivial problem.

How to auto-save a form on Android - Best practices

Sample app

I am trying to introduce auto-save functionality on one of my Android applications. The idea is that as the user inputs first name, last name and after a fixed interval I would like to save that information to the server before the user hits Next button. The final goal is to have something similar to the draft option in the Gmail app where your email information is automatically saved. So, if there is a timer that runs every 10 seconds, I will pass the information on the screen to the ViewModel and let it deal with the logic of saving the data to the server.

A couple of options I have explored are.

  1. Execute recurring code with a specified interval using Handler.
  2. PeriodicWorkRequest -- however this option has a minimum interval of 15 minutes which is a little too much for my use case.
  3. AlarmManager -- This option runs even if your application is not currently running, In my opinion, this option can be an overkill.

I wanted to know if there are best practices/blogs around this and if anyone I on the wrong path or potential red flags with this approach.

Best practices for prefetching data in repositories before its usage in android

I am trying to apply the repository pattern in my project, I have multiple of Repos for different data an example is shown below, I want the data to be ready before its usage, so what're the best practices for doing that... My thoughts are if for example if there's a transition between fragment 1 to fragment 2, if Fragment2 wants to access specific data, then Fragment1 has to make the data ready in the repo while making the transition,
but is there a specific guide for doing that? I feel that opposes the single responsibility principle.

object LanguageRepository {

    // make this ready before its usage
    lateinit var linguisticLanguages: List<Language>

    suspend fun loadAllLanguages() {
        withContext(Dispatchers.IO) {
            
            linguisticLanguages = Transformer.transform(LanguageService.getAvailableLanguages(true))
            // todo if sth happened fetch from cache
        }
    }
}

Java pattern for refactoring abused MVC controller class

So I inherited this spaghetti back end service code base which has probably 10 years of history, it is written in Java and maven. the original author put tons of stuff in a RequestController class, which has functions like

processPostRequestV1
processPostRequestV2
....
processPostRequestV6

and

getRequestV1
getRequestV2
...
getRequestV6

and all the utility functions in just this one class.

they all read and write to the same DB (thank god), but this class has close to 20 dependent beans and 3000 lines of code.

I am wondering, what is the best pattern for refactoring this kind of code, it seems to be a orchestration layer, but what pattern should I used to manage the versions for it? (some of the versions don't even make sense, e.g. code from older version is sharing code with new one, using new dependencies etc, but that is a different matter)

In a MVC pattern, controller is supposed to gather/update data from the Model/Business layer which looks exactly like what this RequestController class is doing, what am I missing here?

dimanche 27 septembre 2020

Versioning of pipeline elements

I have developed a custom-made Python package, which provides 2 classes to play with: Stage and Step. They operate based on a Chain of Responsibility design pattern, and behave in a way where:

  • Both Stage and Step possess handle(request) method
  • Stage has a list of Stages or Steps underneath it
  • Step is the endpoint, which contains logic to be executed on the incoming request

In case of Stage, executing its handle(request) method will make it iterate over children elements in its list, and execute their handle(request) method while passing request argument in-between them (updated with each element it passes through).

In case of a Step, I have an abstract method logic(request), which needs to be overwritten by the user when inheriting from this class, in order to introduce some logic it needs to apply to incoming request argument.

Pipeline logic

Now, I would like to introduce some sort of version control mechanism inside of this pipeline, so that pipeline can identify itself with some unique marker, unique to the set of version and list of steps included in it. I need it, so that if let's say I introduce some new steps into the pipeline in the future, I would like to be able to e.g. redo so older requests, which have been done with an older version of the pipeline.

I have been wondering about what sort of mechanisms I could leverage to get this done, but so far my only idea was to tag each step & stage with version attribute, like self._version = "1.0", plus have the running script actually count number of steps+stages inside of the pipeline from Stage 0's perspective, and somehow combine it with versions sum. While simple, this would require me to remember to up-rev version attribute on each step I would rework etc., and would be prone for an error.

I was wondering, if there are any alternative methods of doing something like this?

Singleton pattern implementation. Cannot find symbol error shown [duplicate]

I was trying to implement the Singleton Pattern in a simple code.

public class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    
    public static Singleton getInstance(){
     if(instance == null){
      instance = new Singleton();
     }
     return instance;
    }
    
    public void op(){
    System.out.print("Works");
    }
    
}

public class Prove {

   
    public static void main(String[] args) {
        Singleton singleton = instance.getInstance();
        singleton.op();
    }
    
}

It keeps showing a cannot find symbol error. I was wondering why this happens

How to get rid of state or dependencies to simple reason

I have a class that has internal state and public getters:

function Section() {

  let ls = ['a','b','c','d','e','f'];
  let i = 0;

  this.map = () => ls[i];

  this.changeI = () => i=(i+1)%ls.length;

}

I have a user of this class:

function Ground() {

    let mover = new Mover(this);

    let map;

    this.map = () => map;

    this.init = () => {
        map = section.map();
    };


    this.draw = () => {
      console.log(map);
    }
}

and user of that class:

function Mover(ground) {

  let map = ground.map;


  this.dojob = () => {
    let usemap = map

    return usemap + 'X';
  }
}

Now when I call changeI, the return of the map function changes so I need to update the variable I use to draw the map in Ground function. I can make it a getter function instead of a variable as Mover class uses, but I think there is something wrong with this approach, I mean is there a better way to do this, or can I get rid of this internal state or the nested dependencies? I need an answer as simple as few abstractions as possible.

Create schedule broadcast API with node.js and Mongodb

Suppose you have to implement a schedule broadcasting to users in their application (like WhatsApp, Line). The data will send from the client (via HTML form) here the logics are,

  1. If isSchedule === false then save the message to the database and broadcast right now.
  2. If isSchedule === true then save the message to the database and wait until time reach and send the message.

How to trigger the database when the time is reaching?

The solution that appears in my mind is using cron job by retrieving data from the database every minute and check with Date.now() if timeInDB - Date.now() < 0 then just broadcast message to the user. But I'm not sure it a good solution to retrieving data every minute? Please see the diagram below, thank you. enter image description here

a question when reading the classical book Design Patterns:Element of Reusable Object-Oriented Software

I'm learning the design pattern by reading the classical book of GOF -- Design Patterns:Element of Reusable Object-Oriented Software.In Chap2:a case study, we define a Glyph abstract class for all objects that can appear in a document structure.In Glyph,there is a method and its description

virtual void Bounds(Rect&): The Bounds operation returns the rectangular area that the glyph occupies. It returns the opposite corners of the smallest rectangle that contains the glyph. Glyph subclasses redefine this operation to return the rectangular area in which they draw.

Why the return type of Bounds operation is void according to its description?

samedi 26 septembre 2020

Is it a good practise to Call stored procedure in Repository or EF

I am fairly new to EF and Repository patterns. Have coded years in Monolith 3 tier architecture , with SPs.

I am now migrating an application from Monolith to Angular/Microservice.

I am confused about using Repository patter which access Db directly. I have Business logic in SP. How good is the performance when we use these patterns with out SPs?

Clean Architecture - obtaining cached data while refreshing it using repository pattern and use cases

I have one question of best practice. I'm trying to apply Clean Architecture in a sample app using MVVM. My question is, if ViewModel is supposed to call the use cases instead of calling directly the Repository (which has access to database and the API), but I want to display the cached results while the information is being refresh, how is supposed the ViewModel to access to the cached data if it's using the use case and not the repository?

I read this post and Android official doc but I'm not sure which is the best way of achieving this behaviour.

Java design pattern to apply a set of actions based upon event type

I have a problem statement in which there are certain set of actions (A1,A2,A3,...,An). Based upon an event type (E1,E2,E3...,Em), different set of actions can be applied.

For example:

Event E1 -> A1, A3, A5

Event E2 -> A2, A5, A7

Also, more actions can be added into action set. Hence, my code should be open for extension.

I thought of applying decorator pattern, but it seems like in decorator pattern we can attach additional responsibility(actions) and return the same object. In my case it is possible that not all actions are returning the same object and might be doing/triggering a different process.

Is there any design pattern in Java which handles this scenario?

How to trigger custom code before every method of a class is executed

I am trying to create a pattern for Chrome Extensions where every time a method is called, based on whether the object is in "background script" or in "content script", either the method code is executed or a message is sent to background and the method is executed there. Manually written code would look like this:

class UnicornSpotter {

    constructor() {
         let that = this;
         listenToMessages((message) => {
             if(message === 'execute_unicorn_spotter') {
                 that.spot();
             }
         });
    }

    spot() {
        if(window.isBackgroundScript) {
             // Do the actual unicorn spotting here
        } else {
             sendMessageToBackgroundScript('execute_unicorn_spotter');
        }
    }

}

This works fine but I want to automate this message sending process so that I don't have to write code for each and every method separately. Is there a way in javascript that allows me to execute the message sending part automatically in the beginning of each method? Ideally, the methods would just contain the actual code and the message sending part is automatically triggered before the actual code.

Design Pattern in C# for Input Validation

In my micro-service I have to check if the input request is valid or not. for validation we are using 10 different functions like Name Validation, Device Validation, Email Validation etc. Now I am thinking to use a design pattern for validation.

Initially I was think to use Strategy Design pattern but in my case either the request will pass all validation or it will break in between and nothing to decide at runtime.

Later I was thinking to use Chain of Responsibilities or Iterator but now I am confused which pattern should I use ?

Is it inadvisable to instantiate data to process it?

Been running in circles on this so I thought I’d put it out there. I’m new to programming and have been learning JavaScript.

I’m trying to apply the Object Oriented perspective to my design, which involves a large collection of dynamically created objects. These objects need to be stored in a database, and accessed regularly. It feels weird to get a bunch (say 20) of items from the database and immediately pass them into a constructor to gain access to their functionality, does it feel weird because it’s a strange thing to be doing? Basically each object needs to be its own instance because it’s properties are unique, but it is of a “class” which serves a similar purpose.

I’m not sure if that made any sense, if not, I apologize. Basically.. is it weird to be instantiating a ton of data you get from a database? Should my class be broader? Will delete if this question sucks.

P.S. I know this may sound wooey but one of the hard things to get a handle on when you don’t know what you’re doing is the stuff which seems assumed to those accustomed. Even a “it depends” answer would be quite helpful.

Full-stack web development of a forum based website [closed]

I have knowledge of computers, networks, data structures, databases, programming basics and mostly everything a computer engineer is expected to know.

I have , with my team, started to work on a project of a forum website for the above mentioned course. We are planning on having a lot of modules other than forums but I have a decent idea about everything else(I think) except for the main forums part. How do I and my team go about in making a forums module for our project. My main questions are:

1.Which stack should we follow like MERN, LAMP, etc? We have built a few pages front end using html, css and javascript already.

2.What design principle works best for a forum website?

3.Relational or non- relational database would be best? and for what reason?

4.As this is a serious project, what to keep in mind from the beginning itself?

5.How do we split this work between 3 people? can all three of us focus full stack or is that a bad idea?

vendredi 25 septembre 2020

Data conversion pattern with Business Object, DTO and Entity/Domain Object

In my Spring boot project I use hibernate and basically we have three kinds of objects

  • DTO object which is used in the controller layer.
  • Business Object - business object is what we use throughout our application.
  • Entity/Domain Object - which is used in JPA layer.

When we are ready to save the data we turn the Business Object to Domain/Entity Obj

And when we are ready to send it to the client/controller we can convert the entity object to Business Obj and this Business object in turn to DTO Obj.

Ideally I was told that the conversion logic of changing BOs to -> (DTOs and entities) and vice versa reside in the BOs itself?

How do we achieve this in an efficient way? Can anyone help with any examples?

Interface segregation principle for a framework interface with optional features

I am designing a authentication framework. I need users of the framework to implement data access logic since it is not the main purpose of the framework and I want to allow multiple data access approaches (SQL, NoSQL, Cache etc.) I don't implement it inside my framework. My framework uses this logic through an interface called IUserStore but the problem is, there are certain methods inside my interface that are used only when certain feature is active and not used otherwise. For example framework will try to access two factor information through GetTwoFactorInfo method only if two factor authentication is enabled.

My question is about interface segregation principle. Is it ok to leave the interface as it is and explain in the documentation that user needs to implement GetTwoFactorInfo only if user wants to use two factor authentication and throw NotImplementedException otherwise? Or should I separate interface for each optional feature and explain in the documentation user should implement and register this interface to service provider to be able to use that feature? A problem with second approach is when injecting services that implement those interfaces to constructors, I need to check if those features are active otherwise I would get an error because service is not registered and I am trying to access those services from service provider. Which leads to extra complexity for my framework classes.

What would be the best way to handle this problem?

Simple console program but I need GoF pattern for search algortihm

I am wondering what GoF pattern to look into in case of implementing a search function in my simple Java console program.

It is basically just a registry class that has the information of all the other model classes that have been registered. I would then like to implement a search that returns members, registered, based on the search keywords used i.e. keywords: Enter name, phone number, car type, age.

I had imagined it to be like you enter the keywords you would like to search by and they would be searched as AND linking them together. Then you could get a new line to enter the keywords you would like and then those would be internally AND but linked to the former with OR.

Example(just x if you do not use keyword):

Name: John Phone-Number:x Car-Type: Wagon Age: >55 

Would return a all Johns fullfilling the other keywords but:

Name: John Phone-Number:x Car-Type: x Age:x
Name: x Phone-Number:x Car-Type: Wagon Age: x
Name: x Phone-Number:x Car-Type: x Age: >55 

Would return all Johns all owners of Wagons and all over 55

The UI is not the question/problem its just for explantation - the question is what GoF pattern should I look into for this implementation, I have been reading on them and I am not quite sure. Iterator patter maybe?

should Inter dependent microservices replicate data of dependent service

We have N microservices where N can be greater that 10. These N microservices depend on a Master Microservice M. So improving latency in our system we replicate bounded context information in each microservice 1 - N. I want to know more about it from external point of view, are we on right track or there is another way to handle such communication between microservices.

Should I Replicate Data If Data size is huge in Microservice Architecture?

Consider company like Amazon, Flipkart.

They shows our order history means they have Order Microservice and Item Detail Microservice.

So Whenever I open my order list, these sites fetch data from order microservice with list of my transaction status against the order. My best guess is they keep maintain order status against transaction Id in Order Table, that is replicated data because same data exist in Payment/Transaction Microservice also.

Can Any one tell me If this transaction data is exponentially increasing in system, did it make sense to store it in Order Microservice also.

Or My guess is wrong in this scenario.

jeudi 24 septembre 2020

Design pattern for game inventory?

Does anyone know of a design pattern that may fit this description?

There will be a focus controller which highlights and focuses an object in a game based on where the player is in the world.

The inventory will have X number of slots. The player may activate any of the slots which contain an item. When the slot is activated, depending on what is currently in focus, will affect the object in focus. I would also want to include items which affects the player, like a passive effect.

Seems like a combination of command, decorator and facade pattern.

Which Design Pattern is Best for creating Enterprise Level .Net Application? [closed]

We are Planning to create an Enterprise Level School ERP Application using WebApi, MVC, C#? Which Pattern is Best for Creating this type of Application like(Repository Pattern or any other)? And We also want to create the Android Application for the School ERP Application? Kindly Guide Me?

class containing member function pointer to own member function

I have this situation:

struct S
{
  auto f()
  {
    return [](){};
  }

  template <typename U = S>
  constexpr static auto fp{&U::f};
};


int main()
{
  (S().*S::fp<>)();
}

Where I would like to give the user flexibility to name f() whatever he wants, so a well-known member function pointer is needed, named, for example, my_library_feature_. Is this a good idea, or maybe f itself should have a well-known name? A defined member function pointer can be detected at compile time and would mean, that the class supports a certain feature, that can be used by the library, such as being able to calculate its hash, or being able to serialize itself, ... I know the alternative approach (std::hash<>), but maybe that approach belongs to a different time and I find it cumbersome anyway (possibly having to declare a friend, a separate template specialization). Aren't friends bad style?

How to best store commands and their response code for a .NET console app?

Description

My app takes user input (ReadLine()) and calls its corresponding function as a result.

At the moment, it's just a switch that checks for certain commands, with their response code inside cases, but I though I ought to separate them for cleaner code.

What's the design pattern of choice here?

Attempted Solution

I could make an abstract Command class with a commandName field and a mandatory Respond() function. Then, I'd hold a List of Commands, iterate over each to check if its commandName matches what the user input, and call its Respond() function (and break the loop) if so.

Problem

That still necessitates manually creating instances of each Command and adding them to the List that holds them.

If possible, I'd like for each Command to be automatically added. I wish to instruct the program to loop over every class in a Commands/ directory and instantiate and add it on its own, or something like that.

Can I do that? If not, what's the best alternative?

How good is the idea to use behavior tree for player movement?

I develop a game with Unity. Now I implement a player parkour (movement) system, so I try to choose pattern that will help me to keep architecture clean in the long term and easily add new states. I tried to use state machine pattern, but I realized, that it grows more and more.

So I gave up on this solution and decided to use behavior tree pattern. But now I'm starting to notice, that this architecture is going deeper and deeper and conditions for parallel states become difficult to control. I think this is not a best way to create player parkour (movement) system.

So my question is: is there a better way to create player movement system and how hard will it be to work with the behavior tree? Maybe there are pitfalls in behavior tree that I didn't notice? I'm searching for architecture, that let me perform parallel states (or analog) by conditions and will be easily maintained.

My prototype now looks like this (don't pay attention to get keys, it's just a quick plan for architecture):

Name of a color or classic color name similar for given

I apologise for silly question but it is really important for me. I have a hex #831727

.square {
  width: 15px;
  height: 15px;
  background-color: #831727;
}
<div class="square"></div>

What is a most accurate name of given color? I need this information to pick corect paint for renew a leather wallet. e.g. Burgundy, Rosewood, Carmine ...

Thank you:)

Choosing an ECU/MCU for a vehicle [closed]

I want to choose a main MCU/ECU for a vehicle design. That vehicle will have lots of sensor datas coming through from other ECU's (like engine ECU) to this main ECU. That sensor datas will be sent with CANBus, but also ethernet will be used for the ECU that will give GPS destination to our main ECU. I want to make a list of features that this ECU/MCU must have. For example:

  • This MCU/ECU might be 8, 16 or 32 bits. But there will be lots of datas coming, so 32 bit would be a better choice. In case of an interrupt, with a 8 bit ECU/MCU, the task might be left unfinished.
  • MCU/ECU should support Ethernet and CANBus interfaces.

etc. So for such a task, what kind of ECU/MCU should I choose? Or what kind of features the ECU/MCU I will choose must have?

Override final properties in abstract class Dart

I created a Abstract Class with methods and properties that a Stateless Widget can override but after implementing the class, due to Stateless Widget immutability, I had to make the widget properties final and in turn make the Abstract class properties final as well. Then, I got error that the final variable must be initialized.

What is the proper way to implement an Abstract Class with final variables?

Abstract Class

abstract class BusinessCard {
  final CardView cardView;
  final CardInfo cardInfo;
  Widget front(BuildContext context);
  Widget back(BuildContext context);
}

Implementing Class

class Card1 extends StatelessWidget implements BusinessCard {
  final CardView cardView;
  final CardInfo cardInfo;

  Card1({
    @required this.cardView,
    @required this.cardInfo,
  });

  @override
  Widget build(BuildContext context) {
    return cardView == CardView.front ? front(context) : back(context);
  }

  @override
  Widget front(BuildContext context) {

  }

  @override
  Widget back(BuildContext context) {
    
  }
}

mercredi 23 septembre 2020

Compare performance of two function applying a pattern

I compared two functions with performance.now(), so I supposed that the second function would be better than first one but it happens the other way around. I don't know why this happen? same1 has into for loop an indexOf and splice function which each one represent a O(n), so we have a O(n^2). In same2 I apply Frecuency Counter Pattern, with three for loops which represent O(3N).

Should be second function faster than first one, isn't it?

    function same1(arr1, arr2) {
        // compare length of both arrays
        if (arr1.length !== arr2.length) return false
     
        for (let i = 0; i < arr1.length; i++) {
            const indexArra2 = arr2.indexOf(arr1[i] ** 2);
            if (indexArra2 === -1) return false;
            arr2.splice(indexArra2, 1);
        }
        return true;
    } 
     
    function same2(arr1, arr2) {
        if (arr1.length !== arr2.length) return false;
     
        let arrObj1 = {};
        let arrObj2 = {};
     
        // { 1: 1, 2: 2, 3: 1 }
        for(let val of arr1) {
            arrObj1[val] = (arrObj1[val] || 0) + 1;
        }
     
        // { 1: 1, 4: 2, 9: 1 }
        for(let val of arr2) {
            arrObj2[val] = (arrObj2[val] || 0) + 1;
        }
     
        for(key in arrObj1) {
            if(!(key ** 2 in arrObj2)) {
                return false;
            }
            if(arrObj2[key ** 2] !== arrObj1[key]) {
                return false;
            }
        }
        return true;
    }
     
    const t0 = performance.now();
    same1([1,2,3,2], [9,1,4,4]);
    const t1 = performance.now();
     
    const t2 = performance.now();
    same2([1,2,3,2], [9,1,4,4]);
    const t3 = performance.now();
     
    console.log(`Call to same1 took ${t1 - t0} milliseconds.`);
    console.log(`Call to same2 took ${t3 - t2} milliseconds.`);

Understanding a C# implementation of the Extensible Enum Pattern

I see the following code in a codebase. However, I don't get how this implements the Extensible Enum pattern.

    // Summary:
    //     An "extensible Enum" .
    public class FileType : IEquatable<FileType>
    {
        public FileType(string TypeName);

        public static FileType A { get; }

        public static FileType B { get; }

        public override bool Equals(object obj);
        public override int GetHashCode();
    }

How an object can be available to all classes in java?

I am creating an application with many java classes. for keeping the configurable information like username, urls', file paths etc, I am using resources/app.properties file.

For reading values from this file, I am using below code

InputStream input = new FileInputStream("../resources/app.properties");
     
Properties prop = new Properties();

prop.load(input);
     
System.out.println("print the url" + prop.getProperty("username"));

as we can see from the code, for reading any property from app.properties file, we need prop object.

can we write this code in such a way that we just need to write first 3 lines once in the code in the main calss and then we can call prop.getProperty("username") from any class in our whole application?

Replace multiple occurences of a string pattern in data table

I have a data table where one of the column contains characters (ID). Some of its rows have a certain pattern (AB_). I would like to replace them with NA using a data.table solution. Input:

dt <- data.table(
ID = c("AB_1","AB_2","b","AB_3","a","c"),
col2 = 1:6,
col3 = 7:12)

Output:

dt <- data.table(
ID = c("NA","NA","b","NA","a","c"),
col2 = 1:6,
col3 = 7:12)

thank you

using interface and composition in java - reuse code with different variables

I have a problem during trying to do reuse code. I want to use main interface with two classes, but some of the methods have same implements, so I decided to use compostion. I mean, to declare instance of the "a" class and do on the method:

void do_some()
a.do_some()

the problem is that the function related to some data members. for example:

 public class Locker implements GeneralStorage {
    private final int current_capacity;

  public int getAvailableCapacity(){
        return current_capacity;
      }
}

public class LongTermStorage implements GeneralStorage {
    private final int current_capacity;
    private Locker locker=New Locker();
       public int getAvailableCapacity(){
           return locker.getAvailableCapacity

what can I do? (I want to return LongTermStorage.current_capacity)

Avoiding if-else with Protobuf generated enums using visitor pattern

Let's say I have a proto object as follows:

oneof sample {
     string str = 1;
     int64 i = 2;
     ... (many other fields inside oneof)
}

The autogenerated java code will generate enum for sample named SampleCase which contains

enum SampleCase {
    STR(1)
    I(2)
    ...
}

Now on the application side, I want to call methods on different objects based on the type of enum SampleCase. A naive way is to do if-else:

if(case == SampleCase.STR) {
    obj1.call();
} else if(case == SampleCase.I) {
    obj2.call();
} else if(....)
...

Visitor pattern seems a good fit here to avoid if-else. I looked at this, but that would require modifying the enums and I don't have access to modify the protobuf generated enums. Any approach how to proceed further?

Also I am open to any other design pattern that could solve this issue.

mardi 22 septembre 2020

Better way to re-design the below object creation?

We designed the below code to create an object based on the arguments, in longer run we might encounter Too many return statements from pylint. What's the best way to redesign?

def get_page(self, page_name):
    if "Login" in page_name.value:
        if self.login_page is None:
            self.login_page = Login(self.driver)
        return self.login_page
    elif "Settings" in page_name.value:
        if self.settings_page is None:
            self.settings_page = Settings(self.driver)
        return self.settings_page
    elif "Home" in page_name.value:
        if self.home_page is None:
            self.home_page = Home(self.driver)
        return self.home_page
    elif "Next" in page_name.value:
        if self.next_login is None:
            self.next_login = Next(self.driver)
        return self.next_login

Note: We defined the page names in ENUM

I don't understand why I am getting this result for substring matching in python [duplicate]

lets suppose I have a string

A = 'MRBTS-12696/GNBTS-1/GNBCF-1/GNCEL-2/TX_AXC-4163'

and I want that if

if 'LNCEL' and 'TX_AXC' in A:
    print('yes')
else:
    print('no')

It is printing yes where as it should just pass the condition and print no

I don't know if I am wrong or I am not getting the desired output. which is no.

as LNCEL is not in the string A.

code a simple logic problem in C to print pyramid pattern (emergency need help rn)

[Out put of code must look like this pattern ][1]

[1]: https://i.stack.imgur.com/JWxLF.jpg**strong text**

Instructions for code as follows No function can be more than 25 lines Each function can accept a maximum of 4 parameters Each file can have a maximum of 5 functions All the variable declarations must be on the top of each function followed by an empty line Use of for loops is forbidden Use of switch case is forbidden Use of printf or any other external C function is prohibited, unless explicitly mentioned

Only function mentioned in the subject is allowed

Your functions should not quit unexpectedly (segmentation fault, bus error, double free, etc) apart from undefined behaviors. If this happens, your project will be considered non functional and will receive a 0.

All heap allocated memory space must be properly freed when necessary.

Only the following libc functions are allowed : malloc(3), free(3) and write(2), and their usage is restricted.

How would you design a alert management system?

I am interested to gain more insights about best practices while designing an alert management system. This is a system which triggers notifications once a given matching condition is fulfilled.

Examples:

  • If number of http errors for last 15 min is more 10% of all request send me a slack message
  • If number of executions for last 1 hour less than 1 send me an email

Moreover design is technology agnostic but a references to open source pieces are welcome.

Base Requirements: (these are just clarification and an answer should not follow them)

  • Model - policies and events. Policy defines a rule which is fired matching a specific condition. Event is an exact point in time when a given policy is triggered.
  • Storage - place where policies and events are kept
  • Scheduling - a mechanism to schedule different tasks checking policies

Questions: (Some guiding questions)

  • How many base component will you define ?
  • How would you model base entities ?
  • What kind of storage would you use ?
  • How will you query the storage ?
  • How would use design scheduling mechanism ?
  • What is the biggest challenge when amount of data grows ?

I am looking moreover for solution with horizontal scaling. Note: Every answer should not strictly following any of suggested questions above.

How to refactor hard coded statuses in code with less code rewriting?

I'm using some hard coded statuses in my app to track the status of an order. For an example

1 - draft
2 - placed
3 - completed

Currently I'm keeping them in a database table as order statuses. In the app level I'm using these status to validate the order updates. Such as

  • If order status = 1, it cannot be completed.
  • If order status = 2, it cannot be deleted.
  • If order status > 2, it cannot be edited.

What I'm not sure is in the future requirements there can be new statuses between current statuses. Like

1 - draft
2 - placed
3 - partially completed 
4 - completed

How to prevent code rewriting in these kind of situations, I would have to rewrite all the conditions in the future if there are several statuses in between the current statuses.

Returning new data in a gRPC steam that should stay open forever

I have a gRPC service that will stream data to the connected client until the client terminates the connection.

I've got it working with dummy data and using Task.Delay, but I'm having trouble figuring out how to put real data into the steam.

public override async Task SubscribeToNewData(Empty request, IServerStreamWriter<MyModel> responseStream, ServerCallContext context)
{

    while(true)
    {
        var data = await GetNewData();
        await responseStream.WriteAsync(data);
    }

}

// Dummy implementation
private async Task<MyModel> GetNewData()
{
    await Task.Delay(5000);
    MyModel output = new MyModel();
    return output;
} 

public void SetData(MyModel data)
{
    ??
}

SetData is called from outside the class roughly every 5 seconds. When this happens, I wan't to immediately write the data to the responseStream.

How can I implement SetData and GetNewData to obtain this functionality?

c++ hex set of strings to array of bytes not return vector

So basically , I want to create a function that

takes this hex pattern:

"03 C6 8F E2 18 CA 8C E2 94 FD BC E5 03 C6 8F E2"

and returns this array of bytes:

BYTE pattern[] = { 0x03, 0xC6, 0x8F, 0xE2, 0x18, 0xCA, 0x8C, 0xE2, 0x94, 0xFD, 0xBC, 0xE5, 0x03, 0xC6, 0x8F, 0xE2 };

My main problem is what i need like each 0x03 in one byte cell, of the output array exactly as i described,

if i use this

std::vector<BYTE> strPatternToByte(const char* pattern, std::vector<BYTE> bytes)
{
    std::stringstream converter;

    std::istringstream ss( pattern );
    std::string word;
    while( ss >> word )
    {
        BYTE temp;
        converter << std::hex << "0x" + word;
        converter >> temp;

        bytes.push_back( temp );
    }

    return bytes;
}

    int main()
    {

        const char* pattern = "03 C6 8F E2 18 CA 8C E2 D4 FD BC E5 03 C6 8F E2";
        std::vector<BYTE> bytes;
        bytes = strPatternToByte(pattern,bytes);
        BYTE somePtr[16];
        for ( int i=0 ; i < 16 ; i++)
        {
            somePtr[i] = bytes[i];
        }


        for(unsigned char i : somePtr)
        {
            std::cout << i << std::endl;
        }
        /*
         * output should be:
          0x03
          0xC6
          0x8F
         * etc
         * .
         * .
         */

        return 0;
}

it doesn't actually do what i need because when i debug it , i look at the bytes vector and i see it puts 0 in a cell, x in a cell , 0 , in cell , 3 in cell , which is not what i want, is there anyway to solve this kind of problem ? the output aint like it should be, I added what the output should be there in the code something like this:

        /*
     * output should be:
      0x03
      0xC6
      0x8F
     * etc
     * .
     * .
     */

the somePtr array is my last output should be, with as i described up.

thanks.

lundi 21 septembre 2020

How to print specific words in the sentence that begin with pattern

I am trying to print a word that has both number and letters from a sentence that start with a specific pattern (LOCUS in this case).

#!/usr/bin/perl -w   use strict;    open (FILE, "ciona_intestinalis.gb") or die$!;    while (<FILE>) {    my $line = $_;    if ($line =~ /^LOCUS\s\w\s*([0-9_]+)/) {    my $variable = $1;    print $variable . "\n";    }    }    close FILE;

Call singleton class in spring boot rest api controller

I am new to spring framework. I have to use spring boot and have a rest controller as below :-

@RestController
public class StatisticsController {

    private TransactionCache transactionCache;

    public StatisticsController(TransactionCache transactionCache) {
        this.transactionCache = transactionCache;
    }

    @PostMapping("/tick")
    public ResponseEntity<Object> addInstrumentTransaction(@Valid @RequestBody InstrumentTransaction instrumentTransaction) {
        transactionCache.addTransaction(instrumentTransaction);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

and I have a class which needs to be singleton :-

@Component
public class TransactionStatisticsCacheImpl implements TransactionCache {

    private static TransactionStatisticsCacheImpl instance;

    public static TransactionStatisticsCacheImpl getInstance(){

        if(Objects.isNull(instance)){
            synchronized (TransactionStatisticsCacheImpl.class) {
                if(Objects.isNull(instance)){
                    instance = new TransactionStatisticsCacheImpl();
                }
            }
        }

        return instance;
    }

    private TransactionStatisticsCacheImpl() {}

I want to know the correct way to call this singleton class in my rest controller. I know that by default the scope of a bean in spring is singleton. Is this the correct way to call the singleton class in rest controller?

@RestController
public class StatisticsController {

    private TransactionCache transactionCache;

    public StatisticsController(TransactionCache transactionCache) {
        this.transactionCache = transactionCache;
    }

    @PostMapping("/tick")
    public ResponseEntity<Object> addInstrumentTransaction(@Valid @RequestBody InstrumentTransaction instrumentTransaction) {
        transactionCache.addTransaction(instrumentTransaction);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

or

We need to call it using the getInstance() method? Also do we need to explicitly have the getInstance method in the TransactionStatisticsCacheImpl class?

Powershell | Delete lines from .txt after specific pattern

InputObject   : created_at : Tue Sep 24 02:31:26 +0000 2020
SideIndicator : =>

InputObject   : text       : CH#66551 by @Test: Testing this script to see if it works
SideIndicator : =>

InputObject   : created_at : Tue Sep 24 00:27:01 +0000 2020
SideIndicator : =>

InputObject   : text       : CH#34330 by Test: Fixed every thing that is able to breathe
SideIndicator : =>

InputObject   : created_at : Tue Sep 22 02:31:26 +0000 2020

InputObject   : text       : CH#66551 by @User2: Fixing stuff

InputObject   : created_at : Tue Sep 22 00:27:01 +0000 2020

InputObject   : text       : CH#34330 by User1: Seeing if it works

InputObject   : created_at : Mon Sep 21 15:54:20 +0000 2020

InputObject   : text       : CH#34294 by User1: Trying to find a workaround

InputObject   : created_at : Mon Sep 21 15:29:13 +0000 2020

InputObject   : text       : CH#34291 by User3: Doing something else

InputObject   : created_at : Mon Sep 21 15:03:15 +0000 2020

InputObject   : text       : CH#34286 by User3: Running around

InputObject   : 

InputObject   : 

I want to remove everything in this .txt-file that comes after the last "SideIndicator : =>". Really appreciate the help. Note: The formatting of the next if a bit off here. "SideIndicator : =>" is found directly under "InputObject" (like you see it when you do a comparison in powershell between 2 files)

How to optimize the comparison of two lists to reduce the number of updates

I am working on an algorithm to compare to lists of ranges. The setup is simple, but the algorithm is getting more and more complex. I'm afraid I might be reinventing the wheel here so I thought I would ask the community if this sounds like any design patterns that have already been figured out.

I have two lists to compare. Each list contains a Boolean - Yes/No, and a range of numbers. Here's a visual:

List 1:

Key   Value     Range Start    Range End
-----------------------------------
A1    Y         1              5
A2    N         9              11
A3    Y         13             15

List 2:

Key   Value     Range Start    Range End
-----------------------------------
B1    Y         3              7
B2    N         9              14

The goal: to identify the optimal number of changes necessary to make list 1 cover the same ranges as list 2. In this case it would be: Update A1 to start at 3 and end at 7, Update A2 to end at 12, Update A3 to end at 14. I think this is similar to what a text-comparison algorithm might do.

I've created a rats nest of a flow chart to model this and I'm only half done. Looking forward to any suggestions that would point me in a better direction.

How can I share props (two-ways) between two components of the same type with Reactjs?

I'm building a music app using React, and I'm a newbie :)

My goal is to

  • load a JSON playlist (formatted as JSPF)
  • display a Playlist based on this JSON
  • fill a Player's queue with the playlist tracks.

So I'm working on several components : Track, Tracklist, Playlist, and Player.

  • Tracklists have Tracks.
  • Playlist and Player have a Tracklist (and other things) : the Player's queue is a Tracklist component.
  • Player is not a descendant of Playlist, it is aside. For instance, I want to be able to queue (or unqueue) some tracks of the Playlist into the Player.

What I want is to be able to share/sync the props of a (same) Track between the Playlist and the Player :

Let's say that I have a favorited prop for a Track.
I would toggle it by clicking a button nested in the Track component. I need to update the props of both tracks either if I click the button within the Playlist, or within the Player; and vice verca : all props should be "synced".

Can I do this with React and how ?

Thanks a lot for your advices !

Who coined the term DAMP

I've recently been introduced to the DAMP way of coding/testing, but after much research I've never been able to find the original definition or any literature about this, different from DRY which has a great definition on "The Pragmatic Programmer" book.

Does anyone knows where this comes from and what is it's original definition? All I've found is this question here

Decorator pattern for building a complete message

I am writing a tcp socket application in c#.in that,server has to send command to connected client and in turn client return some response. My command format is like

<header><header checksum> <operation type><parameter bytes> <checksum>

.for building command I am using decorator design pattern. Like base command bytes ,after that operation type decorator, then after header, footer decorator, decorator will be called in a fixed sequence, is there any way to fix decorator calling sequence or is there any better method to achieve it.

Maintaining versions of a model

I have a class library for carrying out a series of calculations based on a given standard. That standard has now been revised and i need to update the code to carry out calculations according to the new standard, whilst also maintaining the previous standard. Whilst I'm tempted to copy the whole lot and change the bits that have changed in the later standard it seems to go against all good principals of code design. Currently i'm thinking that i should duplicate all classes for the later standard and inherit anything that hasnt changed. But Is there a smarter way...?

namespace standard_2010
{
    class Calc1
    {
        double result {get;}
        void calculate()
    }
    class Calc2
    {
        double result {get;}
        void calculate()
    }
    
    class FinalResult
    {
        Calc1 m_c1;
        Calc1 m_c2;
            
        double result {get;}
            
        FinalResult()
        {
            m_c1 = new standard_2010.Calc1()
            m_c2 = new standard_2010.Calc2()
        }
            
        void calculate()
        {
            // Calculate the referenced calculations
            m_c1.calculate();
            m_c2.calculate();
                
            // save the result of this calculation which is a function of the referenced calcs
            this.result = f(m_c1.result, m_c2.result)
        }
    }
}

namespace standard_2020
{
    class Calc1 : standard_2010.Calc1
    {
        double result {get;}
        void calculate()
    }
    class Calc2 : standard_2010.Calc2
    {
        double result {get;}
        void calculate()
    }
    
    class FinalResult : standard_2010.FinalResult
    {
        FinalResult()
        {
            m_c1 = new standard_2020.Calc1()
            m_c2 = new standard_2020.Calc2()
        }
    }
}

What design pattern does fluuter belong to? Is it in the 23 design patterns?

https://en.wikipedia.org/wiki/Design_Patterns This book talks about 23 design patterns

MongoEngine and WTForm classes: how to avoid duplication business rules when having a MVC pattern

In my flask application, I have two classes. The first one defines the database model (mongoengine)

class Expenses(UserMixin, Document):
    exp_date = DateTimeField(required=True, max_length=10)
    exp_product = StringField(required=True, max_length=200)

And the second one defines a form data as my view (WTForms):

class ExpensesForm(FlaskForm):

    exp_date = WTDateField(
        'Date',
        format='%d/%m/%Y',
        validators=[InputRequired()]
    exp_product = WTStringField(
        'Product',
        validators=[InputRequired()])

I am trying to avoid having two different classes with the same logic. For example, I have to specify that the field exp_product is required in both classes. This can lead to some errors if, for example, I change the required property in one class but forget to change in the other one. Of course, this is a simplified example. It gets worse when I have many fields with many different rules defined.

I think the best solution for that case would be to unify both classes or to apply the Strategy Pattern but I have no idea how to do so.

dimanche 20 septembre 2020

React + Serverless (Domain Driven Design and Microservice Architecture)

Clarification before starting: I am not a professional programmer, I am still in the university, so maybe I am saying barbarities.

Hello,

I have a question about the typical structure in a serveless app implemented with React Native and Cloud Functions (and other cloud services). After a year of experience with React, I have noticed there is no "model" like in other languages like Java... instead there are components and screens, and the client "logic" can be written in both of them. Also, it is very common to make apps with Serverless, so imagine that the most part of your screens and components, connect to cloud functions, which write data on a same database or make queries to API endpoints, and other cloud services.

My question is if that is a pattern, as a lot of people do this that way I suppose there is a name to that.

I have a series of concepts in my head spinning:

 1- Domain Driven Design
 2- Microservice Architecture
 3- FaaS

But I am not really sure about them...

For example, in a microservice architecture, the logic is splitted in microservices which communicates to lightweight mechanisms... (here I imagine my components and screens, which have an unique purpose and connect to their respective cloud functions), but I have also seen that there has to be multiple databases... and in my app there is an unique NO-SQL database... Pd: my cloud functions are not only divided by their purpose but also by the collection of the database they handle.

And about domain driven design, in my app there is deep connection between the implementation and the concepts of the business model and core, as I have my code well structured (representative names, a good project hierarchy...) based on my business use cases... but I am not really sure if I am right.

I would really appreciate the help of someone who has years of experience in the business world to settle these concepts or tell me what kind of pattern is the one I have described

Thank you.

Avoid switch case in Event Dispatcher to call corresponding Event Handler

We have more than 15 event handlers corresponding to each event type. I want to avoid below switch case in Event Dispatcher to call corresponding event handler based on the event type.

Here is my Event Dispatcher class:

public class EventDispatcher : IEventDispatcher
    {
        private readonly IServiceProvider _serviceProvider;
        public EventDispatcher(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task<ResultDto> HandleEvent(IEvent @event, ILogger logger)
        {
            ResultDto resultDto = null;
            switch (@event.EventType)
            {
                case EventType.CARD_BLOCK:
                    resultDto = await HandleAsync<CardBlockedEvent>(@event as CardBlockedEvent, logger);
                    break;
                case EventType.CARD_UNBLOCK:
                    resultDto = await HandleAsync<CardUnBlockedEvent>(@event as CardUnBlockedEvent, logger);
                    break;
                case EventType.CARD_CANCEL:
                    resultDto = await HandleAsync<CardCancelledEvent>(@event as CardCancelledEvent, logger);
                    break;
                case EventType.CARD_GROUP_CHANGED:
                    resultDto = await HandleAsync<CardGroupChangedEvent>(@event as CardGroupChangedEvent, logger);
                    break;
                case EventType.CARD_EXPIRY:
                    resultDto = await HandleAsync<CardExpiredEvent>(@event as CardExpiredEvent, logger);
                    break;
                default:
                    logger.Warning($"Unknown event type");
                    resultDto = new ResultDto { ResultType = ResultType.Failure, Message = "Unknown event type" };
                    break;
            }
            return resultDto;
        }
        private async Task<ResultDto> HandleAsync<TEvent>(TEvent @event, ILogger logger) where TEvent : IEvent
        {
            var handler = _serviceProvider.GetService(typeof(IEventHandler<ResultDto, TEvent>)) as IEventHandler<ResultDto, TEvent>;
            return await handler.HandleAsync(@event, logger);
        }

    } 

Below is the Dependency Registrations:

 public class EventHandlerIoCRegistrations : IRegisterSevices
    {
        public void RegisterServicesWith(IServiceCollection serviceCollection)
        {
            RegisterDispatcher(serviceCollection);
            RegisterHandlers(serviceCollection);
        }
        private void RegisterDispatcher(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient<IEventDispatcher, EventDispatcher>();
        }

        private void RegisterHandlers(IServiceCollection serviceCollection)
        {
            Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(item => item.GetInterfaces()
            .Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == typeof(IEventHandler<,>)) && !item.IsAbstract && !item.IsInterface)
            .ToList()
            .ForEach(assignedTypes =>
            {
                var serviceType = assignedTypes.GetInterfaces().First(i => i.GetGenericTypeDefinition() == typeof(IEventHandler<,>));
                serviceCollection.AddScoped(serviceType, assignedTypes);

            });
        }
    }

Below is the Event handler interface:

public interface IEventHandler<TResult, TEvent>
        where TEvent : IEvent
        where TResult : class
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="event"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        Task<TResult> HandleAsync(TEvent @event, ILogger logger);
    }

Is there any better way to do and to avoid this switch case? Any thoughts?

Looking for the formal name of a request response pattern implemented in aspnet core or http modules in IIS

There is a recognizable pattern in many servers that implement a generic request/response processor. Among many examples, I can name aspnet core middleware or http modules in IIS.

With the request/response pattern that I am referring to, 3rd party developers can implement modules by implementing a well define interface (like middleware in aspnet core). The execution engine can be configured to hand a context (includes both request and response) to each of the modules in order until a response is ready to send back to the requestor.

The challenge that I have is that this specific pattern is not part of GOF patterns that everyone know about. I can tell it is a behavioral pattern.

Is there any formal name and definition for this pattern that is independent of any platform or programming language?

How to reduce duplicate code for calculations based on DTO and model classes

In one of our projects we have some sort of code duplication which we would like to get rid of: It is about code for the same calculations on both DTO and model classes.

E.g. we have the following 2 methods:

boolean isFreeShipping(CartDto cartDto) {
...
}
boolean isFreeShipping(CartModel cartModel) {
...
}

What is the best approach to solve this?

  • Have the calculation only for the model, and convert the DTO to the model if needed?
  • Or vice versa?
  • Introduce a specific value object which holds only the necessary fields and use this for the calculation - with mappers for both DTO and model?

Is there an alternative to using multiple inheritance in python in my case?

Let's say there are several classes

class Order:
  def create_basic_order(self):
    pass
    # something here

  def create_difficult_order(self):
    pass
    # something here  


class Point:
  def create_full_point(self):
    pass
    # something here

  def create_limited_point(self):
    pass
    # something here

And the client sends a request with a specific command in json format. For example {"command": "create_limited_point"}.

And the server should execute the appropriate command. In this case: Point().create_limited_point().

All commands are different. The most obvious way to do it without the 'if construct' is like this:

class App(Order, Point):
  pass
  # maybe something here

# Code to handle client request
command = 'create_limited_point'
a = App()
method_to_call = getattr(a, command)
method_to_call()

The class App collects all the methods that the client can use. Is this a good way to accomplish the task at hand?

Instantiating multiple complex entity objects the "right way"

I'd like to instantiate multiple (i.e. of the same type) complex (i.e. many optional parameters) objects in my code. But how can I go about it and keep honoring SOLID principles?

Here is my thought process so far:

It seems beneficial to me, to separate the creation logic into a separate class, as sometimes the creation process of those complex objects in itself has dependencies. With a separate class, I'm able to provide those dependencies without them leaking into the object class itself. Furthermore this creation class becomes basically a service class, that can be passed around with the DI-container and fully exchanged for another implementation of the creation process.

Just by name and purpose two patterns come to mind: Factory and Builder.

It seems to me that my problem isn't the kind of problem a Factory solves. As I'm not trying to create different objects of a similar type, but really only one type of object multiple times.

So here comes the Builder:

Before I start, I have to clarify what I'm talking about when I mention "Builder" as I came across basically two different kinds of builders. The one kind of Builder seems to be the one by the Gang of Four and I'm not really familiar with this one. But I read about another kind in "Mastering PHP Design Patterns" by Junade Ali that roughly corresponds to the Builder (in Java) by Joshua Bloch as described by himself here and talked about over here.

A very basic implementation would look like this:

class ObjectBuilder implements ObjectBuilderInterface
{
 public function setAttributeA( $value ) : self
 {
  $this->attributeA = $value;
  return $this;
 }

 public function setAttributeB( $value ) : self
 {
  $this->attributeB = $value;
  return $this;
 }

.
.
.

 public function build() : Object
 {
  return new Object ($this->attributeA, $this->attributeB,...);
 }
}

The big advantage to me is that a builder provides setters that can be called in no particular order an still output a valid object. Furthermore the builder itself can have dependencies without them leaking into the object.

BUT as far as I understand the inner workings of a builder, by using the setters on the builder object the builder itself has a state and couldn't be reused for another object without unsetting all attributes first. One could make an unset call at the end of build() but that feels somewhat wrong to me and in my above mentioned sources aswell as everywhere I looked for a real life implementation of such a builder (I live in Symfony-land and had a look into FormBuilder for example) was anything like an unset() used.

So that got me thinking: If I couldn't find that many implementations of that Builder for a common problem in my code, am I somehow really off? Is there maybe a whole other approach I missed so far?

How is it possible to instantiate multiple complex objects by a service that can easily be passed around?

print a pattern,sorted array

I need help with these problems #1 a function given a integer n will print the following pattern n = 2 222 212 222 n=3 3333 3223 32123 32223 3333

#2 a function that fuind the largest subarray in l , and return these the starting and ending indices with solution in O(n) example l =[1,2,0,1,2,3,0,1,2,3,4,5,-11] returns (6,11)

#3 a function that returns a pair of integers in a list that has a particular sum s. and the solution in O(n) example: l= [5,6,7,1,2] fun(8) returns (6,2)

Avoid switch case to call event handler

I want to avoid below switch case to call corresponding event handler based on the event type. We may have more than 20 event types in future.

Here is my code:

public class EventHandlerService : IEventHandlerService
    {
        private readonly IEventHandler<ResultDto, CardBlockedEvent> _cardBlockedEventHandler;
        private readonly IEventHandler<ResultDto, CardUnBlockedEvent> _cardUnblockedEventHandler;
        private readonly IEventHandler<ResultDto, CardCancelledEvent> _cardCancelledEventHandler;
        private readonly IEventHandler<ResultDto, CardGroupChangedEvent> _cardGroupChangedEventHandler;
        private readonly IEventHandler<ResultDto, CardExpiredEvent> _cardExpiredEventHandler;
        public EventHandlerService(
            IEventHandler<ResultDto, CardBlockedEvent> cardBlockedEventHandler,
            IEventHandler<ResultDto, CardUnBlockedEvent> cardUnblockedEventHandler,
            IEventHandler<ResultDto, CardCancelledEvent> cardCancelledEventHandler,
            IEventHandler<ResultDto, CardGroupChangedEvent> cardGroupChangedEventHandler,
            IEventHandler<ResultDto, CardExpiredEvent> cardExpiredEventHandler,
        
            )
        {
            _cardBlockedEventHandler = cardBlockedEventHandler;
            _cardUnblockedEventHandler = cardUnblockedEventHandler;
            _cardCancelledEventHandler = cardCancelledEventHandler;
            _cardGroupChangedEventHandler = cardGroupChangedEventHandler;
            _cardExpiredEventHandler = cardExpiredEventHandler;

            
        }

        public async Task<ResultDto> HandleEvent(IEvent @event, ILogger logger)
        {
            ResultDto resultDto = null;
            switch (@event.EventType)
            {
                case EventType.CARD_BLOCK:
                    resultDto = await _cardBlockedEventHandler.HandleAsync(@event as CardBlockedEvent, logger);
                    break;
                case EventType.CARD_UNBLOCK:
                    resultDto = await _cardUnblockedEventHandler.HandleAsync(@event as CardUnBlockedEvent, logger);
                    break;
                case EventType.CARD_CANCEL:
                    resultDto = await _cardCancelledEventHandler.HandleAsync(@event as CardCancelledEvent, logger);
                    break;
                case EventType.CARD_GROUP_CHANGED:
                    resultDto = await _cardGroupChangedEventHandler.HandleAsync(@event as CardGroupChangedEvent, logger);
                    break;
                case EventType.CARD_EXPIRY:
                    resultDto = await _cardExpiredEventHandler.HandleAsync(@event as CardExpiredEvent, logger);
                    break;
            
                default:
                    logger.Warning($"Unknown event type");
                    resultDto = new ResultDto { ResultType = ResultType.Failure, Message = "Unknown event type" };
                    break;
            }
            return resultDto;
        }

    }

Below is IEventHandler interface:

public interface IEventHandler<TResult, TEvent>
        where TEvent : IEvent
        where TResult : class
    {
        Task<TResult> HandleAsync(TEvent @event, ILogger logger);
    }

Is there a better way to create the right event object without using a big switch statement like above?

how to combine singleton and factory design pattern with python?

Suppose there are several presses, each one published many books I am going to handle many records like 'press name, book name'

I want create the class 'Press' by a unique name(string), but only different string can produce different instances of class 'Press'.

so, I need a class work like 'factory', create a new instance when a record contains a new press, but it also work as singleton if there are already exists which has the same names.

How to test code that has a lot of RPC calls/database operations?

I'm working on a backend service that interacts heavily with other services. It has a frightening lack of unit tests, so I really want to write some tests to ease future developement.

The problem is, there are a lot of RPC calls and database operations. For example, to complete operation A, you first make an RPC call to service B, then get data from database C, finally you write data to database D and return the response. As a back-end service, it is a combination of many such operations. It appears unclear to me how to correcly write tests for these opeartions.

My first guess is to resturcture the code or use mock testing or both. From my point of view, restructuring the whole codebase would be a huge task that I dare not do. Mock testing would be a little troublesome since there are so many services/databases involved and the involved data is complicated. I'm not quite sure how to do this the right way.

I would appreciate if someone could at least give me directions on this matter. How should I write unit tests for the code? Or do there exist better practices for this scenario?

samedi 19 septembre 2020

Microservice Clients Circular Dependency

In a Microservice architecture, using client packages to communicate between services, we ran into an issue where two client packages depend on each other, creating a circular dependency.

We are trying to figure out the best solution for this and I'm wondering if anyone would be able to help or point us in the right direction.

Here is the scenario:

  • Two services, Car and Insurance
  • Two client packages, CarClient and InsuranceClient.

Whenever any service needs to communicate with the Car service, it should use the CarClient package to do so. And whenever any service needs to communicate with the Insurance service, it should use the InsuranceClient package.

The CarClient package has a data transfer object (DTO) Car where one of its properties is insurance. The type for this property is a DTO available in the InsuranceClient package, CarInsurance.

The issue is when the CarInsurance DTO needs to access an enum available in the CarClient package, CarTypeEnum. Now we have the two packages depending on each other.

Microservice Clients Circular Dependency

Possible solutions I can think of:

  1. This is due to a bad design. Redesign the services and packages to prevent this circular dependency.
  2. Move the enums into separate packages, therefore, both clients can depend on these packages but the clients wont't depend on each other.

Any help is appreciated.

How to force changes in method if class gets extendend?

In my application I have the option to export/import certain classes. It requires a little more than simple json serialize/deserializing.

Lets say I have a Company class like this

public class Company
   string Name
   List<Employee> Employees
   CEO Ceo

I have an Export() method and I wanted to add a unit test. So I created a test where I arrange a Company, export it and assert some things. Details aren't important.

Now, if I come back in 2 weeks and add a new class Department to my application and a List of Departments to my Company, I need to extend the Export() method as well.

There are 2 problems with this. 1) I need to remember to extend my Export() method. 2) My test won't actually break. I cannot assert for the existence of a property which I don't even know is gonna exist in 2 weeks.

This test is worse than no test. It gives a false sense of security.

I actually wrote a new version of the export method, which should not require constant extension. The key word here is "should". I'm not sure and the test is not helping.

Basically I don't test that my Export() method "works", I test that my Export() method exports the specific Company that I set up in the unit test.

I have to either get around the need to adjust the unit test, every time I change the Company class.

Or, at a minimum, I need a really good reminder to do it. Something like a breaking unit test...

How to implement a channel and multiple readers that read the same data at the same time?

I need several functions to have the same channel as a parameter and take the same data, simultaneously. Each of these functions has an independent task from each other, but they start from the same value.

For example, given a slice of integers, one function calculates the sum of its values ​​and another calculates the average, at the same time. They would be goroutines.

One solution would be to create multiple channels from one value, but I want to avoid that. I might have to add or remove functions and for this, I would have to add or remove channels.

I think I understand that the Fan Out pattern could be an option, but I can't quite understand its implementation.

Design pattern for subclassing widgets

I'm currently working on a guitar app. This app has several exercices type (find and play the correct displayed note, read music notations...). Each exercice type must return 2 widgets with their states :

  • a page to play the exercice

  • a page to customize the exercice (settings page) Each exercice type has each own unique page. For example, exercice A may need 2 TextField and exercice B may need 1 dropdown button. So far, I implemented it successfully with this pattern :

    I wrote an Exercice class (to store all exercices created by the user in a database) :

class Exercice {
    String name;
    int exerciceType;
    String exerciceSettings; // <-- stored in json
}

And I created this abstract class :

abstract class ExerciceType {
    int get id; // each exercice type has a unique type String get displayedName; Icon get icon;
    Widget settingWidgets(); // return the settings page String toJson();         // serialize settings from the settings page in a json string Widget playPage();       // return the page where we can play the exercice
}

And then, each exercices type can be implemented like this :

class FindNote extends ExerciceType {
    String displayedName = "find_note";
    int id = 0;
    Icon icon = Icon(Icons.audiotrack);
    // this is what concerned me the most, I have to pass the state here... :(
    FindNoteSettingsPage widgetSettings = FindNoteSettingsPage(state: _FindNoteSettingsPageState());
    FindNotePlayPage playPages = FindNotePlayPage(state: _FindNotePlayPageState());
    StatefulWidget settingWidgets() { return widgetSettings; }
    StatefulWidget playPage() { return playPages; }
    String toJson() {
        var settings = {};
        // :( bad things here I suppose... 
        settings["minFret"] = widgetSettings.state._values.start.toInt(); 
        settings["maxFret"] = widgetSettings.state._values.end.toInt(); 
        settings["strings"] = 
        widgetSettings.state.stringsList.stringActive;
        return json.encode(settings);
    }
}

class FindNoteSettingsPage extends StatefulWidget {
          final _FindNoteSettingsPageState state;
        
          FindNoteSettingsPage({Key key, @required this.state}) : super(key: key);
        
          @override
          _FindNoteSettingsPageState createState() {
            return state;
          }
}
        
class _FindNoteSettingsPageState extends State<FindNoteSettingsPage> {
           // some attributes here
        
          @override
          Widget build(BuildContext context) {
            return new Column(//my settings page here with TextField and so on.)
          }
}
        
// same pattern is used to implement the play page class

So far the code is working but I'm not satisfied with this design.

For example, if I want to show to the user his exercices list, each exercice must be instantiated completly (so loading each settings/play page, custom behavior...)

I will greatly appreciate any advices that can improve this design pattern. I suppose I'm not the first to write this kind of logic in Flutter :) Thanks in advance ! I can post a link to the Github repo for anyone requesting it.

Design pattern suggestions for reading and parsing related methods for emails using java Mail API?

I am currently working with selenium and I am using JavaMail API (v. 1.6.2) to retreive mails and parse them for the following uses, e.g:

  1. Extract the account confimation link.
  2. Extract the account confirmation code.
  3. Extract the link for account deletion.
  4. etc...

As you can already infer, I am doing it to automatize certain online account procedures such as account creation and deletion and so on.

First I thought of creating keywords for each and every methods and use them but since there are going to be email session objects, this wouldn't be a nice way to create a new email session object on every single method call.

So if anyone has ever done somethign similar to this, do you have any suggestions for using specific design patterns?

detect repeating patterns across two columns in a dataframe that has an ID variable

I have a data set that has 3 columns , (ID , D , AE). i want to retrieve records where any two values in column D are co-occurring with any value in Column AE 3 times or more:

enter image description here

sample=data.frame(
  ID=c(1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5),
 
D=c('a','b','c','d','e','f','g','y','z','a','b','g','y','d','e','f','g','b','a','y'),AE=c('m','h','j','k','m','h','j','k','m','j','m','h','l','j','k','m','h','m','o','s')
      )

and I want the output to be something like :

output=data.frame(ID=c(1,1),
D=c('a','b'),
AE='m')

please note that i want the output to have records where any two values from column D within a certain ID occurred with a value from column AE 3 times or more.

Interaction of two entities in hierarchy

I am having two classes - Project and Order.

Project is a work project.
Order is an order from a customer of the project.

Orders are stored as files inside each projects' directory structure in a subdirectory that indicates the status of contained order e.g. /project/orders/status/order.json.

I have two related design pattern dilemas.

  1. When retrieving all orders for a given project. Should I project.getAllOrders() or Order.getAll(project);
  2. Same goes for similar operations like changing the status. project.changeOrderStatus(order, status) or order.changeStatus(status)

In "project centric" cases, it makes sense to me, since project probably should be aware of its orders and since the directry structure belongs to the project, it should be the on who manipulates status.

In "order centric" cases the retrieval kind of resembles pattern of REST API, which also makes more sense to me, but changing the status of the order requires the order object to know the path to the project directory, which requires either Project instance in each order, which seems quite wasteful or additional parameter to order.changeStatus which seems to me more like a hack.

I am aware, that the second dilema could be solved by for example using a database, but I would like to keep the directory structure.

(PHP) how to check if input string with specific pattern?

i have table pattern like this : ID Name Pattern 1 Patern A "### ## ##" 2 Pattern B "######" 3 Pattern C "#### ## ####"

how I can match input string with that pattern ? , say if pattern base on that space, not by number or char . thanks

vendredi 18 septembre 2020

AAPT: error: attribute android:style not found for RatingBar

I am trying to create a small size RatingBar and I tried to run below code on my device but I am getting this issue "AAPT: error: attribute android:style not found." after clicking on Run App button
Please help me to find the solution..

activity_main.xml

<RatingBar
  android:layout_width="wrap_content"
  android:rating="4"
  android:id="@+id/ratingBar"
  android:paddingTop="10px"
  android:paddingLeft="20px"
  android:style="@style/RatingBar"
  android:stepSize="1"
  android:isIndicator="true"
  android:layout_height="wrap_content"/>

styles.xml
<style name="RatingBar" parent="Widget.AppCompat.RatingBar.Small">
  <item name="colorControlNormal">@color/ratingColor</item>
</style>

Helper in CPP or H

Suppose I have a helper:

namespace test
{
    void doSomething() 
    {
        // Do stuff
    }
}

Should I put that code in a .cpp file or .h file, so I can then #Include it?

Discovered a pattern using higher order functions. What is this pattern called?

I am working on a python project in which I frequently need to generate a figure containing two axes using matplotlib. The code to generate the figure is identical each time. However I am calling my own functions which accept an axes object as one of their arguments and modify it. I throughout my project, I call different combinations of these functions to populate my figure axes.

It then occured to me that I actually pass these functions themselves and a tuple of their arguments into a higher order function. The higher order function would have the responsibility of calling the functions to populate the two axes objects to generate my figure. I made a toy example to illustrate this below.

import matplotlib.pyplot as plt
import numpy as np

def A(ax, x, a, b, c):

    y = a*x**2+b*x+c
    ax.plot(x, y)

    return ax

def B(ax, x, a):

    y = a*x**2
    ax.scatter(x, y)

    return ax

def C(ax, n):

    ax.axhline(n)

    return x

def plot(ax1, f1, args1, ax2, f2, args2):

    ax1 = f1(ax1, *args1)
    ax2 = f2(ax2, *args2)

    return ax1, ax2
if __name__=="__main__":
    x = np.linspace(0,10,10)

    fig, (ax1, ax2) = plt.subplots(2, 1)
    ax1, ax2 = plot(ax1, A, (x, 1, 2, 3), ax2, C, (5,))

    plt.show()

    x = np.linspace(0, 10, 10)

    fig, (ax1, ax2) = plt.subplots(2, 1)
    ax1, ax2 = plot(ax1, B, (x, 1), ax2, C, (5,))

    plt.show()

The function plot here is an example of such a higher order function. It can take in any combination of functions f1 and f2. It then calls these functions on the given axes objects to generate a figure. The function plot does not care how many arguments f1 and f2 has, which makes it generic enough to reduce the amount of duplicate code I have.

What pattern is this? Is this an example of a decorator? If not does python have any built-in syntactic sugar to support this on a more fundamental level?

Software Engineering: Organize different kind of users

Alright people,

In the last couple of days I've been thinking how to implement this properly, and I'd like to know what your approach would be to implement the following scenario:

  • I'm doing an eCommerce platform, and we have many kinds of "entities". Entities are not necessarily users that have credentials and can login in our platform, and everything should be fairly decoupled from everything else.

  • Real life scenario: We have customers, employees and suppliers, all of these can or not be a User, as in, they may or may not have login credentials. I can attach a contact (address info) to any of these models, or an invoice... The idea is that we may have customers that don't actually have credentials that we issue invoices to, or create an order to a user that doesn't actually login... Same for invoicing, I want to be able to invoice a customer, as well as a supplier.

The problem that I'm having is that these 3 types of user are more or less the same, they can have orders/invoices/contacts/whatever attached to them, but they aren't necessarily a user. In fact, credentials must be something that we should be able to attach to any of those models, if we want, so a supplier can have a login to access whatever they need.

How would you design this?