jeudi 31 mars 2022

how to design this music player in oops java

Functional Requirements

A user can create a playlist from a pool of available songs. A user can delete a playlist. A user can add / delete songs from the playlist. A user can start playing songs by choosing a playlist. On choosing a playlist, the first song in the playlist will start playing. A user can switch songs by using Next, Back command or by choosing another song from the playlist that has been chosen. On reaching the end, Next will switch to the first song in the current playlist. On reaching the start, Back will switch to the last song in the playlist. Only one song can be played at a time. A user can choose to play the song from another playlist if and only if that playlist is selected. Basically two operations have to be done to successfully play the song of their choice. Select the playlist ( which will play the first song when selected ) Choose the song of your choice. An album is a collection of songs owned by the original artist / artist group . Artist Group Example:- One Direction. One Direction Group is the album owner and is considered as an artist. Each song can feature multiple artists but it will be owned by the artist whose album this song belongs to. Each song can only be a part of one album.

May I ask what design pattern is this? (Java) [closed]

May I ask what design pattern is this? It is in programmed in Java language. What would be the best way you recommend people to learn design pattern? In your opinion, how important design pattern is? The code snippet is attached below:

interface Window{
    public void draw();
}

class Simplewindow implements Window {
    public void draw() {
        // draw simple window
    }   
}

abstract class WindowEnhancement implements Window{
    protected Window window;
    
    public WindowEnhancement(Window window){
        this.window=window;
    }
}

class ScrollBarEnhancement extends WindowEnhancement{

    public ScrollBarEnhancement(Window window) {
        super(window);
    }

    public void draw() {
        drawScrollBars();
        window.draw();
    {

    private void drawScrollBars() {
        // draw scroll bars
    }
}
class WindowTest{
    public static void main(String[] args) {
        Window w= new ScrollBarEnhancement(new Simplewindow()); w.draw();
    }
}

Thank you for your help.

Pattern to Angular placeholder cache of http response

I want to implement a cache solution that follows these principles:

  1. The app will always fetch the real data from the back-end even if there's cache available. Backend data will then replace the cache after it is available.
  2. The front-end doesn't need to whether data was updated or not in the backend. This needs to be true even after HTTP calls, the front-end wouldn't need to know that an HTTP Post or HTTP Delete in an endpoint will change some data.
  3. The user should only be able to interact with data that is up to date, this means that interaction with data should never end with a message like "this data doesn't exist anymore".

In summary, the cache only will only act as a placeholder for the real data.

The initial solution that I thought about is to simply implement a wrapper of HttpClient that saves the response of GET requests into localStorage using the request data as a key, so that next time this same request is sent, the wrapper would send an Observable that first emits the cache and then emit the real data from the request.

The main problem is that it's is not based on a known pattern, only a solution that came from my head. The second problem would be with the fact that the component would need to differentiate data that users can interact with from data that does not, which would probably be the source of many bugs.

So, what would known alternatives patterns to implement this, and what is the pro and cons of those patterns.

Which kind of design pattern is this?

So I have this code below and wanted to know from which kind of PHP design patterns is this?


  public static function newInstance($driver) {
    $file = dirname(_FILE_).'/drivers/'.$driver.'.php';
    if (include_once($file)) {
      $driverClass = $driver . 'Driver';
      return new $driverClass;
    } else {
      throw new Exception('Database driver not found');
    }
  }
}


$db = DatabaseDriver::newInstance('MySQL');

mercredi 30 mars 2022

Does Spring dependency injection really make the goal loose coupling?

Spring is famous with it Inverse Control and DI.

I know that dependency injection have several ways like Constructor Dependency Injection etc.

for example

we usually use @Autowired annotation to do Dependency Injection.

when we develop MVC web project.

My question is very simple

Why is a spring framework loosely coupled?

Suppose We have two Dao class One is Dao1 ,other is Dao2

Dao1

public class Dao {
    
    
    public void sayhi() {
        System.out.println("hello");
    }
}

Dao2

public class Dao2 {
    
    public void saygoodbye() {
        System.out.println("say goodbye");
        
    }
}

If we do not use Autowired annotation

the service should be

public class Service {
    
    Dao1 dao=new Dao1();
    
    Dao2 dao2=new Dao2();
    
    public void sayhi() {
        dao.sayhi();
        
    }
    
    public void saygoodbye() {
        
        dao2.saygoodbye();
        
    }
    
}

and the Controller should be

@RestController
public class Controller {
    
    
    Service service=new Service(     );
    
    @GetMapping("test")
    public void saysomething() {
        service.saygoodbye();
        service.sayhi();
    }
    
}

If we do not use Autowired annotation , we must use new keyword to make instance

If we use Autowired annotation

the code

Dao1 dao=new Dao1();
    
Dao2 dao2=new Dao2();

just change it into

@Autowired
Dao1 dao

@Autowired
Dao2 dao2

So,without Autowired annotation

Why is a spring framework loosely coupled?

Triangle pattern in Java with while loop

Hello I was Tasked to make an triangle generator with the symbols and number of rows that users want in java with while loop it worked like this.


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

But I want like this

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

Here is my code

import java.util.Scanner;
import java.lang.Math;

class Main {
 public static void main(String args[]){
  
  ////////////OBJECTS///////////////////////

  Scanner sc = new Scanner(System.in);
  Scanner sc2 = new Scanner(System.in);
  ///////////////////////INPUTS//////////

  System.out.println("Please Enter how many rows do you want");
  int inp = sc.nextInt();
  
  System.out.println("Which symbol do you want");
  String str2 = sc2.nextLine();
 ////////////////VARIABLES///////////////////

  int c = 0; 
  String str = "";
  String str3 = "";
  System.out.println("=====================");

  ///////LOGIC/////////////////////////////

  while(c != inp){
   str = str+str2; 
   System.out.println(str);
   c=c+1;
  }

////////////////////////////////////////////
  
 }
 
}

Do you know that how can i solve it with this logic

JS Method Chaining Controlling Flow

I have created a method in Typescripty which utilizes method chaining to create a simple sql query builder. It implements the basic query methods. What I would like to do is not allow someone to call the offset method for example if they havent called limit previously or calling where twice. I know I can implement something via a map which stores the previously called methods but I was wondering if there is a clean solution to this problem. My current query builder method is

public qb = () =>
{
    let query = this.SELECT;
    const api = {
        where: (key: string, value: number|string) =>
        {
            query = sql`${query} WHERE ${sql.identifier([key])} = ${value}`;
            return api;
        },
        and: (key: string, value: number|string) =>
        {
            query = sql`${query} AND ${sql.identifier([key])} = ${value}`;
            return api;
        },
        orderBy: (key: string, order: 'ASC'|'DESC') =>
        {
            query = sql`${query} ORDER BY ${sql.identifier([key])} ${order}`;
            return api;
        },
        limit: (limit: number) =>
        {
            query = sql`${query} LIMIT ${limit}`;
            return api;
        },
        offset: (offset: number) =>
        {
            query = sql`${query} OFFSET ${offset}`;
            return api;
        },
        get: async () => this.rowMapper(await this.database.query(query)),
    };
    return api;
};

Is there a nice way to force the flow of the method chaining?

Key factors for choosing a framework depending on project size [closed]

Please don’t get the question wrong. This is not A vs B question.

I know that any programming language can bring a project to life.

But many people when the compares frameworks they say this is suitable for medium and large size project. First what makes a web app project medium or large size ?

The size of team working behind it or Is it the code it self or deployment on multi servers or both ?

What make such framework dedicated objectively more than other for this kind of development?

The isolation/decoupling of modules/components is a key factor?

There’s any pattern to follow to make decision before starting?

Thank you.

Implementing uniform gradient across two divs in html css

I created two designs in Adobe XD.

Text Text

I can achieve the first design in HTML with two divs or one div and its after etc. How do I achieve the second design in HTML and CSS?

I also want to add the border so I can't use clip-path either.

mardi 29 mars 2022

What is the name of the approach with ErrorCollector-s?

I have written code with C++ for the last five years. And pretty often, I see something like a class ErrorCollector. The first I saw it using boost::asio. After that, I saw it at GLUT. And today, I saw it again in my work code.

I know what it is and understand how it works. I want to see the name of this approach\mechanism.

Thank you very much in advance!

I tried to ask this question to our Senior team members. But nobody knows the name of it.

Also, of course, I tried to google. The same result.

what design pattern should i use to let the user decide the order that methods will be performed by

I have a class in which the Start() method calls many different methods in certain order. Each method can be called multiple times. There is a need to change this class in such way that in run-time the order of the methods will be defined and then the Start() method will run the methods in the defined order. What would be the best design pattern to use to achive this goal in c# ?

pseudo code example of the current implementation which i wish to change:

class Executer
{
   public Executer() { InitializeOrderOfMethodsBasedOnUserInput(); }

   public void Start()
   {
      /* some code here */
      
      PerformA();
      PerformC("C", 0);
      PerformA();
      PerformB(1);
      PerformB(9);
      PerformD();
   }

   private void PerformA() {}
   private void PerformB(int b) {}
   private bool PerformC(string c, int x) {}
   private void PerformD() {}
}

Desgin of form? [closed]

i have a problem to design a form which has more than 10 inputs and it should be dynamically for example a school has two types of staff, Admin & Teacher and we don't know how many teacher or admin staff will be in school so we need to make dynamically form(HTML+JQUERY) to get their name ,email, contact, designation , qualification , joining date ,salary , experience & contact . if i design in table ROW it look ugly even cannot read the table heading words or textboxes in TD due to number of textbox. if i make in div and call the div dynamically it also not good design , do you have any idea to make it good.

How to design real time pagination capabilities

Problem I have a gateway that fetch data from multiple sources(user data like name age id location..) deployed across regions with separate database per service(due to compliance personal data cannot be cached on gateway but still things like id(primary key) can be cached, how to design get users endpoint that returns list of users paginated with having filter like name age location...

lundi 28 mars 2022

Alias Rails Model with Scope as different class

I have a rails model with a scope that I would like to be able to use as a separate class for future semantics consistency. An example of this would be -

class User
  scope :admin, => { where(admin: true) }
end

For my purposes, it's important that documentation and code is clearer than calling User.admin whenever I want to work with just admins, without creating a separate model. (Schema is identical, and there is more than 1 scope I need to move into a separate object).

My current solution is

class Admin
  @@receiver = User.admin

  def method_missing(m, *args, &block)
    @@receiver.send(m, *args, &block)
  end

  def self.method_missing(m, *args, &block)
    @@receiver.send(m, *args, &block)
  end
end

This way, I can use Admin as an ActiveRecord::Relation where ever I need.

Is this an effective means of solving the issue? Because of gems we're running, I cannot inherit User, or it will start using STI and get really weird really quickly.

Does Singleton Class object in application wherever in use consider as Aggregate relationship?

In definition Aggregate relationship desn't have owmership on relational data.

So according to definition all singleton instance of classes should be called as Aggregation relationsip. Am I right?

Does Singleton objects in application used as Aggregate relationships?

In definition Aggregate relationship desn't have owmership on relational data.

So according to definition all singleton instance of classes should be called as Aggregation relationsip. Am I right?

Service layer user vs admin best practice

Have an application that is quiet large and am rethinking some of the design and wondering if the practices currently in use are correct. I will keep it simple as there its not about coding.

Assume we have a method in a service that we call like _userService.GetUser(..). This method returns a user as expected. If the method is called for a logged in user the method has checks to ensure the user can only see their details.

Now if the method is called by administrator they can retrieve any user and checks are bypassed. Again code not important here.

Questions

  1. Better to separate out the methods per user and per admin
  2. Better to have UserService and AdminUserService?
  3. Should the check be done at DB level and not return a record if it does not match criteria or after loading the entire object and checking properties (current practice)

I am wondering if there are best practices for this because looking at various large projects it seems that most systems write single methods and just deal with logic to determine what to do for the incoming request.

dimanche 27 mars 2022

How to manage options in PySpark more efficiently

Let us consider following pySpark code

my_df = (spark.read.format("csv")
                     .option("header","true")
                     .option("inferSchema", "true")
                     .load(my_data_path))

This is a relatively small code, but sometimes we have codes with many options, where passing string options causes typos frequently. Also we don't get any suggestions from our code editors. As a workaround I am thinking to create a named tuple (or a custom class) to have all the options I need. For example,

from collections import namedtuple
allOptions = namedtuple("allOptions", "csvFormat header inferSchema")
sparkOptions = allOptions("csv", "header", "inferSchema")
my_df = (spark.read.format(sparkOptions.csvFormat)
                     .option(sparkOptions.header,"true")
                     .option(sparkOptions.inferSchema, "true")
                     .load(my_data_path))

I am wondering if there is downsides of this approach or if there is any better and standard approach used by the other pySpark developers.

Mongodb: $regexMatch after converting array $toString not working as expected

I'm using Mongo's $regexMatch operator to find documents where at least part of a field matches the pattern, and this works fine for root-level fields, but the search document has an array with an array field inside. But how do I use it with array fields? I want to return a match if at least one of the array elements matches the pattern.

db.companies.aggregate(
[{$geoNear: {
 near: {
  type: 'Point',
  coordinates: [
   -3.128145200960907,
   -59.99944718666838
  ]
 },
 maxDistance: 10000,
 distanceField: 'dist.calculated',
 spherical: true
}}, {$lookup: {
 from: 'flyers',
 localField: '_id',
 foreignField: 'company',
 as: 'flyers'
}}, {$project: {
 _id: 1,
 socialReason: 1,
 'profile.logo': 1,
 flyers: {
  $filter: {
   input: '$flyers',
   as: 'flyers_ativados',
   cond: {
    $eq: [
     '$$flyers_ativados.status',
     'Ativado'
    ]
   }
  }
 }
}}, {$project: {
 flyers: {
  $filter: {
   input: '$flyers',
   as: 'flyers_ativados',
   cond: {
    $or: [
     {
      $regexMatch: {
       input: '$$flyers_ativados.title',
       regex: 'kuka'
      }
     },
     {
      $regexMatch: {
       input: '$$flyers_ativados.description',
       regex: 'kuka'
      }
     },
     {
      $regexMatch: {
       input: {
        $toString: '$$flyers_ativados.tags'
       },
       regex: 'carne'
      }
     }
    ]
   }
  }
 }
}}])

MongoServerError: PlanExecutor error during aggregation :: caused by :: Unsupported conversion from array to string in $convert with no onError value

very grateful for any suggestion

How to apply Command Design pattern with Dependency Injection using Generic Class?

i want to apply command Design pattern with dependency Injection in the following situation: i have three types of reports in my system (SubscriptionReport, SalesReport, SpechialistReport) so i created one interface IReportService

public interface IReportService<T> where T: class
    {
        public Task<GenericResponse<List<T>>> GetReport(string searchKey, DateTime from, DateTime to);

    }

and to apply OCP i have implemented the GetReport function tree times for (SubscriptionReport, SalesReport, SpechialistReport)

public class SpechialistReportService : IReportService<SpechialistReportDTO>
    {
        public Task<GenericResponse<List<SpechialistReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
        {
            throw new NotImplementedException(); // to be implemented later
        }
    }

 public class SubscriptionReportService : IReportService<SubscriptionReportDTO>
    {
        public Task<GenericResponse<List<SubscriptionReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
        {
            throw new NotImplementedException(); // to be implemented later
        }
    }
 public class SalesReportService : IReportService<SalesReportDTO>
    {
        public Task<GenericResponse<List<SalesReportDTO>>> Report(string searchKey, DateTime from, DateTime to)
        {
            throw new NotImplementedException(); // to be implemented later
        }
    }

after that i have added the dependency

    services.AddScoped(typeof(IReportService<SpechialistReportDTO>), typeof(SpechialistReportService));
    services.AddScoped(typeof(IReportService<SubscriptionReportDTO>), typeof(SubscriptionReportService));
    services.AddScoped(typeof(IReportService<SalesReportDTO>), typeof(SalesReportService));

the problem is in calling the dependency in the controller constructor

 private readonly IEnumerable<IReportService> _reportService; // Should be IReportService<dont know what class should i specify here>

        public ReportController(IReportService<T> reportService)
        {
            this._reportService = reportService;
        }

Any help would be appreciated thanks in advance,

How to use socket gateway on NestJS services/controllers?

I'm working on a NestJS monolith application, in the near future, we'll break it into microsservices, but right now everything is on the same project.

I have a few REST APIs for database crud operations, and right now, I'm working on a new feature that is going to receive a payload from the frontend trough a websocket connection, and will then call a few methods on a specific server.

Right now, I'm a completely newbie on sockets and a beginner on Nest, so this might be an obvious and dumb question

I'm following Nest's documentation: https://docs.nestjs.com/websockets/gateways, but I'm not sure how to apply some of that on a real life application. My socket.gateway.ts has a handleConnection and a sendMessage method, but I need some advice for listening to new events. Right now, the only way I can receive messages is using @SubscribeMessage on a method inside my .gateway.ts class. But that way, my gateway must inject every service that needs to receive a socket connection payload, so I would need a new method inside my gateway for every "action", like I would if I used REST endpoints on a controller.

So, here's my questions:

  1. Following best practices, how should I receive events payload inside my other services? Should I treat the gateway as if it was "kind-of" a controller? Like a method for every "endpoint" (event) I need to receive payload on?
  2. In case question one is correct, should I have a new gateway for every service (like 1 gateway for UserService, another for AppService, and another for MessageService, just like a controller)?
  3. Also, as an extra question... My backend URL is https://example.com/service-name/example, that address is not callable trough my frontend... It tries to reach example.com, not the full URL, what am I missing?

ALSO: I'm not stuck to Nest socket.io lib, I could use another one, but I do prefer to keep using Nest's native lib as it's not my decision only, so...

Edit: I realized my question about "different services" might actually be better interpreted as "different domains".

samedi 26 mars 2022

what do I need to change for this pyramid to print correctly.. can someone walk me through the process with comments

for i in range(5): #number of rows to print

    for space in range(5-i): #prints 5 spaces decrementing by one for every row
        print(' ',end = '')

    for cols in range(5-space): 
        print('*',end='')

I get lost after my second comment im not sure if the first inner loop will execute completely before the start of the second inner loop.

Should I separate transferred data in DTO and options changing method's behavior?

I have a classic DTO interface (Typescript):

interface GetCurrencyDto {
   id?: string
   ticker?: string
   name?: string
}

But what if I want to add options that will change the flow of my service method? Would it be better to create another interface GetCurrencyOptions for service-method paramter named options containing something like: throwError?: boolean, useCache?: boolean, useRelations?: string[], etc.? Or all of them must be part of dto?

React provider pattern in other languages

Sorry for this question

I'm at the process of learning react in a good way and days ago when I finally get how the contexts and providers works on my mind I just fell in love with this technique.

Do you know if there is a pattern that can be applied to other languages like java, c# or python? or if there is a framework or library for working with that on these language

vendredi 25 mars 2022

Is this a valid implementation of Memento Pattern?

I've been studying design patterns from GOF for a few weeks, especially in C#, and I'm struggling with Memento Pattern. I know there is a lot of C# implementations on the web, but I came with my own version of it. The question is: although it diverges from GOF UML, is it still reasonable and valid considering SOLID principles?

What is your opinion?

interface IMemento
{
    List<IMemento> Mementos { get; set; }

    void SetMemento();
    IMemento? GetMemento(uint index);
    IMemento? GetPreviousMemento() => (Mementos.Count > 1) ? Mementos[Mementos.Count - 2] : null; // Optional method
}

class Subject : IMemento // Originator
{

    public Subject(string prop1, int prop2)
    {
        Prop1 = prop1;
        Prop2 = prop2;
        SetMemento();
    }

    private string _prop1;
    public string Prop1 
    {
        get => _prop1;
        set
        {
            _prop1 = value;
            SetMemento();
        }
    }

    private int _prop2;
    public int Prop2
    {
        get => _prop2;
        set
        {
            _prop2 = value;
            SetMemento();
        }
    }

    public List<IMemento> Mementos { get; set; } = new List<IMemento>(); // Caretaker

    public void Method1() { }
    public void Method2() { }

    public void SetMemento() => Mementos.Add((IMemento)MemberwiseClone());
    public IMemento? GetMemento(uint index) => (index < Mementos.Count) ? Mementos[(int)index] : null;
    public IMemento? GetPreviousMemento() => (Mementos.Count > 1) ? Mementos[Mementos.Count - 2] : null;
}

I've already tested and from my point of view, the only big problem can be with memory consume, but that is a normal issue when it comes to Memento and it can be solved with Flyweight, for example.

The refactoring method must either RedirectToAction or do nothing. How can I achieve that?

I'm trying to refactor my controller code. I want to extract a piece of code used in any method of my controller, but this piece of code could either return a RedirectToAction or do nothing. I don't see how I can write my refactor method in order to have 2 differents type of return.

My explanation seems a bit confuse but the code is really simple :

This is the code I want to refactor

 public async Task<IActionResult> Texts()
 {
    var model = new FeaturesViewModel();
    try
    {
        // The code I want to extract
        var currentPage = await _customersRepository.GetCustomersPageAsync(currentRoute);
        if (currentPage == null)
        {
           return RedirectToAction("Error", "Home", new { statusCode = 404 });
        }
        this.RouteData.SetPage(currentPage);

        // any code
    }
    catch (Exception ex)
    {
        // any code
    }
    return View(model);
}

This is the new code :

 public async Task<IActionResult> Texts()
 {
    var model = new FeaturesViewModel();
    try
    {
        // extracted code 
        await GetCurrentPageAsync(this.RouteData.GetRoute());

        // any code
    }
    catch (Exception ex)
    {
        // any code
    }
    return View(model);
}

// the new method wich will be using in every action
private async Task<IActionResult> GetCurrentPageAsync(string currentRoute)
{
   var currentPage = await _customersRepository.GetCustomersPageAsync(currentRoute);
   if (currentPage == null)
   {
       return RedirectToAction("Error", "Home", new { statusCode = 404 });
   }
   this.RouteData.SetPage(currentPage);

   // the problem is : when I get to this line, it doesn't return to the calling method...
}

I haven't tried much because I am wondering wether this is achievable or this is a design dead-end ?

I 've tried passing the name of the action as parameter and do a "return RedirectToAction(action_parameter)". But of course, this is not working as I return back at the beginning of the action and not from where I left.

Thnaks for yours advices !

Best way to propagate a data structure from a chain of project dependencies

I have a Controller project which calls a Provider project, and the Provider project calls 3rd party library:

Controller --> Provider --> 3rd Party

The controller want to get a data structure (let's say CustomInfo) from the 3rd Party. The CustomInfo has various data fields: enum, String, int, etc. There are two ways to do this I am aware of:

  1. Import the 3rd Party library to the Controller project. Thus, the Controller project knows the CustomInfo data structure. But this way seems bad because of adding another coupling of the Controller with the 3rd Party library.
  2. Copy and Paste the CustomInfoclass definition from 3rd Party to Provider project. Then the Controller will only need to depend on the Provider project. But seems copy/paste class definition is a bad behavior too.

So which method is better? Or is there a 3rd method to solve this problem?

Best way to propergate a data structure from a chain of project dependencies

I have a Controller project which calls a Provider project, and the Provider project calls 3rd party library:

Controller --> Provider --> 3rd Party

The controller want to get a data structure (let's say CustomInfo) from the 3rd Party.The CustomInfo has various data fields: enum, String, int, etc. There are two ways to do this I am aware of:

  1. Import the 3rd Party library to the Controller project. Thus, the Controller project knows the CustomInfo data structure. But this way seems bad because of adding another coupling of the Controller with the 3rd Party library.
  2. Copy and Paste the CustomInfoclass definition from 3rd Party to Provider project. Then the Controller will only need to depend on the Provider project. But seems copy/paste class definition is a bad behavior too.

So which method is better? Or is there a 3rd method to solve this problem?

jeudi 24 mars 2022

Satisfying the borrow checker with a struct that processes a queue of actions

I am trying to write a struct which owns some data in a Vec (or perhaps contains a Vec of mutable references - not really important which one), and which can process a queue of "actions", where each action is some sort of calculation which mutates the elements of this Vec. Here is a minimal example of what I have written so far:

// some arbitrary data - may be large, so should not be cloned or copied
#[derive(PartialEq)]
struct T(i32, &'static str);

struct S(Vec<T>);
impl S {
    fn get_mut(&mut self, t: &T) -> &mut T {
        self.0.iter_mut().find(|a| *a == t).unwrap()
    }
    fn process_actions(&mut self, queue: ActionQueue) {
        // some arbitrary calculation on the elements of self.0
        for a in queue.actions {
            let t1 = self.get_mut(a.t1);
            t1.0 += a.t2.0;
        }
    }
}

#[derive(Debug)]
enum Error {
    ActionError,
    ActionQueueError,
}

struct Action<'a> {
    s: &'a S,
    t1: &'a T,
    t2: &'a T,
}
impl<'a> Action<'a> {
    pub fn new(s: &'a S, t1: &'a T, t2: &'a T) -> Result<Action<'a>, Error> {
        if s.0.contains(&t1) && s.0.contains(&t2) {
            Ok(Action { s, t1, t2 })
        } else {
            Err(Error::ActionError)
        }
    }
}

struct ActionQueue<'a> {
    s: &'a S,
    actions: Vec<Action<'a>>,
}
impl<'a> ActionQueue<'a> {
    pub fn new(s: &'a S, actions: Vec<Action<'a>>) -> Result<ActionQueue<'a>, Error> {
        if actions.iter().all(|a| std::ptr::eq(a.s, s)) {
            Ok(ActionQueue { s, actions })
        } else {
            Err(Error::ActionQueueError)
        }
    }
}

fn main() -> Result<(), Error> {
    let t1 = T(1, "a");
    let t2 = T(2, "b");
    let mut s = S(vec![t1, t2]);

    let a = Action::new(&s, &t1, &t2)?; // error: borrow of moved value: `t1`
    let q = ActionQueue::new(&s, vec![a])?;
    s.process_actions(q); // cannot borrow `s` as mutable because it is also borrowed as immutable

    Ok(())
}

There are a few problems with this:

  1. I can't create the Action because t1 and t2 have already been moved.
  2. Even if I could, I can't process the action queue because s is already immutably borrowed in the Action. The reason I want the Action (and ActionQueue) to contain a reference to s is because, from what I understand, it's good to use types prevent the creation of invalid data, e.g. an Action (to be processed by s) referring to data not contained in s.
  3. The get_mut function of S seems a bit weird and hacky, like I shouldn't need to have such a function.

I understand why the errors occur and what they mean, but I don't see any way to get around this problem, because in order to define any Action, I need to refer to elements of s.0 which I am not allowed to do. So my question is, how should this code be rewritten so that it will actually compile? It doesn't matter if the design is completely different, as long as it achieves the same goal (i.e. allows to queue up actions to be processed later).

Multiple unnamed namespaces in the same scope?

I'm looking at the pytorch codebase, and I see multiple anonymous namespaces in the same scope like https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/quantized/cpu/qpool.cpp#L23 and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/quantized/cpu/qpool.cpp#L226

What is the point of this design? Couldn't we just combine them?

R UDF outputs structure for Shiny plotly outputs and DT outputs

I have a UDF in R, which I use to output various, sometimes heavy, plotly graphs. What I have been doing so far is to return them as a list

global.R

myGraphingFunction <- function(inputs){

A <- ggplotly(ggplot(...))
B <- ggplotly(ggplot(...))
C <- ggplotly(ggplot(...))
return(list(Plot1 = A, Plot2 = B, Plot3 = C))
} 

I then go on the index out what plot I need based on where I am in my shiny interface.

This works fine for me, but with heavy dataload, this takes my shiny app many minutes to evaluate. I am wondering if it would be far better if instead of evaluating all the graphs with the UDF, I parameterize which graph output I would need with some extra arguments, and then in the server function call the function multiple times to get all the graphs separately, something like:

global.R

myGraphingFunction <- function(inputs, graphSelectionInputs){

if(graphSelectionInputs == "a"){
plot <- ggplotly(ggplot(...))
} else if(graphSelectionInputs == "b"){
plot <- ggplotly(ggplot(...))
} else {
plot <- ggplotly(ggplot(...))
}

return(plot)
} 

server.R

output$plot1 <- renderPlotly({myGraphingFunction(input, "a")})
output$plot2 <- renderPlotly({myGraphingFunction(input, "b")})
output$plot3 <- renderPlotly({myGraphingFunction(input, "c")})

Bear in mind that I shall always need to invoke each of the graph outputs of the function. That being the case, is there an added value in the aforementioned parametrization? Also, would the differences between the two approaches behave the same for DT outputs? I could not find any literature on the matter myself, I think because this is a very specific use case. I should appreciate any input from users experienced with these sorts of design practices.

mercredi 23 mars 2022

Program design - update global variable value

Suppose I have a global variable pi=3.14 in a script. In most cases, the pi is used as 3.14 in functions and classes in the script. However, the user might need to change the value sometimes. Can the user change the value of pi in the script without modifying the script? (The user don't want to pass the pi to the function as argument.)

For example, the user defines his own pi in another script or Jupyter notebook, and import the relevant functions and classes. Then, the functions and classes will use the new pi. From a software design perspective, is there a good way to do that?

Thank you in advance!

How to make reusable GUI components in JavaFX

Let's say I need to show Alert in my code, but before I show it, I would like to add for example my stylesheets and set text that I have already defined in some ResourceBundle.

So if I need this object more in more than one place in code what pattern should I use to do that? And let's say I have more that one such configured Alerts.

I can go with

  • wrapper/decorator pattern (but I'll have to extend JavaFX alert and forward all their methods)
  • just extend JavaFX alert and make comfortable constructor that will also do my setup
  • make factory for this concrete Alert config that will do setup
  • @Named("ConcreteAlert") Alert concreteAlert + Guice (or provider/factory etc.)

But all of these solutions doesn't feel right. Inheritance would provide comfortable instantiation using custom constructor but hard to maintain. As for Guice, there will be too much Named annotations with all my Alerts (but maybe it is fine, IDK).

Sort of Alerts utility class with static factory named methods for different alerts seems like solution, but I would like to know if it is best fit here.

Javascript design pattern publish-subscribe

I'm learning and practicing Javascript publish-subscribe design pattern.

Here is the code: https://codesandbox.io/s/javascript-forked-5vb602?file=/index.js.

What my issue is, when I want to calculate the most expensive unit, when the previous most expensive unit change to 0, I don't know how to find a new highest unit value.

On the most-expensive-minus, I can only find the corresponding unit price, but not others. So how can I find other values?

This is the whole code:

HTML:

<div id="root">
  <div id="box">
    <ul>
      <li>
        <input type="button" value="-" />
        <span class="num">0</span>
        <input type="button" value="+" />
        <span>single price:</span>
        $<span class="unit">15;</span>
        <span class="label">total:</span>
        $<span class="subtotal">0</span>
      </li>
      <li>
        <input type="button" value="-" />
        <span class="num">0</span>
        <input type="button" value="+" />
        <span>single price:</span>
        $<span class="unit">10;</span>
        <span class="label">total:</span>
        $<span class="subtotal">0</span>
      </li>
      <li>
        <input type="button" value="-" />
        <span class="num">0</span>
        <input type="button" value="+" />
        <span>single price:</span>
        $<span class="unit">5;</span>
        <span class="label">total:</span>
        $<span class="subtotal">0</span>
      </li>
      <li>
        <input type="button" value="-" />
        <span class="num">0</span>
        <input type="button" value="+" />
        <span>single price:</span>
        $<span class="unit">2;</span>
        <span class="label">total:</span>
        $<span class="subtotal">0</span>
      </li>
      <li>
        <input type="button" value="-" />
        <span class="num">0</span>
        <input type="button" value="+" />
        <span>single price:</span>
        $<span class="unit">1;</span>
        <span class="label">total:</span>
        $<span class="subtotal">0</span>
      </li>
    </ul>
    <div class="total-box">
      total purchase
      <span id="goods-num">0</span>
      ; total cost $
      <span id="total-price">0</span>
      ; most expensieve single one is $<span id="unit-price">0</span>
    </div>
  </div>
</div>

Javascript:

const Event = {
  userList: {},
  subscribe(key, fn) {
    if (!this.userList[key]) {
      this.userList[key] = [];
    }
    this.userList[key].push(fn);
  },
  publish() {
    const key = Array.prototype.shift.apply(arguments);
    const fns = this.userList[key];
    if (!fns || fns.length === 0) {
      return false;
    }
    for (let i = 0, len = fns.length; i < len; i++) {
      fns[i].apply(this, arguments);
    }
  }
};
(function () {
  const aBtnMinus = document.querySelectorAll("#box li>input:first-child");
  const aBtnPlus = document.querySelectorAll("#box li>input:nth-of-type(2)");
  const oTotalPrice = document.querySelector("#total-price");
  const oUnitPrice = document.querySelector("#unit-price");
  let curUnitPrice = 0;

  for (let i = 0, len = aBtnMinus.length; i < len; i++) {
    aBtnMinus[i].index = aBtnPlus[i].index = i;
    aBtnMinus[i].onclick = function () {
      this.parentNode.children[1].innerHTML > 0 &&
        Event.publish("total-goods-num-minus");
      --this.parentNode.children[1].innerHTML < 0 &&
        (this.parentNode.children[1].innerHTML = 0);
      curUnitPrice = this.parentNode.children[4].innerHTML;
      Event.publish(
        `minus-num${this.index}`,
        parseInt(curUnitPrice),
        parseInt(this.parentNode.children[1].innerHTML)
      );
      Event.publish(
        `total-minus`,
        parseInt(curUnitPrice),
        parseInt(this.parentNode.children[1].innerHTML),
        parseInt(oTotalPrice.innerHTML)
      );
      Event.publish(
        `most-expensive-minus`,
        parseInt(curUnitPrice),
        parseInt(this.parentNode.children[1].innerHTML),
        parseInt(oUnitPrice.innerHTML)
      );
    };
    aBtnPlus[i].onclick = function () {
      this.parentNode.children[1].innerHTML >= 0 &&
        Event.publish("total-goods-num-plus");
      this.parentNode.children[1].innerHTML++;
      curUnitPrice = this.parentNode.children[4].innerHTML;
      Event.publish(
        `plus-num${this.index}`,
        parseInt(curUnitPrice),
        parseInt(this.parentNode.children[1].innerHTML)
      );
      Event.publish(
        `total-plus`,
        parseInt(curUnitPrice),
        parseInt(this.parentNode.children[1].innerHTML),
        parseInt(oTotalPrice.innerHTML)
      );
      Event.publish(
        `most-expensive-plus`,
        parseInt(curUnitPrice),
        parseInt(oUnitPrice.innerHTML)
      );
    };
  }
})();
(function () {
  const aSubtotal = document.querySelectorAll("#box .subtotal");
  const oGoodsNum = document.querySelector("#goods-num");
  const oTotalPrice = document.querySelector("#total-price");
  const oUnitPrice = document.querySelector("#unit-price");

  Event.subscribe("total-goods-num-plus", function () {
    ++oGoodsNum.innerHTML;
  });
  Event.subscribe("total-goods-num-minus", function () {
    --oGoodsNum.innerHTML;
  });
  Event.subscribe(`total-plus`, function (unitPrice, num, originalPrice) {
    oTotalPrice.innerHTML =
      originalPrice - unitPrice * (num - 1) + unitPrice * num;
  });
  Event.subscribe(`total-minus`, function (unitPrice, num, originalPrice) {
    if (num > 0)
      oTotalPrice.innerHTML =
        originalPrice + unitPrice * (num - 1) - unitPrice * num;
  });
  Event.subscribe(`most-expensive-plus`, function (
    unitPrice,
    originalMostExpensive
  ) {
    oUnitPrice.innerHTML =
      originalMostExpensive < unitPrice ? unitPrice : originalMostExpensive;
  });
  Event.subscribe(`most-expensive-minus`, function (
    unitPrice,
    num,
    originalMostExpensive
  ) {
    if (num > 0) {
      oUnitPrice.innerHTML =
        originalMostExpensive < unitPrice ? unitPrice : originalMostExpensive;
    } else {
      oUnitPrice.innerHTML = "xx"; //how to find the new highest price?;
    }
  });
  for (let i = 0, len = aSubtotal.length; i < len; i++) {
    Event.subscribe(`minus-num${i}`, function (unitPrice, num) {
      aSubtotal[i].innerHTML = unitPrice * num;
    });
    Event.subscribe(`plus-num${i}`, function (unitPrice, num) {
      aSubtotal[i].innerHTML = unitPrice * num;
    });
  }
})();

How Do I create categories for E-commerce app?

I wish to create the UI for categories section but I am confused whether building UI first will make my code unstructured so in the Future I cannot add APIs to fetch the category that the user is clicking.

I wish to create categories like this using API in the future. Can anyone suggest me?

mardi 22 mars 2022

Overwrite a global variable outside of the script

When I am calling the function func in a Jupyter notebook or another script, how can I overwrite the global variable alpha below outside of the script? (I don't want to pass the alpha as the function argument)

# script.py
alpha = 10

def func(a, b):
    return a * alpha + b

For example, the user defines his own alpha in a csv file and have the following code in Jupyter notebook or another script. Is it possible to overwrite on the one defined in script.py?

# Jupyter notebook
from script import func

parameters = pd.read_csv('parameters')
alpha = parameters[0]

print(func(10, 20))

Thank you in advance!

How to avoid including header files of inherited classes?

I want to make a static library that performs Binary Search Tree operations. But I want that BST perform operations both iteratively and recursively.

To do that I created a interface called IBST. And I made that template because I want that BST should support multiple data types.

template <class T>
class IBST
{
  virtual ~IBST { }
  virtual bool insertElement(T value) = 0;
  virtual bool searchElement(T value) = 0;
  virtual bool removeElement(T value) = 0;
};

After that I created two new header files IterativeBST.h and RecursiveBST.h which are inherited from IBST

template <class T>
    class IterativeBST : public IBST<T>
    {
     private:
      Node <T>* root;
     public:
       IterativeBST { }
       virtual ~IterativeBST{ }
       bool insertElement(T value)
       {
        // some operations
       }
       bool searchElement(T value)
       {
        // some operations
       }
       bool removeElement(T value)
       {
        // some operations
       }
    };

This is the Iterative.h file. There is also a RecursiveBST.h file that works the same way, but I don't add it so it won't get crowded.

Finally I have Node.h file which is used for basic structure of BST

template <class T>
    class Node
    {
     private:
      T value;
      Node *left;
      Node *right;

     public:
     // some get set methods and consructor, destructor
    };

After creating this header files, I decided to use factory pattern to decide which implementation(recursive or iterative) will be used.

#include <IBST.h>
#include <IterativeBST.h>
#include <RecursiveBST.h>

template <class T>
     class BSTFactory
      {
          //constructor and desctuctor
          
          IBST<T>* getBST(int input)
          {
             // if input something return new IterativeBST<T>

             //else return new RecursiveBST<T>
          }
      };

These header files are all in static library project. I've just used header files because I used template classes.

Finally I want to use this static library from a executable project. It happens something like this;

#include <IBST.h>
#include <IterativeBST.h>
#include <RecursiveBST.h>
#include <BSTFactory.h>

int main()
{
BSTFactory<int>* factory = new BSTFactory<int>();
IBST<int>* bst = factory->getBST(input);

//bst->insert    bst->remove() goes on like this
}

My problem starts here. The Factory class has to include these files(IterativeBST.h and RecursiveBST.h) in order to return IterativeBST or RecursiveBST in the static library. I thought a solution would be to create BSTFactory.cpp and do the include operation there, but this is not possible since that is template class.

To summarize, I don't want IterativeBST.h and RecursiveBST.h inside the main function. Because I know it is a bad design. But I couldn't find how to solve this.

Which design pattern to use for pre-process process and post-process task

I am working on one migration engine to migrate data from older system to newer system. it is divided into 3 steps.

  1. first getting the data from older tables.
  2. prepare the request body to insert into new tables via APIs
  3. post processing steps.

Which design pattern to use here?

I was thinking of using builder pattern

lundi 21 mars 2022

Rust async but with sequential execution?

TL;DR, can you please share your tips to get a easy-to-read / maintain code, "sequential like" with async rust ?

I am using rust for a while now for fun and at work. My main goal recently is to develop programs that are easy to maintain and where each new commit has few chance to include bug.
Also, I am more and more working with progamming paradigms like Onion / hexagonal architecture and DDD.

To conclude with my context, I am not developping web app where I have to achieve high concurrency, although my code is using Inter-process communication through ROS.

I really enjoy async rust, but I am having troubles to avoid spagethi code...

Do you know any technology / pattern / ... which could help me to get clean code as it would be in a full sync and sequential one?

Do not hesitate to ask question here as I am not really confident about my ability to explain my ideas right :-)

See you.

The typical stuff I want to minimize is the typical "I send data over this channel through sender_x... to continue the reading of my code execution, I now have to find where receiver_x is" (same with actors).

Also, I like to describe my code as workflows as in : order_received.validate_feasibility()?.execute_order()?.send_result_to_anyone_interrested()? Finally, I like to use statemachines as it makes code really easily comprehensible in few secs to anyone reading it.

But... AS soon as I come to async, I have trouble to achieve what's described here.

Design pattern or best practise for the **business layer** (or say **data model**) of an application?

In the MVCs, MVPs, MVVMs and the likes there are clear distinct reponsibilities for each of the layers. The MVX architecture is often stated to be enforced by the framework that is used (windowing libs like Qt, web frameworks like Django...), at least this is what these frameorks claim forcefully.

I have often found that in order for these MVX architectures to be fully enforced you need a great deal of extra architecturing behind the model layer provided by frameworks Qt, wxWidgets, React, Django, Rails... e.g. the model layer of Qt is a thin layer that plays well with the view layer of Qt but what is key for these MVX patterns to work is having an underlying business data model layer that:

  1. Contains the data
  2. Keeps the dependency between the different pieces of data (and makes the relevant updates when an input changes)
  3. That tells the model layer when to send signals

Are there any patterns, libraries, well guided approaches, best practise that help coding the business layer behind the model?

Numbering lines in sections of file with repeating pattern

I am trying to use awk to number repeated lines with the pattern scan-hgi-oi.[0-9][0-9][0-9].out4 in a larger file

The closed I have got to success is the following command

awk *'BEGIN{i=0}{if ($1="scan-hgi-oi.[0-9][0-9][0-9].out4") { i=i+1}   printf"%i\n","%f",i,$1}' test2 > test3*

This only seems to substitute every line with the number 0

The reason why I would like to use awk and not sed for this problem is that the number of repetitions of the pattern is different in each section.

The file has sections looking as follows:

xxxxxxx\
yyyyyyy\
zzzzzz\
scan-hgi-oi.001.out4 number\
scan-hgi-oi.001.out4 number\
scan-hgi-oi.001.out4 number\
ppppppp
xxxxxx\
yyyyyyy\
zzzzzzz\
scan-hgi-oi.002.out4 number\
scan-hgi-oi.002.out4 number\
scan-hgi-oi.002.out4 number\
scan-hgi-oi.002.out4 number\
ppppppp

I would like to get the result beneath.

xxxxxx\
yyyyyyy\
zzzzzzz\
1 number\
2 number\
3 number\
ppppppp
xxxxxx\
yyyyyyy\
zzzzzzz\
1 number\
2 number\
3 number\
4 number\
ppppppp

Hope you can help.

With kind regards from Svend

How to represent relationship between geographical locations like Countries, States, Cities, Towns and Areas into classes?

I want to create a global level database for GeoMap Service and want to represent them through Entity classes along with their relationships.

How I can have such entities classes with their relationship.

World have Countries, Country having States, State having Cities, City having Towns and Town having ZipCodes.

I want to have such complex queries request in system that I need to serve, like below

  1. Get List of 4 countries with their State Data.
  2. Get List of 4 States with their Towns Data.
  3. Get List of 4 Counties with their Towns Data.

Suggest some references if you have any.

I am studying the abstract factory pattern, is it good practice to have an abstract factory for each type of class?

I am implementing the abstract factory pattern, is there a way to not use an abstract class for different class types?

The structure of my classes is like this: Structure Project

Rectangle.cs and Square.cs implement IShape.cs: Structure Class for AbstractShapeFactory

namespace FactoryMethod.Patterns.Creational.Factory.Shape
{
    public interface IShape
    {
        public void Draw();
    }
}
namespace FactoryMethod.Patterns.Creational.Factory.Shape.Normal
{
    public class Rectangle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("Normal Rectangle");
        }
    }
}

NormalShapeImp.cs and RoundedShapeImp.cs implement AbstractShapeFactory.cs

The AbstractShapeFactory.cs class looks like this:

namespace FactoryMethod.Patterns.Creational.Factory
{
    public enum TypeShape
    {
        Square = 1,
        Rectangle = 2
    }

    public abstract class AbstractShapeFactory
    {
        public abstract IShape CreateShape(TypeShape typeShape);
    }
}


public class NormalShapeImp : AbstractShapeFactory
    {
        public override IShape CreateShape(TypeShape typeShape)
        {
            return typeShape switch
            {
                TypeShape.Square => new Square(),
                TypeShape.Rectangle => new Rectangle(),
                _ => new Square(),
            };
        }
    }

The AbstractPaymentFactory.cs class looks like this:

namespace FactoryMethod.Patterns.Creational.Factory
{
    public enum TypePayment
    {
        Google = 1,
        Paypal = 2
    }

    public abstract class AbstractPaymentFactory
    {
        public abstract IPayment CreatePayment(TypePayment typePayment);
    }
}

namespace FactoryMethod.Patterns.Creational.Factory.Payment
{
    public class LocalPaymentImp : AbstractPaymentFactory
    {
        public override IPayment CreatePayment(TypePayment typePayment)
        {
            return typePayment switch
            {
                TypePayment.Google => new LocalGooglePayment(),
                TypePayment.Paypal => new LocalPaypal(),
                _ => new LocalGooglePayment(),
            };
        }
    }
}

I have two abstract factory classes AbstractPaymentFactory.cs Y AbstractShapeFactory.cs

And I have a FactoryProducer.cs class that is in charge of returning one or the other Factory.

namespace FactoryMethod.Patterns.Creational.Factory
{
    public class FactoryProducer
    {
        public static AbstractPaymentFactory GetPaymentFactory(bool isLocal)
        {
            if (isLocal)
                return new LocalPaymentImp();

            return new ForeignPaymentImp();
        }

        public static AbstractShapeFactory GetShapeFactory(bool isRounded)
        {
            if (isRounded)
                return new RoundedShapeImp();

            return new NormalShapeImp();
        }
    }
}

I have my Program.cs class as follows:

static void Main(string[] args)
        {
            #region Pattern Abstract Factory

            /* Factory Payment */
            Console.WriteLine("Factory Payment:");
            Console.WriteLine("Select Type Payment:");
            Console.WriteLine("1- Google (default)");
            Console.WriteLine("2- Paypal");

            int inputType = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Select Account:");
            Console.WriteLine("0- Local");
            Console.WriteLine("1- Foreign (default)");
            bool opAccount = Console.ReadLine() == "0";

            AbstractPaymentFactory factoryPayment = FactoryProducer.GetPaymentFactory(opAccount);
            IPayment payment = factoryPayment.CreatePayment((TypePayment)inputType);
            payment.DoPayment();
            Console.WriteLine("");

            /* End Factory Payment */


            /* Factory Shape */
            Console.WriteLine("Factory Payment:");
            Console.WriteLine("Select Type Shape");
            Console.WriteLine("1- Square (default)");
            Console.WriteLine("2- Rectangle");

            int inputTypeShape = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Select:");
            Console.WriteLine("0- Normal (default)");
            Console.WriteLine("1- Rounded");
            bool opShape = Console.ReadLine() == "0";

            AbstractShapeFactory factoryShape = FactoryProducer.GetShapeFactory(opShape);
            IShape shape = factoryShape.CreateShape((TypeShape)inputTypeShape);
            shape.Draw();

            /* End Factory Shape */

            #endregion
        }

Is what I am doing a good practice? Is there another way to not create a abstract factory for different types?

How to learn structure of web application with python tornado

I can develop something like a blog service that works with a simple mysql with tornado. However, when I look at the web application code for tornado that other developers have posted on github, it does not have the same application structure as in the official documentation. https://www.tornadoweb.org/en/stable/guide/structure.html

What I want to build and may build in the future is a very general web application. I would like to know how to design around DB, what is considered a good configuration for a simple web application, clean architecture that is the talk of the town, etc., and how to separate the configuration? I would like to learn how to write a I would like to know what materials and sample code you would recommend. I am stumped as to where to start. If there is a community I can ask questions or study with, I'd like to know that too!

dimanche 20 mars 2022

JavaScript Sequental operation

What is the best way/pattern to perform sequental operations in JS(NodeJS)? E.g. Create folder->copy file->edit file->etc. This is stand-alone app, so thread-blocking oprations is ok(Sync).

samedi 19 mars 2022

Search after a number pattern

I'm new to this. I just copied my frist script to "tampermonkey".

Im trying to find a pattern of numbers on a website like 500500, 600600, 707070, and similar.

I have this code:

$(document).ready(function() 
{
    var LookFor = "test"; // Change this to find a different string

    if($('body:contains("' + LookFor + '")').length > 0) 
    {
        alert("Found: " + LookFor);
    }
    else
    {
        location.reload();
    }
});

But I dont know how to search after patterns. I would appreciate if you could help me out.

Javascript classes - what solution is more professional in sending emails

I have two classes: MailsTemplates and EmailService. First class is creating templates. Every template has its own method, because every template needs other params:

class MailsTemplates {

  createTemplate1(param1) {
    // some code
  }

  createTemplate2(param2) {
    // some code
  }

  createTemplate3(param3) {
    // some code
  }

  createTemplate4(param4) {
    // some code
  }

}

Second class EmailService has two methods: createConfigurationForEmail and sendEmail. createConfigurationForEmail has three params:

  • userEmailsArr,
  • emailSubject,
  • template (html code provided in a string type, generated by a one of the MailsTemplates method)

My code:

const MailsTemplates = require("./mailTemplates.js");

class EmailService {

  mailTemplates;
  constructor() {
    this.mailTemplates = new MailsTemplates();
  }
  
  #createConfigurationForEmail = (userEmailsArr, subject, template) => {
    // my code
  }

  sendEmail = async (
    userEmailsArr, 
    subject, 
    getTemplate, 
    param1=null, 
    param2=null, 
    param3=null,
    param4=null, 
  ) => {
    const template = getTemplate(param1, param2, param3, param4);
    const emailConfig = this.#createConfigurationForEmail(userEmailsArr, subject, template);
    return await AWSSESSendEmailMethod(emailConfig).promise();
  }

}

const emailService = new EmailService();

And now when I want to send email with template1 I use this code:

emailService.sendEmail(["email"], "Subject", emailService.mailTemplates.createTemplate1, param1);

When email with template2 this code:

emailService.sendEmail(["email"], "Subject", emailService.mailTemplates.createTemplate2, param2);

Is this proffessional enough? What to change to make my code better? Maybe should I provide in invoking sendEmail method my params in createTemplate methods?

How to deal with constness when the method result is cached?

I have a class with a method (getter) that performs some relatively expensive operation, so I want to cache its result. Calling the method does not change behavior of the object, but it needs to store its result in this, so it can't be const.

The problem is that I now have another method that is const and I need to invoke my getter. Is there some generally accepted solution to this problem? Should I bypass the constness checking in the getter to make it const, (Coudn't that cause problems with optimizing compiler?) or I have to propagate the non-constness to all methods that use this getter?

Example:

class MyClass
{
public:
    Foo &expensiveGetter() /*const?*/
    {
        if (cachedValue == nullptr) {
            cachedValue = computeTheValue();
        }
        return *cachedValue;
    }

    void myMethod() /* How to make this const? */
    {
        auto &foo = expensiveGetter();
        // etc.
    }

private:
    Foo *cachedValue = nullptr;
}

I am looking for something like the RefCell in Rust.

vendredi 18 mars 2022

Where to learn Javascript framework/library authoring? [closed]

Any search I try to make on this subject only yields results for learning existing JS frameworks. But I want to know what these guys know to write such frameworks themselves. When I checked out @headlessui/react for example, thinking it had simple enough components from which I can understand some basics of library development, I find they're still quite complex—the code structure, modular architecture, component organization and data flow... All that could be overwhelming. Very much different from what I would write if I were to create a simple, reusable component the best way I could think of!

I think it's more than just JavaScript design patterns I need to know. I'd like to write code and build things that people would use, but I find out there's still much I need to know. Can someone help me as to what resources/books can launch me in that direction? I've tried many times but never found what I was looking for. I already know and understand JavaScript so it makes me wonder where these guys are learning from.

What is the best way to setup public methods in a JS library [closed]

I am relatively new to JavaScript. My company develops an analytics solution written in TypeScript. It is practically a JS library that clients can import into their web pages. My task is to set up a public method that clients can use in order to trigger custom events in our system.

I did some research and from what I understand, there are different ways to do that:

  1. With post messages
  2. With custom events
  3. With public class/methods declared in the lib
  4. With global methods declared in the lib

Number 3 sounds the most logical to me, but I don't have enough experience to know what is the best practice. An ideal integration will look as follow:

<script src="..."></script> <!-- This is our library -->
<script>
    let lib = new ourLib();
    let data = {};

    // Allow the client to send custom events
    lib.triggerEvent('click', data); // this?
    ourLibTriggerEvent('click', data); // or this?
    window.ourLib.triggerEvent('click', data); // or this?
    // dispatch a custom event?
    // send a post message?
</script>

What would be the best practice for doing that? Am I completely off with my approach?

Thank you!

Enumeration with subtypes c#

First of all perhaps this is a problem due to a bad design. Here is my scenario simplified:

I have a class call Day it represent a day of the year, with its date and the "type" of day.

public class Day{
 Date Key;
 TypeDay type;
}

So the day can be a worked day or a holiday one:

public enum TypeDay{
    Work,
    Holiday
}

So far so good, but now holiday days can have subtypes like paidDays and NonPaid days I would need another enum to represent that subtypes or add all subtypes in a single enum (in this example i have 2 days and 2 subtypes but in real live i have 50-40 types) so this get so messy .

 public enum TypeDay{
        Work,
        Holiday_NonPaid
        Holiday_Paid
    }

How can i build this in a better way,any ideas?

Refactor the python design patterns

I have a class called resources and I have defined one method called get_connect. I want to use the data of which get_connect returns to the other classes. I need at least three classes and I use the data of get_connect and I have to parse that data. To implement this I have written the code below


class resources:
    @staticmethod
    def get_connect():       
        
        return 1 + 2


class Source1(resources):
    def __init__(self):
        self.response = resources.get_connect()

    def get__details1(self):
        print(self.response)

class Source2(resources):
    def __init__(self):
        self.response = resources.get_connect()
    def get_details2(self):
        print(self.response)

class Source3(resources):
    def __init__(self):
        self.response = resources.get_connect()
    def get__detail3(self):
        print(self.response)

source1 = Source1()
source2 = Source2()
source3 = Source3()
source1.get__details1()
source2.get_details2()
source3.get__detail3()

But the problem with the code is for every class in init method I am calling the get_connect method. I don't want to repeat the code. I need help for avoiding redundancy which I have asked below

  1. Is there any way I can call get_connect in one place and use it for other classes maybe a decorator or anything? if yes how can I?
  2. While creating objects also I am calling each class and calling each method every time. is there a way to use any design pattern here?

If anyone helps me with these oops concepts it will be useful.

What exactly is a "client" in the interface segregation principle (ISP)?

This is one of a number of things that's been bugging me for a while and for which quibbling over the correct interpretation of this has been leading me in a number of attempted coding projects to more fussing around with design, than it has with making steady forward progress, because I want to make sure I've gotten it "right".

In this case, I have a question about the "interface segregation principle" (ISP) of the five "SOLID" principles of basic object oriented design. Its "canonical" statement is this:

Clients should not be forced to depend on methods they do not use.

However, the question here is, is what is the "client" - because this leads to very different interpretations, and also leads to a seeming dilemma when applied in practice, which is what I'd like to understand if first actually is one, and second, how to best solve it.

One interpretation of this is that it is a "single responsibility principle" for interfaces instead of just classes: i.e. if you have an interface IMessageReceiver, it better not include a Send method. Another possible interpretation is that it means that the implementer of an interface should not be required to implement empty methods, while a third interpretation is that the caller should not be able to see any more methods than it actually needs. And the thing is, I can see merit in all three of these interpretations, yet when you apply them all, it seems that in any suitably large project, highly counterintuitive and seemingly problematic things result. In particular, it's that third one that seems to be the rub.

For one, if something gets used in enough places, it is particularly that last one - the "caller" one - which generally tends to "bite" in that it results naturally in your interfaces being atomized down to single methods only. For example, consider a simple interface to a backend storage or database, which may have a load, save, and update method. Some callers of that, though, may not want to save anything. They may just want to peek at the data. Hence to avoid violating the caller interpretation, we must split off the load method. Add a few more use cases and now it's atomized into a IDataLoader, IDataSaver, and IDataUpdater which all have 1 method each.

And I can't help but feel this almost seems like an anti-pattern, particularly if it happens with enough objects owing to them being used in a suitably wide variety of places. Is it? Or am I misinterpreting something here? After all, nobody makes a generic container class (like the "list", "map", etc. things in a lot of languages) with single-method interfaces to be piecemealed out to whatever it gets passed to.

jeudi 17 mars 2022

Different ways of processing event in finite state machine (software)

I'm learning the state design pattern and curious about two ways of handling events and state transitions. My question actually has nothing to do with the pattern itself.

Given a current state 's' and event 'e', we can capture the transition as:

s' = s->event_handler(e)

In some examples, the handling stops at this point and the event is considered fully handled. In others, however, the handling does not cease after deriving the new state s'. In the latter model, the same event 'e' is sent/fed to s' again in a loop. Effectively, we have:

while (1) {
    s' = s->event_handler(e)
    if (s == s')
        break
}

This appears similar to level vs. edge triggering. The first model is like edge trigger whilst the second, level trigger. In a sense, only when the event handler no longer returns a new state is the event considered handled.

What's difference in the 2 models and their respecitve use cases? Thanks.

mercredi 16 mars 2022

R, find pattern and create index, then filter another column based on the created index

I have a value df df1 = data.frame(ID = c("A1; A2; A3; A4", "B1; B2; B3", "C1; C2","D1"), Value = c("1; 2; 3; 4", "5; 6; 7", "8; 9", "10")).

I have another df df2 = data.frame(ID = c("A2", "B3", "C2", "D1")).

Now I would like to write a function to map the 'ID' from df2 to 'ID' in df1, then filter the Value based on the ith position of ID column. The expected output is filtered_df1 = data.frame(ID=c("A2", "B3", "C2", "D1"), value = c("2", "7", "9", "10")).

Would you be able to give any suggestion to create R function?

Thank you so much!

Handling a framework-specific event and MVVM?

In a WPF application that uses Prism, I have a shell in which there is a docking manager control.

Now I have to listen to an event coming from that docking manager, specifically, when one of its children docking state has changed.

To me, this event should be handled in code-behind as letting the view model do some work against that framework-specific visual control is worse than doing it code-behind.

Question:

Is this the right approach or am I missing something?

What are the popular design patterns used to develop a DotNet Core Web Api application?

I need to develop web api in dotnet core. Can anyone suggest most popular and widely used design pattern that I can use like command design pattern?

lundi 14 mars 2022

Is this the Abstract Factory pattern or something else?

I have an abstract class that's following the singleton pattern, then I have a few concrete classes that extend it:

UML Diagram

At startup, based on the current system, I'm setting a concrete instance as the instance of the singleton like this:

LicenseFactory.setInstance(new SystemALicenseFactory())

With that, at any point in the code, I can consume the abstract method like this: LicenseFactory.getInstance().isUserValid()

Because my concrete classes aren't creating a product, I'm not sure whether I can call this the Abstract Factory pattern or something else. Is it common to use a pattern like this, and is there anything I should have done better?

What is a good design pattern approach for a somewhat dynamic dependency injection in Swift

Let's say there are three components and their respective dynamic dependencies:

struct Component1 {
    let dependency1: Dependency1

    func convertOwnDependenciesToDependency2() -> Dependency2
}

struct Component2 {
    let dependency2: Dependency2
    let dependency3: Dependency3

    func convertOwnDependenciesToDependency4() -> Dependency4
}

struct Component3 {
    let dependency2: Dependency2
    let dependency4: Dependency4

    func convertOwnDependenciesToDependency5() -> Dependency5
}

Each of those components can generate results which can then be used as dependencies of other components. I want to type-safely inject the generated dependencies into the components which rely on them.

I have several approaches which I already worked out but I feel like I am missing something obvious which would make this whole task way easier.

The naive approach:

let component1 = Component1(dependency1: Dependency1())

let dependency2 = component1.convertOwnDependenciesToDependency2()
let component2 = Component2(dependency2: dependency2, dependency3: Dependency3())

let dependency4 = component2.convertOwnDependenciesToDependency4()
let component3 = Component3(dependency2: dependency2, dependency4: dependency4)

let result = component3.convertOwnDependenciesToDependency5()

Now I know that you could just imperatively call each of the functions and simply use the constructor of each component to inject their dependencies. However this approach does not scale very well. In a real scenario there would be up to ten of those components and a lot of call sites where this approach would be used. Therefore it would be very cumbersome to update each of the call sites if for instance Component3 would require another dependency.

The "SwiftUI" approach:

protocol EnvironmentKey {
    associatedtype Value
}

struct EnvironmentValues {

    private var storage: [ObjectIdentifier: Any] = [:]

    subscript<Key>(_ type: Key.Type) -> Key.Value where Key: EnvironmentKey {
        get { return storage[ObjectIdentifier(type)] as! Key.Value }
        set { storage[ObjectIdentifier(type)] = newValue as Any }
    }
}

struct Component1 {
    func convertOwnDependenciesToDependency2(values: EnvironmentValues) {
        let dependency1 = values[Dependency1Key.self]
        // do some stuff with dependency1
        values[Dependency2Key.self] = newDependency
    }
}

struct Component2 {
    func convertOwnDependenciesToDependency4(values: EnvironmentValues) {
        let dependency2 = values[Dependency2Key.self]
        let dependency3 = values[Dependency3Key.self]
        // do some stuff with dependency2 and dependency3
        values[Dependency4Key.self] = newDependency
    }
}

struct Component3 {
    func convertOwnDependenciesToDependency5(values: EnvironmentValues) {
        let dependency2 = values[Dependency2Key.self]
        let dependency4 = values[Dependency4Key.self]
        // do some stuff with dependency2 and dependency4
        values[Dependency5Key.self] = newDependency
    }
}

But what I dislike with this approach is that you first of all have no type-safety and have to either optionally unwrap the dependency and give back an optional dependency which feels odd since what should a component do if the dependency is nil? Or force unwrap the dependencies like I did. But then the next point would be that there is no guarantee whatsoever that Dependency3 is already in the environment at the call site of convertOwnDependenciesToDependency4. Therefore this approach somehow weakens the contract between the components and could make up for unnecessary bugs.

Now I know SwiftUI has a defaultValue in its EnvironmentKey protocol but in my scenario this does not make sense since for instance Dependency4 has no way to instantiate itself without data required from Dependency2 or Depedency3 and therefore no default value.

The event bus approach

enum Event {
    case dependency1(Dependency1)
    case dependency2(Dependency2)
    case dependency3(Dependency3)
    case dependency4(Dependency4)
    case dependency5(Dependency5)
}

protocol EventHandler {
    func handleEvent(event: Event)
}

struct EventBus {
    func subscribe(handler: EventHandler)
    func send(event: Event)
}

struct Component1: EventHandler {
    let bus: EventBus
    let dependency1: Dependency1?

    init(bus: EventBus) {
        self.bus = bus
        self.bus.subscribe(handler: self)
    }
    
    func handleEvent(event: Event) {
        switch event {
        case let .dependency1(dependency1): self.dependency1 = dependency1
        }

        if hasAllReceivedAllDependencies { generateDependency2() }
    }
    
    func generateDependency2() {
        bus.send(newDependency)
    }
}

struct Component2: EventHandler {
    let dependency2: Dependency2?
    let dependency3: Dependency3?
    
    init(bus: EventBus) {
        self.bus = bus
        self.bus.subscribe(handler: self)
    }
    
    func handleEvent(event: Event) {
        switch event {
        case let .dependency2(dependency2): self.dependency2 = dependency2
        case let .dependency3(dependency3): self.dependency3 = dependency3
        }

        if hasAllReceivedAllDependencies { generateDependency4() }
    }
    
    func generateDependency4() {
        bus.send(newDependency)
    }
}

struct Component3: EventHandler {
    let dependency2: Dependency2?
    let dependency4: Dependency4?
    
    init(bus: EventBus) {
        self.bus = bus
        self.bus.subscribe(handler: self)
    }
    
    func handleEvent(event: Event) {
        switch event {
        case let .dependency2(dependency2): self.dependency2 = dependency2
        case let .dependency4(dependency4): self.dependency4 = dependency4
        }

        if hasAllReceivedAllDependencies { generateDependency5() }
    }
    
    func generateDependency5() {
        bus.send(newDependency)
    }
}

I think in terms of type-safety and "dynamism" this approach would be a good fit. However to check if all dependencies were received already to start up the internal processes feels like a hack somehow. It feels like I am misusing this pattern in some form. Furthermore I think this approach may be able to "deadlock" if some dependency event was not sent and is therefore hard to debug where it got stuck. And again I would have to force unwrap the optionals in generateDependencyX but since this function would only get called if all optionals have a real value it seems safe to me.

I also took a look at some other design patterns (like chain-of-responsibility) but I couldn't really figure out how to model this pattern to my use-case.

My dream would be to somehow model a given design pattern as a result builder in the end so it would look something like:

FinalComponent {
    Component1()
    Component2()
    Component3()
}

And in my opinion result builders would be possible with the "SwiftUI" and the event bus approach but they have the already described drawbacks. Again maybe I am missing an obvious design pattern which is already tailored to this situation or I am just modeling the problem in a wrong way. Maybe someone has a suggestion.

How do i correct motif pattern java [closed]

the following expression have :

*891123456789112345678910000000000aaa.aaaa aaaaaa 3

a special caracters (*)at the begining of expression

50 digits

20 cracreters contains space and spécial characters

the number 0 indicates the end of the line

if(saisie.matches("\W\d{20}\d{13}\w(\s,.)\1"))

Bridge Pattern Vs Builder Pattern

The UML diagram of the Bridge pattern and Builder pattern is quite similar to each other on the following GeeksForGeeks links:

https://www.geeksforgeeks.org/bridge-design-pattern/

https://www.geeksforgeeks.org/builder-design-pattern/

I wanted to know if the UML diagram of builder pattern is based of bridge design pattern with difference that the former constructs an object after it executes.

How to build equal ranges of a green or brown tone in a color palette from dark to bright with RGB for images with R?

does anyone know how I can search in many images for green tones and cluster them for a later characterisation of the images? The idea is to include all shades of green from the green palette and only leave out as few as possible, none would be great actually. I have thought of taking a photo with a lot of green tones, clustering it using R and then creating areas between the values of the cluster centres. However, since forming areas of RGB images is a three-dimensional space, I find it difficult to form areas that contain all the color tones in total, but only one color tone should occur in an area, so there are no overlaps. It is also difficult to find an image with all green shades for the clustering. Does anyone have a tip for me?

Thanks in advance!

dimanche 13 mars 2022

React Class Component Separate UI & Business Logic

I am trying to separate UI and Logic in React class component with little bit of js. I know this could be done easily with custom hooks. But I need to do with class components.

I could make some progress, but it doesnot seem efficient, need your input.

App.view.js

import React from "react";
import Header from "../components/Header";
import ListWrapper from "../components/ListWrapper";
import SearchField from "../components/SearchField";
import UserCard from "../components/UserCard";
import AppController from "./App.controller";

class App extends React.Component {
  constructor() {
    super();
    this.state = { users: [], searchValue: "" };
    this.setState = this.setState.bind(this);
  }

  componentDidMount() {
    AppController(this.state, this.setState).fetchUsers();
  }

  render() {
    const filteredUsers = AppController(
      this.state,
      this.setState
    ).handleFilter();

    return (
      <div className="wrapper pb-12 bg-gray-100 mx-auto max-w-7xl">
        <Header heading="🐶 Pets Rolodex" />
        <SearchField
          labelText="Search Pets"
          fieldId="pets-search-field"
          placeholderText="Enter name"
          searchValue={this.state.searchValue}
          handleChange={AppController(this.state, this.setState).handleChange}
          className="w-72"
        />
        <ListWrapper
          listData={filteredUsers}
          ListItem={UserCard}
          ListItemProp="user"
        />
      </div>
    );
  }
}

export default App;

App.controller.js

const AppController = (state, setState) => ({
  // Fetch Users info
  fetchUsers: () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(data => setState({ users: data }))
      .catch(error => console.error(error));
  },

  // Input Field Handler
  handleChange: event => {
    const { value } = event.target;
    setState({ searchValue: value });
  },

  // Filter Handler
  handleFilter: () => {
    const { searchValue, users } = state;
    if (searchValue === "") {
      return users;
    } else {
      return users.filter(usr =>
        usr.name.toLowerCase().includes(searchValue.toLowerCase())
      );
    }
  }
});

export default AppController;

This works fine. Codesandbox

But the issue is, this instantiates multiple objects from function calls AppController(this.state, this.setState) and this happens on every render(){...} It is like I creating and destroying function stored in memory.

What I tried

I moved function call to constructor like below:

  constructor() {
    super();
    this.state = { users: [], searchValue: "" };
    this.setState = this.setState.bind(this);
    this.controller = AppController(this.state, this.setState)
  }

and use this.controller everywhere in view.

But this seems to persist initial state (empty) into function execution context and all logic functions inside it never see a light of new state.

Thanks in advance for your input :)

How to ensure that future Implementations of an Interface will also extend a particular Class

I have an abstract class and two final classes that extend it.

The abstract class is also an implementation of an interface.

Now I have to remove one of the two child classes and add an interface so that people can still come in with their own implementations.

But I need to ensure that whoever implements the new interface is going to extend the existing abstract class. It is required because otherwise it won't be functioning.

Is there a way to achieve that, or I can only document an implementation requirement?

samedi 12 mars 2022

Print an upside down triangle recursively

I am trying to figure out how to print an upside-down triangle recursively, using only one for-loop. I keep getting an error. I'm able to print the first row but I'm having a hard time recalling the function to print the remaining rows and decrementing n.

    public static void printTriangle (int n) {
        if( n == 0 ) 
            System.out.println("");
        for (int i = n; i >0; i--) {
            System.out.print("*");    
        }
        System.out.println();
        printTriangle(n-1);
    }

What are the disadvantages of not following dependency inversion? [closed]

what are the disadvantages of not following dependency inversion?

I know one which testing the classes become easy.is there any other difference other than this?

suppose I have class A and class B. In D.I we create an interface of class B functions and class B implements it in the same way class A uses the interface rather than using the concrete class B.

I know this helps in loose coupling but I don't get what is the disadvantage of it.

How do I have a single instance (singleton?) of DB connection for a whole rust project

For some context, I have worked with Java, Node. My experience is mostly web-backend. Something we usually use in those kind of projects is a single db connection and inject/refer to the connection and build abstractions from that.

I'm looking to do the same thing, although not a web server. I tried searching for singleton in rust but there are multiple solutions. some are with libraries and some with unsafe etc...How can this be achieved in Rust or am I trying to force rust into something it's not. I really don't want/like everything to be passed on through function calls. Makes it harder to refactor if needed.

What are the disadvantages of tight coupling in object oriented programming?

what is the disadvantage of tight coupling other than you can write unit test code better in the case of loosely coupled classes?

I know with loose coupling you can write unit test cases and I know it suits the SOLID principle. but I didn't understand what will happen if I don't do that.

To me what is tight coupling is when you instantiate an object of the class directly without any factory class and without using the interface just directly creating the object of it.

vendredi 11 mars 2022

How does Initialization on demand holder Idiom ensures only "single" instance is created ever?

I went through the wiki https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand Initialization on demand holder Idiom for Singleton pattern, though the wiki mentions how it's thread safe, it doesn't say how this actually ensures only one instance is created ever, i.e if in two different classes Something.getInstance() is called how do they have the same object ?

I am new to Java, so any help would be appreciated.

jeudi 10 mars 2022

C# refactoring Facade for API

I create a dll for my application. I am using Facade design pattern for encapsulate API who makes some programmers (not my organization) because they decision is uncomfortable.

Their API works like this:

  1. Initialize object of DiadocApi
  2. Auth for getting token

For initialize DiadocApi object I need developerKey (get for a subscription). For authorization I need login, password.

My decision badly because it's a singleton and I need make unit-tests. That can I change in my code?

//I GET IT FROM NUGET PACKAGE
using Diadoc.Api;

public sealed partial class DiadocApiFacade
{
    private static readonly object _mutex = new object();

    private static DiadocApiFacade _instance;
    private string _token;
    private DiadocApi _api;

    private DiadocApiFacade() { }

    public static string DefaultUrl => "url was here";
    public string DefaultFromBoxId { get; set; }
    public DiadocApi Api { get => _api; private set => _api = value; }
    
    public static DiadocApiFacade GetInstance()
    {
        if (_instance == null)
        {
            lock (_mutex)
            {
                if (_instance == null)
                {
                    _instance = new DiadocApiFacade();
                }
            }
        }
        return _instance;
    }

    public string Authenticate(string login, string password, string privateDeveloperKey)
    {
        if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(developerKey))
            throw new ArgumentNullException();

        Api = new DiadocApi(developerKey, DefaultUrl, new WinApiCrypt());

        return _token = _api.Authenticate(login, password);
    }

    //method for example, >60% methods like that
    public Document GetDocument(string messageId, string documentId, string boxId = null)
    {
        return _api.GetDocument(_token, boxId ?? DefaultFromBoxId, messageId, documentId);
    }
}

MuleSoft why it has API designer when this is integration platform

I am exploring the usage of MuleSoft and I am new in using it. The MuleSoft is integration platform, then I am wondering why it has the functions of API Designer (API create service)? Because having an API Designer in an integration platform may lead to create business rules as implemented in the API created in MuleSoft! The integration platform would not need to have a facility to create API, rather just a way to call API and manage API request which is provided by API Manager. The API creation shall be done in the other systems which MuleSoft will integrate. This could make integration platform doing more than what it is intended. Or I am missing something? Wanted to understand this aspect of MuleSoft.

The reason could be to give some quick way to use functions of MuleSoft, by directly having an option to create API in MuleSoft itself. May be?

mercredi 9 mars 2022

Why we use builder design pattern instead of setters?

In many examples about builder design patterns, there is one example that makes me confused, the build method calls the house setter to set the value into the house object attribute.

class IglooHouseBuilder implements HouseBuilder
{
private House house;

public IglooHouseBuilder()
{
    this.house = new House();
}

public void buildBasement()
{
    house.setBasement("Ice Bars");
}

public void buildStructure()
{
    house.setStructure("Ice Blocks");
}

public void buildInterior()
{
    house.setInterior("Ice Carvings");
}

public void buildRoof()
{
    house.setRoof("Ice Dome");
}

public House getHouse()
{
    return this.house;
}
}

if we can use the setter to set some value why do we need to use a builder design pattern? doesn't setter can also solve the telescoping constructor problem?

source : https://www.geeksforgeeks.org/builder-design-pattern/

Is there a way to ensure that future implementation of an interface will also extend a class

So I have an abstract class and two final classes that extend it. The abstract class is also an implementation of an interface. So what I have to do is - remove one of the two child classes and add an interface so that people can still come in with their own implementations. BUT the tricky moment is - is there a way to ensure that whoever implements the new interface is going to extend the abstract class or the only way is to document an implementation requirement? They need to exted it as otherwise it won' be functioning.

When and why to return an interface in Golang?

Example code:

type IClient interface {
    UploadFile(sourcePath, host string) error
    CopyFile(sourcePath, destPath string) error
    DeleteFile(sourcePath, option string) error
    GetChecksum(sourcePath string) (*string, error)
    GetSize(sourcePath string) (*float32, error)
}

type FileWorker struct {
    Extension string
    Host string
}

func NewFileWorker(fileExtension, host string) IClient {
    var fileWorker = &FileWorker {
        Extension: extension,
        Host: host,
    }
    return fileWorker
}

I have seen other "New" (or "Get") function returning interface like above. But it does not actually return the interface, but instead a struct that implements said interface. In turn, that struct type is the receiver of various methods implementing said interface.

Question: When and why do we return interfaces? Currently I see this is a roundabout way of doing things, resulting in one having to trace back through multiple files while trying to understand some codes.

How can I write an interface for a place where I obviously can have abstact class but I need an interface?

I have an abstract class that is extended by a final class with very closed implementation(private fields, methods, security oriented). There is a switch-case that depending on some input chooses which constructor to use. I want to get rid of the extended class but leave some interface for people to plugin their own implementation. Any suggestions how to approach this design/OOP problem?

Java overriding a abstract class method that were inherited by multiple subclasses [closed]

I have a question regarding OOP design in Java:

say I want to leverage a java library, which has Abstract class I and class A and B, A and B both extend I.

However, instead of using the library directly, I want to do some modifications of a concrete method f inside class I for my customized use case. After my modification, I would like A and B's f method both to use my new customized implementation instead of the original implementation.

I don't want to modify code in place of the original library (that means I have to create a forked repo and maintain that), what is the best design/abstraction/inheritance strategy I can use to achieve this modification?

Why there is a pattern on the garbage values in the C program?

I try this program in CS50 Week 4 memory. I noticed there is a pattern on the garbage values. Initially, I thought garbage values should be randomize. But, it looks like there is different pattern depended on the number of garbage value requested.

Code: #include <stdio.h> #include <stdlib.h>

int main (void)
{
    //Create an array of 3
    int scores[3];

    //Print 3 random garbage values
    //scores[0] have big random values
    //scores[1] have 3276X
    //scores[2] have 0
    for (int i = 0; i < 3; i++)
    {
        printf("%i\n", scores[i]);
    }
}

Result: pset4/W4.1/ $ ./garbage -1498813296 32767 0 pset4/W4.1/ $ ./garbage -1011161520 32764 0 pset4/W4.1/ $ ./garbage 1340521040 32765 0 pset4/W4.1/ $ ./garbage 1244491248 32765 0 pset4/W4.1/ $ ./garbage -1200874656 32764 0

Can anyone help to explain what is happening here? Thanks!

Should small utility functions be split into header & source files or just add inline keyword?

I have some small utility functions (< 20 lines of code per function) that I am currently putting in a utils.h file with the keyword inline in front of them so I don't run into multiple definition linking errors. This is what I have always done for small functions.

I am wondering what the advantages and disadvantages are to:

  1. Using my method

  2. Putting the function declarations in utils.h and definitions in utils.cpp

What is the difference between Adapter pattern vs dependency injection in OOP?

I have been studying Software architectures and design and I am in the Adapter pattern implementation part. This pattern looks similarly to the dependency injection that most framework uses such as Symfony, Angular, Vue, React, etc. What are their differences?

Or is it the frameworks implementation of Adapter pattern?