dimanche 31 mai 2020

How to print a star right triangle in java?

I want to print this in java.

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

I have already written this code

class star1
{
    public static void main(String[] args)
    {
        for (int i=0; i<5; i++)
        {
            for (int j=0;j<=i;j++)
            {
                System.out.println("* ");
            }
            System.out.println( );
        }
    }
}

But it does not seem to work

Implement strategy pattern with enum

I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}

somewhere in the client:

user.setPay(Pay.CREDITCARD);
user.pay();

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}

somewhere in the client:

if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

How to Copy the fill pattern of a cell to a shape?

I have been writing a code that is copying the color of the cell and pasting it to the relevant shape. I am able to copy the color. However, it seems more complicated to copy the fill pattern of the cell. The problem i have faced is that the pattern parameter of a cell is, for example, "xlLightHorizontal" and the same pattern for a shape is "msoPatternNarrowHorizontal". Both draw the same fill pattern but have different names.

How i copy the color and fill pattern of the cell:

modelText(3, 1) = Sheets("Orders").Cells(row, j + 1).Interior.Color
modelText(3, 2) = Sheets("Orders").Cells(row, j + 1).Interior.Pattern
modelText(3, 3) = Sheets("Orders").Cells(row, j + 1).Interior.PatternColor

How i assign the color and the fill pattern to the shape:

 With Selection.ShapeRange.Fill
        .ForeColor.RGB = modelText(3, 1)
        .BackColor.RGB = modelText(3, 3)
        .Patterned (msoPatternLightHorizontal)
 End With

Note that:

Cells(row, j + 1).Interior.Pattern returns xlLightHorizontal

Where

ShapeRange.Fill.Patterned does not accept xlLightHorizontal as an input parameter

Is there anyway that you know to copy the fill pattern of a cell to a shape?

samedi 30 mai 2020

How to work with multiple shared libraries in jenkins?

Sharing a design issue using jenkins!

I have a project in which I have to use multiple libraries. Multiple Libraries in the sense Project consists of multiple services. and to install the project we have different mechanism to call there are few non standard ansible calls maintained by other team which we have to utilize, basically 20 services leads to 20 different architecture call. They can be in any version which can support any version maintained by different team so as the same we have to think, My question is how we can design the architecture which will do installation of project so code reusability is at the maximum and maintainence with coupling is at minimum, How beautifully we can design this problem?

Considering the limitation of jenkins: we can not keep the same filename in the jenkins shared library src folder. we can not keep the same filename in vars folder as well because the first one will load others wouldn't load. (correct me If I am wrong anywhere) Ref: https://www.jenkins.io/doc/book/pipeline/shared-libraries/

Current Architecture which I have thought of is (It is better not to read current architecture because you might need fresh mind to resolve this)

1 main jenkins file which will load all shared libraries 
1 main shared libraries which will act as parent to all shared libraries
In all 20 shared libraries "all_stages" are written which will create the map which have objects of stages and this map is stored in 1 main common file resides in parent shared library which will have the workflow implementation inside it.
We will pass a yaml stage parameters to this project which stage we have to pick from combined all stages. using this feature we can control the workflow.

Please Do let me know if I am not clear anywhere I will give more details for the same right now It will be difficult to mention the complete project here itself.

Should I build the object in the constructor?

I have a class called book consists off the book name and List of chapters. I read the information about the chapters ( such as the chapters name, chapter number ... etc) from some txt file on the hard desktop.

The book object itself is meaningless without loading the chapters. For best practices, should I write a build method and I build my object like the below ?

Book newBook = new Book(bookName).build();

Where build has the logic of loading the file form hard disk and filling the chapters list, or I should just make this build method private and create an object like the below.

Book newBook = new Book(bookName);

and inside the constructor of the book I should call the private method called build ?

What are some disadvantages of the GoF Flyweight design pattern

I understand the benefits of the flyweight design pattern, but I am unsure of its exact drawback. For example, I understand that it may be break encapsulation, but that is all I can currently think of, what are some possible drawbacks of the flyweight design pattern, there is very little documentation, on this matter.

Architecture issue re best IPC method for multiple file descriptors in one process

This is question about architecture in an application that uses POSIX IPC to communicate between threads. The application uses multiple threads (clients) to send data to a single receiving (server) thread. Each thread is assigned to a separate core using its affinity mask. The threads are all within a single process - no process boundaries to cross.

Currently I use a named pipe (FIFO) to communicate between the multiple writer threads and the single reader thread. The writers all use the same file descriptor and the reader reads from a single pipe.

However, the data must be processed in core (thread) order, with core 0 first, then core 1, then core 2, etc. With only a single pipe the application must organize the incoming messages in core order which adds extra processing overhead. The messages are added to a memory buffer maintained by the server side.

A better architecture from the standpoint of the reader (server) would be to use a separate pipe/socket/shared memory (or other IPC method) for each client. The server would read from each of the client file descriptors in core order, processing each record as it comes in, then read and process data from the next core, in a round-robin fashion. That way the server does not need to organize and process the records in core order, which is expensive. The server just receives them one at a time and processes them immediately upon receipt, then reads from the next core in sequence, etc. No expense of a memory buffer or the overhead of organizing the records as they come in.

My question is, given the requirement described above, which of the POSIX IPC methods would be the best and most performant solution for this use case? I'm planning to go up to as many as 64 cores, so I would need up to as many as 63 file descriptors for the client side. I don't need bidirectional commo.

The lowest system overhead would (I think) be an anonymous pipe. The server side could simply loop through an array of file descriptors to read the data. However, I'm not clear whether an anonymous pipe can be used for threads in a single process because, "It is not very useful for a single process to use a pipe to talk to itself. In typical use, a process creates a pipe just before it forks one or more child processes." https://www.gnu.org/software/libc/manual/html_node/Creating-a-Pipe.html#Creating-a-Pipe

I currently use named pipes, which do work with threads in a single process, and which should work with multiple file descriptors.

I have also used UNIX domain datagram sockets with a single socket. My impression is that multiple sockets may be more system overhead than I need for this situation, but they may be the most performant solution.

Finally, I have considered POSIX shared memory, where each client thread has its own shared memory object. Shared memory is often described as the fastest IPC mechanism (https://www.softprayog.in/programming/interprocess-communication-using-posix-shared-memory-in-linux)

But with shared memory, there is the problem of synchronization. While the other IPC methods are basically queues where the data can be read one record at a time, shared memory requires a synchronization object like a semaphore or spinlock. As the man pages say, "Typically, processes must synchronize their access to a shared memory object, using, for example, POSIX semaphores." (https://www.man7.org/linux/man-pages/man7/shm_overview.7.html.) My concern is that the extra synchronization overhead may reduce the usefulness of shared memory in this situation.

Moreover, despite being billed as the fastest method, I am concerned about possible cache contention with shared memory. "[M]any CPUs need fast access to memory and will likely cache memory, which has two complications [access time and data coherence]." https://en.wikipedia.org/wiki/Shared_memory.

So to sum up, my question is: which of the five POSIX IPC methods -- anonymous pipes, FIFOs, UNIX domain datagram sockets, or POSIX shared memory -- works best for writing to one file descriptor per thread on the client side and reading from all client file descriptors in sequence?

Design Pattern for lazy Fingerprint evaluation and comparison

First off, as "Fingerprint" is a rather broad term, this question is not about finger tips nor specifically about Hashing.

So here is the scenario: I'm developing a fingerprint for special types of graphs (won't go into much detail about the the actual data of this fingerprint as it is not relevant) and need to compute a fingerprint that identifies these graphs according to certain features. I have a POD (struct) that holds this fingerprint data. As an example consider this fingerprint:

struct Crossing; //unimportant for the question
struct Fingerprint{
  int nodes;
  vector<vector<bool>> adjacencies;
  vector<Crossing> crossings;
};

This is not my actual fingerprint but rather a much simpler example that (kind of) works for my question.

To compute my fingerprint I have to consider all possible labelings (ways to label nodes) of my graph and the one that yields the "smallest" fingerprint is used to generate the actual fingerprint. Now as some of the members of this struct are much faster to compute than others (and can be used to throw out labelings that definitely don't generate a minimal fingerprint) I have decided to evaluate the members of this struct lazily. For now I have done this as follows:

Fingerprint getFingerprint(Graph graph){
  auto labelings = graph.generateLabelings();//type of labelings not relevant to question
  auto min_labeling = labelings[0]; //labeling yielding minimum fingerprint
  bool first = true;
  bool adjacencies_evaluated = false;
  bool crossings_evaluated = false;
  int min_nodes;
  vector<vector<bool>> min_adjacencies;
  vector<Crossing> min_crossings;
  //note that labeling is only needed to calculate fingerprint but not part of it:
  for(auto& labeling: labelings)
  {
    auto nodes = getNodes(graph, labeling); 
    //yes I know the number of nodes is independent of the labeling but in my case
    //the labeling matters for all parts of the fingerprint (this example isn't perfect)
    if(first)
    {
      min_nodes = nodes;
      first = false;
      continue;
    }
    if(nodes < min_nodes)
    {
      min_nodes = nodes;
      min_labeling = labeling;
      bool adjacencies_evaluated = false;
      bool crossings_evaluated = false;
    }
    else
      if(nodes == min_nodes)
      {
        if(!adjacencies_evaluated)
          min_adjacencies = getAdjacencies(graph, min_labeling);
        auto adjacencies = getAdjacencies(graph, labeling);
        adjacencies_evaluated = true;
        if(adjacencies < min_adjacencies)
        {
          min_adjacencies = adjacencies;
          min_labeling = labeling;
          crossings_evaluated = false;
        }
        else
          if(adjacencies == min_adjacencies)
          {
            if(!crossings_evaluated)
              min_crossings = getCrossings(graph, min_labeling);
            auto crossings = getCrossings(graph, labeling);
            crossings_evaluated = true;
            if(crossings < min_crossings)//comparison operators for UDT are available
            {
              min_crossings = crossings;
              //not necessary to update min_labeling here
            }
          }
      }
  }
  //min_nodes is already evaluated
  if(!adjacencies_evaluated)
    min_adjacencies = getAdjacencies(graph, min_labeling);
  if(!crossings_evaluated)
    min_crossings = getCrossings(graph, min_labeling)

  return Fingerprint{min_nodes, min_adjacencies, min_crossings};
}

I have simplified the fingerprint for this question a lot, but the code to generate it is still rather large and most importantly repetitive. The basic idea is to evaluate the first parts of the fingerprint, check if they are sufficient for a comparison, and if not to compute more parts of it. And once the minimum labeling is found the not evaluated parts of the fingerprint are set.

Now my question is, if there is a way to generalize the above idea, so that if I ever change my fingerprint not much has to be changed in this function.

My idea would be to provide some kind of container with function-pointers to the functions calculating the members of fingerprint like:

functions = {&getNodes, &getAdjacencies, &getCrossings}

However I'm not sure how to actually store this to

  1. be able to access them like functions[i](graph, labeling) and iterate over them
  2. have the compiler know which element returns which type

On top of that, later in the process I would need to store the return values in the right fingerprint members. In C++ without reflection this approach seems impossible to me, so is there a way to do this (or any other way) to generalize my fingerprint computation?

Design pattern - Filter list of objects through various steps and finally select one object

I have list of objects in database now they are filtered at various steps depends of conditions and then finally select one object from the list and return. Here are Steps

  1. Get a list of objects based on input request from database
  2. Filter some objects based on business rules
  3. Call external HTTP services for each object and set properties of object based on response
  4. Filter the list based on properties set in step 3 and business rules
  5. Call external another HTTP services for each list from step 4 and set properties of object based on response
  6. Get one object base on populated list in step 5 and business rules

Now based on input we don't require some steps like if input value is "1" do step 1,5,6 like if input value is "2" do step 1,2,3,4,5,6 like if input value is "3" do step 1,2,5,6 etc

Which patter should i use here

Why is a Factory Design Pattern recommended? (over simply using an object in JS)

Currently learning about design patterns in JavaScript in this course, I began questioning the use-case of the Factory Design Pattern.

For example, the following is some code that's a Factory Design Pattern for repositories:

const util = require('util')

const Repos = function() {
    // We are creating a copy of this function constructor (not sure what that means).
    let repos = this
    console.log('before' + util.inspect(this, {showHidden: false, depth: null}))

    let repoList = [
        {name: 'Task', source: './taskRepository'},
        {name: 'Project', source: './projectRepository'},
        {name: 'User', source: './userRepository'},
    ]

    for (const repo of repoList){
        repos[repo.name] = require(repo.source)()
    }

    console.log('after' + util.inspect(this, {showHidden: false, depth: null}))
}

While it's nice and clean code, I am questioning, why cannot we just an object, like the following:

const RepoObject2 = {
    Task: require('./taskRepository')(),
    Project: require('./projectRepository')(),
    User: require('./userRepository')(),
}

Appreciate any responses, thanks!

Conceptual example of State Design Pattern in C#

I am currently studying the state Design Pattern and I think I pretty clear about how it works. I was looking at a conceptual example which I have posted below. There is just one part of the code that I don't quite understand.

using System;

namespace BranchingDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.ReadLine();
        }


    }
    // State Interface
    interface IAccountState
    {
        IAccountState Deposit(Action addToBalance);
        IAccountState Withdraw(Action subtractFromBalance);
        IAccountState Freeze();
        IAccountState HolderVerified();
        IAccountState Close();
    }

    //Context
    class Account
    {
        public decimal Balance { get; private set; }


        private IAccountState State { get; set; }

        public Account(Action onUnfreeze)
        {
            this.State = new NotVerified(onUnfreeze);
        }

        public void Deposit(decimal amount)
        {
            this.State = this.State.Deposit(() => { this.Balance += amount; });
        }

        public void Withdraw(decimal amount)
        {
            this.State = this.State.Withdraw(() => { this.Balance -= amount; });
        }

        public void HolderVerified()
        {
            this.State = this.State.HolderVerified();
        }

        public void Close()
        {
            this.State = this.State.Close();
        }

        public void Freeze()
        {
            this.State = this.State.Freeze();
        }

    }
    //Concrete State
    class Active : IAccountState
    {
        private Action OnUnfreeze { get; }

        public Active(Action onUnfreeze)
        {
            this.OnUnfreeze = onUnfreeze;
        }

        public IAccountState Deposit(Action addToBalance)
        {
            addToBalance();
            return this;
        }

        public IAccountState Withdraw(Action subtractFromBalance)
        {
            subtractFromBalance();
            return this;
        }

        public IAccountState Freeze() => new Frozen(this.OnUnfreeze);
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => new Closed();
    }

    //Concrete State

    class Closed : IAccountState
    {
        public IAccountState Deposit(Action addToBalance) => this;
        public IAccountState Withdraw(Action subtractFromBalance) => this;
        public IAccountState Freeze() => this;
        public IAccountState HolderVerified() => this;
        public IAccountState Close() => this;
    }
}

In the concrete class Active there is property of type action delegate which is passed as a parameter in its constructor. Also in the constructor of the context class a delegate of type action is passed as a parameter. Now conceptually I understand this is done as this provides a backreference to the Context object (Account),with the State i.e. closed or Active. This backreference can be used by States to transition the Context to another State. My first question is why a delegate was used?

However I was trying to get the code to run and debug to illustrate what was happening. Therefore my question is in the code how do I need initialize a new Account? Accounts begin with a NotVerified state. I tried this code.

Action initialState = () => { };
            Account account= new Account(initialState);

If I then want to determine the state of the account how do I code that?

vendredi 29 mai 2020

Atomic Use Case: input as new object or object's attributes

Consider the object Customer, which has two attributes customerID and phone, both are String type, and some objects are already stored in a given list, where both attributes must be unique. When designing the UML diagram for atomic use case, what should I choose between the following:

addCustomer(customer: Customer), or
addCustomer(customerID: String, phone: String)

The precondition is to verify if the new customer does not exist in the (already given) list. If choose the former, I can use customer1.equals(customer2), and the latter I have to check both parameters for each Customer in the list, which is longer.

How to design this synchronization pattern in Laravel

I have the following patterns in PHP and I would like to implement it in order to take advantage of the service provider and dependency injection process in laravel.

enter image description here

Explanations :

I'm building a synchronization app and I want it to be very flexible in order to add others platforms in the future. To do so, I have platforms that are implementing and extending interfaces and abstract classes. As the synchronization process doesn't depend on how data are retrieved and pushed then I'm just using the interface "iPlatform" to access to DataPusher and DataRetriever implementations.

All my concrete classes are singleton (platformA, DataPusherA, DataRetrieverA... same for B). "PlatformB" and "PlatformA" are implementing static methods to access to DataRetreiver and DataPusher instances for each platforms.

I thought about contextual Binding to replace these Platform A and B (which are kind of accessors to concrete methods in DataPusherA/RetrieverA and B actually). But I still have some difficulties to understand how to take advantage of the laravel framework to correctly implement that schema.

I'm open to any suggestions to change that schema (if I'm wrong about the pattern used) or if you have some advice to implement it. Thank you very much for your help.

Ps: Sorry if I made some English mistakes, it's not my natural language.

Repository pattern using information from other repositories

I am trying to understand what is the proper approach when the objects generated from a Repository have a reference to objects which are responsible for another Repository.

Let's say I have terminals which can have a list of possible quantities assigned and each quantity has a type. In this case I have 3 repositories TerminalsRepository, QuantitiesRepository, and QuantityTypeRepositories.

How should I populate the quantities information for the terminals and the type information for the quantities? Should the repositories use internally the other repositories or is there a better way to achieve that (for example a service method is retrieving the terminals and then populating the needed data)?

Can someone explain the code using the Mediator pattern or Bridge pattern?

Can someone explain the following code using the Mediator pattern or Bridge pattern?

public interface Relay {
  public void send(String m, User u);
}

...

public abstract User{
  private Relay relay;
  public User(Relay r) {
    relay = r;
  }

  public void send(String message) {
    relay.send(message, this);
  }
...
  public abstract void receive(String message);
}

...

public class ApplicationRelay implements Relay {
  private ArrayList<User> users;
  public ApplicationRelay() {
    users = new ArrayList<User>();
  }

  ...

  public void send(String m, User originator) {
    for(User user: users) {
      if(user != originator) {
        user.receive(m);
      }
    }
  }
}

  1. As for my view, the reason for using the Bridge pattern is: The Bridge pattern was designed in the code, which is one of kinds of structural pattern. Because, it decouples the functional abstraction from the implementation so that the two are independently. In the case, the interface Relay acts as the bridge for the abstract User. The class ApplicationRelay implements relay and it’s independent of the functional abstraction. I'm not sure it's correct for using the bridge pattern.Can some one give me some answer?

  2. I don't really understand how use the mediator pattern in the code. The defination of mediator pattern is that the mediator pattern uses a mediation object to encapsulate the interaction of a series of objects to avoid objects explicitly refer to each other and reduce the coupling between objects . However, in this case, I cannot find the madiator in the codes and it seems that no interaction between the objects. Is the madiator is the ApplicationRelay? Can someone gives me some explaination?

whether the codes use the Proxy pattern or singleton pattern?

I'm not sure the following code using the Proxy pattern or Singleton pattern?

public interface SomeObject {
    void process();
}

public class SomeObjectImpl implements SomeObject {

    public SomeObjectImpl() {
        ...
    }

    @Override
    public void process() {
        ...
    }
}

public class AnotherObject implements SomeObject {
    private SomeObject object;

    @Override
    public void process() {
        if (object == null) {
            object = new SomeObjectImpl();
        }
        object.process();
    }
}

The reasons for me to use the singleton pattern is: The singleton pattern was used in the codes cause it defines that a class must ensure that only a single instance should be created and a single object can be used by all other classes. In the case, when the parent interface object is null, we create an instance of Same-Object when it required.

As for the Proxy pattern, it seems that the someObject is the proxy. But I'm really confused that both the two patterns are correct or only the proxy pattern is correct? Thanks.

I'm not sure these code using the composite pattern or template pattern?

I'm not sure the following code use the composite pattern or template pattern. Or both of them are true.

public class Employee {
    ...
}
public class Manager extends Employee {
    private List<Employee> subordinates;
    public Manager(List<Employee> subordinates) {
        this.subordinates = subordinates;
    }
    public List<Employee> getSubordinates() {
        return this.subordinates;
    }
}

The reasons for using the template pattern is: The code was used by the Template pattern which belongs to the behavior patterns. Because the definition of the pattern is the skeleton of a function in an operation, deferring some steps to its subclasses. In the example, the class emplyee is the skeleton and the manager extends the emplyee. However, other friends prefer to use the composite pattern.

I'm not sure which one is correct. Can you give me some explain explaination? Thanks!

What would be the correct design pattern to use

So I have a Generator interface:

public interface Generator
{
    public Generator getInstance(); (The problem is here - methods in interface can't be static)
    public Account generate() throws WalletInitializationException;
}

And 2 other classes which implements the interface.

Now I'd like to have a GeneratorFactory class that receives the class Class object, invokes the getInstance() method and returns the class object.

Something like this:

public class GeneratorFactory
{
    private GeneratorFactory()
    {
    }

    public static Generator getGenerator(Class<Generator> generatorClass)
    {
        return (Generator) generatorClass.getMethod("getInstance", null).invoke((Need to have instance) null, null); (Should be runtime error)
    }
}

But since the getInstance() method is an instance method and not a static method, I can't call invoke() with a null parameter for the instance.

I thought of doing an abstract class of a Factory which contains a getInstance() method and an abstract generate() method for the generators class to implement it, will that be the correct approach?

Design Pattern for the Database of a Marketplace App

we are building a marketplace with Flutter + Firebase (Auth, Firestore) for iOS and Android. From the functionality there are similarities to products like Uber and AirBNB.

I'm looking for a design patterns for Firestore (in combination with Auth) to hold the DB safe (private area and public marketplace), easy to maintain (cloud functions) and inexpensive (minimization of read/writes). I have some own approaches but believe that this use case occurs so often that there have to be great templates.

Does any of you have information sources on this topic for me? Or maybe someone of you has already set up such a project and can give me a rough description of how the database was structured?

Thank you, Martin

CoR vs simple if else and matrix based functional calls where the chain is request dependent

Scenario

I have used Handlers mapping along with if else conditional construct to handle chains which are request dependent.

Request r(TYPE1, ACTIVE);
std::vector<TYPE, STATUS> mapping;
mapping[TYPE1][PENDING] = myHandlerA();
// ... and so on
mapping[r.type()][r.status()]();

void myHandlerA(Request& r) {
  if(condition4(r))
  Handler4(r);

  else if(condition5(r))
  Handler5(r);

  else if(condition6(r))
  Handler6(r);

  else if(condition7(r))
  Handler7()
}
  1. How do I do it using CoR when the chain is dependent on the request ? Is my approach a good design ?
  2. Is this case applicable to CoR ? Can someone provide a snippet, if yes.
  3. How does one identify applicability of CoR vs a simple mapping based coupled with if else ?

jeudi 28 mai 2020

Find a best practice for Business Intelligent data processing

I'm working in a system that manages human resources and it has a BI (Business Intelligent) part to collect and process data from main system, then visualize processed data into charts, tables, ..

For example, we want to see the relation between person age [in range 18 - 38] (in axis 1) and their monthly salary (in axis 2) [in full salary range]. The aggregation value is counting in person. There is also an additional step called Filter, to filter the result only in the organization A.

The expected result is like this:

                 Age_18<28   Age_28<38 Age_38<48
Salary_<1000         12          25       45
Salary_1000<5000     12          10       2
Salary_>5000         1           1        2

The current processing steps are as below:

  1. Search for axis1: Search all people with age range [18-38] in organization A
  2. Search for axis2: Seach all people in in organization A
  3. Merge results for axis1 and axis 2
  4. Counting people for each condition, for example number of people that has Age_18<28 AND Salary_<1000 is 12, and so on.
  5. Convert to json response

Because there are a lot of cases to handle, the logic becomes complicated to maintain. All steps are handled manually like above.

So I just wonder if this is a common problem and should have a common way to handle, For example a design pattern, or algorithm, or library (Java) or a specific concept to handle such things that I never know before.

Target: - make code more simple, readable and maintainable - easy to extend, i.e add new cases

What I'm about to try: - Apply chain of responsibility + strategy patterns

Identify an Object by property or type

I have a question regarding the design pattern in java.

I have a class named Bottle. Now, I have two kinds of Bottle: glass bottle, and metal bottle.

Which of the following design patterns should I use: 1. Set type of bottle as its property

    class Bottle {
        public enum BottleType { GLASS, METAL }

        BottleType type;
    }
  1. Use inheritance
    abstract class Bottle {
    }

    class GlassBottle extends Bottle {
    }

    class MetalBotle extends Bottle {
    }

Update my question Bottle will be processed by a processor named BottleProcessor

    class BottleProcessor {
        public static breakBottle(Bottle _bottle) {
            //TODO: break bottle
            if _bottle is glass bottle 
                breakGlassBottle()
            else if _bottle is metal bottle 
                breakMetalBottle()
        }
    }

What is the correct hierarchy for state in Redux-saga?

I don't know which this question is insignificant but it is quite confusing for me right now.

I have a state, which will be used as params to make API call. So I assume this state, aka API Object, should be one-one mapping to backend API. However, if I change one value of of API Object, say state.api.A, it will affect available values for another field, say availableB. These available values can be computed purely or fetched remotely.

So here I will have two choices: 1) to separate availableB from API Object, or 2) to store every availableB inside API Object.

Method 1) cons: change to any field of API Object should be an effect otherwise I have to dispatch two reducers for one change.

Method 2) cons: I have to remember removing Assistant Object before I make API calls.

enter image description here

Which one is the correct practice or this question is totally something about over designed?

Which design pattern to use when we have classes that does similar high level functionality but the returns different types in methods?

I have an existing C# console application that takes arguments and based on the arguments creates an instance of markets (UK, US, MX..) using dependency injection.

Each market class does a 'string GetData()', 'string ProcessData()' and 'bool ExportData()'.

The application was initially created for one eCommerce vendor's markets. Now I am told to modify it for a different vendor that does a different process. The high-level flow remains the same.

  1. 'GetData' to fetch records from DB,
  2. 'ProcessData' for any transformation or the likes
  3. 'ExportData'.

The difference is Getdata() pulls records from DB and maps to an object. I am planning to use Petapoco. 'ProcessData' might return a similar class. 'Exportdata' currently does an API call but for the new vendor, I have to write to a file.

I was reading up on patterns I am totally confused. At first, I thought I needed abstract factory pattern and now I think the factory method is what I should be using but I am not sure if I am doing it right. Need some guidance/review here. A sample cs file I created from my understanding of factory pattern. This code is based on the headfirst code samples.

using System;
using System.Collections.Generic;
using StatusExport.Models;

namespace factorymethod
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientFactory factory = null;
            Console.WriteLine("Enter client code:");
            string clientCode= Console.ReadLine();
            switch (clientCode.ToLower())
            {
                case "costco":
                    factory = new CostcoFactory("accountname", "taskname");
                    break;
                    //NEw vendor might be added
                    //case "walmart"
                    //factory = new WalmartFactory("taskname", "type");
                    //break
                default:
                    break;
            }

            bool status = factory.ProcessData();
            Console.ReadKey();
        }
    }

    abstract class Client
    {
        public abstract string AccountName { get; }
        public abstract string Task { get; set; }
        //More properties might be added. Some may not even be used by some of the new vendors. For example, Costco Might need accountname and task. Tomorrow if walmart comes, they might not need these two or may need task and a new property 'type'
        public abstract List<T> GetData<T>();
        public abstract List<T> ProcessData<T>();
        public abstract bool ExportData();
    }


    class CostcoClient : Client
    {
        public override string AccountName { get; }
        public override string Task { get; set; }

        public CostcoClient(string accountName, string task)
        {
            AccountName = accountName;
            Task = task;
        }

        public override List<DBRecord> GetData<DBRecord>() //DBRecord class is specific to Costco. 
        {
            List<DBRecord> dbresult = new List<DBRecord>();
            //dbresult = db return data mapped to an object DBRecord using petapoco. Another vendor might have a different class to which DB records are mapped. So the return type can be generic
            return asn;
        }

        public override List<T> ProcessData<T>()
        {
            throw new NotImplementedException(); //Any data transformation or business logic. Return type might be DBRecord or a new class altogether
        }

        public override bool ExportData()
        {
            throw new NotImplementedException();//Call API or write data to file and if success send true else false
        }
    }

    abstract class ClientFactory
    {
        public abstract bool ProcessData();
    }


    class CostcoFactory : ClientFactory
    {
        public string AccountName { get; }
        public string Task { get; set; }
        public CostcoFactory(string accountname, string task)
        {
            AccountName = accountname;
            Task = task;
        }

        public override bool ProcessData()
        {
            CostcoClient gc = new CostcoClient(AccountName, Task);
            var result = gc.GetData<DBRecord>();
            return true;
        }
    }
}

Do you think this is the right design approach?

I also want to keep the console project independent of vendor project. So maybe 'StatusExport.Program' for the console application. DLL projects StatusExport.Common to hold the interface and abstract classes' and 'StatusExport.Client(ex:StatusExport.Costco)' for each vendor stuff.

Vim search pattern 'foo' but skip lines containing 'bar' without deleting any line

I want to use search and highlight in vim using pattern match. My first search criteria is to look for a string foo in a line. My second search criteria is to skip all foo if the same line contains bar in it. I don't want to delete all lines containing bar. My first search criteria meets with following:

/foo

My second criteria is not meeting with:

/foo.*\(bar\)\@<!

Example text:

1 foo
2 foo bar xx
3 fooobar
4 bar
5 xxx

(here I want to highlight line numbers 1 only)

What I am missing here?

Reference: http://vimdoc.sourceforge.net/htmldoc/pattern.html

What is the best way to handle both Guest Customer and Logged In Customer in E-Commerce application?

In case of e-commerce application as we all know, user can use application either by login into the application or can use as guest user and can add/remove item to his cart and do checkout.

So my question is what should be the best approach to handle both scenarios for guest and logged in customer. I think about two approaches but not sure whether theses are best or we can use some better approaches other than i mentioned below.

1) Whenever the customer hit the e-commerce application through the web then i will create guest customer and and return to the front-end application and stored in the the local storage of web, so that i can use the same customerId whenever user is doing any change to his cart.

2) As i mentioned in the point 1, i will create the guest customer but instead of just returning the customerId, i will return the JWT token which has the customerId and has another field which mentioning whether it is guest customer or not.

I am using Angular in the front-end and NodeJs in the back-end and for the logged In customer i am using the JWT token.

So i was thinking to use the point 2, so that the logic should be consistent whether it is logged in or not i will rely on the JWT token to pass the information between front-end and back-end.

But i am not sure cons for these approach.Please give your suggestions

mercredi 27 mai 2020

How to match two ordered sequence of numbers by their interval distances

I am trying to match two sequence of numbers(ordered), with their distance,for example:

A={1,3,5,8,10} B={2,5,7,9}

the expect result is:

A'={3,8,10} with interval distance:{5,2} B'={2,7,9} woth interval distance:{5,2}

I am now using the brute-force way, but looking for an elegent method.

design pattern to avoid unnecessary addition of abstract functions to accommodate new functionality

In below code I have abstract class TestAlgModule which I will be exposing to library users and there are several functionalities they can use such as VOLUME, MIXER and so on. However, suppose users need a new function which is added only in MixerManager then I need to add that in TestAlgModule abstract class and now suddenly all the derived class needs to add that without any benefit.

How do I avoid this?

 #include <iostream>                                                                                                                                                                                        
 using namespace std;                                                                                                                                                                                       

 enum {VOLUME, MIXER, UNKNONWN};                                                                                                                                                                            

 class TestAlgModule {                                                                                                                                                                                      
 public:                                                                                                                                                                                                    
     virtual void open(int type) = 0;                                                                                                                                                                       
     virtual void close(int type) = 0;                                                                                                                                                                      
 };                                                                                                                                                                                                         

 class volumeManager : public TestAlgModule                                                                                                                                                                 
 {                                                                                                                                                                                                          
 public:                                                                                                                                                                                                    
     void open(int type) {}                                                                                                                                                                                 
     void close(int type) {}                                                                                                                                                                                
 };                                                                                                                                                                                                         

 class mixerManager : public TestAlgModule                                                                                                                                                                  
 {                                                                                                                                                                                                          
 public:                                                                                                                                                                                                    
     void open(int type) {}                                                                                                                                                                                 
     void close(int type) {}                                                                                                                                                                                
     void differentFunction() {};                                                                                                                                                                           
 };                                                                                                                                                                                                         

 /* users calls this to get algModule and then call functions to get the job done */                                                                                                                                                                                         
 TestAlgModule *getTestAlgModule(int type) {                                                                                                                                                                
     switch(type) {                                                                                                                                                                                         
         case VOLUME:                                                                                                                                                                                       
             return new volumeManager();                                                                                                                                                                    
         case MIXER:                                                                                                                                                                                        
             return new mixerManager();                                                                                                                                                                     
         default:                                                                                                                                                                                           
             break;                                                                                                                                                                                         
     }                                                                                                                                                                                                      
     return nullptr;                                                                                                                                                                                        
 }                                                                                                                                                                                                          

 int main() {                                                                                                                                                                                               
     TestAlgModule * test = getTestAlgModule(MIXER);                                                                                                                                         
     test->open();     
     //test->differentFunction();          this can't be called as it is not part of abstract class and users are exposed only abstract class                                                                                                                                                              
     return 0;                                                                                                                                                                                              
 }                     

If something is not clear please let me know and I will do my best to answer it. I am looking for a better way to do this i.e. change in VolumeManager should be independent of MixerManager.

Avoiding circular dependencies the right way - NestJS

Say I have a StudentService with a method that adds lessons to a student and a LessonService with a method that adds students to a lesson. In both my Lesson and Student Resolvers I want to be able to update this lesson <---> student relationship. So in my LessonResolver I have something along the lines of:

  async assignStudentsToLesson(
    @Args('assignStudentsToLessonInput')
    assignStudentsToLesson: AssignStudentsToLessonInput,
  ) {
    const { lessonId, studentIds } = assignStudentsToLesson;
    await this.studentService.assignLessonToStudents(lessonId, studentIds); **** A.1 ****
    return this.lessonService.assignStudentsToLesson(lessonId, studentIds); **** A.2 ****
  }

and essentially the reverse in my StudentResolver

The difference between A.1 and A.2 above is that the StudentService has access to the StudentRepository and the LessonService has access to the LessonRepository - which I believe adheres to a solid separation of concerns.

However, it seems to be an anti-pattern that the StudentModule must import the LessonModule and the LessonModule must import the StudentModule. This is fixable using the forwardRef method, but in the NestJS Documentation it mentions this pattern should be avoided if possible:

While circular dependencies should be avoided where possible, you can't always do so. (is this one of those cases?)

This seems like it should be a common issue when using DI, but I'm struggling to get a definitive answer as to what options are available that can eliminate this situation, or if I've stumbled upon a situation where it's unavoidable.

The ultimate goal is for me to be able to write the two GraphQL queries below:

query {
  students {
    firstName
    lessons {
      name
    }
  }
}

query {
  lessons {
    name
    students {
      firstName
    }
  }
}

What's the pattern for sharing a RestAPI token?

Is there a pattern for how should I store and reuse a restAPI authorisation token across multiple classes?

I'm consuming a RestAPI, my login code takes a user, password and server and then returns an auth token. That login code sits in a common base class for all my RestAPI calls which works fine. But each new object doesn't know the token so has to reauthorise. I need them to share the same token once it's been generated. I can't use a singleton as I may have to login with multiple different users in the same session.

I'm sure there's a pattern for that but I can't find it, can you help?

Appropriate datastructure for flyweight

I am trying to apply the flyweight pattern in a program that generates clouds. I have a class that represents intrinsic states of clouds. A cloud type is defined by its attributes :

class CloudType {
    float size;
    float altitude;
    String color;
    String texture;

   public void display(x, y) {}

}

class ConcreteCloud {
    float x;
    float y;
    CloudType cloudType;

    void display() {
        cloudeType.display(x, y);
    }
}

I would like to create a CloudType factory that takes these characteristics as arguments and returns the corresponding instance of CloudType if it exists, else create and store it beforehand.

class CloudTypeFactory {
    //  SomeContainer<CloudType> container;

    public CloudType getCloudType(float size, float altitude, String color, String texture) {
        CloudType instance = // container get corresponding cloudType
        if (instance == null) {
            instance = new CloudeType(size, altitude, color, texture);
            container.add(instance);
        }
        return instance;
    }

}

The problem:

I have doubts concerning which container to use and consequently the architecture itself. A HashSet could be used, but the search complexity gets proportional to the number of attributes in CloudType , which doesn't seem right. In examples I read online, authors use a HashMap with the key being the name of the CloudType: this defeats the purpose IMO as there might be an infinite number of cloud types in this case.

mardi 26 mai 2020

Design Patterns and OOP principle in Java

Question to solve:

"There are several types of accounting service Orders. The current solution for these orders is to create a new class for each type (based on work type e.g. audits or day-to-day work, whether the order is for priority client , and whether the order is a one off or regularly scheduled work). The full system has 66 * 2 * 2 of these classes (264 order classes!), with 8 of these (2*2*2) provided to you as an example – CPA would like you to find a way to reduce this class load without breaking the existing Order interface."

The Code related to the question:

 if (isScheduled) {
  if (1 == orderType) { 
    if (isCritical) {
      order =
          new FirstOrderTypeScheduled(
              id, clientID, date, criticalLoading, maxCountedEmployees, numQuarters);
    } else {
      order = new Order66Scheduled(id, clientID, date, maxCountedEmployees, numQuarters);
    }
  } else if (2 == orderType) { // 2 is audit
    if (isCritical) {
      order = new CriticalAuditOrderScheduled(id, clientID, date, criticalLoading, numQuarters);
    } else {
      order = new NewOrderImplScheduled(id, clientID, date, numQuarters);
    }
  } else {
    return null;
  }
} else {
  if (1 == orderType) {
    if (isCritical) {
      order = new FirstOrderType(id, clientID, date, criticalLoading, maxCountedEmployees);
    } else {
      order = new Order66(id, clientID, date, maxCountedEmployees);
    }
  } else if (2 == orderType) {
    if (isCritical) {
      order = new CriticalAuditOrder(id, clientID, date, criticalLoading);
    } else {
      order = new NewOrderImpl(id, clientID, date);
    }
  } else {
    return null;
  }
}

So, there are a few types of classes given (8 classes) which are indicated in the above question. What I want to ask is, amongst the design principles and OO design principles (SOLID), is there a method that I should apply in order to solve the above question? (I am thinking of using Bridge Pattern)

Thanks in advance!

Java - Reduce Cyclomatic Complexity

Is there a way I could refactor my code? I have here a validation method that checks if the following attribute is correct. But since my request/RuleAttribute has so many attributes it triggers a sonarqube issue. Sonarqube is only allowing 10.

Note that I have another method named validateSecondAttributes, similar to this one that checks for attributes 3-4. It also triggers the cyclomatic complexity issue on sonarqube.

Here is my code below:

    protected String validateAttributes(RuleAttributes attributes,
                                    boolean isForSimpleFieldComparison) {

    String error = StringUtils.EMPTY;

    if (StringUtils.isBlank(attributes.getEntityField1())) {
        error = "Rule Validation: entityField1 not defined.";
    } else if (StringUtils.isBlank(attributes.getSourceField1())) {
        error = "Rule Validation: sourceField1 not defined.";
    } else if (StringUtils.isBlank(attributes.getEntityField2())) {
        error = "Rule Validation: entityField2 not defined.";
    } else if (StringUtils.isBlank(attributes.getSourceField2())) {
        error = "Rule Validation: sourceField2 not defined.";
    } else if (attributes.getPrefixLength1() < 0) {
        error = "Rule Validation: prefixLength1 must not be less than 0.";
    } else if (attributes.getSuffixLength1() < 0) {
        error = "Rule Validation: suffixLength1 must not be less than 0.";
    } else if (attributes.getPrefixLength2() < 0) {
        error = "Rule Validation: prefixLength2 must not be less than 0.";
    } else if (attributes.getSuffixLength2() < 0) {
        error = "Rule Validation: suffixLength2 must not be less than 0.";
    } else if (isOperatorInvalid(attributes.getOperator())) {
        error =
            MessageFormat.format("Rule Validation: {0} is not a valid operator value.", attributes.getOperator());
    } else if (StringUtils.isNotBlank(attributes.getDataSourceMapping1())
        && StringUtils.isBlank(attributes.getDataSourceMapping2())) {
        error = "Rule Validation: dataSourceMapping2 not defined.";
    } else if (StringUtils.isBlank(attributes.getDataSourceMapping1())
        && StringUtils.isNotBlank(attributes.getDataSourceMapping2())) {
        error = "Rule Validation: dataSourceMapping1 not defined.";
    } else if (StringUtils.isBlank(attributes.getRuleInput())) {
        error = "Rule Validation: ruleInput must not be blank.";
    } else if (hasInvalidRuleInput(attributes.getRuleInput())) {
        error = String.format(
            "Rule Validation: ruleInput value is not valid. Value must be %1$s or %2$s. No ruleInput attribute defined defaults to %1$s.",
            Constants.HIERARCHICAL_CARTESIAN_PRODUCT, Constants.NON_HIERARCHICAL_CARTESIAN_PRODUCT);
    }

    error = validateCombinationOperatorAttribute(attributes, isForSimpleFieldComparison, error);

    return error;
}

Pact Pattern Matching

I need some help to write a Pact Regular Expression Pattern Matching test for the below json. I am struggling to write for Account and AdditionalInfo

{
    "Account": [
        {
            "ContractId": "679",
            "Code": "0000",

        }
    ],
    "AdditionalInfo": [
        {
            "Contract`enter code here`Id": "679,
            "errorMessage": "NOT CARRIED OUT"
        }
    ]
}

Python - Child Class to call a function from another Child Class

I have a pretty big class that i want to break down in smaller classes that each handle a single part of the whole. So each child takes care of only one aspect of the whole.

Example "Design" before and after

Each of these child classes still need to communicate with one another. For example Data Access creates a dictionary that Plotting Controller needs to have access to. And then plotting Controller needs to update stuff on Main GUI Controller. But these children have various more inter-communication functions.

How do I achieve this?

I've read Metaclasses, Cooperative Multiple Inheritence and Wonders of Cooperative Multiple Inheritence, but i cannot figure out how to do this.

The closest I've come is the following code:

class A:
    def __init__(self):
        self.myself = 'ClassA'

    def method_ONE_from_class_A(self, caller):
        print(f"I am method ONE from {self.myself} called by {caller}")
        self.method_ONE_from_class_B(self.myself)

    def method_TWO_from_class_A(self, caller):
        print(f"I am method TWO from {self.myself} called by {caller}")
        self.method_TWO_from_class_B(self.myself)


class B:
    def __init__(self):
        self.me = 'ClassB'

    def method_ONE_from_class_B(self, caller):
        print(f"I am method ONE from {self.me} called by {caller}")
        self.method_TWO_from_class_A(self.me)

    def method_TWO_from_class_B(self, caller):
        print(f"I am method TWO from {self.me} called by {caller}")


class C(A, B):

    def __init__(self):
        A.__init__(self)
        B.__init__(self)

    def children_start_talking(self):
        self.method_ONE_from_class_A('Big Poppa')


poppa = C()
poppa.children_start_talking()

which results correctly in:

I am method ONE from ClassA called by Big Poppa
I am method ONE from ClassB called by ClassA
I am method TWO from ClassA called by ClassB
I am method TWO from ClassB called by ClassA

But... even though Class B and Class A correctly call the other children's functions, they don't actually find their declaration. Nor do i "see" them when i'm typing the code, which is both frustrating and worrisome that i might be doing something wrong.

As shown here

Cannot find declaration

Is there a good way to achieve this? Or is it an actually bad idea?

EDIT: Python 3.7 if it makes any difference.

shell script to read metadata file line by line and take those text as search pattern to find files placed in another directory

I have a directory(say: myDir) with many files dynamically populated inside it

I have a another meta data file with some texts inside it. Eg: cust_order cust_mgmt ... ...

I need to write a script to read that meta data file line by line and use that text as search pattern to find files with same name which were placed in the directory(myDir). Kindly help to write shell script for this scenario.

Thanks, vivek

How can i can detect a pattern present 2 times in a chain character without specifying the pattern?

I want to select characters chains in which a same combination of characters appears two times. But i can't use grepl because i can't specify the pattern which is different in every characters chain.

Here is an example of what i mean :

Flabellum transversaletransversale

Fungiacyathus pusilluspusillus

i want to detect when this happend and add a space between the same combinations of character.

Thank you for your answer.

why using service implementation pattern in spring

Why loose coupling under java code?
i don't understand, be loose coupling when using interface
why using interface?

Service.java

interface Service{
    public void method();
}

in ServiceImpl.java

@Override
ServiceImpl implements Service{
    public void method(){
        //To-do override
    }
}

lundi 25 mai 2020

How to clone a parameterized prototype?

I want to clone a prototype but with some changes. I want to pass the arguments that need to change. I have several candidate solutions but I'm not sure what is the best way. It may be none of them.

Here I have 3 classes, Prototype1, Prototype2 and Prototype3. Each one of them uses a different way of cloning. The class PrototypeBase is just for defining the common behavior among the three classes.

Each class is cloned in the main function.

public class Main {

    public static void main(String[] args) {

        var prototype1 = new Prototype1("a", "b", "c");
        var prototype1Clone = prototype1.clone(null, "bbb", null);

        var prototype2 = new Prototype2("a", "b", "c");
        var prototype2Clone = prototype2.clone();
        prototype2Clone.setB("bbb");

        var prototype3 = new Prototype3("a", "b", "c");
        var prototype3Clone = new Prototype3(null, "bbb", null);
        prototype3Clone.clone(prototype3);
    }
}

class PrototypeBase
{
    protected String a, b, c;

    public void setA(String a) {
        this.a = a;
    }

    public void setB(String b) {
        this.b = b;
    }

    public void setC(String c) {
        this.c = c;
    }

    @Override
    public String toString() {
        return "Prototype{" +
                "a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                '}';
    }
}

class Prototype1 extends PrototypeBase
{

    public Prototype1(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // Won't have a uniform interface across all prototypes
    // since each prototype may have a different number of fields.
    public Prototype1 clone(String a, String b, String c)
    {
        if (a == null)
            a = this.a;

        if (b == null)
            b = this.b;

        if (c == null)
            c = this.c;

        return new Prototype1(a, b, c);
    }
}

class Prototype2 extends PrototypeBase
{
    public Prototype2(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // a, b or c may be expensive to copy. It would
    // be better if we can pass the parameters directly
    // without copying all members first.
    public Prototype2 clone()
    {
        return new Prototype2(a, b, c);
    }
}

class Prototype3 extends PrototypeBase
{
    public Prototype3() {}

    public Prototype3(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // Not so intuitive. Usually, people just
    // ask for a clone and get the result back.
    public void clone(Prototype3 prototype)
    {
        if (this.a == null)
            this.a = prototype.a;

        if (this.b == null)
            this.b = prototype.b;

        if (this.c == null)
            this.c = prototype.c;
    }
}

Each one has its drawbacks. What is the best way to clone a prototype when wanting some fields to have a different value?

What does "classes are not objects" mean?

From the GoF book:

Prototype is particularly useful with static languages like C++, where classes are not objects, and little or no type information is available at run-time. It's less important in languages like Smalltalk or Objective C that provide what amounts to a prototype (i.e., a class object) for creating instances of each class. This pattern is built into prototype-based languages like Self [US87], in which all object creation happens by cloning a prototype.

What is meant by "classes are not objects"?

Isn't that always the case?

What does it mean for a class to be an object?

How can I imitate escaping characters in Lua?

I'm making a parser and I want the input string to support escape characters so that, for example, if parse("Hello [world]") yields: Hello world, then parse("Hello /[world]") would just yield: Hello [world]. I have an implementation that works, however it's constricting.

local function escapeStr(str)
    local escapedStr = str:gsub("/(%[%])", "\1") -- for parsing
    local regStr = str:gsub("/(%[%])", "%1") -- for displaying

    return escapedStr, regStr
end

This function is creating 2 versions of the input string. The first one (escapedStr) replaces an escaped character /[ with an empty character \1. This is the version of the string that the parser uses which I iterate over with gmatch, and it ignores special characters because they've been replaced with \1. Then, during the iteration, I use regStr:sub(start, end) when I want to extract a substring that is going to be displayed to the user, since regStr is what the escaped string should look like when displayed, and regStr and escapedStr are always the same length.

This solution is constricting in that in order to do regStr:sub(start, end), I need to keep track of the position in the string as I'm iterating over it, which is not ideal in more complex situations. It doesn't seem too bad here, for example:

local str = "hello [world], wonderful day today"
local escapedStr, regStr = escapeStr(str)

for begin, stop in escapedStr:gmatch("()%[.-%]()") do
    print(regStr:sub(begin, stop - 1)) --> [world]
end

...but this is only because I'm not matching anything else other than everything between the square brackets. If I wanted to match more patterns in the substring, I'd have to add more captures in my initial string pattern which would quickly get out of hand (messy/lengthy).

for begin0, begin1, stop1, stop0 in escapedStr:gmatch("()%[%a+:()%a+()%]()") do
    local entire_match = regStr:sub(begin0, stop0 - 1)
    local second_match = regStr:sub(begin1, stop1 - 1)

    print(entire_match) --> [world:earth]
    print(second_match) --> earth
end

And in my case I have a lot of matching within the substrings the parser initially selects, and I would like to do something like: "%[(.-)%]" to return the data I need rather than "()%[.-%]()" paired with regStr:sub(start, end) to accomplish the same thing.

I feel like I'm using a very unconventional way of implementing escape characters, so if anyone has a better solution, I would really appreciate it!

Can DAO also handle error checking and creation of DTO objects?

I was going through a diagram that showed connection between Logic and DTO, of obtains, create and modify and DAO design pattern logic mostly delegates its job to DAL thus I got confused that does DAO handles error checking and creation of DTO objects?

Bridge Pattern how to take out Implementor logic

I am trying to figure out how to use the bridge pattern in the following situation. The problem I am facing is I am not able to separate the implementors.

public class GoodTest {
    void sayHi(){
        System.out.println("I want to say:"); // Top part - same for all implementors

        System.out.println("Good Test"); // Middle part different

        System.out.println("I am done"); // Bottom part - same for all implementors
    }
}

public class GoodMathTest {
    void sayHi(){
        System.out.println("I want to say:"); // same for all implementors

        int x = 10;
        System.out.println(x);             // middle part is different from others 
        System.out.println("Good Math Test");  

        System.out.println("I am done"); // same for all implementors
    }
}

public class GoodMathWrittenTest {
    void sayHi(){
        System.out.println("I want to say:"); // same for all implementors

        int x = 10;
        System.out.println(x*x);
        System.out.println("Good Math Written Test"); // middle part different 
        System.out.println(x*x*x);

        System.out.println("I am done"); // same for all implementors
    }
}

I believe the solution, in this case, is to take out Test Type and Subject Test and build their own hierarchy and pass an instance of these to a class which can direct the call to one of these implementors.

The Problem:

  1. As the original method uses things which would be delegated to Subject Test and Test type. How do we take out and break the code Subject Test and Test type.
  2. If I do the above, how would I make write the method for the concrete class which uses the implementors received by dependency injection?

Thanks

Java - Creating a game. Kits, associating players and player-kit fields

I am attempting to create a game that involves kits that players can select. I've currently got a rather lengthy setup so I will try and condense this to what is necessary.

I have a Kit abstract class, which concrete kits extend, let's say for example, Fighter and Archer. These classes have no information about any players, and as such, they only contain information about the kit itself such as the name, a description of the kit, a list of potential skills or abilities (This seems like an appropriate place to put this, though I'm unsure), etc. The idea is that at the start of each game, only one of each of these kits is instantiated and stored, and they are constantly referenced - for example, when a Kit Selection Menu of some sort is made, it will refer to these Kit objects.

When a player selects a kit and uses it, there may be fields specific to that player-kit instance. Say for example, an integer shotsCount that exists for each player that uses the Archer kit. Because I am only creating one instance of a kit per game, shotsCount cannot exist in the Archer class, as it will be shared across all players using the Archer kit (in a "global" manner?), as opposed to a per player basis.

On the other hand, if I were to create multiple kits for each player instance, as opposed to one per game, then if I want to only retrieve information about a kit without any player reference, then this wouldn't make much sense (The player reference in the kit class would be null?). As a result, I don't think this approach is correct.

Say, if I create a PlayerKit class that has this shotsCount variable, this wouldn't make much sense if the player were a Fighter, as that variable is insignificant/irrelevant/doesn't exist for that kit.

On the other hand, if I were to create separate classes for each player-kit instance, associating a player to their kit and the kit-specific stats for the player (for example, PlayerFighter, PlayerArcher, etc.), there would be many classes if there were a large number of kits added in the future, which may be unnecessary or redundant if many do not contain player-kit specific fields.​

I am wondering what the best approach to model this would be or if there are any suggestions regarding this. Are there useful design strategies or patterns for this? I hope I've explained this well enough to be understood. Thanks in advance! :)

Which design pattern should be used if same input comes from different data sources and final object is exactly the same

I need to create an object where input can come from different data sources and final object created is of same class type. For instance

Input source (constructor argument) can either be:

1. file path as string
2. content as string

Note: Data type for both is same which is String.

Which design patter should I use?

I am thinking of using "Simple Factory" and add the methods:

ClassA fromFilePath(String){}
ClassA fromContent(String){}

However not sure where to put the logic to load/process the content from input source to create/initialise the instance.

Please advise.

Design pattern for bulky API controller

Please help me to figure out how to refactor my project with messed layers. I have monolith ASP.net MVC project with API controllers in it and typescript which most API calls are coming from. My biggest problem is that with current design I'm not able to reuse my code and unit test it properly. The only think I can do is do an integration test of whole api endpoint, which is not nice. My api controllers are really bulky like 50/100 lines of code per endpoint, bulkiest controllers has like 4k line of code. I need some help to point me out which direction I should choose to code new features to be able to unit test my business logic and reuse my code.

Most of my API endpoints looks like that:

public IEnumerable<ModelADto> GetComplexData(object[] someQueryParameters)
{
    // parameter validation

    // Getting data from DB table ModelA using complex LINQ queries and someQueryParameters 

    // Getting data from diffrent DB table ModelB using complex LINQ queries and someQueryParameters 

    ....

    // **doing some business logic** using above data to get List of ModelA objects

    //Mapping List<ModelA> to List<ModelADto>

    // returning above List of ModelADto objects

}

I didn't find any good pattern to solve this problem, repository&service pattern doesn't fit here for me, because one API controller will have like 1-15 different services/repositories in it or I'm just missing something and this is the way I should follow?

dimanche 24 mai 2020

Python: Implement a function for find a pattern in an image

I need help with an exercise in python and I have not been able to solve it. The exercise reads like this:

Find a pattern in an image.

You are given 2 images: a base image and a pattern which may appear somewhere on this image. Each image is represented by a list of strings, where each element of the list represents a row of pixels of the image, and each character represents one pixel. Understanding this encoding is not necessary to solve this problem, but for your information, a detailed explanation is provided below

You must return the position x, y of this pattern in the image, or (-1, -1) if the patter is not found. If the pattern appears multiple times, return the position of the highest one (the smallest y), and in case of equality, the leftmost one (the smallest x).

The position of the pattern is represented by the coordinates x, y of it is top-left corner. X represents the column, y represents the row, and the coordinates (0, 0) represents the top-left corner. Implementation.

Implement the function, where the parameters are:

  • imageWidth: the image width
  • imageHeight: the image height
  • image: the image as a list of strings, where each character represents a pixel
  • patternWidth: the pattern width
  • patternHeight: the pattern height
  • pattern: the pattern as a list of strigns, where each character represents a pixel

and which should return:

  • if the pattern is present in the image: the position x, y, as a list of 2 integers, representing the top-left corner of the first pattern, going from top to bottom and left to right.
  • If the pattern is not present in the image: (-1, -1)

Victory Conditions

  • The pattern is indeed located at coordinates x, y.
  • If the pattern appears multiple times, return the position of the highest one (the smallest y), and in case of equality, the leftmost one (the smallest x).

Defeat Conditions

  • The inner image that starst at coordinates x, y does not match the pattern.
  • You take longer than 1 second to answer.
  • There is another matching pattern above or on the left.

The code supplied for the exercise is as follows:

import sys
import math
from contextlib import redirect_stdout


def solve(image_width, image_height, image, pattern_width, pattern_height, pattern):
    # Write your code here
    # To debug: print("Debug messages...", file=sys.stderr)
    return []

# Ignore and do not change the code below
def main():
    image_width, image_height = [int(i) for i in input().split()]
    image = []
    for i in range(image_height):
        image.append(input())
    pattern_width, pattern_height = [int(i) for i in input().split()]
    pattern = []
    for i in range(pattern_height):
        pattern.append(input())
    with redirect_stdout(sys.stderr):
        coordinates = solve(image_width, image_height, image, pattern_width, pattern_height, pattern)
    for i in range(2):
        print(coordinates[i])

if __name__ == "__main__":
    main()

Inserting into templated resource holder - any design pattern to use?

I am wondering what's wrong with my design, and how to fix it.

I have a following (simplified) classes diagram:

enter image description here

And here's minimum possible code:

Resource holder:

template <typename Key, typename Resource>
class ResourceHolder {
public:
    template <typename... Args>
    void insert(const Key& key, Args&&... args) {
        // <resPtr points to a resource>
        resources.emplace(key, std::move(resPtr));
    }

    Resource& get(const Key& key) const {
        if (auto resource = resources.find(key); resource != std::end(resources)) {
            return *(resource->second);
        } throw std::invalid_argument{"No such resource id."};
    }

private:
    std::unordered_map<Key, std::unique_ptr<Resource>> resources;
};

ResourceManager:

class ResourceManager {
public:
    ResourceManager() {
        loadTextures();
        loadSounds();
    }

private:
    ResourceHolder<res::Texture, sf::Texture> textures;
    ResourceHolder<res::Sound, sf::SoundBuffer> sounds;

    void loadTextures() {
        textures.insert(res::Texture::Wizard, "wizard.png");
        textures.insert(res::Texture::Gray,   "gray.png");
        textures.insert(res::Texture::Orange, "orange.png");
    }

    void loadSounds() {
        sounds += ResourceInserter(res::Sound::Bullet, "boing.wav");
        sounds += ResourceInserter(res::Sound::Bing,   "boing_long.wav");
        sounds += ResourceInserter(res::Sound::Poof,   "poof.wav");
    }
};

Can you tell me what's wrong with the code from the OOP/design patterns stand-point and can you suggest a fix, please? Also, perhaps there's something confusing about the classes names?

I am particularly wondering about inserting resources into resource holders.

Currently, if I want to add a new ResourceHolder to a ResourceMananger, I need to do the following inside ResourceManager class:

  1. create new getter e.g. getImages()
  2. create new load function e.g. loadImages()
  3. call loadImages() in ResourceManager's constructor

Is it okay or bad design?

Android app architecture: JSON file + Firebase -> local database?

I'm developing an app whose main data is stored in a big Json file. However there are some additional information, provided by logged-in users, that are retrieved from Firebase Firestore. What's the best app architecture for this scenario? a) keeping the Json file and using Firestore as a layer on top of it, updating the information in the UI with the data donwloaded from Firestore? b) saving the Json file in a local database (updated with data coming from Firestore) which should act the "single source of truth"?

What do you think?

Is builder pattern about number of arguments in the constructor?

I am learning design pattern. As part of that I am going through the Builder design pattern. The definition says that "The intent of the Builder design pattern is to separate the construction of a complex object from its representation". I am trying to understand what does it mean a "complex object".When I check online people are mentioning if the constructor has more arguments or optional arguments then to use builder object.

Is that explanation is correct? If we have optional parameters then why dont we remove those arguments from the constructor and if the client requires that argument can set using a set method?

If we have more constructor arguments and try to create the object using builder class then there can be a chance where client didnt set some arguments and give a call to final method to get the object.

samedi 23 mai 2020

Can anyone help me with this hour glass pattern in C++? [closed]

Take N as input. For a value of N=5, we wish to draw the following pattern :

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

Input Format Take N as input.

Constraints N <= 20

Output Format Pattern should be printed with a space between every two values.

Sample Input 5 Sample Output 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 3 2 1 0 1 2 3 2 1 0 1 2 1 0 1 0 1 0 1 2 1 0 1 2 3 2 1 0 1 2 3 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 strong text

What is about KISS principle?

I am familiar with the KISS principle in software programming, although I don't really understand what it is about in practice. I could find few articles regarding this which rely on quite different examples and statements. So would like to clarify in details.

  1. Case 1.

    As I understand removing of redundant abstractions can be an example of KISS. But from the other side we are also following open/closed and want our application to be extensible so here some abstractions may be needed. Can anyone clarify this?

  2. Case 2.

    I am writing some method - the code of the method can be quite complex from point of reading - with some long expressions etc. Is this example of KISS violation ? Or it is about maintainability of the method ?

    Please provide your examples where you are sure KISS is violated or not.

Design pattern: Don't store direct references (memory leaks & code maintenance)

With a large project with many connected systems and moving parts (a video game, where a lot of state needs to be kept and used in different areas at different times), I am having a growing code maintenance problem where any references I assign to a created class instance object need to be cleaned up on destruction of said instance when it is no longer needed. Finding where all of these references might be is becoming a nuisance.

For this I was thinking about simply not storing references to actual objects directly in other areas of the code, but to instead just store them in a list where they can be accessed by some ID, and just store that ID on the interested parties, so that for deletion, all I have to worry about is removing the object from it's containing list and I don't have to worry about references to it hiding somewhere that prevents it from being garbage collected and persisting for longer than I want it to.

This way objects are no longer responsible for removing their own references to other objects. They should only be able to get temporary references to other objects, that they should not keep.

So something like:

const Spaceships = {};
class Spaceship {
    constructor(id, captain) {
        // Only actual reference to the object stored.
        Spaceships[id] = this;
        this.id = id;
        if (captain) {
            this.captain = captain;
        }
    }
    destroy() {
        // Can safely remove reference here and be confident it will be GCed.
        delete Spaceships[this.id];
    }
    // ES5 accessor syntax.
    get captain() {
        // If the object no longer exists it won't be returned.
        return Captains[this._captainID];
    }
    set captain(captain) {
        if (Captains[captain.id]) {
            this._captainID = captain.id;
            // Prevent setter call loop.
            if (captain.spaceship !== this) {
                captain.spaceship = this;
            }
        }
    }
    warp(location) {
        console.log(`${this.id}: Warping to ${location}`);
    }
}

const Captains = {};
class Captain {
    constructor(id, spaceship) {
        Captains[id] = this;
        this.id = id;
        if (spaceship) {
            this.spaceship = spaceship;
        }
    }
    destroy() {
        delete Captains[this.id];
    }
    get spaceship() {
        return Spaceships[this._spaceshipID];
    }
    set spaceship(spaceship) {
        if (Spaceships[spaceship.id]) {
            this._spaceshipID = spaceship.id;
            if (spaceship.captain !== this) {
                spaceship.captain = this;
            }
        }
    }
    speak(text) {
        console.log(`${this.id}: ${text}`);
    }
}

const kirk = new Captain("J. T. Kirk");
const enterprise = new Spaceship("NCC-1701", kirk);
enterprise.warp("Betazed");
// Destroy the object, which will make any IDs used to access it no longer work.
enterprise.destroy();
// The object would now still be usable for the scope of the variable it is
// assigned to, and no longer.
enterprise.warp("Vulcan");
// This new object would only receive an ID to another object that is no longer
// accessible. 
const spock = new Captain("Spock", enterprise);
// Calling this now would error as the object cannot be found. Would need to
// wrap each call in a check for object existence to handle errors.
// `if (kirk.spaceship) ...`
kirk.spaceship.warp("Andor");

Is there a name for this pattern?

Adapter Design Pattern

I've recently came across this question and I'm just curious if my answer is correct, and if not, where I made a mistake.

My Task:

The signatures of classes A and B are incompatible. Class C is to connect A and B with the Design Pattern Adapter.

What are the advantages of having C inherit from A and B? Explain whether it would make sense to have B inherit from A and C inherit from B.

My answer:

The advantage of making C inherit from A and B is that the signature conflict can be resolved, while A and B could still be instantiated separately.

It would not make sense to have B inherit from A and C inherit from B, because if the functionality that previously caused the conflict is inherited from A to C, B has to take over the implementation of A, the functionality of B would be changed, this would not be the purpose of the design pattern adapter.

Thanks :-)

How to do this type of Pattern in java but only using for loop and nesting

"""this is my code and I am trying to make a triangle pattern like this"""

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

and I don't know where is the problem in this code.

please fix my problem in this code.

public static void main(String[] args) {

    Scanner sc = new Scanner (System.in);

    int n = sc.nextInt();

    for ( int i = 1; i <= n; i++) {

        for ( int j = 1; j <= n-i+1; j++) {
            System.out.print("  ");
        }for ( int j = 1; j == i; j++) {
            System.out.print("* ");
        }
      System.out.println();
    }   

}

}

What is the best Design pattern for the licence subscription?

Requirement is 1. User can increase their licence or decrease licence 2. It may be recurring billing or prorate billing.

How can we track those changes with the best design pattern and makes is easier.

vendredi 22 mai 2020

Are Java Streams implementations of Iterator Design Pattern?

So, as the title asks, can Java Streams be considered an implementation of the Iterator pattern?

Can we consider that the .stream() call on a Collection create some sort of an iterator which allows you to parse the elements of that Collection, without actually exposing the representation of the Collection? (Which is what the Iterator Pattern implies, if I am not mistaking)

EDIT: to avoid confusion, please note that I am not interested in Java's Iterator interface, I just want to know if Java Streams can be considered an implementation of the Iterator Design Pattern, and why?

What are my options for handling multiple choice checkbox data in database platforms?

When collecting data using an HTML form (or other technologies) I can use checkbox input fields sharing a name in order to give people the option to answer a question with multiple answers. I know there are two approaches to this.

Different input element names

  <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
  <label for="vehicle3"> I have a boat</label>

Same input element name

  <input type="checkbox" id="vehicle1" name="vehicles" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicles" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicles" value="Boat">
  <label for="vehicle3"> I have a boat</label>

I want to store the answers in a database of some kind so that I can present the answers back in different ways.

With the first option, I would store the data in separate fields. With the second option I would store the data in a single field, in some form of array. Are there other options in the HTML and the database?

What are the pros and cons of the different approaches?

I can easily find information about how to do either way in different server side languages and databases. I am more interested in why I would choose a particular technique, as once I have made that decision I can figure out how to apply it with any tools available (or choose a tool based on ability to apply the technique). I'm not even sure how to describe this problem to find answers on the internet.

Understanding problems with communications patterns > Preference Key in SwiftUI

I've literally just started to play around with SwiftUI so please excuse if this question is stupid. I'm trying since days, read many different posts and tried to follow the official documentation on apple.com but unfortunately can't get my head around how Preference Keys work in SwiftUI.

Basically my test-application ist structured in 3 different components:

Content View
// contains a form and a text field in an HStack

    ∟ Form View
      // contains the form blocks in a TabView

          L Form Block View
            // contains the form fields

What I want to achieve is an information flow from the actual form fields up to the main view which then updates the text field. From what I've read so far, it seems that PreferenceKey is the best option for this problem. Thus my block view looks as follows:

import SwiftUI

// The preference key
struct MyTextPreferenceKey: PreferenceKey {
    static var defaultValue: MyTextPreferenceData?

    static func reduce(value: inout MyTextPreferenceData?, nextValue: () -> MyTextPreferenceData?) {
        value = nextValue()
    }
}

// The data for the from field block
struct MyTextPreferenceData: Equatable {
    var firstName: String
    var lastName: String
}

// The test form block
struct TestFormBlock: View {

    @State private var firstName = MyTextPreferenceData(firstName: "")
    @State private var lastName = MyTextPreferenceData(lastName: "")

    var body: some View {
       Form {
        TextField("First Name", text: $test.firstName) // this would work if firstName would be declared as String
            .preference(key: MyTextPreferenceKey.self, value: self.fistName) // how would I set the Preference Key value here?

        TextField("Last Name", text: $test.lastName)
            .preference(key: MyTextPreferenceKey.self, value: self.lastName)
       }.padding()
    }
}

struct TestFormBlock_Previews: PreviewProvider {
    static var previews: some View {
        TestFormBlock()
    }
}

Again, I'm sorry if this is a stupid question but I'm really stuck and simply can't get my head around how this works...

Thanks for your help!

Design pattern for multiple DAC and SAC calls

Scenario- After request validation, I will need to

  1. Call database and update the record. Based on a certain condition, I will be calling Service1.

  2. Upon performing this step, I will call another database and update record from the request.

  3. At last I will call audit service to save the transaction details.

This can be achievable in normal code structure. But I am pretty confident there will be plug and play after step 1 or 2, i.e., a database/service call will be introduced in next release after step 1/step 2 (TBD).

I decided to opt for Chain of Responsibility.

Problems

  1. Where ever the operation breaks/exception is generated, code should stop its execution.
  2. Under single Logging object, I am having difficulty to handle the sequential call.
  3. For step 1’s conditional service call, the dynamic modification of the chain of operations is bit complex, as I have to rely on single data type return from the AbstractionHandler.

Is there any alternative design pattern that I can follow?

Does overloading (not overriding) break the Liskov subsitution principle?

There are tons of discussions out there about the LSP, but all of them seem to be excessively blurred.
AFAIK, LSP states that to properly override (not overload) a superclass method in a child, one should assure that the child method:

  1. does not yield a new type of exception that in no scenario is raised by the parent method
  2. has the same signature as the parent method (in case of strongly typed languages)
  3. has the same semantic MEANING of the signature
  4. returns value of the same type/types
  5. returns value of the same semantic meaning

By semantic meaning I mean that if base class method implies that it returns int and this int means, say, USD or EUR, then the overloaded method should also imply that the returned value is either USD or EUR, and returning 'RUB' even in one scenario would violate LSP.

But what if my base class looks like this (example is in Python):

class A:

    func(x: int) -> int
        return x*2

class B(A):

    func(x: int, y: string) -> int
        return x*y

So there are two sub-questions in my question:

  1. What does the term contract mean in more practical terms ? Is it synonimous to interface ?
  2. Does overloading with a signature (in part of list of arguments) that is NOT present in the base class violate LSP?