vendredi 29 décembre 2023

How to use the Command Pattern when dealing with different parameters

Having a look at the UML diagrams for the Command Pattern reported here and here, the class of the invoker object (the one that inkoves the execute() method of a command object) must provide a setCommand() method to allow the client code to set the proper command object on the invoker: but how can such method be used when dealing with command objects that have different parameters which, additionally, are known only at runtime? I'll try to make an example.

class Messenger
{
  public function sendEmail(string $email, string $subject, string $body): void { ... }
  public function sendSms(string $phone, string $text): void { ... }
}

interface Command
{
  public function execute(): void;
}

class SendEmailCommand implements Command
{
  private readonly Messenger $messenger;
  private readonly string $email;
  private readonly string $subject;
  private readonly string $body;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function setEmail(string $email): void { $this->email = $email; }
  public function setSubject(string $subject): void { $this->subject = $subject; }
  public function setBody(string $body): void { $this->body = $body; }

  public function execute(): void
  {
    $this->messenger->sendEmail($this->email, $this->subject, $this->body);
  }
}

class SendSmsCommand implements Command
{
  private readonly Messenger $messenger;
  private readonly string $phone;
  private readonly string $text;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function setPhone(string $phone): void { $this->phone = $phone; }
  public function setText(string $text): void { $this->text = $text; }

  public function execute(): void
  {
    $this->messenger->sendSms($this->phone, $this->text);
  }
}

In such a scenario how much is it useful to have a setCommand(Command $command) on the invoker class? In some languages I would even get an error later when trying to call setX() because the Command interface doesn't define them. Would it be a bad idea to do something like this?

class EmailSendButton()
{
  private readonly Messenger $messenger;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function onClick(): void
  {
    $email = $this->getEmail();
    $subject = $this->getSubject();
    $body = $this->getBody();

    $sendEmailCommand = new SendEmailCommand($this->messenger);
    $sendEmailCommand->setEmail($email);
    $sendEmailCommand->setSubject($subject);
    $sendEmailCommand->setBody($body);
    $sendEmailCommand->execute();
  }
}

I know it is not ideal to instantiate a class inside another class, it creates coupling, but how would you solve it?

I was thinking about setCommand(SendEmailCommand $sendEmailCommand) instead of the easier setCommand(Command $command) but it adds more complexity on the client code than benefits IMO.

mercredi 13 décembre 2023

How to set fields for an object based the object circumstances, without relying on boolean flags?

We have a huge object which sets one by one a lot of fields. However, we've come to a point where we set 3 flags in order to create it based on what we need, which break clean code rules. Basically it looks something like this:

method(boolean flag1, boolean flag2, boolean flag3){
    if (flag1){
        field1 = customValue1;
    }
    if (flag2){
        field2 = customValue2;
    }
    if (flag3){
        field3 = customValue3;
    }

How can I refactor this so it follows the standard (get rid of all the flags)?

Making a separate method for each case wouldn't be alright I think because I would have a LOT of code duplicates (this method has over 200 lines of code due to the number of fields and the way the business logic works in general). Then I thought of creating some sort of Supplier object for each possible case, but... just no. What are my options?

mercredi 6 décembre 2023

how to make logic for pattern "*" question in python

Make the pattern

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

using loops in python

There is some problem in the logic of this for loop can u check and please tell

for i in range(0, 5):
     
        for j in range(0, i+1):
         
            print("* ",end=""
)
      
        print("\r")

mardi 5 décembre 2023

Dynamic BLoC Implementation Switching in Flutter Using Bloc Pattern and Custom Class Loader

I'm facing a challenge in designing a Flutter application with the BLoC state management pattern. The app is intended to be generic but used by multiple clients, some of whom have specific needs requiring customized versions of the main app.

To achieve this, I've implemented a custom class loader that dynamically loads either the default class or an overridden specific class. This applies not only to the app's main classes but also to BLoC implementations. For example, I have a StockBloc and an overridden version called SpeStockBloc. The registration of overridden classes happens at the beginning of the app using MyClassLoader()[StockBloc] = SpeStockBloc.new.

The issue arises when I attempt to consume the StockBloc in a view using context.watch<StockBloc>. Instead of recognizing the overridden SpeStockBloc, it looks for the exact StockBloc type in the widget tree. I understand that it's the correct behavior of Bloc and Provider.

I'm seeking advice or alternative approaches on how to dynamically switch between BLoC implementations at runtime while utilizing context.watch or a similar mechanism, ensuring it takes overridden types into account.

Any insights or suggestions on how to handle this scenario efficiently would be greatly appreciated.

Custom class loader :

/// Class to provide (if registered) a construction function that overrides
/// the initial construction for the [Type] used as a parameter
class DynamicClassLoader {
  final Map<Type, Function> _mappedClasses = <Type, Function>{};

  static final DynamicClassLoader _instance = DynamicClassLoader._internal();

  /// Singleton factory
  factory DynamicClassLoader() {
    return _instance;
  }

  DynamicClassLoader._internal();

  /// Checks if a specific class is registered
  bool hasOverride(Type type) =>
      _mappedClasses.containsKey(type) && _mappedClasses[type] != null;

  /// Access operator for a construction function of an instance of type [type]
  Function? operator [](Type type) {
    return _mappedClasses[type];
  }

  /// Obtains an instantiation function for the overridden class
  Function newInstantiation(Type type, Function fallback) =>
      hasOverride(type) ? this[type]! : fallback;

  /// Assignment operator for a construction method for a type [type]
  void operator []=(Type type, Function func) {
    _mappedClasses.update(
      type,
      (
        Function value,
      ) =>
          func,
      ifAbsent: () => func,
    );
  }
}

/// Access function to the method [DynamicClassLoader.newInstantiation]
Function newInstantiation<Class>(Function fallback) =>
    _newInstantiation(Class, fallback);

Function _newInstantiation(Type type, Function fallback) =>
    DynamicClassLoader().newInstantiation(type, fallback);

Stock bloc :

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import 'package:test_bloc/class_loader.dart';

class StockBloc extends Bloc<StockEvent, StockState> {
  /// factory
  factory StockBloc({required int myCustomParam}) =>
      newInstantiation<StockBloc>(StockBloc.std)(myCustomParam: myCustomParam);

  StockBloc.std() : super(StockInitial()) {
    on<StockEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

@immutable
class StockEvent {}

@immutable
sealed class StockState {}

final class StockInitial extends StockState {}

spe stock bloc :

import '../stock_bloc.dart';

class SpeStockBloc extends StockBloc {
  SpeStockBloc() : super.std() {
    on<StockEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

sub_cmp :

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:test_bloc/bloc/bloc/stock_bloc.dart';

class SubCmp extends StatelessWidget {
  const SubCmp({super.key});

  @override
  Widget build(BuildContext context) {
    StockState bloc = context.watch<StockBloc>().state;

    return const Text("Sub cmp");
  }
}

main :

import 'package:flutter/material.dart';
import 'package:test_bloc/bloc/bloc/bloc/spe_stock_bloc.dart';
import 'package:test_bloc/bloc/bloc/stock_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:test_bloc/class_loader.dart';
import 'package:test_bloc/sub_cmp.dart';

void main() {
  runApp(
    const MyApp(),
  );
}

void registerSpe() {
  DynamicClassLoader()[StockBloc] = SpeStockBloc.new;
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: BlocProvider(
        create: (context) => StockBloc(myCustomParam: 10),
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SubCmp(),
            ],
          ),
        ),
      ),
    );
  }
}


Modelling Gof Observer patterns in UML

I am modeling my project, which I will subsequently implement in Java, using UML. My project involves managing a gym. More specifically, I am currently modeling my GoF Observer diagram. By what I've understood, I can't allow my Graphic Controller, with the models (entity), correct me if I'm wrong. On the other hand, if I let my application controller to implement the Observer, how can I notify the graphic controller that an exercise changed his status? Here I put my two ideas: enter image description here enter image description here

lundi 4 décembre 2023

How do I create a pattern using an array? [closed]

I have to create a pattern using an array, but I have no idea what to do. Class videos aren't helpful, if someone could please help me with this i'd appreciate it.

The pattern I need to make looks like this: Xs patterned to look like C++ logo

I honestly don't know what I'm supposed to do to make this work, we didn't go over arrays in depth and it has to be an array for me to recieve the grade. There's a few more patterns I have to make but I think if i figure this out I'll be able to do those on my own. A visual example of how the code should look would be incredibly helpful.

DB calls in FluentValidator class in DDD implemetation

We are implementing DDD in our project and we are using fluent for data validation.

FluentDataValidation class has some service calls(like diff db calls and AD call) for validating data.

Is this valid in DDD design to have service layer called from Validator class?

        public PublicValidator(IMetadataService metadataService)
    {
        this.When(status => status.IsStatusInComplete(), () =>
        {
            this.RulesWhenStatusIsInComplete(metadataService);
        })
        .Otherwise(() =>
        {
            this.RulesWhenStatusIsOtherThanIncomplete(metadataService);
        });

        this.RuleFor(s => s.Employers)
        .Must((r, p) => !r.people())
        .WithMessage(PeopleMessages.Dates);

        this.When(s => s.Employers != null && s.Employers.Count > 0 && !s.HasDefault, () =>
        {
            this.RuleForEach(s => s.Employers).ChildRules(a =>
            {
                a.RuleFor(s => s.Einperp)
                .NotEmpty()
                .Must(o => (metadataService.GetEmployerByEinperp(o) != null))
                .WithMessage(Constants.IncorrectMetadata);}

Security flow diagram to protect confidential information for external user

I am working on a POC to create flow diagram to secure protected data for external user. We are planning to work on market place where external user will login via external application and paired with a group they belong to. Once pairing is completed between external user and group then as a next step external user can call an api to see all the information associated with the paired group. We needs to impose an security that external user is calling api using same external application once pairing happen. External user can be associated with multiple external application and raise pairing request with same group using market place.

  1. There are application to application interaction.
  2. External user login on market place through external system. It’s a user interface where all the user can login if they have credential.
  3. After successfully login user can see list of group associated with logged in user.
  4. User can select group using market place ui and raise a pairing request.
  5. Once pairing is done then user is authorized to call group api to see detail of that group.
  6. All the external user will call these api using a external application.
  7. As a security we need to validate external user is calling group api using same external system once they raised pairing request on market place.

dimanche 3 décembre 2023

Composability: Iterator vs Lambda

I am having trouble understanding the concept of 'good' functional composability. Assume the following approaches for deleting files with a specific extension:

Using Lambda functions:

def traverse_tree(
        temp_storage: Local, extensions: List[str], is_raw: bool, operation: Callable
):
    for folder_path, subfolders, filenames in os.walk(temp_storage.root_path(is_raw)):
        for filename in filenames:
            base, ext = os.path.splitext(filename)
            if ext in extensions:
                file_path = os.path.join(folder_path, filename)
                operation(file_path)

def clear_temp(
        temp_storage, extensions: List[str], is_raw
):
    traverse_tree(temp_storage=temp_storage, extensions=extensions, is_raw=True, operation=lambda x: os.remove(x))

Using an iterator:

def traverse_tree(
        temp_storage, extensions: List[str], is_raw
):
    for folder_path, subfolders, filenames in os.walk(temp_storage.root_path(is_raw)):
        for filename in filenames:
            base, ext = os.path.split(filename)
            if ext in extensions:
                file_path = os.path.join(folder_path, filename)
                yield file_path


def clear_temp(
        temp_storage: Local, extensions: List[str], is_raw: bool
):
    for path in traverse_tree(temp_storage, extensions, is_raw):
        os.remove(path)

Is one approach favored over the other in terms of modularity and ease of debugging? If so, can you give an example where one approach objectively results in less flexibility?

Thanks,

samedi 2 décembre 2023

Design Method for Separating Retry Logic from Transaction Scope

I encountered an 'org.hibernate.AssertionFailure' error in my test for a specific logic.
ERROR 56862 --- [pool-3-thread-9] org.hibernate.AssertionFailure : HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in ... entry (don't flush the Session after an exception occurs)

The issue arises when a data race condition leads to a Constraint Violation Exception due to the 'longUrl' being a unique column. In this scenario

  1. the first committed transaction context returns its 'shortUrl'
  2. while the other failing contexts should find and return the committed entity.
@Transactional
public String
getShortUrl(String longUrl) {
    UrlEntity   url;
    try {
        // Create Entity For Id
        url = this.db.findUrlEntityByLongUrl(longUrl).orElseGet(
                () -> this.db.save(new UrlEntity(longUrl)));
        
        String shortUrl = this.generator.encode(url.getId());
        url.setShortUrl(shortUrl);
        this.db.save(url);
    } catch (DataIntegrityViolationException e) {
        //  if Conflict return after find
        url = this.db.findUrlEntityByLongUrl(longUrl).get();
        if (url.getShortUrl() != null) return url.getShortUrl();
        url.setShortUrl(this.generator.encode(url.getId()));
    }

    return url.getShortUrl();
}

Based on my understanding, exceptions occurring within the scope of a transaction trigger a rollback, rendering the session unstable. In this context, I am attempting to perform entity retrieval using this unstable session :(

How should I approach the design? I am concerned that managing try-catch blocks at the controller level might shift part of the business logic to the controller, which seems inappropriate.

Is there a suitable design pattern for this situation?

What the way for transferring data to the factory classes?

I want to understand how best to pass data to factory classes

Hello!

Situation:

1)I have a class with records for orders. For example, class Order

2)Separately, I create a factory (simple factory) and different classes for conducting transactions, depending on the type of orders. Orders has 3 types and the realization of the transaction is different for each type:

$transactionFactory = new TransactionFactory();
$transaction = $transactionFactory::create($typeOrder); //creating Class FirstType, Class SecondType{} etc...

And in the end I have 2 classes for types of order: Class FirstType{}, SecondType{} implements some interface and etc...

Question: best way to pass 3-4 order's parameters (like type of transaction, amount...)

$transaction->setAmount(343);
$transaction->setBlahBlah(qwq);

or to constructor

$transactionFactory = new TransactionFactory();
$transaction = $transactionFactory::create($typeOrder, $amount, $blahblah, $foo, $bar); 

or

$transactionFactory = new TransactionFactory();
$transaction = $transactionFactory::create($orderID); 

to the factory's class constructor or pass the order id and make a select to db for get information about order in the Class FirstType, SecondType again?

What is the best way to pass parameters - pass all the necessary data from outside into the parameters or pass $orderId and re-receive the data in factory methods (this is an additional query to the database)?

vendredi 1 décembre 2023

C++: Pointer vs. Reference Design Question

Background

I constantly struggle with when to use pointers versus references in good software design. I'm hoping an example taken from the code I'm writing will help me solidify best practices through peoples' answers.

I have the following classes. Assume public getters for all fields that return the same type as the fields are declared with. For reasons I'd rather not get into, know that I also cannot easily combine the geometry and node classes. Also, ignore the fact that pointers are raw pointers. That's just for simplicity in the example.

// A 2D point
class Point {
private:
    double _x;
    double _y;
};

// A 2D edge. Edges refer to any trapezoids above and below themselves.
class Edge {
private:
    Point* _point1;
    Point* _point2;
    Trapezoid* _above;
    Trapezoid* _below;
};

// A 2d Trapezoid. Trapezoids refer to their place in the tree structure
class Trapezoid {
private:
    Point* _left;
    Point* _right;
    Edge* _top;
    Edge* _bottom;
    TrapezoidNode* _graphNode;
};

// Abstract Node
class Node {
protected:
    Node* _leftChild;
    Node* _rightChild;
};

// Node representing a point
class PointNode : public Node {
private:
    Point* _point;
};

// Node representing an edge
class EdgeNode : public Node {
private:
    Edge* _edge;
};

// Node representing a trapezoid
class TrapezoidNode : public Node {
private:
    Trapezoid* _trap;
};

The algorithm I'm writing takes in a starting Trapezoid and initializes a tree structure with a single TrapezoidNode representing that trapezoid. It also stores that Trapezoid in an unordered_set so that I can easily know what trapezoids exist in the tree at any point in time. From there, I begin breaking down nodes in the tree, replacing them with smaller subtrees consisting of PointNodes, EdgeNodes, and TrapezoidNodes. This process involves the creation of new Points, Edges, and Trapezoids that those nodes refer to. I also keep the unordered_set up-to-date with any new trapezoids that get created.

Key Questions

  1. For the Edge and Trapezoid classes, would it make more sense to use references to Points and Edges (respectively) instead of pointers?

    • The main problem is the lifetime of some of these objects. There are some edges whose life extends beyond that of the trapezoids they become a part of. This suggests the use of pointers, since the trapezoid does not own those edges. Other edges, however, are created for the sole purpose of creating a new trapezoid with limited lifetime. This suggests the use of references, since the lifetime of these edges are tied to the trapezoid that contains them.
  2. For my set of trapezoids, it better design to:

    • A) Use an unordered_set<Trapezoid> and make sure when I create TrapezoidNodes, that I am pointing to the heap memory managed by that set... or

    • B) Manually allocate heap memory for new Trapezoids and use an unordered_set<Trapezoid*> (which requires me to write a hashing function for Trapezoid* instead of Trapezoid

As shown above, my current implementation is to use pointers everywhere.

Move the logic to separate handlers

I have the helper class which translate list TreeField structures to some generic type, and I have a problem with initializing the fields. More precisely, I want to put the logic for each type into separate handlers so that I can add them without changing the logic of ExpressionHelper itself.

What exactly i wanna separate.

var propertyType = property.PropertyType;

if (propertyType.IsPrimitive || propertyType == typeof(string))
{
    var memberExpression = Expression.Property(parameter, property.Name);

    var bind = Expression.Bind(property, memberExpression);

    bindings.Add(bind);
}
else if (type.IsClass)
{
    var memberExpression = Expression.Property(parameter, property.Name);

    var subFieldsInit = GetMemberInitExpression(property.PropertyType, memberExpression, field.Children);

    var bind = Expression.Bind(property, subFieldsInit);

    bindings.Add(bind);
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
    var elementType = property.PropertyType
        .GetGenericArguments()
        .FirstOrDefault() ?? throw new InvalidOperationException($"Generic type for collection {property.Name} not founded.");

    var selectMethod = typeof(Enumerable).GetMethods()
        .Where(m => m.Name == nameof(Enumerable.Select))
        .First(m => m.GetParameters().Length == 2)
        .MakeGenericMethod(elementType, elementType);

    var lambdaParameter = Expression.Parameter(elementType);

    var lambdaBody = GetMemberInitExpression(elementType, lambdaParameter, field.Children);

    var selectLambda = Expression.Lambda(lambdaBody, lambdaParameter);

    var memberAccess = Expression.Property(parameter, property);

    var call = Expression.Call(selectMethod, memberAccess, selectLambda);

    var bind = Expression.Bind(property, call);

    bindings.Add(bind);
}

Is there any pattern that fits my situation or should I structure the code differently? All other code.

public readonly struct TreeField(string name, IEnumerable<TreeField> children)
{
    public required string Name { get; init; } = name ?? string.Empty;

    public IEnumerable<TreeField> Children { get; init; } = children ?? Enumerable.Empty<TreeField>();
}

public sealed class ExpressionHelper
{
    public Expression<Func<TEntity, TEntity>> GetLambdaExpression<TEntity>(IEnumerable<TreeField> fields)
    {
        var parameter = Expression.Parameter(typeof(TEntity));

        var result = GetMemberInitExpression(typeof(TEntity), parameter, fields);

        return Expression.Lambda<Func<TEntity, TEntity>>(result, parameter);
    }

    private MemberInitExpression GetMemberInitExpression(Type type, Expression parameter, IEnumerable<TreeField> fields)
    {
        var bindings = new List<MemberBinding>();

        foreach (var field in fields)
        {
            var property = type.GetProperty(field.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            if (property is not null)
            {
                var propertyType = property.PropertyType;

                if (propertyType.IsPrimitive || propertyType == typeof(string))
                {
                    var memberExpression = Expression.Property(parameter, property.Name);

                    var bind = Expression.Bind(property, memberExpression);

                    bindings.Add(bind);
                }
                else if (type.IsClass)
                {
                    var memberExpression = Expression.Property(parameter, property.Name);

                    var subFieldsInit = GetMemberInitExpression(property.PropertyType, memberExpression, field.Children);

                    var bind = Expression.Bind(property, subFieldsInit);

                    bindings.Add(bind);
                }
                else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    var elementType = property.PropertyType
                        .GetGenericArguments()
                        .FirstOrDefault() ?? throw new InvalidOperationException($"Generic type for collection {property.Name} not founded.");

                    var selectMethod = typeof(Enumerable).GetMethods()
                        .Where(m => m.Name == nameof(Enumerable.Select))
                        .First(m => m.GetParameters().Length == 2)
                        .MakeGenericMethod(elementType, elementType);

                    var lambdaParameter = Expression.Parameter(elementType);

                    var lambdaBody = GetMemberInitExpression(elementType, lambdaParameter, field.Children);

                    var selectLambda = Expression.Lambda(lambdaBody, lambdaParameter);

                    var memberAccess = Expression.Property(parameter, property);

                    var call = Expression.Call(selectMethod, memberAccess, selectLambda);

                    var bind = Expression.Bind(property, call);

                    bindings.Add(bind);
                }
            }
        }

        return Expression.MemberInit(Expression.New(type), bindings);
    }
}

I tried to do this with something like a strategy pattern. But I had a problem with passing

Func<Type, Expression, IEnumerable<TreeField>, MemberInitExpression> memberInit 

into the strategy.

public sealed class BindingContext : IBindingContext
{
    private readonly IEnumerable<IBindingStrategy> strategies;

    public BindingContext(IEnumerable<IBindingStrategy> strategies)
    {
        this.strategies = strategies;
    }

    public MemberBinding Bind(PropertyInfo property, Expression parameter, TreeField field, Func<Type, Expression, IEnumerable<TreeField>, MemberInitExpression> memberInit)
    {
        var strategy = strategies.FirstOrDefault(s => s.AppliesTo(property.PropertyType))
            ?? throw new NullReferenceException($"Binding startegy for {property.PropertyType} not registered.");

        return strategy.Bind(property, parameter, field, memberInit);
    }
}
public sealed class EntityStrategy : IBindingStrategy
{
    public bool AppliesTo(Type type) => type.IsClass && type != typeof(string);

    public MemberBinding Bind(PropertyInfo property, Expression parameter, TreeField field, Func<Type, Expression, IEnumerable<TreeField>, MemberInitExpression> memberInit)
    {
        var memberExpression = Expression.Property(parameter, property.Name);

        var subFieldsInit = memberInit(property.PropertyType, memberExpression, field.Children);

        return Expression.Bind(property, subFieldsInit);
    }
}

What are the Best Practices for Managing Height in Mobile Web with CSS [closed]

What are the CSS standards and best practices for ensuring a mobile web page occupies the entire screen without requiring scrolling? How do these guidelines differ in the context of a PWA application where the presence of an address bar is not anticipated?

Typically, I employ 'height: 100vh' in the body or the main div of my Vue.js components to fill the entire viewport. However, I am unsure if this is the correct practice, as various sources provide differents solutions when I seek answers.

jeudi 30 novembre 2023

how to design a project based system to make so many resource under project?

i want to design a system it is project based system, many resource is organized in project, and the url pattern will like this

  • /projects/{project_a}/dashboard
  • /projects/{project_a}/issues
  • /projects/{project_a}/issues/{issues_id}
  • /projects/{project_a}/users
  • /projects/{project_a}/tasks
  • /projects/{project_a}/tasks/{task_id}/attachments and i do not want to let every controller like ProjectXXXController, and make every jpa query with a where project_id equals xxx clause, how to smart design it? and is multi-tenant pattern a good choose?

a solution for project based system design

How to solve multiple class inheritance without duplicating code in my case?

My concrete classes can be one of the type permutations shown below. But, since I cannot inherit from two classes (case 4 and 5) I had to convert one of them to interface which introduce code duplication shown in FIX section below. I know someone will say "use composition", but I don't see how to change the design to take this into account.

Type permutations:

  1. ControllerSimulator
  2. MovingControllerSimulator
  3. RegistersControllerSimulator
  4. ControllerSimulator + RegistersControllerSimulator
  5. MovingControllerSimulator + RegistersControllerSimulator

CODE

public abstract class ControllerSimulator
{
   protected virtual void OnTurningOn() { }
   public void TurnOn()
   { 
     ...
   }
   
   protected virtual void OnTurningOff() { }
   public void TurnOff()
   { 
     ...
   }

   // more base methods
   ...
}

public abstract class MovingControllerSimulator : ControllerSimulator
{
   public virtual void Disable() { }

   public void SetMotionDuration(TimeSpan duration)
   {
       _motionDuration = duration;
   }

    protected void OnMoveStarted()
    {
       MoveStarted?.Invoke();
    }

    // more base methods
    ...
}

public abstract class RegistersControllerSimulator : ControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }

   // more base methods
   ...
}

FIX

Since I cannot inherit from two classes I decided to convert RegistersControllerSimulator to an interface and create RegistersMovingControllerSimulator and RegistersNonMovingControllerSimulator. But, this requires code duplication which I potentially can solve by moving it to utils.

interface IRegistersControllerSimulator
{
   void UpdateRegister(string regName, object regVal);
}

public abstract class RegistersMovingControllerSimulator : MovingControllerSimulator, IRegistersControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }
}    

public abstract class RegistersNonMovingControllerSimulator : ControllerSimulator, IRegistersControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }
}

public class Concrete_Registers_Moving_Controller : RegistersMovingControllerSimulator
{
    // Uses "await Task.Delay(_motionDuration)" to imitate motion
}

public class Concrete_Registers_NonMoving_Controller : RegistersNonMovingControllerSimulator
{
}

public class Concrete_NonRegisters_Moving_Controller : MovingControllerSimulator
{
    // Uses "await Task.Delay(_motionDuration)" to imitate motion
}

public class Concrete_NonRegisters_NonMoving_Controller : ControllerSimulator
{
}

Java design pattern for mod system(Minecraft mcp)

i'm coding a minecraft client at the moment but I don't know how to write efficient a modular mod system.

Until now I have one superclass called mod and subclasses with the implementation in it and one ModManager class with an ArrayList mods but when I want to get a Attribute from example Mod1 I can't get it like ModManager.getMods().get(Index).attributeName because it's not in Mod. At the Moment I coded it so that these attribute are public static but I think thats not a solution? Is there a better design Pattern or way to implement it?

//Superclass 
package Client.Mods;

import net.minecraft.client.Minecraft;

public class Mod {
    protected Minecraft minecraft;
    private static ModCategory category;
    private static String name = "NoName ERROR";
    private static boolean toggled;


    public Mod(String name, ModCategory category) {
        this.name = name;
        this.category = category;
        toggled = false;
    }

    public void toggle() {
        toggled = !toggled;
        if(toggled)
            onEnable();
        else
            onDisable();
    }

    public void onEnable() {

    }

    public void onDisable() {

    }

    public void onUpdate() {

    }

    public void onRender() {

    }

    public static String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static boolean isToggled() {
        return toggled;
    }

    public void setToggled(boolean toggled) {
        this.toggled = toggled;
    }
}

package Client.Mods;

import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.particles.SimpleParticleType;

public class BetterBowParticles extends Mod{

    public static SimpleParticleType particleType = ParticleTypes.CRIT;

    public BetterBowParticles(String name, ModCategory category) {
        super(name, category);
        particleType = ParticleTypes.ASH;
    }

    public void onRender() {

    }
}

mercredi 29 novembre 2023

Design pattern - json.Unmarshal()

Second argument of json.Unmarshal() api allows passing value of receiver type that implements below interface:

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

json.Unmarshal() under the hood, uses reflect package, to find and invoke UnmarshalJSON() method of the receiver type(as shown below):

u, ut, pv := indirect(v, isNull)
if u != nil {
    return u.UnmarshalJSON(item)
}

Is there a term(design pattern name) for this approach(to inspect receiver type at runtime and invoke methods of that type)?

mardi 28 novembre 2023

Why my pyramid pattern code is not working?

So I tried below code for pyramid pattern and in output pattern first star is getting misplaced.can you tell me why this is happening?

This code I used

This is output i am getting

This is output i am expecting

I tried to develope star pyramid but one star is not getting placed where it is expected in pattern as you can see in above image.

How can I use, in the same project, old and recent python librairies which respectively need old and new python version?

I'm a researcher in cartography and some specific librairies are sometimes only working with python 2.7 while others need python 3.X. I have some projects that need to use multiple of these librairies, and there often are unsolvable conflicts.

For now, I run a first script in a python 2.7 environment (with conda), save the results, activate my 3.X environment (with conda), then run another script which needs python 3.X and loads the previous results.

This is laborious, I would like to automate my workflow but I don't know how to. Any good practices ?

PS: I use miniconda and VScode, but I'm open to other tools.

Best practices for GraphQL in general

What are best practices for designing and implementing GraphQL APIs, considering aspects such as schema design, query optimization, error handling, and security?

How certain practices contribute to improved performance, maintainability, and overall efficiency in GraphQL development. For example, how you would structure your schema to handle nested queries efficiently.

Also what are security concerns by implementing best practices for input validation, authentication, authorization, and protection against common security vulnerabilities. What are robust error-handling strategies within a resolver function that takes security into account?

Design Strategies for Integrating Enroll Plan-Specific Features in a Django Project

I am working on a Django project that comprises three main components:

  1. nkb_assessment_backend: Handles assessments and exams, featuring apps like nkb_exam and nkb_exam_extensions.
  2. nkb_learning_backend: Manages learning-related functionalities including user enroll plans, with apps such as nkb_auth_v2.
  3. nkb_backend: Serves as an overarching layer that possibly integrates or orchestrates functionalities of the above two components.

Requirement: We need to introduce functionality for enroll plan-specific exam slots in the nkb_assessment_backend, where these slots are dependent on user enroll plans managed in the nkb_learning_backend. The challenge is to implement this feature without creating direct dependencies or coupling between the two backend components.

Constraints:

  • Avoid modifications to the nkb_assessment_backend, particularly its database schema or existing models.
  • Maintain a loosely coupled architecture.
  • Ensure the solution is scalable and maintainable.

Question: What are the best practices or strategies to implement this feature within the given constraints and architecture? I am looking for insights or alternative approaches that could efficiently integrate this functionality while maintaining the structural integrity of our Django project.

lundi 27 novembre 2023

Having trouble to design the data pattern in swiftui

I am creating a camera app I have a CameraService which is an ObservableObject and it runs the session. and update some UI according to session status.Then I inject it using .envrionmentObject()

in camera service I have a SettingHolder, which is also an ObservableObject, it inits using the deviceinput variable from the session. It contains the settings status of the camera, users can change it and on screen.

Basically it works like that:

class CameraService:ObservableObject{
   @Published var xxxxxxx
   var settingHolder:SettingHolder?
   func createHolder(){
       settingHolder = SettingHolder(deviceinput)//variable in service
   }
}
class SettingHolder:ObservableObject{
   @Published var focusMode = .lock//view use this to display
   ...
   var input//get from outside
   func changeFocus(){}//using input to change focus
}

But to make the @Published var in SettingHolder can update the view, I have to pass the object from upper view instead of using @EnvironmentObject, and I have use a weird way to init my view

@StateObject var service:CameraService
@StateObject var holder:SettingHolder
    init(service:CameraService){
        self._service = StateObject(wrappedValue: service)
        self._holder = StateObject(wrappedValue: service.settingHolder)
    }

I know it is a bad way using singleton and this post also suggest do not nest the ObservableObject post. But I don't know how to find a better way. So confused about this part.

Decorating class having methods internally calling each other

I have a class IMessageProcessor

public interface IMessageProcessor{
   Task ProcessMessages();
   Task ProcessMessage(Message message);
}

with simplified implementation:

public class MessageProcessor : IMessageProcessor {
   public async Task ProcessMessages(){
      ...
      foreach (Message message in messages){
         await ProcessMessage(message)
      }
      ...
   }

   public Task ProcessMessage(Message message){
      // processing message
   }
}

I have also implemented decorator to be kind of error interceptor/handler:

public class ErrorHandlerDecorator : IMessageProcessor {
   IMessageProcessor decorated;

   public async Task ProcessMessages(){
      try{
         decorated.ProcessMessages();
      }
      catch{
         // exception handling logic
      }
   }

   public Task ProcessMessage(Message message){
      try{
         decorated.ProcessMessage(message);
      }
      catch{
         // other exception handling logic (retries etc.)
      }
   }
}

The problem is when I call ProcessMessages and hitting ProcessMessage method, my decorated ProcessMessage error handling logic is not executed as I call it directly on MessageProcessor instance.

Is this possible to somehow make decorator works when I call some methods internally in decorated class?

Thanks

How to write generic CRUD controller for all entities in golang?

I am creating a Go server using GoFiber to return data from MySQL database. I am using GORM library to save and fetch data from the db. I have 8 entities in total. I have defined model for these entites like this

package models

type Account struct {
    ID        uint      `json:"id" gorm:"primary_key;auto_increment;not_null"`
    Name      string    `json:"name"`
    Company   string    `json:"company"`
    GSTIN     string    `json:"gstin"`
    AccountNo string    `json:"accountNo" gorm:"unique"`
    IFSC      string    `json:"ifsc"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`
}

Now, for each entity, I am writing 4 controller methods: Create, Update, List, Delete. It is basically the same code for each entity, just that the entity name is changing.

package controllers

// GET: List call
func GetAccounts(c *fiber.Ctx) error {
    accounts := new([]models.Account)
    result := database.DB.Find(accounts)
    if result.Error != nil {
        return result.Error
    }
    c.SendStatus(http.StatusOK)
    return c.JSON(accounts)
}

// POST
func CreateAccount(c *fiber.Ctx) error {
    account := new(models.Account)
    err := c.BodyParser(account)
    if err != nil {
        return err
    }
    result := database.DB.Create(account)
    if result.Error != nil{
        return result.Error
    }
    return c.SendStatus(http.StatusCreated)
}

Now, like this, I have written 8 x 4 =32 controller methods. All having duplicate code with just the entity name changing.

I have defined routes for each of these controllers manually as well.

    app.Post("api/account", controllers.CreateAccount)
    app.Get("api/accounts", controllers.GetAccounts)

There is definitely a better way to do this. I am not exactly sure how to do so or implement it. What interfaces should I define, what structs should I embedd, or what to do?

Looking for design pattern for flexibile generic serialization

I have a header-only library that provides three class (templates), namely

  • an abstract DAGNode,

    struct DAGNode;
    using NodePtr = std::shared_ptr<DAGNode>;
    
    class DAGNode 
    {
    public:
        virtual ~DAGNode(){}
        virtual std::string serialize() const = 0;
    
        auto const& get_parents() const {
            return m_parents;
        }
     protected:
        std::vector<NodePtr> m_parents;
    };
    
  • non-abstract class template impl::Derived<T>, which is derived from DAGNode and which is not part of the libraries API and

    // this needs to be specialized by consumer
    template <typename T>
    std::string serialize(T const&) {
        throw std::logic_error("Not implemented.");
    }
    
    namespace impl {
    
    // not part of the librarys API
    template <typename T>
    class Derived : public DAGNode 
    {
    public:
        Derived(T const& t) : m_value(t) {}
    
        std::string serialize() const override final
        {
            return ::serialize(m_value);
        }
    
        void add_parent(NodePtr const& ptr) {
            m_parents.push_back(ptr);
        }
    
    private:
        T m_value;
    };
    
    } // namespace impl
    
  • class template DerivedHolder<T>, which stores a std::shared_ptr<impl::Derived<T>>, which is part of the libraries API.

    
    template <typename T>
    class DerivedHolder
    {
    public:
        DerivedHolder(T const& t) : m_node(std::make_shared<impl::Derived<T>>(t)) {}
        NodePtr holder() const 
        {
            return m_node;
        }
    
        void add_parent(NodePtr const& p) {
            m_node->add_parent(p);
        }
    private:
        std::shared_ptr<impl::Derived<T>> m_node;
    };
    

In the current design, DAGNode has a virtual method std::string serialize() const. Derived<T> final overrides this method and delegates to the function template template <typename T> std::string ::serialize.

A consumer of this library will have to specialize the ::serialize function template for whatever types it wants to use. A typical usage scenario is that the consumer will use the visitor pattern to iterate over all DAGNodes and call the virtual serialize method.

Here is a minimal complete code example.

This approach works well, but I have now come across a use-case, where a consumer of this library needs to replace template <typename T> ::serialize with its own "magic implementation" along the lines of:

template <typename T>
std::string magic_serialize(T const& t) 
{
    if constexpr (std::is_same_v<T, MyMagicClass> ) {
        return t.as_string();
    } else {
        MagicClass m(t);
        return m.as_string();
    }
}

Since magic_serialize is in no way more special than ::serialize, specialization won't do the trick.

Therefore, we need to change the design pattern of the serialization framework of the header-only library. We are free to change any part of the library including the API, though I would prefer any minimally invasive solution over a complete rewrite. We are restricted to C++17 for now.

How can I change the library in such a way, that the consumer has complete control over how any type is to be serialized?

Is a "delayed reference" a known programming pattern?

I'm trying to understand JZZ's API.

One of the pecularities is after you obtain a port (a place to send MIDI instructions to), you can do this:

const a = port.noteOn(0, 'C5', 127); // plays note immediately, a is Promise that returns port
const b = port.wait(500); // b is a Promise that returns an object like port

port.noteOn(0, 'E5', 127); // plays note immediately
b.noteOn(0, 'G5', 127); // plays note in 500ms

The documentation says:

wait()

object.wait(delay) - returns a "delayed reference" of the object.

delay is the timeout in microseconds.

Is this "delayed reference" a known programming pattern? I haven't come across it.

dimanche 26 novembre 2023

Print the following pattern in JAVA [closed]

Question here. Print the following pattern

I tried using the nested loops but couldn't succeed. Please help me

I need to submit this assignment immediately please help someone please. I have tried using various methods but couldn't solve this.

samedi 25 novembre 2023

Creating a service layer with Django Rest Framework

I am fairly new to web-development and just studing design patterns and code architecture. Now, I am developing service layer for business logic. And here I have a dillema. One approach is to use command design pattern. Where I have a class which implements user creation and related processes (e.g. sending email, writting logs etc), also this class has one public method (entry point) and private methods, called inside the entry point. Here is the example of what I mean.

class CreateUser:
    def _create_user(self, **data) -> User:
        # here perform creation of user itself, requesting repository layer
        ...

    def _send_email(self, **data) -> None:
        # here I send email

    def _write_logs(self, **data) -> None:
        # writing logs to a file

    def execute(self, **data):
        self._create_user(**data)
        self._send_email(**data)
        self._write_logs(**data)

On the other hand, there is a approach where I create a common service as a class, that handles user authentication and registration and for each user action has one method:

class UserService:
    def create_user(self, **data) -> User:
        # call to repository
        # send email
        # write logs

    def update_user(self, **data) -> User:
        # call to repository
        # write logs

I don't really know what solution I should choose. I suppose that the command pattern is better, however I'm not sure about more complex scenarious. And throughout the project (or application), should I stuck to one design pattern (e.g. the command) or it's okay to alternate them? Maybe there are other approaches?

Sorry if my question seems silly, I am newbie and I feel lost among so much information (especially clean code patterns), so I am looking for help. Thanks in advance.

Seeking Advice on Optimizing Electrical Field Simulation App, Considering Transition to Python with Flet for Improved Efficiency

I developed a Java/JavaFX app that simulates the electrical field strenght of a cable as a 2D Heatmap (Image_Nr_1). The goal is for users to visually grasp the field distribution in their space.

Here's my current solution: I created a 2D array mirroring the canvas dimensions. Each cell holds an electrical field strength value, visualized by color. After the user draws a line (inputs: x_start, y_start, x_end, y_end, angle), I calculate local field values, add them to the global matrix, and update the canvas (Image_Nr_2). Unfortunately, the update causes significant lag.

Due to code complexity, bad design and inefficiency, I'm planning a rewrite. I'm considering switching to Python with Flet, using libraries like pandas and pycairo.

I thought of three ways of how I could improve the current algorythm design:

Option 1: Use pandas to operate similarly to my current method in the backend, however, create a local matrix for each device ( Image_Nr_3). This seems feasible, with SVG output facilitating device movement and being considerably smaller than JPEG/PNG in this case(as in theory only the min values of each color zone would need to be traced with a path fill or so). However, implementing multiple devices (Image_Nr_4) might be a challenge. This solution would work well when using Flet, as i could then add/remove a gesturedetector container for each new device added to the Canvas

Option 2: Stick with the matrix uptdating approach. Yet here would be the question of how can I selectively update only the changed part of the image in Flet, without replacing the entire image everytime a change has been made to the canvas?

Option 3: Combine both approaches — use a background image to display values for heat map in raster or (ideally) vector graphic format and provide individual gesturedetector containers, which would contain the black device line, for device manipulation. This requires addressing issues from both options.

I've been working on solving the above mentioned issues and have been experimenting with Flet and python. The first approach works, but not yet for overlapping heatmaps (as mentioned as the issue in the first approach). The second approach also partly works, but only by updating the entire image in the Flet Container.

Further, I have looked into libraries such as geopandas, as this is in theory exactly what I want -> would need to draw the polygons depending on the shape of the current heatmap.

I am seeking advice on the most efficient approach and potential solutions for handling multiple devices. Any insights are greatly appreciated!

vendredi 24 novembre 2023

handle methods in a class calling shared sub-methods with varying order and frequency in Java/Kotlin

How can I implement multiple methods in a Java/Kotlin class that invoke the same sub-methods but in a different order, or sometimes a method calls more sub-methods than another? Is there a design pattern for this scenario?

                  +------------------+
                  |   My Class       |
                  +------------------+
                           |
            +--------------+--------------+
            |                             |
 +------------------+         +------------------+
 | Method A         |         | Method B         |
 +------------------+         +------------------+
 | Call SubMethod 1 |         | Call SubMethod 2 |
 | Call SubMethod 2 |         | Call SubMethod 1 |
 | ...              |         | ...              |
 +------------------+         +------------------+
                

  +------------------+         +------------------+
  | SubMethod 1      |         | SubMethod 2      |
  +------------------+         +------------------+
  | Implementation   |         | Implementation   |
  | ...              |         | ...              |
  +------------------+         +------------------+

but i have a lot number of methods to implement on the same class.

Java : generics, inheritance and best design

I have a basic processing interface :

public interface Processing<T> {
    void appendTo(T t);
}

And this inheritance tree :

public class Animal {
}

public class Dog extends Animal {
    public void forDog() {}
}

public class Cat extends Animal {
    public forCat() {}
}

It's about processing animals. I have two solutions. Which one is the best pattern ?

SOLUTION A (with generics) :

public abstract class AbstractProcessing<T extends Animal> implements Processing<T> {
    protected void internalAppend() {}
}

public class CatProcssing extends AbstractProcessing<Cat>{

    @Override
    public void appendTo(Cat cat) {
        cat.forCat();
        internalAppend();
    }
}

public class DogProcessing extends AbstractProcessing<Dog>{
    
    @Override
    public void appendTo(Dog dog) {
        dog.forDog();
        internalAppend();
    }
}

SOLUTION B :

public class AnimalProcessing implements Processing<Animal>{
    @Override
    public void appendTo(Animal animal) {
        if (animal instanceof Cat cat) {
            cat.forCat();
        } else if (animal instanceof Dog dog) {
            dog.forDog();
        } else {
            throw new IllegalArgumentException();
        }
        internalAppend();
    }

    private void internalAppend() { }
}

jeudi 23 novembre 2023

Django Model Structure for products with Multiple Categories

I want to know if it is possible (and if so, what is the most pythonic way) to have a product that belongs to multiple product categories. e.g. an avocado belonging to [Food->Fresh Food->Fruit & Vegetables->Salad & Herbs] as well [Food->Pantry->Global Cuisine->Mexican]?

I am currently using Django-MPTT to create the category tree for single-category products. How do I set up the Product and Category models, what would the data import look like, and what would an efficient query look like? I am open to any suggestion, even if it requires me to rewrite my project. I would appreciate ANY advice on anything to do with this problem.

I am currently using Django-MPTT to create the category tree for single-category products. It makes sense conceptually, but I'm struggling with the multiple-category tree.

I've found some examples of TreeManyToManyField

class Category(MPTTModel, CreationModificationDateMixin):
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            blank=True,
                            null=True)
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['tree_id', 'lft']
        verbose_name_plural = 'categories'


class Product(CreationModificationDateMixin):
    title = models.CharField(max_length=255)
    categories = TreeManyToManyField(Category)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'movies'

but there are no explanations or examples of import/creating data for such a model. I have also seen the following example of how to set up the Category model, but they use a BaseProduct which threw me off:

class CategoryProductBase(BaseProduct):
    main_category = TreeForeignKey(get_category_model_string('Category'))
    additional_categories = TreeManyToManyField(
        get_category_model_string('Category'),
        related_name='extra_product_categories')

Best Practices for Retrieving Selective Data from a Database in a RESTful API

I am currently working on designing a RESTful API that interacts with an SQL database containing a 'Users' table. The example 'Users' table has fields such as AccountID, Username, Password, Firstname, Lastname, Email, Text, Setting1, Setting2, and Setting3.

In the services layer of my application, I have implemented getters and setters for Email, Text, Setting1, Setting2, and Setting3. Additionally, there are getters for Firstname and Lastname (but no setters).

The challenge I am facing is how to efficiently retrieve data from the database when the server code calling these services requires selective fields to perform various operations, while maintaining seperation of the business/services logic from the SQL statements (which exist in data gateway classes). For instance, one part of the code may need Firstname, Setting1, and Setting2, while another part may only need Lastname and Setting3.

I've considered two potential solutions:

  1. Sequential Field Queries: Query each field independently and in sequence. For example, first query for Firstname, then Setting1, and finally Setting2.

  2. Retrieve All Fields: Query all fields and retrieve the necessary data, ignoring the unused fields based on the requirements of the client code.

I am seeking guidance on the following:

  • Best Practices: How is this problem typically solved in the design of RESTful APIs?

  • Pros and Cons: What are the advantages and disadvantages of each method (sequential queries vs. retrieving all fields)?

  • Alternative Solutions: Are there alternative approaches or best practices for efficiently handling selective data retrieval in a scenario like this?

For a code example, the services/business logic functions look like this:

  getUserEmail(userId: number): string {
    // Implement logic to retrieve user email using the database gateway
  }

  setUserEmail(userId: number, email: string): void {
    // Implement logic to update user email using the database gateway
  }

  // Implement similar functions for other fields

  loginUser(username: string, password: string): boolean {
    // Implement logic to check if the provided username and password match a user, using the database gateway
  }

  getUserFirstname(userId: number): string {
    // Implement logic to retrieve user's firstname using the database gateway
  }

  getUserLastname(userId: number): string {
    // Implement logic to retrieve user's lastname using the database gateway
  }

The database gateway class looks like this:

interface UserTableGateway {
  // CRUD Operations
  createUser(user: User): void;
  readUser(userId: number): User | null;
  updateUser(user: User): void;
  deleteUser(userId: number): void;

  // Additional Query Operations
  getUserByEmail(email: string): User | null;
  getUserByUsername(username: string): User | null;
}

I appreciate any insights, experiences, or recommendations that you can provide. Thank you!

mercredi 22 novembre 2023

Java Factory pattern

java spring boot : i have module A and module B each one have some specific services and i have a module c that don't have any dependencies to A and B so what i want is in module C i want to call services from module A or B i want to acheive that using factory pattern.

in module C i have this interface

public interface ThirdPartyCallsStrategy {
    void apply(String orderId);
}

and this is example of factory class

@Component
@AllArgsConstructor
public class CoreCallsFactory {

    private static final String A_PACKAGE = "com.testA.service";
    private static final String A_CLASS = "TestClassA";


    private static final String B_PACKAGE = "com.testB.service";
    private static final String B_CLASS = "TestClassA";


    @SneakyThrows
    public ThirdPartyCallsStrategy createThirdPartyCallsStrategy(String type) {

        Class<?> clazz;
        if (type.equals("A")) {
            clazz = Class.forName(String.format("%s.%s", A_PACKAGE , A_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }

        if (type.equals("B")) {
            clazz = Class.forName(String.format("%s.%s", B_PACKAGE , B_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }
        return null;
    }
}

ThirdPartyCallsStrategy is implemented in different services in different modules

And finally in module C, i make the instanciation through java reflective but this will be at runtime and i really appreciate cleaner way

`public String checkStatusAndRedirect(String orderId, String type) { boolean status = checkStatus(orderId); StringBuilder paymentResultUrl = new StringBuilder(frontUrl + "/public/payment/status?success=");

    if (status) {
        coreCallsFactory.createThirdPartyCallsStrategy(type).apply(orderId);
        paymentResultUrl.append(Boolean.TRUE);
    } else {
        paymentResultUrl.append(Boolean.FALSE);
    }
    return paymentResultUrl.toString();
}`

So what i need is a clean way and change this implementation

How can I "augment" a JS class with methods from another class, without extending it?

I'm writing an app that manages playlists. Basically, my actual logic looks like

//define playlist props
class Playlist{
    public tracks = [];
}

class ApiPlaylist extends Playlist{
    //fill playlist withs (single page) data from API
    public async loadPage(paginationSettings){
        const pageTracks = await...
        this.tracks = [...this.tracks,...pageTracks]; //concat tracks
    }
}

class Paginated extends ApiPlaylist{
    private iterations = 0;
    private endReached = false;
    public async loadAll(){
        while (!this.endReached){
            this.loadNext();
        }
    }
    public async loadNext(){
        this.iterations++;
        await this.loadPage(); //call ApiPlaylist method
        if(...){
            this.endReached = true; //stop iterating
        }
    }

}

const playlist = new Paginated();
playlist.loadAll();

It works.

But what if I have different others paginated datas to get, that are not related to playlists ?

I would like to use the mechanism from PaginatedPlaylist with another classes, without having to duplicate it.

Acually, Paginated extends ApiPlaylist. Is there a simple way to implement the methods from Paginated to ApiPlaylist without using extends ?

Something like

class ApiPlaylist [implements] Paginated{}
class ApiPost [implements] Paginated{}
class ApiPage [implements] Paginated{}

Thanks for your help !

mardi 21 novembre 2023

Shell Script Design Patteren: Source a library file VS Call different files?

We discuss about POSIX compliant shell script here.

While we are writing more and more shell scripts, we build some helper functions to reuse the codes.

We are considering putting a few helper functions (around 10 functions of the same category) into a library file (e.g. string_lib.sh) or splitting each functions into individual script files (e.g. str_replace, str_cmp, etc.) to be called directly.

Due to the potential problem of variable name collision, we lean towards splitting each functions into individual script files. But there will be more than a hundred of script files, which is hard to manage.

We understand in some cases, we do not have a choice to choose between these two.

  • If we need to pass (several) variables from functions back to the caller, we must use a library file and sources it, as they need to share the same variable scope. (Using text file to pass variable is not preferred in most cases.)

  • If we would just like to avoid one script file being too long, split it into different sections and source them sequentially. In this case they usually need some shared variables (e.g. setting variables).

In other cases, these would be the pros and cons comparison.

Grouping helper functions into library files:

  • (o) The library file will be sourced (by . string_lib.sh).
  • (+) Same category of functions written in same file. Easy to manage.
  • (-) Possible of variable name collision.
  • (-) Need to avoid double inclusion, or mutual recursive inclusion which will cause infinite loop.
  • (-) Too many inclusion may slower the script. If only a few functions are used within a library file, other function definitions are redundant.

Split functions into individual script files:

  • (o) The script files will be called directly, just like Linux programs.
  • (+) No need to source (i.e. .) before use. Just put all the scripts into the $PATH directory.
  • (+) Unnecessary functions are not sourced. Possibly faster loading.
  • (+) Called script is in a different shell, the sub-shell. No worry of variable name collision. (Similar concept as Java, C, etc.)
  • (-) One helper function will have one script file. There will be many script files. This is harder to manage.

There is another SO answer about bash design patterns and best practices. Especially Stefano Borini's Modularization section is inspiring. Its import function is smartly written. Do take a look when you need to source script files. However in that SO post, it did not compare between grouping functions into a library file versus splitting functions into individual files.

https://stackoverflow.com/a/739034/1884546

Are there any guidelines or recommended design patterns of shell scripts?

Golang project structure

Project strcture

project-root-directory/
├── internal/
│ ├── session/
│ │ ├── runner/
│ │ │ ├── null.go
│ │ │ ├── runner.go
│ │ │ ├── sql.go
│ │ │ └── source/
│ │ │ ---├── mysql.go
│ │ │ ---├── sql.go
│ │ │ ---└── source.go
│ │ └── cache/
│ └── database/
│ ---├── database.go
│ ---└── mysql.go

Interfaces:

database source runner

The main functionality revolves around 'runner' and 'source', with 'mysql' as the implementation. There will also be 'mysql' used for storage, so I want to clearly distinguish between when I'm calling storage and when I'm calling the database.

I've been adjusting the structure for two days now.I plan to add many more runners and databases.

I'm considering creating subfolders inside 'runner', but the structures they implement are 'runner'. It might become confusing, especially since I'll be using 'mysql' for storage as well. and I really dont want it to be called as mysql.Mysql and prefer it will be called runner.Mysql.

But I am afraid of a large package size but I really dont want sttr mysql.Mysql for each struct

Someone suggested """ I would create a runner repository inside the internal/session/runner (same for source)

Then implement the repository somewhere inside internal/mysql/runner.go and internal/mysql/source.go

"""

TBH I think it will problay what I will do

lundi 20 novembre 2023

Flutter: How to listen/get characteristic of a Text widget?

So, I am trying to make a border/stroke effect for Text widget using Stack and Positioned.

class BorderedText extends StatelessWidget {
  BorderedText({
    super.key,
    required this.text,
    required this.textSize,
    this.borderTextSize,
    required this.textColor,
    required this.borderTextColor,
  }) {
    borderTextSize ??= getBorderTextSize(textSize);
  }
  final String text;
  final double textSize;
  double? borderTextSize;
  final Color textColor;
  final Color borderTextColor;

  double getBorderTextSize(double textSize) {
    return textSize * 1.1;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          child: Text(
            text,
            style: TextStyle(
              color: borderTextColor,
              fontSize: borderTextSize,
            ),
          ),
        ),
        Positioned(
          top: (borderTextSize! - textSize) * 0.5,
          left: (borderTextSize! - textSize) * 0.2,
          child: Text(
            text,
            style: TextStyle(
              fontSize: textSize.toDouble(),
              color: textColor,
              letterSpacing: (borderTextSize! - textSize) * 0.45,
            ),
          ),
        ),
      ],
    );
  }
}

In some cases like textSize >= 70, the border text overflows. How do I listen to the overflow of that text widget and apply the same to the top text ?

Best way of handling two endpoints that depend on each other

I have two endpoints. The first endpoint generates a png image with matplotlib. The second endpoint generates a list of points (x, y coordinates in pixels). The frontend will then display the image as well as the x, y points and the user will be able to hover over the x,y points and view data.

The setup is:

  1. /endpoint1 -> returns svg/png
  2. /endpoint2 -> returns something like
{
   name1: {
     coords: [203, 3204],
     other_field: true,
   },
   name2: {
     coords: [509, 320],
     other_field: false,
   }
}

The issue is that the x, y points shift depending on the requested parameters of the image. For example, if the user requests a different image layer of the same image, the image ends up being shifted a bit and the points change. To generate the points, I would need to replicate a lot of the work to generate the image. Therefore, it makes a lot of sense to just return the points and image together. However, this is a lot of work for one endpoint and I'm wondering if there is a better way to handle this or if this design is considered good/okay?

Viable solution to handling long running query in Java

I have a Spring API which invokes rest call to an enterprise payment platform which calls into JPM Chase. All is fine on that and when taken we save response in our SQL Server DB. Our Spring API is new solution which went live last week into production. For most part has been working well apart with decent response times apart from 3 instances. On 3 different days around same timeframe I spotted through datadog an instance of processPayment endpoint taking over 1 min to respond.

After looking at DataDog logs its easy to spot SQL Query where the issue occurs. However having gone through datadog metrics around this query it typically executes in under 40 milli-seconds. The select query is hitting one table which has clustered + non clustered indexing on table. I don't believe there is an issue here however there obviously is some locking happened on DB at this time occurred maybe not at application level could been DB script being executed to fix data. So question really here is around how application should behave:

  1. Should the API be altered in such a scenario to rollback payment OR Just wait for query to return and capture the response in DB
  2. Is there another viable idea?

dimanche 19 novembre 2023

Is this UML diagram violating the Interface Segregation Principle?

I have created this UML diagram which applies the Template method design pattern: UML diagram

Both concrete classes share a lot of the logic whithin the template methods createTask and completeTask, with small variations for each concrete implementation, so I went for the Template method design pattern. However, one of the concrete classes does not need validation, so it implements the abstract method performValidations as an empty void method.

Is this violating the Interface Segregation Principle? Or would it be OK in this situation to leave the implementation of this abstract method in the concrete class empty?

samedi 18 novembre 2023

Java multiple datastores return same model

I am trying to solve a multiple data source issue where I need to return the same data model regardless of its source. The multiple data sources are all within their own module with correctly configured beans and config etc... (Redis, JPA, and a Rest-based module), they are all working and return their own respective models currently with associated annotations/validations for the given data source (here lies the issue in terms of why not just re-use the same model class from a common module, we cant as we have loads of logic tied up in their respective annotations).

I could upcast and return the interface, but ideally, I would be able to return the DataModel instead as that is what other applications currently code to alongside its ToString, equals, etc... I could also manually transform and map each field to the data model but I feel like there is some sort of pattern that would help me solve this problem.

So I started to look into the proxy pattern to solve this but the more I read about it the more I think it's not the correct one to follow as i would still end up having to cast etc... Are there any patterns that would help me solve this issue? or should I just upcast and return the interface each time from each resource?

Any advice would be appreciated as I think I am misunderstanding some basic concepts.

Project structure

//Not the exact impl, but you see the idea...

Main app

public interface IFetchData {
 Optional<List<DataModel>> fetchAll();
} 

public class FetchData implements IFetchData {
 private IRedisAccess redis; 
 private IJPAAccess jpa; 
 private IRest rest; 

 public FetchData(IRedisAccess redis, IJPAAccess jpa IRRest rest) {
  this.redis = redis;
  this.jpa = jpa;
  this.rest = rest;
 } 

 public Optional<List<DataModel>> fetchAll() {
  List<DataModel> data;
  data = redis.fetchAll();
  //if not null statement return Optional.of(data);
  data = jpa.fetchAll();
  //if not null statement return Optional.of(data);
  data = rest.fetchAll();
  return Optional.of(data);
 } 
  //more methods for interacting with data interfaces...
} 

Module common

public interface IDataGeneric {
 getId();
 getOtherField1();
} 

@Getter
public class DataModel implements IDataGeneric {
 private long id;
 private String OtherField1;
} 

Module Redis

@Getter
@RedisHash
public class DataModelRedis implements IDataGeneric {
 @Id
 private long id;
 @Index
 private String OtherField1;
}

public interface IRedisAcess{
 Optional<DataModelRedis> fetchId(long id);
 Optional<List<DataModelRedis>> fetchAll();
} 

public class RedisAccess implaments IRedisAcess {
 private RedisRepo redisRepo; 

 public RedisAccess(RedisRepo redisRepo) {
  this.redisRepo = redisRepo;
 } 
 methods for interacting with RedisRepo ...
} 

@Repoistory
public interface RedisRepo extends CrudRepository<DataModelRedis, long>{
 Optional<DataModelRedis> fetchId(long id);
 Optional<List<DataModelRedis>> fetchAll();
} 

Module JPA

@Getter
@Table
@Entity
public class DataModelJPA implements IDataGeneric {
 @Id
 @GeneratedValue
 private long id;
 private String OtherField1;
} 

public interface IJPAAccess{
 Optional<DataModelJPA> fetchId(long id);
 Optional<List<DataModelJPA>> fetchAll();
} 

public class JPAAccess implements IJPAAccess {
 private JPARepo jpaRepo; 

 public jpaAccess(JPARepo jpaRepo) {
  this.jpaRepo = jpaRepo;
 } 
 methods for interacting with jpaRepo ...
} 

@Repoistory
public interface JPARepo extends JPARepository<DataModelJPA, long>{
 Optional<DataModelJPA> fetchId(long id);
 Optional<List<DataModelJPA>> fetchAll();
} 

Filtering inside a processing method vs. filtering outside

In my application I am processing a List of IMyInterface instances. Not all, but some of them in addition also implement IAnotherInterface. Note that IAnotherInterface not derives from IMyInterface. Following the Single Responsibility Principle, I have a separate class that processes the IMyInterfaces instances via a Process method. Now I am struggling with the design choice whether

  1. the signature should be Process(IEnumerable<IMyInterface> items) and I filter for IAnotherInterface inside this method
  2. or the signature should be Process(IEnumerable<IAnotherInterface> items), meaning the filtering has to be done outside the processing method by the "client".

To make it more clear, these are the two code options I am struggling between:

// alternative 1:
List<MyInterface> items = GetItems(); // code not shown here
foreach(var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IMyInterface> items)
    myProcessor.Process(items);                
            
    // do some other processing afterwards, not shown here
}

// or alternative 2:
List<MyInterface> items = GetItems(); // code not shown here
foreach (var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IAnotherInterface> items)
    // -> need to filter first
    var filteredItems = filterForIAnotherInterface(items);
    myProcessor.Process(filteredItems);

    // do some other processing afterwards, not shown here
}

Is there any good reasoning for choosing one over the other? My own thoughts are that alternative 1 is easier to use for the client, but then the Process method has to do filtering which adds some kind of an additional responsibility besides it's main responsibility. On the other hand, alternative 2 in some way makes the processing pipeline less readable I think.

vendredi 17 novembre 2023

How do you connect 2 diferent languages or more [closed]

It may sound silly but Im a beginner and still trying to learn more. Many websites now days use many languages in their backend and frontend, such as python, C# for database and others. How do you connect 1 and another programming languages, like for an example if a user click the login button, it will trigger the javascript function and do lookup in the database with python or C# for an example, How do you guys connect that 2 different languages?

I've read and watch several things but still curious

How can I add pattern in only one color ggplot?

How can I manually choose colors to my pallete and also create a pattern in only one color? (I want transparent to be white color with some lines to differentiate from white color).

ggplot(mp8, aes(x = total, y = shape, fill = color)) +
geom_col(position = "fill") +
geom_col(colour = "black", position = "fill") +
scale_x_continuous(labels = scales::percent) +
coord_flip()

ggplot

Is there an advantage to hiding the model layer?

I was looking at a tutorial on the MVVM architecture pattern.

It says that views should never have direct access to the model. So all views are always hidden behind a view model.

For example:

Model

struct Location: Codable, Equatable {

//MARK: Properties

let id: String
let name: String
let country: String

//
let latitude: Double
let longitude: Double

init(id: String, name: String, country: String, latitude: Double, longitude: Double) {
    self.id = id
    self.name = name
    self.country = country
    self.latitude = latitude
    self.longitude = longitude
}
}

View Model that hide the model layer

final class LocationCellViewModel: Identifiable {

//MARK: Properties

private let location: Location

//
var locationViewModel: LocationViewModel {
    .init(location: location)
}

// MARK: - Initialization

init(location: Location) {
    self.location = location
}

// MARK: - Public API

var locationName: String {
    location.name
}

var locationCountry: String {
    location.country
}

....

}

View Model that will be in the view as property

final class LocationsViewModel {

//MARK: Properties

private(set) var locationCellViewModels: [LocationCellViewModel] = []

   ....

 }

Why might it be better to have a LocationCellViewModel array instead of a Location array in the LocationsViewModel class? Is there any advantage to doing so?

jeudi 16 novembre 2023

HTML5 phone number validation with pattern 1-XXX-XXX-XXXX

I want phone number to be in either two formats

xxx-xxx-xxxx

or

1-xxx-xxx-xxxx

if there is area code , it should be 1

can anyone help me with reg required pattern ?

thanks in advance

tried all possible way but no luck . please help

create include dependency graph for non-header files

In my project i have .c and .h files. But also other file extensions (e.g. .abc) that could have an include statement like

#include "common.h"

So they can be seen like normal headers. I have added ".abc" in the FILE_PATTERNS as "*.abc". But it is ignoring them and does not parse them. Any help?

Command pattern design in Spring

I have more or less implemented the command pattern in my Spring Boot application. I still have some doubts and would like to get second opinion on them.

I have a CommandFactory which - when given a command code - returns an instance of command object that implements Command functional interface and has a single method called execute.

Here's an example of use:

  • PersonService:
public Person addChildToPerson(Long personId, Long childId) {
    // acquire a person object from the database given an id
    Person person = (Person) commandFactory.create(GET_PERSON_BY_ID, personId).execute();
    // do the same with child
    Child child = (Child) commandFactory.create(GET_CHILD_BY_ID, childId).execute();
    return (Person) commandFactory.create(ADD_CHILD_TO_PERSON, person, child).execute();
}

Now here's the code of a AddChildToPersonCommand class that is responsible for attaching the child to the person and persisting it in the database.

  • AddChildToPersonCommand:
@RequiredArgsConstructor
public class AddChildToPersonCommand implements Command {

     // declare needed components for performing the command
     private final ChildRepository childRepository;
     private final Person person;
     private final Child child;

     @Override
     public Person execute() {
         // some logic
     }
}

Now, my doubts are mainly concerned with the "declared components" for the execution of a command. I'm unsure whether it's a better practice to operate on the actual objects that have been already retrieved using other commands (in the example: GetPersonByIdCommand & GetChildByIdCommand) or to just give the AddChildToPersonCommand the IDs and let it take care of the rest.

On the one hand, it seems a better approach to operate on the objects as it decreases the responsibilites of AddChildToPersonCommand.

On the other hand, though, the PersonService's methods may end up really big when the logic to-be-performed is not as trivial as in this example.

What do you think?

How to prevent coupling between our code and third party libraries?

Imagine we want to use the following library like this:

use GrahamCampbell\GitHub\GitHubManager;

class Foo
{
    private GitHubManager $github;

    public function __construct(GitHubManager $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->issues()->show('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Does it makes sense to create an interface like:

interface GitHubManagerInterface
{
    public function showIssues(): array;
}

Then implement it and bind the implementation to the interface and use it in my code like the following?

class Foo
{
    private GitHubManagerInterface $github;

    public function __construct(GitHubManagerInterface $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->showIssues('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Or there is a better way to prevent coupling? Or it's over engineering? :)

mercredi 15 novembre 2023

How do I implement a paypal checkout button, given the design patterns that I used in my application?

I followed a long tutorial, and built my application side by side using the design patterns from the turorial. I am now stuck, as I don't know how to implement paypal within the scheme I'm using. I used rxjs and observables to build the app, and admittedly I don't really understand them well. Sorry if this is vague, I don;t know what else to do. The paypal implementation is as follows...

This is the code I do not understand how to implement.

TS file

export class DeposittestComponent implements OnInit {
  

  PAYPAL_CLIENT_ID: string = '##################';

  myAmount: any

@ViewChild('paypalRef', { static: true }) private paypalRef!: ElementRef;

ngOnInit(): void {

  this.renderPaypalButton();

  }

  renderPaypalButton() {
    let orderRef: string | null = null;


    loadScript({ "clientId": this.PAYPAL_CLIENT_ID, currency: 'USD' })
      .then((loadedPaypal) => {
        if (loadedPaypal) {
          const paypal: PayPalNamespace = loadedPaypal;
          paypal.Buttons({
            style: {
              layout: 'vertical',
              color: 'blue',
              shape: 'rect',
              label: 'paypal',
            },
            createOrder: (data, actions) => {
              const postData = {
                amount: this.myAmount
              };
              return fetch(AppSettings.API_ENDPOINT + '/user/create_paypal_transaction', {
                method: "post",
                headers: {
                  'Accept': 'application/json, text/plain, */*',
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify(postData)
              })
                .then((response) => response.json())
                .then((response) => {
                  orderRef = response.orderRef;
                  return response.id;
                });
            },
            onApprove: (data, actions) => {
              return fetch(AppSettings.API_ENDPOINT + `/user/orders/${data.orderID}/capture`, {
                method: "post",
                headers: {
                  'Accept': 'application/json, text/plain, */*',
                  'Content-Type': 'application/json',
                },
              })
                .then((response) => response.json())
                .then((orderData) => {
                  const errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                  if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                    return actions.restart();
                  }
                  const transaction = orderData.purchase_units[0].payments.captures[0];

                  this.paypalRedirect(transaction.status, orderRef);
                });
            },
            onCancel: () => {
              // 
            },
            onError: (err) => {
              this.paypalRedirect('ERROR', orderRef);
            }
          }).render(this.paypalRef.nativeElement);
        } else {
          console.error("");
        }
      })
      .catch((error) => {
        console.error("", error);
      });

  }

  paypalRedirect(status: string, orderRef: string | null) {
    switch (status) {
      case 'COMPLETED':
        if (orderRef) {
          //this.router.navigate(\['/result/success/' + orderRef\]);
        } else {
          console.error("");
        }
        break;
      case 'ERROR':
        if (orderRef) {
          //this.router.navigate(\['/result/error/' + orderRef\]);
        } else {
          console.error("");
        }
        break;
      default:
        console.error("");
        break;
    }
  }

HTML

<div class="form-group">
                <label>Amount</label>

                <input type="text" ngModel name="myAmount" (ngModelChange)="myAmount=$event"
                    value="$" class="form-control">
            </div>

            <div #paypalRef></div>

This is the design pattern of everything else I have done in the application.

TS

export class NewGameAccountComponent implements OnInit {
 
  newGameAccountState$: Observable<State<CustomHttpResponse<any>>>;
  private dataSubject = new BehaviorSubject<CustomHttpResponse<any>>(null);
  private isLoadingSubject = new BehaviorSubject<boolean>(false);
  isLoading$ = this.isLoadingSubject.asObservable();
  readonly DataState = DataState;
  

  constructor(private gameAccountsService: GameAccountsService) { }

  ngOnInit(): void {
    this.newGameAccountState$ = this.gameAccountsService.activeGameAccounts$()
      .pipe(
        map(response => {
          console.log(response);
          this.dataSubject.next(response);
          return { dataState: DataState.LOADED, appData: response };
        }),
        startWith({ dataState: DataState.LOADING }),
        catchError((error: string) => {
          return of({ dataState: DataState.ERROR, error })
        })
      )
  }
  

  createNewGameAccount(newGameAccountForm: NgForm): void {
    this.isLoadingSubject.next(true);
    this.newGameAccountState$ = this.gameAccountsService.newGameAccount$(newGameAccountForm.value)
      .pipe(
        map(response => {
          console.log(response);
          newGameAccountForm.reset({});
          this.isLoadingSubject.next(false);
          return { dataState: DataState.LOADED, appData: this.dataSubject.value };
        }),
        startWith({ dataState: DataState.LOADED, appData: this.dataSubject.value }),
        catchError((error: string) => {
          this.isLoadingSubject.next(false);
          return of({ dataState: DataState.LOADED, error })
        })
      )
  }

}



HTML

<ng-container *ngIf="(newGameAccountState$ | async) as state" [ngSwitch]="state.dataState">
    <ng-container *ngSwitchCase="DataState.LOADED">
        <app-navbar [user]="state?.appData?.data?.user"></app-navbar>
        <section>
            <div class="container">
               


                <div class="row justify-content-center">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="text-center">
                                    <h2><i style="margin-right: 5px;" class="bi bi-person-plus-fill"></i> New Game
                                        Account
                                    </h2>
                                </div>
                    

                                <form #newGameAccountForm="ngForm"
                                    (ngSubmit)="createNewGameAccount(newGameAccountForm)">
                                    ///LOTS OF INPUTS FOR FORM
                                        <button
                                            [disabled]="state.dataState === DataState.LOADING || newGameAccountForm.invalid || newGameAccountForm.pristine|| (isLoading$ | async)"
                                            type="submit" class="btn btn-primary mt-5">
                                            <span *ngIf="isLoading$ | async" class="spinner-border spinner-border-sm"
                                                role="status" aria-hidden="true" style="margin-right: 5px;"></span>
                                            <span *ngIf="isLoading$ | async">Saving...</span>
                                            <span *ngIf="!(isLoading$ | async)">Save Game Account</span>
                                        </button>
                                        
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </ng-container>
</ng-container>

SERVICE

export class GameAccountsService {
  


  private readonly server: string = AppSettings.API_ENDPOINT;

  constructor(private http: HttpClient) { }

activeGameAccounts$ = () => <Observable<CustomHttpResponse<User & GameAccount>>>
    this.http.get<CustomHttpResponse<User & GameAccount>>
      (`${this.server}/user/game_accounts/list_active`)
      .pipe(
        tap(console.log),
        catchError(this.handleError)
      );


 newGameAccount$ = (gameAccount: GameAccount) => <Observable<CustomHttpResponse<User & GameAccount>>>
    this.http.post<CustomHttpResponse<User & GameAccount>>
      (`${this.server}/user/game_account/create`, gameAccount)
      .pipe(
        tap(console.log),
        catchError(this.handleError)
      );

 }
  


interceptor

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  private isTokenRefreshing: boolean = false;
  private refreshTokenSubject: BehaviorSubject<CustomHttpResponse<Profile>> = new BehaviorSubject(null);

  constructor(private userService: UserService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> | Observable<HttpResponse<unknown>>{
    if(request.url.includes('verify') || request.url.includes('login') || request.url.includes('register') 
            || request.url.includes('refresh') || request.url.includes('resetpassword')|| request.url.includes('reset_password')) {
          return next.handle(request);
      }
    return next.handle(this.addAuthorizationTokenHeader(request, localStorage.getItem(Key.TOKEN)))
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if(error instanceof HttpErrorResponse && error.status === 401 && error.error.reason.includes('expired')) {
            return this.handleRefreshToken(request, next);
          } else {
            return throwError(() => error);
          }
        })
      );
  }

Could someone please help me. Simple stuff like even getting the paypal button to load while using the pattern i used is eluding me. Thank you for reading