mercredi 31 mars 2021

Design pattern - Best place for helper class

I have a question regarding source code structure. What is the package should I allocate the helper classes which implement some logic.

enter image description here

Here is my source code structure. Let me explain it:

I have many rules when getting information about a flight, such as baggage allowance rule (BaggageAllocationRule.java), meal rule, seat allocation rule... All above rule has common information that is defined in FlightCommonRule class (extends abstract class Rule). Then, I have abstract class RuleMatcher that provides functions to lookup matched rules. There are 2 types of RuleMatcher, SingleHitRuleMatcher (returns at most one rule), MultipleHitRuleMatcher (returns multiple rules).

I think that BaggageAllowanceRuleMatcher, SingleHitRuleMatcher, MultipleHitRuleMatcher, RuleMatcher are allocated in the wrong package (model).

How should I restructure the source code?

How do I work with double references and consequent import errors

I'm running into a problem with imports and references. I'm gonna use a made-up example to explain (the example uses mongoengine)

Let's say I have the following two classes in two different files

# File 1 
# Titled houses.py

import persons
import mongoengine as me

class House(me.Document):
    residents: me.ListField(me.ReferenceField(persons.Person)) #This will be a list populated with Person objects
# File 2
# Titled persons.py

import houses
import mongoengine as me

class Person(me.Document):
    house: me.ReferenceField(houses.House) #This is a House object

I have two concerns in a scenario like the above

  1. I'm getting a circular import error (b/c they require each other) - I can't get rid of the imports b/c mongo asks that you input the class of the object that will be assigned to the variable
  2. This seems less than ideal - is there a design pattern that betters this situation?

Thanks!

Correct way to go about updating a shared Redux state in React

I have a web page in a react app where I enter text into two separate text boxes that will update the backend with the text entered. The update occurs after a short time where the user no longer types to avoid spamming the server. Once a server update goes out, I update the state with the information that came from the server. This, of course, causes that part to re-render. This works great until a user enters something inside one box and then enters information into the second box before the otther box's update has gone off. The information in the second box is lost and overwritten by the update coming from the server.

It's important to note that the textbox itself stores the state of the text, and only when an action/dispatch cycle is called after the timeout does the redux state update. I tried tieing the textbox text state to redux, but the performance took a hit, and there was noticeable lag when typing.

Currently, I have each text box being passed a prop that maps to a value in from the redux state. These text boxes have different values mapped to them, but they are from the same state.

I don't really know the best way to approach this such that the textboxes store their values after being fetched from the server and still will not lose text when the other is updated.

In the component that renders the page:

render() {
//... other code
return (
/*... some jsx ...*/
<DetailTextArea className="textArea" detailType="implementation" text={practiceInView.implementation_details}/>

/*... more jsx ... */
<DetailTextArea className="textArea" detailType="evidence" text={practiceInView.evidence_details}/>
);
}

What's the correct way to create an DAO class for an a composition class

I am doing this 'B' class that have 'C' and/or 'D' class common attributes that I will implement in their parent class 'A', like client and employee that inherits person values, in this case, I am replacing inheritance for composition, for now, I don't want to use a ORM framework, will I have an BDAO and CDAO, that evokes ADAO to make association in BD or create every A attribute in an B and C table?

 public class A{
 public long ID;
 public int attributeA;
 }
 public class B{
 public long ID;
 public int attributeB;
 A a = new A();
 }
 public class C{
 A a = new A();
 public int attributeC;
 }

 public class Main{
 public static void main(String[] args) 
 {
 B bObject = new B();
 bObject.attributeB=0;
 A aObject = new A();
 aObject.attributeA=1;
 bObject.A=a;
 }
 }

 public class BDAO{
 public void add(B b){
 Conn.preparedStatement(("insert into bTable (id,attributeB,FK_idA) 
values("b.ID+","+b.attributeB+","+b.A.id+")").execute();
 new ADAO().add(B.a);
 }
 }

 public class CDAO{
 public void add(C C){
 Conn.preparedStatement(...
 new ADAO().add(A.a);
 }
 }

 public class ADAO{
 public void add(A a){
 Conn.preparedStatement("insert into aTable (id,attributeA)
 values ("a.ID+","+a.attributeA+")").execute();
 }
 }

Computed field in MongoDB

I have two MongoDb collections:

FILM

{ _id: ObjectId("60644a81655e8216acf44b6e"), name: 'Django' }
{ _id: ObjectId("60647242c31ba840a0479221"), name: 'Kill Bill' }

SCREENING

{ _id: ObjectId("60644598655e8216acf44b6a"),
  name: 'Django',
  reviews: '1150',
  cinema: '01' }
{ _id: ObjectId("606445c7655e8216acf44b6b"),
  name: 'Django',
  reviews: '2130',
  cinema: '02' }
{ _id: ObjectId("606445c7655e8216acf44b6c"),
  name: 'Django',
  reviews: '2102',
  cinema: '03' }
{ _id: ObjectId("60647218c31ba840a047921f"),
  name: 'Kill Bill',
  reviews: '2000',
  cinema: '01' }
{ _id: ObjectId("60647218c31ba840a0479220"),
  name: 'Kill Bill',
  reviews: '587',
  cinema: '02' }

I want to add, in FILM collection, a new computed field total_reviews, that sum the total reviews of a FILM; for example:

FILM

{ _id: ObjectId("60644a81655e8216acf44b6e"), name: 'Django', total_reviews: "3382" }
{ _id: ObjectId("60647242c31ba840a0479221"), name: 'Kill Bill', total_reviews: "2587"}

Someone can I help me? Thanks...

Design Pattern for converting Java Data Model to XLS Workbook Sheet

Basically, I want to convert Java Object Model into two different sheets of an XLS workbook. I have solved this problem so far but I am trying to find better solution in terms of design pattern.

Here is the response Object Model.

class Response {
  List<Model1> list;
}

class Model1 {
  String attr1;
  String attr2;
  List<Model2> list;

  @JsonProperty(value="attr1")
  String getAttr1() {..}
}

class Model2 {
  String attr1;
  String attr2;

  @JsonProperty(value="attr1")
  String getAttr1() {..}
}

For conversion layer, I created a parent interface with different implementation as below.

public interface Converter<T> {
  Sheet convert(T t);
}

public class DataConverter {

   public Workbook getWorkBook(Response res) {
      Sheet model1Sheet = new Model1SheetConverter().convert(res);
      Sheet model2Sheet = new Model2SheetConverter().convert(res);
      return new Workbook().sheets(List.of(model1Sheet, model2Sheet));
   }
}

public class Model1SheetConvert implements Converter<Response> {
   public sheet convert(Response res) {
       I do loop over here for data model 1 and then with some business logic generate sheet.
   }
}

public class Model2SheetConvert implements Converter<Response> {
   public sheet convert(Response res) {
       I do loop over here for each data model 1 then I pass data model 2 and then with some business logic generate sheet.
   }
}

Now problem with this approach are:

  1. I am iterating two times for data model 1.
  2. There will be some dynamic rows for sheet 1 and sheet 2 based on data model 1. I can not handle this part here with this approach.

Can someone please suggest a good design pattern for this approach? Or, is there is any other way, I can do it differently.

Make Install-able Python third-party Submodule

I have a pip package that I want third party developers to add to it.

Meaning: the 'root' pip package has the basic interfaces and abstract classes and it can detect sub-classes. Now I want a third-party developer to write another module that inherits classes from the root package (the 3rd-party submodule has the root package as a dependency) and consequently the root package can detect subclasses from the 3rd party package.

So by the end when in a script typing something like that: import mypackage.* the root package and all submodules are imported

Any recommendation for a good practice to do that?

Thanks

mardi 30 mars 2021

How to notify a high level Provider from a singleton? (Flutter design pattern)

In my app I have a singleton SettingsData which holds all of the user's settings data (instead of having to read asynchronously from SharedPreferences every time do it once). I create that singleton before calling RunApp(...).

On top of that I have a Widget CurrentItems (which is a ChangeNotifierProvider),a business logic representing the items to be shown to the user based on his current settings/preferences.

Upon any change in the users settings(debounced of course), I want to notify the CurrentItems object so it can fetch relevant items from the server, and after getting new relevant items update the UI (the last part is already working since CurrentItems is a ChangeNotifierProvider)

What would be a reasonable way/pattern to achieve that? For instance, making SettingsData a ChangeNotifierProvider and CurrentItems a Consumer is not a good option since CurrentItems is a high-level item, meaning that the entire UI would be rebuilt on every settings change before new items were fetched from the server.

Design Pattern for different users

I have 2 different types of users in my app: LoggedInUser and GuestUser They both have same functionalities such as createNewOrder and cancelOrder (the implementation should be different) but LoggedInUser can do much more such as WriteReview,FavouriteProduct etc.

I want a design pattern for these types of users, so that I don't check which type of user my application has at the moment and I just call the method without knowing the actual type of the user.

Is it even possible to do this? Which design pattern is the most suitable?

What I have done so far is creating an abstract class called User which has the similar functionalities:

abstract class User{
  void createOrder()
  void cancelOrder()
}

and also a class for LoggedInUser and a class for GuestUser:


class LoggedInUser extends User{
  //some instance variables
  void favouriteProduct(String id){
   //...
}

 void writeReview(Review review){
 //...
 }
  @override
  void cancelOrder(){
 //...
 }
  @override
  void cancelOrder(){
 //...
 }
}

class GuestUser extends User{
 //some instance variables
 
 @override
  void cancelOrder(){
 //...
 }
  @override
  void cancelOrder(){
 //...
 }
}

Thanks

Add a property in javascript class component in order to communicate between method

As title say and below indicate

class T extends React.Component {
    constructor(props) {
        super(props)
        this.a = false;
    }

    methodA {
    //will set 'a' in this method, maybe async.
    }

    methodB {
    // will get 'a' in this method.
    }

    render() {
        return (
                   <div>hello,world</div>
        )
    }
}

This looks like a very simple code. However, as the component become more complicated and the logic ascend, we need to add more property to the class to satisfy the communication of the method, like:

> class T extends React.Component {
>      constructor(props)
>        this.a = false;
>        this.b = 123;
>        this.c = 'string';
>        this.d = null;
>        this.e = [];
>        ...
>        this.z = ........
>      }

Apparently, it is not decent. So, could you please inform me do we have any other solution to replace that? Do we have any decent way to communicate between method in one class? Thanks in advance.

lundi 29 mars 2021

Fluent builder design pattern - how to force customer to set variables

I have a problem with design pattern. Let's say i have a simple class:

public class Person {

    private String name;
    private String surname;
    private int age;

    private Person(){}

    public String toString()
    {
        return "name: "+name+" surname: "+surname+" age: "+age;
    }

    public static final class Builder{

        private String name;
        private String surname;
        private int age;

        public Builder name (String name){
            this.name = name;
            return this;
        }

        public Builder surname (String surname){
            this.surname = surname;
            return this;
        }

        public Builder age (int age){
            this.age = age;
            return this;
        }

        public Person build(){
            Person person = new Person();
            person.name=name;
            person.surname=surname;
            person.age=age;
            return person;
        }
    }
}

It works fine, but it's not required to set variables before invoking "build" method. How could i change that?

Why notification/request marker interfaces for Mediator?

Whilst I am a massive fan of MediatR, it feels strange to take it as a dependency on all my projects (even those that dont "dispatch" and are merely posting POCOs reference the marker interfaces).

What is the need therefore for marker interfaces in the first place, when the below code works with plain POCOs?

Is there any issues with removing the marker interfaces from Notification and Request?

Handler interfaces

public interface INotificationHandler<in TNotification> where TNotification : class
{
    Task Handle(TNotification notification, CancellationToken cancellationToken);
}

public interface IRequestHandler<in TRequest, TResponse> where TRequest : class
{
    Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
}

Plain POCO without marker interfaces

class TestNotification
{
    public int UserId { get; set; }
    public int Age { get; set; }
}

class TestRequest
{
    public int UserId { get; set; }
}

Handlers

class TestRequestHandler : IRequestHandler<TestRequest, int>
{
    public Task<int> Handle(TestRequest request, CancellationToken cancellationToken)
    {
        return Task.FromResult(request.UserId);
    }
}

class TestNotificationHandler : INotificationHandler<TestNotification>
{
    public Task Handle(TestNotification notification, CancellationToken cancellationToken)
    {
        Console.WriteLine("hello");
        return Task.CompletedTask;
    }
}

Main

static void Main(string[] args)
{
    _ = new TestNotificationHandler()
                .Handle(new TestNotification(), CancellationToken.None);

    var result = new TestRequestHandler()
                        .Handle(new TestRequest() { UserId = 111 }, CancellationToken.None)
                        .Result;

    Console.WriteLine($"result is {result}");
}

C# fiddle

https://dotnetfiddle.net/HTkfh9

Is it possible to refactor this Controller create method in Laravel?

Is there a design pattern or good practices for this kind of view inizialization code? In this case, depending on the parameter ($tipoPedido) it sets up the view in different ways:

 public function create(Request $request, RepositorioDepositos $repositorioDepositos, RepositorioEmpresas $repositorioEmpresas)
    {
        $tipoPedido = strtoupper($request->tipo);

        $datos = ['action' => "/api/pedidos", 'tipo' => $tipoPedido];


        if ($tipoPedido == TipoRemitoStock::ESPECIAL) {

            if (!tengoPermiso(\App\Permiso::STOCK_CREAR_REMITO_ESPECIAL)) {
                return mensajeErrorNoTienePermiso();
            }

            $datos['origen']  = null;
            $datos['destino'] = $repositorioDepositos->getTodosNoFinalizados();
        }
        
        
        elseif ($tipoPedido == TipoRemitoStock::INTERNO) {
            $datos['origen']  = $this->getMisPosiblesDepositosOrigen($repositorioDepositos);
            $datos['destino'] = $this->getMisPosiblesDepositosDestino($repositorioDepositos);
        }
        
        
        elseif ($tipoPedido == TipoRemitoStock::PROVEEDOR) {
            $datos['origen']      = null;
            $datos['destino']     = $this->getMisPosiblesDepositosDestino($repositorioDepositos);
            $datos["proveedores"] = $this->proveedoresConOCsDeMaterialesAprobadas($repositorioEmpresas);
        }
        
        else {
            die("Tipo de pedido no implementado: " . $tipoPedido);
        }


        $vista = view('ventas.formulario-abm-pedido', $datos);

        return $vista;
    }

Now we need to add 3 new types so there will be 3 new elseif blocks.

Bridge pattern: how to define functions that call the implementation of the derived class

I am working on a polymer simulation code that employs the Bridge pattern to separate abstractions (the objects involved in the simulation) and their implementations (how they are represented e.g. one particle per monomer, continuous grid, etc.). A problem that I am facing is that I am struggling to define a class hierarchy of abstractions where lower abstractions can execute functions defined on other classes higher up in the hierarchy.

I would like to define a base abstraction Monomer that incorporates a number of methods that call the MonomerImpl implementation. Say, a method applyDisplacement to move the monomer in space. However, when I define a derived abstraction MonomerTypeA with several implementations MonomerTypeAImplGrid, MonomerTypeAImplParticles, etc., I would like to call applyDisplacement, defined at the top of the hierarchy class, but using the specific implementation of my monomer class.

This is an example of what I have tried:

class Monomer
{
  public:
    ...
    void applyDisplacement(Vector displacement)
    {
       getImplementation()->applyDisplacement(displacement);
    }

  private:
    std::unique_ptr<MonomerImpl> p_impl;
    virtual MonomerImpl* getImplementation();

};

class MonomerImpl
{
  public:
    ...
    void applyDisplacement(Vector displacement)
    {
       for (int i=0; i<positions.size(); i++)
       {
           positions[i] += displacement;
       }
    }

  private:
    std::vector<Vector> positions;

};

And:

class MonomerTypeA
{
  public:
    ...

  private:
    std::unique_ptr<MonomerTypeAImpl> p_impl;
    MonomerImpl* getImplementation()
    {
        return (MonomerImpl*) p_impl.get();
    }

};

If I use a virtual function getImplementation function can only return a MonomerImpl* pointer, then I can't implement any additional functionality to the implementation. Alternatively, if I try to scrap inheritance and just define a bunch of different implementations, I will have a lot of code duplication.

Is there any solution that gets the best of both worlds?

dimanche 28 mars 2021

How to add extension points in my library?

I've started writing DataFilters a while ago after I discovered and used elastic search with it's wonderful lucene syntax. The idea behind that project was first to learn new stuff but I was also wondering if I could create something similar to work with other datasources.

Long story short, I now have something that work pretty well (I think) with the BCL classes and I now want to extend it to support third party libraries like NodaTime.

The main parts are IFilter interface

using System;

namespace DataFilters
{
    /// <summary>
    /// Defines the basic shape of a filter
    /// </summary>
    public interface IFilter : IEquatable<IFilter>
    {
        /// <summary>
        /// Gets the JSON representation of the filter
        /// </summary>
        /// <returns></returns>
        string ToJson();

        /// <summary>
        /// Computes a new <see cref="IFilter"/> instance which is the exact opposite of the current instance.
        /// </summary>
        /// <returns>The exact opposite of the current instance.</returns>
        IFilter Negate();

#if NETSTANDARD2_1
        public virtual void ToString() => ToJson();
#endif
    }
}

with two implementations : Filter

using DataFilters.Converters;

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
using static Newtonsoft.Json.DefaultValueHandling;
using static Newtonsoft.Json.Required;
using System.Text.RegularExpressions;
#if !NETSTANDARD1_3
using System.Text.Json.Serialization;
#endif

namespace DataFilters
{
    /// <summary>
    /// An instance of this class holds a filter
    /// </summary>
#if NETSTANDARD1_3
    [JsonObject]
    [JsonConverter(typeof(FilterConverter))]
#else
    [System.Text.Json.Serialization.JsonConverter(typeof(FilterConverter))]
#endif
    public class Filter : IFilter, IEquatable<Filter>
    {
        /// <summary>
        /// Filter that always returns <c>true</c>
        /// </summary>
        public static Filter True => new Filter(default, default);

        /// <summary>
        /// Pattern that field name should respect.
        /// </summary>
        /// <returns></returns>
        public const string ValidFieldNamePattern = @"[a-zA-Z_]+((\[""[a-zA-Z0-9_]+""]|(\.[a-zA-Z0-9_]+))*)";

        /// <summary>
        /// Regular expression used to validate
        /// </summary>
        /// <returns></returns>
        public static readonly Regex ValidFieldNameRegex = new Regex(ValidFieldNamePattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));

        /// <summary>
        /// Name of the json property that holds the field name
        /// </summary>
        public const string FieldJsonPropertyName = "field";

        /// <summary>
        /// Name of the json property that holds the operator
        /// </summary>
        public const string OperatorJsonPropertyName = "op";

        /// <summary>
        /// Name of the json property that holds the value
        /// </summary>
        public const string ValueJsonPropertyName = "value";

        /// <summary>
        /// <see cref="FilterOperator"/>s that required <see cref="Value"/> to be null.
        /// </summary>
        public static IEnumerable<FilterOperator> UnaryOperators { get; } = new[]{
            FilterOperator.IsEmpty,
            FilterOperator.IsNotEmpty,
            FilterOperator.IsNotNull,
            FilterOperator.IsNull
        };

        /// <summary>
        /// Generates the <see cref="JSchema"/> for the specified <see cref="FilterOperator"/>.
        /// </summary>
        /// <param name="op"></param>
        /// <returns></returns>
        public static JSchema Schema(FilterOperator op)
        {
            JSchema schema;
            switch (op)
            {
                case FilterOperator.Contains:
                case FilterOperator.StartsWith:
                case FilterOperator.EndsWith:
                    schema = new JSchema
                    {
                        Type = JSchemaType.Object,
                        Properties =
                        {
                            [FieldJsonPropertyName] = new JSchema { Type = JSchemaType.String },
                            [OperatorJsonPropertyName] = new JSchema { Type = JSchemaType.String },
                            [ValueJsonPropertyName] = new JSchema { Type = JSchemaType.String }
                        },
                        Required = { FieldJsonPropertyName, OperatorJsonPropertyName }
                    };
                    break;
                case FilterOperator.IsEmpty:
                case FilterOperator.IsNotEmpty:
                case FilterOperator.IsNotNull:
                case FilterOperator.IsNull:
                    schema = new JSchema
                    {
                        Type = JSchemaType.Object,
                        Properties =
                        {
                            [FieldJsonPropertyName] = new JSchema { Type = JSchemaType.String },
                            [OperatorJsonPropertyName] = new JSchema { Type = JSchemaType.String }
                        },
                        Required = { FieldJsonPropertyName, OperatorJsonPropertyName }
                    };
                    break;
                default:
                    schema = new JSchema
                    {
                        Type = JSchemaType.Object,
                        Properties =
                        {
                            [FieldJsonPropertyName] = new JSchema { Type = JSchemaType.String,  },
                            [OperatorJsonPropertyName] = new JSchema { Type = JSchemaType.String },
                            [ValueJsonPropertyName] = new JSchema {
                                Not = new JSchema() { Type = JSchemaType.Null }
                            }
                        },
                        Required = { FieldJsonPropertyName, OperatorJsonPropertyName, ValueJsonPropertyName }
                    };
                    break;
            }
            schema.AllowAdditionalProperties = false;

            return schema;
        }

        /// <summary>
        /// Name of the field  the filter will be applied to
        /// </summary>
#if NETSTANDARD1_3
        [JsonProperty(FieldJsonPropertyName, Required = Always)]
#else
        [JsonPropertyName(FieldJsonPropertyName)]
#endif
        public string Field { get; }

        /// <summary>
        /// Operator to apply to the filter
        /// </summary>
#if NETSTANDARD1_3
        [JsonProperty(OperatorJsonPropertyName, Required = Always)]
        [JsonConverter(typeof(CamelCaseEnumTypeConverter))]
#else
        [JsonPropertyName(OperatorJsonPropertyName)]
        //[System.Text.Json.Serialization.JsonConverter(typeof(FilterOperatorConverter))]
#endif
        public FilterOperator Operator { get; }

        /// <summary>
        /// Value of the filter
        /// </summary>
#if NETSTANDARD1_3
        [JsonProperty(ValueJsonPropertyName,
            Required = AllowNull,
            DefaultValueHandling = IgnoreAndPopulate,
            NullValueHandling = NullValueHandling.Ignore)]
#else
        [JsonPropertyName(ValueJsonPropertyName)]
#endif
        public object Value { get; }

        /// <summary>
        /// Builds a new <see cref="Filter"/> instance.
        /// </summary>
        /// <param name="field">name of the field</param>
        /// <param name="operator"><see cref="Filter"/> to apply</param>
        /// <param name="value">value of the filter</param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="field"/> does not conform with <see cref="ValidFieldNamePattern"/></exception>
        public Filter(string field, FilterOperator @operator, object value = null)
        {
            if (!string.IsNullOrEmpty(field) && !ValidFieldNameRegex.IsMatch(field))
            {
                throw new ArgumentOutOfRangeException(nameof(field), field, $"field name is not valid ({ValidFieldNamePattern}).");
            }

            Field = field;
            switch (@operator)
            {
                case FilterOperator.EqualTo when value is null:
                    Operator = FilterOperator.IsNull;
                    break;
                case FilterOperator.NotEqualTo when value is null:
                    Operator = FilterOperator.IsNotNull;
                    break;
                default:
                    Operator = @operator;
                    Value = value;
                    break;
            }
        }

#if NETSTANDARD1_3
        public string ToJson()
        {
            return this.Jsonify(new JsonSerializerSettings());
        }
#else
        public string ToJson() => this.Jsonify();
#endif

        public override string ToString() => ToJson();

        public bool Equals(Filter other)
            => other != null
            && (ReferenceEquals(other, this)
            || (Equals(other.Field, Field) && Equals(other.Operator, Operator) && Equals(other.Value, Value)));

        public override bool Equals(object obj) => Equals(obj as Filter);

#if NETSTANDARD1_3 || NETSTANDARD2_0
        public override int GetHashCode() => (Field, Operator, Value).GetHashCode();
#else
        public override int GetHashCode() => HashCode.Combine(Field, Operator, Value);
#endif

        public IFilter Negate()
        {
            FilterOperator @operator = Operator switch
            {
                FilterOperator.EqualTo => FilterOperator.NotEqualTo,
                FilterOperator.NotEqualTo => FilterOperator.EqualTo,
                FilterOperator.IsNull => FilterOperator.IsNotNull,
                FilterOperator.IsNotNull => FilterOperator.IsNull,
                FilterOperator.LessThan => FilterOperator.GreaterThan,
                FilterOperator.GreaterThan => FilterOperator.LessThan,
                FilterOperator.GreaterThanOrEqual => FilterOperator.LessThanOrEqualTo,
                FilterOperator.StartsWith => FilterOperator.NotStartsWith,
                FilterOperator.NotStartsWith => FilterOperator.StartsWith,
                FilterOperator.EndsWith => FilterOperator.NotEndsWith,
                FilterOperator.NotEndsWith => FilterOperator.EndsWith,
                FilterOperator.Contains => FilterOperator.NotContains,
                FilterOperator.IsEmpty => FilterOperator.IsNotEmpty,
                FilterOperator.IsNotEmpty => FilterOperator.IsEmpty,
                FilterOperator.LessThanOrEqualTo => FilterOperator.GreaterThanOrEqual,
                _ => throw new ArgumentOutOfRangeException(nameof(Operator), "Unknown operator"),
            };
            return new Filter(Field, @operator, Value);
        }

        public bool Equals(IFilter other) => Equals(other as Filter)
;

        public void Deconstruct(out string field, out FilterOperator @operator, out object value)
        {
            field = Field;
            @operator = Operator;
            value = Value;
        }
    }
}

MultiFilter

using DataFilters.Converters;
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using static Newtonsoft.Json.DefaultValueHandling;
using static Newtonsoft.Json.Required;

#if !NETSTANDARD1_3
using System.Text.Json.Serialization;
#endif

namespace DataFilters
{
    /// <summary>
    /// An instance of this class holds combination of <see cref="IFilter"/>
    /// </summary>
    [JsonObject]
#if NETSTANDARD1_3
    [JsonConverter(typeof(MultiFilterConverter))]
#else
    [System.Text.Json.Serialization.JsonConverter(typeof(MultiFilterConverter))]
#endif
    public class MultiFilter : IFilter, IEquatable<MultiFilter>
    {
        /// <summary>
        /// Name of the json property that holds filter's filters collection.
        /// </summary>
        public const string FiltersJsonPropertyName = "filters";

        /// <summary>
        /// Name of the json property that holds the composite filter's logic
        /// </summary>
        public const string LogicJsonPropertyName = "logic";

        public static JSchema Schema => new JSchema
        {
            Type = JSchemaType.Object,
            Properties =
            {
                [FiltersJsonPropertyName] = new JSchema { Type = JSchemaType.Array, MinimumItems = 2 },
                [LogicJsonPropertyName] = new JSchema { Type = JSchemaType.String, Default = "and"}
            },
            Required = { FiltersJsonPropertyName },
            AllowAdditionalProperties = false
        };

        /// <summary>
        /// Collections of filters
        /// </summary>
#if NETSTANDARD1_3
        [JsonProperty(PropertyName = FiltersJsonPropertyName, Required = Always)]
#else
        [JsonPropertyName(FiltersJsonPropertyName)]
#endif
        public IEnumerable<IFilter> Filters { get; set; } = Enumerable.Empty<IFilter>();

        /// <summary>
        /// Operator to apply between <see cref="Filters"/>
        /// </summary>
#if NETSTANDARD1_3
        [JsonProperty(PropertyName = LogicJsonPropertyName, DefaultValueHandling = IgnoreAndPopulate)]
        [JsonConverter(typeof(CamelCaseEnumTypeConverter))]
#else
        [JsonPropertyName(LogicJsonPropertyName)]
#endif
        public FilterLogic Logic { get; set; }

        public virtual string ToJson() => this.Jsonify();


        public IFilter Negate()
        {
            MultiFilter filter = new MultiFilter
            {
                Logic = Logic switch
                {
                    FilterLogic.And => FilterLogic.Or,
                    FilterLogic.Or => FilterLogic.And,
                    _ => throw new ArgumentOutOfRangeException($"Unsupported {Logic}")
                },
                Filters = Filters.Select(f => f.Negate())
#if DEBUG
                .ToArray()
#endif
            };

            return filter;
        }
#if NETSTANDARD1_3 || NETSTANDARD2_0
        public override int GetHashCode() => (Logic, Filters).GetHashCode();
#else
        public override int GetHashCode()
        {
            HashCode hash = new HashCode();
            hash.Add(Logic);
            foreach (IFilter filter in Filters)
            {
                hash.Add(filter);
            }
            return hash.ToHashCode();
        }
#endif

        public bool Equals(IFilter other) => Equals(other as MultiFilter);

        public override bool Equals(object obj) => Equals(obj as MultiFilter);

        public bool Equals(MultiFilter other)
            => Logic == other?.Logic
            && Filters.Count() == other?.Filters?.Count()
            && Filters.All(filter => other?.Filters?.Contains(filter) ?? false)
            && (other?.Filters.All(filter => Filters.Contains(filter)) ?? false);
    
}
}

DataFilters.Expressions and DataFilters.Queries are two libraries that I also wrote and that allow to create C# Expressions or WHERE SQLs given an IFilter instance as a input (extension methods).

What i'm trying to do now is to provide an extension point so that I could write a new library (called DataFilters.NodaTime for example) that could handle NodaTime types somehow while deferring everything else to DataFilters.Expressions (a library that I already released).

That extension point should add ability to handle nodatime type but I have no clue how to get started on this

For now, I'm thinking about something like this :

  • create a new library DataFilters.Expressions.NodaTime
  • create a new IFilter extension method in it : it will be tailored to handle NodaTime types.

The goal is to be able to handle NodaTime types both with DataFilters.Expressions and DataFilters.Queries for example.

Could it be a good approach or is there a better way to handle this ?

Thanks in advance to anyone who could help me on this

system Design: service to request data for N users in M different data sources

I am struggling to create a clean design for a system that needs to call N services for M applicants.

details:

  1. each service returns different domain objects
  2. each service call should be in a different thread
  3. Max # of applicants 3
  4. max # of services currently there is no defined limit. will need to check on system limits

I am looking for best practices on design and also maintainability. my goal is to define a new service that implements an interface, then the system will add the service to the list. in my current design, I need to define the list of services manually and pass the dependencies and needed data. note: i'm using java 8 and spring

// given

Future futureOne = new DataCollectorTaskOne(applicantData, serviceOne);

Future futureTwo = new DataCollectorTaskTwo(applicantData, ServiceTwo);

// where

DataCollectorTask extends callable(not a bean just a pojo), that will call the service(initialize from the constructor) using the applicant data.

@Data
@RequiredArgsConstructor
public class DataCollectorTask<T> implements Callable<T> {
    public final BankRecordsService bankRecordsService;
    public final ApplicantData applicantData;

    @Override
    public T call() throws Exception {
        return bankRecordsService.executeRequest(applicantData)
    }

in spring I can autowire the list of beans that extends an interface. in this case I will be able to get the list of services because they will have the @Service annotation but the CallableService beans are just pojos(not manage by spring).

service interface

public interface DataCollector<T> {

  /* This will be use to disable or enable services in different environments*/
  boolean isActive();

  /*The data service will be responsible to implement the mapping*/
  void mapData(DataCollectorRequest request, ApplicantData mappingDestination, T data);

  /*different services have different time expectations*/
  int getTimeOut();

  /*this will determine based on the data in the applicantData if everything was successful*/
  boolean isRequestSatisfied(ApplicantData valueInDatabase, DataCollectorRequest dataCollectorRequest);

}

I have a feeling there is a better design than what i have right now. Also, i have a question about about multithreading should the system create a thread for each applicant then each thread will create a thread for each service ? or just create a thread for N*M services.

Difficult extracting shared logic in two Rails classes adding/updating records

I have an app that aims to helps people to meet up. I have a database table that stores time windows of availability for a particular user:

AvailabilityWindow (user_id, start_time, end_time, can_travel, travel_radius, target_user, will_travel, state) (state can be 'active' or 'removed')

User availability can be open to all other users, or targeting a specific user (by using the target_user_id field in AvailabilityWindow). To make creating untargeted/targeted availability easier, I have two classes:

class UserOpenAvailability
   class << self
     def for(user)
       new(user, user.availability_windows.where(target_user_id: nil))
     end
   end

   def initialize(user, availability: [])
     @user = user
     @availabilities = availability
   end

   def add(start_time, end_time, can_travel: false, travel_radius: 0)
      @availabilities << AvailabilityWindow.new(user: user, start_time: start_time, end_time: end_time, can_travel: can_travel, travel_radus: travel_radius)
   end

   def existing_availability
     self.class.for(@user)
   end

   def save
     # complicated save logic
   end

end
class TargetedUserAvailability
   class << self
     def for(user, target_user)
       new(user, target_user, user.availability_windows.where(target_user: target_user))
     end
   end

   def initialize(user, target_user, availability: [])
      @user = user
      @target_user = target_user
      @availabilities = availability
   end

   def add(start_time, end_time, can_travel, travel_radius, will_travel: true)
      @availabilities << AvailabilityWindow.new(user: user, target_user: @target_user, start_time: start_time, end_time: end_time, can_travel: can_travel, travel_radus: travel_radius, will_travel: will_travel)
   end

   def existing_availability
     self.class.for(@user, @target_user)
   end

   def save
     #...
   end
end

These can be used as follows to either add to existing availability:

availability = UserOpenAvailability.for(user)
availability.add(...)
availability.save

or save a fresh set of availability:

availability = UserOpenAvailability.new(user, [])
availability.add(...)
availability.save

The problem I'm having is that the logic in the save method is extensive, and very similar in both classes.

When a user updates their availability, I need to add/update records in the AvailabilityWindow table.

  • any new availability needs to be added as a new record
  • any previous availability that has been deselected needs to be 'removed' by changing the state to removed
  • any changes to existing availability (e.g. end_time brought forward) requires the existing availability to be removed and a new, reduced time slot added.
  • any unchanged availability needs to be untouched

Implementing the above logic is fairly complicated. It needs to be wrapped in a transaction, it needs to compare existing availability with new availability to work out what needs to be saved/removed, it needs to save all the updates and report if any changes ended up being made.

At the moment it looks kind of like this:

def save
  @user.with_lock do
    ActiveRecord::Base.transaction do 
      added_availabilities.each do |availability|
        raise ActiveRecord::Rollback unless availability.save
      end
      removed_availabilities.each(&:remove!)

      @availability_changed = (added_avaialbilities + removed_availabilities).any?
      return true
    end
    false
  end
end

def availability_changed?
  !!@availability_changed
end

def added_availabilities
  @availabilities.select do |new_availability|
    existing_availabilities.none? do |existing|
       existing.same_availability?(new_availability)
    end
  end
end

def removed_availabilities
  existing_availabilities.select do |existing|
    @availabilities.none? do |new_availability|
       new_availability.same_availability?(existing)
    end
  end
end

This code is currently sitting in both classes and I'm having trouble refactoring it out. I don't think creating a base class that both my classes extend from really works because the #add methods have different arguments.

I could move the logic into a concern/module, but then there's going to be bidirectional dependencies as the concern expects there to be both a @availabilites array and existing_availabilities method. That seems like I'm just hiding the problem.

I can only think of adding a class such as AvailabilityWindowUpdater that takes a set of existing availability windows and a desired set of availability windows, and performs all the above save logic. But having a class called ..Updater is usually not a good sign.

Can anyone help with some suggestions?

What to set as default when the type is A (Scala)

I have an exercise in Scala in which I have to transform that kind of list (a,a,a,b,c,d,d,e,a,a) into ((a,3),(b,1),(c,1),(d,2),(e,1),(a,2)). I obviously know that my algorithm is not correct yet, but I wanted to start with anything. The problem is that I don't know how to turn on the function (last line), because the error is that whatever I take as previous' argument, it says that required: A, found: Int/String etc. The previous was meant to be as a head of the previous iteration.

def compress[A](l: List[A]): List[(A, Int)] = {
def compressHelper(l: List[A], acc: List[(A, Int)], previous: A, counter: Int): List[(A, Int)] = {
  l match {
    case head::tail => {
      if (head == previous) {

        compressHelper(tail, acc :+ (head, counter+1), head, counter+1)
      }
      else {
        compressHelper(tail, acc :+ (head, counter), head, 1)
      }

    }
    case Nil => acc



  }


}
compressHelper(l, List(), , 1)

}

CQRS design pattern in microservices

Can somebody give real time example of CQRS pattern? Let suppose I am working for banking application, so account creation, balance update everything I will put in command and balance check I will put in query. this is in simple layman terms.

Can somebody explain how technically I should design? for command and query which database will be helpful SQL or NOSQL and why?

Pattern detection in sequence of users behaviour for clustering

I need to detect variable-size patterns in a set of fixed-size strings, where each string represents a sequence of activity of a group of users.

As an example, i have a 10 character string or user 1 where each char represents an activity intensity: 'LLMLLMGLML' meaning that the first 2 samples where of a low intensity, the third a medium intensity and then the activity gets lower again. Another example, for user2: 'LMMGMLLMLL'. Both users had a common pattern: 'LLMLL'

My intention is to classify users in terms of their overall activity, defining similarity based on the number of common patterns

Can you recommend an approach to this problem?

Should you use nested directories for entities when designing your symfony application?

Should you use nested directories for entities when designing a Symfony application?

For example, we have many entities, is it worth splitting them into folders using namespases?

User
User/Domain
User/Domain/Response
...

vs

User
UserDomain
UserDomainResponse
...

vs

User
Domain
Response
...

It seems to me that the second approach is more logical, but it seems to me that it is rarely used.

Which is the best to use and why? Perhaps there is a coding style guide in Symfony?

How to implement multilayer in asp.net core web api when using repostiry pattern?

I am very new to programming actually I have different layer in project basically I want to to perform database related operation in separate data access layer not in repository concrete class, I have searched on google to solve my problem but could not find any help to solve my problem, sorry about my weak English.

webApi(Controller)

    [HttpPost]
    [Route("api/account/Login")]
    public int Login(LoginViewModel model)
    {          
            var result = _accountRepository.Login(model);
            return result;         
    }

Repository (in another library project)

 public class AccountRepository : IAccountRepository
        {
         public int Login(LoginViewModel model)
            {           

// **this below database related operation I want to move into another library(Data access layer)**

            var p = new DynamicParameters();
            p.Add("@pLogin", model.Email);
            p.Add("@pPassword", model.Password);
            var result = _dapper.Get<int>("[uspLoginUser]", p, commandType: CommandType.StoredProcedure);
            return result;
               
            }
       }

this is what I want to do in repository pattern to call another function which would be in another layer called data access.

public class AccountRepository : IAccountRepository
{
    public int Login(LoginViewModel model)
        {
           
                var result = _AccountAction.LoginUser(model);
                return result;
           
        }
  }

Data Access layer

public class AccountAction
    {
        private readonly IDBHelper _dapper;       
        public AccountAction(IDBHelper dapper)
        {
            _dapper = dapper;
        }
        
        public int LoginUser(LoginViewModel model)
        {
            var p = new DynamicParameters();
            p.Add("@pLogin", model.Email);
            p.Add("@pPassword", model.Password);
            var result = _dapper.Get<int>("[uspLoginUser]", p, commandType: CommandType.StoredProcedure);
            return result;

        }
    }

DBHelper

public interface IDBHelper : IDisposable  
    {
        DbConnection GetConnection();
        T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);
        List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);
        int Execute(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);
        T Insert<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);
        T Update<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure);
    }

samedi 27 mars 2021

How to print the factorial of a number like this? [closed]

How to print a factorial of a number in this pattern in C and Python. For example, Factorial of 5 is 120 and it will print like this -

1 * 2 * 3 * 4 * 5 = 120

Confusion with loops in mips

Pattern: 1 22 333 4444 55555 I have printed the above pattern in C but having problems while writing this program in MIPS. I think I am not good with the nested loops but I am learning. Someone please help.

Python to Mips Pattern conversion

My school assignment requires me to convert this python code to mips, I am beginner at MIPS hence I have no idea how to approach this solution.

Please make sure to comment the code which could help me understand the code.

Any help would be appreciated.

TIA.

#Set Values

#take input for max no of symbols from user

max_no_of_symbols=int(input("Enter Max Number Of Sybols(should Be ODD)"))

#only enter odd num

if max_no_of_symbols %2 == 0:

print("Error, Please enter a odd number")

else:

#caculate num of spaces

NumOfSpaces=int((max_no_of_symbols-1)/2)

NumOfSymbols=1

while NumOfSymbols != max_no_of_symbols :

    #print output

    for i in range(NumOfSpaces):

        print(" ",end="")

    for i in range(NumOfSymbols):

        print(NumOfSymbols, end="")

    #adjusting values for new line

    NumOfSpaces=NumOfSpaces-1

    NumOfSymbols=NumOfSymbols+2

    print(" ")


while NumOfSymbols != 0 :

   #print output

    for i in range(NumOfSpaces):

        print(" ",end="")

    for i in range(NumOfSymbols):

        print(NumOfSymbols, end="")

    #adjusting values for new line

    NumOfSpaces=NumOfSpaces+1

    NumOfSymbols=NumOfSymbols-2

    print(" ")

Print pattern in MIPS

How to print the following two patterns in MIPS:

a)
1
12
123
1234
12345

b)
1
22
333
4444
55555

Thanks!!

Choosing a design pattern and data structure for multiple sets of questions with varying difficulties

I have a Question class:

class Question 
{
    int Id { get; set; };
    string Text { get; set; }
    QuestionDifficulty Difficulty { get; set; }
    List<Answer> Answers { get; set; }
}

And an enumeration QuestionDifficulty:

enum QuestionDifficulty { Easy, Medium, Hard, VeryHard }

I have to pick multiple question sets of the same size of each difficulty level from a container collection called Repository for a test:

class Repository { List<Question> Questions { get; set; } /*other fields omitted for brevity*/ }

The number of questions to be picked for each difficulty level will be specified by a dictionary IDictionary<QuestionDifficulty, int>. Since there are multiple ways it can be picked, I have written an interface IQuestionPicker that defines this behavior. :

interface IQuestionPicker
{ 
    public QResult Pick(Repository repo, 
                               int setCount, 
                               IDictionary<QuestionDifficulty, int> requiredQuestionCounts);
}

One of the implementations is called UniqueQuestionPicker that picks a different collection of questions for each set. So no two sets will have any common questions. Hence, the Repository container needs to have, for each difficulty level, at least requiredQuestionCounts[difficulty] * setCount questions. So it performs the validation first. I wanted to move this validation to its own method HasEnoughQuestions() returning a bool. But I realized then I cannot include the data about which difficulty level has the problem in my exception.

class UniqueQuestionPicker : IQuestionPicker
{
    public List<QuestionResult> Pick(Repository repo, 
                               int setCount, 
                               IDictionary<QuestionDifficulty, int> requiredQuestionCounts)
    {
         var questions = repo.Questions ?? 
                throw new NullReferenceException($"{nameof(repo.Questions)} of argument {nameof(repo)} is null");

            var groups = questions.GroupBy(question => question.Difficulty);
            
            // Get actual number of questions for each difficulty level
            Dictionary<QuestionDifficulty, int> actualQuestionCounts = groups
                .ToDictionary(group => group.Key, group => group.Count());
            
            // Validate if each difficulty level has enough questions
            foreach (var difficulty in actualQuestionCounts.Keys)
            {
                int requiredQuestions = requiredQuestionCounts[difficulty] * setCount;
                int actualQuestions = actualQuestionCounts[difficulty];
                if (actualQuestions < requiredQuestions)
                {
                    throw new InvalidOperationException(
                        $"Not enough questions of difficulty \"{difficulty}\"")
                    {
                        Data =
                        {
                            ["RequiredQs"] = requiredQuestions,
                            ["ActualQs"] = actualQuestions
                        }
                    };
                }

            Random random = new();
            List<QuestionResult> results = new();
            foreach(var group in groups)
            {
                var difficulty = group.Key;
                QuestionResult result = 
                    new(difficulty, setCount, questionsPerSet: requiredQuestionCounts[difficulty]);

                var shuffledQuestions = group.OrderBy(q => random.Next());
                
                for(int i = 0; !result.Full; i++)
                {
                    result.Add(shuffledQuestions.ElementAt(i));
                }
                results.Add(result);
            }
            return results;
            }  
    }
}

I'm a bit unsure about how my result data structure QResult should look like. It should contain the specified number of question sets, each set containing the specified number of easy, medium, hard and very hard questions. I had first planned to use IDictionary<QuestionDifficulty, List<HashSet<Question>>>, or IList<IDictionary<QuestionDifficulty, HashSet<Question>>> but they both look a bit clumsy. I want to also allow combining two QResults picked from different repositories to be merged to a new QResult.

I plan to include more picker implementations like ShuffledQuestionPicker which would include the same questions in each set but they will be shuffled.


This is what the current QResult I've written called QuestionResult looks like. Once the SetCount and QuestionsPerSet are passed through its constructor, the Add() method automatically creates a new HashSet<Question> and advances an internal pointer called currentSet when the QuestionSets[currentSet].Count becomes equal to QuestionsPerSet. I have used a HashSet since I have to check before adding the question, that none of the previous sets contain it already and this makes it O(1). A QuestionResult object will exist for each difficulty level, hence my picker returns List<QuestionResult>.

public class QuestionResult
    {
        public IEnumerable<IEnumerable<Question>> QuestionSets { get => questionSets; }

        public int QuestionsPerSet { get; }

        public int SetCount { get; }

        public bool Full { get; private set;  }

        private readonly List<HashSet<Question>> questionSets = new();

        private int currentSet = 0;

        public QuestionDifficulty Difficulty { get; }

        public QuestionResult(QuestionDifficulty difficulty, int setCount, int questionsPerSet)
        {
            Difficulty = difficulty;
            QuestionsPerSet = questionsPerSet;
            SetCount = setCount;
        }

        public void Add(Question question)
        {
            if (questionSets[currentSet].Count == QuestionsPerSet)
            {
                questionSets.Add(new HashSet<Question>());
                currentSet++;
            }
            if (questionSets.Any(set => set.Contains(question)))
            {
                throw new InvalidOperationException("Duplicate addition attempted");
            }
            if(questionSets.Count == SetCount && questionSets[currentSet].Count == QuestionsPerSet)
            {
                Full = true;
            }
        }

        public bool TryAdd(Question question)
        {
            try 
            {
                questionSets[currentSet].Add(question);
                return true;
            }
            catch(InvalidOperationException)
            {
                return false;
            }
        }
    }

Something about this approach does not feel right, it has gotten quite complex. Can someone recommend a better way to do this, a better data structure and design pattern?

vendredi 26 mars 2021

what is the best creational pattern to apply for class to access different databases

i have an application written in python

currently there are around 5 classes that are used to access different databases.

Structure of these classes are like below (i know it is poorly designed):

class access_db_a(self, db):
      def connect():
      def select():
      def insert():

class access_db_b(self, db_2):
      def connect():
      def select():
      def insert():

My question is: what is the best creational design pattern to apply here (i.e. Signleton, Factory Method)?

Using Spring Service to only save using Sping JPA, I have done it for single responsibility, Is it a correct approach?

In spring-boot I have a Service class which is used to only save using spring-data. I have done it for Single Responsibility of SOLID design pattern. Is it the right approach? or Can we call directly repository in the place implementation in another service.

public class Sample {
    Test save(Test test);
}

@Service 
@AllArgsConstructor

public class SampleImpl implements Sample {
   final TestRepository testRepository;
    
@Override
 Test save(Test test) {
testRepository.save(test);
}

}

@Service
@AllArgsConstructor
public class HelloWorldServiceImpl implements HelloWorldServive {
   private final TestService testService; // Is this right 
   private final TestRepository testRepository; // Is this right to use?
   private final HelloWorldService helloWorldService;

   @Override
   public helloWorld() {
     Test test = new Test();
     testService.save(test);

     HelloWord helloWorld = new HelloWorld();
     helloWorldService.save(helloWorld);
 }

}

Design pattern for different formats

I have a requirement where i need to output data in given format (can be anything xml, json, doc, csv, xls, signed xml) etc. After that I need to wrap it in given format (zip, gzip, cab, etc). What would be good design pattern for it?

Memento Pattern:Philosophy of createMemento() method in Originator class

I've question about the philosophy of createMemento() in Originator class in Memento Pattern.

My teacher said:

now that Originator class no longer stores Memento objects internally, we should give it two new methods; createMemento() and setMemento().

The createMemento() method stores the current state of the Originator inside a Memento object and returns it. So we call this method and say, "Hey, save your current state and give it to me", we'll get an Memento object.

I'm confused. Because when I was trying to implement the Originator class that stores a list of Memento internally ,I still needed to have this createMemento() method.

my class:

public class MyOriginator {

    private String content;
    
    //stores a list of Momento internally
    private List<Momento> previousStates;

    public MyOriginator() {

        previousStates = new ArrayList<>();
    }

    public void push() {
        previousStates.add(createMomento());
    }

    // need to have it.
    private Momento createMomento() {
        return new Momento(content);
    }

    public void pop() {

        int lastIndex = previousStates.size() - 1;

        this.content = previousStates.get(lastIndex).getContent();

        previousStates.remove(lastIndex);
    }
}

So createMemento() seems to have nothing to do with storing or not storing Memento objects internally and storing or not storing Memento objects internally is not the reason of making and using of createMemento().

What is the reason for using and creating this method? in both case ( stores Memento objects internally and not storing Memento objects internally), I had to implement that method.

How the compiler infer types using strategy pattern (with overloaded() in struct or class)?

I am struggling to understand how this code even compile when passing a "callable" struct/class.

Referring to the main function below, I would expect the compiler to tell me that there is no matching constructor for Point3D (CallableI is not an instance of FuncType).

What I would be tempting to do is to create an algo member inside CallableI and constructs the point referring to it. But this solution is better on many aspect so I want to understand how it is working under the hood.

I have a base class Point3D :

template<typename T>
class Point3D
{
typedef std::function<T (const Point3D<T> &p1, const Point3D<T> &p2)> FuncType;
private:
    T x;
    T y;
    T z;
    FuncType algo;
public:
    Point3D(T x, T y, T z, FuncType algo) : x(x), y(y), z(z), algo(algo){}
    T First() const {return x;}
    T Second() const {return y;}
    T Third() const {return z;}
    
    T computeDistance(Point3D<T> &p2){
        return algo(*this, p2);
    }
};

I am using a struct CallableI to hold a particular function to be called overloading operator ().

struct CallableI
{
    CallableI(){};
    
    double operator() (const Point3D<double> &p1, const Point3D<double> &p2){
        double x1{p1.First()}; double x2{p2.First()};
        double y1{p1.Second()}; double y2{p2.Second()};
        return std::abs(x1 - x2) + std::abs(y1 - y2);
    }
};

And I am calling the suggested code with the main function below :

int main(int argc, char **argv) {
    
    CallableI myCallable;
    Point3D<double> p1(14.3, 12.3, 2.0, myCallable);
    return 0;

Type safe container for Bipredicate

I have a design problem that I'm not sure how to solve. I've created an Evaluator class that evaluates a parsed expression. The expression is of shape amount > 50. The operator is used to understand which predicate must be created. Then, the LHS is sent to a different object to get its actual value. The value can be String, Integer, Double and more. My problem starts when I try to create the correcet predicate and initialise it with the proper values. I get warnings that it isn't type-safe, using a raw type etc. I'd like to solve this issue if I can and not suppress the warnings. My current thought is creating a container class which I named Value, that's generic. But I'm stuck on continuing this line of thought. My code:


public class Evaluator {
    static PredicateFactory predFactory = new PredicateFactory();


    public boolean evaluate(String[] expression, Data data){ // currently doesn't actually work, just testing
        BiPredicate predicate = predFactory.createPred(expression[1]);
        predicate.test(data.getAttribute(expression[0]), 50);
    }
}

public class PredicateFactory {


    public BiPredicate<?,?> createPred(String operator) {
        return switch (operator) {
            case "<" -> (BiPredicate<Double, String>) (i, j) -> i <  Double.parseDouble(j);
            case ">" -> (BiPredicate<Double, String>) (i, j) -> i >  Double.parseDouble(j);
            case "from domain" -> (BiPredicate<String, String>) (i, j) -> i.endsWith("@" + j);
            default -> null;
        };
    }

public class Value<T>{
    private T val;

    Value(T val){
        this.val = val;
    }

    public T getVal(){
        return this.val;
    }
}


public class Data {
    private int id;
    private int total_price;
    private String date;
    private String email;
   ....

    Data(int id, int price, String date, String email, ){
        this.id = id;
        this.total_price = price;
        this.date = date;
        this.email = email;
.....
    }

    public Value<?> getAttribute(String attribute){ 
        return switch(attribute){
            case "value" -> new Value<>((double) this.total_price);
            case "email" -> new Value<>(this.email);
            default -> null;
        };

    }
}


Thank you for any pointers

Is it good design to have state-representative properties on a service class?

I have an application with a service class that retrieves database metadata from a database and returns it to calling classes.

To connect to the database, the service class methods accept a parameter that details the connection credentials.

I'm considering a change whereby the credentials would be stored within the service class. One of the reasons for this is that calling classes (which have the responsibility, for example, of comparing schemas on different servers) may connect to multiple different databases/servers, so the calling class would basically have a collection of these service classes, rather than a collection of connection credentials (e.g., IConnectionInfo in the following example).

Another thing I might like to do within the application is to have implementation of this service class (IDatabaseService in the following example) for different types of RDBMS (e.g., SQL Server, Oracle, etc.), and this seems like the best way of leaving it open to that (the information returned from the service would be very generic and applicable to all supported types of RDBMS).

Example code for what the service class might look like:

public class DatabaseService : IDatabaseService
{
    private readonly IConnectionInfo ConnectionInfo;
    
    public bool IsConnected; // INotifyPropertyChanged
    
    public string ServerName => IConnectionInfo.ServerName;
    public string DatabaseName => IConnectionInfo.DatabaseName;
    
    public DatabaseService(IConnectionInfo connectionInfo)
    {
        ConnectionInfo = connectionInfo;
    }
    
    public IEnumerable<Table> GetTables()
    {
        //...
    }
    
    public IEnumerable<Column> GetTableColumns(Table table)
    {
        //...
    }
}

There are a few reasons I'm a bit doubtful of this approach:

  1. I'm implementing INotifyPropertyChanged within this class so that I can update the UI to show the user whether or not they are connected (e.g., I could switch this to false if any calls to the server failed). For this reason it seems to behave like a ViewModel (as opposed to a Service).

  2. I'm unsure as to whether it's good practice to have properties on a service class that represent its state, e.g., ConnectionInfo, IsConnected.

Does the above look like an acceptable design?

Build a design system with Vuejs

Hi and thanks in advance for taking a time to read this.

Im really new in this subject but as the title says, im trying to get information about how to create a small custom design system with Vuejs ( like carbon design system) that could work across platforms (like Wordpress) importing it as a library ( as bootstrap for example) for brand consistency. I don't know if it is something that one can do with this framework and if i should take others technologies in consideration to do so. If someone has experience in this and can tell me where to look, it would be really helpful.

Thank you :)

Python Program to print Diamond pattern for input numbers?

I want this output:

         1 

     0      0

 1       1       1 

      0      0

         1

My code:

    n=2
k = 2 * n - 2
x = 0
for i in range(0, n):
    x += 1
    for j in range(0, k):
        print(end=" ")
    k = k - 1
    for j in range(0, i + 1):
        if(x==2):
            print(0,end=" ")
        else:
            print(1, end=" ")
    print("\r")
k = n - 2
x = n + 2
for i in range(n, -1, -1):
    x -= 1
    for j in range(k, 0, -1):
        print(end=" ")
    k = k + 1
    for j in range(0, i + 1):
        if(x==2):
            print(0,end=" ")
        else:
            print(x, end=" ")
    print("\r")

For the above code I am getting output:

    1 

  0   0 

3   3   3 

 0    0 

    1 

Defensive programming against client code if I myself implement the client code and the Interface?

I'm writing an application in Python. Somewhere, I write a model layer composed with classes, and, any of them, say:

class Orders:

has a bound method whose signature is :

def delete(self, id=None, name=None):

I need id or name not to be None. Then, here is my question:

Since I myself write the model layer and the client code, which would be something like:

model.Orders().delete(id=1234)

Would be good practice to check the parameters inside the delete method with code like:

if not any((id, name)):
    raise ValueError('Order Id or Order name must be provided')

?

I think, since I write the two sides, I will always call the delete method providing one of the parameters avoiding checking and saving a lot of code. I expect the model layer will reach 2 or 3 thousand lines, interfacing a database server.

I put a specific example, but I'd appreciate an answer for the general case.

Plural class implementing singular. Is there a name for this design pattern?

Say I have a Product interface with a single method price():

interface Product {
  fun price(): Float
}

Now, I create a Products class that implements it:

class Products(private val products: List<Product>): Product {
  fun price() : Float {
    return products.fold(0f) { acc, fl -> acc + fl }
  }
}

Maybe Product is not the best example, but I find this pattern useful when you need to aggregate many products' price in many places of your codebase. This way, that logic is encapsulated in Products class.

I wonder if there is a name for this pattern.

jeudi 25 mars 2021

Upload to s3 which trigger lambda, wait for lambda to respond

So I have an architecture in which the user uploads there file onto the front end, which then sends it to a s3 bucket, which in turn triggers a lambda for validation and processing, which sends the response to the front end of successful upload or validation error.

I don't understand if there is way to implement this in JavaScript (or any other similar language).

In the normal scenario, the front end uploads to server 1, and waits for it's response. The server 1 then tells the front end whether it was a success or a failure, and that is what the front end tells the user.

But in this case, the upload is done to s3 (which is incapable of taking responses from lambda, and send it back to the user), and response is to be expected from the other one (the lambda).

How can this be implemented? If the architecture is flawed, please do suggest improvements.

Can you recommend some inspiring high-quality open-source projects to learn from?

Aspects I am interested in:

  • delivery and maintenance of a very complex project,
  • design patterns usage in practice,
  • SOLID principles in practice,
  • versioning,
  • security,
  • implementation of a customizable white label product,

I am primarily interested in web applications implemented using typescript, react, node.js (including frontend and backend). However, other projects written in any standard language are also welcome.

matching the string with pattern with no of mismatches. My code is working correctly but i can't figure out how to optimize it and make it faster

#python3

import sys
from _collections import deque

def hashTable(s, prime, x):    # calcuate hash
    h = list([] for _ in range(len(s) + 1))
    h[0] = 0
    for i in range(1, len(s) + 1):
        h[i] = (h[i - 1] * x + ord(s[i - 1])) % prime
    return h

def subhash(table, start, length):    #calculate subhash
    y = pow(x, length, pr)
    hash_value = (table[start + length] - y * table[start]) % pr
    return hash_value

def nextmsm(le, i, n):        #find next mismatch
    c = 0
    st = deque()
    st.append((0, le))
    a = 0
    while len(st) != 0:
        if c > n:
            break
        a, le = st.pop()
        th = subhash(tx, a+i, le)
        ph = subhash(pt, a, le)
        if th == ph:
            continue
        if le == 1:
            if th != ph:
                c = c + 1
        else :
            st.append((a, le//2))
            st.append((a+le//2, le - le//2))

    if c > n:
        return False
    return True


def solve(o, text, pattern):     # find pattern with mismatch
    global tx, pt
    pos = []
    tx = hashTable(text, pr, x)
    pt = hashTable(pattern, pr, x)
    for i in range(len(text) - len(pattern)+1):
        if nextmsm(len(pattern), i, o):
            pos.append(i)

    return pos


pr = 1000000007
x = 263
while True:
    line = input()
    k, t, p = line.split()
    ans = solve(int(k), t, p)
    print(len(ans), *ans)

this sol first takes the input k that is no of max mismatch, t= text, p = pattern, it then passes to solve function which calculates the hash value and call function msmatch to find no of mismatch. Msmatach function calculates the subhash which then with the help of binary search helps to find no of mismatch

Factory Design Pattern in Python

Situation: I have implemented a factory design pattern in Python as below. There are different screens which have different configurations. One can register the screen in the factory and get the screen in case correct configuration is passed to respective factory class method.

Question: I am wondering if this is a clean solution as each screen class (Screen1, Screen2, ..) has a main-method which calls in a specific order the respective private class methods. Is there a better/cleaner way to handle the main methods in each class?

Highly appreciate any comments and improvements!!

Code:

import numpy as np
import pandas as pd

from abc import ABCMeta, abstractmethod 

df = pd.DataFrame({"ident": ["A1", "A2", "B3", "B4"], "other_col": np.random.randint(1, 6, 4)})


class IScreens(metaclass=ABCMeta):

    @abstractmethod
    def main(self):
        pass 
    

class Screen1(IScreens):
    
    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]    
    
    def __get_letter(self):
        self.data["campaign"] = self.data[self.batch].str[:1]

        return self.data
    
    def __get_number(self):
        self.data["num"] = self.data[self.batch].str[1:]

        return self.data
    
    def __some_other_stuff(self):
        self.data["other_stuff"] = self.data["num"].astype(int) * 100 / 2

        return self.data
    
    def main(self):
        self.data = self.__get_letter()
        self.data = self.__get_number()
        self.data = self.__some_other_stuff()
        # some more processing steps follow 

        return self.data
    
    
class Screen2(IScreens):
    
    def __init__(self, data, config):
        self.data = data
        self.batch = config["cfg1"]    
    
    def __some_cool_stuff(self):
        self.data["cool_other_stuff"] = self.data[self.batch] + "_COOOOL"

        return self.data
    
    def main(self):
        self.data = self.__some_cool_stuff()
        # some more processing steps follow 
        
        return self.data
        

class ScreenFactory:

    def __init__(self):
        self._screens = {}

    def register_screen(self, screen_name, screen_class):
        self._screens[screen_name] = screen_class
    
    def get_screen(self, data, config):
        
        if "screen_indicator" not in config:
            raise AssertionError("Your config file does not include 'screen_indicator' key")
        
        screen = self._screens.get(config["screen_indicator"])
        if not screen:
            raise AssertionError("screen not implemented")
        return screen(data=data, config=config)
    

factory = ScreenFactory()

factory.register_screen(screen_name="s1", screen_class=Screen1)
config = {"screen_indicator": "s1", "cfg1": "ident"}
factory.get_screen(data=df, config=config).main()

factory.register_screen(screen_name="s2", screen_class=Screen2)
config = {"screen_indicator": "s2", "cfg1": "ident"}
factory.get_screen(data=df, config=config).main()

Database Architecture for booking system with slots and passes

I'm in the process of designing a booking system that allows admins to create bookable entities such as squash courts, tennis courts etc. For this system an admin would create slots for each of those entities and then assign those slots either to a specific day.

The system, however should also be able to book passes such as day passes or weekend passes which would essentially encompass several slots.

Slots Table

Day Start Time End time
1 9:00 10:00
2 9:00 10:00

If for example day 1, which is a Monday has 7 one-hour slots and Tuesday has the same and I want to create a two day pass, how would I set up my database architecture to accomplish this, keeping in mind that other users should still be able to book individual slots and making sure that we can set a maximum limit on how many times the individual slot can be booked?

Why do so many libs have their own base Exception class?

I recently noticed that a lot of libraries and frameworks bring their own base Exception class. The list is quite long.

enter image description here

When checking the code I only find them to be empty and extending PHPs own Exception class or another empty class which then extends PHPs base Exception. For example in PHPUnit:

https://github.com/sebastianbergmann/phpunit/blob/master/src/Util/Exception.php

Does every lib has it's own reasons to do so or is there some general concept I'm not aware of?

BOM - best naming

I have a basic question about naming a BOM-project.

I have outsourced the dependencies of my project to a separate BOM and now want to use the advantages of dependency management. I have integrated this BOM into my projects as a parent.

Later I would like to migrate all my projects from Spring to SpringBoot, which is why the BOM will later receive the SpringBoot parent as a parent. This gives me the following structure: [SpringBoot-Parent] -> [myBOM] -> [myProject]

My BOM is currently called xyz-dependencies.

I would be interested in your opinion and experience. Would you call the BOM xyz-dependencies or xyz-parent?

Best regards

C# Winforms MVP: How to bind complex properties in Supervising Presenter/Controller variant?

Despite reading a lot of Q&A and blogs about this topic, I am still having trouble finding a concrete example of both Passive View and Supervising Controller comparison in code, in particular how databinding works in Winforms for "complex" objects/properties. Passive View is clear to me, but I do not understand how this is supposed to be implemented in Supervising Controller (or even if in this case, Passive View is the only alternative).

Tried to come up with a very simple example.
This can be considered as pseudo-code:

public class Model
{
    public string Name { get; set; }
    public Dictionary <string, string> PhoneNumbers { get; set; }
}

public class View : IView // Form
{
    public TextBox txtName { get; set; }

    // Supervising presenter
    // How to bind these to Model's PhoneNumbers dictionary property?
    // Should this be 1-way binding (data to view), 2-way binding, or be performed by presenter?
    // Should there be a "ViewModel" that exposes these separately somehow?
    public DropDownList cmbPhoneState { get; set; } // keys
    public TextBox txtPhoneNumber     { get; set; } // values
}

public class Presenter
{
    private IView view;
    private Model model;

    public Presenter(IView view)
    {
        this.view = view;
        this.model = new Model();
    }

    // Passive view
    // 1. Populate cmbPhoneState with keys from model's dictionary, and (for ex.) set first one selected
    // 2. Show first phone number value in textbox; when user changes selection, update view accordingly

    // Supervising presenter
    // -> ?
}

In this post it seems that the author comes up with a solution, but this seems extremely overkill to the average developer I am for such a simple requirement. I don't need 100% test coverage and I am not trying to avoid doing work; simple does not mean lazy.

How should the view bind to complex properties (ex. a dictionary, or another custom Type) in Supervising Controller pattern? Say user adds another phone number to the collection: this happens in the view, but then who notifies who, and how?
Alternatively: should this pattern be avoided in this case and more complex ones?

(please no link to Martin Fowler articles or Wikipedia in the answer; pseudo-code is very welcome)

mercredi 24 mars 2021

Extracting certain word(s) after specific pattern, while excluding specified patterns. in R

Using R, I want to extract the building, plaza or mansion names. The names are ahead of whether its specified a building ,mansion, plaza. Here is an example

addresses<-c("big fake plaza, 12 this street,district, city", 
"Green mansion, district, city", 
 "Block 7 of orange building  district, city",
"98 main street block a blue plaza, city",
 "blue red mansion, 46 pearl street, city")            

What I want to get is

"big fake" "Green" "orange" "blue" "blue red"

The code I currently using is

str_extract(addresses, "[[a-z]]*\\s*[[a-z]+]*\\s*(?=(building|mansion|plaza))")

Sometime the name is two words sometimes one. However because of the varied format, sometimes there is an 'a' or 'of' which is also getting extracted. How do I continue to extract the two word formats of the building name but exclude the 'a' or 'of'

Thanks in advance

Is there an elegant way to manage multiple related functions through one big function? [duplicate]

I have n different functions that are all highly related but take slightly different arguments.
As a metaphor, consider that they represent n different sorting algorithms. Now, I want one big parameterized function sort which is called from the outside and then internally calls the correct sorting algorithm / the correct function.
As an additional requirement, it must be possible to give all these subfunctions different input information (different number of arguments).

I came up with a solution but I feel like this is bad style.. can anyone with more experience give his/her thoughts to this solution?

def function_one(*args):
    arg1, arg2 = args[0:2]
    # do something here
    
def function_two(*args):
    arg3, arg4 = args[2:4]
    # do something here

# imagine that here are more functions

def function_n(*args):
    arg1, arg3, arg5 = args[0], args[2], args[4]
    # do something here

switcher = {
    'one': function_one,
    'two': function_two,
    # ... imagine that here are more mappings
    'n': function_n
}

def some_super_function(arg0, arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, ..., argN=None):
    return switcher.get(arg0)(arg1, arg2, arg3, arg4, arg5, ..., argN)

using(), access data from parent callee for logging purposes

I have a custom build log framework that logs to a database.

For example it can do

L.e("Error invalid password", userGuid);

This works fine for general use but the application is quite complex and there are a lot of different parts that are called from the main code. For example a login sequence could send an SMS for OTP which is handled by a completely other part of the system and it does not make sense to pass a lot of values thru just for logging purposes.

What I want to achieve is to tag the log with for example userGuid so that I can search for everything related to this specific user. I also want to tag any logging in the SMS module even though the SMS module does not know anything about the user concept.

So what I am thinking of is if it is possible to get the current threadid and store some things regarding the logging in a higher level. I wonder if this is at all possible.

Psuedo code:

void Login(UserName, Password) {
    User user = UserManager.GetUser(UserName)
    using(L.SetUser(user.ID)) {   //Here I want to use user.ID later in code that dont know the context
        SmsManager.SendOtp(user.Phonenumber)
    }
}

public class SmsManager {
    public static void SendOtp(string phonenumber) {
        if (phonenumber == "") {
            L.error("Phone number is empty");   //How can I use the value from L.SetUser above? Could I use a hash table of threadids in L or would that be a bad idea? 
        }
    }
}

Kind regards Jens

How to maintain well structured code and latency optimized code together?

I'm working on a c++ data analysis project. My workflow goes like this

  1. Analyze the data and build models
  2. Optimize the code for latency, to deploy for production
  3. goto 1

Step 1 has lots of machine learning parameters, using which I test very minor variations of algorithms. In step 2, I clean up the unused parts of the code (non optimal parameters), optimize code for latency (changing maps to arrays for example), and deploy the code. These modifications are done directly on the step 1's code. No separate branch in maintained.

When new data is obtained and step 1 is required to be repeated, I would have lost the ability to test minor variations of an algorithm. One way to solve this is to maintain two branches. One will be an experimental branch, which has all the parameters for the minor variations of the algorithm. Another branch will be latency optimized code. But, the problem here is any small change in experimental branch will need to be repeated in the latency optimized branch, because there two branches cannot be merged. There are huge differences (even new files appearing) between experimental branch and latency optimized branch, which hinder direct merging.

Is there any other way to solve this?

regex expression that match any type of characters excluding white space [duplicate]

i need a regular expression that match any type of caractér except whitespace anywhere i used this one [^] its okay for any type of character but it still accept white space

design pattern for links

I have a bunch of functors that take some data and build new ones when operator() is invoked. The input data of the functors may be some "local" data to the functor, some "global static" data, or the result of another functor.

In the first two cases, the functor has full control of the lifecycle of the data (either local or guaranteed to last forever). The problem comes with the last case, since functors may be deleted, modified and re-run, leading to reallocation or deletion.

I was thinking of developing a single interface of a Link, that basically acts as a proxy for the data. Something like:

template<typename T>
class Link {
  T & get();
};

Maybe, provide specializations for Persistent and Builded types and, in the last case, also provide methods to query the memory state of the data (broken link) or to ask who is supposed to build it.

How this kind of problems is generally approached? Should I also create an Output class whose instances are owned by the functors that actually build that data?

Bonus question : how to correctly define operator< to allow the use of associative containers, without risking to lose data?

std::map<Link<Key>,Value>

weak_ptr do not allow it

mardi 23 mars 2021

How to solve this strong dependency between those classes?

I have two classes A and B.

Class A has several properties. One of them are an instance of class B.

At some point in the main function I will define an instance a of A. I will need to do some computation on its property of type B. This computation, however, needs another property of a.

The result is a.property3.computation(a.property1,someValue). I think it's ugly.

Here is some "pseudo-code" (in Kotlin but I am facing the same problem using other languages as well):

class B {
    val property : Map<String,Int>
    
    fun computation(val parameter1: Int, val parametre2: Double) : Int {
        //doing some computation
        return result
    }
}

class A {
    var property1 : Int 
    var property2 : Stirng 
    var property3 : B 
}

fun main (){
    val someValue = 0.4 //It's here to show the idea that the function `computation` needs also some other arguments that does not come from `A`'s propery
    val a = A()
    val result = a.property3.computation(a.property1,someValue)  // here is the line that bothers me !
}

Laravel Controller Pattern, when put all logic?

Turn and move, I'm developing in laravel, and I still don't know what I do when I face this situation,

Usually when you access the controller through any service to search for any resource, such as a list of users, you use it directly in the model, such as

User :: all () and returns, and it's good, the controller doesn't look so dirty, however, when working with reports, the situation seems to get out of control a little

Because you need to access more than one model, do specific searches in the database, calculations too, etc ... Your controller is getting huge and with a lot of responsibilities

I particularly create a helper class and put these functions in it, and then I call the controller, but even so, every time I do this I still do not have the impression that the concept of responsibility has not been defined correctly,

I see people mixing this with the concept of a repository, which also doesn't seem right since the repository serves to create a channel for accessing storage data more like a contract, right,

So, if someone can help me with this question I would be very grateful, where do I put all this logic from the controller?

How do you do it?

#laravel #patterndesign

Does the decorator pattern violate SOLID principles?

Let's say we have a component class like this:

class Component:
    def operation(self) -> str:
        return f"Performing operation"

    def another_operation(self) -> str:
        return f"Performing another operation"

We then have a child of component that overrides both of its methods:

class ChildComponent(Component):
    def operation(self) -> str:
        return f"Performing operation differently"

    def another_operation(self) -> str:
        return f"Performing another operation differently"

We may then define a decorator that modifies the behaviour of operation:

class Decorator(Component):
    _component: Component = None

    def __init__(self, component: Component) -> None:
        self._component = component

    def operation(self) -> str:
        return f"Decorated...({self._component.operation()})"

    def another_operation(self) -> str:
        return self._component.another_operation()

From my understanding, even though we are not modifying the behaviour of another_operation() in the decorator, we must still define it rather than rely on the superclass method otherwise Component's another_operation() will be called instead of ChildComponent's method, and you'd have a bad hybrid situation on your hands.

If we were to do that however, then any time the Component class gained a new method, we'd have to add it to the decorator too, which isn't in keeping with the Interface Segregation Principle. So we either have to violate SOLID principles and maintain twice the amount of code that we need to, or risk using the wrong methods for those we don't explicitly override in the decorator.

Could someone please provide some clarity around this?

How to pass regex in presidio library

I want to recognize my custom pattern using Microsoft's Presidio library in python. while passing the regex I am getting this error. AttributeError: 'str' object has no attribute 'regex'

from presidio_analyzer import PatternRecognizer
regex = ("^[2-9]{1}[0-9]{3}\\" +
             "s[0-9]{4}\\s[0-9]{4}$")
#p = re.compile(regex)
aadhar_number_recognizer = PatternRecognizer(supported_entity="AADHAR_NUMBER",
                                      patterns=[regex])```

How to write a program to print X OR O triangles which combinely form a box of matrix

How to write a pattern program which prints a output in the form like

Ex1: input : no of rows = 5

output : X O O O O
         X X O O O
         X X X O O
         X X X X O
         X X X X X

Ex2: input : no of rows = 3

 output : X O O
          X X O
          X X X 

I'm getting this error while executing the Haskell program

Question:Define a new Rating type with the constructors One, Two, .. Five. It should

derive Ord, Eq and Enum behaviors

Make the new type an instance of Show, giving the displays as the appropriate number

of stars (i.e., "*", "**" and so on) My program: import System.IO

import Data.List

main = do --Main function

data Rating = One | Two | Three | Four | Five deriving (Eq, Ord, Show, Enum) {-Created a new Rating datatype with constructors One,Two..Five deriving Ord,Eq,Enum behaviours

instance Show Rating where --Creating New instance of show show One ""
show Two "" show Three "
" show Four "****" show Five "*****" Error: Error parse error on input data

Single web app, multiple client(UI localization)

I have one web application and multiple clients. Language localization is not an issue as it is already handled. But UI feature localization is now starting to look bad as the number of clients grows.

lets say I have 3 clients, A, B, C all the client want only small UI details or sometimes a bit bigger UI feature changed in single module. How I currently handle this is by creating localize directory for each of this clients and adding needed scripts there which allow me to add/change UI views. if A, B and C want button with different design then I have jquery trigger that listen to events in all of the localize directory. On production A client will only have localize_A directory and problem solved. But as the application grows bigger we have a lot of repeated code, dependency growing larger and larger. s you can imagine this is starting to get messy and not so easy to manage. thus we have decided to improve it even if it means refactoring big part of our project. I want to get rid of this and have good architecture to handle this issue. How would big project handle this kind of scenario?

lundi 22 mars 2021

Adding a class with Generic Type to an existing class caused a domino effect changes on the code. What is the approach to solve this?

I am currently on a project and need to use a class created by another developer inside an existing class I developed.

Not the real code, but this is similar to the current code (I removed the interface for the sake of brevity)

class MyClass // this is my class
{
    uint data;

    // other methods here, omitting it
}


class AnotherClass<T> // class from another developer, I need to include this inside my class
{
    void MyMethod()
    {
        T data;
    }
}

This AnotherClass needs to go inside MyClass (composition).

The MyClass has been widely used on the program (it has an interface but I removed it here for simplicity of the example) and being instantiated by a factory.

class MyClassFactory
{
    public static MyClass GetNewInstance()
    {
        return new MyClass();
    }
}

public class TestClass
{
    public TestClass()
    {
        var c = MyClassFactory.GetNewInstance();
        var d = MyClassFactory.GetNewInstance();
        var e = MyClassFactory.GetNewInstance();
        var f = MyClassFactory.GetNewInstance();
        var g = MyClassFactory.GetNewInstance();
    }
}

I am having a discussion with the developer and he wants me to change my MyClass to be a generic based, which means, that will introduce changes on lots of area

public class TestClass
{
    public TestClass()
    {
        var c = MyClassFactory.GetNewInstance<uint>(); // i need to revisit ALL the getnewinstance call and add the generic type
        var d = MyClassFactory.GetNewInstance<byte>();
        var e = MyClassFactory.GetNewInstance<long>();
    }
}


class MyClassFactory
{
    public static MyClass<T> GetNewInstance<T>()
    {
        return new MyClass<T>();
    }
}


class MyClass<T> // this is my class
{
    uint data;
    AnotherClass<T> anotherclass;
    // other methods here, omitting it
}


class AnotherClass<T> // class from another developer, I need to include this inside my class
{
    void MyMethod()
    {
        T data;
    }
}

It seems not a scalable solution since if I have 1,000 calls to MyClassFactory.GetNewInstance, all the 1,000 calls needs to be revisited and change to appropriate data type. To avoid the domino effect changes, I instead suggested to just provide the type via enum.

enum DataType
{
    Byte,
    Int
}

class MyClass
{
    uint data; // this is an existing variable that is being used on myclass computations, anotherclass doesn't need this variable. This doesn't need to be generic
    object anotherClass;

    MyClass(DataType d = DataType.Int) // default parameter, most of the types are int and this will lessen the change
    {
        switch(d)
        {
            case DataType.Byte:
                anotherClass = AnotherClass<byte>();
                break;
            case DataType.Int:
                anotherClass = AnotherClass<int>();
                break;
        }
    }

}

This will result in less changes, but I personally don't like the casting that will be needed for the object. I can use dynamic datatype but still, there is no compiler-check safety.

Is there a methodology or design pattern to solve this kind of problem?

Edit : just to elaborate, the generic specifier is only for the anotherclass. The myclass doesn't need the generic specifier. Basically, the aim of the author of the anotherclass is to use the smallest datatype possible, hence the use of generics on the another class.

All the computations inside the myclass uses uint. But the anotherclass uses the smallest datatype possible.

I guess the question is, how to fit it in with an existing class that is already being heavily used on the source code with minimal modifications.