lundi 28 février 2022

Implement an interface in a class with additional methods

I'm trying to embrace clean code and design patterns and came across to the following scenario.

interface SystemLogInterface
{
    public function log(string $type);
}

My fist class implementation is

class LogDownloadService implements SystemLogInterface
{
  public function log(){}
}

and my second class

class LogUserService implements SystemLogInterface
{
  public function setAttr(){}
  public function log(){}
}

My thought is that the second class is not able to implement the same interface because the consumer of this class can also invoke the setAttr() method.

For example

public function foo(LogUserService $service)
{
 $service->setAttr($this->getAttr())
 $service->log()
}

If i want to change the interface implementation i will need to also change the body of the method, which is wrong.

How am i supposed to approach this?

Note: setAttr() can not be moved to the constructor

Template specification but template parameter not used?

I was looking at this file in the Pytorch repo: https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/quantized/cpu/conv_packed_params.h

#pragma once

#include <ATen/ATen.h>
#include <ATen/core/ivalue.h>

template <int kSpatialDim = 2>
struct ConvPackedParamsBase : public torch::jit::CustomClassHolder {
  virtual at::Tensor apply(
      const at::Tensor& input,
      double output_scale,
      int64_t output_zero_point) = 0;
  virtual at::Tensor apply_relu(
      const at::Tensor& input,
      double output_scale,
      int64_t output_zero_point) = 0;
  virtual at::Tensor apply_dynamic(
      const at::Tensor& input,
      bool reduce_range) = 0;

  virtual std::tuple<at::Tensor, c10::optional<at::Tensor>> unpack() = 0;

  virtual torch::List<int64_t> stride() const = 0;
  virtual torch::List<int64_t> padding() const = 0;
  virtual torch::List<int64_t> output_padding() const = 0;
  virtual torch::List<int64_t> dilation() const = 0;
  virtual int64_t groups() const = 0;
  virtual bool transpose() const = 0;
};

It appears to be a template specification but kSpatialDim is never used. I was wondering what is the purpose of this kind of design?

dimanche 27 février 2022

Is there any other design pattern other than composite in the question. Question says "apply proper creational patterns to create objects"? [closed]

Suppose you are designing the file system of an operating system. The current version of the operating system supports 2 types of files – directory file and text file. A directory file contains other files while a text file contains a collection of ASCII texts. Each of the file has a name, type, create date, owner id, and permission (read and write) for owner and others. Each non directory file also has a size (in KB) attribute. Changing permission on a directory file will change the permission on that file as well as all the files stored under that directory file. Users may also query the size of a file (for a directory file, the size is the sum of size of all the files contained in the directory file and other sub directory files). A client object can have a reference to any file object and is capable of changing permission and getting size. The client object know the type of files (‘directory’ or ‘text’) but may not know how to create object of the files (apply proper creational patterns to create objects). Apply appropriate design patterns wherever application and implement an efficient file system for your operating system. Write a test program to create the file hierarchy and test your client program. Now, add a new file type (called multimedia file) to your file system without changing the existing code except adding its type ‘multimedia’.

How to organize a series of code to handle rollback mechanism gracefully? [closed]

I have a strange logic with rollback mechanism like:

A ------------> B ------> C ------> D
   |error        |error
   |             |
Rollback A<----Rollback B

The code now isn't very satisfied with me like:

try:
  A()
except ExceptionA:
  RollbackA()
try:
  B()
except ExceptionB:
  RollbackB()
  RollbackA()
C()
D()

Can anyone help me to optimize it? Sorry for confusing every one, what I concern is I want to optimize it with a graceful framework or design pattern. Current code hasn't any problem. However, If I have many steps to rollback, it will become complicated and redundant.

samedi 26 février 2022

Is Antlr4 Visitor really a visitor?

I've been learning how to make an AST with Antlr4's visitor and after reading Terrance Parr's book, and multiple forums on the topic of AST generation specifically with Antlr visitors, it seems that the standard approach for doing this involves overriding the Antlr generated visit methods like this (From The Definitive Antlr 4 Reference).

public static class EvalVisitor extends LExprBaseVisitor<Integer> {
    public Integer visitMult(LExprParser.MultContext ctx) {
        return visit(ctx.e(0)) * visit(ctx.e(1));
    }
    public Integer visitAdd(LExprParser.AddContext ctx) {
        return visit(ctx.e(0)) + visit(ctx.e(1));
    }
    public Integer visitInt(LExprParser.IntContext ctx) {
        return Integer.valueOf(ctx.INT().getText());
    }
}

In this book, and many threads, typically the way to approach overriding the base visitor is to call visit() within the visitor itself. Seemingly, the visitor itself governs the traversal of the parse tree.

However, when I look anywhere else about how the visitor pattern is typically implemented, the visit method almost never calls visit() within itself. Usually the accept method is used within a node or element to govern the traversal of a tree structure and calls accept on the node's children to do so, while the visitor mainly handles what operations occur for that particular visit, on that particular tree's node.

Wikipedia Example, but reduced for most important parts

public class ExpressionPrintingVisitor
{
    public void PrintAddition(Addition addition)
    {
        double leftValue = addition.Left.GetValue();
        double rightValue = addition.Right.GetValue();
        var sum = addition.GetValue();
        Console.WriteLine("{0} + {1} = {2}", leftValue, rightValue, sum);
    }
}

public class Addition : Expression
{
    public Expression Left { get; set; }
    public Expression Right { get; set; }

    public Addition(Expression left, Expression right)
    {
        Left = left;
        Right = right;
    }
    
    public override void Accept(ExpressionPrintingVisitor v)
    {
        Left.Accept(v);
        Right.Accept(v);
        v.PrintAddition(this);
    }
    
    public override double GetValue()
    {
        return Left.GetValue() + Right.GetValue();    
    }
}

In this particular example, PrintAddition() is the "visit()" method being called by accept to perform the operation.

Am I misunderstanding the visitor pattern? Is the antlr4 visitor not a standard visitor? Or is more happening under the hood of the Antlr visitor that I'm not understanding. To me, the simplified description of the visitor pattern implementation is using an "accept" method on a node's children to traverse a tree, while calling the visitor to perform operations on the children of that node.

I appreciate any help on the topic, and apologize if anything is unclear.

What is the difference between the Antlr4 visitor and standard visitors?

I've been learning how to make an AST with Antlr4's visitor and after reading Terrance Parr's book, and multiple forums on the topic of AST generation specifically with Antlr visitors, it seems that the standard approach for doing this involves overriding the Antlr generated visit methods like this (From The Definitive Antlr 4 Reference).

public static class EvalVisitor extends LExprBaseVisitor<Integer> {
    public Integer visitMult(LExprParser.MultContext ctx) {
        return visit(ctx.e(0)) * visit(ctx.e(1));
    }
    public Integer visitAdd(LExprParser.AddContext ctx) {
        return visit(ctx.e(0)) + visit(ctx.e(1));
    }
    public Integer visitInt(LExprParser.IntContext ctx) {
        return Integer.valueOf(ctx.INT().getText());
    }
}

In this book, and many threads, typically the way to approach overriding the base visitor is to call visit() within the visitor itself. Seemingly, the visitor itself governs the traversal of the parse tree.

However, when I look anywhere else about how the visitor pattern is typically implemented, the visit method almost never calls visit() within itself. Usually the accept method is used within a node or element to govern the traversal of a tree structure and calls accept on the node's children to do so, while the visitor mainly handles what operations occur for that particular visit, on that particular tree's node.

Wikipedia Example, but reduced for most important parts

public class ExpressionPrintingVisitor
{
    public void PrintAddition(Addition addition)
    {
        double leftValue = addition.Left.GetValue();
        double rightValue = addition.Right.GetValue();
        var sum = addition.GetValue();
        Console.WriteLine("{0} + {1} = {2}", leftValue, rightValue, sum);
    }
}

public class Addition : Expression
{
    public Expression Left { get; set; }
    public Expression Right { get; set; }

    public Addition(Expression left, Expression right)
    {
        Left = left;
        Right = right;
    }
    
    public override void Accept(ExpressionPrintingVisitor v)
    {
        Left.Accept(v);
        Right.Accept(v);
        v.PrintAddition(this);
    }
    
    public override double GetValue()
    {
        return Left.GetValue() + Right.GetValue();    
    }
}

In this particular example, PrintAddition() is the "visit()" method being called by accept to perform the operation.

Am I misunderstanding the visitor pattern? Is the antlr4 visitor not a standard visitor? Or is more happening under the hood of the Antlr visitor that I'm not understanding. To me, the simplified description of the visitor pattern implementation is using an "accept" method on a node's children to traverse a tree, while calling the visitor to perform operations on the children of that node.

I appreciate any help on the topic, and apologize if anything is unclear.

Best approach to manage TextWrite Object and multiple Async threads writing to the same file

Use Case

I am writing multi-threaded application where I create multiple Async threads sending Async Http Client Calls and every thread will write its response to a single shared file that the main thread creates before it fires the multiple async threads. I could resolve the thread safety by using TextWriter.Synchronized but this will require me to pass the same object to all the threads as a parameter, I can't do as this will break my design as the interface method my domain object implementing does not have such a parameter accepting TextWriter object, to resolve this issue I added a method to my ObjectFactory Class that returns a synchronized TextWriter Object, the problem with this approach is that multiple objects will try to access the same file and they will fail eventually with FileInUse Error and I do not like the idea of having multiple objects for the same purpose.

Question

I am thinking of Object Pooling Design Pattern to solve this issue. It is the first time I am implementing this approach which from what I read it is mainly used to minimize the cost of the creation of the complex objects multiple time but here I am using it to maintain the singularity of the object during the life time of the main thread which I am not sure it is correct.

What are the common factors / design pattern of the open source React UI libraries? [closed]

Question 1: What are the common factors / design pattern of the open source React UI libraries e.g. Material UI, Ant Design and React Bootstrap?

I would like to create my own React UI library for business use without using external UI libraries. Thus, I want to know what I could learn from the existing popular UI libraries and apply to my own.

Currently, I have limited use cases for each component. What I would like to achieve is creating those components with the existing confirmed use cases and add those possible use cases in future.

Question 2: So... how do those open source React UI libraries mentioned above manage their current and future use cases?

Is CodeBehind Bad Practice for Every WPF UI Design? [closed]

Recently I am doing a WPF class library, and I come out a question about XAML Code Behind. I know MVVM is a good practice for UI creation as it could help to better maintain the code, easy to modify when changes is needed, and easy to change UI platform.

But now I am doing a class library target only for WPF, can I use code behind to do it? Is it still a bad practice for WPF UI design?

Help needed, thanks in advance! :)

vendredi 25 février 2022

What is the worst time complexity of knuth-morris-pratt pattern matching algorithm

I am confused between O(n) and O(n+m).

Is there a way to access an internal parameter in a custom constructor from struct in Go?

I would like to access an internal property in a custom constructor, in my case it's a property from a superclass, like this:

type BaseRepository struct {
    database mongo.Database
}

type PointRepository struct {
    BaseRepository

    pointCollection mongo.Collection
}

func NewPointRepository() *PointRepository {
    pointCollection := ***self***.database.GetCollection("points")

    pr := &PointRepository{
        pointCollection: pointpointCollection,
    }
}

As you can see, I need to access something like self to this approach works.

How can I workaround this situation?

What does data_provider stands for? [BloC Design Pattern]

I am following some videos/courses for BloC. A structure like this took my attention:

enter image description here

And I applied the folder structure. What I couldn't figure out is what should be inside in data_provider how it should look? What am i supposed to put in it?

Is it justifiable to implement Observer Pattern on Factory?

I have created a Factory by the name duckFactory which creates different Ducks from some Duck classes, now I want every time a duck is created the duckStore class must be notified. For this purpose, I created a DuckFactoryObserver interface which I implemented on the duckFactory class.

This is the Observer interface I created.

namespace App\interfaces\Observers;

interface DuckFactoryObserver {
    public function add( Duck $duck );

    public function notify();
}

This is where I Implemented the Observer pattern.

namespace App\Factories;
use App\Characters\MallardDuck;
use App\Characters\RubberDuck;
use App\Characters\DecoyDuck;
use App\interfaces\Observers\DuckFactoryObserver;

class DuckFactory implements DuckFactoryObserver {

    private $ducks = [];

    public function duckCreator( string $color, string $duckType ) {

        switch ( $duckType ) {
            case 'mallard':
            return new MallardDuck( $color, $duckType );
            break;
            case 'rubber':
            return new RubberDuck( $color, $duckType );
            break;
            case 'decoy':
            return new DecoyDuck( $color, $duckType );
            break;
            default:
            return 'No Duck of Such Type';
            break;
        }
    }

    public function add( Duck $duck ) {
        $this->ducks[] = $duck;
    }

    public function notify() {
        foreach ( $this->ducks as $duck ) {
            echo $duck->display();
        }
    }
}

My doubt is, is it a wise choice to implement one pattern on the other?

jeudi 24 février 2022

how can i print my pattern with two symbols [duplicate]

Hello i want to print my triangle pattern using two symbols. one line $ and the other * and so on. currently all the lines are printing *.

        <?php

function printPattern($n)
{
    for ($i = 1; $i <= $n; $i ++) {
        for ($j = $i; $j <= $n; $j ++) {
            echo "*";
        }
        echo "<br>";
    }
    echo " ";
}
$n = 10;
printPattern($n);
?>

How to identify various string patterns in rows in Pandas dataframes when there are various values in between raws

Entity  Identified
0   Ref-Name    T.M.Chanika
1   Location    Kandy
2   Email   chanikalakmini23@gmail.com
3   Degree  Certificate Level of REVIT
4   Degree  Certificate Level of ADVANCED COMPUTER
5   Skill   Auto Cad
6   Degree  Certificate Level of ADVANCED COMPUTER
7   Skill   3D MODELLING using
8   Skill   Auto Cad
9   Institute   University of Moratuwa of Mechanical Engineering
10  Degree  NVQ Level 05 -Technical

Here I want to find some patterns that outputs in a NER model. For example (Name, Location, Email) pattern & (Degree, Institute) pattern. How we can do this using Pandas. If all the pattern are in order we can use some thing like this pattern = ['Ref-Name','Location','Email']

pat_i = [df[i-len(pattern):i] # Get the index 
 for i in range(len(pattern), len(df)) # for each 3 consequent elements 
 if all(df['Entity'][i-len(pattern):i] == pattern)] # if the pattern matched
pat_i

[     Entity                 Identified
 0  Ref-Name                T.M.Chanika 
 1  Location                      Kandy
 2     Email  chanikalakmini23@gmail.com]

How we can identify patterns if there are values in between like in Degree & Institute

mercredi 23 février 2022

I am implementing factory design pattern in Scala and got a compilation error when i tried to access child class method

 abstract class Computers{
    def hdd:String
    def RAM:String
    def CPU:String
  } 
   class PC(storage:String,memory:String,Cores:String) extends Computers{
   def display:String="This is PC"
    var device="PC"
    def hdd={
      "Hard disk"+" "+storage 
    }
    def RAM={
     memory
    }
    def CPU={
     Cores
    }
  }
   class LAPTOP(storage:String,memory:String,Cores:String) extends Computers{
    def see:String={
      "Hi All"
    }
    var device="Laptop"
    def hdd={
     storage
    }
    def RAM={
     device +":" +memory+" RAM"
    }
    def CPU={
      Cores
    }
  }
  object Computers{    
    def apply(compType:String,storage:String,memory:String,Cores:String)={
      compType match{
        case "PC"=>new PC(storage:String,memory:String,Cores:String)
        case "LAPTOP"=>new LAPTOP(storage:String,memory:String,Cores:String)
      }
    }  
    def main(args:Array[String]){
      val c1=Computers("PC","1 TB","12 GB","5 GHz")
      val c2=Computers("LAPTOP","1 TB","12 GB","5 GHz")
      println(c1.display)
      println(c1.hdd)
      println(c2.RAM)

    }
    
  }

Hi All,i am new to scala and tried to implement factory design pattern. But when i tried to call child class method (display method of PC class)got below compilation error : 'Value display is not a member of Computers' Can some one help why i am getting the error

Is there an alternative to Template Method pattern when using common logic?

I have a problem. Most of the solutions in the project follow the Template Method design pattern. At the same time, along with the complexity of business logic, solutions are becoming more and more confusing.

For example, there is some Copier interface:

public interface Copier {

    void copy() {
        copyA();
        copyB();
    }
}

Some classes can implement this interface by this way:

public class MusicCopier implements Copier {

    @Override
    protected void copyA() {
        SomeUtils.copy(new File(...), new File(...)));
    }

    @Override
    protected void copyB() {
        // three arguments here
        SomeUtils.copy(new File(...), new File(...)), new File(...));
    }
}

public class DocumentsCopier implements Copier {

    @Override
    protected void copyA() {
        SomeUtils.copy(new File(...), new File(...)));
    }

    @Override
    protected void copyB() {
        // three arguments here
        SomeUtils.copy(new File(...), new File(...), new File(...)));
    }
}

Then somewhere these classes are used like this:

Copier musicCopier = new MusicCopier();
Copier documentsCopier = new DocumentsCopier();

musicCopier.copy();
documentsCopier.copy();

Etc. Great. Here comes the idea to replace the interface with an abstract class and bring the main logic there. Then the abstract class will look like this:

public abstract class Copier {

    protected void copy() {
        copyA();
        copyB();
    }
    
    protected void copyA() {
       SomeUtils.copy(getASource(), getADest()));
    }

    protected void copyB() {
       SomeUtils.copy(getBSource(), getBDest(), getBExcluded()));
    }
    
    // and these terrible methods overridden in superclasses:
    protected void getASource() {}
    protected void getBSource() {}
    protected void getADest() {}
    protected void getBDest() {}
    protected void getBExcluded() {}
    // protected void getOrSetWTF() {}
}

Accordingly, the subclasses will be as follows:

public class MusicCopier extends Copier {

    @Override
    protected void getASource() { /* pass some path here */}
    
    @Override
    protected void getBSource() {/* pass some path here */}
    
    @Override
    protected void getADest() {/* pass some path here */}
    
    @Override
    protected void getBDest() {/* pass some path here */}
    
    @Override
    protected void getBExcluded() {/* pass some path here */}
}

Etc. It turns out that we are "setting up logic", which is now all in an abstract class. And the more complicated it is, the more "get" (or "set"?) there are. All this creates confusion and such code is simply unpleasant to write - especially if the project is large and developers have to "configure superclasses".

In some subclasses, I need to do something else in copyA() or in copyB(). Then I have to override these methods entirely:

@Override
protected void copyA() {
    doSomethingHere();
    
    SomeUtils.copy(new File(...), new File(...)));
    
    doSomethingHereTo();
}

Or put these "doSomething" methods also in an abstract class and then override/implement it in subclasses.

Is there patterns or combinations of them that would help get rid of this ugly design?

mardi 22 février 2022

Remove trailing white spaces on X pattern

#include <iostream>
#include <iomanip>
void draw_x(int n) {
  int r, c;
  for (r = 1; r <= n; r++) {
    for (c = 1; c <= n; c++) {
      if (r == c || c == (n + 1) - r) {
        std::cout << "*";
      } else {
        std::cout << "_";
      }
    }
    std::cout << std::endl;
  }
}

int main() {
  int n;
  std::cin >> n;
  if (n % 2 == 0) {
    std::cout << "Sorry, not odd" << std::endl;
  } else {
    draw_x(n);
  }
}

Here is my code, how would I remove any extra underscores on the right after it is printed?

enter image description here

The image shows the underscore in the middle on the right and I dont know how to remove it within my code.

What's the best way to wrap code within a new Thread, based on a boolean?

I have a method that performs some unit of work, and can optionally be spawned within a new thread or synchronously, dependant on a boolean parameter.

What's the cleanest or most standard way to implement this strategy?

To figuratively illustrate this example:

private static void MyMethod(Boolean synchronous) {

   if (synchronous) {
       SomeMethod();
   } else {
       new Thread(() => {
           SomeMethod();
       }.Start();
   }

}

Which is the design pattern to go in this situation?

I'm working on something and I've already used some design patterns, but none of them fulfills my needs completely, and that makes me think I might use a combination of patterns, but I'm a little bit stuck so I will explain the situation here and hopefully somebody could add some light about the right way to work on this one. The language I'm working with is PHP 8, in case that it helps or limits on finding a solution.

I have a class that builds, via static methods, GraphQL queries and mutations. I can't give you the exact implementation but it's something like this:

class GraphQLBuilder
{
    public static function getSettings(): string
    {
        return <<<GRAPHQL
            query{
                settings{
                    id
                    name
                    alias
                }
            }
GRAPHQL;
    }

    public static function getSetting(string $id): string
    {
        return <<<GRAPHQL
            query{
                setting(id: "$id"){
                    id
                    name
                    alias
                }
            }
GRAPHQL;
    }

    public static function setName(string $id, string $name)
    {
        return <<<GRAPHQL
            mutation {
                setting(
                    id: "$id",
                    name: "$name"
                ) {
                    id
                    name
                }
            }
GRAPHQL;
    }
}

The GraphQL server is migrating to a new version and the field alias will be called aka, but for compatibility reasons they will keep the old field for a year. I need to create a new version of the Builder class that supports the new aka field, so it will have different getSettings() and getSetting($id) methods, but the setName() method will be the same.

My goal is to create a class that works with all the methods used (in the example, getSettings(), getSetting($id) and setName($id, $name)) but fallbacks to a base class for the not implemented methods. I'd use an interface to check that all the methods are covered in the new class.

So far, I've tried to use the strategy pattern by creating a BuilderFactory that returns whether GraphQLBuilder or GraphQLBuilderNewVersion, so the methods could be used at the same way: builder::getSettings(), but that makes me include the setName() method, without any difference, in the GraphQLBuilderNewVersion, and I wouldn't like to do that because I don't want to maintain the same code in different classes.

Another approach was creating an abstract class GraphQLAbstractBuilder that has a static $settingProvider attribute, and a GraphQLBuilderBase that holds all the methods that would be needed to fallback. Both GraphQLBuilder or GraphQLBuilderNewVersion extend from GraphQLBuilderBase and implement their own specific methods, but I'd like that those specific methods are controlled in the interface but they don't have a fallback, so I can make them fail in a controlled way.

I feel like I'm overthinking this and it may be a very straightforward solution, so any advice or tip to make a robust design on this problem will be really appreaciated.

What could be the best Design Pattern for vanilla Javascript? [closed]

I was asking myself a few days ago this simple question : if we use frameworks like Angular, React or Vue, is it for the reason that we really need them, or is it just because they force||constrain front programmers to use a unique design pattern, allowing them to work together ? So here comes the second question : couldn't we imagine a simple ( or not .. ) design pattern that we could use without fashionable frameworks, allowing front-end programmers to code good, efficient javascript ?

How to design a logging event in python in an efficient way, rather than simply adding the events inside a function?

I want to implement the server-side event analytics feature (using https://segment.com/), I am clear in using the api, just we have to add the event api's inside a function whose action we need to monitor, for example, for creating a new user account in my application, I will have an event inside the function create_user

def create_user(email_id, name, id):
  # some code to add the user in my table
  ....
  ....
  # calling the segment api to track event
  analytics.track(user_id=email_id, event="Add User", properties={"username": name})

The above code works, but design wise I feel it can be done in a better way, since the create_user should have functionality of adding the user only, but here it contains the track event, and I have to do the same in modifying all the areas wherever I need to monitor by adding this analytics api and this makes my code contain irrelevant logic, I read about decorators but my analytics event depend on the code logic inside the function (like if the user email is valid then only I add the user to Db and trigger the event), so that doesn't seem to help.

So I am seeking help here in handling this scenario with the better approach and keeping the code clean. Is there any way or design approach exist for solving this case?

lundi 21 février 2022

Uploading files when creating new entities

I'm wondering if there is a common solution/pattern for the following situation:

Let's say I have a webshop application. There you can create orders, which consists of items. Each order item can have one or more files as attachments. (May not make sense, but it's just an example). Pseudocode:

Order
{
    Guid Id
    List<OrderItem> Items
}

OrderItem
{
    Guid Id
    List<Attachment> Attachments
}

Attachment
{
    Guid Id
    string Filename
    byte[] Content
}

The technology is ASP.Net MVC + React. When creating an order, I cannot send the files in the same request due to request length limits. So I have to first send a request to create an order, and then send the files one by one. How do I get the correct OrderItem id (in frontend) for each attachment?

When creating an order, none of the items have ids. CreateOrder method returns the created order and items with ids, but how can I map items in the result to items in the request that don't have ids? Result items may even be sorted differently.

One option could be to add a separate id field to OrderItem dto, e.g. NewItemId. In that case, that id would be generated by the frontend and returned by the backend in the result. However, due to how the application is structured, that would require including the property in a domain class. Is there any more elegant solution?

Python search string exact regex

I have the following statement:

name:jhonatan (intellectual person) {age:20} ;
name:jose  (kind person) {age:30} ;
name:pedro (cautious person)      {age=40} ;
name:marcos (cautious person)      {age=40};

I need to get only the names that start with J, in this case the output would be:

name:jhonatan (intellectual person) { age:20};
name:jose  (kind person) {age:30};

the goal is to use re.findall. I was trying with the following code:

re.findall(r'name:j[\w\s]+)

but I didn't get a successful exit

How do I make this pattern with number of rows and columns specified by the user?

I received this assignment and I spent the last hour trying to figure it out but I don't seem to know how to do it. I have tried many ideas but none of them worked. Here is the expected output: enter image description here

This is my final version of the code. It works however for some reason it doubles the number of columns. I'm not sure how to fix it.

int rows;
int columns;
int k = 0;
int j;
int i;
string pattern1;
string pattern2;
cout << "Enter number of desired rows: ";
cin >> rows;
cout << "Enter number of desired columns: ";
cin >> columns;
pattern1 = " \\@/";
pattern2 = " /*\\";

for (i = 1; i <= rows; i++)
{
    for (j = 1; j <= columns; j++)
    {
        if (i % 2 == 0)
        {
            cout << " /@\\";
        }
        else
            cout << pattern1;
        if (k == 0)
        {
            if (i % 2 == 0)
            {
                cout << " \\*/";
            }
            else
                cout << pattern2;
        }
    } cout << endl;
}

How to create a factory method based on static dispatch? [closed]

I want to study design pattern use rust language. From this code it works properly but it uses dynamic dispatch. How can I change the code to use static dispatch? Thanks!

trait Shape {
    fn draw(&self);
}

enum ShapeType {
    Rectangle,
    Circle,
}

struct Rectangle {}

impl Shape for Rectangle {
    fn draw(&self) {
        println!("draw a rectangle!");
    }
}

struct Circle {}

impl Shape for Circle {
    fn draw(&self) {
        println!("draw a circle!");
    }
}

struct ShapeFactory;
impl ShapeFactory {
    fn new_shape(s: &ShapeType) -> Box<dyn Shape> {
        match s {
            ShapeType::Circle => Box::new(Circle {}),
            ShapeType::Rectangle => Box::new(Rectangle {}),
        }
    }
}

fn main() {
    let shape = ShapeFactory::new_shape(&ShapeType::Circle);
    shape.draw(); // output: draw a circle!

    let shape = ShapeFactory::new_shape(&ShapeType::Rectangle);
    shape.draw(); // output: draw a rectangle!
}

Using different DTO representations for get/create/update of an object?

Let say that i have object A that has a reference to object B (in db).

interface A {
   id: string;
   bId: string;
}

interfaceB {
   id: string;
   name: string;
   // other properties
}

When creating object A, i have an autocomplete component (with API lookup). In this situation i just need bId property of an object B in order to store it in a db).

When i want to edit object A, or to show it (as a single entity or in a table) i need an object B (or a partial object) in order to preselect autocomplete component (for autocomplete component i need id and name property). Also if i want to display object A in a table, i just need a name property from B.

1 - Have one DTO for everything (get/post/put), in that case :

interface A {
  id: string,
  bId: Partial<B> // in partial object i will have just {name and id}
 }

For post/put calls, a payload would be for example {id: 3, {id: 129}} and for get requests data would be {id: 3, {id: 129, name: 'Something'}}

2 - Have different DTOs (that are basically the same in all but in one property)

3 - Something else?

What would be a good practise for this?

how should I design follow scenario which will help to maintain the code easily?

I have one onboarding page. On the Server side, I get all data entered by user like (Enterprise name, address, user info, user address, phone, etc) in JSON Object. Using this JSON object, I have to create the following object.

  1. Enterprise
  2. User
  3. Some other objects.

How can I get access to typedef types or another way exist to avoid the error? [duplicate]

I study CRTP and write the code below, but it is not working. What happens and how can I resolve it? I know that I can make 3 parameters for Unit class, but I want to avoid it if it is possible. error C2504: 'Unit<Warrior<char,int>>': base class undefined

template<class SomeUnit>
class Unit
{
public:
    void foo(typename SomeUnit::Key key, typename SomeUnit::value_type v)
    {
        static_cast<SomeUnit*>(this)->foo(key, v);
    }
};

template<class T, class U>
class Warrior : public Unit<Warrior<T, U>>
{
public:
    typedef T Key;
    typedef U value_type;

    void foo(Key key, value_type v)
    {
        std::cout << key << " " << v << std::endl;
    }
};

int main()
{
    Unit<Warrior<char, int>> war;
    war.foo('a', 5);

    return 0;
}

dimanche 20 février 2022

What to do in Java instead of calling a subclass constructor?

I'm writing a class to represent a protocol packet, and one of the header fields indicates which packet subtype it is — let's say the two subtypes are Foo and Bar. So I'd like to have a class hierarchy of:

MyPacket MyFooPacket MyBarPacket

There's a MyPacket constructor that takes a String representing te encoded packet and starts decoding it, storing each decoded fields in a MyPacket attribute, and after all the common fields are done and we know whether it's a MyFooPacket or a MyBarPacket, I'd like to then turn this MyPacket into a MyFooPacket or MyBarPacket and leave it up to the subclass' constructor to store the remaining fields in subclass attributes. But I see this isn't possible in Java.

What am I supposed to do instead?

Has Swift in Version 5.5+ a Native Language/Framework Implementation of Property Observers?

I am currently catching up with the latest language development of Swift, porting old Objective-C code to Swift 5.5/5.6. Searching for property observer patterns I found a confusing amount of old methods, which seems to point back to previous Swift versions.

Yet, I found no native implementation of an observer pattern for object properties (like the native e.g. implementation of Codable).

So, before I start manually adding a custom observer pattern for my objects. My Question:

Is there a native implementation for property observers in Swift 5.5/5.6?

  • Without @objc
  • Without NSObject
  • No NotificationCenter
  • No delegate pattern, I need a pattern that allows multiple observers.

Fictive example to illustrate what I mean with property observer pattern:

class MyObject : Observable {

  var value = 0

}

class MyUser : Observer {
  func init(obj: MyObject) {
    obj.addObserver(self)
  }
  func deinit() {
    obj.removeObserver(self)
  }
  func onValueChanged(obj: AnyObject, name: String) {
    // ...
  }
}

Repository Interface with (or without) IProgress

I've got a repository interface (simplified example code):

public interface IPersonRepository
{
    Task<PersonDTO> Get();
}

With two implementations.

One for a direct connection to a database:

public SqlPersonRepository : SqlRepository, IPersonRepository
{
    public SqlPersonRepository(IDbConnectionProvider dbCon) : base(dbCon) { }

    public async Task<PersonDTO> Get()
    {
        // use dbCon and dapper to get PersonDTO from database
    }
}

And another one for remote access via web api:

public ApiPersonRepository : ApiRepository, IPersonRepository
{
    public ApiPersonRepository(IApiConnectionProvider apiCon) : base(apiCon) { }

    public async Task<PersonDTO> Get()
    {
        // use apiCon (contains base url and access token) to perform an HTTP GET request
    }
}

The interface makes sense here, because the server can use the SqlPersonRepository. And the remote (native) client can use the ApiPersonRepository. And for most all of the the use cases, this is all I need.

However, my application supports an extraction of a subset of data from the server so that the client application can run while offline. In this case, I'm not just grabbing one person, I'm grabbing a large set of data (several to tens of megabytes) which many times will be downloaded over a slow mobile connection. I need to pass in an IProgress implementation so I can report progress.

In those cases, I need an ApiDatabaseRepository that looks like this:

public ApiDatabaseRepository : ApiRepository, IDatabaseRepository
{
    public ApiDatabaseRepository(IApiConnectionProvider apiCon) : base(apiCon) { }

    public async Task<DatabaseDTO> Get(IProgress<int?> progress)
    {
        // use apiCon (contains base url and access token) to perform an HTTP GET request
        // as data is pulled down, report back a percent downloaded, e.g.
        progress.Report(percentDownloaded);
    }
}

However the SqlDatabaseRepository does NOT need to use IProgress (even if Dapper COULD report progress against a database query, which I don't think it can). Regardless, I'm not worried about progress when querying the database directly, but I am worried about it when making an API call.

So the easy solution, is that the SqlDatabaseRepository implementation accepts the IProgress parameter, with a default value of null, and then the implementing method just ignores that value.

public SqlDatabaseRepository : SqlRepository, IDatabaseRepository
{
    public SqlDatabaseRepository(IDbConnectionProvider dbCon) : base(dbCon) { }

    public async Task<DatabaseDTO> Get(IProgress<int?> progress = null)
    {
        // use dbCon and dapper to get DatabaseDTO from database
        // progress is never used
    }
}

But that smells funny. And when things smell funny, I wonder if I'm doing something wrong. This method signature would give the indication that progress will be reported, even though it won't.

Is there a design pattern or a different architecture I should be using in this case?

Address lookup pattern java

What is the best pattern or design to choose to search for an address. For example, there will be a request

SELECT * 
FROM addresses 
where street_name = 'abcd' 
  AND house_number = '1' 
  AND corps_number = '1' 
  AND app_number = '23' 
  AND index_app = 'A'

if there is no result, remove index_app from the end For example

SELECT * 
FROM addresses 
where street_name = 'abcd' 
  AND house_number = '1' 
  AND corps_number = '1' 
  AND app_number = '23'

And keep going until you get the result.

In Java app I have a request, since I initially do not know what data will be, whether there will be an apartment or building number, based on this data, I form sql and send a request. It’s just that if nothing was found, I need to find out why, maybe there is such a house, but I made a mistake with the apartment number.

How to design a complex function for scalability?

I have an app that needs to process various types of user uploaded files. The most common is images.

However not all images are handled in the same way. How they are processed depends on what they'll be used for e.g. a product image needs to be much bigger size than a profile picture.

I have made a single function called processImage() which takes in arguments about the image that needs processing and creates different size images etc.

Its layout is like this:

mediahandler.js

processImage({ area, usage, uploadto, filepath, mimetype, etc, etc });
{
  // This could be a number of places like S3, Google Drive

  if (area === "Shop") {
    // What area will this image be used in? Determines properties and metadata of images

    if (usage === "Hero") {
      // What is the purpose of the image?
      // Hero images will be large and high quality

      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    } else if (usage === "Thumbnail") {
      // Thumbnails will be small and low quality
      if (uploadto === "SSD") {
        // Now write to serveer hard drive using file system
      } else if (uploadto === "S3") {
        // Now upload to S3 using a buffer
      }
    }
  }
}
// Other functions
 processVideo(){ }

As you can see the number of if/else or even switch statements grows quickly. I fear this will be end up becoming a huge convoluted do-it-all function which may not scale well (I really don't know if this is even a legitimate concern).

If I was to break this function apart and create several functions e.g. processStoreImage() and processPofileImage() then I will end up repeating a lot of code between them and violate the DRY (Don’t Repeat Yourself) principle.

Is there a 'better' way of going about this?

Class method returning Sub-Class in JavaScript

In Mongoose documentation we find:

In Mongoose, the term "Model" refers to subclasses of the mongoose.Model class.
You should not use the mongoose.Model class directly.
The mongoose.model() function creates subclasses of mongoose.Model...

I have never seen this kind of design pattern where a class method creates subclasses (not instances) of itself. Does this design pattern have a name?

Offical doc can be found here: https://mongoosejs.com/docs/api/model.html

Designing wallet system in nodejs

I am making a product for which I want to have a credit-based system so that a user can buy credit with real money and use it within the app. I am using Nodejs for the backend and MongoDB as the database. Some approaches I've looked into:-

  1. Write models for credit system and use mongo transactions throughout.
  2. Use blockchain for making a new closed(only for my app) currency.

I don't know which way to go or even if one way is wrong or not. Please share some ideas if you have and maybe some open source libraries that can help.

vendredi 18 février 2022

Suggestions on how to create large scale plugin system nodejs?

I'm working on a project(built in node.js) which converts figma design to react source code and Currently we are building functionality where user can generate code with all the actions they integrated like navigation, API integration, firebase, supabase etc.

At initial level, it was super easy to handle with small actions like navigation (same page, different page, back navigation), where i just had to inject one line code into generated JSX page like below before return of JSX.

window.location.href="www.google.com"

But now it's getting complicated where we need to handle more complex actions & also 3rd party integrations.

How can i define system in such a way that there's no dependencies of actions with each other & easy to inject code of API integration or any other 3rd party libraries template.

I read one blog which had similar pattern, look at it here. But still wanted to know if there is any other solution or workaround available.

If not code example, any reference system would help also from github.

How can I structure my classes which usually need to be called together?

I have some related classes that implement the same method

class Dog {
    public void speak() { System.out.println("Bark") }
}
class Cat {
    public void speak() { System.out.println("Meow") }
}

90% of the time, users would want both the dog and the cat to speak. They don't want to know the details. When we add a new animal, they'll want it to speak too. The idea is to avoid:

// All animals need to be explicitly told to speak every time
new Dog().speak();
new Cat().speak();

// But we just added Birds, and the users need to remember to add this call everywhere
new Bird.speak();

I could do something like

class Animals {
    public void speak() {
        new Dog().speak();
        new Cat().speak();
        new Bird().speak();
    }
}

So that users can just call new Animals().speak() every time.

However, 10% of the time, it does need to be configurable. What I want is a way for users to do something like this

// Used most of the time
Animals.withAllAnimals().speak();

// Sometimes they don't want cats, and they want the dogs to woof instead
Animals.exclude(Cat)
  .configure(Dog.sound, "Woof")
  .speak();

How can I structure my classes to accomplish this?

why asp.net core use Feature for HttpRequest and HttpResponse? [closed]

For example, to represent Header, asp.net core uses HttpRequestFeature to get headers:

internal sealed class DefaultHttpRequest : HttpRequest {
   // ...
   private FeatureReferences<FeatureInterfaces> _features;
   private IHttpRequestFeature HttpRequestFeature => _features.Fetch(ref _features.Cache.Request, _nullRequestFeature)!;

   public override IHeaderDictionary Headers {
      get { return HttpRequestFeature.Headers; }
   }
}

so why not just design it directly as:

internal sealed class DefaultHttpRequest : HttpRequest {
   // ...
   private IHeaderDictionary headerDictionary = new HeaderDictionary();
  
   public override IHeaderDictionary Headers {
      get { return headerDictionary ; }
   }
}

why use an extra abstract layer HttpRequestFeature?

jeudi 17 février 2022

Design patterns for mathematical visualisation tool in C++

I am writing a visualisation tool for creating mathematical animations for a YouTube channel that I want to create. The tool will eventually have similar functionality to Manim, except that I am implementing everything using OpenGL in C++.

I have already developed the base functionality for visualising models via the OpenGL pipeline. However, I am a bit stuck with designing an animation manager to conveniently choreograph multiple models over the timeline of an animation. This is because I am still developing an intuition for when to apply specific design patterns in different contexts. So far, I have applied the Observer Pattern as follows - I have a Visualiser class which holds pointers to Models and, amongst other things, keeps track of the global timestamp of the animation. Each model holds a shared pointer to the Visualiser object that points to it, to be able to observe the timestamp of a given frame and compute a local time parameter for the lifetime of the model (e.g. for the purpose of moving the model along a parametrised trajectory). I would like to equip each model object with the following actions over its lifetime (Model is an abstract class with these virtual methods):

  1. Scaling.
  2. Translating
  3. Rotating about an axis
  4. Ramping up - i.e. visualising the construction of the model at the beginning of its lifetime (e.g. tracing the perimeter of a circle)
  5. Ramping down - i.e. visualising the destruction of the model at the end of its lifetime.
  6. Transforming to a different model (e.g. smooth transformation from a circle to a square)
  7. Transform from a different model (instead of ramping up)
  8. Transform to a different colour

I would like to implement an interface (in Model?) that allows me to implement an arbitrary combination of the above actions. Each Model will be specified a start and end time corresponding to the global timestamp in Visualiser, and each action will be given a start time and a duration for the action (except for ramp up/down, which will only be given a duration). I am leaning towards using the Decorator Pattern here, but I am not sure how to adapt it to this context.

I would appreciate any advice on which design patterns would be best for the above scenario.

Cpp: using scoped resource without passing arguments around

I've been struggling with a design problem in cpp for a while. I have a resource (In this scenario a configuration). This configuration is global, and it is initialized and cleared multiple times during the program execution (If it's cleared, there is no current configuration, and if something needs it will fail).

I want to use this configuration inside a class- but I do not want to pass it around as a parameter, since it will change dozens of functions, and complicate classes interfaces a lot (and sometimes it even might be a weird dependency, especially if some derived classes need it and some do not).

Now I use a weird singleton, that can be cleared and initialized, but the codebase grew, and it looks bad now

Pseudo code for demonstration:

Configuration::init(buffer);
SomeClass some_class(param1, param2);
some_class.do_dirty_work_using_the_configuration();
Configuration::clear()

This code is not RAII and I actually use a class to initialize and clear the configuration in the real implementation.

I heard the solution should be dependency injection, but as far as I know there is no good implementation for it in cpp

Thank you!

Terraform: make immutalbe environment

Looking for help to address following issue.

When sequentially running tg plan & tg apply & tg plan both plans always showing the environment changes.

Sometimes it's clear when resources are some timestamps or null_resources. Sometimes not very e.g: data or some jsonencode function. And sometimes it's not clear at all when you not in context, e.g: gateway_deployemnt_id:

There must some anti-pattern or list of resources we should try avoid to use but I can't find it.

mercredi 16 février 2022

Print the following pattern for the given N number of rows

Pattern for N = 4 4444 4444 4444 4444

Sample Input 1: 7 Sample Output 1: 7777777 7777777 7777777 7777777 7777777 7777777 7777777

my code is only print 4

SOLID What is wrong in this class?

Can anybody help with a task? What is wrong in this class I can't understand what is wrong here

MySqlClient class

  • connection(url: String, user: String, Password: string): boolean
  • query(sql: String): List
  • create(object: Object): Object
  • buildWhereCondition(conditions: HasMap): String

Why persist permissions in the db?

Lets assume we have following two roles for a given application: User and Admin

User has following permissions: ReadUser, UpdateUser Admin has following permissions: ReadUser, UpdateUser, CreateUser, DeleteUser

Most of the applications I have worked upon persists both the roles and permissions to the db as follows:

Role (RoleID, RoleName) (1, User) (2, Admin)

Permission (PermissionID, PermissionName) (1, CreateUser) (2, ReadUser) (3, UpdateUser) (4, DeleteUser)

RolePermission (ID, RoleID, PermissionID) (1, 1, 2) (2, 1, 3) (3, 2, 1) (4, 2, 2) (5, 2, 3) (6, 2, 4)

My question is what is the benefit around persisting permissions to the db compared to having map of roles with permissions in the code to handle permissions?

I would appreciate if you can elaborate the pros and cons.

mardi 15 février 2022

Does C# currently support contravariant interfaces? (E.g. Collections of interfaces without requiring inheritance of a derived interface)

Does C# have a way of requiring a property or field to implement a multiple interfaces without requiring implementation of a derived interface?

As an example of non-working code to explain the concept:

public interface IBase1 {...}
public interface IBase2 {...}
public interface in IContravariantDerived : IBase1,IBase2 {}

public class DerivedClass : IBase1,IBase2 {...}

Ex1:

IContravariantDerived MyObject = new DerivedClass(); //Fails because object does not implement IContravariantDerived 

Ex2:

interface<IBase1,IBase2> MyObject = new DerivedClass(); //Fails, not valid syntax.

This would be for interfacing with 3rd part libraries (e.g. a property with INotifyPropertyChanged and INotifyCollectionChanged),but where the 3rd party library is sealed, or boiler plate wrappers would bloat the code.

If there isn't anything in the current spec, does an IL weaving library or a planned feature for the next c# version exists?

How to abstract interface method whose param is derived-class-dependent in C#?

I have two version of data manager, and an interface to abstract these two managers. All these two managers take the data's description as string, hiding the specific data structure.

Now I need to add a method with a param of Action<Item> (rather than Action<string> with string stores the description), this action is passed to SDK which cannot be modified.

In this case, the Action<Item> varies according to the specific implementation of Item. How to add this method in C# way?


Here is the example

  1. The interface of different data manager
// the interface
interface IContentManager
{
    void UpdateProduct(string id, string productDescription);

    // TODO: public void ApplyForAll(Action<???> op)
}
  1. The first version of data manager based on a database SDK

The database SDK provides these classes which cannot be modified

class ProductItem { }
class ProductDBWriter
{
    // this method cannot be modified
    public void ApplyForAll(Action<ProductItem> op) { }
}

The data manager based on database SDK

class DBContentManager
{
    void UpdateProduct(string id, string productDescription) { }

    public void ApplyForAll(Action<ProductItem> op)
    {
        _writer.ApplyForAll(op);
    }

    private ProductDBWriter _writer;
}
  1. The second version of data manager, a lightweight version
class ProductItemSlim { }

class SlimContentManager
{
    void UpdateProduct(string id, string productDescription) { }

    // TODO: public void ApplyForAll(Action<???> op)
}

The question is: what is the C# way to abstract the ApplyForAll method?

Restricting certain public APIs/classes to users in java

I have a application where users can write their customizations using the exposed public APIs. There are few public classes and API that are public but we don't want them to be accessible in the customization code for the users. Is there any way in java to do this without changing the access modifiers of the remaining APIs. I am exploring java security manager, don't know if it would work, any help would be appreciated.

Change the state of an object according to the state of the other objects

According to this main:

int main() {
    Worker* w1 = new Worker();
    Worker* w2 = new Worker();
    Worker* w3 = new Worker();
    Worker* w4 = new Worker();
    w1->worksWhen(w2, w3); // When w1 works then w2 & w3 starts working
    w2->worksWhen(w1, w3, w4); // When w2 works then w1 & w3  & w4 starts working
    w1->work(); // So that - w2 & w3 is working because w1 works now
    return 0;
}  

How should we write the Worker class? I try with this:

class Observable;
class Observer {
public:
    virtual void update(Observable& o)=0;
};

class Observable {
    list<Observer*> observers;
public:
    void addObserver(Observer& o)  {
        observers.push_back(&o);
    }
    void notify() {
        list<Observer*>::iterator it = observers.begin();
        while (it != observers.end()) {
            (*it)->update(*this);
            it++;
        }
    }
};

class Worker : public Observable {
    bool working;
public:
    Worker() {
        working = false;
    }
    bool isWorking() {
        return working;
    }
    void worksWhen() {
        
    }
    void work() {
        this->working = true;
        notify();
    }
};

My question is: How can I get in worksWhen sometimes 2 arguments of Worker and sometimes 3 arguments of Worker, what should I receive in the worksWhen function and how can I update all the state of the other workers?

lundi 14 février 2022

In a Create method , how to deal with the situation that data has been stored but operation failed?

I’m writing a scheduler module for job scheduling. In the Create method, my code will

  1. store the job info into database
  2. add the job to a scheduler instance

But I don’t know how to deal with the scenario that the job info has been stored into database but failed to be added to the scheduler. I want to make sure the jobs in database and scheduler are consistent. My current way is to delete the job info in database once the second step fail. Does that make sense? Or is there any other best practice? Thanks!

Is the relationship between a View and a Controller in MVC really just a Strategy pattern?

The Gang of Four book states the following:

[...] The main relationships in MVC are given by the Observer, Composite and Strategy design patterns.

The best example of this I could find was this github repo, which shows the following class diagram:

enter image description here

I'm particularly interested in the Strategy part of the MVC, where the following holds:

MVC Name GoF Name
View Context
Controller Strategy
ConcreteController ConcreteStrategy

Regarding the relationship between View and Controller, The book Head First Design Patterns states the following:

The controller may also ask the view to change. When the controller receives an action from the view, it may need to tell the view to change as a result. For example, the controller could enable or disable certain buttons or menu items in the interface

It also shows an example where the ConcreteController equivalent BeatController) defines an additional association with the ConcreteView equivalent (DJView):

package headfirst.designpatterns.combined.djview;
  
public class BeatController implements ControllerInterface {
    BeatModelInterface model;
    DJView view;
   
    // BeatController implementation
}

This association is not present in the Strategy pattern, which only has an arrow going from Context to Strategy (and not the other way round).

I've seen many other examples online where such an association from the Controller to the View is defined. Is the relationship between Controller and View really only a strategy? If not what is it?

MVC is (not?) a combined pattern of Composite, Strategy and Observer according to Head First?

The Gang of Four book states the following:

[...] The main relationships in MVC are given by the Observer, Composite and Strategy design patterns.

The best practical example I could find of this was in this github repo:

enter image description here

Where the following holds:

MVC Name GoF Name GoF Pattern
Model Subject Observer
View Observer Observer
ConcreteView ConcreteObserver Observer
Controller Strategy Strategy
Button Leaf Composite
Text Leaf Composite
Window Composite Composite
ConcreteModel ConcreteSubject Observer
ConcreteController ConcreteStrategy Strategy

In contrast, the book Head First Design Patterns states the following about the MVC:

The Controller may also ask the view to change. When the controller receives an action from the view, it may need to tell the view to change as a result. For example, the controller could enable or disable certain buttons or menu items in the interface

In the subsequent example, the authors allow the ConcreteController equivalent BeatController) to define an association with the ConcreteView equivalent (DJView):

package headfirst.designpatterns.combined.djview;
  
public class BeatController implements ControllerInterface {
    BeatModelInterface model;
    DJView view;
   
    // BeatController implementation
}

I can sort of see the practical reason they did this, namely that the Controller needs to talk to the View. However, this association is not present in the UML above, and indicates a deviation from the GoF idea that MVC is an Observer, Composite and Strategy superpattern.

Why did they do this? How does it fit into the GoF description?

Color with Excel and Openpyxl

Good morning, I would like to fill some cells with a gray background, the code works and the color as well, in visual code in the preview of the excel file I see the colors correctly, are that when I open the file with excel the background is always black. any help?

        def excel():
                # Writing on a EXCEL FILE
                filename = ("testexcelcolor.xlsx")
                try:
                    wb = load_workbook(filename)
                    ws = wb.worksheets[0]  # select first worksheet
                except FileNotFoundError:
                    headers_row = ['Name SGV PN', 'IVU Nummer']
                    wb = Workbook()
                    ws = wb.active
                    ws.append(headers_row)
                for cols in ws.iter_cols():
                     if cols[-1].value: # need to check the cells have values.
                            # otherwise colors the entire row.
                        cols[-1].fill = PatternFill(bgColor="FFFFFF", fill_type="solid")
                wb.save(filename)
                ws.append([ivunumber])
                wb.save(filename)
                wb.close()
        excel()

Optimized method of getting list of attributes in Java 8?

My question is an extension of this question.

To get a list of attributes we can use this code:

List<String> namesList = personList.stream()
                                   .map(Person::getAge)
                                   .collect(Collectors.toList());

However if I want to get 100 different attributes.
List<String> namesList = personList.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getSurName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getFathersName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getMothersName)
                                   .collect(Collectors.toList());

then would it be better to rewrite this line 100 times or should I simply run 1 loop and collect all the attributes there.

Does the composite design patterm adhere the principles of SOLID (spacialy the L and the I)?

Does the composite design template adhere to the principles of solid? if all the compositing method are declared at the component its violation of the Interface Segregation Principle. if compositing method are declared at the composite its violation of Liskov Substitution Principle - because we change are behaver when it leaf and when it composite. am i wrong?

How can I fill my rich model from repository when I am no using ORM?

I am trying to develop my application using the DDD approach and I should set all of my properties private. I need to use Aerospike as my database and there is no ORM to fill my properties magically like EntityFramework with a private default constructor. Now, How can I fill this reach model without exposing a full property constructor that can be accessible everywhere and can breach the rule of encapsulation business domain rules?

making all properties protected and creating an internal inherited class inside the repository namespace that can act as a proxy object to fill property can be a solution But I have no idea about the best practice and acceptable design.

dimanche 13 février 2022

How to set public data in Strategy Pattern

I am making a custom flow form function, including flow and form, with various controls in the form (including, single line text, number input box, date input box, etc.), and the properties of each control are different, so I need to deal with receiving parameters and echo

I used MAP to receive irregular properties, and used Strategy Pattern to make a converter for each control, converting the MAP into a corresponding control object

public interface FormWidgetRequestConverter<T extends WidgetProperties>  extends MapConverter<T>, FormWidget {
@Component

public class WidgetEmailRequestConverter implements FormWidgetRequestConverter<WidgetEmail>{

    @Override
    public WidgetEmail convert(LinkedHashMap<String, Object> source) {
        return JacksonUtils.convertValue(source, WidgetEmail.class);
    }

    @Override
    public FormWidgetTypeEnum getType() {
        return FormWidgetTypeEnum.EMAIL;
    }

}

Now I want to optimize (that is, when there are 10 identical controls, it is necessary to extract these 10 identical attributes into parameters for batch query, and then set them back, so that there is no need to query again every time a control is dropped, it is actually the same Inquire)

What can i do

Matching pattern and adding values to a list in TCL

I wondered if I could get some advice, I'm trying to create a list by reading a file with input shown below

Example from input file

Parameter.Coil = 1
Parameter.Coil.Info = Coil
BaseUTC.TimeSet_v0 = 1
BaseUTC.TimeSet_v0.Info = TimeSet_v0
BaseUTC.TimeSet_v1 = 1
BaseUTC.TimeSet_v1.Info = TimeSet_v1
BaseUTC.TimeSet_v14 = 1
BaseUTC.TimeSet_v14.Info = TimeSet_v14
BaseUTC.TimeSet_v32 = 1
BaseUTC.TimeSet_v32.Info = TimeSet_v32
VC.MILES = 1
VC.MILES.Info = MILES_version1

I am interested in any line with prefix of "BaseUTC." and ".Info" and would like to save value after "=" in a list

Desired output = TimeSet_v0 TimeSet_v1 TimeSet_v14 TimeSet_v32

I've tried the following but not getting the desired output.

set input [open "[pwd]/Data/Input" r]

set list ""
while { [gets $input line] >= 0 } {
incr number
set sline [split $line "\n"]
if {[regexp -- {Steering.} $sline]} {
#puts "lines = $sline"
if {[regexp -- {.Info} $sline]} {
set output [lindex [split $sline "="] 1]
lappend list $output
}}}
puts "output = $list"
close $input

I get output as

output = \ TimeSet_v0} \ TimeSet_v1} \ TimeSet_v14} \ TimeSet_v32}

Can any help identify my mistake, please.

Thank you in advance.

Python Singleton objects with the same attribute should reference to the same object

I want Python to return the same object when the instances are created with the similar attributes. Also when I am changing some attribute of one instance, that attribute should be synchronized between other instances also.

class Session:
    def __init__(self, id):
        self.id = id 
        self.data = None

session1 = Session(1)
session1.data = 202
print(session1.data) # 202
print(id(session1)) # should be 1111

session11 = Session(1)
print(session11.data) # 202
print(id(session11)) # should be the same as session1 -> 1111

session2 = Session(2)
print(id(session2)) # 2222

You can see above that I want session1 and session1a be the same object because of Session(1), while session2 is another object because of Session(2).

How could I do it?

Loading and sharing configuration data in an Akka project

/Users/aronayne/projects/code-scraps/src/main/java/q2

Title

Pattern for reading Akka configuration into an application.

Body

I’ve defined two applicaiton.conf files, one for each environment dev and prod :

application-dev.conf application-prod.conf

To read the configuration values I use a config object builder (using lombok) named ConfigurationObject to set the values read from the application configuration files. The configuration object just stores two properties ‘kafkaBrokers’ and ‘someOtherConfig’ :

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigLoader.class);

    public static void main(String[] args) {

        String env = "dev";
        final Config configDev = ConfigFactory.load("application-"+env+".conf");
        final ConfigurationObject configurationObjectDev = ConfigurationObject.builder()
                .kafkaBrokers(configDev.getString("kafka-config.brokers"))
                .someOtherConfig(configDev.getString("kafka-config.brokers"))
                .build();

        env = "prod";
        final Config configProd = ConfigFactory.load("application-"+env+".conf");
        final ConfigurationObject configurationObjectProd = ConfigurationObject.builder()
                .kafkaBrokers(configProd.getString("kafka-config.brokers"))
                .someOtherConfig(configProd.getString("kafka-config.brokers"))
                .build();

        LOGGER.info(configurationObjectDev.toString());
        LOGGER.info(configurationObjectProd.toString());

    }
}

Here I’ve defined the configuration object to store the values read from application.conf :

import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class ConfigurationObject {
    final String kafkaBrokers;
    final String someOtherConfig;
}

Should I just use ConfigFactory.load directly instead of wrapping each property from a given environment application.conf to a configuration object, in this case ConfigLoader. Is there a pattern I should use for this ?

Application conf files :

application-dev.conf :

kafka-config {
    brokers="broker1,broker4"
    brokers = ${?MY_KEY_ENV}
}

some-other-config {
    brokers="broker-prod1,broker-prod4"
    brokers = ${?MY_KEY_ENV}
}

application-prod.conf :

kafka-config {
    brokers="broker-prod1,broker-prod4"
}
some-other-config {
    brokers="broker-prod1,broker-prod4"
   brokers = ${?MY_KEY_ENV}
}

samedi 12 février 2022

Using Traits to configure an application

I've been trying to figure out a good idiomatic configuration pattern in Rust. I read a few articles and the impression I'm getting is that Traits are a way to go for my use-case. However the examples were either too simplistic or too complex. But I went ahead an refactored my application but encountered some stuff I've never seen/understood. I marked the two locations in the code.

(a) - It took a minute to get this running as I kept dealing with compiler errors but finally tried &* assuming I was de-referencing the Box and then passing a reference to it. I'm not entirely sure this is correct and would like some insight into why it works and if it'll bite me later.

(b) - None of the articles/examples I read explained how to pass the configuration to other internal methods. Again I just kept adding symbols until the compiler was happy so I'm not too confident this is the right way.

On the pattern:

My example code's structure is very similar the actual application. I take the user's input then pass it to the App which delegates the creation of the data to Words::add() who delegates the creation of a Word to Word::new() and so on. In the actual application there's an additional layer or so where metadata is generated but in the end a each of these need access to the configuration. I started with a global static config which led to testing headaches, then moved to a concrete Config type which resulted in a massive struct dealing with all the different contexts.

My goal is to have an immutable configuration that can change based on context e.g. dev, testing, production etc. I'm assuming this is a big topic that might not have a simple answer but curious if there any insights into this. I was unable to find one that fits my use-case so I'm not 100% confident I'm going in the right direction.

Link to the playground.

// Trait

pub trait Configuration: std::fmt::Debug {
    fn prefix(&self) -> String;
    fn suffix(&self) -> String;
}

// App

#[derive(Debug)]
pub struct App {
    config: Box<dyn Configuration>,
    data: Words,
}

impl App {
    pub fn new(config: Box<dyn Configuration>) -> Self {
        Self {
            config,
            data: Words::default(),
        }
    }

    pub fn add(&mut self, word: &str) {
        self.data.insert(&*self.config, word);
        // (a) This -----^^
    }
}

#[derive(Debug, Default)]
struct AppConfig;

impl Configuration for AppConfig {
    fn prefix(&self) -> String {
        "re".to_string()
    }
    fn suffix(&self) -> String {
        "able".to_string()
    }
}

// Words

#[derive(Debug, Default)]
struct Words(Vec<Word>);

impl Words {
    fn insert(&mut self, config: &dyn Configuration, word: &str) {
        // (b) This -------------^^^^

        let word = Word::new(config, word);

        println!("Adding {:?}", word);

        self.0.push(word);
    }
}

#[derive(Debug, PartialEq)]
struct Word(String);

impl Word {
    pub fn new(config: &dyn Configuration, word: &str) -> Self {
        Self(format!("{}{}{}", config.prefix(), word, config.suffix()))
    }
}

fn main() {
    let config = AppConfig::default();
    let mut app = App::new(Box::new(config));
    app.add("use");
    app.add("mark");
    app.add("seal");
}

#[cfg(test)]
mod tests {

    use super::*;

    #[derive(Debug, Default)]
    struct TestConfig;

    impl Configuration for TestConfig {
        fn prefix(&self) -> String {
            "test".to_string()
        }
        fn suffix(&self) -> String {
            "able".to_string()
        }
    }

    #[test]
    fn test() {
        let config = TestConfig::default();
        let mut app = App::new(Box::new(config));
        app.add("");

        assert_eq!(app.data.0[0], Word("testable".to_string()));
    }
}

Why does this Java callback pattern work?

I came across this Java callback example on the internet, and I don't understand why it works.

Callback.java:

interface Callback {
  void call();
}

SomeTask.java:

class SomeTask extends Thread {
  @Override
  public void run() {
    System.out.println("SomeTask started");
  }

  public void execute(Callback callback) {
    System.out.println("execute in SomeTask");

    callback.call();
  }
}

SomeThread.java:

class SomeThread extends Thread {
  @Override
  public void run() {
    System.out.println("SomeThread started");

    SomeTask someTask = new SomeTask();

    someTask.start();

    someTask.execute(this::foo);
  }

  private void foo() {
    System.out.println("foo in SomeThread");
  }
}

Main.java:

class Main {
  public static void main(String[] args) {
    new SomeThread().start();
  }
}

Specifically, why does "someTask.execute(this::foo)" work when SomeThread does not implement the Callback interface, and SomeTask invokes "callback.call()"?

And, is the the correct way to implement a callback pattern in Java?

Replacing strings in vector: Every instance replaced by previous found instance

I'm working with a lot of text files I have loaded into R and I'm trying to replace every instance (or tag) of </SPEAKER> with a certain string found earlier in the text file.

Example: "<BOB> Lots of text here </SPEAKER> <HARRY> More text here by a different speaker </SPEAKER>"

I'd like to replace every instance of "</SPEAKER>" with the name of, say "<BOB>" and "<HARRY>" based on the NAME that has been found earlier, so I'd get this at the end:

"<BOB> Lots of text here </BOB> <HARRY> More text here by a different speaker </HARRY>"

I was thinking of looping through the vector text but as I only have limited experience with R, I wouldn't know how to tackle this.

If anyone has any suggestions for how to do this, possibly even outside of R using Notepad++ or another text/tag editor, I'd most appreciate any help.

Thanks!

Useless Kotlin delegate

I'm trying to understand why we have feature as delegate in Kotlin. This example is similar to wiki example https://en.wikipedia.org/wiki/Delegation_pattern

Check this commented fragment, I don't need it for using area function on bounds so why we should use : ClosedShape by bounds ?

interface ClosedShape {
    fun area(): Int
}

class Rectangle(val width: Int, val height: Int) : ClosedShape {
    override fun area() = width * height
}

class Window(private val bounds: ClosedShape)  /*: ClosedShape by bounds */ {
    init {
        bounds.area()
    }
}

vendredi 11 février 2022

Where should I put the complex queries using the Repository Pattern?

I have an application in which I use Entity Framework, and I have a class called BaseRepository<T> with a few basic CRUD methods, such as (Get, GetAll, Update, Delete, Insert), and from this class I generate my specific repositories, such like BaseRepository <Products>, BaseRepository<People>, BaseRepository<Countries> and many more.

The problem is that, when I have a complex logic in the service, that involves making joins of several tables and that does not return an entity, but an object that is handled in the service (it is neither a DB entity nor a DTO), I find that repositories don't help me much with just basic CRUD operations.

Where should I put this query complex? in which of the repositories should it be? How do I join these repositories? The problem is that I see that the repositories handle a single entity, what should I do in this case? I've been doing some research and read that returning IQueryable<T> is bad practice, so I rule out that possibility of sending IQueryable<T> of the tables I'm going to join the service and do it there.

I've researched and found no clear answer. I would like to know how and where these complex queries are organized, since I also want to respect the responsibility of each repository with its respective entity.

Callback casting and set from another object [resolved]

I just wanted to ask if my approach is wrong or one is the right way and it can be done.

In the project, I have one hal and several types of Dir based on Base. When I create some dir I pass hal to it because each dir uses it in its own way. Everyone also reacts in their own way to events in the hal. so I wanted to use the callback mechanism. I one moment I have only one specific controller, and I change it, delete, and create another, at this moment I must connect callback. I create a solution with one dir type, and it's working fine. But what path choose when I want to use a few different dir, Can I cast to base and use base in Hal something like this:

class Base;

class Hal
{
  public:
  void set_callback(void (Base::*callback)(int), Base* base)
  {
    m_callback = callback;
    m_base = base;
  }
  void fun()
  {
    (m_base->*m_callback)(some_int);
  }

  private:
  Base* m_base;
  void (Base::*m_callback)(int);
};
#include "Hal.h"

class Base
{
  public:
  virtual void active() = 0;
  virtual void foo(int variable) = 0;
};
class Dir : public Base
{
  public:
  Dir(Hal& hal)
  : m_hal(hal)
  {}
  void active()
  {    
    auto callback = &Dir::foo;
    //add some casting?
    m_hal.set_callback(callback, this);
  }
  void foo(int variable)
  {
    // some code
  }

  private:
  Hal& m_hal;
};

Maybe I should add a separate class for routing such callbacks? Or use a different mechanism? Unfortunately, I don't have functional lib available in this project /:

Design pattern - Python function applied to different objects

I have modified Numpy's apply_along_axis() function and I want to be able to use this function on different objects (such as xarray.DataArray and other multi-dimensional data structures). My modified apply_along_axis() coerces the input to a numpy array using np.asanyarray(). I would like to have a design pattern where i can apply this function to different objects but preserve the meta-data associated with those objects. The meta-data/attributes are now lost because of the coercion to a numpy array.

I do not want to modify the core functionality of apply_along_axis() or do type checking on the arguments within apply_along_axis(). I want to be able to easily add support for new data structures in the future... I was thinking of either wrapping the input datastructures or the apply_along_axis() function. But I'm not sure how to go about it. Looking for elegant solutions.

How should we design API which need to aggregate (join) from multiple database tables [closed]

We are working on product which provide API for listing, with filtering, sorting, paginating ... The response result is aggregating from multiple database tables, to enrich data from those tables, or for filtering, sorting.

I"m considering to 2 solutions

  1. JOIN multiple tables, with condition for querying, and order for sorting.
  2. Create a view (or temporarily table) for storing aggregated data, it's transform from all related tables, and then API will query on that table only. Each record on that table will be updated once business tables have changed.

For the 1st solution, I think it's easy for maintaining consistent data, however it's hard for scaling, and the performance could be impact a lot because of many join. Especially for query on particular fields.

On another hand, 2nd solution is suitable for CRUD behaviour, but we need to maintain a logic for updating data on temporarily table, also we might need to add more field to that table if we are asked to show more data in the API.

I don't know exactly which design is good, and do we have any design pattern suitable for this requirement

mercredi 9 février 2022

Pattern to Orchestrate sequence of API calls C#

I have 3 microservices exposing APIs for interaction.

The order microservice receives order from UI and makes an API call to Inventory microservice to update the inventory details to reduce the itemCount.

Once the above operation succeeds, the order microservice will make calls to Payment microservice to initiate payments. If payment succeeds, the order microservice will return success to UI. If payment fails, the order microservice has to rollback the itemCount by calling Inventory microservice.

I know that this is a typical Saga based pattern and can be achieved using messaging bus. But all the microservices in this case are capable of only handling API calls. Thinking about other patterns, I am not sure this scenario fits into a state pattern .

Note: For the sake of example, I have used Order,Payment and Inventory microservices. But typically my question is about orchestrating sequence of API calls without excessive if-else. Failure of one of the API call should rollback the other API call by calling appropriate API (eg: If PATCH call succeeds on service A , but not on service B, then the PATCH call on service A has to be rolled back on Service A)

mardi 8 février 2022

Trying to identify a design pattern or strategy used to isolate, utilize, and manage database connections

I ran into some code and I wanted to research other people's approaches to it, but I'm not sure what the design pattern is called. I tried searching for "database executer" and mostly got results about Java's Executor framework which is unrelated.

The pattern I'm trying to identify uses a single class to manage connections and execute queries through the use of functions that allow you to isolate any issues related to connection management.

Example:

// Service class

public Service {
  private final Executor executor;

  public void query(String query) {
    ResultSet rs = (ResultSet) executor.execute((connection) -> {
      Statement st = connection.createStatement();
      return st.executeQuery(query);
    });
  }
}

// Executer class

public Executer {
  private final DataSource dataSource;

  public Object execute(Function function) {
    Connection connection = dataSource.getConnection();
    try {
      return function(connection);
    } catch(Exception e) {
      log...
    } finally {
      // close or return connection to pool
    }
  }
}

As you can see from above, if you ever have a connection leak you don't need to search through a bunch of DAOs or services, it's all contained in a single executor class. Any idea what this strategy or design pattern is called? Anyone see this before or know of open source projects that utilize this strategy/pattern?

REST API resource naming suffix

Our project came into discussion about URI pattern for Rest API.

The basic idea is a better description / readability of the endpoints themselves, by adding CRUD elements practically as a suffix in the endpoint name.

  • CRUD as /api/.../create, /api/.../read, /api/.../update and /api/.../delete endpoint pattern

So, examples (different examples without consistency for one project):

- GET    /api/v1/endpoint-names/read
- GET    /api/v1/endpoint-names/read/{id}
- GET    /api/v1/endpoint-names/read-paginated/{pageId}
- POST   /api/v1/endpoint-names/create
- PUT    /api/v1/endpoint-names/update-by-id/{id}
- DELETE /api/v1/endpoint-names/delete/{id}

I am aware of some recommendations, but I am interested in additional naming conventions / suggestions for web services with more complicated URI structures.

Or there is no real need for something like this?

lundi 7 février 2022

Best practice around request body of Rest API

I just wanted to create a Rest API. But I'm confused with the request format. As per the current requirement, my API is needing an array of objects as input. Eg. [{'key':'value'},{'key':'value'},{'key':'value'}]

But I'm thinking to have it like

{
  'key':[{'key':'value'},{'key':'value'},{'key':'value'}]
}

Can someone help me with, what is the best practice for having the request format(Array of objects or wrapper around an array of objects).

Design Pattern Factory Method question - why the factory method in ConcreteCreator won't be available yet?

I am reading "Design Patterns" by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. In chapter of factory method, there's one paragraph:

"Factory method in C++ are always virtual functions and are often pure virtual. Just be careful not to call factory methods in the Creator's constructor - the factory method in the ConcreteCreator won't be available yet."

I don't understand why the factory method in ConcreteCreator won't be available yet? is it because C++ is a compiled language therefore the method of the children class won't be available as the parent class is compiled first? Thank you.

How to implement scenario in RabbitMq or any other queue

I have a scenario for which I am trying to figure out how to implement this queue architecture. I was looking into using RabbitMQ but am open to other queue solutions if they are better for the following scenario.

We upload a file from the frontend to the backend. The backend processes (uploads) the file to S3. I plan on creating a message and insert it into a queue that we need to process file ABC.csv. This file contains products that we will need to fetch information on from certain API’s.

The APIs have a rate limit/throttling. Therefore we cannot send all messages together.

Each client (user) provides us with an API key to use. For example, say we need to send emails on behalf of client using send grid. So the client provides us their API and we send out emails on behalf of them. But the issue is Sendgrid has rate limit so we cannot blast those calls.

Now that being said. The csv will have each line as a user to send email to. The csv May gave 50k lines.

The issue I am running into is. If I create a message for each row, then all of User 1 messages will be in front of queue with rate limit for its api key. When user 2 comes, their messages will be behind User 1’s and therefore until user 1’s msgs are not all sent the consumer will not be able to send user 2’s messages.

Question: how can setup queue archetype such that we handle the rate limit set by Sendgrid for each user’s api key and are still able process next user’s messages as they come in, instead of making them wait until the first user’s messages are sent.

Creating a pattern with forward slash and backslash in C++ from an Input Sequence

I'm trying to do a college project where I use C++ to develop something similar to a star pattern. I need help fixing my code. My current one is an attempt to make this pattern upside-down which I also don't know how to invert. Due date: 2/11/22.

This is the original instructions.

 Write a program  that follows the pattern demonstrated with sample input and output below the numbers in the sequence correlate to a column of /s in odd # columns and \s in even columns.

Sample input:
1 1 3 1 2 3 5 2 1 2 2 3 7 2 3 1 2 1 3 5 2 3 1 2 5 7 3 1 3 4 2 5 3 2 4 4 1 2 1 3 3 2 1 2

Sample output:

                                             o                                                                       
                                            /|\                                                                      
                                            < >                                                                      
                                            / \                                                                      
                                           /   \                                                                     
                                        /\/     \              /\                                                    
                                     /\/         \  /\        /  \                                                   
                                /\  /             \/  \      /    \          /\                                      
                               /  \/                   \/\  /      \        /  \                                     
                              /                           \/        \    /\/    \  /\            /\                  
               /\            /                                       \  /        \/  \          /  \                 
              /  \/\  /\    /                                         \/              \    /\  /    \                
       /\    /      \/  \  /                                                           \  /  \/      \/\             
    /\/  \  /            \/                                                             \/              \/\    /\    
   /      \/                                                                                               \  /  \/\ 
/\/                                                                                                         \/      \

This is the code I tried so far. Code:

#include <iostream>
using namespace std;

//Array to print the slashes to create the pattern
void patternPrint(int n)
{
    for (int i = 0; i < n; i++) //For loop to create the pattern upside down
    {
        for (int j = 0; j <= i; j++) {
            if (j % 2 == 0)
            {
                cout << "\\" + "\n" + "  "; //on each next even column there will be 2 spaces + breakline for diagonal line
            }
            else
            {
                cout << "/" + "\n"; //on each next odd column there will be 2 spaces + breakline for diagonal line
            }

            cout << endl;
        }
    }
}

int main()
{
    int rows;
    int patternsize;

    cout << "Please choose how many rows you want your pattern to have";
    cin >> rows;
    cout << "Please enter a sequence of numbers to create your pattern. It will be alternating / and '\'s. Seperate each # with the enter key: ";
    int *array = new int[rows];
    for (int i = 0; i <= rows; i++)
    {
        std::cin >> array[i];
    }
   
    patternsize = sizeof(array)/sizeof(array[0]);
    cout << "Your pattern's amount of rows is = " << patternsize;
   
    patternPrint(patternsize);
   
    delete (array);
    return 0;
}

Implementing MVC design pattern in a real project JAVA Swing

I'm learning about design patterns and trying to implement the MVC design pattern in an old project. I can't really find actual project tutorials so I thought I would share my code here and ask for your guidance.

//import java.beans.Statement;
import java.sql.Connection;
import java.sql.*;


public class Home extends javax.swing.JFrame {
    
    public Home() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        upPanel = new javax.swing.JPanel();
        lblHome = new javax.swing.JLabel();
        midPanel = new javax.swing.JPanel();
        sPane = new javax.swing.JScrollPane();
        dataTbl = new javax.swing.JTable();
        tfSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();
        btnAddCon = new javax.swing.JButton();
        btnEditCon = new javax.swing.JButton();
        btnDelCon = new javax.swing.JButton();
        lblContacts = new javax.swing.JLabel();
        btnGroups = new javax.swing.JButton();
        botPanel = new javax.swing.JPanel();
        credTxt = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Iris");
        setBackground(new java.awt.Color(255, 250, 250));
        setResizable(false);
        setSize(new java.awt.Dimension(1000, 600));

        upPanel.setBackground(new java.awt.Color(0, 156, 255));
        upPanel.setForeground(new java.awt.Color(255, 250, 250));
        upPanel.setPreferredSize(new java.awt.Dimension(1319, 100));

        lblHome.setBackground(new java.awt.Color(0, 156, 255));
        lblHome.setFont(new java.awt.Font("sansserif", 0, 36)); // NOI18N
        lblHome.setForeground(new java.awt.Color(255, 250, 250));
        lblHome.setText("Contacts");

        javax.swing.GroupLayout upPanelLayout = new javax.swing.GroupLayout(upPanel);
        upPanel.setLayout(upPanelLayout);
        upPanelLayout.setHorizontalGroup(
            upPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(upPanelLayout.createSequentialGroup()
                .addGap(570, 570, 570)
                .addComponent(lblHome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(632, 632, 632))
        );
        upPanelLayout.setVerticalGroup(
            upPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(upPanelLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(lblHome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(60, 60, 60))
        );

        getContentPane().add(upPanel, java.awt.BorderLayout.PAGE_START);

        midPanel.setBackground(new java.awt.Color(255, 250, 250));

        sPane.setBackground(new java.awt.Color(255, 250, 250));
        sPane.setName(""); // NOI18N

        dataTbl.setBackground(new java.awt.Color(248, 248, 255));
        dataTbl.setForeground(new java.awt.Color(0, 156, 255));
        dataTbl.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        sPane.setViewportView(dataTbl);

        tfSearch.setBackground(new java.awt.Color(248, 248, 255));
        tfSearch.setFont(new java.awt.Font("sansserif", 0, 14)); // NOI18N
        tfSearch.setForeground(new java.awt.Color(51, 51, 51));
        tfSearch.setToolTipText("Search by contact info ");
        tfSearch.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        tfSearch.setSelectionColor(new java.awt.Color(0, 156, 255));
        tfSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfSearchActionPerformed(evt);
            }
        });

        btnSearch.setBackground(new java.awt.Color(0, 156, 255));
        btnSearch.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
        btnSearch.setForeground(new java.awt.Color(255, 250, 250));
        btnSearch.setText("Search");
        btnSearch.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnRefresh.setBackground(new java.awt.Color(218, 165, 32));
        btnRefresh.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        btnRefresh.setForeground(new java.awt.Color(255, 250, 250));
        btnRefresh.setText("Refresh");
        btnRefresh.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        btnAddCon.setBackground(new java.awt.Color(40, 155, 15));
        btnAddCon.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
        btnAddCon.setForeground(new java.awt.Color(255, 250, 250));
        btnAddCon.setText("Add");
        btnAddCon.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnAddCon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddConActionPerformed(evt);
            }
        });

        btnEditCon.setBackground(new java.awt.Color(0, 156, 255));
        btnEditCon.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
        btnEditCon.setForeground(new java.awt.Color(255, 250, 250));
        btnEditCon.setText("Edit");
        btnEditCon.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnEditCon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditConActionPerformed(evt);
            }
        });

        btnDelCon.setBackground(new java.awt.Color(195, 5, 5));
        btnDelCon.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N
        btnDelCon.setForeground(new java.awt.Color(255, 250, 250));
        btnDelCon.setText("Delete");
        btnDelCon.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        lblContacts.setBackground(new java.awt.Color(255, 250, 250));
        lblContacts.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
        lblContacts.setForeground(new java.awt.Color(0, 156, 255));
        lblContacts.setText("Contacts:");

        btnGroups.setBackground(new java.awt.Color(0, 156, 255));
        btnGroups.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        btnGroups.setForeground(new java.awt.Color(255, 250, 250));
        btnGroups.setText("Groups");
        btnGroups.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnGroups.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGroupsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout midPanelLayout = new javax.swing.GroupLayout(midPanel);
        midPanel.setLayout(midPanelLayout);
        midPanelLayout.setHorizontalGroup(
            midPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(midPanelLayout.createSequentialGroup()
                .addGap(161, 161, 161)
                .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSearch)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnRefresh)
                .addGap(55, 55, 55)
                .addComponent(btnGroups)
                .addGap(85, 85, 85))
            .addComponent(sPane, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(midPanelLayout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(midPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(midPanelLayout.createSequentialGroup()
                        .addComponent(btnAddCon)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEditCon)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelCon))
                    .addComponent(lblContacts))
                .addGap(90, 1058, Short.MAX_VALUE))
        );
        midPanelLayout.setVerticalGroup(
            midPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, midPanelLayout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addGroup(midPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch)
                    .addComponent(btnRefresh)
                    .addComponent(btnGroups))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
                .addComponent(sPane, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblContacts)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(midPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDelCon)
                    .addComponent(btnEditCon)
                    .addComponent(btnAddCon))
                .addGap(12, 12, 12))
        );

        sPane.getAccessibleContext().setAccessibleName("");

        getContentPane().add(midPanel, java.awt.BorderLayout.CENTER);

        botPanel.setBackground(new java.awt.Color(0, 156, 255));
        botPanel.setForeground(new java.awt.Color(255, 250, 250));
        botPanel.setToolTipText("");
        botPanel.setPreferredSize(new java.awt.Dimension(1319, 60));

        credTxt.setEditable(false);
        credTxt.setBackground(new java.awt.Color(0, 156, 255));
        credTxt.setFont(new java.awt.Font("sansserif", 3, 12)); // NOI18N
        credTxt.setForeground(new java.awt.Color(255, 250, 250));
        credTxt.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        credTxt.setText("Iris - Developed by Bachar Sabra and Charbel El-Khoury.");
        credTxt.setBorder(null);
        credTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                credTxtActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout botPanelLayout = new javax.swing.GroupLayout(botPanel);
        botPanel.setLayout(botPanelLayout);
        botPanelLayout.setHorizontalGroup(
            botPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(botPanelLayout.createSequentialGroup()
                .addGap(402, 402, 402)
                .addComponent(credTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 513, Short.MAX_VALUE)
                .addGap(428, 428, 428))
        );
        botPanelLayout.setVerticalGroup(
            botPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(botPanelLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(credTxt)
                .addGap(30, 30, 30))
        );

        getContentPane().add(botPanel, java.awt.BorderLayout.PAGE_END);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void tfSearchActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void credTxtActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnAddConActionPerformed(java.awt.event.ActionEvent evt) {                                          
        AddContact addContact = new AddContact();
        
        addContact.setVisible(true);
        addContact.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }                                         

    private void btnEditConActionPerformed(java.awt.event.ActionEvent evt) {                                           
        EditContact editContact = new EditContact();
        
        editContact.setVisible(true);
        editContact.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }                                          

    private void btnGroupsActionPerformed(java.awt.event.ActionEvent evt) {                                          
        Groups groups = new Groups();
        
        groups.setVisible(true);
        groups.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dispose();
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        getContacts();
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Home().setVisible(true);
            }
        });
    }



    public static void getContacts() {
        try {
            Connection conn = null;
            Statement stmt = null;
            conn = JDBCCon.getCon();
            stmt = (Statement) conn.createStatement();
            ResultSet myRs;
            myRs = stmt.executeQuery("SELECT * FROM `contacts` ;");
            while (myRs.next()) {
            System.out.println("working in main");
            System.out.println(myRs.getString("Last_Name") + ", " + myRs.getString("First_Name"));
            }

        } catch (Exception e) {
            System.out.println("Error in getContacts function : "+ e);
        }
    }


    private void searchContacts() {
        String seach = tfSearch.getText();
        try {
            Connection conn = null;
            Statement stmt = null;
            conn = JDBCCon.getCon();
            stmt = (Statement) conn.createStatement();
            ResultSet myRs;
            myRs = stmt.executeQuery("SELECT * FROM `conatcts` WHERE First_Name = '"+seach+"' OR Last_Name = "+seach+" ;");
            if (myRs.next() != false) {
                System.out.println("no groups found");
            }else{
                System.out.println("groups ");
            }

        } catch (Exception e) {
            System.out.println("Error in searchGroups function : "+ e);
        }

    }


    // Variables declaration - do not modify                     
    private javax.swing.JPanel botPanel;
    private javax.swing.JButton btnAddCon;
    private javax.swing.JButton btnDelCon;
    private javax.swing.JButton btnEditCon;
    private javax.swing.JButton btnGroups;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnSearch;
    private javax.swing.JTextField credTxt;
    private javax.swing.JTable dataTbl;
    private javax.swing.JLabel lblContacts;
    private javax.swing.JLabel lblHome;
    private javax.swing.JPanel midPanel;
    private javax.swing.JScrollPane sPane;
    private javax.swing.JTextField tfSearch;
    private javax.swing.JPanel upPanel;
    // End of variables declaration                   

}

From what I understand it goes View for design like JFrames, Buttons, Pannels etc...Controller for ActionEvents and maybe constructers, setters and getters and Model for the main class and maybe database connection and queries.