dimanche 31 octobre 2021

How to share frame rendering between two proceses

Im designing a game menu for an arcade machine as a personal project and to get more familiar with IPC. The project runs on a raspberry Pi rendering to a LED matrix using Hzeller's led matrix library. The menu would present the user a list of games rendered on the matrix. When the user selects a game, the main process will fork and spawn the game in a new process. The game will start and render to the matrix. At any point the user can exit the game which will return the user back to the game menu. Presumably there will be communication between processes so each aren't simultaneously rendering to the matrix at the same time.

Now where I am uncertain is how to actually share resources that are needed to render to the matrix. The library has a background updater thread that cannot be running in both process. Im not certain how this is typically done but here are the solutions I came up with:

  1. Resources needed for rendering are cleaned up and reinitialized before switching contexts between parent and child processes

  2. The Child will serialize the underlying framebuffer data and send it to the main process for rendering.

The first solution seems a little hacky and requires me to make small changes to the library. I also want to create an interface to decouple the menu/game to the display its actually rendered on. This way I can make a separate implementation of the interface to render to a GUI on a computer screen. Choosing this option would be synonymous of creating an entirely new window for the child process (not sharing the same window).

The second solution would require copying the underlying framebuffer of the child process to shared memory. It would then would be picked up by the parent thread copied again out of shared memory and rendered. I worry about latency and how to manage frame rate in this solution. In addition, I am utilizing the library's vsync capability and am unsure how the child would be utilize this if rendering is done in the parent process

My questions are:

  • Are there any other solutions? If not which of the two are better design wise.
  • If I go option two, how would the child take advantage of the vsync functionality and how would I manage framerate in this scenario?

Pagination Duplicating Values in RecyclerView in MVVM

I am new in Kotlin MVVM also, I tried to achieved Pagination with legacy approach and stucked in a issue with my RecyclerView, whenever I scroll it the data duplicated, I tried DiffUtils but no help.

I Logged the data in VIEWMODEL class the data is not repeating but, when I logged in Activity where I am observing it is showing duplicate values

SEARCHRESULTACTIVITY.KT

class SearchResultActivity : AppCompatActivity() {
private lateinit var layoutManager: LinearLayoutManager
private lateinit var recyclerView: RecyclerView
private lateinit var pullAdapter: CustomAdapter
private var pageNumber = 1
private var totalItemsCount = 0
private var firstVisibleItemsCount = 0
private var visibleItemsCount = 0
private var previousTotal = 0
private var loading = true
private var fillPullList: ArrayList<RepoPull> = ArrayList()
private var userName: String = ""
private var repoName: String = ""
private var isEnd = false


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    initialize()

    getDataPull(userName, repoName)

    loadNextData()

}

private fun initialize() {
    setContentView(R.layout.activity_search_result)
    recyclerView = findViewById(R.id.repoRecView)
    layoutManager = LinearLayoutManager(this)

    getSearchQuery()

}

private fun getSearchQuery() {
    userName = intent.getStringExtra("owner").toString()
    repoName = intent.getStringExtra("repo").toString()
    populatePullRv()

}

private fun populatePullRv() {
    recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
    recyclerView.layoutManager = layoutManager
    pullAdapter = CustomAdapter(this, fillPullList)
    recyclerView.adapter = pullAdapter
    progressBar.visibility = View.VISIBLE
}

private fun loadNextData() {
    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)

            val mLayoutManger = recyclerView.layoutManager as LinearLayoutManager
            visibleItemsCount = mLayoutManger.childCount
            totalItemsCount = mLayoutManger.itemCount
            firstVisibleItemsCount = mLayoutManger.findFirstVisibleItemPosition()

            if (loading) {
                if (totalItemsCount > previousTotal) {
                    previousTotal = totalItemsCount
                    pageNumber++
                    loading = false
                    progressBar.visibility = View.GONE
                }
            }
            if (!loading && (firstVisibleItemsCount + visibleItemsCount) >= totalItemsCount) {
                getDataPull(userName, repoName)
                loading = true
                Log.d("PAGE", pageNumber.toString())
            }


        }

    })
}

private fun getDataPull(username: String?, reponame: String?) {
    val myViewModel = ViewModelProviders.of(this).get(PullVM::class.java)

    myViewModel.endofList.observe(this, {
        if (it == true) {
            isEnd = true
            progressBar.visibility = View.GONE
            Toast.makeText(this@SearchResultActivity, "All PR Fetched", Toast.LENGTH_SHORT)
                .show()

        }

    })

    myViewModel.status.observe(this, {
        if (it == false) {
            showError(getString(R.string.no_net))

        }
    })

    myViewModel.getPullDataFromVM().observe(this, {

        if (it != null) {
           listRepos(it)  **//DUPLICATE VALUE COMING**
        } else {

            showError(getString(R.string.nothing_found))
        }
    })



    myViewModel.getPullList(username.toString(), reponame.toString(), pageNumber)

}

private fun showError(s: String) {
    progressBar.visibility = View.GONE
    val theView =
        this@SearchResultActivity.findViewById<View>(android.R.id.content)
    Snackbar.make(
        theView,
        s,
        Snackbar.LENGTH_LONG
    ).show()
}


@SuppressLint("NotifyDataSetChanged")
fun listRepos(repos: List<RepoPull>) {
    if (!isEnd) {
        progressBar.visibility = View.GONE
        fillPullList.addAll(repos)
        pullAdapter.notifyDataSetChanged()
    }
}}

PULLVM(View Model).kt

 class PullVM : ViewModel() {
var pullList: MutableLiveData<List<RepoPull>>
var status = MutableLiveData<Boolean?>()
var endofList = MutableLiveData<Boolean?>()

init {

    pullList = MutableLiveData()
}

fun getPullDataFromVM(): MutableLiveData<List<RepoPull>> {

    return pullList
}

fun getPullList(ownerName: String, repoName: String, pgNo: Int) {

    val retriever = GitHubRetriever


    val callback = object : Callback<List<RepoPull>> {
        override fun onFailure(call: Call<List<RepoPull>>, t: Throwable) {
            status.value = false
        }

        override fun onResponse(
            call: Call<List<RepoPull>>,
            response: Response<List<RepoPull>>
        ) {
            if (response.body()?.size == 0) {
                endofList.value = true
            }
            if (response.code() == 404) {
                pullList.postValue(null)

            } else {
                status.value = true
                val repos = response.body()
                if (repos != null) {
                    pullList.postValue(repos) 
                }
            }
        }

    }

    retriever.userRepos(
        callback,
        ownerName,
        repoName,
        pgNo
    )
}

How to create a calendar database that shows users availability

Context

I want to build an app where users who belong to a company and a team can add their availability for a given day (available/unavailable) using a calendar. I want to set up a database.

  • The company should be able to access the calendar, teams and users availability and to give a manager status to users.
  • Managers can access the calendar, create teams, add users in their team and set their own availability for a given date
  • Users can set their own availability for a given date

Is this the right way I should imagine my database ? I would like to have more opinions.

Company
  company_id
  calendar_id

User
  user_id
  user_name
  user_status
  company_id
  calendar_id

UserTeam
  user_team_id
  user_id
  team_id

Team
  team_id

Calendar
  calendar_id

Event
  event_id
  event_date
  event_availability
  calendar_id

What I can do better in this class? Python class refactoring

I have this code with some classes and the inheritance tree. What I can do better in this code? If we look in the direction of designing classes.

CAR_TYPES = {
    'Car': 'Car',
    'Truck': 'Truck',
    'SpecMachine': 'SpecMachine'
}


class CarBase:
    def __init__(self, brand, photo_file_name, carrying):
        self.car_type = None
        self.photo_file_name = photo_file_name
        self.brand = brand
        self.carrying = carrying

    def get_photo_file_ext(self):
        return self.photo_file_name.split(".")[-1]

    def __str__(self):
        return f"Car type: {self.car_type} | Brand: {self.brand} | Carrying: {self.carrying}"


class Truck(CarBase):
    def __init__(self, photo_file_name, brand, carrying, body_lwh):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['Truck']
        self.body_lwh = body_lwh
        self.body_length = 0
        self.body_width = 0
        self.body_height = 0
        self.body_volume = 0

        if body_lwh:
            self._set_lwh()
            self._set_body_volume()

    def __str__(self):
        return f"{super().__str__()} | Length: {self.body_length} | Width: {self.body_width}, " \
           f"| Height {self.body_height}, | Volume: {self.body_volume}"

    def _set_lwh(self):
        try:
            self.body_length, self.body_width, self.body_height = map(float, self.body_lwh.split('x'))
        except ValueError:
            self.body_length, self.body_width, self.body_height = 0.0, 0.0, 0.0
            print("Value Error. Check your values and try again!")

    def _get_body_volume(self):
        return self.body_length * self.body_width * self.body_height

    def _set_body_volume(self):
        self.body_volume = self._get_body_volume()


class Car(CarBase):
    def __init__(self, photo_file_name, brand, carrying, passenger_seats_count):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['Car']
        self.passenger_seats_count = passenger_seats_count

    def __str__(self):
        return f"{super().__str__()} | Passenger seats count: {self.passenger_seats_count}"


class SpecMachine(CarBase):
    def __init__(self, photo_file_name, brand, carrying, extra):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['SpecMachine']
        self.extra = extra

    def __str__(self):
        return f"{super().__str__()} | Extra: {self.extra}"

I want to make this code more readable and more scalable, but I don't have any experience in this field and I want to learn it.

For example, what I can do with car_type variable? I tried to put car_type to CarBase class, but I don't know, how I can assign it later and to make it right from the design side

Design pattern for avoiding triplicate code for dart csv log writer (class properties, csv header, row values)

Firstly I'm fairly new to dart, so I'm not sure how I would even search properly for this, but what I'm trying to do is use the same name for the csv row header, the class properties and then using the properties for the row values.

Is there a sane way to use a single "name", variable or something else to reuse for multiple purposes? The main concern I have with what I'm doing here is that it's overly verbose and means it could be easy to miss a property while developing. It can be assumed that each row will contain all values (null or otherwise) and these will match in order with the respective "header" row and each of these should have a corresponding property in the class.

My current solution is to just define the property, and a method to write a header row and a method to write all the relevant properties to a new row, but it feels like unnecessary code duplication.

My work in progress code is as follows:

class ExperimentLog {
  // top level (experiment)
  String experiment;
  String subject;
  String? condition;
  DateTime? expStartTime;
  DateTime? expEndTime;
  int? expElapsedTimeMs;

  // trial level
  int trial = 0;
  String? cue;

  DateTime? trialStartTime;
  DateTime? trialEndTime;
  int? trialElapsedTimeMs;

  double? xStart;
  double? yStart;
  double? xEnd;
  double? yEnd;
  double? avgVel;

  bool? correct;

  // movement level
  double? xPos;
  double? yPos;
  double? angle;
  double? stepVel;

  // internal
  List<List<dynamic>> _logRows = [];
  Stopwatch expStopWatch = Stopwatch();
  Stopwatch trialStopWatch = Stopwatch();

  ExperimentLog(this.experiment, this.subject,
      {this.condition, DateTime? expStartTime}) {
    this.expStartTime = expStartTime ?? DateTime.now();
    _addHeaderRow();
  }

  void _addHeaderRow() {
    List<dynamic> _logRow = [];
    _logRow.add("experiment");
    _logRow.add("subject");
    _logRow.add("condition");
    _logRow.add("expStartTime");
    _logRow.add("expEndTime");
    _logRow.add("expElapsedTimeMs");

    _logRow.add("trial");
    _logRow.add("trialStartTime");
    _logRow.add("trialEndTime");
    _logRow.add("trialElapsedTimeMs");
    _logRow.add("cue");
    _logRow.add("xStart");
    _logRow.add("yStart");
    _logRow.add("xEnd");
    _logRow.add("yEnd");
    _logRow.add("avgVel");
    _logRow.add("correct");

    _logRow.add("xPos");
    _logRow.add("yPos");
    _logRow.add("angle");
    _logRow.add("stepVel");

    _logRows.add(_logRow);
  }

  void _addRow() {
    List<dynamic> _logRow = [];
    _logRow.add(experiment);
    _logRow.add(subject);
    _logRow.add(condition);
    _logRow.add(expStartTime);
    _logRow.add(expEndTime);
    _logRow.add(expElapsedTimeMs);

    _logRow.add(trial);
    _logRow.add(trialStartTime);
    _logRow.add(trialEndTime);
    _logRow.add(trialElapsedTimeMs);
    _logRow.add(cue);
    _logRow.add(xStart);
    _logRow.add(yStart);
    _logRow.add(xEnd);
    _logRow.add(yEnd);
    _logRow.add(avgVel);
    _logRow.add(correct);

    _logRow.add(xPos);
    _logRow.add(yPos);
    _logRow.add(angle);
    _logRow.add(stepVel);

    _logRows.add(_logRow);
  }

  void startTrial({int? trial}) {
    trialStartTime = DateTime.now();
    trialStopWatch.stop();
    trialStopWatch.reset();
    trialStopWatch.start();

    this.trial = trial ?? this.trial + 1;
  }
}

Pattern forming java..Not able to come up with a method

THE QUESTION IS:

Analyse the given pattern and print for the given interger N.

Input Format

A single digit N will be given.

Constraints

1<=N<=100

Output Format

It should print the pattern

Note: Even digit is a special condition, identify it accordingly to proceed the algo.

Sample Input 0

9

Sample Output 0

 * * 1 * *
 * *222* *
 * 3 3 3 *
 *4* 4 *4*
 555555555
 *4* 4 *4*
 * 3 3 3 *
 * *222* *
 * * 1 * *

Explanation 0

When the input is given as 9, It prints the following pattern. Analyse the pattern and come up with an algorithm to satisfy any given number.

The numbers have been printed straight and diagonally ..but not able think of a method to implement this...

the problem of sending data that maps directly to your database tables

I was searching for the uses of DTO. Microsoft Docs mentioned one of the uses as the following:

The client receives data that maps directly to your database tables. However, that's not always a good idea. Sometimes you want to change the shape of the data that you send to client.

I would like to know what would be the problem if we send data that maps directly to database tables? will there be any security issues?

samedi 30 octobre 2021

Design pattern to model transactions

There is a set of tasks I need to execute as an atomic transaction. i.e while executing the tasks, if any task fails, I need to revert the changes done during the previous tasks and exit without executing the subsequent tasks. This is similar to how DB transactions are handled. Is there a well known design pattern to address this case ?

P.S. I tried to search on internet but got a bunch of research papers, since the question must be common to most of the systems, I m just checking whether there is a known recommended method to solve this problem.

Can't figure out which code design pattern to use

I'm building an .NET CORE 3.1 API and there is controller method which receives XElement from body. XElement is SOAP Envelope but envelopes body content can be A B C or D DTOs, totally from each other different by their content.

Envelopes DTO body snippet DTO looks like this:

    /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Pasted XML", "0")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody
{
    private object bodyContentField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(nameof(A), typeof(A), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(B), typeof(B), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(C), typeof(C), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(D), typeof(D), Namespace = "namespace")]
    public object BodyContent
    {
        get
        {
            return this.bodyContentField;
        }
        set
        {
            this.bodyContentField = value;
        }
    }
}

When the controller method is called I receive Envelope I can deserialize it and see the content of for example A, B,C or D, depending of Envelope body content.

Further I need to recognize which one is which and call proper logic class depending on received message A, B, C or D to do other operations for particular message. How can I do this recognition and calling appropriate A, B, C or D logic in a right way? Could it be Factory design pattern?

Somehow don't feel that this is the best way:

        [HttpPost]
    public async Task ProcessEnvelope([FromBody] XElement envelopeMessage)
    {
        var xmlSerializer = new XmlSerializer(typeof(Envelope));
        using var stringReader = new StringReader(envelopeMessage.ToString());
        Envelope envelope = (Envelope)xmlSerializer.Deserialize(stringReader);

        if (envelope.Body.BodyContent is A contentA)
        {
            _logicA.Map(contentA);
        }

        if (envelope.Body.BodyContent is B contentB)
        {
            _logicB.Map(contentB);
        }
    }

Values problem on Axis Y on Ripley's K Function

I'm new on this site, so I hope I make the question in a good way haha. The problem is the following. I'm trying to apply Ripley's K Function to a point pattern. The main problem is that in axis Y, values are too high. Points are cultural centers (where people do artistic activities). In my data set, there are 306 cultural centers in total. But in Ripley's plot, it appears 2.000.000 points grouped in 200 mts. Sthg imposible. Does anyones know why occurs this error?

Search data set

espacios <- read_sf("https://ift.tt/3CqHs2W) %>% st_transform(crs = 5347)

Build neighborhood

palermo_espacios <- espacios %>% filter(BARRIO == "PALERMO") %>% select(FUNCION_PRINCIPAL, BARRIO, LONGITUD,LATITUD, geometry)

Point pattern

act_ppp_espacios <- as.ppp(st_geometry(palermo_espacios[!st_is_empty(palermo_espacios), ]))

Ripley's K Function

K <- Kest(act_ppp_espacios, correction = "none")

plot(K)

In axis Y we should get values from 0 to 306, which is the total values of my data set. Instead there are values from 0 to 4.000.000

Plz help! =)

Fighting back sequential coupling with correct design pattern

everyone reading this. First and most important, thank you for spending time on this.

So now let me go straight to the question.

Recently I received a homework where I have to deal with sequential coupling (masking it deeper in the code so outer classes doesn't see it). I'll put below an example of this and explanation.

    class Start{
    static void main(String[] args) {
        //First way
        Dog dogA = new Dog().setDogAType("prefix")
        //Second way
        Dog dogB = new Dog().setDogBType("prefix")
        //Custom
        Dog dogC = new Dog().firstMehtod("prefix")
             .secondMethod_a()
        dog.betweenSecondAndThird()
        dog = dog.theLastMethod()
        dog.optionalLastLast()
    }
}

class Dog {

    String id, prefix, subfix, name

    Dog() {
        //getting tokens for operations in the methods
    }
    
    Dog firstMehtod(String prefix) {
        println("firstMehtod")
        return this
    }

    Dog secondMethod_a() {
        println("secondMethod_a")
        return this
    }

    Dog secondMethod_b() {
        println("secondMethod_b")
        return this
    }

    Dog thirdMethod_a() {
        println("thirdMethod_a")
        return this
    }

    Dog thirdMethod_b() {
        println("thirdMethod_b")
        return this
    }

    Dog theLastMethod() {
        println("alwaysLast")
        return this
    }

    static void betweenSecondAndThird() {
        println("betweenSecondAndThird")
    }

    void optionalLastLast() {
        println("optionalLastLast")
    }   


    Dog setDogAType(String prefix) {
        Dog dog = new Dog().firstMehtod(prefix)
            .secondMethod_a()
            .thirdMethod_b()
            .theLastMethod()
    }

    Dog setDogBType(String prefix) {
        Dog dog = new Dog().firstMehtod(prefix)
            .secondMethod_b()
        dog.betweenSecondAndThird()
        return dog.thirdMethod_b()
            .theLastMethod()
    }
}

As you can see from the name of the method there is first method, two second methods and so on, we also have two methods that call some of the methods in their order and we can also have in outer class using directly the first, second and so on methods. Important note is that all methods are not building the Dog, but more like helper method for calling some stuff that build dogs in the database.

The idea and the thing that should be achieved is to:

  • Get hide the sequantial coupling as much as possible To have two-three quick ways
  • To achive the same goals as with setDogBType() and setDogAType() Be
  • able to make a completly custom one like the ones in the Start class.

My current idea is to use the Strategy pattern by doing the following:

  • Make abstract class BaseStrategy that will contain these first, second methods, with abstract method for building a dog.
  • Make three strategies - one for DogAType, one for DogBType with the specific methods called and one DogCustomType that will call the methods based on the arguments passed.
  • Dog class will be just like a DTO, that will carry our results

How do you see my current idea and do you see something I'm missing or having a better idea to do it?

PS: Wishing you an awesome weekend!

OO-Design: How to make it clear to IDEs which subclass return type a function returns?

I have implemented a protocol in an object oriented way. There are Command and Response classes for each Command and its Response. There is also a Device class, which aids with sending Commands and getting their response.

Now, if I send a command and want to interpret the response I can do:

/** @var Device */
$response = $device->sendCommand(new GetSomethingCommand());
// response can now only be a SomethingResponse object, so I can safely access:
$response->someField;
// But IDEs do not know this,
// so if I want to have auto-completion
// I need to explicitly do an instanceof check:
if($response instanceof SomethingResponse){
    //now I can access $response->someField without the IDE complaining.
    $response->someField;
}

My question is: Is the way I implemented this bad design? Is there anything I can do to make this clearer to IDEs? I want to avoid to constantly do absolutely unnecessary instanceof checks.

Here is the most important content of some classes to understand the structure:

class Device{
    //...   
    public function sendCommand(Command $command): Response{
        $this->deviceConnection->send($command->encode());
        return $command->decode($this->deviceConnection->readUntil());
    }
    //...
}
abstract class Command{
    //...
    
    public function encode(): string{
        //...
    }
    
    abstract public function decode(string $data): Response;
}
class GetSomethingCommand extends Command{
    ///...
    public function decode(string $data): SomethingResponse{
        return new SomethingResponse($data);
    }
}
abstract class Response extends CharacterStream{
    //...
    
    public function __construct(string $data){
        //code calling decode
    }
    
    abstract protected function decode(FieldStream $dataStream);
}
class SomethingResponse extends Response{
    //...
    protected function decode(FieldStream $dataStream){
        //...
    }
}

My idea for a solution

One idea I got while writing this question is to have the sendCommand functionality in the Command class. I have the following issues with this though:

  1. This would require passing the Device or DeviceConnection object to this send function, which makes the raw protocol implementation which only worked with strings up until now dependent on the Device classes/interfaces (which implement specific communication).
  2. It also would be a lot (well 3 lines) of boilerplate code in each Command class.

That's why I really don't like this idea, but maybe it is actually the proper way to do it?

This is how it would look like I think:

//in the command class:
abstract class Command{
    //...
    abstract public function send(DeviceConnection $deviceConnection): Response{
        $deviceConnection->send($this->encode());
        return $this->decode($deviceConnection->readUntil());
    }
    //...
}
//in each command class we need to overload the return type:
class GetSomethingCommand extends Command{
    ///...
    public function send(DeviceConnection $deviceConnection): SomethingResponse{
        return parent::send($deviceConnection);
    }
    //...
}

Q: [Python] How to print a pyramid of full pyramids?

So I'm a newbie programmer, and we were recently tasked with printing a full pyramid of asterisks with the number of rows being based on the input, then printing a pyramid of those pyramids.

Basically the output I'm expecting when the user inputs Number of Rows: 4 is:

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

This is the best that I could work on using looping.

rowInput = int(input("Number of Rows: "))
rowCount = 0
min = rowInput
max = rowInput

while (rowCount < rowInput):
  digit = 1
  while (digit < min): 
    print(end=" ")
    digit += 1
  while (digit >= min and digit <= max):
    print(end="*")
    digit += 1
    
  print()
  min -= 1
  max += 1
  rowCount += 1

Input:

Number of Rows: 4

Output:

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

I think that it could work with another loop on top, but I can't think of a viable way to increment the spaces between two triangles. Are there any other options?

my problem that i need design patterns in practical solution ( in real life examples)

I need design patterns in practical solution (in real life examples) - like observer for refresh or log - Facade Pattern for what case ?

I need to know when to apply any design pattern ? which design pattern for specific problem? tutorial online not clear about that

I searched the internet many times, but all article theoretical answer
https://www.tutorialspoint.com/design_pattern

vendredi 29 octobre 2021

How to name common class among some classes named XXXHandler?

There ars many Handler class in my project. May be like:

class AHandler {
    BHandler bHandler;
    String getV();
    ...
}

class BHandler {
    String getV();
    ...
}

Now, I want to refact them.
Solution 1:

class HandlerHelper {
    String getV();
    BHandler bHandler;
}

Then, AHanlder and BHandler refer HandlerHelper.
How to name HandlerHelper? Thank you.

How to design notification system that sends real-time alerts created by users

I've been thinking about how to design a system that supports user created scheduled alerts. My problem is once the alerts are created and inserted into a database, I don't know what the best way to go about scheduling those alerts. Polling the database to see which alerts need to go out next doesn't seem entirely right to me.

What are some ways this could be handled on a scale where say a million users could create their own custom alerts like change baby diaper at 3pm everyday?

How to wrap a command inside if-else statements with same condition used in many places

I have a class with many public methods. Each method executes a single task when a single condition is met. The conditions in all methods are exactly the same as seen below:

public class MyClass{
    
    public ClassA method1 (arguments...){

        if(condition(aLong, aString)){
            return doSomething(arguments...)
        }else{
            throw new CustomException();
        }

    }

    public void method2 (arguments...){

        if(condition(aLong, aString)){
            doSomethingElse(arguments...)
        }else{
            throw new CustomException();
        }

    }

    public List<ClassB> method3 (arguments...){

        if(condition(aLong, aString)){
            return doSomethingDifferent(arguments...)
        }else{
            throw new CustomException();
        }
    }

    private boolean condition(Long aLong, String aString){
        // some code
        return true;
    }
}

I wanted to get rid of the repeating if...else condition by using the command pattern, so i created a class like below to wrap the actual execution inside an if else statement.

public abstract class ValidCommand<T extends Serializable> {

    private BiPredicate<Long,String> predicate;
    private Long aLong;
    private String aString
    
    public ValidCommand(BiPredicate<Long,String> predicate,Long aLong, String aString){
        this.predicate = predicate;        
        this.aLong = aLong;
        this.aString = aString;
    }

    public T execute(){
        if(predicate.test(playlistId, requestUserId)){
            return onExecution();
        }else{
            throw new CustomException();
        }
    }

    protected abstract T onExecution();

}

and I refactored the class with the methods as below:

public class MyClass{

    private BiPredicate<Long,String> predicate = (a,b) -> condition(a,b);
    
    public ClassA method1(arguments...){

        ValidCommand<ClassA> validCommand= new ValidCommand(predicate,aLong,aString){
            @Override
            protected Serializable onExecution() {
                return doSomething();
            }
        };

        return validCommand.execute();
    }
    .
    .
    .
 
}

My question is if there is a better way of doing this in Java and if is worth bothering in terms of code readability and DRY principles. Note that the number of methods inside MyClass may increase and probably all of them will share the same condition.

Access Members of ObjectA from contained ObjectB

If I have several levels of object containment in an object tree where:

ObjectA contains a List<ClassB> ObjectBs
=> ObjectB contains a List<ClassC> ObjectCs
===> And so on...

Is there an easy way/design pattern to access a variable/member of ObjectA through its containing member Object C?

For example:

nameOfObjectA = ObjectC.GetUpmostContainer().GetName()

Curently I am instantiating the tree recursevily and with my knowledge I would need to pass the name of ObjectA on each instantiation of an object, which will be contained by ObjectA.

jeudi 28 octobre 2021

Which pattern should I choose? [closed]

I am facing a problem and would like to hear an advice. On my website, customer has a wallet balance. Customer can do 4 things - Buy, Sell, Send fiat currency, Send cryptocurrency.

Each of these 4 operations change the wallet balance.

Read about an observer pattern but that would be more useful when you have few publishers and lots of subscribers. In my case these are 4 publishers(buy,sell,fiat,crypto) and 1 subscriber(wallet balance).

class SendFiat(){
    SendFiat();
}

class SendCrypto(){
    SendCrypto();
}

class Buy(){
    Buy();
}

class Sell
{
    Sell();    
}

All of these 4 methods, influence wallet balance record in database. When this is updated, I use SignalR to update html on client-side but that's another story.

Which pattern should I choose?

Difficult with design pattern in python application

I have little experience coding and I am having trouble coming up with a design for this specific application (the first one I am trying on my own). The app should be able to read and extract the info from a qrcode printed on a shopping receipt, use this info to access a web page and retrieve a table from it. Every tuple in the table corresponds to a product and it has 3 columns: the product description (str), the quantity (float), and a code (int).

Then it will use this information to search for the details of each product in a data base. I have 2 different data bases to search from: one for industrial products (that I search using the code attribute), and one for perishable products (that I search using the description attribute - using the fuzz package). These 2 sources will give me a json file containing detailed information about the products, but with a different schema. I also would like to have a 3rd source, which would be populated with information previously got from the 2 external sources.

The receipt would contain the information to instantiate an Order object and the json files the information to instantiate an Product objects. Also, Product objects could mean different things (items like food (that would have nutrition facts) or hygiene (that would not have nutrition facts), for example). And lastly, I would have a Person object, so that each Order would have a relation with a single Person, but the Person could be related to multiple Orders.

I am having trouble figuring out what would be the best design pattern, how to segregate and organize modules, what should be a class or when just using functions are fine and also how to store and access information. I am starting to study these subjects, but some guidance here would be very much appreciated. That is a lot of stuff, so here is what I have so far and some specific things I have in mind:

app
│   main.py (ask for user input to select receipt image and call other modules. 
|            In the end I have some json files for order info and product information)
│   qrcode.py (only functions that read the image and return the information)   
│   search_order.py (only functions to access web page and return json file with order information)  
|   search_product.py (only functions to access data base and return json file with product details)
|   order.json (store order details) 
|   product_by_code.json (store list of industrial products in json format)
|   product_by_description.json (store list of perishable products in json format)

*Shortly I will look to store the info a sql DBMS, but that is what I have so far.

Some questions I have:

  • Order would be a class that will only store information and be composed of a unique ID attribute, a date of creation, a RetailStore object and a list of Product objects, and the quantity (weight or units) of each product. I believe those attribute should be created when a object is instantiated and not change after that. Is that a correct thinking or should it be more flexible? Should search_order.py be responsible for instantiating the object, since it is the source of the information? But one day the abstraction of Order could change, how to deal with that then?

  • Since I have different sources for the products detail information, should I have a single file dealing with all the sources or one for each and something to deal with them and provide an simpler interface for the instantiation of a Product?

  • Product would be a class that will only store information and be composed of description, category, brand, Nutrifacts object (if food), Ingredients object. Should I have an abstract Product class, and, in the same file, concrete sub classes like (Food, Cleaning, Hygiene, etc)? How to instantiate an object considering I have different sources for most of the information used here? Should I have different Product methods decorated with @classmethod to have alternative constructors? Should the Product class be in the same file as the Order class?

  • Once I have a Person object, with its Order objects (with its Product objects), how should I serialize (and then deserialize) all this information? Should I store locally in a json file?

I feel I am living in a tree recursive maze trying to figure these things out. I have many other doubts, but I hope clearing up those questions is a good above start.

Factory Method with Generic Interface

I have two different types of item: Picture and Video. In order to manage them, I have created an interface and two classes which implement it

public interface Item{
}

public class ItemPicture: Item{
}

public class ItemVideo: Item {
}

Now I have some classes to manage that items, that inherit from a manager interface

public interface ItemManager<T>{
   IList<T> FGetByGroup(string idgroup);
}

public class ItemManagerPictures : IItemManager<ItemPicture>{
   public IList<ItemFoto> FGetByGroup(string idgroup){
      ...
   }
}
public class ItemManagerVideos: IItemManager<ItemVideo>{
   public IList<ItemVideo> FGetByGroup(string idgroup){
      ...
   }
}

In order to have a factory method which creates the appropriate object, I have created this class

public class ItemManagerCreator
    {
        public static IItemManager<Item> MakeItemManager(string type)
        {
            IItemManager<Item> objMgr = null;

            switch (type)
            {
                
                case "Picture":
                    objMgr = (IItemManager<Item>)new ItemManagerPictures();
                    break;

                case "Video":
                    objMgr = (IItemManager<Item>)new ItemManagerVideos();
                    break;

                default:
                    break;
            }
            return objMgr ;

        }
    }

From the controller I want to do this

var type="Picture";

IItemManager<Item> itemMgr = ItemManagerCreator.MakeItemManager(type);
var itemList = itemMgr.FGetByGroup(string idgroup);

But I get this casting error

Can't convert from type '...ItemManagerPictures' to type '...IItemManager`1[...Item]'.

which makes me think I'm doing something wrong, but after 1000 turns, I think the problem is with the factory method and generics, which is not well designed.

I'm new to design patterns, and maybe I'm not applying the right one.

Thanks in advance

is Proxy class related to proxy design pattern

there is a class in java called Proxy: https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html As I understood it is used to implement interfaces on runtime. On the other side when searching for this, I came across a page explaining the proxy design pattern, so are they related in any way? or they are totally separate things?

Replace If else in C Sharp

This is my Business Layer Code public void UpdateRecords() {

int resultCountries = 0
int resultState = 0
int resultDistrict = 0
int resultCity = 0
DataTable dt = dataAccess.GetRecords();
foreach(DataRow dr in dt.Rows)
{    
    int PersonId = Convert.ToInt32(dr["PersonId"].ToString());
    resultCountries = dataAccess.UpdateCountries(PersonId);
    if(resultCountries > 0)
    {
        dataAccess.UpdateMessage(personId,"Country Updated Successfully");
        resultState = UpdateState(personId);
        if(resultState > 0)
        {
            dataAccess.UpdateMessage(personId,"State Updated Successfully");    
            resultDistrict = UpdateDistrict(personId);
            if(resultDistrict > 0)
            {
                dataAccess.UpdateMessage(personId,"District Updated Successfully");
                resultCity = UpdateCity(personId);
                if(resutlCity > 0)
                {
                    dataAccess.UpdateMessage(personId,"City Updated Successfully");
                    continue;
                }
                else if(resutlCity == 0)
                {
                    dataAccess.UpdateMessage(personId,"City Not Updated Successfully");
                    continue;
                }
                else
                {
                    dataAccess.UpdateMessage(personId,"Some error occured while updating city...");
                    continue;            
                }        
        
            }
            else if(resultDistrict  == 0)
            {
                dataAccess.UpdateMessage(personId,"District not Updated Successfully");
                continue;
            }
            else
            {
                dataAccess.UpdateMessage(personId,"Some error occured while updating district..");
                continue;
            }        
        }
        else if(resultState  == 0)
        {
                dataAccess.UpdateMessage(personId,"State not Updated Successfully");
                continue;
        }
        else
        {
            dataAccess.UpdateMessage(personId,"Some error occured while updating state..");
            continue;
        }        
    }
    else if(resultCountries == 0)
    {
        dataAccess.UpdateMessage(personId,"Country not Updated Successfully");
        continue;
    }
    else 
    {
        dataAccess.UpdateMessage(personId,"Some error occured");
        continue;
    }
}

}

From business Layer I am calling data access layer methods,UpdateCountries,UpdateState,UpdateDistrict,UpdateCity which are updating country, state,district,city against personId in person table.

If country update is successful,state is updated otherwise log the error in db and update next record. Same is done for state,district,city. But here there are lots of if else used,kindly let me know how to replace if else in code. Do not want to use switch case or ternary operator,also not allowed to use stored procedure. The dataaccess layer methods return integer value of 1 if update is successfull,0 if condition is not satisfied,-1 if error.

mercredi 27 octobre 2021

c# - which is the fastest pattern scanning algorithm?

so I am coding a Sigmaker which searches for a certain Byte Array in Program Memory.

So far i'm making good progress, i'm just a little disappointed with the scan speed. with larger ranges it can sometimes take up to 5 minutes to get a valid result.

I'm using the following code right now:

IntPtr bytesRead;
ReadProcessMemory(process.Handle, baseAddress, moduleBytes, moduleBytes.Length, out bytesRead);

for (int modulePos = 0; modulePos < moduleBytes.Length; modulePos++)
{
   if (moduleBytes[modulePos] == patternBytes[pos] || mask[pos] == '?')
   {
       if (pos == maskLength)
       {
           foundstuff.Add(IntPtr.Add(baseAddress, modulePos - maskLength));
           pos = 0;     
       }
       pos++;
    }
    else
    {
        modulePos -= pos;
        pos = 0;
    }
}

I have accordingly searched for better algorithms and found the following: KMP Algorithm for Pattern Searching

Reading that, I added a KMP Algorithm to my project and after hours of work i have to realize that despite different codes and several rewrites the kmp algorithm is in the end 3-4 times slower than the code i used before, which doesn't sum up with the multiple comments in different threads that the KMP Algorithm would be the fastest one for my Work?

So did I do something wrong or is the Algorithm that I use actually the fastest Method for my Signature Scanner? Are there better Algorithms?

In case I did something wrong, I'll just add the Code here that I used:

IntPtr bytesRead;
ReadProcessMemory(process.Handle, baseAddress, moduleBytes, moduleBytes.Length, out bytesRead);

//converting ByteArray to HexString for the Algorithm
string data = ByteArrayToHexViaLookup32(moduleBytes); //will look like this "0F A2 03 00 01.."

//algorithm
int[] value = SearchString(data, pattern);
//Output = Offset of the found pattern

Here is the SearchString(data, pattern) Module

Is it 'worth' subclassing a python class to change the initialiser, or are there better patterns to use?

I'm designing a library with a fairly powerful class - we can think of it as a list.

I'm expecting users to want to create their own lists, prepopulated with certain content. For the sake of example, things like "add n identical items to the list", or "initialise with the numbers from a->b". Note that these things don't really change how the list works, they just set it up in some complex way.

The users will need to use these from different bits of code, be able to reuse them in the future.

I can see two possible ways for the users to do this:

Create a function which builds the object for them, e.g.:

def make_item_list(n,x):
    ls = [x]
    ls *= n
    return ls

Or, alternatively, subclass the list to add an initialiser:

def RepeatList(List):
    def __init__(self,n,x):
        super().__init__()
        self.listitems = [x]*n

Clearly this is a toy example but which of these is more sensible and 'pythonic'? If there are other patterns in Python to do this, what are they? If the choice of pattern depends on something else I haven't mentioned, what is it and how would it influence decision making? I'm happy to provide more info if you need it. Thank you!

What is the design principle to only assign a single meaning to a boolean variable?

I'm pretty sure I was taught a long time ago that it's bad practice to use a boolean variable to hold information about more than one property. I've not been able to find the name of a design principle that covers this.

As an example, say we wanted to record whether a customer wanted milk and sugar in their drink. We'd have one variable for milk and one for sugar.

We wouldn't conflate these into variables milk&Sugar and milk&NoSugar because the choice of Sugar is in both variables, so what would it mean if both boolean variables were true? Does the customer want sugar or not?

But is there a name for this design principle?

(A colleague has tried to justify the latter, noting that this works if one boolean takes precedence over the other. Seniority rather than sense has prevailed!)

Microservices and Coupling - competing design principles

So coupling is a hot topic with microservices, and I have not been able to find specific advice beyond top level design concepts.

I have a service that integrates data from multiple data sources. A key function is associating the data. And now the code is being migrated to a platform with microservices.

So I have one service right now that provides

  • datasource A with a key I assign, which is held in memory. Data expires quickly, so putting this in memory is an acceptable optimization for resource use.
  • datasource B with a key which associates to datasource A

So if the App A restarts, all associations are lost and we start over.

Now if I split this into two microservices, when microservice A crashes, then the keys in microservice B "expire" and are no longer valid. In my thinking, that makes us tightly coupled.

One microservice goal is loose coupling. But I just don't see how I can do that if I am tightly coupled. Single responsbility principle allows for exception to single responsibility for "cohesive related functions", which seems to apply.

I always thought that the single responsibility principle needs to be tempered with wisdom. Splitting every single tiny function into separate programs at some point becomes wasteful.

So bottom line is I am in a philosophical argument here, and I don't know how to approach the question about coupling. Clearly, at some point it doesn't matter if data is coupled, you have to draw boundaries at some point and this makes this choice to split the service a subjective decision. You could argue that primary key association is least amount of coupling you could ever have, so I should get over myself. At the same time, creating two databases (one for each service) to track key associations seems like overkill.

And there is a practical argument. I have software that works. No need to change that. It would be a lot of work to split these out. I would need to make a permanent database to store these keys, for example. I would need to detangle coupled classes and functionality. In the work vs value equation, it's hard to say "the value of 100 hours of work is microservices for microservices sake." That's not to say microservices for microservices sake isn't valid, but I would rather spend 100 hours on creating "real" value.

How do you decide? Am I missing a clear guiding principle here?

Which one of the SOLID Principles are the most violated? [closed]

This question was asked to me by a colleague and we are divided between Single Resonsability and Depency Inversion. Which of the solid principles do you think is the most violated in this ActiveRecord pattern?

public class WorkItem{
     
        private string _id;
        private string _name;

        public void Save(){
            SqlConnection cnx = new SqlConnection(ConfigurationManager.ConnectionStrings["database"]);
            cnx.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cnx;
            if (_id){
                  cmd.CommandText = "INSERT INTO WorkItem (Id, Name) VALUES ('";
            }else{
                  cmd.CommandText = "UPDATE WorkItem SET Id ...'";
            }

            cmd.CommandText += _id + "','" + _name + "')";
            cmd.ExecuteNonQuery();
            cnx.Close();
        }
        
        public void GetById(string id){
            SqlConnection cnx = new SqlConnection(ConfigurationManager.ConnectionStrings["database"]);
            cnx.Open();            
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cnx;
            cmd.CommandText = "SELECT Id, Name FROM WorkItem where Id = '" + id + "'";

            SqlDataReader dr = command.ExecuteReader();
            
            if (dr.Read()){
                _id = dr["id"].ToString();
                _name = dr["name"].ToString();
            }else{
                return null;
            }
        }
    }

Create Person(Real person or Legal Person) using design pattern

I have person class :

public class Person : 
    {
     public Guid Id { get; set; }
     public Guid? PersonRealId { get; set; }
     public Guid? PersonLegalId { get; set; } 
     public virtual PersonReal PersonReal { get; set; }
     public virtual PersonLegal PersonLegal { get; set; }
    }

the real one :

 public class PersonReal 
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public Guid Sex { get; set; }
        public string FirstName { get; set; }
    }

and the legal one has :

public class PersonLegal 
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Name { get; set; }
        public Guid? TopManager { get; set; }
        public string NationalCode { get; set; }
    }

the person is always one of the real or legal type and not both of the same time . what is the best pattern to implement person using design pattern?

Redundant assignment vs check before assignment in Java

In front of a long loop, it costs more (processor + memory) to assign redundantly the same value, or to check before the assignment? 

int count = 0;
for(int i=0; i<100_000; i++){
    if (...) {
        count++
        doLogic(count); // logic is strictly related with count
    } else {
      count = 0;  //50.000 redundant assignment
    }
}

VS.

int count = 0;
for(int i=0; i<10_000; i++){
    if (...) {
        count++
        doLogic(count); // logic is strictly related with count
    } else {
        if(count > 0) { // 50.000 checks 
          count = 0;
        }
    }
}

And would it cost the same if count would be present in a different object (injected as singleton in a spring context) and the increments/check/reset would be like:

config.incrementCount();
config.getCount();
config.resetCount();

How could Vulkan pNext design be implemented in a safer way?

Vulkan introduces a member .pNext of type void* in all its core structs allowing to create handles. This member purpose is to allow to extend the structure by passing a pointer another one.

This is mainly used for extensions, so that the same struct can be extended by two different extensions without any need to modify the original members. You simply check .sType of the .pNext (the first few bytes), and apply a std::any_cast / reinterpret_cast (or equivalent) to get the other members depending on the value.

I find this idea very elegant, as it not only allows flexible, extensible design, but also is very convenient when you try to maintain backwards compatibility.

(See also the references for more context)


Problem:

There is however something that bugs me in this design: this void* (or std::any for that matters). You must trust the user, who must put a valid member, and cannot assume anything about the type. Consider the following case:

struct extension_a
{
    structure_type_t sType;
    void* pNext;
    //... Other members
 };
 
struct extension_b
{
    structure_type_t sType ;
    void* pNext;
    //Other members MATCHING THOSE OF A IN SIZE, member per member
}

So two structs with members matching in size and order, only the valid sType differs. If user U does the following :

extension_b ext 
{
    .sType = extension_a_identifier, //<-------------------
    .pNext = nullptr,
    //other members initialized
};

const create_info creator 
{
    //...
    .pNext = &ext;
    //... Other members
};

framework_command(something, &creator, otherthing);

It is very likely the data of ext will be reinterpreted as if the one from a extension_a, resulting in either undefined behaviour or unexpected results as it is supposed to be extension_b data.


Questions:

Thus leading to the question in the title:

How could Vulkan pNext design be implemented in a safer way?

But also to :

  • Am I mistaken in the way Vulkan handles the .pNext members?

*Note that my question is not about reimplementing this in Vulkan *. This would be completely stupid, Vulkan devs have other things to do. It is more about porting the design to another API.


Design proposition:

(This is expressed in the C++ way for readability)

  • .pNext is split into other members. An additional member, .extensions specifies the active extension(s).
struct create_info
{
    extension_a* pExtensionA = nullptr;
    extension_b* pExtensionB = nullptr;
    
    extension_flags extensions = extension_flags::nothing;
    
    //... Other members
    
    void add(extension_a* const ext)
    {
        pExtensionA = ext;
        
        if(pExtensionA != nullptr)
        {
            extensions  |= extension_a_identifier;
        }
        else
        {
            //Reset the part of extension notifying extension_a_identifier
        }
    }
    
    //... Similar for extension_b
};

Where extension_flags is taken from a VkStructureType-like enum allowing to build unique flag combination (using binary OR for example).

  • Should you need to restrict to one extension of the struct, you can proceed this way
struct create_info_2
{
    extension_a* pExtensionA = nullptr;
    extension_b* pExtensionB = nullptr;
    
    extension_flags extensions = extension_flags::nothing;
    
    //... Other members
    
    void extend(extension_a* const ext)
    {
        pExtensionA = ext;
        pExtensionB = nullptr;
        
        extensions  = extension_a_identifier;
    }
    
    void extend(extension_b* const ext)
    {
        pExtensionA = nullptr;
        pExtensionB = ext;
        
        extensions  = extension_b_identifier;
    }
    
};

  • Finally, in functions using create_info, you check extension to know what to do and only use the appropriate member:
if(creator != nullptr)
{
    switch(creator.extensions)
    {
        //...
    }
}
  • Pros:

    • Well, this forces the user to put something valid.
    • Solves the problem explained above.
    • Does not require a chain.
  • Cons:

    • This is not as flexible. It works for API versions (simply #ifdefs with the additional possible members) but not for extensions, which surely do not have access to this part of the code.
    • It is somewhat a pain to maintain. Additional #ifdefs checking the API version may be required in the commands using those structs.
    • Generating extension_flags mask can be a problem, especially if they are more than 64 possible things. It can however be split in several enums, one per structure extension_flags_xxx_create_info for example.

Needless to say, I am not exactly satisfied by such a design, as it looses in flexibility but more importantly in maintainability and extensibility.

References

Vulkan: What is the point of sType in vk*CreateInfo structs?

Purpose of pNext in Vulkan structures

Why do some struct types let us set members that can only be a certain value?

Decorator Pattern in Pascal/Lazarus

I am trying to implement the Decorator Pattern in a very simple example.

In this way, which should be the right one as far as "Decorator Interface" implements "Shape Interface" it does not work.

The line triangle := TGreenShapeDecorator.create(triangle); fails because tringle is of type IShape but not IShapeDecorator;

program project1;

{$mode objfpc}{$H+}

uses
   Classes, SysUtils;

type
   {Shape Interface}
   IShape = interface
      function draw():String;
   end;

   {Clase 1}
   TTriangle = class(TInterfacedObject, IShape)
      function draw():String;
   end;

   {Decorator Interface}
   IShapeDecorator = interface(IShape)
      property shape:IShape;
      function draw():String;
   end;

   {Decorator 1}
   TGreenShapeDecorator = class(TInterfacedObject, IShapeDecorator)
      shape : IShape;
      constructor create(shape_in:IShape);
      function draw():String;
   end;

function TTriangle.draw():String;
begin
   Result := 'Triangle';
end;

constructor TGreenShapeDecorator.Create(shape_in:IShape);
begin
   shape := shape_in;
end;

function TGreenShapeDecorator.draw():String;
begin
   Result := 'Green ' + shape.draw();
end;


var
   triangle : IShape;

begin
   // Triangle OBJECT
   triangle := TTriangle.Create;
   WriteLn(triangle.draw());

   // Green decorated triangle
   triangle := TGreenShapeDecorator.create(triangle);
   WriteLn(triangle.draw());

   ReadLn();
end. 

In this other way it works:

program project1;

{$mode objfpc}{$H+}

uses
   Classes, SysUtils;

type
   {Interfaz}
   IShape = interface
      function draw():String;
   end;

   {Clase 1}
   TTriangle = class(TInterfacedObject, IShape)
      function draw():String;
   end;

   {Decorator Interface}
   IShapeDecorator = interface
      property shape:IShape;
      function draw():String;
   end;

   {Decorator 1}
   TGreenShapeDecorator = class(TInterfacedObject, IShapeDecorator, IShape)
      shape : IShape;
      constructor create(shape_in:IShape);
      function draw():String;
   end;

function TTriangle.draw():String;
begin
   Result := 'Triangle';
end;

constructor TGreenShapeDecorator.Create(shape_in:IShape);
begin
   shape := shape_in;
end;

function TGreenShapeDecorator.draw():String;
begin
   Result := 'Green ' + shape.draw();
end;


var
   triangle : IShape;

begin
   // Triangle OBJECT
   triangle := TTriangle.Create;
   WriteLn(triangle.draw());

   // Green decorated triangle
   triangle := TGreenShapeDecorator.create(triangle);
   WriteLn(triangle.draw());

   ReadLn();
end.

Showing the result:
Triangle Green Triangle

Is it possible to do it in the first way and I am doing something wrong?, or is it not possible and the only way is the second one?

Thank you.

mardi 26 octobre 2021

How to optimise database design for software versions

We want to design database schema which will have information related to software release and it's mapping -- to which software version it can be updated and downgraded to.

Current database schema -

software_version
------------------------------------------------
ID 
version - string
release_notes - string
artifacts_url - string

We have another table where we keeps mapping for those -

software_version_mapping
------------------------------------------------
ID 
base_version - foreign key to software_version
update_to_version - foreign key to software_version

This way works for both update and downgrade. But the problem is we have more than 100 version and software_version_mapping is growing too much since we have to keep mapping with all for new version.

Can I get suggestion on this - how can we minimise the entries in software_version_mapping which will satisfy conditions like -

  1. new version can be updated from any / all previous one
  2. new version can be updated from only selected old versions
  3. new version can be updated between range of versions
  4. we should be able to add downgrade mapping as well

Thanks in Advance!

If I have two separate "factories" that doesn't extend to an abstract parent factory, is it still a factory pattern?

enter image description here Is this still considered a factory pattern? My client knows which superclass they need so they also know which factory to use. But these "factories" doesn't extend to a single abstract factory, unlike what has been demonstrated in my textbooks, so I'm a bit confused.

Examples of recursive predicates

In Stone's Algorithms for Functional Programming, he gives a design pattern for recursively defined predicates, which in Scheme is

(define (check stop? continue? step)
  (rec (checker . arguments) 
    (or (apply stop? arguments) 
        (and (apply continue? arguments) 
             (apply (pipe step checker) arguments)))))

where pipe is the author's function to compose two functions in diagrammatic order, ((pipe f g) x = (g (f x)).

So, for instance, to test whether a function is a power of two, you could define

(define power-of-two? (check (sect = <> 1) even? halve))

where (sect = <> 1) is the author's notation for currying, equivalent to lambda x: x == 1.

Clearly a lot of predicates could be implemented recursively but it would not be useful. And clearly there are some recursive predicates that wouldn't use this pattern, like predicates on trees.

What are some classic predicates that fit this pattern? I guess testing if something is in the Cantor set, but that's almost the same as the above.

Design pattern for decoupling core and auxiliary functionality

Consider a synchronous (Java) function WORKER which takes some input and returns some output. I will refer to this as the core functionality. Its exact nature and implementation is irrelevant; what's important, however is that function WORKER is huge, it consists of multiple steps/substeps/subsubsteps and it puts in motion a large OOP machinery while calculating the output.

There are some auxiliary features, which are orthogonal to the core functionality: WORKER has to be monitored/tracked and reported (statistics at the end). Currently the auxiliary functionalities are embedded in the core functionality resulting in a hard-to-maintain, cumbersome code.

The question is this: are there some design patterns to decouple the core and auxiliary functionalities?

My first idea was to define WORKER with the help of a set of possible states. Reaching any of those states would trigger the callback of some registered observers (through which the auxiliary functionality is solved.) Here is the code demonstrating the idea:

public class StateMachine<State> {
    protected State state;
    public StateMachine(State state) {this.state = state;}
    public ArrayList<StateObserver<State>> observers = new ArrayList<>();
    public void transit(State newState) {
        observers.stream()
            .filter(o -> o.from.equals(state) && o.to.equals(newState))
            .forEach(o -> o.callback.run());
        state = newState;
    }
    public void registerObserver(State from, State to, Runnable callback) {
        observers.add(new StateObserver<State>(from, to, callback));
    }
}
@AllArgsConstructor public class StateObserver<State> {
    State from, to;
    Runnable callback;
}
@Getter public class Worker extends StateMachine<Worker.State> {
    enum State { INIT, WORKING, DONE; } 
    public Worker() { super(State.INIT); }
    @SneakyThrows public void doWork() {
        for (int i = 0; i < 10; ++i) {
            transit(State.WORKING);
            Thread.sleep(100);
        }
        transit(State.DONE);
    }
}
public class Progress {
    public Progress(Worker worker) { 
        worker.registerObserver(Worker.State.INIT, Worker.State.WORKING, () -> System.out.print("Starting...\n[ "));
        worker.registerObserver(Worker.State.WORKING, Worker.State.WORKING, () -> System.out.print("\b=>"));
        worker.registerObserver(Worker.State.WORKING, Worker.State.DONE, () -> System.out.print("\b]\ndone.\n"));
    }
}
public class App {
    public static void main(String[] args){
        Worker worker = new Worker();
        new Progress(worker);
        worker.doWork();
    }
}

This code, however, has some serious limitations:

  1. it's not clear what's the best way to create sub-states for Worker (sub-Workers?)
  2. how sub-substates should be advertised for observers for registration
  3. how the observers access arbitrary intermediate/temporary objects from Worker (e.g. the loop variable i in the above example)

Is it bad practice or plainfully wrong to declare a class which has methods that returns some value from another class in Python?

I wanted to separate the logic for my code and I don't have any experience with design patterns, but this question is nogging my head. I have a class Person that should have a pair of keys for encrypting and decrypting messages. The class calls methods from another class RSA, which contains all the logic for handling this.

Here is a snippet of the code for Person:

from RSA import RSA 

class Person:
    def __init__(self, name):
        self.name = name
        self._keys = None

    def generate_keys(self):
        self._keys = RSA.generate_keys()

    def sign(self, message):
        return RSA.sign(message, self._keys)

    def verify(self, recipent_pk, signature, message):
        return RSA.verify(recipent_pk, signature, message)

And a snippet for RSA:

class RSA:

    def generate_keys():
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        return private_key

    def sign(message: int, private_key: rsa.RSAPrivateKey):
        bytes_msg = message_to_bytes(message)
        signature = private_key.sign(
            bytes_msg,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        return signature

I'm asking because Pylint is yelling at me for not declaring self as the first parameter for each method in RSA. However, the code works fine without declaring it, but am I missing something here? Furthermore, message_to_bytes is a helper function used to convert the input from an integer to byte representation. Is it okay that it goes outside the class at the module level, or do I need to declare it inside the RSA class? (Currently it works, but it feels wrong coming from Java).

Convert List to Iterable by mapping values?

I have the following method taking a generic interface:

protected Iterable<Category> getEntity() {

    List<CategoryDTO> categoryList = categoryService.findAll();

    // now I need to set an Iterable<Category> list and return it
    // ... ???
    Iterable<Category> iterable;
    return iterable;
}

But as it is impossible to create interface instance, I have really no idea how to fill Iterable<Category> list and return it.

Here is my Category interface that I am trying to set and return:

public interface Category {
    String getName();

    String getItemType();
}

How can I fix that problem?

[architecture][patterns] Multi-service sync implementation

I have this one service that integrates some third party data provider with our systems. The service runs as Spring Batch jobs, so every step is a single job executed one after another.

The responsibilities of the service:

  1. gathering data from different files, databases and other services

  2. process the data

  3. produce one unified entity from the gathered data

  4. update several other systems with unified entity

I have no impact on the framework or tech stack here.

I faced the following issue: how to update other services and mark somehow that the particular update succeeded?

I thought about the db flags for every service to be updated, but this approach seems not to scale well (for every next service someone has to remember to add the flag).

There are broadcast patterns or bi-directional sync patterns but are they applicable for my scenario? How are they implemented?

Design Pattern to handle configuration depending on concrete implementations

I have the following code structure:

  • an algorithm interface defines a method execute(some_data, configuration).
  • various algorithms implement the interface and the execute(some_data, configuration) method differently.

The client now can create a concrete algorithm. Afterwards he passes some_data as argument to the method execute. Moreover, the client has to pass a configuration object ...

My problem is the following:

The configuration object strongly depends on the concrete algorithm. How can I structure this? Obviously I can define an abstract configuration and extend the concrete configuration depending on the concrete algorithm. But then I have to check inside of the concrete execute(some_data, configuration) implementation if the configuration fits to the class. I do not really know how to handle this ...

Can you help me? Is this a typical problem with easy best practice solution?

How to show possible actions in an activity diagram?

I am trying to depict an application in an activity diagram. It is about membership to an association. Both the member and association can cancel the membership of that member. I am not sure how to depict it. It is the diagram

There are three action flow beginning make member activity, finish as member, cancel membership by member and cancel membership by assoc. Is it a true representation? Three of the action flow are possible and only one can come true. I thought using black boxes but it is said to depict parallel activities. Or instead should I use decision diomand? What is the best depistion for this scenerio?

lundi 25 octobre 2021

How should I design a class that has some common props/method, but some are not

I'm working on a network class (aggregate) that has multiple types of network ex. (host, peering etc..). So I have a problem with the availableIp field because some network type does have, but some doesn't. For example hosting network type will need this field so I have to initialize it on the constructor, but since the ICommonNetworkInfo doesn't have it I will have to cast it to concrete class that contain this field. So I make my own solution by creating another interface that contains this field and implement on a concrete class that need this field.

interface ICommonNetworkInfo {
  val name: String
  // I dont want to put availableIp here
  // because some network type doesn't have this field
}

interface IHostAddress {
  val availableIp: List<String>
}

enum class CloudProvider {
  GOOGLE,
  AWS,
  AZURE
}

data class CloudHostingNetwork(
  val cloudProvider: CloudProvider,
  override val name: String,
  // I only want this common field
  // but some other fields will be used later on the service layer
  override val availableIp: List<String>
): ICommonNetworkInfo, IHostAddress {
}

data class InternalHostingNetwork(
  val employeeId: String,
  override val name: String,
  // I only want this common field
  // but some other fields will be used later on the service layer
  override val availableIp: List<String>
): ICommonNetworkInfo, IHostAddress {
}

data class CreateHostingNetworkCommand(
  val networkId: String,
  val ipv4Cidr: String,
  // it can be either internal hosting or cloud hosting or else
  val networkInfo: ICommonNetworkInfo
)

abstract class AbstractNetwork() {
  lateinit var ipv4Cidr: String
}

class HostingNetwork: AbstractNetwork {
  // this field only belong to hosting network
  // other network type doesn't have this field
  var availableIp: List<String>

  constructor(command: CreateHostingNetworkCommand){
    // todo ...
    this.ipv4Cidr = command.ipv4Cidr
    // dirty solution that i made
    val temp = command.networkInfo as IHostAddress
    // I only want 
    availableIp = temp.availableIp
  }
}

but it seems dirty and complex for me. what can I do to refactor this code. Are there any design patterns that fit perfectly for this problem.

Best practises for consuming multiple third party APIs in existing API

I'm trying to find out the best approach for designing the following scenarios.

Let's assume, that I already have, a REST API implementation, which is going to fetch books, from different providers and serve them back, to my own client.

  1. Each provider offers a separate API for serving books to its consumers.
  2. Each provider, has a completely different structure on the response from the previous one.
  3. My client should always get exactly the same format, so the frontend-client application can handle the responses.

Some output examples:

Provider 1

[
  {
    "bookId": 32,
    "bookName": "foo",
    "author" : {
      "name" : "John",
      "surname": "Doe"
    },
    "publisher": {
      "name" : "Foo Books",
      "address": "New York"
    }
  },
  ...
]

Provider 2

[
  {
    "publisherCompany": {
      "name": "Foo Books",
      "position": "New York",
      "books": [
        {
          "id": 32,
          "title": "Foo",
          "author": {
            "name" : "John",
            "lastName": "Doe"
          } 
        },
        ...
      ]
    }
  },
 ...
]

Both of those 2 providers, are outputting the same values, but in different format. Moreover some keys are completely different.

What I'm looking for, is an Architectural Design or a Design Pattern, so i can map each different output, to my own format.

What i have tried in the past

  • I had created my own Entities
  • I had different services for each consumer and after fetching the data, i was instantiating my own entities and mapped the responses accordingly.
  • After having my objects (Entities) filled with data, i was passing them to a transformer function to transform them to the desired output.

My questions:

  • Is there any Design Pattern for this?
  • Is there any terminology for this scenario so i can do a research?
  • In which way you would approach this scenario?
  • Any resources for reading ?

Thanks ;)

Does dependency injection in ASP.NET Core add performance overhead?

I'm working on a app where DI was avoided to improve performance. The service dependency is implemented as a static class and referenced directly in the calling class. This is presenting the typical challenges for testing since it's not possible in inject a stub for this service.

My first thought is to setup a regular class and interface, put it into the container as a singleton, and then inject it into the calling class constructor. This API app is very performance critical, so the design choices cannot add any extra milliseconds to the response time.

Is it possible to use DI without adding some performance overhead? If not, is there another design pattern I can use to maintain performance but improve the testability of the class at the same time?

should i use Factory pattern for sending dynamic mails for more than 50 clients

I am having chalice project and using that i am sending mails to the clients. Every client is associated with an organization. Till now i was using same template for all clients but now i need to make changes in the mail template at organization level like every organization demand different things in the mail for their users. Should i use factory design pattern in chalice for solving this problem if organizations are more than 50. I doubtful because for that i have write 50 different classes for each organization Or should I use decorator feature of python which can wrap every function as per the requirement. Please help me with this if you are having clear knowledge of Design pattern.

def userDecoratorMail(func): #passing method as first class function
    def wrapperFunc(appdata):
        if appdata["org_id"] == 5: #checking the condition with client id
            return func(appdata)
        return "Secondary Template"  #return secondary templte.
    return wrapperFunc
        
@userDecoratorMail     
def mail(appdata): # Base method
    return appdata #some mail function will get trigger with appdata information
dict1 = {"user_id":"123","username":"chandresh","org_id":5}

mail(dict1) # calling base method.

dimanche 24 octobre 2021

Trying to print a "Triangle of triangles" using for loops. Can't seem to print horizontally

The program needed is one that takes an integer as input to make a triangle out of triangles, like so: sample of input and output

I've tried this code:

num = int(input())


for i in range(0, num):
    for j in range(0, num - i - 1):
        print(" ", end = "")
    for k in range(0, 2 * i + 1):
        for l in range(num):
            print(" " * (num - l - 1) + "*" * (2 * l + 1))
            
    print()

It prints out the triangles the right amount, but they're on top of each other: vertical triangles

I tried adding end = "" to the print(" " * (num - l - 1) + "*" * (2 * l + 1)) and it kind of fixes the vertical printing. It's just that the smaller triangles are printed horizontally as well, like so: horizontal lines

Is there any way to print out strings horizontally without using end = "" ? Or am I just taking the wrong approach to the problem? I hope I'm explaining this correctly, I'm just new to coding. Thanks!

Pass Method as Parameter using C# with Parameters - Using the Command Pattern

I'm new to passing delegates and was wondering if the following code is possible to do?

CommandQueue.AddCommand(
    new CommandItem(
        group.MyGroupActionMovement(
            new Vector3(-1000,-1000,-1000))));

ok to elaborate I'm going to do a code dump of my bad attempt at the command pattern...

So I'm trying to create a queue of commands. Starting with just the movement command. It takes a vector3 as a parameter. Other Commands will have different parameters like enums and game objects.

This is supposed to be my interface for commands/actions but, I've been messing with it to see what I can do.

public class IGroupAction: MonoBehaviour
{
    public delegate bool Del(Vector3 destination);

    public virtual bool Execute()
    {
        return true;
    }
}

This is supposed to be the command/action unit/item

public class GroupActionItem
    {
     public IGroupAction MyGroupAction;

     public GroupActionItem(IGroupAction.Del action)
    {
            
    }
       
    public bool PerformAction()
    {
      return MyGroupAction.Execute();
    }
}

This is the command pattern that I've completed so far

public class GroupAction
{
    public List<GroupActionItem> Actions;

    public GroupAction()
    {
        Actions = new List<GroupActionItem>();
    }
        
    public void AddAction(GroupActionItem groupActionItem)
    {
        Actions.Add(groupActionItem);
    }
        
    public void ClearActions()
    {
        Actions.Clear();
    }

    public void PerformActions()
    {
        if (Actions.Count >= 1)
        {
            if(Actions[0].PerformAction())
            {
                Actions.Remove(Actions[0]);
            }
        }
    }
}

This is where I execute the movement command

public class GroupActionMovement : IGroupAction
{
    public override bool Execute()
    {
        return Movement();
    }

    public bool Movement(Vector3 destination)
    {
        return true;
    }
}

public class Group : MonoBehaviour
{
    public GroupActionMovement MyGroupActionMovement;
}

This is the execution of the coded behavior.

public class Player : MonoBehaviour
{
    
    public Dictionary<Group,GroupAction> PlayerGroupsActions;
    public List<Group> Groups;
    
    void Start()
    {
        PlayerGroupsActions = new Dictionary<Group, GroupAction>();
        Groups = GetComponentsInChildren<Group>().ToList();
        foreach (Group group in Groups)
        {
            GroupAction playerGroupActions = new GroupAction();
            PlayerGroupsActions.Add(group,playerGroupActions);
        }
    }
    
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            //remove the foreach
            foreach (Group group in Groups)
            {
                //directly apply the group
                PlayerGroupsActions.TryGetValue(group, out GroupAction playerGroupActions);
                if (playerGroupActions != null)
                {
                    playerGroupActions.AddAction(new GroupActionItem(group.MyGroupActionMovement.Movement));
                }
            }
        }

        foreach (Group group in Groups)
        {
            PlayerGroupsActions.TryGetValue(group, out GroupAction playerFormationActions);
            if (playerFormationActions != null)
            {
                if (playerFormationActions.Actions.Count != 0)
                {
                    playerFormationActions.PerformActions();
                }
            }
        }
    }
}

I'm sorry if this isn't the best explanation of what is going on or, that a code dump is not the best way to explain what i'm doing.

Select columns by pattern and replace factor at once

I have a data frame with several columns. Some of the columns have fixed patterns at the beginning for example q1a, q1a_30, q1a_60, q1a_90. I want to call the columns with the same begging pattern and replace their factors.

Process I can do it separately, for each stage but is there any way to do it at once? Here is as far what I have done:

df[,grepl("q1a", colnames(df))]
df$q1a<- recode_factor(df$q1a, `1` = "Yes", `2` = "No",`3` = "I don't know",`4` = "Maybe")

Why does ChangeNotifierProvider exist?

According to Flutter's documentation here (https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple),

one way to control the state management is to use ChangeNotifierProvider(or InheritedWidget) when one of its descendants is a Consumer which is rebuilt when the underlying ChangeNotifier changes. Flutter's team reiterates that approach on the official youtube Flutter channel.

However, that means that some business logic element (ChangeNotifier) is now part of the Widget tree (which otherwise is all about how the UI will look like). So I don't understand why those classes (ChangeNotifierProvider,InheritedWidget,Consumer) even exist.

In particular, why isn't the following approach superior:

-Business logic is a singleton and a ChangeNotifier.

-Instead of Provider(...), for every Widget depending on the business logic simply do this:

BusinessLogicSingleton.instance.addListener(() {

      setState(() {

      });

at initState(...).

What am I missing here?

Should id field be optional or not?

For example, I have entity Person which can be obtained from DB, or inserted into DB.

class Person {
    id: number;
    name: string;
    age: number;
}

id field is autogenerated column in DB, so in situation when model is obtained from DB it will be always filled.

But when creating model, we are to set name and age fields.

So, in case, when we getting model from DB - id field is not optional and is always set. In case when we creating new model to insert into DB id field should be unset, and therefore in model definition should be optional.

Are there any best practices or common approaches to handle this problem?

Patterns for making two packages as loosely coupled as possible

So I'm learning to build a parser for a intro class for software design.

I have built a tokenizer package that splits my input string into Token objects that have getters for both the value and type. I can also return a raw String for value and type of the current token.

My public facing interface from the Tokenizer currently looks like this.

public Tokenizer(Grammar rules, String input)
public Token getCurrentToken() {...} // Token has public getters similar to the two methods below
public String getCurrentValue() {...}
public String getCurrentType() {...}
public void nextToken() throws InvalidTokenException {...}
public void previousToken() {...}

In my Parser class I also have a TokenReceiver(interface) and a TokenizerAdapter class (implements Receiver and my specific tokenizer)

  public void next();
  public Token getToken();
  public String getType();
  public String getValue();
  public Token getToken();
}

The rules are that each of the different steps in the parsing has to be done with different packages that are as loosely coupled as possible to any implementation details of the other packages, i.e. the parser should in theory work with any tokenizer I find(for example on Github), not just my own Tokenizer implementation, provided I just make an Adapter for it.

If I send back the Token objects from the Tokenizer then my parser will have to know about the Token objects (the getter methods specifically), which adds coupling to my Tokenizer implementation.

Sending back straight Strings for the value and type and then creating a another Token class in the Parser package and recreating Tokens objects feels instinctively wrong to me. Could an anonymous inner class for Token in the adapter class be a good solution?

I'm looking for what kind of patterns or concepts that can help me reference my Tokens from the Tokenizer while preserving a loose coupling to my specific tokenizer implementation.

Sorry if question is really stupid and the answer is really obvious, design patterns are still very abstract to me and we're learning about so many of them I have a hard time knowing which one to use for different circumstances.

How refactoring this function?

I need refactoring this function with SOLID or clean code or design patterns, any can help me? The switch I don't know if I can refactoring

I have created new functions for decoupling but switch loop it's driving me crazy

I added custom functions created by me, hasCorrectSugars check that number of sugars is 0,1 or 2 and checkSugars check that exists sugars...

protected function execute(InputInterface $input, OutputInterface $output): int
{
    $this->setDrinkType($input);

    if (in_array($this->drinkType, $this->allowedDrinkTypes)) {
        /**
         * Tea       --> 0.4
         * Coffee    --> 0.5
         * Chocolate --> 0.6
         */
        $money = $input->getArgument('money');
        switch ($this->drinkType) {
            case 'tea':
                if ($money < 0.4) {
                    $output->writeln('The tea costs 0.4');
                    return 0;
                }
                break;
            case 'coffee':
                if ($money < 0.5) {
                    $output->writeln('The coffee costs 0.5');
                    return 0;
                }
                break;
            case 'chocolate':
                if ($money < 0.6) {
                    $output->writeln('The chocolate costs 0.6');
                    return 0;
                }
                break;
        }
        if ($this->hasCorrectSugars($input)) {
            $this->checkSugars($input, $output);
            return 0;
        }
        $output->writeln('The number of sugars should be between 0 and 2');
        return 0;
    }
    $output->writeln('The drink type should be tea, coffee or chocolate');
    return 0;
}

    protected function hasCorrectSugars($input): bool
{
    $sugars = $input->getArgument('sugars');

    if ($sugars >= $this->minSugars && $sugars <= $this->maxSugars) {
        return true;
    }

    return false;
}

protected function checkSugars($input, $output): void
{
    $sugars = $input->getArgument('sugars');

    $output->write('You have ordered a ' . $this->drinkType);
    $this->isExtraHot($input, $output);
    $output->write(' with ' . $sugars . ' sugars');
    if ($sugars > 0) {
        $output->write(' (stick included)');
    }
    $output->writeln('');
}

Public and Private API Auth with Microservices

BACKGROUND

I am wanting to develop a public and private API from my SaaS.

The web app would be accessible via app.example.com, with the private API being located at app.example.com/api.

The plan would be to have the public API that can be used externally at api.example.com.

Also, not all features/methods/endpoints will be available between the APIs.


QUESTION

Would it be best to write 1 microservice between the APIs (e.g. just User Microservice), or write 2 microservices (e.g. App User Microservice & API User Microservice) - one for each API?

I ask this as the intent is to use sessions or JWTs for the private API, and API keys/secrets (in headers) for the public API. I am unsure if it is best to implement both auth schemes in 1 service or have 2 separate services.

In other words: should I develop 2 microservices for the same feature but with different auth requirements, or should I develop 1 microservice but make it compatible with 2 multiple schemes?


EXTRA

Just as an FYI, Nginx would be used as a reverse proxy (API Gateway). I plan to implement auth within each microservice as opposed to within an API gateway to make the system more decentralized.

Thank you for your suggestions and help.

samedi 23 octobre 2021

How to implement behaviour in multiple classes?

Suppose n classes, each one of those got the same behavior at insertion in database:

  1. create connection
  2. query definition
  3. data for query definition
  4. error handling(in case duplicated or integrity errors in database)
  5. close connection

Some of the classes don't need this implementation, others need one implementation(says insert_user implementation) and other ones need two or more implementation(insert_reasons, insert_reason_video each one of those with different query, data definition and error handling)

How can I avoid copy/paste code. I'm coding in python

class One:
    def insert_objects(self, objects=None):
        db, cursor = open_connection()
        query_insert_object = """INSERT INTO objects (name, model_id)
        VALUES (%s,(SELECT id FROM models WHERE name=%s));"""
        try:
            for object in objects:
                object_data = (object, self.name)
                cursor.execute(query_insert_object, object_data)
            db.commit()
        except IntegrityError as e:
            if e.msg == "Column 'model_id' cannot be null":
                print("model_id no ha sido insertado, inserte el modelo")
            if e.msg == "Duplicate entry 'perrito-3' for key 'name'":
                print("model.name-object.name previamente insertado para el modelo: {}".format(self.name))
            db.rollback()
        finally:
            close_connection(db, cursor)

    def insert_model(self):
        db, cursor = open_connection()
        query_insert_model = """INSERT INTO models(name) VALUES (%s);
        """
        data_model = (self.name)
        try:
            cursor.execute(query_insert_model, data_model)
            db.commit()
        except IntegrityError a e:
            print("model.name previamente insertado con valor: {}".format(self.name))
            db.rollback()
        finally:
            close_connection(db, cursor)

class Two:
    def insert_user(self):
        db, cursor = open_connection()
        query_insert_user = """INSERT INTO users (id, name) VALUES (%s,%s);"""
        data_user = (self.id, self.name)
        try:
            cursor.execute(query_insert_user, data_user)
            db.commit()
        except IntegrityError:
            print("user.id previamente insertado con valor: {}".format(self.id))
            db.rollback()
        finally:
            close_connection(db, cursor)
.
.
.
class N:
    def insert(self):
        """Generalization of above code"""
        db, cursor = open_connection()
        query = get_query()
        data = get_data()
        try:
            execute_insert()
        except:
            error_handling()
        finally:
            close_connection()

Note: I've already seen Strategy Pattern but still no found solution for multiple implementations

How to implement conditional visibility of methods in a Builder design pattern?

How to change the visibility of methods in a Builder design pattern ?

For example I have this Builder :

public class Builder {

    public Builder a() {
        //
        return this;
    }

    public Builder b() {
        //
        return this;
    }

}

User can use the API and do this :

new Builder().a().b();
new Builder().a();
new Builder().b();
new Builder().b().a();

I want to allow him to access method b() only if a() has been called :

new Builder().a().b();
new Builder().a();

A simple example could be a SQL request Builder. You shouldn't be allowed to call when() before select().

How to do so?