dimanche 30 avril 2023

How to include design patterns in a game using javafx? [closed]

I want to build a game using JavaFX, and I want to include at least three design patterns in this game. One of the design patterns should be the Bridge design pattern, and the other two should be different types of Singleton design pattern. I also want to include Multi-Threading. Can you give me some ideas?

Thoughts on how to implement JSON to XML compiler and which design patters to use

Currently I have an assignment, topic of which is "design patterns and their usage in real world applications (Java language)". My goal is to create a simple JSON to XML compiler using at least 7 design patterns. I have studied design patterns well enough to understand most of them, but when it comes to practical realization there are some troubles implementing the system.

What I tried: At first I had ideas about creating JSON structure using Composite design pattern like this: enter image description here The same structure with XML: XMLEntity, XMLObject, XMLArray. Then I would create something like XMLWriter and use State design pattern to appropriately write elements in the document. And then create a class which accepts JSONEntity and returns XMLEntity (Conversion is done using XMLWriter). But in the process I got confused by tree-like structure of the pattern and now am not sure whether it is appropriate here at all. I think both JSONEntity and XMLEntity should be represented, so that one object contains all other child objects. And when I need to convert it to JSON - the process could be recursive. But, again, I am confused whether it is possible to do so using Composite pattern.

Any ideas on where to start and which patterns to use in implementation are really welcome.

How to utilize the object updated by first child class into parent class into second child class

I have a use case related to spring applications. I have 2 child classes consider it as

@Component
public class OhioServiceCenter extends TeslaServiceCenter
@Component
public class FloridaServiceCenter extends TeslaServiceCenter

Now as we can see we have 2 child classes both of which are extending one parent abstract class. Now I have one bean which I am auto-wiring into both of the child classes which returns me an inventory, you can consider it a list of items. Let's for the sake of consideration say this bean is Tesla and have one method in Tesla called getCars this method returns me a List<Car>. Now both of the the child classes implmenting a parent abstract methods called doService both of them have different implementations. But both of them have same dependency on the List<Cars.

Now as per my usecase. I don't want both of the child classes holding the List<Cars because its a memory problem both of the child classes holding same inventory is memeory wastage.(NOTE - that getCars will return new List everytime means to say there content will be same but in memory there will be new list created everytime and that can't be changed). What I expect is that parent class should hold the inventory and then both of the child class should be able to operate over it .

APPROACHES I TRIED

  1. I tried to kept the parent class as an abstract class and have abstract method getCars which is being implemented by both the child classes. My thinking was I could autowire the Tesla object in child classes and could maintain a inventory in abstract class but the problem is for both of the child classes there are different memories are allocated for parent classes too so even if first child class could update the parent object second wont be able to access it.
  2. Also one another problem is abstract classes can't autowire things so I can't also controll the part of getting inventory directly into abstract class
  3. I tried to create parent class as a normal class but then the problem is doService can't be abstracted as java don't allows the abstract method in normal classes

PROBLEM IN SHORT SUMMARY I want 2 child classes to be able to share the same memory references of a parent class so that both the parent classes could access and update the same object in parent class.

samedi 29 avril 2023

Advice on Architectural Design for a Customizable Dashboard

Project Information

I am working on developing a highly customizable dashboard for data visualization using Angular. My plan is to use the PrimeNG framework for the overall UI and ECharts for the visualization. I also intend to use Gridster2 to handle the grid/dashboard layout. The visualizations will include text, tables, charts, and network diagrams. The data will be provided (at least for now) by a JSON file, which can contain a few hundred to about 50k rows (open in a new tab for full-res).

In the following figure, you can see a mockup for a very simple example dashboard. Dashboard Example Mockup

The next image shows sample options for a single panel of the dashboard (the menu should open when you click on the "pen button" of a panel). Here I would like to have a function to set some general settings for each panel (like font size, color, header of the panel, ...). Other settings, however, should be specific to the selected type of panel (= type of visualization), such as the column width of a table or the labeling of the axes for xy-plots (open in a new tab for full-res).

Panel Settings Mockup

Ideally, the dashboard should act as a quick overview. Clicking on the "Enlarge" button should open a popup that shows the same visualization in full-screen and with more details. I'm not sure if the information is relevant for the architecture, but rather too much than too little info :)

Questions to Consider

I have a few questions about the general architectural structure of the dashboard and best practices.

  1. What would you guys choose for the dashboard architecture?
  2. How would you guys enable support for adding additional visualization methods without much effort in the future?
  3. What would be your approach to implementing the settings: Some settings should be available for all panel types, and others specific to each panel type?

My thoughts towards the Questions

I've been thinking about these questions myself for quite a while, and here are my thoughts and approaches so far:

  1. Using the Model-View-Controller (MVC) architecture for the parent dashboard architecture. The "model " would be implemented with a Redux store to maintain a consistent state across all panels. The "view" would be implemented through the diverse panels. The "controller" would be implemented by the dashboard, which mediates between the model and the panels, and processes and delegates user input, ...

  2. Using the plugin architecture to enable extensibility in the future. For this, there could be a "PanelCore" that does common things like rendering, setting options, updating, and triggering events, ... For each visualization method (such as table, chart, ...) a single "plugin" (a separate class extending the corresponding API) would then be developed. In such a plugin I would implement the necessary functions like "initialize", "update", "render", "onHover", ... implement. The various plugins could then be managed by a plugin manager of the dashboard controller (see MCV).

  3. I am not sure what would be a good approach for implementing the options properly. I was thinking of a modular architecture in combination with the builder pattern so that you can easily reuse existing options for multiple "plugins" (visualization methods). But I have a feeling that there is a more elegant solution that fits well with the plugin architecture mentioned in point 2.

In case you need more information, I will of course provide it immediately! Otherwise, I would really appreciate your suggestions and ideas so that I can implement the most maintainable and reusable dashboard design possible. So far, I haven't found much information on the internet about how to build a dashboard properly from a computer science and software architecture point of view.

Thank you!

please help me to make a hourglass pattern

please help me to make a hourglass pattern using python, with output result same like this:

 1 2 3 4 5
  * * * *
   A B C
    6 7
     *
    D E
  8 9 10
 * * * *
F G H I J

im done tried it for over 2 hours and still didnt get the pattern enter image description here

i'm done tried over 2 hours and still didnt get the pattern

How come design patterns followed by JDBC API and JPA are different?

I was trying to understand the design patterns and their implementation within the Java library itslef:

I am bit confused when it comes to these two APIs:

  1. JDBC API: This API is said to implement Bridge design pattern.

Bridge pattern is a structural design pattern in software development that is used to decouple an abstraction from its implementation so that both can be modified independently. And if we stick to specification, we can easily replace one implementation with another.

  1. JPA: This API is said to implement ORM/Factory (EntityManagerFactory) design pattern.

As far as I know, if we stick to JPA specification then we can easily replace one implementation (ex. Hibernate) with another (ex. EclipseLink). Which means API and implementation can be developed independently.

So can someone please tell me why not JPA is also called to implement Bridge design pattern?

vendredi 28 avril 2023

Python object factory repeats constructor arguments multiple times

In writing a python object factory, I'm running into a lot of parameter repetition in the constructors. It feels wrong, like there is a better way to use this pattern. I'm not sure if I should be replacing the parameters with **kwargs or if there is a different design pattern that is more suited to this sort of case.

A simplified example is below. The real code is of course more complicated and you can see more reasons why I'd do it this way, but I think this is a reasonable Minimal Reproducible Example

External to these classes, for the API, the most important factors are species and subspecies. It happens to be that internally, is_salt_water is important and results in a different object, but that's an internal matter.


class Fish:
    def __init__(self, species, sub_species, length, weight):    # Repeating this a lot
        self.species = species
        self.sub_species = sub_species
        self.length = length
        self.weight = weight
        self.buoyancy = self.buoyancy()

    def buoyancy(self):
        raise Exception("Do not call this abstract base class directly")


class FreshWaterFish:
    def __init__(self, species, sub_species, length, weight):    # Repeating this a lot
        self.fresh_water = True
        super().__init__(species, sub_species, length, weight)   # Repeating this a lot
    def buoyancy(self):
        self.buoyancy = 3.2 * self.weight   #totally made-up example. No real-world meaning


class SaltWaterFish:
    def __init__(self, species, sub_species, length, weight):    # Repeating this a lot
        self.fresh_water = False
        super().__init__(species, sub_species, length, weight)   # Repeating this a lot

    def buoyancy(self):
        self.buoyancy = 1.25 * self.weight / self.length  #totally made-up example. No real-world meaning

def FishFactory(self, species, sub_species, length, weight, is_salt_water = False): # Repeating this a lot
    mapper = {True : FreshWaterFish, False: SaltWaterFish}
    return mapper[is_salt_water](species, sub_species, length, weight) # Repeating this a lot

Design patterns in an email client

Which and where can be used design patterns in an basic email client ? I'm currently fetching emails through POP3 and IMAP protocols, also send it using SMTP.

To build a response from email server I used builder patterns.

alluvial filled with pattern

I have the following sankey plot, and I'd like to fill the bars with patterns, instead of different colors.

enter image description here

based on a df reproducible with the following code:

data<- data.frame("ID"=rep(c(1:20),2), "time"=c(rep(1,20),rep(2,20)), "value"=c("B","G","B","G","B",rep("G",3),rep("B",2),"G",rep("B",3),"G",rep("B",6),"G","B","G","B",rep("G",3),rep("B",2),"G",rep("B",3),"G","B","switch",rep("B",2),"switch"))

Here the code for the sankey:

library(dplyr)
library(ggplot2)
library(ggalluvial)
library(ggpattern)

data %>% 
  group_by(time) %>% 
  mutate(w = n()) %>% 
  ggplot(aes(x = time, stratum = value, alluvium = ID,
             fill = value, label = value, y = 1/w)) +
  scale_x_discrete() +
  scale_y_continuous(name = "", label = scales::percent_format(accuracy = 1)) +
  geom_flow(stat = "flow", knot.pos = 1/4, aes.flow = "forward") +
  geom_stratum() +
  theme(legend.position = "bottom") +
  labs(x = "", fill = "")

I'd like to fill the bars with patterns, instead of different colors.

I tried with scale_pattern_type_manual(values=c('stripe', 'wave', 'wave', "crosshatch", "none","stripe", "crosshatch","none")) but it does not work.

Injecting and mocking helper classes vs. actual functionality?

I have a helper class FooItem that acts as a facade for another class Foo. I'm now creating another class Bar which internally uses FooItem to do its Foo related actions.

Since FooItem is a facade, my initial thought is to neither inject it in Bar, nor mock during testing, and instead, when testing Bar, assert against Foo directly. The idea is that FooItem is inconsequential to what Bar should be doing with Foo.

Is this approach better than injecting a FooItem into Bar and also asserting on its methods instead of Foo? It's tested itself, so technically asserting against it should be safe.

Some thoughts:

  • If asserting on FooItem in Bar, if it breaks in the future, Bar's tests will fail as collateral.
  • Asserting on a facade or helper feels intuitively wrong since it feels most like an internal implementation detail that should be inconsequential to the actual goal target, which is communicating with Foo.
  • In the future, if I use another utility instead of FooItem or directly act on Foo instead, the tests would be remain the same if I dont assert on FooItem.

This might actually be two separate discussions, one about injecting FooItem into Bar when instantiating it and another about asserting against Foo or FooItem in Bar's tests.

jeudi 27 avril 2023

How to implement the Builder Design Pattern with the use of smart pointers?

I want to implement the builder pattern in C++ for a project that I am working on. I have found plenty of examples of this design pattern that uses raw pointers, but none that uses smart pointers. Since my opinion is that smart pointers are the way to go when writing modern C++ code, I wonder how the builder pattern can be implemented with the use of smart pointers for the director, builder, product et cetera.

I use the conceptual example code of Refactoring.Guru for the C++ builder design pattern as reference: https://refactoring.guru/design-patterns/builder/cpp/example.

How can I transform this conceptual example into a modern C++ builder pattern with the usage of smart pointers? I understand that where raw pointers are present, you can replace them with smart pointers, but i am mostly struggling with where to use unique pointers and shared pointers and how to pass them from function to function. Do I use unique pointers and just move them in every function call or do I use shared pointers in the case of the product for example?

It's a shame Refactoring.Guru does not include such a version of this example.

Thanks in advance.

How to add methods dynamically to an instance of SQLModel class

I am trying to add functionality for conversion of timeseries data from one format to another based on the value type of the Element object, here, I am abstracting all that and just trying to print the type of conversion, I'd like to modify the Element class such that methods could be added dynamically based on the value type of an Element instance during the object instanciation. assuming all conversions are possible except to itself, I created a functions mapper dictionary to index search the respective function and add it using the setattr method, instead of using a mapper for functions, it seemed better to directly set the functions using types.MethodType(locals()[f"{self.value_type}_{conversion_method}"], self), in both cases, the code raises no errors but also doesn't add the methods as I wanted to, wondering where am I going wrong here.

from uuid import UUID, uuid4
from sqlmodel import Field, SQLModel


def a_to_b_function():
    print("A to B")


def a_to_c_function():
    print("A to C")


def b_to_a_function():
    print("B to A")


def b_to_c_function():
    print("B to C")


def c_to_a_function():
    print("C to A")


def c_to_b_function():
    print("C to B")


VALUE_TYPE_CONVERSION_MAPPER = {
    "A_to_B": a_to_b_function,
    "A_to_C": a_to_c_function,
    "B_to_A": b_to_a_function,
    "B_to_C": b_to_c_function,
    "C_to_A": c_to_a_function,
    "C_to_B": c_to_b_function,
}


class AllBase(SQLModel):
    id: UUID = Field(default_factory=uuid4, primary_key=True)


class Element(AllBase, table=True):
    """
    interacts with elements table
    """


    value_type: str = Field(default=None)  # A, B, C - possible values

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        all_types = [
            "A",
            "B",
            "C",
        ]
        for value_type in all_types:
            if value_type != self.value_type:
                conversion_method = f"to_{value_type}"
                setattr(
                    self,
                    conversion_method,
                    VALUE_TYPE_CONVERSION_MAPPER[
                        f"{self.value_type}_{conversion_method}"
                    ]
                    # types.MethodType(locals()[f"{self.value_type}_{conversion_method}"], self),
                )

Semi-circle diagram

I want to create a semi-circle diagram something like this: Semi-circle diagram.

But can't make it proper work dynamically. I want to use TextView, but can't make it exactly as it is in the photo.
This is what I've tried, but it's now wanted I want. And I don't have any solutions. Do you think you have some resources or code improvements for me?

val numViews = 8
        for (i in 0 until numViews) {
            // Create some quick TextViews that can be placed.
            val v = TextView(requireContext())
            // Set a text and center it in each view.
            v.text = "View $i"
            v.gravity = Gravity.CENTER
            v.setBackgroundColor(-0x10000)
            // Force the views to a nice size (150x100 px) that fits my display.
            // This should of course be done in a display size independent way.
            val lp = FrameLayout.LayoutParams(150, 250)
            // Place all views in the center of the layout. We'll transform them
            // away from there in the code below.
            lp.gravity = Gravity.CENTER
            // Set layout params on view.
            v.layoutParams = lp

            // Calculate the angle of the current view. Adjust by 90 degrees to
            // get View 0 at the top. We need the angle in degrees and radians.
            val angleDeg = i * 200.0f / numViews - 160.0f
            val angleRad = (angleDeg * Math.PI / 180.0f).toFloat()
            // Calculate the position of the view, offset from center (300 px from
            // center). Again, this should be done in a display size independent way.
            v.translationX = 300 * Math.cos(angleRad.toDouble()).toFloat()
            v.translationY = 300 * Math.sin(angleRad.toDouble()).toFloat()
            // Set the rotation of the view.
            v.rotation = angleDeg + 90.0f
            mBinding.main?.addView(v)
        }

mardi 25 avril 2023

Iterator design pattern using unique_ptr instead of raw ptr

I've got this fairly simple C++ code from refactoring.guru. It compiles and works as expected. However, it uses new and delete via the CreateIterator() member function, and I'd like to port it to use unique_ptr, but I'm not sure how to do that exactly.

I've created a CreateIterator2() function using unique_ptr, which compiles (I think this is what I want), but not if I invoke it, so I commented out the invocation.

I'm not sure what I am missing to return a smart pointer and avoid using raw new/delete.

// refactoring.guru c++ design patterns
#include <iostream>
#include <string>
#include <vector>
#include <memory>

template<typename T, typename U>
class Iterator {
public:
    typedef typename std::vector<T>::iterator iter_type;

    Iterator(U* p_data, bool reverse = false) : m_p_data_(p_data) {
        m_it_ = m_p_data_->m_data_.begin();
    }

    void First() {
        m_it_ = m_p_data_->m_data_.begin();
    }

    void Next() {
        m_it_++;
    }

    bool IsDone() {
        return (m_it_ == m_p_data_->m_data_.end());
    }

    iter_type Current() {
        return m_it_;
    }

private:
    U* m_p_data_;
    iter_type m_it_;
};

template<class T>
class Container {
    friend class Iterator<T, Container>;

public:
    void Add(T a) {
        m_data_.push_back(a);
    }

    Iterator<T, Container>* CreateIterator() {
        // want to avoid this
        return new Iterator<T, Container>(this);
    }

    //think this is what I want  - compiles
    std::unique_ptr<Iterator<T, Container>> CreateIterator2() {
        return std::unique_ptr<Iterator<T, Container>>(this);
    }

private:
    std::vector<T> m_data_;
};

class Data {
public:
    Data(int a = 0) : m_data_(a) {}

    void set_data(int a) {
        m_data_ = a;
    }

    int data() {
        return m_data_;
}

private:
    int m_data_;
};

void ClientCode() {
    std::cout << "________________Iterator with int______________________________________" <<        std::endl;
    Container<int> cont;

    for (int i = 0; i < 10; i++) {
        cont.Add(i);
    }

    Iterator<int, Container<int>>* it = cont.CreateIterator();
    for (it->First(); !it->IsDone(); it->Next()) {
        std::cout << *it->Current() << std::endl;
    }

    //THIS DOESN"T COMPILE
    //std::unique_ptr<Iterator<int, Container<int>> it = cont.CreateIterator2();
    //for (it->First(); !it->IsDone(); it->Next()) {
    //    std::cout << *it->Current() << std::endl;
    //}


    Container<Data> cont2;
    Data a(100), b(1000), c(10000);
    cont2.Add(a);
    cont2.Add(b);
    cont2.Add(c);

    std::cout << "________________Iterator with custom Class______________________________" << std::endl;
    Iterator<Data, Container<Data>>* it2 = cont2.CreateIterator();
    for (it2->First(); !it2->IsDone(); it2->Next()) {
    std::cout << it2->Current()->data() << std::endl;
    }
    //avoid this
    delete it;
    delete it2;
}

int main() {
    ClientCode();
    return 0;
}

Design Architecture

Further, I have a query regarding design

Problem Statement:-

I have subcategories defined under Vehicle Class as :- Bike ,Car, truck, bus

Further, there are different variants under each four categories

Bike :- sport, standard Car :- sport, standard, electric Truck :- Mini Truck , Power Truck Bus:- Mini Bus, AC Bus

I have to calculate the price based on variants. For example Mini Bus price.

Question:- How should I define the classes ?

  1. Keep only vehicle as a class .
  2. Keep Vehicle as a base class and make bike, car, truck , bus as subclasses and they should inherit the base class.
  3. make sports bike as class which will inherit bike class which will further inherit vehicle class

What is the best possible solution following OOPS and Solid.

Prioritize one endpoint in terms of compute in FastAPI web server

We have a FastAPI based web server serving an ML model. There are two endpoint in this app: /client and /internal

We use /internal endpoint to encode millions of documents in batches for our own internal usage. And the /client endpoint is exposed to clients where they can request to encode their documents and it is always just one document per request.

There could be situations where we hit the internal endpoint with request to encode millions of documents and then the client hits the client endpoint to encode their one document.

Naturally we want to prioritize clients requests so that the client should not have to wait until our millions of documents are encoded.

What are the best strategies to accomplish this within a given framework of FastAPI + python. How can I prioritize clients requests to serve them faster?

I have come up with the following ideas:

  1. Just spin up another instance of the web server on a different port to serve clients requests - this is the easiest solution to implement;
  2. Isolate one gunicorn worker for the /client endpoint - I'm not even sure if this is possible?;
  3. Refactor the web server with Producer/Consumer pattern implementing a priority queue. This is doable but probably will take a lot of time and research on how to implement this.

lundi 24 avril 2023

Qt Best Practices with Widgets & UI forms

This is my first time using Qt, and also my first time using it for a relatively serious project. I understand that writing Qt code is a bit different from writing plain C++ due to the nature of the problem space. I believe I have a good grasp of signals & slots and general library, as well as QtCreator. I've reviewed a number of tutorials, documentations, and GitHub projects with no clear answer to my question, at least without digging into one of said projects (which are quite large and therefore hard to question code design use cases), assuming they are well designed.

My question is how to widgets are modularized (and ui forms, presumably) into their own files; I am aware that a ui_mainwindow.h file is generated from mainwindow.ui, and contains the (global) widget objects/variables which you can access from MainWindow.cpp, however I am at a bit of a loss as to how to you would go about putting those widget objects into their own files and/or classes, therefore encapsulating them e.g.:

MainWindow.cpp
MainWindow.h
Button.cpp
Button.hpp
Search.cpp
Search.hpp
ListView.cpp
ListView.hpp

There is the option of creating everything programmatically which I have seen projects do; RPCS3 by contrast only seems to use new ui forms for separate pages/menus. I would however like to keep presentation and logic separate, but am not sure how to go about it without having a single bloated MainWindow.cpp file.

Design pattern for output string lookup [closed]

Suppose I have a program which is based around decrypting blobs to human readable format. I face the issue when each developer describes decrypted blob content as they understand it. Same applies to logging and error messaging.

So I want to unify language our app uses. Preferably in a way which allows me to give some files to support/ui guys/etc. so that they define what they wanna see.

I need to unify

  1. Error messages
  2. Logs
  3. Other user output including enum-to-string and bitfield/struct-to-strings kind of decryption.

I was thinking at some point of getting away with just a couple of maps, but I was wondering if there’s some good design patterns for that.

Are there design patterns for multi dimensional lookups?

I am looking to see if there is a general design pattern or strategy to handle a use case I see often in our codebases. My best attempt to generalize this use case is "Map permutations of n parameters to a specific value, and look up the appropriate value when provided those parameters."

Due to high cardinality of some parameters we prefer not to spell out every single permutation of parameters with a massive truth table. In fact, we often have negation configuration (e.g. return value ABC when parameters are NOT permutation XYZ) to avoid such a massive truth table. Parameters can be optional during lookup. Also, sometimes we add new parameters.

For example - imagine you want to store a "support phone number" value for your store's customers. This is influenced by their country of residence, average spend, and primary language. With 100 supported countries, 3 spend categories, and 15 supported languages, we would have to enumerate 100x3x15=4500 entries in this truth table to fully capture all permutations. In our real use case we see far more permutations than 4500 but this gives you an idea.

In reality, rules exist like "always use phone number 555 555 5555 if language is French", or "in Canada it is illegal to provide different services based on annual spend, so spend will not change the phone number provided". We take advantage of these rules to short-circuit lookups and avoid having to create a massive 4500 entry truth table.

In our code we accomplish configuration storage and look-ups like this with disparate JSON schemas and custom code for each instance. Is there a more general pattern/tool to handle this flow?

Factory method in dynamic library with explicitly instantiated templated classes

This is a follow up question to the one placed in Factory method does not work when used in dynamic library with templated classes.

To keep to post shorter I have placed the code in: https://godbolt.org/z/ab8Ys8dKe

I am compiling the code with g++ -g -fPIC Base.cpp Derived.cpp factory.cpp -shared -o test.so to create the dynamic library and then linkin it with: g++ -g -o main main.cpp -I . -L. test.so but I am getting an error: /main: error while loading shared libraries: test.so: cannot open shared object file: No such file or directory

How can I link the library correctly?

In NestJS why does the `service` layer seems entangled with the `module` instead of been agnostic?

Context:

I'm researching NestJS as our next framework to use for our greenfield projects and this will be my first time working with it. Even though NextJS is new to me I'm not new to rest API development in multiple platform, framewosk & languages and I've seen from having frameworks very strict like NestJS where you have your model-view-controller pattern to very loose frameworks that without best practices and patterns it's like the wild west. I'm strong on development patterns specially the ones that makes our developers life easier and more productive. Meaning that I rather have a good pattern in-place with a framework that works for us rather than a so called "better" framework that we have to work for the framework.

Questions:

  1. Why does the service layer which I have considered to be agnostic to the controller and the framework should be Injectable in nature and the usual pattern that I see online is having the service within the module file structure? Should it be in theory it's own thing?

  2. If that is the right way the what is the purpose of creating the service layer on top of an already layer of controller abstraction under the module?

To be clear I'm not questioning the need of the service layer but I'm questioning the entanglement of the service layer to the framework. Otherwise the nestjs service layer would be just some sort of façade to the actual service layer that contains the logic.

Your guidance will be highly appreciated it!

My understanding of the pattern:

(please correct me if I'm wrong)
Layer Description
Controller Knows about the framework (nestjs, koa, express) and transforms whatever comes from the framework into something that the service layer understands.
Service Has the actual logic which is agnostic to the framework and the controller. In theory you could extract the layer entirely out into it's separate package and/or could be used by a different controller that might using a different framework and it should work just fine not knowing the difference.

I've tried going through NestJS examples and looking and searching for nestjs best practices. I was expecting a clear consistent pattern across the board that fulfills the mode-view-controller-service pattern.

dimanche 23 avril 2023

Factory method does not work when used in dynamic library with templated classes [duplicate]

I have created a templated class where I would like to use the factory method. The templates should be explicitly defined to create objects of type int, double and bool.

The factory has a checkIn registry mechanism through the use of the a static bool.

The factory is defined as:

#ifndef Factory_H
#define Factory_H

#include <memory> 
#include <map>

template<class Type> 
class Base;

template<class Type> 
class Factory
{
    public:
        using createObj = std::shared_ptr<Base<Type>>(*)();

        static bool registerObj( const std::string& name, createObj type)
        {
            std::map< std::string, Factory::createObj >& registry = getRegistry();

            if(registry.find(name) == registry.end())
            { 
                registry[name] = type;
                return true;
            }
            return false;
        };

        static std::shared_ptr<Base<Type>> New( const std::string& name)
        {
            auto it = getRegistry().find(name);
            if (it == getRegistry().end()) {
                return nullptr;
            }
            return it->second();
        };
        
    private:
        static std::map<std::string, createObj>& getRegistry()
        {
            static std::map<std::string, Factory::createObj> registry;
            return registry;
        };        
};

#endif

The base class is defined as:

#ifndef Base_H
#define Base_H

#include "factory.h"

template<class Type>
class Base: public Factory<Type>
{
    public:
        Base();
        virtual void foo() = 0;
};

#endif

and implemented as:

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

template <class Type>
Base<Type>::Base()
{}

// Explicit initalization
template class Base<int>;
template class Base<double>;
template class Base<bool>;

The derived class is defined as:

#ifndef Derived_H
#define Derived_H

#include "Base.h"

template<class Type>
class Derived: public Base<Type>
{
    private:
        static bool checkIn_;
        static std::string className_;

    public:
        Derived();
        virtual void foo() ;
        static std::shared_ptr<Base<Type>> Create();

};
#endif

and implemented as:

#include "Derived.h"

template<class Type>
Derived<Type>::Derived()
{}

template<class Type>
std::string Derived<Type>::className_("Derived");

template<class Type>
std::shared_ptr<Base<Type>> Derived<Type>::Create()
{
    return std::make_shared<Derived>();
}


template<class Type>
bool Derived<Type>::checkIn_ = Base<Type>::registerObj(Derived::className_, Derived::Create);

template<class Type>
void Derived<Type>::foo()
{
    std::cout << typeid(Type).name() << std::endl;
}

// Explicit initalization
template class Derived<int>;
template class Derived<double>;
template class Derived<bool>;

The main.cpp is defined as:

#include<iostream>
#include "Derived.h"
#include "Base.h"

int main()
{
    auto obj1 = Base<int>::New("Derived");
    auto obj2 = Base<double>::New("Derived");
    auto obj3 = Base<bool>::New("Derived");

    obj1->foo();
    obj2->foo();
    obj3->foo();

    return 0;
}

If I compile everything in one executable: g++ -g *.cpp -o main. The factory method works.

If I try to compile it as a library; g++ -g -fPIC Base.cpp Derived.cpp -shared -o test.so followed by g++ -g -o main main.cpp -I . -L. test.so it no longer works. There is nothing in the registry... I would guess the static bool is not doing its job.

How can I make this work?

Is using shared mutable state ok for small functionality

Recently I am working on a feature that let's a user change his data, so I keep a copy of all his changes until user presses "Save" and then that copy is persisted. It looks something like this:

const initialData = {email: "something@gmail.com", firstName: "John", lastName: "Smith"}
const currentData = {email: "something@gmail.com", firstName: "James", lastName: "Smith"}

In this example user just decided to change his first name.

I need to have this information about current data in two places:

  1. In Save callback, so that when user presses Save button it is persisted
  2. In "UpdateUI" functionality so that change can be visible in the UI, and to change "currentData" value on input change.

Doing this requires to have some shared state where both "Save" and "UpdateUI" can have access to the current and latest of user changes.

Since I read a lot about how shared mutable state is root of all evil, I was wondering is using shared state for such small functionality alright, or is there some better way?

samedi 22 avril 2023

I'm looking to know if I am implementing the Proxy Pattern correctly

I am currently working hard to improve my code quality & apply design patterns. Today was dedicated to the Proxy Pattern.

My goal was to let a AuthService class act as a manager for any authentification service I may use in the future.

The user should be able to instantiate any service's class as a parameter to AuthService, so that there'd be no hassle when the need to change the service arises: all you'd need is to update the parameter.

For that purpose, I created an AuthInterface interface in Typescript which would be implemented by the AuthService manager componement & the actual services modules. I tried very hard to respect the SOLID principles by using dependency injection instead of using external code.

This being said, I am unsure if this design is an actual implementation of the Proxy pattern, or if I turned it into an anti-pattern by adding too much complexity.

Please find the code below:

// The interface for AuthService & any auth module

interface AuthInterface<ServiceType, UserType> {
  init(initCallback?: () => ServiceType): ServiceType;
  signIn(
    authProvider?: ServiceType,
    signIncallback?: (authProvider?: ServiceType) => boolean | never | object
  ): boolean;
  getID(
    authProvider?: ServiceType,
    getIDCallback?: (authProvider?: ServiceType) => UserType
  ): UserType;
}

// The AuthService component which takes any authentification module. Is this the Proxy pattern?

class AuthService<ServiceType, UserType>
  implements AuthInterface<ServiceType, UserType>
{
  SomeService;
  constructor(SomeService: AuthInterface<ServiceType, UserType>) {
    this.SomeService = SomeService;
  }

  init(initCallback: () => ServiceType) {
    return this.SomeService.init(initCallback);
  }

  signIn(
    authProvider: ServiceType,
    signIncallback: (authProvider?: ServiceType) => boolean | never
  ) {
    return this.SomeService.signIn(authProvider, signIncallback);
  }

  getID(
    authProvider: ServiceType,
    getIDCallback: (authProvider?: ServiceType) => UserType
  ) {
    return this.SomeService.getID(authProvider, getIDCallback);
  }
}

// An authentification module, here Firebase, to add as a parameter to AuthService

class FirebaseAuth<ServiceType, UserType>
  implements AuthInterface<ServiceType, UserType>
{
  init(initCallback: () => ServiceType) {
    return initCallback();
  }

  signIn(
    authProvider: ServiceType,
    signIncallback: (authProvider?: ServiceType) => boolean | never
  ) {
    return signIncallback(authProvider);
  }

  getID(
    authProvider: ServiceType,
    getIDCallback: (authProvider?: ServiceType) => UserType
  ) {
    return getIDCallback(authProvider);
  }
}

I am new to Typescript, so please do not hesitate to tell me where the code can be improved.

I would be very grateful for any clarification. Thank you!

jeudi 20 avril 2023

What kind of design pattern follow php? [closed]

Interviewer asking many times what kind of design pattern use in php. I have searched in google also but I didn't get any relevant answer.

So, kindly suggest me a better way or tell me the actually what wants listening the interviewer.

mercredi 19 avril 2023

How can I better organize my java classes to use delegation, without the tedium?

I have a Java project where one overwhelmingly large class had been split up into smaller classes, entirely because of readability reasons. Guice dependency injection is used.

public interface FooDataService { Foo getFoo(){} }
public class FooDataServiceImpl { @Override Foo getFoo(){} }
// Also BarDataService, BazDataService, and more


public interface DataService extends FooDataService, BarDataService {}
public class DataServiceImpl implements DataService {
    private final FooDataService fooDataService;
    private final BarDataService barDataService;
    // ...

    @Inject
    public DataServiceImpl(FooDataService fooDataService, BarDataService barDataService) {
        this.fooDataService = fooDataService;
        this.barDataService = barDataService;
        // ...
    }
    
    @Override Foo getFoo(){ return fooDataService.getFoo(); }
    @Override Bar getBar(){ return barDataService.getBar(); }
    // A very large number of methods follow.
}


// Usage
public class ApiService {
    // The idea was to only inject the one dataService variable instead of injecting FooService, BarService, etc.
    // There's not really place where FooDataService is used but not BarDataService, except unit tests
    @Inject
    private final static DataService dataService;

    public void doThing() {
      dataService.getFoo();
      dataService.getBar();
    }
}

This is mostly fine since it keeps all the XDataService classes relatively small. DataServiceImpl itself used to be 2000+ lines long. But it's getting a little tiresome.

  1. As we add more methods, DataServiceImpl is now 600 lines long and it's hard to find where any method is in the file. DataServiceImpl also gets merge conflicts quite frequently now as multiple devs are adding functionality to it.
  2. If we need to add a new method to FooDataService or change a function signature, we have to do it in 4 places, which is annoying.
  3. Occasionally, FooDataService would need to call a method in BarDataService, which breaks the nice separation of duty we had between the classes.

Is there a better way to go about it so that we can have small, readable classes?

I wrote a class with "init" method. Should I call it from other class methods? Or leave it to the object user? (Code Design) [closed]

I have a java class with an init method. It's different from the constructor. The constructor just initializes the variables/fields. The init method connects to a database and performs some verifications on the database + it kick starts a background thread which handles incoming requests.

If you wanna think of it in pseudo-code:

class SomeService:

    ...
    queue
    other fields
    ...

    public SomeService(Constructor input):
        initializes fields...

    public void init():
        connect to database and verify certain existence of a table
        start a thread
        initialized = true

    public String doSomething(Some Input):
        if !initialized: throw exception
        add job to queue to be picked up by the running thread

    public Integer doSomethingElse(Some Other Input):
        if !initialized: throw exception
        add job to queue to be picked up by the running thread


My question is, is it better to force the object user to call init before using the class methods? If you check the code above, any method will throw exception if it's called before init.

Benefits:

  • This provides separation of concerns -- a method is only responsible of doing its job.

Downside:

  • This, however, makes a bad class usability: what if init failed? the object user will always has to handle this. And might even try to call init before every other class method call.

The other option is call init at the beginning of every class method, internally.

Benefits:

  • The class user doesn't need to worry about anything but getting his services done by the object.

Downside:

  • Now a method isn't as good in terms of separation of concerns. It does its job after it tries to initialize the object.

Please note that the initialization procedure is a must before any other method does its job. Other methods won't be functional unless the object is initialized by calling init.

I believe it's obvious why I separated init from the constructor:

  1. It's perfectly fine to have the object without it being initialized, and leave initialization for later.
  2. A constructor shouldn't take long for initialization, which isn't the case. Connection to database, running multiple statements, and starting a thread. This isn't as snappy as just setting fields values.
  3. If connection to database failed in a constructor, this will result in no object creation. This is bad behavior because the database can be available some other time after trial of object instantiation.

What I did is:

  • Called init at the beginning of every method. To get the benefit of that.
  • Availed init as public method to permit object caller for eager initialization.

So, what is it do you think is better? Call init at the beginning of every method? Leave it completely for the object user to handle it?

I tried to look it up but didn't find a fruitful answer.

I also tried to find in java 8 standard library if any class has init method, but couldn't find any. However, I found in java extension, Cipher class, which has init. and it works like approach#1 (leave it to the caller). That being said, this makes sense because its init takes user input, while mine doesn't.

I asked a chatgpt based bot and I got an answer that I should go with approach#2, calling init at the beginning of every method.

Python code patterns: elegant way of trying different methods until one suceeds?

I'm trying to extract informations from an HTML page, like its last modification date, in a context where there are more than one way of declaring it, and those ways use non-uniform data (meaning a simple loop over fetched data is not possible).

The ugly task is as follow:

def get_date(html):
  date = None
  # Approach 1
  time_tag = html.find("time", {"datetime": True})
  if time_tag:
    date = time_tag["datetime"]
  if date:
    return date

  # Approach 2
  mod_tag = html.find("meta", {"property": "article:modified_time", "content": True})
  if mod_tag:
    date = mod_tag["content"]
  if date:
    return date
  
  # Approach n
  # ...

  return date

I wonder if Python doesn't have some concise and elegant way of achieving this through a `while" logic, in order to run fast, be legible and maintenance-friendly:

def method_1(html):
  test = html.find("time", {"datetime": True})
  return test["datetime"] if test else None

def method_2(html):
  test = html.find("meta", {"property": "article:modified_time", "content": True})
  return test["content"] if test else None

...

def get_date(html):
  date = None
  bag_of_methods = [method_1, method_2, ...]

  i = 0
  while not date and i < len(bag_of_methods):
    date = bag_of_methods[i](html)
    i += 1

  return date

I can make that work right now by turning each approach from the first snippet in a function, append all functions to the bag_of_methods iterable and run them all until one works.

However, those functions would be 2 lines each and will not be reused later in the program, so it just seems like it's adding more lines of code and polluting the namespace for nothing.

Is there a better way of doing this ?

Visitor pattern without double dispatch

Recently I ran across a code snippet that demonstrated a modified visitor pattern without double dispatch.

They used the run time class to compose the visit function name, which allowed them to move the accept function to the base class of the data classes, and then later to replace it completely by adding a generic visit function in the visitor.

I suppose the same thing could be done in Java and C# using reflection.

What are the advantages and disadvantages of such an approach?

"""Example of a modified visitor design pattern using runtime info instead of double dispatch"""
from __future__ import annotations # enable postponed evaluation for cyclic reference classes
from abc import ABC
from abc import abstractmethod
from typing import List

class CursorVisitor(ABC):
    def visit(self, cursor: ICursor) -> None:
        visit_func_name = f"visit_{type(cursor).__name__}"
        visit_func = getattr(self, visit_func_name)
        visit_func(cursor)        
    @abstractmethod
    def visit_Cursor2D(self, cursor: Cursor2D) -> None:
        pass
    @abstractmethod
    def visit_Cursor3D(self, cursor: Cursor3D) -> None:
        pass

class ICursor(ABC):
    @abstractmethod
    def print(self) -> None:
        pass

class Cursor2D(ICursor):
    def __init__(self, x: int, y: int) -> None:
        self._x = x
        self._y = y
    def move(self, dx: int, dy: int) -> None:
        self._x += dx
        self._y += dy
    def print(self) -> None:
        print("Cursor2D(", self._x, ",", self._y, ")")

class Cursor3D(ICursor):
    def __init__(self, x: int, y: int, z:int) -> None:
        self._x = x
        self._y = y
        self._z = z
    def move(self, dx: int, dy: int, dz: int) -> None:
        self._x += dx
        self._y += dy
        self._z += dz
    def print(self) -> None:
        print("Cursor3D(", self._x, ",", self._y, ",", self._z,")")

class CursorMoveVisitor(CursorVisitor):
    def __init__(self, dx: int, dy: int, dz: int) -> None:
        self._dx = dx
        self._dy = dy
        self._dz = dz
    def visit_Cursor2D(self, cursor: Cursor2D) -> None:
        cursor.move(self._dx, self._dy)
    def visit_Cursor3D(self, cursor: Cursor3D) -> None:
        cursor.move(self._dx, self._dy, self._dz)

class CursorPrintVisitor(CursorVisitor):
    def visit_Cursor2D(self, cursor: Cursor2D) -> None:
        cursor.print()
    def visit_Cursor3D(self, cursor: Cursor3D) -> None:
        cursor.print()

def demo_use_of_visitor():
    cursor_list: List[ICursor] = []
    cursor_list.append(Cursor2D(5,5))
    cursor_list.append(Cursor3D(6,6,7))
    for cursor in cursor_list:
        move_visitor:CursorMoveVisitor = CursorMoveVisitor(1,1,1)
        move_visitor.visit(cursor)
        print_visitor:CursorPrintVisitor = CursorPrintVisitor()
        print_visitor.visit(cursor)



demo_use_of_visitor()

How can Proxy and Facade design patterns be combined?

I have a third party library class Lib and an own LibProxy where LibProxy adds some caching before passign the control to Lib. This would have been textbook Proxy, but LibProxy also simplifies the interface to Lib. Which also makes it a Facade.

What is the course of action here? Making LibProxy comply to the interface of Lib and adding a separate LibFacade feels like overkill. This is what it would look like: Client->LibFacade->LibProxy->Lib.

Can I call it LibProxyFacade instead? Or is there some other pattern that is equivalent to the Proxy/Facade combination?

mardi 18 avril 2023

Storing and Retrieving state changes

I'm exploring how to design a database that can store state changes with the timestamp they occurred. The goal is to have fast access to all states within a given time period (e.g. 5 seconds). Inserting new values shouldn't be super slow, but number one priority is querying speed.

The data is generated like this:

ts: 1672527600010, field_0001 = true, field_0002 = 1491, field_0003 = "v07:01"
ts: 1672527600010, field_1001 = 47, field_1002 = -83
ts: 1672527600020, field_0002 = 595
ts: 1672527600050, field_1001 = 150, field_1003 = 75

The timestamp is in Milliseconds since Unix Epoch. Only the state of the fields that changed are transmitted and every block of fields is transmitted separately. It is not guaranteed that the timestamps are transmitted in the correct order. There are 10 blocks with a total of 250 fields.

Querying this data with the ts_begin = 1672527600000 and ts_end = 1672527605000 the result should look like this:

ts_occurred_ms field_0001 field_0002 field_0003 field_1001 field_1002 field_1003
1672527600010 true 1491 "v07:01" 47 -83 NULL
1672527600020 true 595 "v07:01" 47 -83 NULL
1672527600050 true 595 "v07:01" 150 -83 75

The result should combine all tables into one and fill up cells with the last available value for the field. The user should be able to see all fields at every timestamp.

What are some best practices for designing such a database?

What kind of schema should I use to store the state changes?

The first idea I came up with was to create a table for each block of fields

data_0000(ts_corrected, ts_occurred_ms, field_0001, field_0002, field_0003, ...)
data_1000(ts_corrected, ts_occurred_ms, field_1001, field_1002, field_1003)
data_2000(ts_corrected, ts_occurred_ms, field_2001, field_2002, field_2003, ...)
...

ts_corrected and ts_occurred_ms combined are the primary key in each table.

WITH data AS (
    SELECT
        COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms) AS tsoccurred_ms,
        LAST_VALUE(field_0001) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_0001,
        LAST_VALUE(field_0002) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_0002,
        LAST_VALUE(field_0003) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_0003,
        LAST_VALUE(field_1001) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_1001,
        LAST_VALUE(field_1002) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_1002,
        LAST_VALUE(field_1003) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_1003,
        LAST_VALUE(field_2001) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_2001,
        LAST_VALUE(field_2002) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_2002,
        LAST_VALUE(field_2003) IGNORE NULLS OVER (ORDER BY COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms, data_2000.tsoccurred_ms)) AS field_2003
    FROM data_0000
        FULL JOIN (SELECT * FROM data_1000 WHERE tscorrected = 0 AND tsoccurred_ms < 1672527605000) data_1000 ON data_0000.tsoccurred_ms = data_1000.tsoccurred_ms
        FULL JOIN (SELECT * FROM data_2000 WHERE tscorrected = 0 AND tsoccurred_ms < 1672527605000) data_2000 ON COALESCE(data_0000.tsoccurred_ms, data_1000.tsoccurred_ms) = data_2000.tsoccurred_ms
)
SELECT *
FROM data
WHERE tsoccurred_ms BETWEEN 1672527600000 AND 1672527605000
ORDER BY tsoccurred_ms;

Unfortunately for a mere 150 000 state changes this query already takes about 7 seconds in my test environment.

I didn't find a way to make this query more efficient as the subquery needs to join the whole tables as there could be columns where the value hasn't changed for hundreds of thousands of rows.

The second idea was to create a single table for all changes.

data(ts_corrected, ts_occurred_ms, field_id, value)

This significantly increases the storage space needed, as every field change also stores the corresponding timestamp.

WITH cte AS (
    SELECT tsoccurred_ms,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 0001 THEN value END) AS field_0001,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 0002 THEN value END) AS field_0002,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 0003 THEN value END) AS field_0003,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 1001 THEN value END) AS field_1001,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 1002 THEN value END) AS field_1002,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 1003 THEN value END) AS field_1003,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 2001 THEN value END) AS field_2001,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 2002 THEN value END) AS field_2002,
        MAX(CASE WHEN tscorrected = 0 AND field_id = 2003 THEN value END) AS field_2003
    FROM (
        SELECT * FROM cbm_data_1 WHERE tsoccurred_ms BETWEEN 1672527600000 AND 1672527605000
        UNION ALL
        SELECT *
        FROM ( SELECT * FROM cbm_data_1 WHERE tsoccurred_ms < 1672527600000  ORDER BY tsoccurred_ms DESC ) t1
    ) t2
    GROUP BY tsoccurred_ms
),
cte2 AS (
    SELECT tsoccurred_ms,
        COALESCE(field_0001, MAX(field_0001) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_0001,
        COALESCE(field_0002, MAX(field_0002) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_0002,
        COALESCE(field_0003, MAX(field_0003) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_0003,
        COALESCE(field_1001, MAX(field_1001) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_1001,
        COALESCE(field_1002, MAX(field_1002) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_1002,
        COALESCE(field_1003, MAX(field_1003) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_1003,
        COALESCE(field_2001, MAX(field_2001) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_2001,
        COALESCE(field_2002, MAX(field_2002) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_2002,
        COALESCE(field_2003, MAX(field_2003) OVER (ORDER BY tsoccurred_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS field_2003
    FROM cte
)
SELECT *
FROM cte2
WHERE tsoccurred_ms BETWEEN 1672527600000 AND 1672527605000

This is a lot faster, but when I add a couple million state changes queries also begin to take a long time. Maybe I am missing something.

lundi 17 avril 2023

Can a usecase have repositories from different domains as dependencies, following the clean architecture principles?

Assume I have two models: Student and Course, so we have a simple many-to-many relationship here, i.e., each student can take many courses and each course has many students.

I also have a usecase for adding a Student to an existing Course, where I receive as input the Student id and the Course id, and add this pair to my Relationship table which is managed by a AddStudentToCourseRepository.

The problem that I'm facing is the following: If the client tries to add a student to a course that does not exist, my application needs to return an error. I though about adding the ReadStudentByIdRepository and the ReadCourseByIdRepository as dependencies of my AddStudentToCourseUsecase, so I can check whether both id's are valid before calling the AddStudentToCourseRepository.

My question is: Am I going against the clean architecture principles by doing that, I mean, is it a bad practice to have a usecase having repositories from multiple domains as dependencies ? And if I am, how would you guys proceed in this situation ?

What's the difference between Flux pattern and Mediator pattern?

Is there a difference between the two patterns of flux and mediator? And isn't redux a mediator pattern?

Redux, a representative implementation of the Flux pattern, has a single store in the center that allows components to pass events through action without having to exchange data directly between components, where reducer is used to process events, notify each component of these changes and trigger rendering.

I think Redux is a pattern that uses two types of observer pattern and Mediator pattern.

I think flux pattern is a one-way binding of data from Mediator pattern.

How to pass array of objects type in MediatoR patterns?

Hope You are doing well!

I am using MediatoR design pattern in which i want to accept array of collections as an object in my controller. Earlier i was using as a single object but now how can i allow the MediatoR to accept array as parameter.

From: public async Task<ActionResult<ServiceResponse>> AddField(AddFieldCommand objFieldCommand)

To: public async Task<ActionResult<ServiceResponse>> AddField(AddFieldCommand[] objFieldCommand)

I tried doing this but it is giving me the below error:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0311  The type 'Application.Commands.Fields.AddFieldCommand[]' cannot be used as type parameter 'TRequest' in the generic type or method 'IRequestHandler<TRequest, TResponse>'. There is no implicit reference conversion from 'Application.Commands.Fields.AddFieldCommand[]' to 'MediatR.IRequest<Application.Common.ServiceResponse<int>>'.   Application C:\Users\Admin\Documents\Projects\Source Code\Application\Commands\Fields\AddFieldCommand.cs    28  Active

Can any one please help me?

dimanche 16 avril 2023

Architecture for a pipeline that requires multiple references for the same object in Rust

I am currently learning Rust and in order to have hands-on experience I have been playing around with a few small projects.

Currently I am doing a small Computer Vision pipeline for doing multiple different image processing (QRDetection and decode, for now) and display the processed image on the screen alongside a table with some information. For this i thought about having the following main components:

  • Stage: A trait that shall be implemented by any image processor.
  • SourceStage: A trait that shall be implemented by any image source.
  • CameraSource: It implements a SourceStage responsible for retrieving video from the Camera.
  • QrDecoder: It implements the Stage trait, draws a rectangle arround the QR codes and keeps any QR information of the last frame.
  • PipelineManager: Responsible for storing and passing the image trough the different Stages in a sequence order (for now) that may be used in the future on another projects.
  • UIManager: Display all UI components including the processed frames from the pipeline.

For now the the main flow is to just have the PipelineManager be owned by the UIManager and run the pipeline (which contains the CameraSource and the QrDecoder) on every frame.

The problem arrives after, I also want to display the QR information of the last frame in a table that's owned by the UIManager, so I require a reference of the QrDecoder to be saved in the UIManager. The Stages object should be owned by the PipelineManager but the same object could be referenced multiple times (mutability not needed).

The only way I can think of to solve this issue is by using the combination of Rc<RefCell> for every stage and passing the QRDecoder to the UIManager and PipelineManager, but this seems to be bad practice.

PipelineManager

use opencv::{prelude::*};
use std::cell::{RefCell};
use std::rc::Rc;

pub trait Stage {
    fn process(&mut self, input: &mut Mat) -> Result<()>;
}

pub trait SourceStage {
    fn get_frame(&mut self) -> Result<Box<Mat>>;
}

pub struct CVPipelineManager{
    start_stage: Option<Rc<RefCell<dyn SourceStage>>>,
    stages: Vec<Rc<RefCell<dyn Stage>>>
}


impl CVPipelineManager{
    pub fn new() -> Self {
        Self {
            stages: Vec::new(),
            start_stage: None,
        }
    }

    pub fn add_stage(&mut self, stage: Rc<RefCell<dyn Stage>>){
        self.stages.push(stage);
    }

    pub fn process(&mut self) -> Result<Box<Mat>>{

        if let Some(ref mut start_stage) = self.start_stage {
            let mut frame = start_stage.borrow_mut().get_frame()?;
            self.process_image(frame.as_mut());
            return Ok(frame);
        }
        return Err(anyhow!("Process cannot be called if a start stage was not defined"));
    }

    pub fn process_image(&mut self, input: &mut Mat) -> Result<()> {
        for stage in self.stages.iter_mut() {
            stage.borrow_mut().process(input)?;
        }
        Ok(())
    }

This code implements only the PipelineManager and the required traits, to get a better understanding of the problem.

Is there a better architecture for this or does Rust provide better tools for handling this kind of problems? I cannot think of any other way to design this without increasing the the effort too much when implementing a new Stage.

Classes common behavior + immutability in Kotlin

Is there a way to achieve the following but in a more immutable way?

abstract class Abstract {
    abstract val general1: String
    abstract var counter: Int // Don't want to use var here

    fun sumCounter(value: Int) {
        counter += value
    }
}

data class A (
    val a1: String,

    override val general1: String,
    override var counter: Int = 0,
): Abstract()

data class B (
    val b1: String,
    val b2: String,

    override val general1: String,
    override var counter: Int = 1,
): Abstract()

fun <T : Abstract> doSomething(obj: T) {
    //...
    obj.sumCounter(10) // I want: val newObj = obj.sumCounter(10)


    println(obj) // A(a1=a1, general1=general1, counter=10)
                 // B(b1=b1, b2=b2, general1=general1, counter=11)
    //...
}

fun myMain() {
    val a = A("a1", "general1")
    doSomething(a)

    val b = B("b1", "b2", "general1")
    doSomething(b)
}

It could be some Kotlin trick, functional approach, or design pattern to avoid creating the same methods in A and B. But I don't want to use reflections or convert to json and back.

Is there a way to automatically generate overriding function for child classes?

I have a snippet of code in my system, put it short, there are three classes, A, B extends A, and a singleton service C. C implemented one function, and I want it's behavior customizable based on caller.

class A {

void abort() {
  C::doSomething();
}

}

class B : public A {}

class C {

void doSomething() {
  ... a bunch of logics here.
}

}

There are multiple child classes extending A, and the current implementation is they enumrate all cases in doSomething, but I realized the cases are actually related to the caller. So I want to make the code looks like:

class A {

virtual void abort() = 0;

}

class B : public A {

void abort() override {
  C::doSomething<B>();
}

}

class C {

template <class T>
void dosomething() {
  ...T specific logic.
}

}

And since the overrided abort function only do one thing that is related to the implementing class, I wonder if there is a mechanism to make this automatic that I don't need to make every child class implement it (because I need to teach other people more about how to integrate into the system, and I prefer it works with least amount of code added.)

Thanks.

samedi 15 avril 2023

Is Chain of Responsibilities suitable for creating DAG like pipelines?

I understand that the CoR pattern is used when we have a sequence of tasks that need to be carried out, each takes the previous output as input and produces some new output.

Now I would like to see if I can apply this pattern to create non-linear pipelines. I have something like this in Kotlin:

interface Handler<I, O> {
    fun handle(input: I): Result<*>
}

How can I make it so that I can implement something like the following with concurrent execution path?

Peel mangos (Mango -> PeeledMango)
|
Dice mangos (PeeledMango -> DicedMango)
|    
|
|    Peel bananas (Banana -> PeeledBanana)
|    |
|    Dice bananas (PeeledBanana -> DicedBanana)
|  /
|/
|
Blend (DicedMango, DicedBanana, Yogurt, Milk -> MangoBananaSmoothie)

Implementing state pattern in practise

I have use case which has physical mailbox and got some package there. My app should have state unlock, lock, payment. Unlock can perform every person if mailbox is empty. If it not empty just owner or person who got shared item. Locking can be performed by both persons. Also other person should pay for item, otherwise cannot use item. Using item is free until 1h after that is payable. Also we have 100 differnet mailbox.

The first implementation was done without state, but some change requestes propagates trought all apis. I was thinking if would be smart to use state/strategy pattern?

............................

Change the value of the private member in the class designed by singleton pattern

Today I have a question about this code.

class Engine
{
    static Engine* getInstance()
    {
        return instance = (instance == NULL) ? new Engine() : instance;
    }
    SDL_Renderer* getRenderer() {
        return mRenderer;
    }
    bool init();
    bool Clean();
    bool Quit();

    void Update();
    void Render();
    void Events();

    SDL_Renderer* getRenderer()
    {
        return mRenderer;
    }
private:
    Engine();
    static Engine* instance;
    SDL_Renderer *mRenderer;
};

Engine* Engine::instance = NULL;

If I want to change the value of mRenderer as like a reference variable, I must write this code void render(Engine::GetInstance()->getRenderer()). So I don't know how the mRenderer change are.

Thanks for reading.

how to input image and it display like this picture

how to input image and it display like this picture(https://i.stack.imgur.com/PNTYd.jpg) need to use code css or software ? tell me plz

I use wordpress elementor I want to make mockup and temple by my own

vendredi 14 avril 2023

Is it ok to hand off to dev typography specs in this convention and not H1 - H6

enter image description here

As a UX/UI designer specific sizes for H1 - H3 cause issues so I prefer to use system shown on the left side of the image. Is this a problem in handoff? It creates much more flexibility. Thanks

I researched different approaches to typography and style guides(DSM's) to make my approach to design flexible and not locked in. I and wanted developers input.

PHP localization with static analysis?

It seems that the industry standard for PHP localization is passing string names to the global localization function:

  echo $this->getTranslator()->translate( 'library:Bid confirmation' )

So if I want to add a new call like that I have to navigate to the translation file, search for the translation I need and copy paste it manually to the new code line.

Another issue here is, if I add a new string for translation, there is no static check that I add it to all language files. Same goes for modifying an existing string name due to context change or page redesign.

It would be great to instead have some kind of static structure that the existing PHP analysis tools could use, e.g.

  echo $this->getTranslator()->Library->BidConfirmation;

So that I could ctrl-space on $this->getTranslator()->Library-> and get a prompt of all valid properties of that object. Additionally the analysis tool could check if all language objects correctly comply with the abstract parent that defines the list of required translations.

On the other hand I wouldn't want to bother with possibly performance-degrading techniques like reflection. Neither would I want to add a separate PHP file for every second level object like Library in the example above - there could be dozens of them.

Can anyone share their experience from a success story that adds design-time support to the localization process?

What's the best approach for setting up connections with multiple carriers in a microservices architecture?

I'm working on a project where I need to set up connections with multiple carriers such as DHL, DPD, and PostNL for sending products to our customers. I'm planning to use a microservices architecture for this purpose.

My question is, should I create separate microservices for each carrier or everything in a single microservice? What would be the best approach in terms of maintainability, scalability, and performance?

I would appreciate any advice or recommendations based on your experience. Thank you in advance.

jeudi 13 avril 2023

Hello. https://ift.tt/KwGLkCX will be grateful for reactions and comments under my new project

https://www.behance.net/gallery/167850663/Learning-Mobile-App

Hello. I will be grateful for reactions and comments under my new project

How to pass data to child objects from a controller style class

Given I have a sort of controller class which needs to setup some other objects e.g.

class ControllerClass
{
private someData: DataClass[];

private doSomeWorkOnData(): void
{
this.someData.foreach((value) =>
{
someData.doWork(//pass in values);
}
}
}

class DataClass
{
// Should these classes have their own version of the data?
public readonly numberData: number = 32;
public readonly stringData: string = "something";

public doWork(//pass in values): void{}
}

My question is should the data for the above variables in the DataClass be passed in each time so that the ControllerClass has the only copy of them saving space, or should each of the DataClasses have their own version of it even though they never change. I feel like that approach simplifies the code but makes it very memory intensive for no real reason.

Both of them work fine, but is either memory intensive or slightly messy looking.

Pattern index not getting used in my postgres query

My query is

SELECT * 
FROM all_persons
WHERE ((("email") ilike ('abc.com%')))
ORDER BY "lastOrderAt" DESC
OFFSET 0 LIMIT 20

I have already added indexes on table on column emailvarchar_pattern_ops.

Using explain I found that index is not used. Can someone guide that is the index wrongly created or how can I speed up the query?

mercredi 12 avril 2023

How to create a container for data of different types in Java?

I'm trying to figure out what is the right Java code structure of a feature written in JavaScript.

I have several classes each of them should handle its method calls and store related data. Each class processes data for different ids (some kind of containerId). Data values are of different types:

// javascript
class A {
  constructor() {
    this._containers = new Map();
  }

  method1(id, data) {
    // ensure that a container for <id> exists
    const container = this._containers.get(id);
    container.set('hello', 'world');
  }

  method2(id, data) {
    // ensure that a container for <id> exists
    const container = this._containers.get(id);
    container.set('prop', 1);
  }

  method3(id, data) {
    const container = this._containers.get(id); // in this case no need to ensure
    container.set('some', 1.0);
  }
}

class B {
  constructor() {
    this._containers = new Map();
  }

  method1(id, data) {
    // ensure that a container for <id> exists
    const container = this._containers.get(id);
    container.put({ prop1: 'value1', prop2: 0 }); // this is actually not allowed in js, pseudo-code
  }
}

I'd like to remove code duplication (and also the responsibility of data storing management) with composition. Moving all store logic in a separate class, e.g. DataHolder. I just want to call dataHolder.add(containerId, key, value); which will check that a container exists and add key, value to it.

Java DataHolder could have an underlying storage as a Map<String, ?>. Due to method overloading I could define different variations of an add method:

// java
public class DataHolder {
  private Map<Integer, Map<String, ?>> containers = new HashMap<>();
  // ...
  add(int containerId, String key, ? value) {}
  add(int containerId, ? value) {} // it could take container.size() as a key
}

How do I define this ? in DataHolder so that it handles everything correctly. If it's an Object how does A class know which type a value is? instanceof seems a bad idea. (When an A instance decides that it got the last chunk of data it should create a new Record for example with collected values).

If it's not the way a Java code is written, so what is the way?

Another approach could be to create AContainers class which holds a map of A instances (for each id) with all fields defined inside A class. But I don't like this approach because in that case AContainers should proxy all method calls to A instance (and also have some knowledge when A is done). For each algorithm A, B, ..., Z there will be 1 additional class. (2*N classes instead of N). And it should anyway implement the logic of creating an A instance on event (which contradicts the initial intent to move the creation logic outside the processors).

C program for a reverse triangle pattern

I want to draw a pattern like this:

enter image description here

the code below is what I tried and the output for this code is like this:

enter image description here

#include <stdio.h>

int main() {
  int a, b, c, s;
  for (a = 5; a >= 1; a--) {
    for (s = a; s <= 4; s++) {
      printf(" ");
    }
    for (b = a; b <= 9; b++) {
      printf("%d", b);
    }
    for (c = 8; c >= a; c--) {
      printf("%d", c);
    }
    printf("\n");
  }
  return 0;
}

Good Patterns to pass down data in deep OOP composition?

This is a general open question about best practices and scalability in Python using OOP.

Overtime, I have been using in several projects Class inheritance and composition. This pattern has helped me abstracting and encapsulating a lot of the code. However, as the codebase increases, I have been trapped in a recurrent pattern where I have a "master" Class which "orchestrates" another classes by composition, which in turn also have another composed classes to orchestrate and so on. This creates a "deep" tree structure of dependant classes.

The problem is that if I want to pass down arguments to many of the Class components from the master class, I have to pass it down on everytime I init the class again and again, writing redundant code. For example (a simple example just to illustrate the kindof composition but imagine a much deeper structure than this):

 class UploaderExecutor:
     def __init__(self, mediatype: Literal['video', 'image'], channel: Literal['online', 'offline'], ...):
     self.uploader = Uploader(mediatype, channel, ...)
     self.validator = Validator(mediatype, channel, ...)
     self.reporter = Reporter(mediatype, ...)
     ...

 class Uploader():
     def __init__(self, mediatype, channel, ...):
         self.configurator = Configurator(mediatype, channel...)
         self.file_parser = FileParser(mediatype, channel...)
         self.Notificator = Notificator(mediaype, channel...)
         ...

 class Validator():
     def __init__(self, mediatype, channel, ...):
         self.file_validator = FileValidator(mediatype, channel...)
         self.name_validator = NameValidator(channel...)
         ...

 class Reporter():
     def __init__(self, mediatype, channel, ...):
         self.slack_reporter = SlackReporter(mediatype, channel...)
         self.telegram_reporter = TelegramReporter(mediatype, channel...)
         ...

   #etc etc

I guess this pattern of passing down arguments to all the composed classes is not escalable as more and more cases are added. Also I do not want to rely in solutions like global variables, because I want to decide which data passing down to which composed classes (maybe not all of them would need for example mediatype). So my question is which kind of abstractions or design patterns are recommended in these cases?

mardi 11 avril 2023

Bast practices for writing new code on existing project?

I wonder what it is better to do when working on an existing project and facing different "style" of coding and organization of source code in general.
It is better to keep my style of coding about conventions on naming, documentation, spacing, etc... (personally I work with python and always try to stick to standard PEPs) or adapt it to the existing one? What if the existing one is unclear or inconsistent itself and refactoring is not an option?

I tried reading articles about collaborative coding.

lundi 10 avril 2023

Alphabet Pattern in C language

i have code C language like this

int main() {
   char A[3][6] = {
      "ABCDE",
      "FGHIJ",
      "KLMNO"
   };

   int i, j, x, y;
   x = 0;
   y = 1;

   for (i=0; i<=2; i++) {
      for (j=0; j<=4; j++) {
         printf("%c ", A[i][j]);
         x++;

         if (x == y) {
            printf("\n");
            y++;
            x=0;
         }
       }
   }
}

If i run the above code, it will display like this :

A 
B C 
D E F 
G H I J 
K L M N O

How can I display pattern the output like below, just by making a few changes to the code above :

        A
      B C
    D E F
  G H I J
K L M N O

O N M L K
  J I H G
    F E D
      C B
        A

Thank you

dimanche 9 avril 2023

Pattern, ignore '&' and subsequent characters if they contain any specific characters

Example, I have 3 String:

String A = "&aHi"; // true, 2 characters in total
String B = "Hi"; // true, 2 characters in total
String C = "Hi!"; // false, 3 characters in total

When the string contains "&" followed by some character like "[0-9A-FK-ORX]" I want it to be excluded in the check if the string is less than 3 characters or greater than 15 characters.

This is what I currently have: Pattern:

"^(?i)(?:(?!&[0-9A-FK-ORX]).|^.{0,2}|^.{16,})$"

but I can't get it to work, I'm trying to get it to ignore lower and upper case, I'm checking that it's less than 3 or greater than 15, but I can't get what I need.

Adapting a Latex-Chart design

I would like to create a chart in latex similar to the one in the papers "Automation and new Tasks" (Daron Acemoglu) and "The Rise of Robots in China" (Hong Cheng), but I have problems adapting the design.

Attached is my sample code. How can I adapt it so that it looks like this? Does anyone have any ideas?

BG

This is the disgn of the chart i want to adapt

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.17}

\begin{document}

\begin{figure}[h!]
    \centering
    \begin{tikzpicture}
        \begin{axis}[            xlabel={Year},            ylabel={Robot Density},            xmin=2003, xmax=2017,            ymin=0, ymax=50,            xtick={2003,2005,2007,2009,2011,2013,2015,2017},            ytick={0,10,20,30,40,50},            legend pos=north west,            ymajorgrids=true,            grid style=dashed,        ]
        
        \addplot[            color=blue,            mark=square,            ]
            coordinates {
            (2003, 0.03)(2005, 0.14)(2007, 0.61)(2009, 2.32)(2011, 7.45)(2013, 17.24)(2015, 33.25)(2017, 49.34)
            };
            
        \addlegendentry{Robot Density}
        
        \end{axis}
    \end{tikzpicture}
    \caption{Robot Density in China (2003-2017)}
\end{figure}

\end{document}

I have tried to find a solution through ChatGPT and Google, however I don't know what specifically to look for.

Java Design Pattern for initializing dynamic private variable

I have an interface named IClientServer.java

interface IClientServer {
   void save(String fileName);
}

It's Impl looks this way:

public class ClientServerImpl implements IClientServer {

    private final String key;
    private final Client client;

    public ClientServerImpl(final String key1, final String key2) {
        this.key = key1 + key2;
        this.client = openConnection(key);
    }

    @Override
    public void save(String fileName) {
    client.save(fileName);
....
  }
}

Note that the above Interface and Impl are in a common project accessible to all projects and every project currently using this initialize the bean per their own keys at the configuration level and use them directly.

I now have to create an API that is also in a common project that will need to access the ClientServer

New class: IClassA.java

public interface IClassA {
   void save(boolean validate, String fileName);
}

It's Impl:

public class classA implements IClassA {

    private final IClientServer clientServer;

    public classA(IClientServer clientServer) {
        this.clientServer = clientServer;
    }

    @Override
    public void save(boolean validate, String fileName) {
    //perform computation and then proceed to save
    clientServer.save(fileName);
....
  }
}

Now, classA.save() is invoked after consuming a Kafka Record from the topic.

Since IClassA is also in the common library, how do I initialize ClientServerImpl with dynamic keys specific to the caller?

PS: I can have both the keys as part of the kafka record if it's needed.

samedi 8 avril 2023

Is it considered as appropriate practice to store such tiny data "records" in Model's constants instead of DB?

Working on various little/medium web projects I've noticed that it's became a usual practice for me to store some data in model's constants instead of Database, especially when such data is strongly connected to model and is critical to keep it unchanged for code to work.

For example, as shown below, when I have to store various vehicle's events (refuel, service, parking ans so on), I prefer to store theese record's TYPEs as constants instead of making a dedicated model/table for them, despite the fact that those TYPEs may have not only 'code', which would be ok to store in constants, but some extra "fields" as well (like display_name, some flags and so on), which seems more like smth that should be stored in DB.

So, the question is - what is the best bractice for such situation when it's critical to keep some data unchanged, but the data seems more like db-records then just scalar constants? What solutions/patterns are common used and considered as appropriate for such situations?

(I see that the question may seem too inparticular, but I think it would be good to gather some design patterns references here that would be useful for futher readers)

class VehicleEvents extends Model {

    public const TYPE_PARKING       = 'parking';        
    public const TYPE_WASHING       = 'washing';        
    public const TYPE_SERVICE       = 'service';        
    public const TYPE_REFUEL        = 'refuel';           
    public const TYPE_TOW           = 'tow';           

    private const TYPES_INFO = [
        self::TYPE_PARKING =>       ['display_name' => 'Парковка', 'is_regular' => true],
        self::TYPE_WASHING =>       ['display_name' => 'Мойка', 'is_regular' => true],
        self::TYPE_SERVICE =>       ['display_name' => 'Сервис', 'is_regular' => true],
        self::TYPE_REFUEL =>        ['display_name' => 'Заправка', 'is_regular' => true],
        self::TYPE_TOW =>           ['display_name' => 'Эвакуатор', 'is_regular' => false],
    ];

    public static function getTypes() {
        return array_map(fn($code) => self::getTypeInfo($code), array_keys(self::TYPES_INFO));
    }
    public static function getTypeInfo($type) {
        return array_merge(self::TYPES_INFO[$type] ?? [], ['code' => $type]);
    }

    // ...
}

vendredi 7 avril 2023

Multiple calling @property that reduce list

I'm training my skills of design patterns. With a Factory schema i tried to get and pop example numbers from a imited list.

With initialization of seccond account i recieved an IndexError. In debug mote i noticed that between initialisation of acc01 and acc02 I have a 4 uses of AccountManager.number() func. Same with AccountManager.account_id().

from abc import ABC
from random import choice, randint


class AccountsManager:
    def __init__(self) -> None:
        self._last_id_number = 0
        self._allowed_numbers = [randint(10_000, 99_999) for _ in range(5)]

    @property
    def number(self) -> int:
        if not self._allowed_numbers:
            raise IndexError
        number = choice(self._allowed_numbers)
        self._allowed_numbers.pop(self._allowed_numbers.index(number))
        return number

    @property
    def account_id(self) -> int:
        account_id = self._last_id_number
        self._last_id_number += 1
        return account_id


class TemplateBankAccount(ABC):
    def __init__(self, manager, owner: str, account_type: str = '') -> None:
        self.manager = manager
        self.id_number = manager.account_id
        self.account_number = manager.number

        self.owner = owner
        self.account_type = account_type
        self._amount = 0

    def __str__(self) -> None:
        raise NotImplementedError

    @property
    def amount(self) -> int:
        return self._amount

    @amount.setter
    def amount(self, direction: str, value: int) -> None:
        if direction == '+':
            self._amount += value
        elif direction == '-':
            self._amount -= value
        else:
            raise ValueError


class PersonalBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Personal Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class CompanyBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Company Account')

    def __str__(self) -> str:
        return f'{self.account_type}: owner name restricted.'


class SavingsBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Savings Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class AccountCreator:
    def __init__(self) -> None:
        self.manager_group = AccountsManager()

    def create_account(self, owner_name, account_type):
        allowed_types = {'Personal': PersonalBankAccount(self.manager_group, owner_name),
                         'Company': CompanyBankAccount(self.manager_group, owner_name),
                         'Savings': SavingsBankAccount(self.manager_group, owner_name)}

        return allowed_types.get(account_type, 'Non offered account type')


def main() -> None:
    creator = AccountCreator()
    create_account = creator.create_account
    acc_01 = create_account('Andrew Wiggins', 'Personal')
    acc_02 = create_account('NASA Inc.', 'Company')
    acc_03 = create_account('John Paul Wieczorek', 'Savings')

    list_of_accounts = [str(account) for account in (acc_01, acc_02, acc_03)]
    print('\n'.join(list_of_accounts))


if __name__ == '__main__':
    main()

I do not know how to change code to get values from self._last_id_number and self._allowed_numbers only once per create_account call.

jeudi 6 avril 2023

Execute a method right before execution of various methods in different classes using Java

I am facing a code design challenge and not very sure how to resolve it. Tried researching a bit on the net but that made me even more confused.

InterfaceI1 -> Parent level interface (Single method)

Class C1 -> C1 implements I1 (C1 overrides method from I1 has no method of its own)

Class CC1, CC2, CC3, CC4, CC5 -> All these extend C1 (Overrides method in C1 and has methods of its own as well)

The problem is : I need to execute a piece of code on execution of certain methods in classes CC1, CC2, CC3, CC4, CC5. These methods have nothing in common and certainly its not the overridden method.

Is there a way to write this common piece of code in a central place and make it execute on execution of concerned methods?

Also the execution of this common piece of code would also depend on another environmental condition. For eg :

If the method in CC1 is executed && its a weekend { Execute the common code }

Since i dont want to clutter all the methods with the same boilerplate code i did some research and came across AOP. It looked like a fit for the requirement though not sure if conditional execution could be managed with AOP. As i was reading about it i learned about Action At Distance anti-pattern and how its not good for the code manta inability.

Any leads or suggestions would be helpful.

Edit : CC1, CC2, CC3, CC4 is not a spring bean

AWS Step Function - Wait until a group of other Step Functions have finished then fire a different Step Function

I have a scenario where I need to post process results that have been produced by a group of discrete Step Functions. How can I orchestrate this arrangement such that, if I have Step Function A, B and C. Once A, B and C have completed successfully then trigger Step Function D.

Step Function D will take as a payload outputs from Step Functions A, B and C. A, B and C are triggered from an external Java Microservice. I have a Dynamo DB table containing details of A, B and C, so I know which execution IDs belong together.

This seems to be quite a common pattern so I was hoping that there was already some sort of robust design to address it.

I have thought about using SNS to trigger an event when Step Functions A, B and C complete but I need to capture these events together in a group. So if I had a Lambda which captured the event, I would need to somehow know which event this is and whether or not all prior events have been received. I could use a Dynamo DB table to track each Step Functions completion status, at the end of the Step Function update the row. Then the lambda when it receives the completion event can check if each of the rows pertaining to the group of executions is marked as completed? Would this introduce a race condition? is this a trustworthy method?

mercredi 5 avril 2023

How can I FIX/CHANGE the almost invisible Menu Items in my Website's Mobile Version?

As you develop your application, you can use Swift syntax to write code that interacts with the user interface, accesses device hardware and sensors, communicates with servers, and more. There are many resources available online to help you learn Swift, including official documentation, tutorials, and communities.

What Design Patterns can be applied to my application?

I have a student project, a simple standalone Python application to track common expenses (Split Wiswe analog).

The code is complete and working. The goal of the project is to apply several Design Patterns and I need help with this.

Can anyone tell me which Design Pattern can be implemented here?

Which design pattern to implement in order to split the responsibilities?

I have a part of my application that I would like to refactor. The classes involved have too many responsibilities as well as too many dependencies. Different parts of the code that needs refactoring make use of the same app modules. These modules are used in the same way - to check whether another operation can occur.

Example:

  1. The user wants to perform an update - check if the user is signed in.
  2. The user tries to use a paid app feature - check if the user is signed in and has the right to use that feature.

I am seeking for a design pattern that will centralize the logic that is used in too many places in the same way.

Do architecture patterns force a specific folder structures?

By following an architecture patterns, am I forced to follow a specific file structure? For example if I'm following MVC, am forced to have a folder structure similar to what asp.net core mvc has?

Doesn't architecture patterns just tell us how different components should communicate?