jeudi 30 avril 2020

Design patterns or design to read data from lexs.xsd doPublish instance

I have a sample instance in below link. http://www.datypic.com/sc/lexs314/e-lexspd_doPublish.html

I did unmarshall xml to object and got a complex object. I need a design pattern or design to read data from that complex object and assign it to a pojo. While reading data from complex objects, I have to check if conditions for each variable and retrieve data and it's lot of code. Could someone guide in a direction to map or parse that complex object and retrieve data and assign data to a pojo. Let me know if you need more information.

Is this class avoiding temporal coupling

I have a wrappr object that takes a connectionstring and opens up a database and initializes an API before it can be used. After reading Mark Seeman blog post on temporal coupling I've been going crazy over trying to refactor my API so it is clear. I've looked at the .net class SqlConnection and they require Open before you use it, so maybe this type of coupling is unavoidable? I don't know if there is a way to do what I want since it's a wrapper of an existing API but here is what I have. There can only be one connection at a time, else you have to close and restart

public class MyService
{

    public MyService(string dataSource)

    public void StopRequest()

    public void StopAPI()

    public Response SendRequest(string request, string pass)

}

You see it requires a datasource string, and starts the API so SendRequests will work but you can only really have one service at a time so unless I save it in some sort of static var or DI singleton, you'd have to call new ..(datasource) everytime even though it's always the same. The only thing that bothers me is if you call stopRequest or StopAPI & then call SendRequest, it will throw an error of course. I think this is avoiding temporal coupling but wanted some thoughts.

OOP, Need advice about creating programs with an architecture

I need to learn the right way to use OOP. I mean do's & dont's, pros or cons about some specific examples -which i will plan to learn that too-. When to use interface or abstract class, controlling an object implicitly(at the class that object instantiated from, might be the wrong word choice, don't know about the terminology good) or explicitly(at some other controller class) etc. What i'm trying to tell is i'm sure there are right ways to use OOP, but i don't know how to reach that educational contents. Which educational contents(documents, books, tutorials) you can suggest me to learn about creating a good structure for my program?

Thanks all, have a nice day.

Explanation For Factory Method

I'm learning the factory method,when and why to use,but one thing that was a little bit ambiguous is that why are we using the static keyword for the factory method,can somebody clarify. as shown in the code below:

enum VehicleType { 
    VT_TwoWheeler,    VT_ThreeWheeler,    VT_FourWheeler 
}; 

// Library classes 
class Vehicle { 
public: 
    virtual void printVehicle() = 0; 
    static Vehicle* Create(VehicleType type); 
}; 
class TwoWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am two wheeler" << endl; 
    } 
}; 
class ThreeWheeler : public Vehicle { 
public: 
    void printVehicle() { 
        cout << "I am three wheeler" << endl; 
    } 
}; 
class FourWheeler : public Vehicle { 
    public: 
    void printVehicle() { 
        cout << "I am four wheeler" << endl; 
    } 
}; 

// Factory method to create objects of different types. 
// Change is required only in this function to create a new object type 
Vehicle* Vehicle::Create(VehicleType type) { 
    if (type == VT_TwoWheeler) 
        return new TwoWheeler(); 
    else if (type == VT_ThreeWheeler) 
        return new ThreeWheeler(); 
    else if (type == VT_FourWheeler) 
        return new FourWheeler(); 
    else return NULL; 
} 

PS: This code can be found on GeeksForGeeks.

Alternative or design pattern to avoid InternalsVisibleTo?

Context:

I have a Unity project in which I have numerous internal types which in turn are used by other types such as editors.

As project is growing up, it starts to be a little difficult to find yourself in all this, so one would use assembly definitions which are nothing more that the equivalent of .csproj files.

So that's pretty cool since you can finally split your work into separate projects, but now comes another problem: how to access those internal types?

The InternalsVisibleTo comes in handy in this case but the downside is that, everything non-public gets now exposed, adding a bit more to the confusion.

Question:

What alternative approach or design pattern for doing without InternalsVisibleTo?

How to pass the base class on the caller side and accept derived

I have a service that returns the base class response. For sure it has derived responses.

    public class ResponseBase
    {
        public string Response { get; set; }
    }

    public class DerivedResponse : ResponseBase
    {
        public string AdditionalResponse { get; set; }
    }

Here is the service code:

public class SomeService
{
    public ResponseBase GetResponse() => new DerivedResponse();
}

Then I need to handle different responses in different ways. Obviously try to get appropriate behavior via 100500 if\elses is not a good solution. And I decide to have One special response handler for each concrete response.

    public interface IHandlerBase<T>
        where T : ResponseBase
    {
        void Handle(T response);
    }

    public class DerivedResponseHandler : IHandlerBase<DerivedResponse>
    {
        public void Handle(DerivedResponse response)
        {

        }
    }

Also, we need to encapsulate behavior which will decide what handler to get in order to handle the concrete response and I think not a bad solution for that will be factory. And I got a problem with that because I don't know what to return since I don't know compile-time derived type:

    public class HandlerFactory {
        public IHandlerBase<> /*WHAT RETURN HERE*/ CreateHandler(ResponseBase response)
        {
            //decide the derived type of the 'response' and return appropriate handler
        }
    }

For sure we can remove generic parameter, accept base class in all handlers, then convert to special in the concrete handlers, but I don't think it is a good solution. So could you please advise how to do that in a clean way, maybe some patterns or solutions?

Python: do I need a Singleton?

I've multiple instanciated logger classes in logger.py which I import in multiple other modules.

logger.py

class Logger:
    def __init__(self, name='default'):
        # create a Logger with custom handlers
        # ...

main_logger = Logger('main_logger')
another_topic_logger = Logger('another_topic_logger')

module_a.py

from logger import main_logger
main_logger.info('hello!')

How does Python handle it in the background? Do I need a Singleton wrapper or is that just fine?

Is there an equivalent of the exhibit pattern in Python/Django?

I have tried googling it but I get flooded with results on wrappers when trying to query decorators.

In the Rails world, I used to use https://github.com/objects-on-rails/display-case, " An implementation of the Exhibit pattern, as described in Objects on Rails" a lot, in essence:

class LeagueExhibit < DisplayCase::Exhibit
  def self.applicable_to?(object, context)
    object.class.name == 'League'
  end

  def render_icon(template)
    # Do something
  end
end

and then wrap with something like @leagues = exhibit(League.all) which then will allow @leagues.render_icon or @leagues.a_league_method.

I want to do the same with a Django view, I have some helper methods for one of my models that are needed only in that view. Ideally I would be interested in passing the target object to a class and when a method does not exist on that class, to delegate the call to that object.

Does this exist in Python? Is there a library or is it so trivial that can be implemented with a dunder method?

Single sign on service architecture and design pattern

I'm studying how to build some sort of SSO service for a project I'm working on. We are using NodeJS, but it's not a mandatory environment. Let me explain the situation:

I have a client who signs up to our app. The signup process generates N accounts via API on N third party services on behalf of the user.

What I want to achieve from now on is the user being able login into our app with just the "local credenitals" and use it as a "pipe service" to consume data stored by the third party services. So I'm planning to keep a local DB with a one to many table with 1 local user credentials and N third party credentials.

The data provided by third party APIs range from few bytes to video streams (ie assume the size and structure of the provided data is unknown).

And here is the question:

What method is better between the following options and why?

1- Create a pass through server that makes API requests to third party API and sends the results to the client (so receiving the data from third party API and forwarding them to the client).

2- Send to the client the third party credentials and let the client handle all the API requests to them (just sending the correct credentials for a service to the client).

3- Some other option I didn't think of

Thanks in advance for the answers.

Sonar reports 0% coverage for a public method invoked from a private method

This an Angular 9 project where in an injectable angular service is invoking it's private method from a constructor.

export class Service {
    private serviceVariable: string;

    constructor(private someOtherService: SomeOtherService) {
        this.serviceVariable = 'Hello Angular Service!';
        this.someOtherService.getObservable().subscribe(value => {
            this.handleThisNow(value);
        });
    }



    private handleThisNow(value) {
        if (value > 0) {
            this.anotherPrivateMethod(value);
        } else {
            this.aPublicMethod(value);// sonar shows 0% coverage for this line and build fails for new code
        }
    }
    }

What is wrong in this class? Is it wrong to invoke a non-private method from a private method? Or is it wrong to invoke a private method from a constuctor?

mercredi 29 avril 2020

What should be the length of a website url form input?

I'm developing a user's profile screen and in the editing part, the user can save a personal website URL (like https://www.example.com). What is usuallly the max length that a website url form input has?

How can I mandate one class will hold One type of inner object

I have a requirement like from different type of objects I need to create AlertModelWrapper object. For this I can pass student only to StudentAlertGenerator, and teacher only to TeacherAlertGenerator. What should be the interface method here? If i take object i can't mandate student can have only Student type. Where my design lags?

public class StudentAlertGenerator : IAlertGeneratorType
{
  private readonly IDateTransformationService transformationService
  public StudentAlertGenerator(IDateTransformationService transformationService)
  {
     this.trnasformationservice =transformationservice
  }
  public AlertModelWrapper CreateAlertTypeModel(Student student)
  {
    return new AlertModelWrapper ()
    {
        ID= "std_"+student.Id,
        AlertModel = new AlertModel () { alertDetails=student.Name + "has an alert on " +transformationService.Transform(DateTime.Now())}
    };
  }
}

and teacher alertGeneratory as follows

public class TeacherAlertGenerator : IAlertGeneratorType
{
  private readonly IDateTransformationService transformationService
  public StudentAlertGenerator(IDateTransformationService transformationService)
  {
     this.trnasformationservice =transformationservice
  }
  public AlertModelWrapper CreateAlertTypeModel(Teacher teacher)
  {
    return new AlertModelWrapper ()
    {
        ID= "tea_"+teacher.Id,
        AlertModel = new AlertModel () { alertDetails=teacher.Name + "has an alert on " +transformationService.Transform(DateTime.Now())}
    };
  }
}

Python Logging patterns and BKMs

I often find myself adding lots of log prints to my code, either to assist with profiling and debugging or to inform users of issues with the tool they are running.

With this, I'm also finding that I'll have redundant logs printing, each with their own contexts. For example, suppose I had two functions:

def sub_function(args):
    logging.info(f"Beginning to look for things that match args: {args}")
    found_arguments = []
    for arg in args:
        logging.info(f"Searching file system for {arg}")
        ...
        if some_value:
            found_arguments.append(some_value)
            logging.info(f"Found value {some_value}!")

    logging.info(f"Found arguments: {found_arguments}")
    return found_arguments

def calling_function(args):
    logging.info(f"Going to search for {args}!")
    result = sub_function(args)
    logging.info("Found arguments: {result}")
    ...

This might produce a log that looks like:

Going to search for ["arg1", "arg2"]!
Beginning to look for things that match args: ["arg1", "arg2"]
Searching file system for "arg1"
Searching file system for "arg2"
Found value /tmp/arg2!
Found arguments: ["/tmp/arg2"]
Found arguments: ["/tmp/arg2"]

Barring the fact that this example will produce a lot of logging output, it doesn't have a way to separate context for the logging. For example, a developer might be very interested to know what is happening in the sub_function() and doesn't necessarily care what tools or outer calling_function()s might be utilizing it.

But a tool developer wants to produce specific messages for the results, and doesn't necessarily care about the internal workings of the sub_function(), just that they have their calling_function() and need to print specific messages. Users might get frustrated, or even ignore logging if there is too much 'junk' in the log.

Is there a best practice for how to handle logging in this way? Of course, I could change some logs to logging.debug() instead of logging.info() but that requires a lot of coordination between developers on different layers. One man's info is another man's debug, after all. The only thing I can think of is implementing different loggers, but then I can see that exploding into a multitude of different loggers that need to be able to redirect output to various places, which then could make it hard for developers and users to know exactly what they are gonna see when they run a tool.

Thanks

BASH: Generating pattern from filenames

I have files in a directory as

file_01_20_01_2020.txt
file_02_20_01_2020.txt
otherfile_01_28_01_2020.txt
otherfile_02_18_01_2020.txt
otherfile_03_18_01_2020.txt

I want to get output as

*20_01_2020.txt
*28_01_2020.txt
*18_01_2020.txt

StateMachine (One Trigger with Two States)

I am using Statless.StateMachine and I am facing a situation where I have one trigger with two states! Let me explain, I have an application where I need to activate some buttons when a user fills out a textbox but at the same time, those buttons will be deactivated when the user clears the textbox.

What I have done is that I have created two states Waiting and Editing. On waiting, the buttons are deactivated while on editing the buttons are activated as long as the textbox is not empty. To solve this, I wrote the following code:

_machine.Configure(State.ChoiceWaiting)
    .OnEntry(() => Setup())
    .PermitIf(Trigger.Edit, State.Editing, () => CheckEditing())
    .PermitReentryIf(Trigger.Wait, () => !CheckEditing());

_machine.Configure(State.Editing)
    .OnEntry(() => Setup2())
    .PermitIf(Trigger.Wait, State.ChoiceWaiting, () => !CheckEditing())
    .PermitIf(Trigger.Edit, State.ChoiceWaiting, () => !CheckEditing())
    .PermitReentryIf(Trigger.Edit, () => CheckEditing());

Now KeyUp event of the textbox is:

private void TextBlock_KeyUp(object sender, KeyEventArgs e)
{
    _machine.Fire(Trigger.Edit);
}

the previous code is working fine, the problem appears when pressing Backspace while the textbox is empty

System.InvalidOperationException: 'Trigger 'Edit' is valid for transition from state 'ChoiceWaiting' but a guard conditions are not met. Guard descriptions: 'Function

I know that I can solve the issue by having a condition to determine which trigger to fire on KeyUp event, but I feel that defeats the purpose of State Design Pattern as I need to control the states without the mess of if-else inside the code like KeyUp (outside StateMachine as PermitIf will do the decision on its own).

Is a correct application of the state design pattern? Or is there something I have missed?

JavaFX MVC inter package comunication

My team and I are creating a university project. We have to create an application that emulates the famouse game Monopoly in Java. We are using JavaFX as graphic library. This is my first "big" project and now that we have got all the MVC parts completed, we need to make them communicate.

My view must update every time a player pays money or if its pawn moves on the board and in a lot of other cases. We have a GameEngine controller that relates all the Controller/Model components.

My question (that plagues me from several days) is: If I create a ViewController that gets the data from the GameEngine and then this controller updates the view, is that a MVC violation ?

Or is better to create many methods in my ViewController that updates single components that could be called by other controllers? In this case, which would be the best way to do it?

I thank you in advance and I apologize for my English.

How to implement a checked builder pattern in Java

I'm trying to implement a checked builder pattern similar to how it's described in this: https://dev.to/schreiber_chris/creating-complex-objects-using-checked-builder-pattern

The result I'm trying to reach is as follows:

Builder builder = new Builder('TestVal')
    .when('this').then(new Set<String> {'val1','val2'})
    .when('that').then(new Set<String> {'val3','val4'});

And the resulting object would contain a collection with any number of whens with the associted thens e.g. a Map like this (the param for when() is unique):

'this' => ['val1','val2'],
'that' => ['val3','val4']

I'm struggling with a couple things:

  1. How to associate the values passed into then() with the value passed into when()
  2. How to require then() be called after when(). (e.g. - .when('this').when('that') //invalid

Pass data objects with constructor service objects in dependency injection

I'm a bit familiar with dependency injection. Today a case came. I need to make an object from a data.So I completed code in the structure

public class StudentGeneratorTypeFromXML : IAlertGeneratorType
{
    private readonly XML student;
    public StudentGeneratorTypeFromXML(Student student)
    {
        this.student= student;
    }
    public AlertModelWrapper CreateAlertTypeModel()
    {
        return new AlertModelWrapper ()
        {
            ID= "std_"+student.Id,
            AlertModel = new AlertModel () { alertDetails=student.Name + "has an alert on " +DateTime.Now()}
        };
    }
}

Like this I have different sources like Excel etc...

And say I have teacher's alerts also have the different combinations

Now a new requirement comes. I have already IDateTransformationService in my system which runs on the customer customization. Its asked to do this transformation also with this. Means the above example should change to DateTime.Now() to transformationService.Transform(DateTime.Now());

There is lot of places create the object already in my project. I'm using unitycontainer now. Is there a way to auto resolve IDateTransformationService in place so that I needn't to each place and change creation of object after manual resolve? Eg: some code like below. But the object initialization shouldn't expect the first paramter and it should autoresolve

public StudentGeneratorTypeFromXML(IDateTransformationService transformationService,Student student)
{
    this.transformationService=transformationService
    this.student= student;
}

Allow instantiate of specific variables of a class based on the variable value

I have a use case where I have to instantiate a given class with only specific variables based on the value of variable (let say in this example) typeName. For a variable String typeName, if its value is TYPE-1, only specific set of variables (a,b,c) should be allowed to be instantiate. Similarly if its value is TYPE-2, only the another set of variables (x,y,z) should be allowed to instantiate.

if(typeName == "TYPE1") 
 {
     CentralClass class = new CentralClass(a,b,c);  //initiating only variable a,b,c
 }
else
{  
     CentralClass class = new CentralClass(x,y,z);  //initiating only variable x,y,z
}

Class Structure

public class CentralClass {

 String typeName; //ALLOWED Values TYPE1, TYPE2
 String x;
 String y;
 String z;

 String a;
 String b;
 String c;
}

What would be the best way to do so via any design pattern etc.

Note: The structure of the class is open for change. We can have multiple classes(clubbing different variables), inner, static classes, or any design pattern enforced etc.

How can remove conditional statements while adding the common responsibilitu to the class?

I am building up a validation engine. There are common rules, which I have consolidated in a parent interface static method.

public interface EmployeeValidator {
    Predicate<Employee> build(Employee employee);

    static Predicate<Employee> getCommonRules(Employee employee) {
        return validateAge().and(validateGenger());
    }

    private static Predicate<Employee> validateAge() {
        ...
    }

    private static Predicate<Employee> validateGenger() {
        ...
    }
}

Now, the class that implements this interface will add more validation rules to it. There will be multiple implementations of EmployeeValidator

class BackOfficeStaffValidator implements EmployeeValidator {

    @Override
    public Predicate<Employee> build(Employee employee) {
        return EmployeeValidator.getCommonRules(employee).and(validationsOnDirectReports());
    }

    private Predicate<Employee> validationsOnDirectReports() {
        ...
    }
}

But the problem with this approach, at the client. I need conditional statements or switch case to select the proper implementation.

Employee employee = ...;

if(employee.staffType() == StaffType.TECHNICAL) {
    Predicate<Employee> build = new TechnicalStaffValidator().build(employee);
} else if(employee.staffType() == StaffType.BACK_OFFICE) {
    Predicate<Employee> build = new BackOfficeStaffValidator().build(employee);
}

is there a way to improve my current design? If the current approach is moving in the right direct suggest an alternate approach.

Question regarding the implementation of a connection pool

I was asked in an interview the below question. The code given to me is

interface Connection {
    void execute();
    void close();
}


interface ConnectionPool {
    Connection getConnection();
}

class Client {

    ConnectionPool connectionPool = new MyConnectionPool() ;

    Connection connection  = connectionPool.getConnection();

    public void execute() {
        try{
        connection.execute();
    }finally {
            connection.close();
        }
    }
}

class MyConnectionPool implements ConnectionPool {

    MyConnectionPool(List<Connection> connections) {

    }
    @Override
    public Connection getConnection() {
        return null;
    }
}

Here the implementation of the Connection is done by somebody else, I can only change the MyConnection pool class or create new classes. The issue is whenever the client call connection.close, the connection object is actually closed, the requirement is instead it should be added back to the connection pool which somebody else can use.

My implementation is like

class MyConnectionPool implements ConnectionPool {

    Queue<Connection> connections;

    MyConnectionPool(List<Connection> connections) {
        this.connections = new LinkedList(connections);
    }
    @Override
    public Connection getConnection() {
        MyConnection connection = new MyConnection(connections.poll(), this);
        return connection;
    }

    public void closeConnection(Connection connection) {
        connections.add(connection);
    }
}

class MyConnection implements Connection {


    Connection connection;
    boolean isClosed = false;
    MyConnectionPool connectionPool;

    MyConnection(Connection connection, MyConnectionPool connectionPool) {
        this.connection = connection;
    }

    @Override
    public void execute() {
        if (!isClosed){
            connection.execute();
        }
    }

    @Override
    public void close() {
        if (!isClosed) {
            connectionPool.closeConnection(this);
        }

    }
}

Is it correct ? Is there a better way to achieve the same.

Rust generic "component registration" pattern

I'm learning Rust, and am running up against a wall to do with managing ownership.

I have some different structs implementing trait Device (which actually simulate real hardware attached on a physical bus, with a generic interface). Each is assigned a unique id : u16. These Devices should all be a registered by their ID in a struct Controller. Sometimes the Controller is sent generic messages with an attached ID and generic command which the Device should perform (as accepted by the trait). I'd like to be able to be able to register different components on the fly, and all of the communication/mutation of the components should go through the Controller, so it seems natural to me that the Controller should own via Box<> es all of the registered components.

The problem is that there is a particular special device Pic implementing Device which should always be on the bus, i.e. registered in the Controller (in the real hardware, it is soldered on, not plugged into an expansion slot). The rest of the simulated hardware needs to be able to read and mutate the Pic directly by calling special functions only it has. At least this is implemented on the real hardware this way (wires go directly from these extra parts of the hardware directly to the Pic, bypassing the IO controller). But, once the Controller generically registers the Pic like any other object, it forgets its type and just knows it implements trait Device, so the other parts of the system can't access it anymore. I don't want my controller to have to know about the Pic specifically as a device, keeping a special space for one, and have special cases e.g. for looking it up as an ordinary device.

I think the natural thing to do is to keep the owner of the Pic somewhere else, and make the Controller not own any devices. Then problem is that the controller still needs to mutate the Devices sometimes, so would presumably need to register mutable references. Then the borrow-checker would prevent anyone else from obtaining a mutable reference to the Pic by any other means anyway.

(Obviously I need some kind of redesign here, but) my question is: How can I avoid this problem? I think I can store all my Devicees in RefCells just for the Pic's benefit but this seems like a bit of a hack (and incurs a runtime penalty).

Small Javascript Lib to draw SVG file

I'm new to JavaScript and I decided to make a script that allows other developers to show SVG elements in the web browser. (It is just for learning purpose), and it is still under development.

I code it in ES5 first and then I'm willing to upgrade it to ES6+ so I can learn and understand the difference.

I really appreciate your help to review it before I move forward and tell me what is wrong, what can I improve, if I used a design pattern in a wrong place... any help from you will be great.

So I tried to implement MVC pattern, inheritance, Factory pattern, function statement, function expression, IIFE ...

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="rasm.js"></script>
    <script src="app.js"></script>
</body>
</html>

src lib:

var modelController = function() {'use_strict';
    var createSVGElment = function(qualifiedName) {
        return document.createElementNS('http://www.w3.org/2000/svg', qualifiedName)
    };

    var Element = function(options) {
        this.element = null;
        this.style = options.style || '';
    };
    Element.prototype.buildElement = function() {
        this.element.setAttribute('style', this.style);
    };

    var Container = function(options) {
        Element.call(this, options);
        this.height = options.height || 700;
        this.width = options.width || 1200;
        this.element = createSVGElment('svg');
    };
    Container.prototype.buildElement = function() {
        Element.prototype.buildElement.call(this);
        this.element.setAttribute('width', this.width);
        this.element.setAttribute('height', this.height);
    };

    var Rectangle = function(options) {
        Element.call(this, options);
        this.height = options.height;
        this.width = options.width;
        this.x = options.x;
        this.y = options.y;
        this.text = options.text;
        this.element = createSVGElment('rect');
    };
    Rectangle.prototype.buildElement = function() {
        Element.prototype.buildElement.call(this);
        this.element.setAttribute('x', this.x);
        this.element.setAttribute('y', this.y);
        this.element.setAttribute('width', this.width);
        this.element.setAttribute('height', this.height);
    };

    var Ellipse = function(options) {
        Element.call(this, options);
        this.x = options.cx;
        this.y = options.cy;
        this.rx = options.rx;
        this.width = options.rx * 2;
        this.ry = options.ry;
        this.height = options.ry * 2;
        this.text = options.text;
        this.element = createSVGElment('ellipse');
    };
    Ellipse.prototype.buildElement = function() {
        Element.prototype.buildElement.call(this);
        this.element.setAttribute('cx', this.x);
        this.element.setAttribute('cy', this.y);
        this.element.setAttribute('rx', this.rx);
        this.element.setAttribute('ry', this.ry);
    };

    var Link = function(options) {
        Element.call(this, options);
        this.from = options.from;
        this.to = options.to;
        this.defsElement = createSVGElment('defs');
        this.element = createSVGElment('line');
        this.camputePath = function() {
            if (this.from instanceof Ellipse) {
                this.fromX = this.from.x + this.from.rx;
                this.fromY = this.from.y;
            } else {
                this.fromX = this.from.x + this.from.width;
                this.fromY = this.from.y + (this.from.height / 2);
            }

            if (this.to instanceof Ellipse) {
                this.toX = this.to.x - this.to.rx;
                this.toY = this.to.y;
            } else {
                this.toX = this.to.x;
                this.toY = this.to.y + (this.to.height / 2);
            }
        };
    };
    Link.prototype.buildElement = function() {
        var pathEelement = createSVGElment('path');
        pathEelement.setAttribute('d', 'M0,0 L0,6 L7,3 z');
        pathEelement.setAttribute('fill', '#000');

        var markerEelement = createSVGElment('marker');
        markerEelement.setAttribute('id', 'arrow');
        markerEelement.setAttribute('markerWidth', '10');
        markerEelement.setAttribute('markerHeight', '10');
        markerEelement.setAttribute('refX', '0');
        markerEelement.setAttribute('refY', '3');
        markerEelement.setAttribute('orient', 'auto');
        markerEelement.setAttribute('markerUnits', 'strokeWidth');

        markerEelement.appendChild(pathEelement);
        this.defsElement.appendChild(markerEelement);

        this.camputePath();
        this.element.setAttribute('x1', this.fromX);
        this.element.setAttribute('y1', this.fromY);
        this.element.setAttribute('x2', this.toX - 10);
        this.element.setAttribute('y2', this.toY);
        this.element.setAttribute('stroke', '#000');
        this.element.setAttribute('stroke-width', '2');
        this.element.setAttribute('marker-end', 'url(#arrow)');
    };

    var Text = function(options) {
        Element.call(this, options);
        this.x = options.x;
        this.y = options.y;
        this.value = options.value;
        this.element = createSVGElment('text');
    };
    Text.prototype.buildElement = function() {
        Element.prototype.buildElement.call(this);
        this.element.setAttribute('x', this.x);
        this.element.setAttribute('y', this.y);
        this.element.textContent = this.value;
    };

    // Element factory
    function ElementFactory() {};
    ElementFactory.prototype.createElement = function(o) {
        switch(o.type) {
            case 'container':
                this.elementClass = Container;
                break;
            case 'rect':
                this.elementClass = Rectangle;
                break;
            case 'ellipse':
                this.elementClass = Ellipse;
                break;
            case 'link':
                this.elementClass = Link;
                break;
            case 'text':
                this.elementClass = Text;
                break;
            default:
                throw 'Warning: the type ' + o.type + ' is invalid';
        }
        return new this.elementClass(o);
    };
    var elementFactory = new ElementFactory();

    // storing register
    var register = {
        eltSVG: null,
        elts: []
    };

    return {
        registerElement: function(options) {
            var el = elementFactory.createElement(options);
            if (options.type === 'container') {
                register.eltSVG = el;
            } else {
                register.elts.push(el);
            }
            return el;
        },

        getRegister: function() {
            return register;
        },
    };
}();

var viewController = function() {'use_strict';
    return {
        displayElement: function(el) {
            var selector = el.element.tagName === 'svg' ? 'body' : 'svg';
            el.buildElement();
            if (el.defsElement) { // for line element
                document.querySelector(selector).appendChild(el.defsElement);    
            }
            document.querySelector(selector).appendChild(el.element);
        },
    };
}();

(function(global, model, view) {'use_strict';
    function processText(el, o) {
        if (['above', 'inside', 'below'].indexOf(o.text.position) < 0) {
            throw "Text position must be: above, inside or below and not " + o.text.position;
        }
        var x, y;

        if (el.element.tagName === 'rect') {
            x = el.x + (el.width * 0.1) // 20% of the width
            if (o.text.position === 'above') {
                y = el.y - 5;
            } else if (o.text.position === 'inside') {
                y = el.y + (el.height / 2);
            } else if (o.text.position === 'below') {
                y = el.y + el.height + 20;
            }
        } else { // ellipse 
            x = el.x - (el.rx * 0.2)
            if (o.text.position === 'above') {
                y = el.y - el.ry - 5;
            } else if (o.text.position === 'inside') {
                y = el.y;
            } else if (o.text.position === 'below') {
                y = el.y + el.ry + 20;
            }
        }

        return {
            x: x,
            y: y,
        }
    };

    global.$R = global.Rasm = {
        draw: function(options) {
            if (options.type !== 'container' && !model.getRegister().eltSVG) {
                throw 'You must create an svg element first';
            }
            var el = model.registerElement(options);
            view.displayElement(el);

            // process text option
            if (options.text) {
                var textCoord = processText(el, options);
                var text = model.registerElement({
                    "type": "text",
                    "x": textCoord.x,
                    "y": textCoord.y,
                    "value": options.text.value,
                });
                view.displayElement(text);
            }
            return el;
        },
    };
})(window, modelController, viewController);

An example of how we can use it:

$R.draw({
    "type": "container",
    "height": 700,
    "width": 1100,
});

/** Left side */
var rect1 = $R.draw({
    "type": "rect",
    "x": 20,
    "y": 20,
    "width": 345,
    "height": 648,
    "style": "stroke-dasharray: 5.5; stroke: #006600; fill: #fff"
});
var rect2 = $R.draw({
    "type": "rect",
    "x": 50,
    "y": 100,
    "width": 250,
    "height": 100,
    "text": {
        "position": "inside",
        "value": "I'm a text inside a rectangle"
    },
    "style": "stroke: #006600; fill: #fff"
});
var rect3 = $R.draw({
    "type": "rect",
    "x": 50,
    "y": 300,
    "width": 250,
    "height": 100,
    "text": {
        "position": "above",
        "value": "I'm a text above a rectangle"
    },
    "style": "stroke: #006600; fill: #fff"
});
var rect4 = $R.draw({
    "type": "rect",
    "x": 50,
    "y": 500,
    "width": 250,
    "height": 100,
    "text": {
        "position": "below",
        "value": "I'm a text below a rectangle"
    },
    "style": "stroke: #006600; fill: #fff"
});

/** Right side */
var rect5 = $R.draw({
    "type": "rect",
    "x": 700,
    "y": 20,
    "width": 345,
    "height": 648,
    "style": "stroke-dasharray: 20; stroke: #006600; fill: #fff"
});
var ellipse1 = $R.draw({
    "type": "ellipse",
    "cx": 870,
    "cy": 200,
    "rx": 150,
    "ry": 70,
    "text": {
        "position": "above",
        "value": "I'm a text above an ellipse"
    },
    "style": "stroke: #129cc9; fill: #b5e5f5"
});

var ellipse2 = $R.draw({
    "type": "ellipse",
    "cx": 860,
    "cy": 500,
    "rx": 100,
    "ry": 70,
    "text": {
        "position": "inside",
        "value": "I'm a text inside an ellipse"
    },
    "style": "stroke: #129cc9; fill: #b5e5f5"
});

/** Links */
$R.draw({
    "type": "link",
    "from": rect2,
    "to": ellipse2,
});
$R.draw({
    "type": "link",
    "from": rect3,
    "to": ellipse1,
});
$R.draw({
    "type": "link",
    "from": rect4,
    "to": ellipse1,
});

I hope you concentrate only on the lib structure and code, the SVG example that I took is just to be able to practice what I have learned.

I need to implement different workflow depending on type of file dropped in screen, and I want to avoid multiple if-else [closed]

https://springframework.guru/service-locator-pattern-in-spring/ I have taken reference from above article to implement in java but I am not able to find anything simliar in angular.

How to implement iterator design pattern on C++?

I'm curious about how to implement the iterator pattern the way STL does in a stack ADT.

#include <iostream>
#include <vector>

int main() {
    std::vector<char> v = { 'a', 'b', 'c', 'd', 'e', 'f'};

    std::vector<char>::iterator it = v.begin();

    while(it != v.end()) {
        std::cout << *it << "->";
        ++it;
    }

    std::cout << "\n";

    return 0;
}

Output

a->b->c->d->e->f->

so far I have implemented the following code

#include <iostream>
#include <memory>

template<class T>class Node {
private:
    T data = 0;
    std::shared_ptr<Node<T>> next_node = nullptr;

public:
    Node(T data = 0, std::shared_ptr<Node<T>> next_node = nullptr)
        : data(data), next_node(next_node)
    {
        std::cout << "created node[" << data << "]\n";
    }

    ~Node() {
        std::cout << "deleted node[" << data << "]\n";
    }

    // getters and setters

    T getData() const {
        return this->data;
    }

    std::shared_ptr<Node<T>> getNextNode() const {
        return this->next_node;
    }

    void setData(T value) {
        this->data = value;
    }

    void setNextNode(std::shared_ptr<Node<T>> node) {
        this->next_node = node;
    }
};

template<class T>std::ostream& operator<<(std::ostream& o, const std::shared_ptr<Node<T>> node) {
    return o << "node["<< node->getData() <<"]-> ";
}

template<class T>class Stack {
private:
    std::shared_ptr<Node<T>> top = nullptr;

public:
    Stack()
        : top(nullptr)
    { /* empty */ }

    ~Stack() { /* empty */ }

    void push(T value) {
        if(!top) {
            top = std::shared_ptr<Node<T>> (new Node<T>(value));
        } else {
            top = std::shared_ptr<Node<T>> (new Node<T>(value, top));
        }
    }

    void display() {
        if(!top) {
            std::cout << "display::The stack is empty.\n";
        } else {
            std::shared_ptr<Node<T>> p = top;

            while(p) {
                std::cout << p;
                p = p->getNextNode();
            }

            std::cout << "\n";
        }
    }

    class Iterator {
    private:
        std::shared_ptr<Node<T>> node;

    public:
        Iterator(std::shared_ptr<Node<T>> node)
            : node(node)
        { /* empty */ }

        bool hasMore() {
            return node->getNextNode() != nullptr;
        }

        Iterator getNext() {
            return Iterator(node->getNextNode());
        }

        int getData() {
            return node->getData();
        }
    };

    Iterator begin() const {
        return Iterator(top);
    }

    Iterator getIterator() {
        Iterator it = Iterator(top);

        return it;
    }
};

int main() {
    Stack<char> stack;

    for(char i = 'a'; i < 'f'; ++i) {
        stack.push(i);
    }

    Stack<char>::Iterator it = stack.begin();

    while(it.hasMore()) {
        std::cout << it.getData() << "->";
        it = it.getNext();
    }

    std::cout << "\n";

    return 0;
}

Output:

created node[a]
created node[b]
created node[c]
created node[d]
created node[e]
101->100->99->98->
deleted node[e]
deleted node[d]
deleted node[c]
deleted node[b]
deleted node[a]

My question is how to implement nested template detection for the Iterator class, as you can see the expected output is a char type and I am getting integers.

Can someone help me understand how this is implemented in the STL and how it could be implemented in an ADT?

thanks!!!

mardi 28 avril 2020

Implementing Pattern in Java to Call Method Dynamically at Runtime

I am trying to wrap my head around the implementation of a Strategy pattern in Java, as I believe it is the implementation I need to get the desired behavior. I have a method called chooseAction() that accepts a single parameter that denotes the state of the world at a specific time. Let's say it contains information about the current level of traffic and the weather, as well as the current time. Depending on the Time enum and a Person's availableActions list, a Person can perform different actions. However, each action needs its own individual choose method that returns a boolean denoting whether or not they will do it. A Person would have different reasons to choose whether or not to go to work than brush their teeth.

This is what I currently have.

public enum Action{
GO_TO_WORK{
    @Override
    public TimeList getTimes() {
        return new TimeList(Time.MORNING);
    }, 
BRUSH_TEETH{
    @Override
    public Time getTimes() {

        return new TimeList(Time.MORNING, Time.NIGHT);
    }, 
WATCH_TV{
    @Override
    public Time getTimes() {
        return new TimeList(Time.MORNING, Time.EVENING);
    };
}

public class Person{

final static List<Action> availableActions; //Contains an unchanging list of actions a Person can do 

public List<Action> chooseAction(WorldState worldState)
{
     Time time = worldState.getTime(); //Get the current time
     List<Action> validActions = getAvailableActions(time); //Actions the Person can do now
     List<Action> chosenActions = 
     for (Action a : validActions) {
        switch (a) {
        case BRUSH_TEETH:
            if (chooseToBrushTeeth(this, worldState))
                chosenActions.add(a);
            break;
        case GO_TO_WORK:
            if (chooseToGoToWork(this, worldState))
                chosenActions.add(a);
            break;
        case WATCH_TV:
            if (chooseToWatchTV(this, worldState))
                chosenActions.add(a);
            break;
        default:
        }
    }
    return chosenActions;
}
public List<Action> getAvailableActions(Time time)
{ 
     List<Action> validActions = new ArrayList<>();
     for(Action a: availableActions)
     {
        if(a.getTimes().contains(time))
        {
           validActions.add(a);
        }
     }
     return validActions;
}

public enum Time{

MORNING, AFTERNOON, EVENING, NIGHT;

}

public class TimeList{

public TimeList(Time... time) {
    for (Time t : times) {
        this.add(t);
    }
}

The individual choose methods return either true or false depending on the parameters of the state of the Person and the WorldState object. The exact specifications of these methods and the WorldState class are unimportant to this problem. What I'm trying to do is apply a Strategy pattern or a similar design pattern so that I can remove the inefficient switch/case and much of the redundancy. The tricky part is that I cannot simply use inheritance to make different objects for each Action and have them call their own choose method. This is because the Actions do not make the choice, the Person does. I want to design it so that, for instance, I can have a LazyPerson and an ActivePerson who can potentially choose differently when GO_TO_WORK is a valid action, even if the WorldState is the same.

I think I'm close to understanding it, but I'm not quite there yet. Any help would be greatly appreciated.

How can I initialize an object of type interface with a constructor from a class that implements the parent interface?

I have interface Worker, interface Painter that extends Worker and Person that implements Worker. How do I create a Person that is also a Painter?

Do I have to create a subclass from Person?

Why does

Painter painter = new Person();

not work?

String pattern detection

I want to turn a string into a html tag with a specified pattern like this:

Walking in the !boldstreet

I want to detect the !bold in the string and turn the following word into "<b>street</b>".

    String s = "Walking in the !boldstreet" 
    String result = null;
    String[] styles = {"!bold", "!italic", "!deleted", "!marked"};
    String[] tags = {"b", "i", "del", "mark"};
    List<String> indexer = new ArrayList<String>(Arrays.asList(tags));
    int index = 0;
    for (String x: styles) {
        if (s.startsWith(x)) {
            result = style(s, indexer.get(index));
            break;
        }
        index++;
    }
    if (result == null) result = s; //there was no formatting


    return result;

      //style method
      public String style(String text, String tag) {
    return "<" + tag + ">" + text + "</" + tag + ">";
}

This works but when i pass something like this to it: "Walking !deletedin the !boldstreet"

only it will turn !boldstreet into html tags. How can i make it turn everything like those into html tags?

Access to private member of a class only inside a class that has an instance of that class

I'm implementing a Linked List. I have two classes Node and SingleLinkedList. Now I need to access a private member of the Node class from the SingleLinkedList class but outside I would this wasn't possible; in this way I can return a Node instance from SingleLinkedList and the users can't accede all the data structure with that Node. In Java when a class has a object of another class (composition) can do this, in C++ there are friend classes. How can I do this in Javascript?

The following is a "example toy" that I'm implementing to test my knowledges acquired so far and to see what problems come up

class Node {
         next = null;
         constructor(value) {
            this.value = value;

         }
      }

      class SingleLinkedList {
         #size = 0;
         #head = null;
         #tail = null;

         // read only get accessor property
         get size() {
            return this.#size;
         }

         isEmpty() {
            return this.#size === 0;
         }

         // insert a new Node (in tail) with the desired value
         push(value) {
            const node = new Node(value);

            if (this.isEmpty()) {
               this.#head = node;
            } else {
               this.#tail.next = node;
            }

            // the following instructions are common to both the cases.
            this.#tail = node;
            this.#size++;

            // to allow multiple push call
            return this;
         }

         pop() {
            if (this.isEmpty())
               return null;

            let current = this.#head;
            let newTail = current;
            while (current.next) {
               newTail = current;
               current = current.next;
            }
            this.#tail = newTail;
            this.#tail.next = null;
            --this.#size;
            if (this.isEmpty()) { //There was only 1 element
               this.#head = null;
               this.#tail = null;
            }
            return current.value;
         }

         //Remove one element from the head
         shift(){
            if(this.isEmpty())
               return null;

            let val = this.#head.value;
            this.#head = this.#head.next;
            this.#size--;
            return val;
         }

         //Insert the passed element in head
         unshift(value){
            let currentHead = this.#head;
            this.#head = new Node(value);
            this.#head.next = currentHead;
            this.#size++;
            return this; //allow multiple call
         }

         //Return the element at the specified index
         get(index){
            if(index<0 || index>=this.#size)
               return null;

            let current = this.#head;


            return current.value;
         }

         //Set the item at specified index with the specified value
         //Return a boolean value
         set(index,value){
            if(index<0 || index>=this.#size)
               return false;

            let current = this.#head;
            for(let i=0 ; i<index ; current = current.next,++i)
               ;
            //At the end of the above for current will contain the right node
            current.value = value;
            return true;    
         }

         //Insert the node with the specified value at the
         //position(if index === 2 insert the node between the second and
         //the thirth node). Return a boolean
         insert(index,value){
            if(index <0 || index > this.#size)
               return false;
            if(index===0)
               this.unshift(value);
            if(index===this.#size)
               this.push(value);


         }
         // generator to return the values
         *[Symbol.iterator]() {
            for (let current = this.#head; current; current = current.next) {
               yield current.value;
            }
         }

         // the values of each node
         toString() {
            return [...this].join(' ');
         }
      }

      const myLinkedList = new SingleLinkedList();
      myLinkedList.push(3).push(5);
      console.log(myLinkedList.toString());

For example if I make private the nextproperty of the class Node
I can't anymore access the variable inside my SingleLinkedClass. Instead if I leave the code like that and I return a Node instance from some function the user can accede almost all my structure using the next property. Does it exist some , possibly simple, solution in Javascript?

Detect the presence or absence of a string in a pattern with Python

I'm a beginner in python coding. I need a hand to find an elegant way to do this:

I've got the following dataframe :

  pattern  nb
1   a,b,c  150
2       b  100
3     c,b  30
4       c  10

According to the presence of string, I want a dataframe like that :

  pattern   nb    a    b     c
1   a,b,c   150   150  150   150
2       b   100   0    100   0
3     c,b   30    0    30    30
4       c   10    0    0     10

Many thanks in advance.

Greetings from France

Arnaud

Java Class Collect All Child Attributes

I want to create a class that may have its children attributes. For example:

public class Parent {
    private String a;
    private String b;
}
public class ChildA extends Parent {
    private String c;
    private String d;
}
public class ChildB extends Parent {
    private String e;
    private String f;
}

How could Parent have attributes of ChildA when ChildA is passed and ChildB when ChildB is passed? It may be done by get it as a plain Object, however how to do it in more OOP way?

Suggestion for software architecture for event management software using modern technology

I have been a .net developer and know asp.net, vb.net, c#, javascript, html, css, sql and some other technologies. I can understand software pattern and practices and have coded some apps using 3 tier architecture.

However, I am in to project management now but want to enhance my skills using some modern tech. I have some introduction about cloud, microservices, AWS, angular etc but do not have much detailed knowledge (like JS, asp.net ,SQL).

I am planning to build an event management system which would basically have an event organizer log in and setup events and then have the end user login using google/facebook and subscribe and purchase for events.

I MUST have the mobile version of this app (ofcourse along with the web version). The project looks very simple and i could easily code this in 2/3 tier with asp.net, SQL and JS but i would want to have application features as below and learn new tech. for myself :

  1. no downtime of application (may be i can utilize the cloud but need to know in depth)
  2. dynamic scaling of the apps - if a particular event has more selling of tickets or higher volume, i do not want to get additional RAM or space on server. it should auto-scale (i believe AWS/Azure might have something on this but i am not aware).
  3. open source is welcome, I know asp.net hosting on IIS on AWS would cost rather than asp.net/nodejs on linux box on AWS, same goes for database.

Please suggest me the rights architecture. I thought of : SQL as DB (open to any other SQL/NoSQL database as well) asp.net core microservices for business rules angular + css + html + android UI + iphone UI as fron tend which would make calls to microservice APIs.

Please Suggest. Thanks

How to draw pattern using Java according to a given number [closed]

I am trying to write a program that draws the following pattern depending on an input number: exampe: input:
3 result:
0****1
23**45
678901

ex: imput:
5:
Result:
0********1
23******45
678****901
2345**6789
0123456789

just to be clear: The input number represents how many rows, and multiplicating the input by 2 is the number of the digits. the (*) should separate 2 digits in the first raw and then 4 digits in the second, etc...

Thank you all in advance

Python - Flask ImportError: cannot import name 'Userauth' from 'models'

I learn to made apps in Flask, I got an error cz I think I made an circular import but I am not sure and really new in Flask. I have this in application.py:

application = Flask(
    __name__, static_folder="client/build", static_url_path="/client/build"
)

DB = SQLAlchemy(application)
jwt = JWTManager(application)

from models import Userauth, Product

...

if __name__ == "__main__":
    from models import Userauth, Product
    application.run()

I know that looks weird because double command from models import Userauth, Product, but if I just write the second command (before application.run()) I got an error to running flask run

my model.py:

from application import DB

class Userauth(DB.Model):
...

class Product(DB.Model):
...

If I run python application.py I got this error:

(venv) /% python application.py
Traceback (most recent call last):
  File "application.py", line 28, in <module>
    from models import Userauth, Product
  File "//models.py", line 1, in <module>
    from application import DB
  File "//application.py", line 28, in <module>
    from models import Userauth, Product
ImportError: cannot import name 'Userauth' from 'models' (/models.py)

Do you know how to deal with this problem? How is the good design pattern in Flask apps should be?

Thank you.

To understand %*d and if (( scanf( "%d", &n ) != 1 ) || ( n <= 0 )) in c

I have to print this pattern in c

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

And I found this code associated with it

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int main()  
{ 
    while ( 1 ) 
    { 
        printf( "Enter a non-negative number (0 - exit): " ); 

        int n; 

        if ( ( scanf( "%d", &n ) != 1 ) || ( n <= 0 ) ) break; 

        if ( INT_MAX / 2 < n )  
        { 
            n = INT_MAX / 2; 
        } 

        int width = 1; 

        for ( int tmp = n; tmp /= 10; ) ++width; 

        putchar( '\n' ); 

        int m = 2 * n - 1; 

        for ( int i = 0; i < m; i++ ) 
        { 
            for ( int j = 0; j < m; j++ ) 
            {
                int value1 = abs( n - i - 1 ) + 1;
                int value2 = abs( n - j - 1 ) + 1;

                printf( "%*d ", width, value1 < value2 ? value2 : value1 );
            } 
            putchar( '\n' ); 
        } 

        putchar( '\n' ); 
    } 

    return 0; 
 }

I want to know why in this statementscanf( "%d", &n ) != 1 is used

if (( scanf( "%d", &n ) != 1 ) || ( n <= 0 ));

and also how single format specifier is accepting two values here

printf( "%*d ", width, value1 < value2 ? value2 : value1 );

Why % and * are used together"%*d"??

Springboot application Controllers Designing

i am kind of new with programming, i need help with designig the RestControllers. I am trying to design a website Using spring boot, the site supposed to have Guests, Users(registerd), Admin, SuperAdmin. would it be true to use the GuestController as the main one, and let all of the other controllers such as Admin,User,Superadmins extend the GuestController? Thanks

How can I write a Print method for variable arguments without templates?

int temp=10;
string tempStr="hello";
LOG("test num:", temp, ", str:", tempStr);

#define LOG(...) Logger::getInstance().Print(__VA_ARGS__)

I already know how I make Print using template. But I wonder that can I make Print without template? Is it impossible? Beacuse I want to make Print method from virtual function.

class Logger : public ILogger
{
public:
virtual void Print(...) override
{
// what should I do in here?
}
}

    class ILogger
    {
    public:
    virtual void Print(...) =0;
    }

lundi 27 avril 2020

Not able to distinguish injectable objects in the Bridge design pattern with Spring boot framework

I am not sure how I can inject the abstract class and its extensions in the bridge design pattern in Spring. Let's consider the classic bridge design pattern example of shape:

Color.java

public interface Color {

  String fill();
}

Blue.java

@Service("Blue")
public class Blue implements Color {
  @Override
  public String fill() {
    return "Color is Blue";
  }
}

Red.java

@Service("Red")
public class Red implements Color {
  @Override
  public String fill() {
    return "Color is Red";
  }
}

Shape.java

public abstract class Shape {
  protected Color color;

  @Autowired
  private Something something;

  @Value(${foo.bar})
  private String fooBar;

  public Shape(Color color){
    this.color = color;
  }

  abstract public String draw();
}

Square.java

public class Square extends Shape {

  public Square(Color color) {
    super(color);
  }

  @Override
  public String draw() {
    return "Square drawn. " + color.fill();
  }
}

Triangle.java

public class Triangle extends Shape {

  public Triangle(Color color) {
    super(color);
  }

  @Override
  public String draw() {
    return "Triangle drawn. " + color.fill();
  }
}

BridgeApplication.java

@SpringBootApplication
public class BridgeApplication {
  public static void main(String[] args) {
    SpringApplication.run(BridgeApplication.class, args);
  }
}

Controller:

@RestController
public class BridgeController {

  @Autowired
  @Qualifier("Red")
  private Color red;

  @GetMapping("/red")
  @ResponseStatus(HttpStatus.OK)
  public String redSquare() {
    Shape square = new Square(red);
    return square.draw();
  }

}

The problem arises when we would like to inject the abstract class Shape or its extensions like Square or Triangle. Because of the fact that constructor accepts a Color object and we cannot decide if the Color is a type of Red or Blue (That's the whole point of using Bridge design pattern here) then we cannot define Shape or its extensions to be a Spring Bean because there will be multiple beans of the type Color available. The easy workaround is like what I did to construct the object directly instead of injecting it. However, now there will be all challenges regarding any value I am injecting or any other Bean I would like to inject in the Shape class or its extensions (like fooBar or something) because the corresponding classes are constructed manually.

One solution is to start dealing with the manual injection that will create a lot of unnecessary complexity with the value and bean injections and it's not a clean solution at all. Like this or referring to this question. So I was wondering if there is a clean way of having some form of Bridge design pattern in the Spring framework or due to the Spring limitations, there is none.

Keeping Startup clean with options and multiple Jwt bearers

I am trying to keep the Startup as clean as possible. The API receives a JWT token currently only from Google (but in future also Apple I think) but I allow to specify multiple IdPs, you can place it into the config file.

When a user logs in, I check if it is already registered, if no I save user details, in both cases I exchange the token with a self-issued Jwt (it is like a flag, if you have my token I am sure you are in my database).

I am avoiding doing manual (with the libraries) checks on the Jwt token, I have created a policy that excludes self-issued Schema on the login endpoint.

Now the problem: how I can add multiple Schemas with named options? This is my current code:

Startup.cs

services.AddAuthentication().AddJwtBearer();
services.ConfigureOptions<ConfigureAuthenticationOptions>();
services.ConfigureOptions<ConfigureJwtBearerOptions>();

services.AddAuthorization();
services.ConfigureOptions<ConfigureAuthorizationOptions>();

ConfigureJwtBearerOptions.cs

using MakersPortal.Core.Dtos.Configuration;
using MakersPortal.Core.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace MakersPortal.WebApi.Options
{
    public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
    {
        private readonly IKeyManager _keyManager;
        private readonly JwtIssuerDto _issuer;

        public ConfigureJwtBearerOptions(IKeyManager keyManager, JwtIssuerDto issuer)
        {
            _keyManager = keyManager;
            _issuer = issuer;
        }

        public void Configure(JwtBearerOptions options)
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _keyManager.GetSecurityKeyFromName("jwt").Result,

                ValidIssuer = _issuer.Issuer,
                ValidateIssuer = true
            };

            options.Audience = _issuer.Audience;
            options.SaveToken = true;
        }

        public void Configure(string name, JwtBearerOptions options)
        {
            Configure(options);
        }
    }
}

Correct design pattern and technology to map functions to each other

Abstract:

I'm attempting to create a "data interoperability API" or in other terms "high-level query interface API" that will be consumed by (data scientists, web apps, any who wants to query multiple datasets).

Assumptions:

The underlying data will usually be in these formats:

1) Best case scenario - XML (with proper XSD). • the XML serves as meta-data that describes (where that data resides, file, web service,etc... field descriptions) • points to delimited data (CSV) or even binary data

OR

2) Just plain XML as meta-data (NO XSD).

• the XML serves as meta-data that describes (where that data resides, file, web service,etc... field descriptions) • points to delimited data (CSV) or even binary data

OR

3) Plain data (CSV no headers)

This API will be provided as distributable (In case of Java a JAR, or Python extension) that can be loaded by consumer applications.

Progress so far:

1) Im able to load XSD using JAXB for Java and PyXB for Python version and generate class based on XSD info. Im calling “xjc” as system process via Java :

   ProcessBuilder processBuilder = new ProcessBuilder(CMD_ARRAY)Process process = processBuilder.start();

2) Im able to also bind objects & data in memory and issue (what I call “native queries”).

 //1. instance 
            jaxbContext = JAXBContext.newInstance(clazz);
            //2. Use JAXBContext instance to create the Unmarshaller.
            unmarshaller = jaxbContext.createUnmarshaller();
            //3. Use the Unmarshaller to unmarshal the XML document to get an instance of JAXBElement.
            inStream = new FileInputStream( this.xmlFile);
            OaisInteropFrameworkStates.setState(OaisInteropFrameworkStates.STATE_LOAD_NATIVE_API);
            returnedObject  = unmarshaller.unmarshal(inStream);

3) Next step (High level Public API mapping) - What I need advice on , see the diagram below (Everything black boxes are tested and working refer to the red shapes).

High level data flow architecture:

enter image description here

Actual question 1) What is the best design pattern approach, in order to automatically map/wrap different functions?

Assumptions:

1) (User native to public mapping) - The user MUST provide a XML (or maybe JSON) 1 to 1 mapping of function signatures

2) The mapped function will always return a String

3) Native API must be decoupled from Public API and they have no knowledge of each other. (except via the mapping file or any auto-generated code based on the xml mapping file. Similar to client & server interfaces.

4) I have very limited time to work on this project, 8-10 hours per week. Therefore simplicity over elegance/

Some thoughts:

I was looking at XML-RPC Python (https://docs.python.org/3/library/xmlrpc.client.html#module-xmlrpc.client) or Java (https://www.tutorialspoint.com/xml-rpc/xml_rpc_examples.htm).

2) Also REST-RPC, or some other service-oriented architecture.

3) Have the user create XSD that maps the function endpoints and use JAXB (Rather not, XSD is too verbose, and these days Python minded scripting people will hate that...)

I like the approach were XML-RPC uses a similar mapping xml:

Request:

<?xml version="1.0" encoding="ISO-8859-1"?>
<methodCall>
   <methodName>sample.sum</methodName>
   <params>
      <param>
         <value><int>17</int></value>
      </param>

      <param>
         <value><int>13</int></value>
      </param>
   </params>
</methodCall>

Response:

<?xml version="1.0" encoding="ISO-8859-1"?>
<methodResponse>
   <params>
      <param>
         <value><int>30</int></value>
      </param>
   </params>
</methodResponse>

Thanks a million!

PHP Singleton as CallBack for HTTP Request in HTTP Server

I want to know if there will be any synchronization / concurrency related issues ? if we serve a "request" event (in HTTP Server like swoole) using a "Singleton" as "callback to the request event". In other words the callback that serves the request first create a singleton object (if it does not already exists.

I am creating singleton on "request" event of HTTP Server (Swoole). The static member which is used to created single instance also calls a non-static member of the (same) singleton object, in addition. This non-static member actually serves the request.

$http->on('request', 'Bootstrap::getInstance');

//Singleton

class Bootstrap{

  protected static $instance;

  private function __constructor(){  
         //initialize Phalcon Micro Routers and Events to fuse with Swoole
  } 

  public static getInstance($htpRequest, $httpResponse) {
       if (!$instance) { 
         self::$instance = new Bootstrap();
       }
       //Also call the non-static member to serve "request"
       self::instance->run($htpRequest, $httpResponse);
    }

  //non-static function to serve request
  public function run(httpRequest, httpResponse) {
      // Serve Request
  }

}

PHP Regex patern, KODI season poster extractor

In kodi Database, table tvshow, column C06 we have this kind of data :

<thumb aspect="poster">http://image.tmdb.org/t/p/original/xjm6uVktPuKXNILwjLXwVG5d5BU.jpg</thumb>
<thumb aspect="poster" type="season" season="6">http://image.tmdb.org/t/p/original/5msClP3ba8iOHvpuZjU6NyzwEB7.jpg</thumb>
<thumb aspect="poster" type="season" season="3">http://image.tmdb.org/t/p/original/xG6kJnvmGme2ZgLZASFrI1PFUnY.jpg</thumb>

I would like with a regex pattern, to extract the http:// link :

1st case -> aspect="poster" => what is the general poster of the TV show
2nd case -> season="X" => Where X is the number of the season poster i want to get

I can't get answer for this problem, i found some regex but they just extract all link, it's not possible to filter as i need, like this one :

preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $TVShowPosterString, $match);

Best regards,

S.

Making a diamond with a line in the middle c#

So I need to make a program that will print out a diamond shape with a line in the middle, the side is equal to the line, and the user inputs that value. I've tried to do it but can I can only print out a diamond without the line, or to make it in pieces, one hollow pyramid and one inverted hollow pyramid, but with that, I get a shape with 2 lines in the middle, any help is crucial!

example: input 5

output:

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

Creates string parser to parse nested structures

I'm looking for information how to create parser to parse a strings like this:

[1,2,"abc",[2.2345,76,"n"],["abc",1,"c"],23,44]

Every value (number, decimal, string, null) in square brackets separated by comma and in brackets can be nested another square brackets with any number of values.

I need to create it in Java.

Q: Is there some library, algorithm / design strategy / design pattern, how to create such parser?

Microservices design part in WebApi

Hi I am trying to create a project skeleton uses CQRS pattern and some external services. Below are the structure of the solution.

  • WebApi
  • Query Handlers
  • Command Handlers
  • Repository
  • ApiGateways ( here is the interfaces and implementation of microservice calls)

We want to keep controller as thin. So we are using query handlers and command handlers to handle respective operations.

enter image description here However, we use a external microservices to get the data we are calling them from Query handlers. All the http clinet construction and calls will be abstracted in them.The response will be converted to a view model and pass it back to Query handler.

We name it as a ApiGateways. But it is not composing from multiple services. How do we call this part in our solution? Proxy or something? Any good example for thin controllers and microservice architecture

Design pattern to avoid passing unecessary parameters?

In my current project i defined the following interface:

public interface CmdExecutor {
    void execute(String[] tokens, OutputStream outputStream, List<ServerWorker> serverWorkers) throws IOException;
}

Every CmdExecutor needs tokens and outputStream but after the executon of his job, I need to update some information in List<ServerWorker>.

There is some design-pattern that can help me to avoid passing to every worker this List? I've heard about using an "event bus", there is some other option other than this approach?

Thank you

how can practice my knowledge in oop, data structure and design pattern to study new mobile app cross platform like xamarin

Stupid question, but I like programming and please help ... I studied lesson of: C ++ , pointers; c #; oop; datastructure and alogorithm; and design pattern. However, when I wanted to enter the mobile applications on xamarin, I did not benefit from what I studied previously. The question is how do I watch strucure of xamarin to understand how these many functions contain. Thanks and sorry because my English is not excellent.

what's the difference between proxy and repository pattern

repository pattern, heavily used in Entity Framework, which is a class has a repository field(normally injected by DI), so whatever you do save, delete,update a record, you let the repository instance do it like

_repository.delete("someID");

so isn't that the same thing that proxy pattern try to achieve? In proxy pattern, you also have a proxy instance, and let this instance does the job for you.

so what's the difference between proxy and repository pattern

dimanche 26 avril 2020

Design Pattern for Adding items to GamePlayer

I am working on designing a toy game project where I have characters in the game. Characters can carry items in Satchels or boxes. The boxes can carry items like gold coin, magical ring etc while Satchels can contain food item, books etc.

What design pattern can I use to provide items to players such that I can enforce certain items can only be put in Satchels and not boxes. I don't need the code, just give me some direction how I can implement such design.

Any suggestion would be highly appreciated.

Autofac multiple implementation of same interface and implements are called in a if logic

I have an interface called ibaseinterface using which I have created 2 classes lets say baseclass1 and baseclass2.

Now I have a class named as top-level as below

public class toplevel
{
    public ibaseinterface selection(string selection)
    {
        int.TryParse(selection, out int sel);
        if (sel < 2)
            return new baseclass1();
        else
            return new baseclass2();
    }
}

based on user input I select the class that needs to be called. so how do I resolve the dependencies, in this case, using autofac.

Note: I definitely can't have different interfaces for the base classes.

Cast the static types of n Implementations of an Abstract Class to correspond with their dynamic Type - with at least code as possible

I have a library that works with Actors. An interface for Actor implementation is defined in the abstract class Actor and the actor-library works with Actor*, but in order to use another library I need to implement static functions for each class, and my actor-library naturally thinks every implementation has the static class of Actor, so in order to solve this problem I created the following variant of pointers and a wrapper for an example situation:

ActorImpls = std::variant<
    ActorType1*,
    ActorType2*,
    ActorType3*,
    ActorType4*,
>;

And a cast function that reinterprets the static type to be the same of the dynamic type through checking a dynamic member field:

  ActorImpls staticCorrespond2Dynamic(Actor* cl){
             std::string s = cl->getDynamicName();
                if(s.compare("Dynamic ActorType1")==0){
                    ActorType1* x = reinterpret_cast<ActorType1*>(cl);
                ...

Now I can call static functions for the given ActorImpls with a visitor, but i will always call the function with the same name, it will be ActorType1->staticFunc() or ActorType2->staticFunc(), is there a way to make the wrapper work with less code?

The visitor looks something like this for a static-print-func:

struct VisitPrintStatic{
        VisitPrintStatic() {}
        void operator()(ActorType1* x){x->printStaticName();}
        ...

What else I have tried: implementing with variadic templates, the main problem is that getting the any info on runtime makes is almost impossible to work with. There are the folowing types of functions to consider, they have the same name through all actors:

Actor* ActorX = new ActorTypeX;
ActorX->staticFunc() //where ActorTypeX must be reinterpreted from Actor* to ActorTypeX*
ActorTypeX::staticFunc(ActorTypeX& obj, Args...) //(same as above)

Why inheritance is usually used instead of composition when implementing the observer pattern?

#include <iostream>
#include <set>

class Observer
{
public:

    virtual void update() = 0;
};

class Subject
{
    std::set<Observer*> observers;

public:

    void addObserver(Observer* observer)
    {
        observers.insert(observer);
    }

    void deleteObserver(Observer* observer)
    {
        observers.erase(observer);
    }

    void notifyObservers()
    {
        for (auto observer : observers)
            observer->update();
    }
};

class HaveValue1 { public: virtual int getValue1() const = 0; };
class HaveValue2 { public: virtual int getValue2() const = 0; };

class ObservingForValue1 : public Observer
{
    HaveValue1* subject;

public:

    ObservingForValue1(HaveValue1* subject) : subject(subject) {}

    virtual void update()
    {
        std::cout << "New value of Value1: " << subject->getValue1() << '\n';
    }
};

class ObservingForValue2 : public Observer
{
    HaveValue2* subject;

public:

    ObservingForValue2(HaveValue2* subject) : subject(subject) {}

    virtual void update()
    {
        std::cout << "New value of Value2: " << subject->getValue2() << '\n';
    }
};

class UsingInheritance : public HaveValue1, public HaveValue2, public Subject
{
    int value1;
    int value2;

public:

    UsingInheritance(int value1, int value2) : value1(value1), value2(value2) {}

    void setValue1(int value) { value1 = value; notifyObservers(); }
    void setValue2(int value) { value2 = value; notifyObservers(); }

    virtual int getValue1() const override { return value1; }
    virtual int getValue2() const override { return value2; }
};

class UsingComposition : public HaveValue1, public HaveValue2
{
    int value1;
    int value2;

    Subject observersForValue1;
    Subject observersForValue2;

public:

    UsingComposition(int value1, int value2) : value1(value1), value2(value2) {}

    void observeValue1(Observer* observer) { observersForValue1.addObserver(observer); }
    void observeValue2(Observer* observer) { observersForValue2.addObserver(observer); }

    void unobserveValue1(Observer* observer) { observersForValue1.deleteObserver(observer); }
    void unobserveValue2(Observer* observer) { observersForValue2.deleteObserver(observer); }

    void setValue1(int value)
    { value1 = value; observersForValue1.notifyObservers(); }

    void setValue2(int value)
    { value2 = value; observersForValue2.notifyObservers(); }

    virtual int getValue1() const override { return value1; }
    virtual int getValue2() const override { return value2; }
};

int main()
{
    std::cout << "With Inheritance:\n";

    UsingInheritance inheritance{ 1, 2 };

    ObservingForValue1 io1{ &inheritance };
    ObservingForValue2 io2{ &inheritance };

    inheritance.addObserver(&io1);
    inheritance.addObserver(&io2);

    inheritance.setValue1(11);
    inheritance.setValue2(22);

    std::cout << "\nWith Composition:\n";

    UsingComposition composition{ 1, 2 };

    ObservingForValue1 co1{ &composition };
    ObservingForValue2 co2{ &composition };

    composition.observeValue1(&co1);
    composition.observeValue2(&co2);

    composition.setValue1(11);
    composition.setValue2(22);
}

Output:

With Inheritance:
New value of Value2: 2
New value of Value1: 11
New value of Value2: 22
New value of Value1: 11

With Composition:
New value of Value1: 11
New value of Value2: 22

I've learned the observer pattern from many sources, yet none of them mentioned implementing it with composition. I think using composition is more powerful than inheritance for couple of reasons:

1 - A class can have lots of observers and each one observing for a different thing. If I wanted to achieve the same behavior (having different observers observing n different things), I'll have to change the base class so that it supports n types of observers and later on, if I wanted it to support n + 1 observers, I'll have to change it again or inherit from another class. Whereas when using composition, I can just add another Subject and that's it.

2 - With inheritance if I wanted to notify the observers, I'll notify all the subscribed ones, even if each one of them is looking for a different thing. Whereas when using composition, I can just notify the desired ones.

3 - Composition is prefered over inheritance anyways. If some behavior is achievable using both inheritance and composition, Why the inheritance approach is more popular?

In the code above, I have an Observer and a Subject. There are 2 types of Subject, one using inheritance called UsingInheritance, and the other uses composition, called UsingComposition. Each one of them has 2 values, value1 and value2. There are 2 observers, ObservingForValue1 which is only interested in value1 and ObservingForValue2 which is only interested in value2. Notice that when using UsingInheritance, all the subscribed observers get notified even if the value they're interested in didn't change, whereas when using UsingComposition, only the desired ones get updated.

Is there are a better implementation of this factory?

I just learned what is factory. I want to implement it on my project( I didn't need it, but I think it is very important to write and not only read). So I rewrote my popups. There are 3 types of these. 1. Popup yes/no, 2. Popup with single text output, 3. Popup with single text output and select I write this question to ask you, if there is a good implementation, if I understood the concept, maybe you cant improve it.

const DELETE_TASK = { title: 'Are You Sure You Want To Delete?' };
const EDIT_TASK = {
    title: 'Text EDIT_TASK',
    label: 'Label here',
    placeholder: 'Placeholder here'
}

function PopupBase(object) {
    this.HTML = createSection();
    this.HTML.appendChild(createButton());
    this.HTML.appendChild(createP(object.title));
    this.HTML.style.display = 'flex';

    function createSection() {
        const section = document.createElement('section');
        section.className = 'popup';
        return section;
    }
    function createButton() {
        const button = document.createElement('button');
        button.className = 'popup-exit';
        button.innerText = 'x';
        return button;
    }
    function createP(text) {
        const title = document.createElement('p');
        title.className = 'popup-title';
        title.innerText = text;
        return title;
    }
}

function TextInputPopup(object) {
    this.HTML = new PopupBase(object).HTML;
    this.HTML.appendChild(createForm(object.label, object.placeholder));

    function createForm(label, placeholder) {
        const form = document.createElement('form');
        form.className = 'popup-form';
        form.setAttribute('autocomplete', 'off');
        form.appendChild(createLabel(label));
        form.appendChild(createInput(placeholder));
        form.appendChild(createButton());
        return form;
    }
    function createLabel(labelText) {
        const label = document.createElement('label');
        label.setAttribute('for', 'form-input');
        label.innerText = labelText;
        return label;
    }
    function createInput(placeholderText) {
        const input = document.createElement('input');
        input.id = 'form-input';
        input.className = 'popup-form-input';
        input.name = 'title';
        input.maxLength = '20';
        input.placeholder = placeholderText;
        input.setAttribute('required', 'true');
        return input;
    }
    function createButton() {
        const button = document.createElement('button');
        button.className = 'popup-form-submit';
        button.type = 'submit';
        button.innerText = 'SAVE';
        return button;
    }
}

function SelectTextInputPopup(object) {
    this.HTML = new TextInputPopup(object).HTML;

    const parentNode = this.HTML.querySelector('.popup-form');
    const newNode = createSelect();
    const referenceNode = this.HTML.querySelector('.popup-form-submit');
    parentNode.insertBefore(newNode, referenceNode);
    // console.log('from SelectTextInputPopup', this.HTML);

    function createSelect() {
        const select = document.createElement('select');
        select.id = "todoForm-priority-select";
        for (let i = 0; i < 3; i++) {
            select.appendChild(createOption(i + 1));
        }
        return select;
    }
    function createOption(i) {
        const option = document.createElement('option');
        option.className = "main-content-forms-todoForm-selector-option";
        option.value = i;
        option.innerText = i;
        return option;
    }
}

function YesNoPopup(object) {
    this.HTML = new PopupBase(object).HTML;
    this.HTML.classList.add('delete-popup');
    this.HTML.appendChild(createAnswers());

    function createAnswers() {
        const div = document.createElement('div');
        div.className = 'popup-answer';
        div.appendChild(createButton('yes'));
        div.appendChild(createButton('no'));
        return div;
    }
    function createButton(option) {
        const button = document.createElement('button');
        button.className = `popup-answer-btn ${option}`;
        button.innerText = option;
        return button;
    }
}

function PopupFactory() {
    this.create = (type) => {
        switch (type) {
            case 'yesNo':
                return new YesNoPopup(DELETE_TASK).HTML;
                break;
            case 'editTask':
                return new SelectTextInputPopup(EDIT_TASK).HTML;
                break;
            case 'firstTime':
                return new TextInputPopup(DUMMY).HTML;
                break;
            case 'editList':
                return new TextInputPopup(EDIT_LIST).HTML;
                break;
            case 'addList':
                return new TextInputPopup(DUMMY).HTML;
                break;
        }
    }
}

export { PopupFactory };

Any design pattern can replace promise/then chain in javascript?

Now I am using Promise/then to design my code(part of code in class) like below:

Condition.getFromServer()
.then(ContentInfoFromServer =>
    this.foo(para)
)
.then(para =>
    this.bar(para)
)
.then(para =>
    this.jor(para)
)
.then(para =>
    this.dom(para)
)
.then(para =>
    this.pam(para)
)

But I think it is not very good for performance. So I want find something replace this code, I've tried the chain of responsibility. But it seems like so heavy for this. Could you please suggest some good way to replace that. Thanks in advance!

Does Saga Pattern able to help to reverse Payouts incase if any Failure occurs?

I am very new to Saga Pattern. I understood that with the help of Saga, we can able to reverse the things if any failure occurs.

Whatever the examples I've seen, they are mostly like Orders Service -> Payment Service -> Other Service, and in Payment service, funds happen from Customer to Merchant, and incase if any failure occurs at Other Service, this payment transaction can be able to reverse because here funds flowing from Merchant to Customer (in reverse failure process)

BUT, my Query is: I have a Reverse scenario like this: Payouts Service -> Customer Service

In Payouts Service, funds happen from Merchant to Customer

Can we able to make Reverse the Transactions for Payouts using Saga in case if any Failure occurs at Customer Service? (ie., Reverse the funds from Customer to Merchant, incase if any failure occurs)

Does above possible using Saga? Hope my query is clear. I will be glad if someone could be able to help me on above.

samedi 25 avril 2020

Design Pattern for too many requests write in the database

hi i have an api for feedback of a website that too many request for submit rate on database so the question is here Is there a pattern design that can be done better?

reasing variable to new query in Realm

I'm new to Realm and I coulnd't find anything related to this in the documentation. I'm trying to make a method which gets a specific object from the Realm database by ID when I call it. It looks like this:

 private var singleVendor: SingleVendor? = null

     fun subscribeToVendor(
        liveData: MutableLiveData<SingleVendor>,
        id: Int
    ) {
        singleVendor?.removeAllChangeListeners()
        val singleVendor = getRealm().where(SingleVendor::class.java).equalTo("id", id).findFirstAsync()
        singleVendor?.addChangeListener<SingleVendor> { _ ->
            liveData.value = singleVendor
        }    
    }

It is needed for a VendorFragment, when someone clicks on a vendor in a list, I'd like to get the specific vendor data and update the VendorFragment with it. But when I try call this method again, singleVendor gets invalidated. I'm using LiveData here, because I'd like to encapsulate Realm.

Am I missing something? Is there a pattern for this? Thank you in advance!

Do I have to store or calculate statistics whenever I need them?

I am creating an application and I will need statistics from the data I will have in my SQL database.

For example, I have a table "animals", with a column "type" that can be equal to "dog" or "cat". I need to calculate statistics of the type "number of animals", which will therefore be equal to the number of entities in my table "animals", or "percentage of cat", which will therefore be equal to the number of cat/ number of animals * 100.

This example was simplified to the maximum, but in my application, it will be more complex calculations, and in greater numbers.

For my statistics, do I have to create another "statistics" table, and update it every time I modify my "animals" table, or do I calculate these statistics every time I have a request on my API? What are the best practices?

Extract string after pattern to unknown stop point

In a dataframe I have a column named buckets that contains rows that fit the following pattern:

{"21-45":1,"541-600":2,"46-60":2,"721-840":2,"1201-1320":1}

{"21-45":7,"481-540":10,"541-600":6,"46-60":2,"721-840":2}

{"481-540":1,"301-360":1,"<20":2,"61-120":1,"21-45":10}

{"481-540":1,"21-45":200,"721-840":1,"<20":3,"61-120":2}

I wish to extract the number that follows the pattern "21-45":

So I would be left with:

1

7

10

200

The pattern "21-45": can appear anywhere in the string and the number of digits following it vary and may end in a "," or in a "}".

The dataframe is very large, so I would like to accomplish this as parsimoniously as possible. I have no idea what the best way is to approach this problem.

Thank you.

Javascript - how to split / divide revealing module into smaller parts?

I would like to split / divide my module "Engine" into smaller parts (and keep it in one file).

Suppose I have a lot of code in a method "paintText()" - this code should be in in separate part.

How to do this?

My module "Engine" is like:

HTML

 <button type="button" id="addText">1. Add some text</button> 
 <button type="button" id="countText">2. Count letters</button> 
 <button type="button" id="addColor">3. Add color</button> 

<div id="elText"></div>
- - - - - - - - - - - - - - - - - - 
<div id="elCounter"></div>

Javascript:

var Engine = (function(){
    var addTextButton = document.querySelector('#addText');
    var countButton = document.querySelector('#countText');
    var colorButton = document.querySelector('#addColor');

    var textArea = document.querySelector('#elText');
    var counter = document.querySelector('#elCounter');

    addTextButton.addEventListener('click', addText, false);
    countButton.addEventListener('click', showCounter, false);
    colorButton.addEventListener('click', paintText, false);

    // Engine function
    function addText( event ){
        textArea.innerHTML += '<br /> add some text';
    }
    // Engine function
    function showCounter( event ){
        counter.innerHTML = 'amount of liter = ' + textArea.innerText.length;
    }

    // ADDITION function - separate it as submodule!!!
    function paintText( event ){
        /*
            lot of code....
            lot of code....
        */
        textArea.style.backgroundColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);// random color
    }

    return {
        paintText : paintText
    }
})();

It is simple - you can: 1. add some text 2. count letters 3. add background color.

Working JSFiddle - "One big Module":

I am trying to separate "paintText()" method into submodule, but I don't know how to do this right way.

Wrong way:

I created 2 modules "Engine" and "Color", it works but this is stupid to have 2 modules.

var Engine = (function(){
    (...)


    function randomColor( event ){

        Color.paintText( textArea )

    }
})();

//submodule
var Color = (function(){
    function paintText(){
    }
    return {
        paintText : paintText
    }
})();

Working JSFiddle - "Splitted Module - wrong way"

It know it should look like this (to keep all parts in one object) :

pseudo code:

app = {};

//engine
app.engine = function(){
... engine here
}

//additional submodule
app.color = function(){
... color here
}

//additional submodule
app.images = function(){
... images here
}

but I don't know how to make it work!

Help please.