vendredi 31 décembre 2021

Is there any way for Async write/listen to SQS FIFO.?

We have an application which has a requirement for FIFO processing of messages from queue. Currently we are working with ActiveMQ and are thinking of moving to Amazon SQS.

I was wondering if there was any way to have an async write + listen on the Amazon SQS which can achieve fast speeds and FIFO ordering as well.

We have already tried writing a producer+consumer with sync operation, but it is too slow for our needs.

We are trying to build it using Java aws sdk, and are using AmazonSQSAsyncClientBuilder

How to avoid typecasting to subclass when using null object pattern

I have a Value interface with a method to show value as a string. Usually the value is an integer so IntegerValue implements Value. Sometimes value is unknown which I use null object pattern for so UnknownValue implements Value.

When the value is actually an integer, it's useful for the client to check whether the value is high enough (IntegerValue.isEnough). This affects how this value is displayed to the user later on. However, if the value is unknown, it doesn't make sense to check if it's high enough--the value is unknown. By the Interface Segregation Principle, UnknownValue should not have an isEnough method.

interface Value {
  toString(): string;
}

class IntegerValue implements Value {
  private value: number;
  constructor(v: number) { this.value = v }
  isEnough() { return this.value >= 30 }
  toString() { return '' + this.value }
}

class UnknownValue implements Value {
  toString() { return 'unknown' }
}

But the client accesses a Value and won't know whether it's an IntegerValue. So I'd have to check and then typecast it.

if(value.toString() !== 'unknown') {
  handleInteger(value as IntegerValue) // <-- check if isEnough inside
} else {
  handleUnknown(value)
}

I was wondering if there was a design pattern that could solve this with polymorphism, without typecasting.

I was considering the Visitor Pattern like so:

interface ValueVisitor {
  handleInteger(v: IntegerValue): void;
  handleUnknown(): void
}

class ViewValueVisitor implements ValueVisitor { ... }
class JsonSerializerValueVisitor implements ValueVisitor { ... }

interface Value {
  toString(): string;
  acceptVisitor(v: ValueVisitor): void;
}

class IntegerValue implements Value {
  ...
  acceptVisitor(v) { v.handleInteger(this) }
}

class UnknownValue implements Value { 
  ...
  acceptVisitor(v) { v.handleUnknown() }
}

But the Visitor Pattern violates the Open Closed Principle. I was wondering if there is a better solution.

not able to define logic for decrementing pattern

I am trying to print the below pattern but not getting how to build logic where i am going wrong in below code. I want to achieve using stack

Expected output :

01
02 01
03 02 01
04 03 02 01
05 04 03 02 01
06 05 04 03 02 01
07 06 05 04 03 02 01
08 07 06 05 04 03 02 01
07 06 05 04 03 02 01
06 05 04 03 02 01
05 04 03 02 01
04 03 02 01
03 02 01
02 01
01

My code :

n=15
lst=[]
var=''
lg = len(str(n))

  for row in range(1,n+1):
    if row <=breaking:
      print(  str(row).zfill(lg) + ' ' +var )
      var = str(row).zfill(lg) + ' ' +var 
    else:
      pass

This above code printed up till here after that how to procced with decrementing pattern

01
02 01
03 02 01
04 03 02 01
05 04 03 02 01
06 05 04 03 02 01
07 06 05 04 03 02 01
08 07 06 05 04 03 02 01

Event Sourcing with Credit Transaction if not accept to lack of credit

I'm now learning event sourcing. I know many examples of event sourcing are banking or credit systems.

However, they don't discuss the conflict between the same timing commands.

Here is the example:

Backgraound

  • User X has $100 at 01:10:00
timeline payment A ($70) payment B ($80)
01:10:00 request Payment A
01:10:10 trace current balance at 01:10:10
01:10:11 request Payment B
01:01:12 accept Payment with enough balance $(100 - 70) trace current balance at 01:01:12
01:01:13 execute the payment event accept Payment with enough balance $(100 - 80)
01:01:14 execute the Payment event

if the User X query his balance, he got 100 + (- 80) + (- 70) = $-50

It's a terrible situation I think.

-> Question1. Where is the discussion about this solution about the situation?

I know some engineers propose the queue or (pessimistic) lock about the table to solve this problem at CRUD pattern.

Of course, we can use these solutions for event sourcing commands, but these patterns decrease event sourcing patterns' benefits, availability.

-> Question 2. Does the event sourcing system use queue or lock exist?

(OffTopic)

Given These problems, I think some credit system needs a CRUD system and a better persistence logging system which can trace the domain flow.

-> Question 3. My proposal is some thing strange, isn't it?

jeudi 30 décembre 2021

Is it a better design to inherit from an abstract class or from an interface if the child classes have a common property?

I have two classes B and C which share a common property a of type D.

class B
{
  public D a {get;set;}
  public E b {get;set;}
}

class C
{
  public D a {get;set;}
  public F c {get;set;}
}

I could make a

abstract class A 
{
  public D a {get;set;}
}

from which B and C inherits.

class B:A
{
  public E b {get;set;}
}

class C:A
{
  public F c {get;set;}
}

I also know that i will have a service with a method GetValue which returns an object of type A.

interface Service
{
  A GetValue();
}

The class A could also be an interface but then the property a had to be implemented double by B and C. The question is should I use interface or abstract for implementig A? To inherit from abstract class just for the reason that two classes have a common property seem to be not a good practice, but I am not sure.

mercredi 29 décembre 2021

How to construct several singleton objects?

I have a singleton, for example:

#include <bits/stdc++.h>

class A { 
 private:
  A() {printf("init a unparam A\n");}
  virtual ~A() = default;

 public:
  static A& Inst() { static A u; return u;} 
  void print() {printf("my no = %d\n", no_);}
  int no_ = -1;
};

I know this is odd; in most situations, I only need one in my program. However, in some cases, I need several objects in one program, so I added a constructor with an int parameter.

#include <bits/stdc++.h>

class A { 
 private:
  A() {printf("init a unparam A\n");}
  A(int i) : no_(i) { printf("init a A with no = %d\n", no_);}  // this part is added
  virtual ~A() = default;

 public:
  static A& Inst() { static A u; return u;} 
  static A& Inst(int i) { static A u(i); return u;}   // added
  void print() {printf("my no = %d\n", no_);}
  int no_;
};

In main.cpp:

int main() {
  A & a = A::Inst();
  a.print();
  A & b = A::Inst(1);
  b.print();
  A & c = A::Inst(2);
  c.print();
}

The result is:

init a unparam A
my no = 0
init a A with no = 1
my no = 1
my no = 1  // Inst(2) only get the Inst(1) object, why?

In my opinion, the first a will create a Inst by calling the no parameter constructor, b will create one with no=1, c create one with no=2.

But the real result is, b and c share one object.

Could you help on this? How can I make this work?

How to Implement MVI in Android using just Java

Please does anyone have a link to a resource that helps in learning how to create an app using mvi design pattern but all code should be in Java and not Kotlin

Spring can not pick a JpaRepository that extends a generic interface

Problem description

I have a couple of controllers that look like this:

@RequestMapping("InkUsage")
@RestController
public class InkUsageController extends BaseController<InkUsageDto> {
    public InkUsageController(BaseService<InkUsageDto> service) {
        super(service);
    }
}

@RequestMapping("MediaCategoryUsage")
@RestController
public class MediaCategoryUsageController extends BaseController<MediaCategoryUsageDto> {
    public MediaCategoryUsageController(BaseService<MediaCategoryUsageDto> service) {
        super(service);
    }
}

Both of them extend a BaseController class that looks like this:

@AllArgsConstructor
@RestController
public class BaseController<T> {
    private BaseService<T> service;

    @PostMapping
    public ResponseEntity<List<T>> getAll(){...}
    

    ...
}

The BaseService looks like this:

@AllArgsConstructor
@Service
public class BaseService<T> {
    private BaseRepository<T> repository;
    
    public List<T> getAll() {...}

    ...
}

The BaseRepository is just an interface that JpaRepositories extend:

public interface BaseRepository<T> {
    List<T> getAllAggregated(String dateFormat);
    List<T> getAllNonAggregated(String dateFormat);
    ...
}

This is how one of the JpaRepositories look like:

@Repository("InkUsageRepository")
public interface InkUsageRepository extends JpaRepository<InkUsageEntity, Long>,
        BaseRepository<InkUsageDto> {
    @Query("SELECT new api.coloradodashboard.inkusage.InkUsageDto(DATE_FORMAT(i.date, :dateFormat) AS formatted_date, sum(i.cyanLitresUsed), sum(i.magentaLitresUsed), sum(i.yellowLitresUsed), sum(i.blackLitresUsed)) " +
            "FROM InkUsageEntity i " +
            "GROUP BY formatted_date " +
            "ORDER BY formatted_date ASC")
    List<InkUsageDto> getAllAggregated(@Param("dateFormat") String dateFormat);

    ...
}

The problem is that when I run the application Spring complains that BaseService requires a single bean of type BaseRepository but it found 2, which is true. However, both implementations use a different class as a generic type(one uses BaseRepository<InkUsageDto>, for example) and it seems Spring can not pick up that.

Question

How can I tell Spring to use the proper repository?

What I already tried

  • Spring suggests using a @Primary qualifier, but that will not solve my problem because I plan on having 5 JpaRepositories extending BaseRepository.
  • I tried passing the repository into the BaseController constructor, then immediately create new BaseService(repository) in the BaseController constructor but Spring complains it can not find a bean of type BaseRepository.
  • I checked whether passing a variable into a @Qualifier is possible, but they only take constant expressions.
  • A solution that will probably work but I avoid is to create BaseRepository class implementation for each repository, but that means having 5 implementations with the same code except the repository field.

My code doesn't work with methods. (Java)

I wrote a pattern code but can't manage to work it with methods. When I delete all the methods (except main method) it works. I must use 2 extra methods for this program, so I can't delete them. I put down there 2 images of 2different outputs (with methods, without methods). Can you help me out with this. Thx..enter image description hereenter image description here

import java.util.Scanner;

public class asdas3 {

 public static void main(String[] args) {
    
     Scanner input = new Scanner(System.in);
     
     System.out.print("Enter a Letter: ");
     String letter1 = input.next();
     char letter = 0;
     if((letter1.length() == 1)) {
         if ( 65 <= letter1.charAt(0) && letter1.charAt(0) <= 90)
             letter = letter1.charAt(0);  
         else if ( 97 <= letter1.charAt(0) && letter1.charAt(0) <= 122) {
             letter = letter1.charAt(0);                                              
         }
         else 
             System.out.println("Invalid input !");
     }
     else {
         System.out.println("Invalid input !");
     }
     char[][] diamond = new char[0][0];
     constructDiamond (letter);
     printDiamond (diamond);
    
   }
 
 public static char[][] constructDiamond (char letter) {
      
     int a = 0;
     a = letter;
     if(65 <= a && a <= 90) {
     a -=64; }
     else if (97 <= a && a <= 122) {
     a-=96;
     }
      
     char[][] diamond = new char[(2*a)][(2*a)];
     if(a == 1)
         System.out.println("A");
     else {             
         char changingLetter = 65;
         for(int i = 0 ; i < a ; i++) {                         // Row                                 
             diamond[i][a - i] =  changingLetter;
             diamond[i][a + i] =  changingLetter; 
             changingLetter++;
         }
         changingLetter = 65;
         int p = 0;
         for(int j = (2*a)-1 ; j > a ; j--) {   
             diamond[j][a - p] = changingLetter;
             diamond[j][a + p] = changingLetter;
         p++;
         changingLetter++;
         }
     
     }
        
      return diamond;     
      
  }
 
  public static void printDiamond (char[][] diamond) {
      
      for(int n = 0 ; n <= diamond.length-1 ; n++) {
          for (int m = 0 ; m <= diamond[1].length-1 ; m ++) {
              System.out.println(diamond[n][m]);                  
          }
          System.out.print("/n");
      }
      
              
  }
    

}

Design pattern for filtering by attributes

I am a scientist trying to learn better software engineering practices, so that my analysis scripts are more robust and easily useable by others. I am having trouble finding the best pattern for the following problem. Is there an OOP framework for easy subsetting by instance attributes? For instance:

  • I have a large table of vehicle trajectories over time [[x, y]]. These are different drivers in different cars, time-trialing on a track.
import pandas as pd
import numpy as np
df = pd.DataFrame({'Form': {0:'SUV', 1:'Truck', 2:'SUV', 3:'Sedan', 4:'SUV', 5:'Truck'},
                   'Make': {0:'Ford', 1:'Toyota', 2:'Honda', 3:'Ford', 4:'Honda', 5:'Toyota'},
                   'Color': {0:'White', 1:'Black', 2:'Gray', 3:'White', 4:'White', 5:'Black'},
                   'Driver age': {0:25, 1:37, 2:21, 3:54, 4:50, 5:67},
                   'Trajectory': {0: np.array([[0, 0], [0.25, 1.7], [1.2, 1.8], [4.5, 4.0]]), 
                                  1: np.array([[0, 0], [0.15, 1.3], [1.6, 1.3], [4.2, 4.1]]), 
                                  2: np.array([[0, 0], [0.24, 1.2], [1.3, 1.6], [4.1, 3.9]]), 
                                  3: np.array([[0, 0], [0.45, 1.6], [1.8, 1.8], [4.2, 4.6]]), 
                                  4: np.array([[0, 0], [0.85, 1.9], [1.5, 1.7], [4.5, 4.3]]), 
                                  5: np.array([[0, 0], [0.35, 1.8], [1.5, 1.8], [4.6, 4.1]]), 
                                 }
                  })
  • A function takes as input a trajectory, and analyzes it over time. eg.
def avg_velocity(trajectory):
    v = []
    for t in range(len(trajectory) - 1):
        v.append(trajectory[t+1] - trajectory[t])
    return np.mean(v)
  • I'd like to write a program that can analyze the trajectories of a particular subset eg. the average velocities of all drives on SUVs, the average velocities of all drives on white vehicles.

My current solution is to:

  1. I use a Pandas Dataframe to store the table.
  2. I subset by different criteria (ie. df.groupby(by=['Form']) )
  3. Iterating over this list of dataframes, I pass each trajectory to a function avg_velocity(trajectory).
  4. I store the results in a nested dictionary ie. results[vehicle_make][vehicle_form][vehicle_color][driver_age].
  5. To retrieve information, I access the nested dictionary by key.

A natural OOP way might be to create a class Drive with many attributes (ie. Drive.make, Drive.form, Drive.age, ... etc.).

class Drive:
    
    def __init__(self, form, make, color, age, trajectory):
        self.form = form
        self.make = make
        self.color = color
        self.age = age
        self.trajectory = trajectory
... 

However, I am not sure how to quickly subset by a particular criteria when each drive has been separated into different instances. Say I suddenly want to plot the average velocity of all drives by Toyotas. I'd have to iterate through a list of Drive instances, check if Drive.make == 'Toyota'. Is this a common problem with OOP?

Not able to define logic in else for pattern printing

Got stuck expected pattern printing

Below is my code , I have printed the first part but got stuck with else part printing required some input how to build logic for else part

n=29
breaking= int((n+1)/2)
lst  = [ len(str(num).zfill(2)) * ' ' for num in reversed(range(1,n+1)) ]
cnt=-1
for row in range(1,n+1):

  if row <= breaking:
    lst[cnt]=str(row).zfill(2) + '   '
    print(' '.join(lst))
    cnt = cnt - 1 
    
  else:  

Expected output :

                                          01   
                                       02    01   
                                    03    02    01   
                                 04    03    02    01   
                              05    04    03    02    01   
                           06    05    04    03    02    01   
                        07    06    05    04    03    02    01   
                     08    07    06    05    04    03    02    01   
                  09    08    07    06    05    04    03    02    01   
               10    09    08    07    06    05    04    03    02    01   
            11    10    09    08    07    06    05    04    03    02    01   
         12    11    10    09    08    07    06    05    04    03    02    01   
      13    12    11    10    09    08    07    06    05    04    03    02    01   
   14    13    12    11    10    09    08    07    06    05    04    03    02    01   
15    14    13    12    11    10    09    08    07    06    05    04    03    02    01
   14    13    12    11    10    09    08    07    06    05    04    03    02    01
      13    12    11    10    09    08    07    06    05    04    03    02    01
         12    11    10    09    08    07    06    05    04    03    02    01
            11    10    09    08    07    06    05    04    03    02    01
               10    09    08    07    06    05    04    03    02    01
                  09    08    07    06    05    04    03    02    01
                     08    07    06    05    04    03    02    01
                        07    06    05    04    03    02    01
                           06    05    04    03    02    01
                              05    04    03    02    01
                                 04    03    02    01
                                    03    02    01
                                       02    01
                                          01

mardi 28 décembre 2021

How do you handle async initialization of an object?

Let's say I have an object Foo which requires some asynchronous work, bar(), to be done before it is ready to be used. It feels like each solution I try, I run into an anti-pattern.

Solutions considered:

  • Keep an initialized variable in Foo. Call bar() in Foo's constructor. When bar() completes, set initialized = true. My issue with this approach is that it introduces uninitialized and initialized states into the object, which in my understanding should be avoided.

  • Setup Foo in a parent and inject the data in via arguments. My problem with this approach is that it just pushes the issue farther up the stack; if this is done, now some other class is responsible for doing Foo's initial work.

What is common practice in a situation like this? Thanks!

lundi 27 décembre 2021

What is the best practice to update a list view in real-time for web application?

Scenario

Imagine a transporatation company a has large number of trucks. Each truck has its metadata stored in an indexed summary ready for query, such as plate/location/speed/ETA/status/driver etc. Operators can use any filter/sort to get a paged list result in a web app, which fetches data from a RESTful API GET: {baseUrl}/trucks backed by a SQL server.

As the data is rapidly changing in nature(truck moves every sec!), we can imagine that the list result can possibly change anytime when any truck's metadata changed. And further more, this change can be filter/sort specific: e.g. a drive swap for a truck may only affect listing result for operators who filter/sort by driver, or the listing result actually contains that truck.

Target

Let this "list view" auto updates whenever the list result changes.

Current apporach

Web app does polling every minute (So call GET: /trucks every minute) for a fresh listing result (So short polling, yes). However, this approach is not smart enough as in some cases data changes a lot faster than a minute, while in other cases a lot of traffic are wasted for no change at all. Also it's not recommended in this answer, which I fully agree with.

Problem

I was thinking of long polling or websocket to let server pushes update to the web app whenever the list result changes. However, it's easy to track changes for a single truck but not for a list, as a list could change when any truck gets updated in the database.

For example, if we have trucks with the following data:

| Plate | Driver Name | Status | | -------- | ----------- | ------ | | PLATE-01 | Aaron | Running | | PLATE-02 | Ben | Running | | PLATE-03 | Charlie | Running | | PLATE-04 | Daniel | Running | | PLATE-05 | Edison | Running | When a user lists trucks by driver's name for page 2 with size of 2, he gets truck 03/04. then his list should get updated when:

  1. Truck 03/04 has an update, for example truck 03 stopped, list result remains the same trucks but different driver values.
  2. Truck 02 has driver swapped to Francis, then list result should become truck 04/05.
  3. Truck 05 has driver swapped to Adam, then list result should become truck 02/03.

It's easy to capture/track the change for scenario 1, we can simply track every truck in the list result. But I cannot see any good way to solve scenario 2/3, apart from tracking every truck in the database, which is not possible.

Question

What is the best practice/design to update this list view in real-time?

OOP - How to pass data "up" in abstraction?

I have run into a problem when designing my software.

My software consists of a few classes, Bot, Website, and Scraper.

Bot is the most abstract, executive class responsible for managing the program at a high-level.

Website is a class which contains scraped data from that particular website.

Scraper is a class which may have multiple instances per Website. Each instance is responsible for a different part of a single website.

Scraper has a function scrape_data() which returns the JSON data associated with the Website. I want to pass this data into the Website somehow, but can't find a way since Scraper sits on a lower level of abstraction. Here's the ideas I've tried:

# In this idea, Website would have to poll scraper. Scraper is already polling Server, so this seems messy and inefficient
class Website:
    def __init__(self):
        self.scrapers = list()
        self.data = dict()

    def add_scraper(self, scraper):
        self.scrapers.append(scraper)
   
    def add_data(type, json):
        self.data[type] = json

    ...
# The problem here is scraper has no awareness of the dict of websites. It cannot pass the data returned by Scraper into the respective Website
class Bot:
     def __init__(self):
          self.scrapers = list()
          self.websites = dict()

How can I solve my problem? What sort of more fundamental rules or design patterns apply to this problem, so I can use them in the future?

Using Factory Design Pattern in Spring

I organized the factory design pattern but I'm not sure if I used it right or wrong.

Here's my data model;

@Data
@AllArgsConstructor
@NoArgsConstructor
abstract public class Ga implements Serializable {

    private static final long serialVersionUID = -1977929156280284414L;

    private String id;
    private GaStaEnum gaSta;
    private PlaTuEnum plaTu;
    private BoaSiEnum boaSi;

}

@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class XGa extends Ga {

    private static final long serialVersionUID = 3116827666531342601L;

    private Pla pla1;
    private Pla pla2;
    private int laSoPiIn;

.....

And my factory pattern is like this;

public class GaFactory {

    public static Ga createGa(GaType type) {
        Ga ga = null;

        if (X.equals(type)) {
            ga = new XGa();
        }

        return ga;
    }

}

I called the factory like this;

public XGaDTO init() {
    Ga xGa = GaFactory.createGa(X);
    repository.save((XGa) xGa);
    return mapper.toDTO((XGa) xGa);
}

Did I use it right? Or maybe I should add something more?

Thanks for advices.

Why use this pattern of having a pointer to a class? [closed]

Python programmer totally new to c++. Rewriting https://github.com/karpathy/scriptsbots as my first project. You may be able to follow this question without having to read the actual code.

The author uses a pattern that I can't understand.

  • He defines a GLView class (here)
  • Then rather than using the class directly, he creates a pointer to an instance of the class like so GLView* GLVIEW = new GLView(0);. Also worth noting that GLView.h forward declares GLVIEW (here).
  • And rather than making use of the class methods directly, he defines functions that call the methods via the pointer to the instance. For example: void gl_changeSize(int w, int h) {GLVIEW->changeSize(w,h)}.

I suppose there must be some purpose for all this that I'm not seeing yet. So what's this pattern for? Is it common? Does it have a name?


If helpful, here's what's going on in my head: why not

  1. Make an instance of GLView like this: glView = GLView();
  2. Call its methods like this: glView.gl_changeSize()

Generic function to call recursive templated function with different template parameters

I have a templated function hierarchy which works like this:

template <typename T>
SomeClass<T> Primary(SomeInputClass& input) {
  vector<SomeClass<T>> individual_results;
  for (auto& next_states : input.GetNextStates()) {
    //
    // change input's internal state here, then call:
    //
    if (/* needs recursion based on some condition in input */ ) 
      individual_results.push_back(SwitcherCaller<T>(input)); 
    else 
      // some base case operations with individual_results
  }
  
  SomeClass<T> aggregated_results = AggregateIndividualResults<T>(individual_results);
  return aggregated_results;
}

template <typename T>
SomeClass<T> SwitcherCaller(SomeInputClass& input) {
  string type = input.GetTypeFromInternalState();

  if (type == "ClassA") return Switcher<T, ClassA>(input);
  else if (type == "ClassB") return Switcher<T, ClassB>(input);
  else if (type == "ClassC") return Switcher<T, ClassC>(input);
}

template <typename T, typename C>
SomeClass<T> Switcher(SomeInputClas& input) {
  SomeClass<C> child_results = Primary<C>(input);
  SomeClass<T> parent_results = CreateParentResultsFromChild<T, C>(input, child_results);
  return parent_results;
}

The above code captures what I want to do generically in a data processing pipeline. This pipeline is generic, so it can be called with different kinds of templates by different callers.

The callers need to do the following:

  1. Make the first call to Primary with a root template, with an instance of SomeInputClass with its internal state configured as required.
  2. Implement SwitcherCaller for all possible child classes that can be reached as defined by the internal states.

For example, assume there are two callers. Caller 1 does the following:

void PrimaryCallerOne() {
  SomeInputClass input = CreateInputForCallerOne();
  SomeClass<RootClassOne> results = Primary<RootClassOne>(input);
}

template <typename T>
SomeClass<T> SwitcherCaller(SomeInputClass& input) {
  string type = input.GetTypeFromInternalState();

  if (type == "ClassOneA") return Switcher<T, ClassOneA>(input);
  else if (type == "ClassOneB") return Switcher<T, ClassOneB>(input);
  else if (type == "ClassOneC") return Switcher<T, ClassOneC>(input);
}

And Caller 2 does this:

void PrimaryCallerTwo() {
  SomeInputClass input = CreateInputForCallerTwo();
  SomeClass<RootClassTwo> results = Primary<RootClassTwo>(input);
}

template <typename T>
SomeClass<T> SwitcherCaller(SomeInputClass& input) {
  string type = input.GetTypeFromInternalState();

  if (type == "ClassTwoA") return Switcher<T, ClassTwoA>(input);
  else if (type == "ClassTwoB") return Switcher<T, ClassTwoB>(input);
}

Calling Primary is easy. My problem is, how do I design this to implement SwitcherCaller() elegantly? One way is to put all these functions in a class, make SwitcherCaller() virtual, and have each caller implement it.

Is there any other way without classes? Maybe using functors?

dimanche 26 décembre 2021

How To Approach Server OOP Design?

I am developing a program that processes scraped data from several websites. We will call it the "main server".

The scraping process occurs on a series of other programs which are distributed amongst different remote computers. The data is sent from each scraping program to my main server program over a socket. A single website has multiple scraping programs pulling data from it (each Scraper is responsible for its own portion of the website).

I have a few classes in mind for the main server, the relevant ones are Bot, Server, Website, and Scraper.

Bot is the "program" class, it contains executive data at the highest level of abstraction:

class Bot:
    def __init__(self):
        self.websites = dict()
    
    def add_website(self, name):
        self.websites[name] = website(name)

    def process_data(self):
        for website in websites:
            ...

Website is self-explanatory:

class Website:
    def __init__(self, name):
        self.name = name
        self.pages = dict()
        self.scrapers = list()

    def add_page(self, pageDescription):
        ...

Server is where things start to get a bit shaky:

class Server:
    def __init__(self, addr, scraperPort, placerPort):
        self.addr = addr
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        pass

    def handle_requests(self, c):
        while True:
            try:
                data = c.recv(65535)
            except (ConnectionAbortedError,ConnectionResetError):
                return
            decoded = data.decode()
            try:
                requestJson = json.dumps(decoded)
            except:
                # error
            if requestJson['type'] == 'hello':
                requestJson['socket'] = c

            packetQueue.append(requestJson)


    def start(self):
        self.socket.bind('localhost', PORT)
        self.socket.listen(1000)
        while True:
            (client, address) = self.socket.accept()
            start_new_thread(self.handle_requests, (client))

As you can see, Server is responsible for accepting socket connections from all scrapers. Once it receives a connection, it will receive a "hello" packet, which will contain the Website the scraper is for as well as a unique identifier. The goal is to "attach" that socket to the proper Website/Scraper object, so that further communications with this socket are designated to that Website.

However, as it stands, Server has no awareness of the dictionary of Website objects. Even if I made Server a member of the high-level Bot object, Server itself would still have no awareness of these objects from inside handle_requests(). As of right now, you can see at the last line of handle_requests() I am adding each packet to a queue. Each Scraper is polling this queue:

class Scraper:
    def poll_packet_queue(self):
        packet = packetQueue.peek()
        if packet['website'] == self.website and packet['guid'] == self.guid:
            # the packet was designated for this website, and this scraper's portion of the website data

This feels messy and wrong. The first issue with this is that when one of the sockets (scrapers) accepted by Server throws a connection error, it is important I clear the website data corresponding to the scraper's socket. However, since Server's handle_requests() has no direct awareness/communication with the Scraper/Website object besides the packetQueue, it is impossible to know which scraper's data to clear when the socket throws the error. The only way this would be possible with the current design is to keep track on the unique identifier and website associated with the socket INSIDE the server object using a local variable in handle_requests(), and on disconnect, create a local disconnectPacket with the locally stored identifier and website, which would eventually be picked up by the scraper object polling the packetQueue:

    def handle_requests(self, c):
        website = None
        identifier = None

        while True:
            try:
                data = c.recv(65535)
            except (ConnectionAbortedError,ConnectionResetError):
                disconnectPacket = dict()
                disconnectPacket['guid'] = identifier
                disconnectPacket['website'] = website
                return
            decoded = data.decode()
            try:
                requestJson = json.dumps(decoded)
            except:
                # error
            if requestJson['type'] == 'hello':
                requestJson['socket'] = c
                identifier = requestJson['guid']
                website = requestJson['website']

            packetQueue.append(requestJson)

But again, this feels messy. Is there a better way to design this program? If so, is there a more fundamental rule behind it that I can apply to similar situations in the future?

Image uploading and validation architecture diagram

I am working on a project whereby I am to design a system for users to upload, download and search for images within a database. I created a system architecture diagram for the upload component which I would like some feedback on. To start, the upload component must be:

  1. Secure only allowing for images which are also unique.
  2. Scalable to over 1 million requests per month with 100 terabytes of data uploaded per month.
  3. Robust and operational 24/7.
  4. Data does not need to be immediately available to download, the deadline for upload to complete is 1 week.



It would be great to get some feedback on my architecture. If it helps, here are some prompts that may make it easy to structure any feedback:

  1. What is missing?
  2. What must be removed?
  3. What problems were overlooked?
  4. Will this meet the scalability demands required?
  5. What additional changes would you make?



Explanation of architecture diagram:

  1. A Frontend allows a user to upload a compressed folder of images. The frontend lightly verifies the contents of the folder to ensure it matches some schema (i.e. just JPEGs). Upload is asynchronous and the user won't wait for the whole pipeline to complete, just the initial upload. They will later be notified of the status of their folder's acceptance.
  2. A Load Balancer selects which upload server instance images are sent to.
  3. Upload servers handle additional verification on the images, checking that the content type and schema is correct (i.e. same as above- just JPEGs). These upload servers then chunk the image folder for concurrency, sending subsets of the folder into a queue once they've passed verification.
  4. A Queue receives some subset of the image dataset which includes a unique hash that maps chunks to the same dataset.
  5. There are two consumers of that queue; one is a Validation Database which keeps let's say 10 percent of the un-validated images as reference. Another is an advanced ML Validation Service. As with the upload servers, there are multiple instances of the ML Validation Service. Sorry for the change in graphical representation, I ran out of space. ML Models take the images as input 1 by 1, validate them by running them through their networks and then passing fully validated images to an S3 Bucket (i.e. images that returned True for every ML validation). The ML component runs models in parallel so that the time it takes to run all ML validation is equal to the time it takes to run the slowest ML validation. Only images that pass all validations are sent to the database.
  6. If an image passes validation then it is sent to an S3 Bucket within AWS via some Database Connector.



A couple notes that came up while I was thinking about this:

  1. Near Real-time over Batch Processing. Although this process could be batch processed, storing potentially invalid images in some database will take up unnecessary space and money.
  2. Near Real-time over Stream Processing. Processing images too quickly may result in invalid images making their way into the database leaving room for potentially malicious actors who may potentially exploit weaknesses in the ML models. Near Real-time gives quality engineers the luxury of checking on the database every hour as opposed to being glued to a screen.

Closing Notes:
I'm new to this and hoping to benefit from your substantial experience here on stack. Please don't be shy to include a question even if it might seem basic, I look forward to incorporating your valuable advice and happy to explain any of these components in more depth. If there are design patterns I can make use of, or perhaps links that would be helpful to read, I am open to any book or article suggestions you may have for me.

Thank you in advance!

Architecture Diagram

Best practice for product developement with Java Spring [closed]

From my understanding a code product has a clear API you can call, extend and customize.

I am practising code patterns and want to improve my style of coding. I want to understand spring patterns and best practice for product developement, e.g. best practice usage of interface and proxies. Especially I am looking for examples working with generics to provide smart, safe and more reusable code APIs.

Knowing this is not a very precise question. How are these principles called? Do you have any advices, guides or examples to look into?

samedi 25 décembre 2021

Finding intersections between an implicit fill pattern and an outer layer for formation of a 3D printing slice

I am sure there are lots of solutions on the internet but it is pretty hard for me to understand someone else's code. Therefore, I want to ask a question about my own case. Basically, I want to put an infill pattern (which is defined by a implicit function such as cos(x)+cos(y)+cos(z)=0) into a slice. How can I find the intersections and plot the slice accordingly ?

(I have also heard and searched about marching-cubes algorithm but I'm not sure how to implement it in this case.)

Here is my code:

import numpy as np
from stl import mesh
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

class Triangle:
    
    def Triangle_builder(triangle_number):
        px=stl.x[triangle_number][:]
        px=np.append(px, px[0])
        py=stl.y[triangle_number][:]
        py=np.append(py, py[0])
        pz=stl.z[triangle_number][:]
        pz=np.append(pz, pz[0])
    
        # ax.plot3D(px,py,pz)
        
        p0=stl.points[triangle_number][0:3]
        p1=stl.points[triangle_number][3:6]
        p2=stl.points[triangle_number][6:9]
        p3=stl.points[triangle_number][0:3]
        
        return p0,p1,p2,p3
          
def isect(p0,p1,plane_p,plane_n):
    vector_x=p1[0]-p0[0]
    vector_y=p1[1]-p0[1]
    vector_z=p1[2]-p0[2]
    vector=np.array([vector_x,vector_y,vector_z])
    
    denom=np.dot(vector,plane_n)
    if denom==0:
        return None #parallel
    else:
        isect_p=p0+vector*(np.dot((plane_p-p0),plane_n)/denom)
        if isect_p[2]>max(p0[2],p1[2]) or isect_p[2]<min(p0[2],p1[2]):
            return None
        else:
            isect_px=isect_p[0]
            isect_py=isect_p[1]
            isect_pz=isect_p[2]
            
    return isect_px,isect_py,isect_pz
       
def plotter(hdy):
    for i in range(len(hdy)-1):
        # print(hdy[i])
        # print(hdy[i+1])
        ax.plot3D([hdy[i][0],hdy[i+1][0]],[hdy[i][1],hdy[i+1][1]],[hdy[i][2],hdy[i+1][2]])
    return ax

def filter(list_):
    for i in range(len(list_)):
        if list_[i]==None:
            list_.pop(i)
    return list_
    
def hyp_part1(x,y,z):
    return np.cos(x)+np.cos(y)+np.cos(z)
    
stl = mesh.Mesh.from_file("sphere.stl")
row,col=stl.z.shape
z=np.arange(stl.min_[2],stl.max_[2],1)
for k in z:
    plane_p=np.array([0,0,k])
    plane_n=np.array([0,0,1])
    isect_list=[]
    i=0
    while i<row:
        j=0
        p_list=Triangle.Triangle_builder(i)
        i=i+1
        isect_list=[]
        while j<3:
            p0=p_list[j]
            p1=p_list[j+1]
            isect_list.append(isect(p0, p1, plane_p, plane_n))
            j=j+1
            filter(isect_list)
            # print(isect_list)
            if len(isect_list)==2:
                ax=plotter(isect_list)

x_range = np.arange(0,4,5) 
y_range = np.arange(0,4,5)
X,Y = np.meshgrid(x_range,y_range)
A = np.linspace(-10, 10, 8)

A1,A2 = np.meshgrid(A,A)    

for z in A: 
    X,Y = A1, A2
    Z = hyp_part1(X,Y,z)
    ax.contour(X, Y, Z+z, [z], zdir='z')

for y in A: 
    X,Z= A1, A2
    Y = hyp_part1(X,y,Z)
    ax.contour(X, Y+y, Z, [y], zdir='y')

for x in A:
    Y,Z = A1, A2 
    X = hyp_part1(x,Y,Z)
    ax.contour(X+x, Y, Z, [x], zdir='x')

Slices and the pattern with excess lines Slices alone

Are we instantiating interface in Strategy Pattern? [duplicate]

https://www.javatpoint.com/strategy-pattern

I have heard that we can't initiate (make objects) of interfaces, but in Strategy Pattern, we are creating an object of Strategy interface.

Code

public interface Strategy {  
      public float calculation(float a, float b);  
}
public class Context {  
  
       **private Strategy strategy;**  
       
       public Context(Strategy strategy){  
          this.strategy = strategy;  
       }  
  
       public float executeStrategy(float num1, float num2){  
          return strategy.calculation(num1, num2);  
       }  
}

In context class, we have created an object of Strategy interface. How is this possible as interfaces can't be instantiated.

Dependency Injection with Strategy and factory pattern in spring boot

I have recently implemented Strategy + Factory Method pattern in my application, but in my implementation class i am not able to initialise object. Getting Null pointer exception : cannot invoke method

@Component
class someClass {

private final StrategyFactory strategyFactory

    someClass(StrategyFactory strategyFactory) {
        strategyFactory = strategyFactory
    }

Request strategy = strategyFactory.getBanks(getBankName)
                        .orElseThrow({ -> new IllegalArgumentException("No Bank found with the name " + getBankName) })

            strategy.fetch(getBankName)
}

Actual factory class , can we use @autowired instance here instead using new keyword

@Component
class StrategyFactory {

    private Map<String, BankNameRequest> name = new HashMap<>()

    StrategyFactory() {
        name.put("sbi", new SBIService())
        name.put("hdfc", new HDFCService())
        name.put("union", new UnionService())
    }

    Optional< BankNameRequest > getBanks(String bname) {
        return Optional.ofNullable(name.get(bname))
    }
}

strategy interface

interface BankNameRequest {

        void fetch(String name)

}

implementation class

@Component
class SBIService implements BankNameRequest {

    @Autowired
    private KafkaService kafkaService

    @Override
    void fetch(String name) {
       kafkaService.queue(name)
    }
}

kafka servcie class

@Service
class KafkaService {

    @Autowired
    private KafkaTemplate<String, byte[]> kafkaTemplate

    void queue(String name) {
        //impl
    }
}

here kafkaService is getting null. How can i autowire this kafka service?

vendredi 24 décembre 2021

i need a psudocode of picture 2 upload below

Imagine that you’re working on a notification library which lets other programs notify their users about important events. The initial version of the library was based on the Notifier class that had only a few fields, a constructor and a single send method. The method could accept a message argument from a client and send the message to a list of emails that were passed to the notifier via its constructor. A third-party app which acted as a client was supposed to create and configure the notifier object once, and then use it each time something important happened. At some point, you realize that users of the library expect more than just email notifications. Many of them would like to receive an SMS about critical issues. Others would like to be notified on Facebook and, of course, the corporate users would love to get Slack notifications. Some of them would like to be informed through every channel. One possible solution is given below: Extending a class is the first thing that comes to mind when you need to alter an object’s behavior. However, inheritance has several serious caveats that you need to be aware of. Inheritance is static. You can’t alter the behavior of an existing object at runtime. You can only replace the whole object with another one that’s created from a different subclass. enter image description here

I NEED A PSUDOCODE OF THIS PICTURE enter image description here

How can abstract my code to avoid duplication if a increase the number of variables to consider?

Currently there are be 4 combinations

  • Add hours.
  • Add days.
  • Subtract hours.
  • Subtract days.
private String modifyDate(Character symbol, LocalDateTime date, Long digits, String period) {
        switch (symbol) {
            case '+':
                if (period.contains("days")) {
                    return date.plusDays(digits).toString();
                } else {
                    return date.plusHours(digits).toString();
                }
            case '-':
                if (period.contains("days")) {
                    return date.minusDays(digits).toString();
                } else {
                    return date.minusHours(digits).toString();
                }
            default:
                System.out.println("Not defined operation");
        }

        return "";
    }

If a new period is added (let's say years), it will be necessary to add a new if statement in each case:

if (period.contains("years")) {
    return date.plusYears(digits).toString();
} else if (period.contains("days")) {
    return date.plusDays(digits).toString();
} else {
    return date.plusHours(digits).toString();
}

Also if a new unexpected case is added (a combination, especial cases), then it will be necessary to repeat the logic to validate the periods.

Do you have a recommendation to improve the solution? Pattern recommendation, functional interfaces implementation, any recommendation is welcome.

Thanks in advance!

Encapsulation vs data hiding (they are not the same)

I am a little confused by whole terminology of encapsulation and data hiding. I'm reading a book "Dive into design patterns" by refactoring guru and when he explains what encapsulation is, I thought that something is off.

I've searched and I found a really nice explanation: https://stackoverflow.com/a/28614407/11993214.

He mistook encapsulation with data hiding. After reading answer from above link I sum this up to those definitions:

encapsulation - is when we are seperating from a piece of code, data and methods, which are using these data, and we are packing them together. data hiding - is a place where everything we can, we do as private and we are implementing getters and setters as the only places from which we can access this data.

But as I read more, I've got even more confused. He made a topic: Encapsulate what varies. It have two subcategories - encapsulate on method level, and on class level. It says for example to remake this:

enter image description here

into this:

enter image description here

I think it's similar to the statement from question from link above.

Whatever changes encapsulate it. Protecting anything which is prone to change.

, and answer to this was:

(...) And 2, as noted by CommuSoft, isn't really a definition, it's a rule of thumb. And I will add that it's a rule of thumb about when to use data hiding, not encapsulation

So now, I have this section from book, and based on this example that I gave I think that it is more likely to be an encapsulation case. But if I'm thinking correctly and it is similar to the quotes from linked topic, than based on that answer this example code is a rule of thumb about when to use data hiding? So to sum up... I'm really confused if I understand encapsulation and data hiding correctly. Based on those examples which I provide, I'm thinking that this example is encapsulation. Is it correct? And if yes, than how is it different from the topic mentioned in quotes?

I'm looking forward to your answers, and if this whole explanation is not clear than please give me feedback, and I will try my best to do better.

jeudi 23 décembre 2021

How to print following pattern getting issue with spaces?

I am trying to write the code but not getting how to achieve expected output Causing issue with space and not able to make proper judgement how to get exact spaces after every iteration

My code :

n=15
cnt=0
lst=[str(' ') for x in range(1,n+1)]
initial_length=len(''.join(lst))
print(initial_length)
for row in range(1,n+1):
  lst[cnt-1]=str(row)
  cnt=cnt-1
  print(' '.join(lst))

Output of above code is not as expected output

                            1
                          2 1
                        3 2 1
                      4 3 2 1
                    5 4 3 2 1
                  6 5 4 3 2 1
                7 6 5 4 3 2 1
              8 7 6 5 4 3 2 1
            9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
        11 10 9 8 7 6 5 4 3 2 1
      12 11 10 9 8 7 6 5 4 3 2 1
    13 12 11 10 9 8 7 6 5 4 3 2 1
  14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Expected output :

                                  1
                                2 1                                                                 
                              3 2 1                                                              
                            4 3 2 1
                          5 4 3 2 1                         
                        6 5 4 3 2 1                       
                      7 6 5 4 3 2 1                     
                    8 7 6 5 4 3 2 1 
                  9 8 7 6 5 4 3 2 1
               10 9 8 7 6 5 4 3 2 1 
            11 10 9 8 7 6 5 4 3 2 1 
         12 11 10 9 8 7 6 5 4 3 2 1
      13 12 11 10 9 8 7 6 5 4 3 2 1
   14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Seperate Web Framework From Main Application

I have a question regarding software design/architecture. I want to build an application, which provides a REST API and runs several algorithms in the background. My main aim is to seperate these two functions strictly. Ideally it would not matter for anyone developing the algorithms which framework is currently being used. The web framework would be resposible for providing the API and making calls to any service/database needed for the main application.

My first guess to accomplish such an architecture would be to have an "internal API" between the web framework and main application. I am at a loss though as to how to design such an API. The implementation would be in Java, but I think the first aim of the architecture should be to give a structure that it could be implemented in any OOP language.

Since I am unexperienced in designing software I want to kindly ask if such an architecture makes sense and if anyone could point me to resources, which describe something similar. So far I could not really find what I want. Maybe I am simply missing the right keywords to describe my problem.

Thank you for your help.

How to design like this with boxShadow? [closed]

an Image with diamond shaped I want the diamond shape like that. How could I achieve this ? I have tried this with after before , still cannot got the solution .

Efficient algorithm for comparing one-on-one tournaments

I was thinking of doing a simple program, which basically has a list of some items - such as foods, for an example - and which pairs two foods against each other for user to choose his or her favourite out of those two options. Ultimately, a list of ranked candidates would emerge. Behind the scenes, I thought two really simple "algorithms" to work by.

  1. Working through each pairing possible to score the list perfectly. Seems really tedious for the user when there are many items in the list.

  2. Simple elimination. Two foods enter, one leaves for the next round. But I can't really then get a rank, other than just general estimates of categories of performance.

So I was wondering, what other ranking systems there would be for one-on-one "tournaments" like this?

Should I plumb CancellationTokens through all of my class methods in an asp.net core 3.1 web api?

I've been building a web server in asp.net core 3.1 for a little while and I've started to notice (and frankly, dislike) that Im plumbing cancellation tokens through my application. I came up with a solution to this "problem" (it is and it isn't) and am seeking opinons.

First, just so we're all on the same page - let's recap the request pipeline:

  • A request hits the server and the asp.net core framework instantiates an HttpContext
  • The framework instantiates a CancellationToken and attaches it to the HttpContext.RequestAborted property, (which, yes lol, has the type CancellationToken)
  • Some mapping happens behind the scenes in the framework, and a controller is resolved from the DI container (the controllers are registered as services)
  • The controller method is called, decorated by a pipeline of middleware through which the HttpContext instance is passed
  • The framework performs model binding on the HttpContext instance (taking from the route params, query params, body, header, etc ) and then attempts to pass the results to the method discovered during mapping
  • Model binding results that fit the signature are injected (or passed, whichever word you prefer) as well as the CancellationToken taken from the HttpContext.RequestAborted property.

Second - here is some context on my problem:

I use Autofac for dependency injection, and I learned at some point that you can give dependencies (class instances) Lifetime Scopes, which will dictate how long lived a class instance is. I also developed a practical or intuitive perspective, which is a little different, and also differs by scope type. Examples probably illustrate this best:

  • a single instance for the lifetime of the application (where you can store data, and then resolve it anywhere else in the application at any time),
  • a unique instance each time the type is injected, so no state is shared between injected instances
  • others!

Since this is an asp.net core 3.1 mvc/web api, a lifetimeScope is available from Autofac that allows you to resolve the same instance from the container from within the context of the current request (in other words, any code executing for any one given request will resovle the same instance. Different request? Different instance). This is the .InstancePerLifetimeScope() scope type in Autofac 6.

Using this information, I realized that I could write a piece of middleware that assignes the httpContext.RequestAborted cancellation token to a transport class that has a lifetime scope of InstancePerLifetimeScope and then inject that transport into the places that directly consume the token. In the codebase, this is not very many places (certainly far fewer than all of the plumbed locations).

Here is a minimal set of code that demonstrates what such a no-plumb scenario might be set up like - imagine each class is in its own file:

public class SetCancellationTokenTransportMiddleware
{
    private readonly RequestDelegate next;

    public SetCancellationTokenTransport(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext context, ITransportACancellationToken transport)
    {
        transport.Assign(context.RequestAborted);
        await next(context);
    }
}



// Autoface module registers
public class GeneralModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<SomeDependency>().As<ISomeDependency>();
        builder.RegisterType<Repository>().As<IRepository>();
        builder.RegisterType<CancellationTokenTransport>().As<ITransportACancellationToken>().InstancePerLifetimeScope();
    }
}

// mvc controller - cancellation token is not injected
public class Controller
{
    private readonly ISomeDependency dep;

    public Controller(ISomeDependency dep)
    {
        this.dep = dep;
    }

    [HttpGet()]
    public async Task<Thing> Get()
    {
        return await dep.Handle();
    }
}

// This thing gets bypassed -- the cancellation token isn't plumbed through here
public class SomeDependency : ISomeDependency
{
    private readonly Repository repository;
    
    public SomeDependency(IRepository repository)
    {
        this.repository = repository;
    {

    public async Task Handle() // no token is passed
    {
        return await repository.GetThing(); // no token is passed
    }
}

public class Repository : IRepository
{
    private readonly ITransportACancellationToken transport;
    private readonly DbContext context;

    public Repository(ITransportACancellationToken transport, DbContext context)
    {
        this.transport = transport;
        this.context = context;
    }

    public async Task<Thing> GetThing()
    {
        // The transport passes the token here - bypassing the calling class[es]

        return await context.Things.ToListAsync(transport.CancellationToken); 
    }
}

So my question generally is - what do you think about this approach to providing Cancellation tokens directly to token consumers (and not their intermediaries)? What Pros and Cons you can think of? Have you ever been burnt by this approach? Does anyone use this in their applications or those they've worked on?

One argument against this pattern I can think of are cases where you need explicitely deprive a code path of a cancellation token. However, the repository here could also technically be designed in a such a way that allows one to choose if cancellation is allowed. Using a Unit of Work pattern, this is also partially mitigates (and the transport class would be injected into the unit of work).

I would very much like to hear some experienced perspectives on this one. General thoughts are of course welcome as well.

mercredi 22 décembre 2021

irregular spaces making pattern abnormal

I have a pattern which i printed using below code

Code :

n=5

def pyramidupdown(n):
  cnt=0
  space=2
  lst= [str(row) for row in reversed(range(1,n+1))]
  for i in range(1,n+1):
    if i == 1:
      s=' '.join(lst)
      print(s)
    else:
      lst[cnt]=' '
      s=' '.join(lst)
      print(s)     
      cnt = cnt + 1

It prints the pattern below as output :

5 4 3 2 1
  4 3 2 1
    3 2 1
      2 1
        1

But my issue is with spaces when the n value is defined 2 digit like 15 the pattern is not printed properly

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
  14 13 12 11 10 9 8 7 6 5 4 3 2 1
    13 12 11 10 9 8 7 6 5 4 3 2 1
      12 11 10 9 8 7 6 5 4 3 2 1
        11 10 9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
            9 8 7 6 5 4 3 2 1
              8 7 6 5 4 3 2 1
                7 6 5 4 3 2 1
                  6 5 4 3 2 1
                    5 4 3 2 1
                      4 3 2 1
                        3 2 1
                          2 1
                            1

Expected output :

 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
    14 13 12 11 10 9 8 7 6 5 4 3 2 1
       13 12 11 10 9 8 7 6 5 4 3 2 1
          12 11 10 9 8 7 6 5 4 3 2 1
             11 10 9 8 7 6 5 4 3 2 1
                10 9 8 7 6 5 4 3 2 1
                   9 8 7 6 5 4 3 2 1
                     8 7 6 5 4 3 2 1
                       7 6 5 4 3 2 1
                         6 5 4 3 2 1
                           5 4 3 2 1
                             4 3 2 1
                               3 2 1
                                 2 1
                                   1

what changes do i need to make in existing code to print properly the pattern

What is the best way to write different css or scss for the same component? [closed]

Imagine that I have a complex component like a dropdown menu and I want it to have some custom styles when I use it in different places. Not only colors, but spacing and icons too.

If I'm using something like react, or vue, I could pass parameters to the props.

We can also use only scss, and there are a lot of ways of overwriting the styles:

.dropdown{
 width: 100px
}

//overwrite for my custom menu
.my-custom-menu{
 .dropdown{
   width: 120px;
  }
}

Or if using something like BEM, I could even make the main class name a variable and change it:

.dropdown{
  &__container{
    width: 100px;
  }
}

//custom
.other-dropdown{
 &__container{
   width: 120px;
  }
}

What is the best way? Are there other ways of doing this?

Design pattern for implementing the Polling approach in c#

I want to implement polling approach in c# using design patterns with some generic code with the below scenario.

I have 3 console application names Employee, Orders, Salary and in this from the Employee application I am initiating the Orders and Salary console application , once I will initiate application Orders and Salary console application are long running application which will keep on running and we are updating the local text file with the completion status for each of the application.

From the Employee application I have created a Timers objected and using Elapsed Event for 2 sec to check the file text whether it has status of both the file has been completed or not.

So I want to make the below implementation in more generic way or using some other approach/design patterns so that we can achieve the similar polling concept as I have ore complex situation where I have to use the same repetitive code for each time . Any suggestion on this ?

var poolingTimer = new Timer(2 * 1000);
                        poolingTimer.AutoReset = false;
                        poolingTimer.Elapsed += async delegate
                        {
                            
                            if (logic to check if File text has console application completed status)
                            {
                                poolingTimer.Stop();    
                            }
                            else
                            {
                                poolingTimer.Start();
                            }
                        };

                        poolingTimer.Start();

Regex max 100 2 digits

I want to do a regex to have a maximum number of 100 with 2 decimals

I made the following regex:

^\d *\,\d{0.2}$

my problem : I can only put a comma (ex: 100,00) but if I put a dot it does not work (100.00) i tried to change my regex with ^\d *\,.\d{0.2}$ but i have the same problem

how can I do ?

thank you

mardi 21 décembre 2021

Design pattern to use to populate multiple class fields

I have a use case where I have to parse an XML document and fill details in a corresponding fields of an internal model POJO Details. Let's say, the XML look like following -

<?xml version="1.0" encoding="UTF-8"?>

...
<TagA>
 <Child1>
 ...
 </Child1>
 <Child2>
 ...
 </Child2>
</TagA>

...

<TagB>
 <Child1>
 ...
 </Child1>
 <Child2>
 ...
 </Child2>
</TagB>
....

And the internal model POJO looks like following -

public class Details {

...

Set<TagAInfo> tagAInformation; 
Set<TagBInfo> tagBInformation;

...

}

The XML has multiple fields like TagAs, TagBs etc.

Current implementation: So currently there is a mapper/parser class(let's say Mapper.java) that calls multiple methods like mapTagAInfo(details, xmlRootElement), mapTagBInfo(details, xmlRootElement) etc. on details(i.e. instance of Details.java) something like following -

public class Mapper {
 ....

public Details mapInfo(XmlElement xmlRootElement) {
  Details details = new Details();
  mapTagAInfo(details, xmlRootElement)
  mapTagBInfo(details, xmlRootElement)
  mapTagCInfo(details, xmlRootElement)
 ....
 return details;
}

private void mapTagAInfo(details, xmlRootElement) {
  stp1: Extract <TagA> tag element info using a utility which reads the xml document
  stp2: use the stp1 info and convert to internal model POJO TagAInfo and 
  add to details (details.addTagAInfo(tagAInfo))
}

Question: The current implementation makes the code look very ugly(as in a single class Mapper.java multiple things are happening), so wanted to know if I can use some design pattern to improve the code ? If so, please suggest what design pattern to use and an example explaining the design pattern usage would help a lot.

implement Singleton inside model class is unrecognized [closed]

I have created an database connection with singleton design pattern.

I have also created an model called User, And I want to create an inner method which called save() which should getInstance() of the singleton and insert the model data to the Database.

But when I try to get the Instance of the singleton It's does not recognize it.

Singleton implementation:

    public class DatabaseConnection {
        private static DatabaseConnection dbIsntance = null;
        private static Connection con;
    
        private DatabaseConnection() {}
    
        public static DatabaseConnection getInstance() {
            if (dbIsntance == null) {
                dbIsntance = new DatabaseConnection();
            }
            return dbIsntance;
        }
    
        public Connection getConnection() throws Exception {
            if (con == null || con.isClosed()) {
                String url = "jdbc:mysql://localhost:3306/";
                String dbName = "db";
                String driver = "com.mysql.jdbc.Driver";
                String userName = "root";
                String password = "";
    
                Class.forName(driver).newInstance();
                con = DriverManager.getConnection(url + dbName, userName, password);
            }
            return con;
        }
    }

Model class:

public class User {
        private int id;
        private String username;
        private String password;
    
        
    
        public void saveOrUpdate(){
            Connection con = null;
            try {
                con = DatabaseConnection.getInstance().getConnection();
                PreparedStatement stmt = con.prepareStatement("insert into users (`username`, `password`) values (?,?)");
                stmt.setString(1, this.username);
                stmt.setString(2, this.password);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (con != null) {
                    con.close();
                }
            }
        }
    }

The Idea(Intelij) show me an error Cannot resolve symbol 'DatabaseConnection'

What I have did wrong?

How do you prefer to receive information from designers regarding builds/style guides?

Im new to both UX/UI and coding and want to know how coders prefer to receive information from designers in regards to style guides and also, I use Zeplin to communicate currently with developers.. Do you like/dislike the platform?

My goal here is to communicate current and future projects to the developers, that is easiest/best practice. Any and all advice welcome. Thank you!

How to design a flexible container with latest n elements?

I want to design a fast container with fixed window size.

Here is the demo:

class SumFish {  // i named this class Fish, because fish only has 7 seconds memory, quite like fixed window size
 public:
  SumFish(size_t N) : n_(N), sum_(0.) {}
  void push(double v) {
     data.push_back(v);
     sum_ += v;
     if (data_.size() > n_) {
       sum_ -= v.front();
       data_.pop_front();
     }
  }
  double sum() const { return sum_; }
  std::deque<double> data_;
  double sum_;
};

I think it's good, since i can calculate the latest n elements' sum in O(1).

But for a container which need to calculate median in data stream.

I need to use two heap to make it in O(logn), I can do it in the push function, but i think it's not the best design, since if i have a Fish only want sum(), it still have heap operation, which cost more time.

So, i perfer to design a similiar class MedianFish:

class MedianFish {
 public:
  MedianFish(size_t N) : n_(N), sum_(0.) {}
  void push(double v) {  // I dont merge this with SumFish
      // because it will cost more time, if i only used to calculate sum.
     // compare, and do heap operation, i ignored
  }
  double median() const { return left_heap.front(); }
  std::deque<double> data_;
  double sum_;
};

I also want another Fish, which record data in my time range. please see the code:

class TimeFish {
 public:
  TimeFish(size_t N) : n_(N), sum_(0.) {}
  void push(double ts, double val) {  // please notice here, i use ts to control the container size
    time_.emplace_back(ts);
    data_.emplace_back(val);
    sum_ += val;
    if (time_.empty()) return;
    double fore_ts = time_.front();
    while (!data_.empty() && ts - fore_ts > size_) {  // pop data if push ts - data.front.ts > N
      double victim = data_.front();
      sum_ -= victim;
      data_.pop_front();
      time_.pop_front();
      if (!time_.empty()) fore_ts = time_.front();
    }
  }
  std::deque<double> data_, time_;
};

util now, i have two different push method, TimeFish(pop data when time is > N) and SizeFish (pop when data size > N).

two function, Median and Sum, which i can combine out:

TimeSumFish, TimeMedianFish, SizeSumFish, SizeMedianFish.

i think there may be some design pattern can optimize my code, (decorator pattern seems match, but i dont know how to merge two push functions) because there is some duplicates code. (For example, TimeSumFish and TimeMedianFish will share the same push function)

Can you help on this?

How to print this pyramid pattern up side down?

I am trying to print below pyramid pattern. But not clicking how to build logic for it ?

Pattern :

5 4 3 2 1
  4 3 2 1
    3 2 1 
      2 1
        1 

I have tried this code seems like this is not a right approach to get it.Any solution is appreciated

import numpy as np
n = 5
cnt=0
var = np.arange(1,n+1)
for row in range(1,n+1):
  print(var[::-1][cnt:])
  cnt= cnt + 1

Output of above pattern:

[5 4 3 2 1]
[4 3 2 1]
[3 2 1]
[2 1]
[1]

lundi 20 décembre 2021

Design patterns that can be used to achieve inheritance and polymorphism

Are there any design patterns that can be used to achieve polymorphism and inheritance?
I am not sure if strategy pattern could be an example of this.

Refactoring a class to comply with single responsibility principle

Consider a shape with a color, a width, and a height. Each shape should compute its own perimeter and have a method able to draw itself. A Shape allows sorting a list of shapes. To allow sorting the shapes by comparing their surfaces, each shape should be able to compare itself to another shape using the compare method of the Comparable interface. Each Shape should support the instantiation (i.e., creation) of objects belonging to the Shape class or to the classes that inherit from the Shape class (e.g., the Circle class).
How to refactor this to comply with the Single responsibility principle?

My thoughts:
The only problematic thing I see with this design is that the Shape should support the instantiation of objects. So this behavior can be removed from the shape class, and probably a separate class called factory could be made to perform this operation.
Not sure if there is any other refactoring one could do

How to form a pattern of X in the format of a box but instead every line the position of X alternates?

if anybody could help me with this problem it would be a great help. SO the task at hand is summarised into this:

Write a function named diagonal(n) that takes a positive integer parameter ‘n’ and that prints an n × n box pattern with Xs on all four sides and on the main diagonal. The illustration shows the desired output for n = 9.

XXXXXXXXX

XX X

X X X

X X X

X X X

X X X

X X X

X XX

XXXXXXXXX

i have little to no idea how to edit this question so it looks proper when I publish it.

So my progress so far is:

def diagonal(n):

for row in range(n):

    for col in range(1):

        print("X", end="")

    print()

diagonal(7)

If somebody could help me out, I would appreciate it big time. Thanks

CSS guidelines about repeatitive structures vs particular instances

Here are 3 equivalents pages:

  1. https://jsfiddle.net/a1g6cfdk
  2. https://jsfiddle.net/04dqzf8a
  3. https://jsfiddle.net/06hfwbm4

I think 1) is the "classic" way of doing, and 3) is being "too smart".

I'm not a fan of 1) because I feel that we repeat "page", I kinda like 2 because the HTML is "cleaner".

I just realised I could also create page elements like this:

https://jsfiddle.net/2j9kvbem

<html>
<body>
  <page id="page1"></page>
  <page id="page2"></page>
  <page id="page3"></page>
</body>
</html>

Maybe that's the cleanest: the HTML tag to express the repeative structure and CSS to express the particularities.

Is there a guide somewhere which would list CSS conventions/architecture guidelines reguarding this topic?

Why are the methods declared in the interface not executed?

I'm trying to implement the Factory Method on the simplest basic example, but the log() methods in the FileLogger and StdoutLogger classes are simply skipped.

index.php

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

function clientCode(LoggerFactory $creator)
{
   $creator->createLogger("hello");
}

clientCode(new FileLoggerFactory("uml\uml.txt"));
clientCode(new StdoutLoggerFactory("uml\uml.txt2"));

Logger.php

interface Logger
{
    public function log(string $message);
}

LoggerFactory.php

interface LoggerFactory
{
    public function createLogger(): Logger;
}

FileLoggerFactory.php

class FileLoggerFactory implements LoggerFactory
{
    private $filePath;

    public function __construct(string $filePath)
    {
      $this->filePath = $filePath;
    }

    public function createLogger(): Logger
    {
      return new FileLogger($this->filePath);
    }
}

StdoutLoggerFactory.php

class StdoutLoggerFactory implements LoggerFactory
{

    public function __construct()
    {

    }
    public function createLogger(): Logger
    {
        return new StdoutLogger();
    }
}

FileLogger.php

class FileLogger implements Logger
{
    private $filePath;

    public function __construct(string $filePath)
    {
      $this->filePath = $filePath;
    }

    public function log(string $message)
    {
        // the method does not work
        echo "message: $message </br>";
    }
}

StdoutLogger.php

class StdoutLogger implements Logger
{
    public function __construct()
    {

    }

    public function log(string $message)
    {
        // the method does not work
        echo "message: $message";
    }

}

Tell me how to correctly use the Factory Method pattern in this construction?

dimanche 19 décembre 2021

Defining a Regex pattern for permutation string restriction in XSD

Trying to define a permutation string that allows only one character value occurrence. That is, no duplicate values. To use the simplest "abc" example:

<xsd:simpleType name="perm">
  <xsd:restriction base="xsd:string">
    <xsd:pattern value="[a-c]{0,1}" /> <!-- not sure this is sufficient for uniqueness -->
    <xsd:maxLength value="3" />
  </xsd:restriction>
</xsd:simpleType>

I need the further guarantee of prohibiting duplicate character values Valid values should only include the following permutations: [a-c]{1} a; or b; or c [the first candidate character works] OR a[bc]{1}; or b[ca]{1}; or c[ab]{1} [The second needs to exclusive OR the above and not AND or UNION of them ] ab, or ac; ba, or bc; ca, or cb OR abc, or acb; bac, or bca; cab, or cba [The Regex I know will not nest any of above combinations into exclusive ORs] The pattern I seek needs to disallow strings containing duplicate (or triplicate) character values for example aa, aba, aca, abb, ...cca, ... bcc, ... cbb, ... cbc, ... ccc

The StackOverflow FAQ says of Regex quantifier {min,max} occurrences: {n,m} means "repeat the previous element at least n times and at most m times" But that does not guarantee unique values via non-duplicate restriction because repeat can duplicate

Does XSD have a permutation restriction pattern construct?

My actual problem is for maintaining a permutation register for unique Hexadecimals 'digit' values with the same restrictions as above by saying:

<xsd:simpleType name="hexdecperm">
  <xsd:restriction base="xsd:string">
    <xsd:pattern value="[0-9a-f]{0,1}" /> <!-- for'integers' -->
    <xsd:pattern value="[1-9a-g]{0,1}" /> <!-- for'naturals' -->
    <xsd:maxLength value="16" />
  </xsd:restriction>
</xsd:simpleType>

Thanks in advance

MVVM Pattern in TypeScript (Angular)

Read many sources about design patterns but couldn't find fully described answer on my question. My questions are about MVVM Pattern:

  1. What is View in angular;
  2. What is Model in angular;
  3. What is ViewModel in angular. Would be greate if you described it in way of your understanding. Thanks!

Have no idea to gain the indexes of art and artist from the URL using C# [closed]

Here is the example of gaining the index of art and artist:

static string pixivURL = "https://pixiv.net/"; // Main URL of Pixiv website
static string artistIdx = pixivArtistURL.Replace(pixivURL+"users/", ""); // Artist number/index after "https://www.pixiv.net/users/"
public static string pixivArtistURL = pixivURL + "users/" + artistIdx; // Pattern of a Pixiv artist's URL
static string artIdx = pixivArtistURL.Replace(pixivArtistURL+"artworks/", ""); // Art index/number after "https://www.pixiv.net/artworks/"
public string pixivArtURL = pixivURL + "artworks/" + artIdx; // Pattern of the URL of an artwork/submission of a pixiv artist

protected static string test1 = "https://www.pixiv.net/users/artistIdx";
protected static string test2 = "https://www.pixiv.net/artworks/artIdx";

And I am now going to get the art index and artist index for following these patterns, but I really have no idea whether I coded properly and don't even know how to test to get the example of the index. ;(

How to deal with heterogeneous data sources in repository pattern?

Suppose you want to implement a repository patter for handling the data of the app. Imaging you have two Data Sources:

  1. Local cache (or database)
  2. Remote service (Rest API)

The service doesn't allow to make changes, but just to retrieve data, so a very simple interface for the data source could be

interface DataSource {
   suspend fun getClients(): Result<List<Client>> 
   suspend fun getClient(): Result<Client>
}

Both remoteDataSource and cacheDataSource will implement it.

However, the cacheDataSource needs to be filled with the data, so it would need an extra function, something like suspend fun addClients(clients: List<Client>), so I could be change the interface into:

interface DataSource {
   suspend fun getClients(): Result<List<Client>> 
   suspend fun getClient(): Result<Client>
   suspend fun addClients(clients: List<Client>)
}

This however would be bad, as the remoteDataSource will not implement addClients.

So I could remove that function from that interface and make cacheDataSource to implement another interface:

interface CacheClients {
   suspend fun cacheData(clients: List<Client>)
} 

The problem is now that my repository, which should just receive two instances of DataSource, wouldn't know about the other interface that the cacheDataSource is implementing.

What do you think is the best approach in this situation?

samedi 18 décembre 2021

How to distinguish which following archetecture have lower coupling?

I have read a bound of articles about coupling which all without exception view it from a high perspective. They rarely elaborate it with real projects.

So, there is a specific question I met:

Simplified model as following:

  • architecture 1
# m: module
      ---------                                                                 
      |context|
      ---------
     /  |    |  \
    /   |    |   \
----  ----  ----  ----
|m1|  |m2|  |m3|  |m4|
----  ----  ----  ----
  • architecture 2
# m: module
# al: abstract layer
      ---------
      |context|
      ---------
      /       \
   -----     -----
   |al1|     |al2|
   -----     -----
  /   |       |   \
----  ----  ----  ----
|m1|  |m2|  |m3|  |m4|                                                          
----  ----  ----  ----

The questions is:

  1. Which one have looser coupling than the other and why?
  2. If answer is latter, then is there any relation between loose coupling and more layers?

How to print this pattern, I NEED QUICK

could someone please help me how to print this pattern in python, You need to create a diamond-shaped layered pattern as the output of this challenge. Each layer of the pattern will conatin lower case english alphabets starting with a in the outermost layer then b in the layer within and so on. The alphabets in a single row are seperated by a specific string named fillChar.

Note: there are spaces before each row starts and no spaces after row is completed in the pattern.

Input Format

The first line of input contains a single integer n denoting the size of the pattern. For example, if n=5, then pattern will contain alphabets from a to e. the second line will contain the string fillChar.

    [IMAGE][1]A

vendredi 17 décembre 2021

Extracting characters between double quotes

In my project I need to extract some parameters from a settings file. Below is a section of the line that I am reading, the parameter I need to extract is the Program Prefix.

...  ProgramPrefix="" ReceiveTimeout="80000" ...

I need to extract what is between the double quotes for ProgramPrefix. The problem is that in-between these quotes can be any alphanumeric character, symbol, space, or no character at all.

Below is my current solution for extracting any character before the second double-quote, the problem it doesn't work for the case of nothing being between the double quotes

    EOPdefL = string.find(line,"ProgramPostfix=")
    EOPdef = string.match(line,'([^"]+)',EOPdefL+16)

When there is nothing in-between the double quotes the output for EOPdef is:

EOPdef = ReceiveTimeout=

I would like EOPdef to just return an empty string if there are no characters.

EOPdef = ""

how to design Page for Email Sending structure like Gmail design pattern in dot net core mvc

I have created Email API and also created controller in my application where I added API method as well, now I want to design a structure so that I can add emailId, subject, body like Gmail in design with their all feature in dot met core MVC.

Does including Collections in Entities violate what an entity is supposed to be?

I am building a Web API using Dapper for .NET Core and trying to adhere to Clean Architecture principles. The API is consumed by an external Angular front-end.

I have repositories that use Dapper to retrieve data from the database, and this data then passes through a service to be mapped into a DTO for display to the user.

It is my understanding that an entity should be an exact representation of the database object, with no extra properties, and that I should use DTOs if I require some additional properties to show the user (or if I wish to obscure certain properties from the user too).

Suppose I have a DTO:

public class StudentDTO
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public List<Assignment> Assignments { get; set;}
}

and its corresponding Entity:

public class Student
{
  public Guid Id { get; set; }
  public string Name { get; set; }
}

With this model, should I want to get a student with all of their assignments, I'd need to have two repository calls, and do something like this in the service:

public StudentDTO GetById(Guid id) 
{
  var student = this.studentRepository.GetById(id);
  var assignments = this.assignmentRepository.GetByStudentId(id);
  return SomeMapperClass.Map(student, assignments);
}

But this seems inefficient and unnecessary. My question is, should I not just retrieve the Assignments when I get the student entity in the repository, using a JOIN? Or would this violate what an entity is supposed to be?

I apologise, I do realise this is a rather simple question, but I'd really like to know which method is the best approach, or if they both have their use cases

jeudi 16 décembre 2021

Java - Generic for Payment processing with Strategy pattern

I am trying to implement Strategy pattern approach for payment processing in my Spring webflux based application.

My application supports multiple payment method like, Card Payment, Cash Payment, ... Also, we have to support Square & Stripe for Card payment.

Model class,

// Model interface
public interface PaymentModel {

}

// Base model with attributes needed for all payment types
public class BaseModel implements PaymentModel {

    private Float amount;
    private Integer userId;
}

public class SquareCardModel extends BaseModel {

    private String merchantId;
    private String device;
    private String orderId;

}

public class StripeCardModel extends BaseModel {

    private String merchantId;
    private String orderId;

}

public class CashModel extends BaseModel {

    private String name;
    private String orderId;

}

Service Class,

@Service
public interface PaymentService<T extends PaymentModel> {

    Mono<ServerResponse> pay(T model);

    String method();
}

@Service
public class CashPaymentService implements PaymentService<CashModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(CashModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

@Service
public class SquarePaymentService implements PaymentService<SquareCardModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(SquareCardModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

@Service
public class StripePaymentService implements PaymentService<StripeCardModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(SquareCardModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

Factory Class,

@Service
public class PaymentFactory<T> {

    private final List<PaymentService<? extends PaymentModel>> paymentServices;

    @Autowired
    public PaymentFactory(List<PaymentService<? extends PaymentModel>> paymentServices) {
        this.paymentServices = paymentServices;
    }

    public PaymentService<? extends PaymentModel> retrievePaymentService(final String paymentMethod) {
        Optional<PaymentService<? extends PaymentModel>> paymentService = paymentServices.stream()
                .filter(service -> service.method().equals(paymentMethod)).findFirst();

        if (paymentService.isEmpty()) {
            throw new IllegalArgumentException("Unsupported Payment method ");
        }
        return paymentService.get();
    }

}

User choose the payment method and the call comes to the backend,

@Transactional
    public Mono<ServerResponse> payBilling(ServerRequest request) {
            return request.bodyToMono(PaymentDto.class).flatMap(paymentReq -> {
                if (paymentReq.getPaymentType().equals("CC")) { // For Card
                    return processCardPayment(usr, paymentReq);
                } else {
                    return badRequest().bodyValue("Not supported yet !");
                }
            });
    }

private Mono<? extends ServerResponse> processCardPayment(
            PaymentDto paymentReq) {
            PaymentService<PaymentModel> paymentService = (PaymentService<PaymentModel>) paymentFactory
                    .retrievePaymentService(paymentReq.getPaymentType());
            PaymentModel paymentModel = buildPaymentModel((String) paymentReq.getPaymentType(), paymentReq,
                    jsonMap);
            return paymentService.pay(paymentModel);
    }

    private PaymentModel buildPaymentModel(final String paymentMethod, final PaymentDto paymentReq,
        if (paymentMethod.equals("squarePayment")) {
            SquareCardModel model = new SquareCardModel();
            model.setAmount(paymentReq.getTotal());
            model.setMerchantId(paymentReq.getMerchantid());
            model.setOrderId(orderId);

            return model;
        }

        return null;

    }

Questions:

  1. Not sure if I have implemented generics properly with the strategy pattern.
  2. Also, I dont like type casting here. (PaymentService). is there any better approach?
  3. Why do I still need to use if for creating different model.

if (paymentMethod.equals("squarePayment")) {

PaymentService<PaymentModel> paymentService = (PaymentService<PaymentModel>) paymentFactory
                        .retrievePaymentService(paymentReq.getPaymentType());
                PaymentModel paymentModel = buildPaymentModel((String) paymentReq.getPaymentType(), paymentReq,
                        jsonMap);
                return paymentService.pay(paymentModel);

mercredi 15 décembre 2021

Has the recombine step been left out of modern education?

My first programming instructor taught me to code correctly the first time, by verifying all code on paper before we even touched a computer.

Many of the modern code analysis tools flag long methods for being too long, by exceeding some arbitrary length.

These programs purpose splitting a "long" method into several single-use methods.

Designing, writing and testing with these many smaller methods and classes is easier, no question.

However, newcomer(outside) readability degrades with each split.

When I was taught to split the design into parts, I was also taught to recombine single-use methods and in-line multi-use methods as much as possible.

My question is: Has the recombine step been left out of modern CS education?

Suitable Design pattern [closed]

I am looking for the suitable design pattern for my use case. Let's I have list of account and I would like to enrich each of the account depends of the criteria. e.g.:

  • if the account belongs to US account, account will be prepend with prefix US
  • all the confidential field will be masked
  • etc

I am thinking to use pipeline to solve this problem. Can someone give some advise?

Pipeline design pattern implementation

Thanks

A design pattern or architecture related to rendering components based on roles and permissions?

I want to know if there's a software design pattern that can solve a challenge I'm facing. I have a web application that works with several different user role types like SuperAdmin, Admin, Reseller, Dealer, Customer, Volunteer, etc...

And our React code is littered with if statements that check a person's role as well as other conditions to decide "what type of ui component" to present them. Here's a very simplified example:

// Container.js
<div>
   <h1>Something</h1>
   {['SuperAdmin', 'Admin'].includes(user.role) && (<input type="text" value="{record.first_name}" />)}
   {['Reseller', 'Dealer'].includes(user.role) && (<span className="border-2">{record.first_name}</span>)}
   {['Customer', 'Volunteer'].includes(user.role) && process.env.NETWORK_MODE === 'intranet' && (
    <div className="bg-grey">
        <span>Created at {record.create_at}</span>
        <span>This customer wants to be anonymous</span>
    </div>
   )}
   {['Reseller'].includes(user.role) && user.accountBalance > 0 && user.statementDate > (new Date()) && (
     <div>Please pay your bills</div>
   )}
</div>

The above example is very difficult for us to manage because there are over 100 components . When we need to change the access permissions for a role type or add other conditions, we have to go through every component and look for any stray if statements. We were thinking of writing some automated tests, but feel like we need to refactor the UI code before that's practical.

Are there some software engineering design patterns that would be relevant to my situation? If so, just state the names and i'l read up on it.


Right now, I'm contemplating an approach like this:

// Container.js
<div>
   <h1>Something</h1>
   <Customer user={user} />
   <BillNotice user={user} />
</div>

// Customer.js
const Customer = ({user}) => {
   if(['Admin', 'SuperAdmin'].includes(user.role)) return <CustomerVersion1 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <CustomerVersion2 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <CustomerVersion3 />;
   ...etc...
}

const CustomerVersion1 = () => <Component />;
const CustomerVersion2 = () => <Component />;
const CustomerVersion3 = () => <Component />;

...etc...

// BillNotice.js
const BillNotice = ({user}) => {
   if(['Admin', 'SuperAdmin'].includes(user.role)) return <BillNotice1 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <BillNotice2 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <BillNotice3 />;
   ...etc...
}

const BillNotice1 = () => <Component />;
const BillNotice2 = () => <Component />;
const BillNotice3 = () => <Component />;

Basically I'm making each component responsible for deciding how it should present itself. Then I can write unit test for each component by mocking the user argument and see if the appropriate component is returned. If this approach actually has a name, that would be great and I can read up more on it!