mardi 30 novembre 2021

Identifying code smells in the classes which represent a protoype for a facebook

Consider the following two classes:

public class Person<P extends Comparable<P>> {
    
    private List<Person<P>> following = new ArrayList<Person<P>>();
    private List<Person<P>> friends = new ArrayList<Person<P>>();
    private P id;

    public Person(P id) {
        this.id = id;
    }

    public P getId() {
        return id;
    }

    public List<Person<P>> getFollowing() {
        return following;
    }

    public List<Person<P>> getFriends() {
        return friends;
    }
    
    public boolean isFollowing(Person<P> person) {
        return following.contains(person);
    }


    public void addFriend(Person<P> person) {
        friends.add(person);
    }
}

public class WasteBookController<P extends Comparable<P>> {
    
    List<Person<P>> people = new ArrayList<Person<P>>();
    /**
     * Adds a new member with the given name to the network. 
     */
    public void addPersonToNetwork(P name) {
        people.add(new Person<P>(name));
    }

    /**
     * @preconditions person1 and person2 already exist in the social media network.
     * person1 follows person2 in the social media network.
     */
    public void follow(P person1, P person2) {
        if (person1.equals(person2)) {
            return;
        }

        for (Person<P> member1 : people) {
            if (member1.getId().equals(person1)) {
                for (Person<P> member2 : people) {
                    if (member2.getId().equals(person2)) {
                        List<Person<P>> following = member1.getFollowing();
                        following.add(member2);

                        if (member2.isFollowing(member1)) {
                            member1.addFriend(member2);
                            member2.addFriend(member1);
                        }
                    }
                }
            }
        }
    }

    public int getPopularity(P person) {
        Person<P> member = people.stream().filter(p -> p.getId().equals(person)).findFirst().get();
        int popularity = 0;

        for (Person<P> other : people) {
            List<Person<P>> following = other.getFollowing();
            if (following.contains(member)) {
                popularity += 1;
            }
        }

        return popularity;
    }

    public int getFriends(P person) {
        Person<P> member = people.stream().filter(p -> p.getId().equals(person)).findFirst().get();
        return member.getFriends().size();
    }

    /**
     * Returns an iterator to the network (each member)
     * ordered by the given parameter.
     */
    public NetworkIterator<P> getIterator(String orderBy) {
        Comparator<Person<P>> comparator = null;
        if (orderBy.equals("popularity")) {
            comparator = Comparator.comparing(p -> -getPopularity(p.getId()));
        } else if (orderBy.equals("friends")) {
            comparator = Comparator.comparing(p -> -getFriends(p.getId()));
        }

        comparator = comparator.thenComparing(Person::getId);

        return new NetworkIterator<P>(people.stream()
                     .sorted(comparator)
                     .map(Person::getId)
                     .collect(Collectors.toList())
                     .iterator());
    }

    public void switchIteratorComparisonMethod(NetworkIterator<P> iter, String orderBy) {
        // TODO Part d)
    }
}

I want to identify if there are any design issues or code smells in this?
It's like a backend implementation for a Facebook where people can have followers and friends
A person cannot follow itself, and if a person1 follows person2 and person2 follows person1, they are friends.
I am looking for some ways to improve it. P extends Comparable

- Since I want the IDs to be comparable, I did this. But I am not sure if this is a perfect way

Choosing a design pattern for a given specification [closed]

An organization can be thought of as a series of Organisational Units - Divisions, Faculties, and Schools. Each Organisational The unit has a head (e.g., the Dean of Engineering, Head of CSE), a manager, and a series of supporting staff affiliated with the unit and contain other Organisational Units. Schools can offer courses and cannot contain other organizational units. Select the most suitable Design Pattern to model this system

My Thoughts:
I cannot think of a design pattern in this case as this just seems to me a simple set of classes etc.

Implementing Factory Method design pattern in Unity

i have the following code:

Product code -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Guns : MonoBehaviour //product
{
    public abstract void shoot();
    public GameObject CreateBullet(GameObject bullet)
    {
        return Instantiate(bullet, transform.position, Quaternion.identity);
    }
    public void ShootBullet(GameObject bullet, Vector3 direction)
    {
        bullet.transform.Translate(direction * Time.deltaTime);
    }

}

Concrete Product Code 1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class M16 : Guns //ConcreteProduct
{
    [SerializeField] GameObject m16bullet;
    Vector3 m16bulletdirection = new Vector3(5, 0, 0);

    public override void shoot()
    {
        CreateBullet(m16bullet);
        ShootBullet(m16bullet, m16bulletdirection);
    }

}

Concrete Product Code 2

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Uzi : Guns //ConcreteProduct
{
    [SerializeField] GameObject uzibullet;
    Vector3 uzibulletdirection = new Vector3(10, 0, 0);

    public override void shoot()
    {
        CreateBullet(uzibullet);
        ShootBullet(uzibullet, uzibulletdirection);
    }
}

Creator Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class GunCreator : MonoBehaviour //Creator
{
    public abstract Guns GunFactory();
}

Concrete Creator Code 1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class M16Creator : GunCreator // ConcreteCreator
{

    public override Guns GunFactory()
    {
        return new M16();
    }
}

Concrete Creator Code 2

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UziCreator : GunCreator // ConcreteCreator
{
    public override Guns GunFactory()
    {
        return new Uzi();
    }
}

and a client code, which currently do nothing as I dont know how to make a gun using this method. So How do all of this help me create new gun prefab with the relevant code on them?

Besides, as far as i understand, every new gun will have to have a NewGunCreator class that derives from GunCreator and a NewGun class that derives from Guns. wouldnt it be easier to leave out the creator classes?

cheers!

Alternative to enum that is open to extension

I have an IUserRole interface that represents different user role implementations, such as NormalUser and Administrator. Each user user role implementation allows checking for specific permissions that it allows. Example:

public class Program
{
    enum UserPermission { Permission1, Permission2 }
    
    interface IUserRole
    {
        bool HasPermission(UserPermission perm);
    }
    
    class NormalUser : IUserRole
    {
        private static readonly List<UserPermission> _permissions = new() 
        {
            UserPermission.Permission1 
        };
        
        public bool HasPermission(UserPermission perm)
        {
            return _permissions.Any(x => x == perm);
        }
    }
    
    class Administrator : IUserRole
    {
        private static readonly List<UserPermission> _permissions = new() 
        {
            UserPermission.Permission1,
            UserPermission.Permission2
        };
        
        public bool HasPermission(UserPermission perm)
        {
            return _permissions.Any(x => x == perm);
        }
    }
    
    public static void Main()
    {
        IUserRole role = new Administrator();
        var hasPermission = role.HasPermission(UserPermission.Permission1);
        Console.WriteLine($"Has Permission: {hasPermission}");
    }
}

Live example here

I wanted to avoid using enums here because it, to me, violates open/closed principle. The code smell is that the enum is not finite or fixed. Permissions can evolve over time, so I have to ask myself if I want to be adding to the enum each time.

An alternative I considered is this:

public class Program
{
    interface IUserPermission {}
    class Permission1 : IUserPermission {}
    class Permission2 : IUserPermission {}
    
    interface IUserRole
    {
        bool HasPermission<T>() where T : IUserPermission;
    }
    
    class NormalUser : IUserRole
    {
        private static readonly List<IUserPermission> _permissions = new() 
        {
            new Permission1()
        };
        
        public bool HasPermission<T>() where T : IUserPermission
        {
            return _permissions.OfType<T>().Any();
        }
    }
    
    class Administrator : IUserRole
    {
        private static readonly List<IUserPermission> _permissions = new() 
        {
            new Permission1(),
            new Permission2()
        };
        
        public bool HasPermission<T>() where T : IUserPermission
        {
            return _permissions.OfType<T>().Any();
        }
    }
    
    public static void Main()
    {
        IUserRole role = new Administrator();
        var hasPermission = role.HasPermission<Permission1>();
        Console.WriteLine($"Has Permission: {hasPermission}");
    }
}

This sort-of addresses the issue: I now can simply add a class instead of modifying an existing enum when I need to add new permissions. But overall this design is lacking:

  1. I still need to modify the IUserRole implementations to add support for new permissions. This makes any benefits to replacing the enum for something more open to extension nearly moot.
  2. Using empty classes to represent permissions doesn't make me feel warm and fuzzy inside: It feels over engineered and abusive of classes which are classically supposed to represent behavior.

I started this with a specific question: What is the best alternative to enum here as to better respect/adhere to the open/closed principle? But the answer, I suspect, might be broader: The overall design probably needs attention. My whole approach feels wrong somehow.

Live example here

Powershell question - How can I deleted lines from a certain position?

(Sorry in advance for my bad english.)

I have 2 questions:

  1. Question: I have a .txt file and search with powershell for a word into the .txt:

My code: Select-String .\example.txt -pattern "myword" | select -ExpandProperty line

OK nice. PowerShell found the word within line 63. After line 63, the .txt file has x more lines, and all of (64) them should be deleted. How can this be done?

get-content .\example.txt | select-string -pattern 'myword' -notmatch | Out-File .\new_example.txt

This deleted only line 63. However, this should remain and only the rest should be deleted.

  1. Question: Almost the same. I search for two countings Example: 12 and 33 into the .txt Powershell found not 12a and 33a. That's right. Powershell should for it "11a until 56a", and clear line "10a" and "123a"

Example .txt file: 10a, 11a, 21a, 20w, 32a, 56a, 123a,

That is desired .txt file: 11a, 21a, 20w, 32a, 56a,

How can I make it? I hope so mutch that you can help me by this problems. Thanks.

OOPS: Why Design-Pattern and Why not Coding-Pattern

Thanks in advance for your reply.

I am interested in C/C++ mentoring. My way of teaching would be to explain the necessity of a new concept/technology first or what is the drawback in the existing system. In that way, I tried to arrive for the necessity and the naming reason for design patterns.

Now come to my actual question. I know almost all design pattern at least theoretically and used some practically too. No problem in usage. But when I teach, I used to raise few questions towards myself which I may expect from students.

  1. Can’t I survive without design patterns? - seems like just a logics/algorithms for a problem. since its solution for a common/repeated problem is it publicized just to avoid the reinvention of the same wheel?.

  2. Called as design pattern but it seems like a coding-pattern? - If its just code logics, why its called as design pattern. As a programmer, I can also analyse which loop statement should I use? ie. for/while/ do-while? can I name it as "loop design pattern". If someone answers as "hey this is just a problem dealing with building blocks(conditional/loop/datatypes/storage classes) of coding language. If so, I can raise same question against a singleton -"Hey its just a problem dealing with static keyword".But static key word too part of building block. If so, I can raise same question against a Factory, Builder, bridge, visitor, strategy - "Hey they are just problems dealing with dynamic binding which is achieved using raw, unsafe "void" pointers in C and safe virtual mechanism in C++" that's it" do you agree?.

  3. Are they introduced to achieve SOLID principles? I came to know about SOLID principles 5 years later I started to use design patterns. ie. theoretically I was not perfect. But after i read those principles I could understand every design pattern satisfies at least one of those five rules. Hence can I conclude as SOLID is design level constraints and design patterns are code level solutions. Hence it should be called as "coding patterns"

  4. So what is the boundary line for design and coding?

  5. Is it just a make-life-easy tool?(ie. Reusability: Productivity: maintainability: Extendibility: scalability, etc).

  6. Or do you want to simply compromise me as "Hey someone named it so, leave it"?

I have my own answer in different view, which you please correct?

Answer 1: Before a developer, a designer(low level/high level) also will bother about entity/objects and communication between objects, all. For him the language is UML and he has class, sequence, state diagram, etc. So we can understand that these patterns were published as UML diagrams by designers only, but code solutions were given later by different developers hence named as "design" patterns?

Answer 2: In C, "type" and "logic" were kept separated(even for user defined datatypes using struct keyword). But in C++, some of the logics were merged as member functions-eg. boundary checking for array type. so while writing the standalone functions in C, you need to worry only about algorithms/logics which you can name as "coding pattern" for "repeated problems". But in OO paradigm(C++), while defining your "type" itself you have to think more than storage space. ie. data members, which you cant simply call as logics, because instead of defining a type you almost design a "type" by considering constraints, like 1. only-single instance for singleton, 2. enabling provision for new states in state pattern, etc.

If you feel, I confuse myself or have too much analysis on this, please allow me. I want to have more clarity while explaining to students because they should not get confused. Thanks

lundi 29 novembre 2021

Java Regex pattern not working for filename matching

I am trying to pull filenames with the below pattern RID12345678_DLF0013B-P-21311118121541.txt RID123456789_DLF0013B-P-21311118121541.txt RID12345678_DLF0013B-I-21311118121541.txt

So below is the Regex pattern I gave

"([\w{11,12}]_DLF0013B-[I|P]-[\b\d{14}\b])" - This one throws error for the bold part saying illegal escape sequence.

If I get rid of \b - "([\w{11,12}]_POS340BN1-[I|P]-[\d{14}])" - this one picks below file even though there are 15 bytes after character P.

RID12345678__DLF0013B-P-213111181215410.txt

Please help!

Command Pattern: Executing multiple commands in sequence from different place of system

I need undo system which can execute single or multiple commands. If its multiple commands i need to have opportunity to add commands to the list and in end point execute all commands. Example: Class A, Class B, Class C, Class D: A(add command to list then send it to class B) -> B(add command to list then send it to class D) -> D(add command to list then execute all commands); A(add command to list then send it to class C) -> C(add command to list then send it to class B) -> B(add command to list then execute all commands A)->A(add command to list then execute all commands) Then i can do undo and i want to get this result: A<-C<-B<-A

If two interfaces having same method name and signature and a class implements both interfaces then which design pattern is violated here?

Interface A{ Void draw(); }

Interface B{ Void draw(); }

Public class Demo implements A,B{ @override Public void draw(){ } }

Parse JSON document based on predefined JSON mapping document in Java

I want to get some idea if there is any library in Java that I can use to parse a JSON document based on a predefined JSON mapping document, or only way to achieve this is to write custom java code.

If it's required to write Java custom code what type of design pattern or data structure I should follow. Any advice will be very much appreciated.

Example -

Input JSON document -

{
  "basicInfo": {
    "name": "name",
    "age": "25",
    "address": "address"
  },
  "education": [
    {
      "ug": {
        "unversity": "university",
        "major": [
          "cs",
          "ds"
        ],
        "year": "2012"
      },
      "pg": {
        "unversity": "university",
        "major": [
          "cs",
          "ds"
        ],
        "year": "2015"
      }
    }
  ]
}

Predefined JSON mapping document

{
    "definitions": {
      "basicInfo": {
        "maxOccurance": "1",
        "fields": [
          {
            "key": "name",
            "type": "S",
            "lenght": "50",
            "usage": "M",
            "maxOccurrance": "1"
          },
          {
            "key": "age",
            "type": "S",
            "lenght": "3",
            "usage": "O",
            "maxOccurrance": "1"
          }
        ]
      },
      "education": {
        "maxOccurance": "10",
        "fields": [
          {
            "pg": {
              "maxOccurance": "1",
              "fields": [
                {
                  "key": "university",
                  "type": "S",
                  "lenght": "50",
                  "usage": "M",
                  "maxOccurrance": "1"
                },
                {
                  "key": "major",
                  "type": "S",
                  "lenght": "3",
                  "usage": "O",
                  "maxOccurrance": "1"
                }
              ]
            }
          }
        ]
      }
    }
  }

Expected output JSON document

{
    "basicInfo": {
      "name": "name",
      "age": "25"
    },
    "education": [
      {
        "pg": {
          "unversity": "university",
          "major": "cs"
        }
      }
    ]
  }

dimanche 28 novembre 2021

Using two different priority queues in Golang

I am a Gopher Noob. I ran into this question recently regarding implementing priority queues in Golang. I went through https://pkg.go.dev/container/heap@go1.17.3 for implementing a priority queue. All one has to do is implement the heap.Interface for the container. Its straightforward enough and i have no questions about that.

My question though is this: I need two priority queues. One is a minimum and maximum priority queue. In Java, this is quiet easy is initialize. I just have to change the comparator during initialization and thats it. In golang, I simply have to change the Less method in sort.Interface which is fine. However, I am not interested in writing redundant code and i am looking for cleaner way to create both priority queues.

Here is an example for what i am looking to do:

// A PriorityQueue1

type PriorityQueue1 []*Item

// Implement all the following methods for the min Prioirity queue
func (pq PriorityQueue1) Len() int { return len(pq) }

func (pq PriorityQueue1) Less(i, j int) bool {
    // We want Pop to give us the highest, not lowest, priority so we use greater than here.
    return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue1) Swap(i, j int) {
  //Swap
}

func (pq *PriorityQueue1) Push(x interface{}) {
  //Define push logic
}

func (pq *PriorityQueue1) Pop() interface{} {
  //Define pop logic
}

Now, I define the maximum priority queue (**everything is the same except Less**), which goes like this.. 

// A PriorityQueue2

type PriorityQueue2 []*Item

// Implement all the following methods for the max Prioirity queue
func (pq PriorityQueue2) Len() int { return len(pq) }

func (pq PriorityQueue2) Less(i, j int) bool {
    return **pq[i].priority < pq[j].priority**  // Thats it. One line change..
}

func (pq PriorityQueue2) Swap(i, j int) {
  //Swap
}

func (pq *PriorityQueue2) Push(x interface{}) {
  //Define push logic
}

func (pq *PriorityQueue2) Pop() interface{} {
  //Define pop logic
}

Now why would i have to go through this ordeal of rewriting almost the same methods as that of the min queue for a one line change in Less. I am looking to reduce the boilerplate and i am wondering about what is the cleanest and concise way to go about solving this question. I am also not interested in using any third party libraries (but i am interested in its logic if there is one which provides a clean wrapper).

Please provide some inputs. Thanks..

Model classes vs Model in MVC

Does the model in MVC contain both business logic (algorithms and stuff) and the classes that are mapped to entity tables in databases? Those mapped classes are called model as well, specifically, because they model some data. My confusion is this: Does model contain the business logic? or is it just entities? It turns out that it contains, from Mozilla docs: Model: Manages data and business logic.

I got confused by how Java Spring projects are structured. There are controllers, service (business logic), repository(connection to database, aka DAOs) and model classes (Classes of objects that are received by controller and often mapped to database entities). Let's map this to MVC "components":

View - Not in a spring app;

Controller - Rest controller (or just Controller, depending on how you want to structure your app);

Model - Services, Repositories, Model classes (???).

I am confused here, that we have model in both left and right sides.

Thanks.

How and what resources can I use to understand software engineering and computer science as a whole better?

I am a self-taught front-end web developer. I have worked in teams and build built projects on my own. I have been able to solve technical problems and blockers by simply googling. However, I still feel a lot of emptiness. like there is a lot I do not know nor understand in computer science. I have simply been a tool user. learn tools like javascript and CSS and react and styled-components and web-pack, and sass, etc., and all these get the job done. However, I want to understand the core concept of programming. not just learning and making use of tools. I want to be able to look at a block of code written in any programming language, and understand what is going on within that block. even if I don't understand the syntax in itself.

simply put, I want to go low level, I want to understand the core of programming, what is happening under the hood when a program runs, how it all relates, why javascript is single-threaded, why C is faster, why JavaScript is an interpreted language.

How do I pick up this knowledge, please? (I'm not sure I constructed the question well but please, do answer to the best of your abilities)

Is there a X software problem that can be solved using two design patterns together? [closed]

Is there a software problem that can only (better) be solved using two or three design patterns approach ? If so can you give an example then explain for me ?

samedi 27 novembre 2021

Which layer should we implement usecases in the clean architecture

Im working on a project which is getting bigger and bigger, so i followed some online courses to get to know what clean architecture is,UseCases are core logics of the application,for example by looking at the UseCases we should know whats going on in the application, we have usecases and Repository signitures inside of the core layer,in the infrastructure we need to implement the repository logic(anything interacts with the database)please correct me if I'm mistaken, but what about the usecases where should use cases be implemented inside the core or inside the infrastructure? thanks in advance

C# extendable class library - how to reference extension object

What is the best way to reference objects coming from possible extension methods?

I have a class library FooApi.Core which exposed the public class FooApi.Core.Client. This can be used on its own, but what if I want to give the user the possibilty to extend this library with e.g FooApi.WebApi?

To add the extension to FooApi.Core.Client I added a extension method in FooApi.WebApi which should add the web api object to the Client.

namespace FooApi.WebApi
{
    public static class Extensions
    {
        public static FooApi.Core.Client AddWebApi(this FooApi.Core.Client client)
        {
            // that already requires a WebApi object in core client / reference to the project i want to be extendable
            client.WebApi = new WebApi();
            return client;
        }
    }
}

Null Object Pattern in a self-referencing object

Suppose I have a class named Node, which represents a node in a hierarchical structure. For instance it could look something like this:

public class Node
{
  public readonly string Data { get; set; }
  public readonly Node Parent { get; set; }
  public readonly List<Node> Children { get; } = new()

  public Nome(string Data, Node parent)
  {
    Data = data;
    Parent = parent;
  }
}

Notice the property Parent is of type Node and it's non-nullable, so I cannot assign null to it. Now suppose I want to implement the Null Object Pattern for this class, for instance to create the root node.

I found myself in a chicken and egg situation because I cannot create a Node without having a node.

Are there any alternatives except making Parent nullable?

What's the best way to manage fixed data?

I am trying to make a web app can look up game items. The items are composed as follows.

  1. They may be added or changed by game updates.
  2. They have attributes which have range by item types (ex. Ring can have max strength +5, mana +20 etc..)
  3. The number of items are about 3-4 thousands.

Now, I hard-coded some of them as map data structure for my prototype, but I think it's not efficient. I consider of using RDBMS, such as PostgreSQL, so I can easily filter items by SQL and the main structure of items will get hardly changed. Also, it is easy to import or export. However, if I use RDBMS, the hard part is to manage item attributes. The item can have multiple attributes and I need to know the minimum and maximum stats of each. Are there better way to manage these data?

Timetable in django

In my django app i would like to create a timetable showing all appointments per day. For example:

Time   | Seat 1   | Seat 2 | etc
9:00am  John Doe   Jim Doe
10:00am John Doe   Jim Doe

Currently i have models for appoint and seat:

class Appointment(models.Model):

    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True)
    start_appointment = models.DateTimeField(default=timezone.now, blank=True)
    end_appointment = models.DateTimeField(default=timezone.now, blank=True)
    name = models.CharField(max_length=255)
    date_created = models.DateTimeField(_('Date Created'), auto_now_add=True)
    date_updated = models.DateTimeField(_('Date Updated'), auto_now=True)

class Seat(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    short_description = models.TextField(blank=True, null=True)
    created_at = models.DateField(auto_now_add=True)

Could you please propose a way or steps of how to achieve that?

vendredi 26 novembre 2021

i am trying to print plus sign(+) star pattern in javascript can you explain me what is wrong with my code and give a solution

In this image i have a javascript program which prints plus star pattern(at least thats what i intend to print) but it is just printing empty spaces can you tell me what is wrong with my code here

Reading patterns from file in Game of Life [closed]

So I am trying to code the Game of Life and I am having trouble trying to actually read the patterns from file, I am not sure how I would go about doing this. Right now I have it so that you have to manually input positions through scanner and that gets you the pattern you want. But I want to do it through plaintext and being able to read the pattern but I am just not sure how to do that. Some of the features I have is being able to put how many rows and columns you want the board to be and how many generations.

JS Good Practices - Creating related exceptions with factories?

Is it a "good practice" to create errors related with a same concept via factory?

I mean, for example, in a sign up validation, could it be a good practice to do the following?

"use strict";

const { functions } = require("../../../services/firebase")

const authErrors = Object.freeze({
  invalidPassword() {
    return new functions.https.HttpsError(
      "invalid-argument",
      "Invalid password.",
      {
        status: "error",
        code: "auth/invalid-password",
        message: "The provided password is invalid. It must contain between 8 and 40 characters, including at least one uppercase letter, one lowercase letter, and a number.",
      }
    );
  },
  invalidUsername() {
    return new functions.https.HttpsError(
      "invalid-argument",
      "Invalid username.",
      {
        status: "error",
        code: "auth/invalid-username",
        message: "Username must be between 3 and 30 characters, including numbers, letters, hyphens, periods, or underscores.",
      }
    );
  },
  // ... more related errors 
});

module.exports = authErrors;

and then use them as follows?

if (!validateUsername(username)) {
  throw authErrors.invalidUsername();
}

Note: I am using Google Cloud Functions, and it has no sense for my use case to throw instances of custom errors.

Is it possible to pass argument to the last method of method calling chain in Java?

say a methods are calling like this with same argument:

method a -> method b -> method c -> method d

Is it possible to pass argument from a to d directly? since method b and c does not do anything with the argument?

jeudi 25 novembre 2021

Python Generic functions with generic parameters

I'm not sure if I used the right terms in the title. This maybe a known way to program interface functions for a subsystem or module but because I don't know the keywords, I'm not finding the results in my search queries.

I want to create a function whose intention can be clearly described in the functions name but the parameters are flexible. I want to write the function to be generic enough so that the function can complete the intention with whatever parameters it receives from whichever caller.

Let's take a function do_foo. do_foo can take in some_obj whose attributes allows do_foo to do its work. Additionally, do_foo can just take in the individual attributes it cares about like obj_attr0 or obj_attr1 and perform the same work. In both cases, the expected result is the same as well.

So this would look something like this:

Class SomeObj(): 
   def __init__(self, obj_attr0, obj_attr1, obj_attrN):
     self.obj_attr0 = None
     self.obj_attr1 = None
     self.obj_attrN = None # denotes an N number of attributes

def do_foo(params)
   # unpack params. do_foo requires obj_attr0 and obj_attr1 and so its searching it in the params iterable
   # determine which data is passed in 
   # execute the work the same way regardless of what form the data is passed in
   pass

obj_attr0 = None
obj_attr1 = None
obj_attrN = None
some_obj = SomeObj(obj_attr0, obj_attr1, obj_attrN)
# One can either call with a subset of attributes that would make up SomeObj or SomeObj itself if all the information is there. E.g.:

params = (some_obj)
do_foo(params)

# OR

params = (obj_att0, obj_attr1)
do_foo(params)

I know python offers *args and **kwargs facilities that offer the flexibility above. I'm looking for some examples of where the implementation lends itself to reducing pitfalls. What is a good way to implement the above? And if there are any resources out there what are examples/articles/or terms that describe the above style of programming? Clearly, I'm trying to write my interface functions to be generic and usable in multiple logic paths where the users has its data in different forms where sticking to a specific parameter list is limiting.

Source of Design Patterns for a beginner

I’m just started learning coding. I’m playing about in Python at the minute but I’m planning to learn some C very shortly.

I’ve just been introduced to simple design patterns.just simple things like averaging a list or finding the highest value etc.

Is there a book, or a site with a collection of these things that can be coded into a language of choice and built into a working program.

Also a good intro to the software design process?

I HAVE A "QUIZ" IN "SINGLETON" PATTERN ANYONE CAN ANSWER THAT

Implement the following problem:

A modern cement factory utilizes a computer-controlled furnace. The job of the furnace is to take in chemical materials, bring them to a certain temperature (300 Co). Using the appropriate design pattern design the controller class of the factory. (Hint: use singleton pattern)

How to refactor this code into multiple classes and not have to repeat the try-catch block?

I have a class with the following structure(reduced to bare minimum)

class Main{

    processTask(){
        try{
            data = preStep1();
            preStep(data);
            processFurther(data);
        }
        catch(Exception1 e){
            handleEx1();
        }
        catch(Exception2 e){
            handleEx2();
        }
    }

    processFurther(data){
        switch(data){
            case cOne:
                doOneThing();
                break;
            case cTwo:
                doTwoThing();
                break;
            case cThree: 
                doThreeThing();
                break;
            case cFour:
                doFourThing();
                break;
            default:
                doDefault();    
        }
    }

}

The four functions doOneThing, doTwoThing, etc. are in another utility class let's say MainHelper.

Now, a requirement has come that the code for four case cOne, cTwo, cThree, cFour needs to be in 4 separate files, like MainOne, MainTwo, MainThree and MainFour. This is a must and cannot be avoided.

The problem that I face is that if I just split it as it is, then I have something like this

class MainOne{

    processTask(){
        try{
            data = preStep();
            doOneThing();
        }
        catch(Exception1 e){
            handleEx1();
        }
        catch(Exception2 e){
            hanldeEx2();
        }
    }

}

Now this preStep() and handeling exceptions is going to be repeated exactly like this in all the four classes. How can we through a design pattern or some custom way make it so that we don't have to repeat this code.

If the code was without the try-catch then I could have done the following. But I am not sure how I can do it now since there is a try-catch involved.

class MainOne{

    processTask(){
        Util.preProcess();
        doOneThing();
    }
}

class Util{

    preProcess(){
        data = preStep1();
        preStep2();
        return data;
    }

}

java strategy design pattern

Can you guys give me an idea for design patterns topic. I need a software problem that can be solved by using 2 design patterns. Any problem for me. ? I know the patterns that are mentioned in the book called "Head first design patterns".

I need to understand how to use a strategy design on a project PHP Project?

Note: it's a PHP Project

I have a situation where i use 2 API providers for my project. They are like similar with what info they (API) provides. I must set this right way since maybe tomorrow there will be some more APIs added. So my project will need some methods. Basic, here is what i have so far:

abstract class A {}// first api class, mostly contains API configs and call 
abstract class B {}// second api class, also mostly contains API configs and call 

//than first API has a sub classes of something like cars and trucks
class Car extends A implements ApiMethodsInterface {} // for the cars 
class Truck extends A implements ApiMethodsInterface {} // for the trucks

//now second API has a sub classes for cars , trucks and spaceships
class Car extends B implements ApiMethodsInterface {} // for the cars
class Truck extends B implements ApiMethodsInterface {} // the trucks
class SpaceShip extends B implements ApiMethodsInterface {} // for the space ships

//they all have more or less similar methods 
// so i used an Interface that all above classes 
interface ApiMethodsInterface
    //methods are
    public function getModels()
    
    public function getYears()

    public function getPrice()

since every sub class implements this interface , i code by interface

Now, i have a situation, where SpaceShips has more methods to add, like getEquipment() and some more info, methods that other classes are not implementing. Trucks also has more methods that others do not implements , like, hasTrailer(), trailerLength() etc...

My question is , what to do now, should i use Interface segregation, and add Interfaces to classes that implements those methods, and later check if object instantiated is having this method than run, else some exception, or to add missing models into the abstract classes A and B, and override methods into the classes that use those methods, or maybe there is even more good way of solving this. Quite new into Design Patterns btw...

Maybe i am overengineering but i really want to do this in a good way.

Thanks

Implementing an api integration with symfony5

I have a setup, but I can't decide how to do it in the most logical way. The issue is;

I want to use the APIs of many marketplaces in my current Symfony app. There is a structure as follows.

MarketPlace1 -> Products, Orders, Customers etc.
MarketPlace2 -> Products, Orders, Customers etc.
MarketPlace3 -> Products, Orders, Customers etc.

Since it is necessary to make authorization with different parameters for each marketplace, I store the authorization information in a single column in JSON format in order not to pollute the database. E.g;

MarketPlace1 -> apiKey: xxx ApiSecret: yyy
MarketPlace2 -> authToken: zzz
MarketPlace3 -> userName: xxx password: yyy

Here I thought of using Abstract Factory to set up the basic structure and separate the creation of objects, but I couldn't achieve this in Symfony. I feel like I'm doing something wrong.

Instead of fetching all the authorization information from the database each time, I think it would make more sense to store it in the current session when the user logs in to the website and use it throughout the session. Anyone have a more logical idea? (This will be a website that many different customers use by adding integrations.)

As a result, when the customer clicks on the MarketPlace1 integration and goes to the "Orders" page, only the orders from MarketPlace1 will be displayed. Below is the design I've tried;

interface BaseInterface {
    public function makeRequest();
}

class Base implements BaseInterface {
    private $client;
    private $auth;

    public function __construct()
    {
        $this->auth = [
            'auth' => [
                'appKey' => 'HARD CODED',
                'appSecret' => 'HARD CODED'
            ]
        ];
    }

    private function setUrl($url)
    {
        $this->client = new \SoapClient($url, [
            .......
            ))
        ]);
    }

    private function getClient()
    {
        return $this->client;
    }

    protected function makeRequest(string $requestMethod, array $parameters)
    {
        .....
    }
}
class Order extends Base implements OrderInterface
{
    public function getOrderDetails($id)
    {
        .... Some logic here.
        return $orderDetails;
    }

    public function getOrderList(): ?array
    {
        .... Some logic here.
        return $orderDetail;
    }
}

Class structure or design pattern for a shared border between two cells

This is more of a "best practice" or "best approach" kind of question; I was able to solve the core Problem myself, but I wonder how a situation like this should best be resolved.

Imagine a 2-dimensional board with a grid of square cells. Each cell is an independent instance of a class.

This would be the Pseudocode:

class Board {
    int width;
    int height;
    Array cells;
}

class Cell {
    Board parent;
    int x;
    int y;
    int value;
}

(To make the example a bit more clear: Imagine this is a Sudoku puzzle, with each cell holding a value.)

Now, while each Cell is independent, some Cells share a border. Let's say that this border is also it's own class, since it can be configured separately (for example, one cell's top border might be of a different color, style or thickness).

Now, if I extend the Pseudocode to accomodate for this:

class Cell {
    ...
    Array borders;
}

class CellBorder {
    Cell parent;
    int direction; // 0=top, 1=right, 2=bottom, 3=left
    Style style; // thickness, style, color, etc.
}

My Question is: Clearly, two connected Cells share a Border - what's the best way to deal with something like this?

  • Where is the Border instance initially created? Inside the Cell? Outside the Cell, in the Board class?
  • How would two Cells share a Border? Do they each have a pointer to the same instance, or two separate instances that just copy each other?
  • What if a Cell is moved to a different position? Are all affected Borders reconstructed or existing instances swapped?
  • If I want to configure a specific Border, how do I select it? By picking Cell(x,y).rightBorder? Cell(x+1,y).leftBorder? Board.border(x,y,'right')? (Ideally it shouldn't matter, but perhaps there is some benefit to one method over the other)
  • Should Borders (and perhaps even Cells) be created in a factory?

My current solution, is to only have the "top" and "left" Borders in each Cell, while linking the "bottom" and "right" Border to the neighbors "top" and "left" Borders respectively.

But generally speaking, what would be a good and flexible approach here? Would the Border handling be relayed to the Board instead of the Cells? I'm sure this type of problem must be fairly common and has some best-practices or perhaps even a well-suited design pattern.

How to use strategy pattern in nodejs

I am making some rest calls in my code based upon the value in a variable. Each of these rest calls takes a different number of parameters but the response remains the same.

if (type=="Membership"){
    reponse=await claimRepo.findDetailsByMembersip(memberNumber)
}
else if (type=="Claim"){
    reponse=await claimRepo.findDetailsByClaim(claimNumber)
}
else if (type=="Date"){
    reponse=await claimRepo.findDetailsByDate(date)
}

Now inside the claimRepo class

async findDetailsByMembersip(memberNumber){
    const data=requests.get('someurl')//make the call
    return {
        data,
        statusCode
    }
}

async findDetailsByClaim(claimNumber){
    const data=requests.get('someurl')//make the call
    return {
        data,
        statusCode
    }
}

async findDetailsByDate(date){
    const data=requests.get('someurl')//make the call
    return {
        data,
        statusCode
    }
}

Is there a way to get rid of these if-else blocks and implement this using the strategy pattern ?

mercredi 24 novembre 2021

Best way to store chess piece locations to easily lookup a location given a piece or a piece given a location using object oriented design principles

I'm currently working on a OO representation of a simplified chess game. Most of it is straightforward enough but one design decision I'm a little unsure about is the relationship between the chessBoard and pieces. The bottom line is I'm trying to figure out the best way to represent the chessboard / piece relationship so that I can easily and efficiently query "given a spot, is there a piece here" and "given a piece, what spot is it on"?

Currently, the Piece class stores both their own location (using a Spot class) and a reference to the Board class. The board class represents the board as a Dictionary<Spot, Piece> (the simplified game only has a few pieces so it felt unnecessary to store a mostly empty array of N by M spots like other examples I've seen) to track what spots on the board have what pieces on them. This is useful and seems intuitive to me since the piece can use the reference to the board when trying to move and ask "is there anyone at this spot?" and it can return the piece if any that is on a given spot. Similarly, in order to move the piece I need to know where it currently is and storing the location on the piece itself seems like a good OO approach.

The part where I'm running into some questions / trouble is how to keep those values in sync such that if I call (public method) Board.MovePiece() or (private setter) Piece.CurrentPosition = new spot() both Piece.CurrentPosition and the Board's Dictionary<Spot, Piece> are updated properly. Keeping everything as private as possible while making sure that calling a method on either the board or the piece while keeping the other class in sync is very tricky if not impossible. If C# had friend classes like C++ I could just make the Board a friend of the Piece then they could set each other's private vars no problem (I'm aware of internal which improves things but I don't think it prevents other code in the project from theoretically calling stuff it shouldn't). Right now my solution to this is a custom setter on the piece.CurrentPosition property so that every call to change it results in the correct call to public board members (which absolutely works) but I feel like I could do better. The biggest risk is the board methods are public and could be called outside the piece class and thus not update the piece location but I'm not a huge fan of the redundancy / slight complexity smell the code has currently.

Here's a simplified look at my code:

public class Board : IBoard
    {
        private uint _width;
        private uint _height;
        private Dictionary<Spot, Piece> _pieceLocations;

        public Board(uint width, uint height)
        {
            _width = width;
            _height = height;

            _pieceLocations = new Dictionary<Spot, Piece>();
        }

        // heavily used by piece when determining legal moves, what pieces and free spaces are in range etc.
        public Piece CheckSpot(Spot spot)
        {
            Piece piece;
            if (_pieceLocations.TryGetValue(transformSpot(spot), out piece))
            {
                return piece;
            }
            return null;
        }
 
        /// remove instead of null to potentially optimize space a bit
        public bool RemovePiece(Spot spot)
        {
            if (spot != null)
            {
                return _pieceLocations.Remove(transformSpot(spot));
            }
            return false;
        }

        /// This function will simply attempt to just move the piece to the specified destination.
        /// It's up to the caller to make sure the move is a valid chess move, etc
        public Spot MovePiece(Spot destination, Piece pieceToBeMoved)
        {
            // remove piece from current position
            // note the need to have current position here
            RemovePiece(pieceToBeMoved.CurrentPosition);

            // attempt to place at and return new position
            return PlacePiece(destination, pieceToBeMoved);
        }

        /// Simply places piece at specified destination if not occupied by another piece
        private Spot PlacePiece(Spot destination, Piece pieceToPlace)
        {
            var transformedDestination = transformSpot(destination);

            //business logic to check for stuff like a piece already at destination

            _pieceLocations.Add(transformedDestination, pieceToPlace);

            return transformedDestination;
        }

Note transformSpot just makes sure coordinates are not out of bounds and "wraps them around" to be within board dimensions if need be.

public abstract class Piece : IPiece
    {
        protected IBoard _board;
        public ColorType Color { get; protected set; }
        private Spot _currentPosition;

        public Piece(ColorType color, Spot currentPosition, IBoard board)
        {
            _board = board;
            Color = color;
            CurrentPosition = currentPosition ?? throw new ArgumentNullException(nameof(currentPosition), "When creating a piece you must specify a location");
        }

        public Spot CurrentPosition { 
            get { return _currentPosition; } 

            // I wanted to make sure that the piece's current position was always in sync with the board.
            // Calling <Board> functinos here seemed like a reasonable approach.
            protected set {

                // if position is being set to null remove from board
                if (value == null)
                {
                    _board.RemovePiece(_currentPosition);
                    _currentPosition = null;
                }
                else
                {
                    _currentPosition = _board.MovePiece(value, this);
                }
            }
        }

        public void Move()
        { 
            // note that I now need the current position to figure out where I can go etc.
            
            // insert logic to determine where we can move using chess rules etc.
            var destination = new Spot(x,y);

            // if spot is occupied remove piece
            var occupyingPiece = _board.CheckSpot(destination);
            if (occupyingPiece != null)
            {
                occupyingPiece.RemovePiece();
            }

            // call custom setter which in turn updates board to move piece from current spot to destination
            CurrentPosition = destination;
        }

        public void RemovePiece()
        {
            // call custom setter which in turn updates board to remove piece
            CurrentPosition = null;
        }

And some super rough pseudo code for the main driver

            List<Piece> whitePieces = generateWhitePieces();
            List<Piece> blackPieces = generateBlackPieces();

            while (gameActive)
            {

                //somehow determine which piece to move
                var pieceToMove = whitePieces.PickPiece();

                // could pass and store CurrentPosition at this level but if it's not stored on the piece or easily 
                // accessible from the board but feels slightly icky
                pieceToMove.Move();

                pieceToMove = blackPieces.PickPiece();

                pieceToMove.Move();
                // etc.

            }

Again, main flaw on top of some possibly unneeded complexity seems to be that Board.MovePiece() needs to be public for Piece to call it but that means anyone can also call MovePiece() and move something on the board without updating the piece.

Possible solutions I have considered:

I'm totally overthinking this and this is a fairly reasonable approach.

  • having the piece own its own location feels right, just wish I had better access modifiers to protect sensitive values but allow friends to change them (I'm aware of internal but doesn't seem to solve my issues fully)

I could just remove currentPos and:

  • have the board class maintain a Dictionary<Piece, Spot>

This feels like simply shifting the issue and having board maintain two dictionaries of essentially the same info in different orders feels silly, but at least it tightly couples the data together and allows the board to be the "authority" on where everything is. Leaning towards this but have a feeling this could be optimized somehow with the right data structure

  • have the main driver / game class maintain a dictionary / tuple list of pieces and their current position and have the Piece.Move() pass back info on where the board tells them they are now.

Again this just feels like we're shifting the issue but even more so. On the other hand I can kinda see the rationale for the game to want to keep track of pieces but that still feels pretty anti OO and I'd probably prefer keeping this to the Board as described above.

In theory could also

  • Just make current position setter public so Board could change it directly and add some complex checks in both the Board functions and the Piece.CurrentPosition setter to make sure if one is changed so is the other.

Feels much worse and adds more complexities / risks than it solves in my opinion. If it weren't for this issue CurrentPosition should have a private setter.

Anyway would very much appreciate any feedback / insight!

Different MVC diagrams

I've found two different diagrams showing the MVC design pattern and the flow between M & V & C. Both are described as MVC, but in 1) the View can directly communicate with the Model, 2) has no such connection - the communication is made via the Controller. Isn't the 2) diagram more the MVP design pattern than MVC?

1) enter image description here

2) enter image description here

How to make the JVM proxy the only one interface method?

public interface Action {
    void doSomething();
    void dontProxy();
}

For example with this interface, I just want the JVM to proxy the doSomething method.

class DynamicProxy implements InvocationHandler{
    private Action work;
    public DynamicProxy(Action action){
        this.work = action;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName()+" start");
        var tmp = method.invoke(work,args);
        System.out.println(method.getName()+" end");
        return tmp;
    }

Action action = (Action) Proxy.newProxyInstance(handler.getClass().getClassLoader(),work.getClass().getInterfaces(),handler);

The work is an instance of the Action interface implementation class. If I use Proxy.newProxyInstance, it seems to make all the interface methods be handled by the handler.

Is there an object-oriented alternative to the Front Controller Pattern?

Okay, so i stumbled upon the Front Controller Pattern, and as far as i know from web frameworks like Spring Web (Java) or Flask (Python), they all embody this Design Pattern, leading to code such as (sample Spring Web):

@PreAuthorize("hasAnyAuthority('ROLE_USER','ROLE_ADMIN','ROLE_SYSADMIN')")
@GetMapping(value = "/path/to/{id}/somewhere")
public void doIt(@PathVariable("id") String id)
{
    // ...
}

@PostMapping(value = "/path/to/{id}/somewhere")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SYSADMIN')")
public SomeDto doSomething(@PathVariable("id") String id)
{
    // ...
}

@GetMapping(value = "/api/agb/check")
@PreAuthorize("hasAnyAuthority('ROLE_USER','ROLE_ADMIN','ROLE_SYSADMIN')")
public SomeDto doSomeotherthing()
{
    // ...
}

@GetMapping(value = "/api/agb")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_SYSADMIN')")
public List<SomeDto> getAll()
{
    // ...
}

The "advantage" of this pattern is the centralized control flow, is said. But, isn´t it the case that object-oriented design is about distributing responsibilities and therefore getting rid of such centralized control flow?

Is there a more object-oriented design alternative to the front controller pattern when handling web requests?

Creating a global SQLite DB Connection with Singleton pattern in Swift

I detect whether a connection exists on a Singleton instance and if it doesn't it will open up a new connection on app start up. However, ideally I'd like for the open function to fire when the Singleton is first created without having to explicitly call it and assign it to some variable within the class.

The way I have the code now it defeats the purpose of having a shared Singleton because I just access the static connection object. When I attempt to change the static conn to an instance variable I get the error Instance member 'conn' cannot be used on type 'DBConnection'

Non-working code

class DBConnection {
    static let shared = DBConnection()
    var conn: Connection? = nil
    
    private init() { }
    
    static func open(dbPath: URL) throws {
        var dbConnections: [Connection] = []
        
        do {
            let dbConnection = try Connection("\(dbPath)/db.sqlite3")
            dbConnections.append(dbConnection)
            print("found connection, \(dbConnections)")
        } catch {
            throw SQLiteDBError.couldNotOpenConnection
        }
        
        self.conn = dbConnections[0]
        print("successfully opened connection")
    }
}

How can you call a private function within a Singleton class on init and assign it to some variable?

Current working code

class DBConnection {
    static let shared = DBConnection()
    static var conn: Connection?
    
    private init() { }
    
    static func open(dbPath: URL) throws {
        var dbConnections: [Connection] = []
        
        do {
            let dbConnection = try Connection("\(dbPath)/db.sqlite3")
            dbConnections.append(dbConnection)
            print("found connection, \(dbConnections)")
        } catch {
            throw SQLiteDBError.couldNotOpenConnection
        }
        
        self.conn = dbConnections[0]
        print("successfully opened connection")
    }
}

Main app init

@main
struct MyApp: App {
    
    init() {
        if DBConnection.conn != nil {
            do {
                try DBConnection.open(dbPath: FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0])
            } catch {
                print("error")
            }
        } else {
            print("Connection already existed")
        }
    }
    ....
}

How do companies design searches to be fast and highly available while there are things constantly being added?

For example, let's say you have an eBay clone and you are storing all the data in a SQL database. One way you could design your search is to query your database for every search, so say someone searches for "red sweatshirt" you could do something like SELECT * FROM database WHERE Match("red sweatshirt") or something along those lines. But surely these companies cache things (maybe using redis?) since I would assume doing a SQL query everytime a user searches for something would be way too slow. However, how do you solve the problem of things being constantly added. Like what if every second there are 20 new items being posted that match the search criteria "red sweatshirt". How can you resolve this since if you use a cache then you would be missing out on items.

This is a basic question I was pondering for myself that I couldn't come up with an answer too, I was curious if some more experienced engineers could enlighten me. I generally wanted to get an idea of how companies design their searches in terms of requests and what database structure they would use.

Traditional MVC design pattern

I have several questions about the Model-View-Controller architecture. I am a bit confused with all the conflicting information and different diagrams on the MVC pattern I've found on the Internet.

  1. Is the diagram below a correct representation of the MVC flow between the layers? If so, is View allowed to update Model directly not via Controller? enter image description here
  1. What is the difference between the passive Model and the active Model and how does each of these variations impact the Model change propagation to Controller and View?

  2. How is the new data fetched to both View and Controller after Model update (with and without Controller interference in Model update)

3a. (active Model - observers, notifications) Are both View and Controller notified each time Model updates and they get the new data from Model?

3b. (passive Model - no notifications) Does Controller receive updated Model state after it delegates Model update and notifies View about Model change?

I would be grateful for any piece of help with understanding the MVC.

Composite Pattern Iterating over Children of leafs

How could I check if any objects in my list have children of it's own?

I might have blown this code entirely up and I missed the purpose.

here is what I tried

import java.util.Arrays;
import java.util.List;

public class Employee {
    public String name;
    public double pay;

    public Employee(String name, double pay) {
        this.name = name;
        this.pay = pay;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPay() {
        return pay;
    }

    public void setPay(double pay) {
        this.pay = pay;
    }

    public void addEmployee(Employee emp) {
        throw new UnsupportedOperationException();
    }

    public void removeEmployee(Employee emp) {
        throw new UnsupportedOperationException();
    }
    public double calculateTotalPay() {
        throw new UnsupportedOperationException();
    }

    public void printList(){
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", pay=" + pay +
                '}';
    }
}

package composite;

public class DatabaseEngineer extends Employee {

    private int numberOfDB;

    public DatabaseEngineer(String name, double pay, int numberOfDB) {
        super(name, pay);
        this.numberOfDB = numberOfDB;
    }

    public int getNumberOfDB() {
        return numberOfDB;
    }

    @Override
    public void addEmployee(Employee emp) {
        throw new UnsupportedOperationException();
    }

    @Override
    public double calculateTotalPay() {
            return  this.getPay() + (1000 * this.getNumberOfDB());
    }
}

package composite;

public class SoftwareEngineer extends Employee {

    private String title;

    public SoftwareEngineer(String name, double pay, String title) {
        super(name, pay);
        this.title = title;
    }

    @Override
    public double calculateTotalPay() {
        if (this.title.equals("SWE2")) {
            return this.getPay() + 5000.00 * 1;
        } else if (this.title.equals("Senior SWE")) {
            return this.getPay() + 20000.00 * 1.5;
        } else if (this.title.equals("Principle Engineer")) {
            return this.getPay() + 50000.00 * 2;
        } else
            return 0.0;
    }
}

package composite;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Manager extends Employee {


    List<Employee> listOfEmployee = new ArrayList<Employee>();

    public Manager(String name, double pay) {
        super(name, pay);
    }

    @Override
    public void addEmployee(Employee employee) {
        listOfEmployee.add(employee);
    }

    @Override
    public void removeEmployee(Employee employee) {
        listOfEmployee.remove(employee);
    }

    @Override
    public double calculateTotalPay() {
        double pay = 0.0;
        for (Employee employee1 : listOfEmployee) {
            if (employee1 instanceof SoftwareEngineer) {
                pay += employee1.calculateTotalPay();
            }
            if (employee1 instanceof DatabaseEngineer) {
                pay += employee1.calculateTotalPay();
            }
            if (employee1 instanceof Manager) {
                pay += employee1.getPay();
            }
        }
        return pay;
    }

    @Override
    public void printList() {
        listOfEmployee.forEach(System.out::println);
    }
}

package composite;


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

        /**
         * Test managers that manage some employees.
         */
        Employee softwareEngEmployee = new SoftwareEngineer("joe", 200.00, "SWE2");
        Employee databaseGuy = new DatabaseEngineer("bob", 200.00, 2);
        Employee manager = new Manager("tim", 200.00);
        manager.addEmployee(softwareEngEmployee);
        manager.addEmployee(databaseGuy);
        manager.addEmployee(manager);

        System.out.println(manager.calculateTotalPay());

        /**
         * Test managers that manage managers with some employees.
         */

        Employee softwareEngEmployee1 = new SoftwareEngineer("joe", 200.00, "SWE2");
        Employee databaseGuy1 = new DatabaseEngineer("bob", 200.00, 2);
        Employee manager1 = new Manager("tim", 200.00);
        Employee manager2 = new Manager("cali", 200.00);
        Employee manager3 = new Manager("swan", 200.00);

        manager1.addEmployee(softwareEngEmployee1);
        manager1.addEmployee(databaseGuy1);
        manager1.addEmployee(manager1);
        manager1.addEmployee(manager2);
        manager1.addEmployee(manager3);


        System.out.println(manager1.calculateTotalPay());

        manager1.removeEmployee(manager1);

        System.out.println(manager1.calculateTotalPay());

        /**
         * printing out employees
         */
        manager1.printList();


    }
}

My iteration does not discover the child of managers.

Example:

manager2.addEmployee(databaseGuy1);

As databaseGuy1 goes inside the manager2, the calculateTotalPay, from the manager class will not find him.

I tried google for getChild() and I've also tried playing with indexes, without success.

how to upload figma file(wireframe) on github?

I am making an app based on fitness. For that, I am making wireframe designs in Figma. Now I want to upload that Figma file on Github because I am working in a team of 4 members and we 4 can work together.

What is the proper way using composition in Golang

I'm OOP guy, recently I have to work on Golang the language that I haven't done it before. Though I already went through many articles talking about composition, I notice it's a bit tricky to use it properly on Golang

Let's say I have two examples of Golang composition, I don't know which one will be correct, and would it be different between of them? Thank you

First example

type BaseClass struct {
   db *DB
}

func NewBaseClass(db *DB) *BaseClass {
  return &BaseClass{db}
}

type ChildrenClass1 struct {
     baseClass *BaseClass
}

func NewChildrenClass1(db *DB) *ChildrenClass1 {
  baseClass := NewBaseClass(db)
  return &ChildrenClass1{baseClass}
}

type ChildrenClass2 struct {
     baseClass *BaseClass
}

func NewChildrenClass2(db *DB) *ChildrenClass2 {
  baseClass := NewBaseClass(db)
  return &ChildrenClass2{baseClass}
}

func main(){
  db := NewDB()
  chilrend1 := NewChildrenClass1(db)
  chilrend2 := NewChildrenClass2(db)
}

Second example

type BaseClass struct {
   db *DB
}

func NewBaseClass(db *DB) *BaseClass {
  return &BaseClass{db}
}

type ChildrenClass1 struct {
     baseClass *BaseClass
}

func NewChildrenClass1(baseClass *BaseClass) *ChildrenClass1 {
  return &ChildrenClass1{baseClass}
}

type ChildrenClass2 struct {
     baseClass *BaseClass
}

func NewChildrenClass2(baseClass *BaseClass) *ChildrenClass2 {
  return &ChildrenClass2{baseClass}
}

func main(){
  db := NewDB()
  baseClass := NewBaseClass(db)
  chilrend1 := NewChildrenClass1(baseClass)
  chilrend2 := NewChildrenClass2(baseClass)
}

How to Solve Proxy Design Pattern Assignment Problem

**

  • Exercise Please Help Me To Solve This assignment Throught Proxy Design Pattern

** We’re going to build an O/RM (Object Relational Mapper). ORMs are tools responsible for mapping data between a relational database and an objectoriented model. There are many popular O/RMs out there such as Hibernate and Entity Framework. You can see a “super simplified” implementation of our imaginary ORM in the proxy package.

We use the DbContext class to read or write data to our database. The Demo class shows the typical workflow for using a DbContext

  • Read an object from a database (dbContext.getProduct())
  • Change the properties of the in-memory object (product.setName())
  • Ask the dbContext to save the changes (dbContext.saveChanges())

If you run the code in the Demo class, you’ll only see a SELECT statement printed on the terminal. This simulates reading a product record from a database.

What is missing is the two UPDATE statements that should be generated when we save the changes. The reason this is happening is that our DbContext cannot keep track of the changed objects. So, when we call saveChanges(), nothing happens.

We can solve this problem using the proxy pattern. A proxy object looks like our target object (eg a Product object) but it adds some extra behavior to it.

For example, when we call the setName() method, the proxy notifies the DbContext that it is changed. DbContext provides a method for this: markAsChanged().

Use the proxy pattern to allow DbContext keep track of changed objects and persist them in a database.

NOTE: Some real-world O/RMs automatically generate these proxy objects based for you, so you don’t need to code them by hand.

mardi 23 novembre 2021

How to print decreasing and increasing star pattern using while loop in java? Like sandglass?

Print the following pattern using while loop in java.




**

*

*

**




Similarity or Pattern Matching or Disambiguation

input a sentence. input a string. if input string is found in a list of related words do something to disambiguate two different senses. Pattern matching - Disambiguation - Similarity. Python or C# or WPF code.

Is this wrong way to use factory pattern

Is this wrong way to use factory pattern ?

class SettlementAPIFactory @Inject constructor(
      val instantPayFeatureFlags: InstantPayFeatureFlags,
      val banklinSettlementAPI: BanklinSettlementAPI,
      val moneyMoverCaller: MoneyMoverCaller
    ) {
    
      fun getSettlementAPI(customerToken: CustomerToken): SettlementAPI {
        if (instantPayFeatureFlags.useBanklin(customerToken)) {
          return banklinSettlementAPI
        }
        return moneyMoverCaller
      }
    }

Basically I am defining a factory which is returns banklinSettlementAPI or moneyMoverCaller for a customer based on some feature flag condition.

They way I am planning to use this factory is to get correct settlementAPI object for each customer and invoke a method on it, something like this

val factory SettlementAPIFactory  = SettlementAPIFactory()
factory.getSettlementAPI(customerToken).callSettlement();  

I am wondering if this is wrong way to define factory since I am actually not creating new objects. What could have been better implementation or pattern to use ?

How can I decide to better implement this functionality? [closed]

Tell me, please, how to properly organize this idea? I have library A and two projects B, C. Project B connects library A, and project C also connects library A.

I want to do something like this:

code of library A:

template<class TContainer> class a {
public:
   virtual void foo (const TContainer& container) = 0;
};

template<class TContainer> class b: public a<TContainer> {
public:
   virtual void foo (const TContainer& container) {
      // a lot of code
      int info = getInfoFromContainer(container);
      // a lot of code
   };
   int getInfoFromContainer (const TContainer& container) {
      return 0;
   };
};

template<class TContainer> class c : public a<TContainer> {
public:
   virtual void foo (const TContainer& container) {
      // a lot of code
      double info = getInfoFromContainer(container);
      // a lot of code
   };
   double getInfoFromContainer (const TContainer& container) {
      return 0;
   };
};

code of project B:

// only here the container implementation appears
class ContainerB;

// explicit specialization for ContainerB
template<> int b<ContainerB>::getInfoFromContainer (const ContainerB& container) { ... }
template<> double c<ContainerB>::getInfoFromContainer (const ContainerB& container) { ... }

// example using
ContainerB     myContainer;
a<ContainerB>* myClass = new b<ContainerB>();
myClass->foo(myContainer);

code of project C:

// only here the container implementation appears
class ContainerC;

// explicit specialization for ContainerC
template<> int b<ContainerC>::getInfoFromContainer (const ContainerC& container) { ... }
template<> double c<ContainerC>::getInfoFromContainer (const ContainerC& container) { ... }

// example using
ContainerC     myContainer;
a<ContainerC>* myClass = new b<ContainerC>();
myClass->foo(myContainer);

The problem is that it is "difficult" for containers B and C to create an abstract class. And declare this abstract class in library A. And also that in projects B and C, I must operate with a pointer to class a. Classes a, b, c were moved to library A to reduce the amount of repetitive code. Briefly, about the problem, you need getInfoFromContainer to take a different type and work out differently in projects B and C.

Is it possible to do this or is it bad to maintain in the future? How else can you do it? Is it possible to use a functional style here? Senc.

lundi 22 novembre 2021

How to avoid instanceOf and dynamic getter check?

This code is from the CardUtility class I am using in my application.

    public static boolean areBothColoredAndHaveSameColor(Card c1, Card c2) {
        if (c1 instanceof ColoredCard coloredCard1 && c2 instanceof ColoredCard coloredCard2)
            return coloredCard1.getColor() == coloredCard2.getColor();
        return false;
    }

    public static boolean areBothNumberedAndHaveSameNumber(Card c1, Card c2) {
        if (c1 instanceof NumberedCard numberedCard1 && c2 instanceof NumberedCard numberedCard2)
            return numberedCard1.getNumber() == numberedCard2.getNumber();
        return false;
    }

    public static boolean areBothSpecialAndHaveSameSpeciality(Card c1, Card c2) {
        if (c1 instanceof SpecialColoredCard specialColoredCard1 && c2 instanceof SpecialColoredCard specialColoredCard2)
            return specialColoredCard1.getSpeciality() == specialColoredCard2.getSpeciality();
        return false;
    }

I can obviously see the code duplication happening here but I am bound by the fact that I can't use an equals check and because of the inheritance hierarchy: NumberedCard and SpecialColoredCard both extend the abstract ColoredCard class. How can I avoid the redundancy? Should I make all of these implement a new CardWithKeyProperty interface and refactor these methods to a single doBothHaveTheSameKeyProperty() method? But again I am not sure because ColoredCard is one step higher in the inheritance hierarchy so all of them implementing the same interface doesn't sound right.

Does Information Expert pattern contradict Service Layer Pattern?

While reading about GRASP patterns I stopped at Information Expert, which states that behavior on classes state should be within that same class. But that is a complete opposite with Service Layer pattern which I used for years. Services have behavior for Domain objects' state. Which confuses me

I would be grateful for a thoughtful answer.

Nested MVC and BehaviorSubjects

Let's assume we have an object that is manily a list, List and has its view ListV, and a controller ListC to manage the state.
On the other hand, we have items in that list. Each one has Item model, ItemC to control its state, and ItemV to draw it.

What I am doing is that ListC is inside ListV and that is how we reach the ListM. However, ListV should have ItemV, and the that one should have ItemC where we get ItemM. The question is: Where to we store reference to instances of ItemM?

My problem now:
Let's assume there are 2 instance of ItemM: itemM1 and itemM2; Where do we store those instances? I tried storing them in the instance of ListM, but them even after updating an item using its controller, ListM would still have the old reference.

Java state pattern with different properties and sql

I have main domain class Broadcast that can have three states:

public class Broadcast {
    private Long id;
    private String title;
    private Author author;
    private State state;

    // constructor, getters and setters                                                     
}

Each state contains different properties.

public abstract class State {
    private Broadcast stateContext;

    public State(Broadcast stateContext) {
        this.stateContext = stateContext;
    }
}

public class UpcomingState extends State {
    private OffsetDateTime createdAt;
    private OffsetDateTime scheduledAt;

    public UpcomingState(Broadcast stateContext) {
        super(stateContext);
    }

    // getters and setters
}

public class LiveState extends State {
    private OffsetDateTime startedAt;

    public LiveState(Broadcast stateContext) {
        super(stateContext);
    }

    // getters and setters
}

public class EndedState extends State {
    private OffsetDateTime startedAt;
    private OffsetDateTime endedAt;

    public EndedState(Broadcast stateContext) {
        super(stateContext);
    }

    // getters and setters
}

How do I design the tables in the database to store objects of this class (for example, postgresql) while still preserving information about state transitions, assuming some states might be applied multiple times?

For example, upcoming -> live (first data) -> live (second data) -> ended.

Best way to call multiple operations multiple times after another

I have the following scenario:

there are 3 API's that I call every 5 minutes. I do this asynchronously so the order of calling the API doesn't matter. A 'call' itself contains

  1. A HTTP-request to the API
  2. The extraction of data (reading the response)
  3. Storing it into a Database.

so these 3 steps are always the same. Currently my code looks somewhat like this:

scraper.Request()
scraper.Extract()
scraper.Save()

I surely put that into another function to wrap it up but it somehow looks weird to me. Are there any 'Patterns' I could follow, that match my scenario?

Thanks in Advance

Need help understanding a line of code I've seen online [closed]

I am learning c# and was looking at design patterns and I came across a line I feel like I've seen before but can't remember what it does.

https://dotnettutorials.net/lesson/decorator-design-pattern-real-time-example/

On step 3 it says protected Pizza pizza, it's creating a protected variable called pizza but why does it use the Interface to create this variable. If possible could you direct me to a page to read up on this as I can't search it as I don't know how to word it. Sorry for the dumb question.

dimanche 21 novembre 2021

Singleton in clustered kubernetes

I am familiar with the singleton design pattern and how to make it thread-safe etc, but only to the concepts restricted to a single JVM.

Now I am stuck with a task to achieve singleton in a system running multiple pods, without using any application servers. If you could share the code snippet which you had worked on previously would be great.

I am not using spring or any other frameworks currently.

Selecting a corresponding strategy based on the subtype of the instance

I have an interface IResponse that represents a response to a Question and a few concrete response types that implement IResponse:

interface IResponse<out TQuestion> where TQuestion: Question
{
     TQuestion Question { get; }
     Candidate Candidate { get; }
     string Answer { get; }
}

class MultipleChoiceResponse : IResponse<MultipleChoiceQuestion>
{
    public MultipleChoiceQuestion Question { get; }
    public Candidate Candidate { get; }
    public string Answer { get; }
}

class TextResponse : IResponse<TextQuestion>
{
    public TextQuestion Question { get; }
    public Candidate Candidate { get; }
    public string Answer { get; }
}
...

abstract class Question {..}
class MultipleChoiceQuestion : Question {..}
class TextQuestion : Question {..}
...

For each response type, I have a corresponding response evaluator that implements IResponseEvaluator:

interface IResponseEvaluator<TQuestion, TResponse> 
    where TQuestion : Question
    where TResponse : IResponse<TQuestion>
{
    decimal Evaluate(TResponse response);
}

class DefaultMultipleChoiceResponseEvaluator : IResponseEvaluator<MultipleChoiceQuestion, MultipleChoiceResponse>
{
    public decimal Evaluate(MultipleChoiceResponse response)
    {
        ...
    }
}

class DefaultTextResponseEvaluator : IResponseEvaluator<TextQuestion, TextResponse>
{
    public decimal Evaluate(TextResponse response)
    {
        ...
    }
}
...

Finally, I have an EvaluationAggregator with a method EvaluateAll that provides a common interface to accept a collection of all subtypes of IResponse using IEnumerable<IResponse<Question>>:

class EvaluationAggregator
{
    public IResponseEvaluator<MultipleChoiceQuestion, MultipleChoiceResponse> ChoiceEvaluator { get; set; }   

    public IResponseEvaluator<TextQuestion, TextResponse> TextEvaluator { get; set; }

    ...
    
    public decimal EvaluateAll(IEnumerable<IResponse<Question>> responses)
    {
         decimal totalScore = 0;
         foreach (var response in responses)
         {
              decimal score = response switch
              {
                  MultipleChoiceResponse mcr => ChoiceEvaluator.Evaluate(mcr),
                  TextResponse tr => TextEvaluator.Evaluate(tr),
                  ...
              };
              totalScore += score;
         }    
         return totalScore;
    }
}

Since, TQuestion in IResponse<TQuestion> is covariant(marked with out), I can pass responses to all question subtypes as a single IEnumerable to EvaluateAll. However, to select the right evaluator for the type , I'm still having to switch on the type of the response. If I add more response types in the future, the code will have to be modified. Is there a design pattern or a cleaner way to do this?

This is how I would call it:

IEnumerable<IResponse<Question>> responses = FetchAllTypesOfResponses();

var aggregator = new EvaluationAggregator 
{
    ChoiceEvaluator = new DefaultMultipleChoiceResponseEvaluator(),
    TextEvaluator = new DefaultMultipleChoiceResponseEvaluator()
};

decimal totalScore = aggregator.EvaluateAll(responses);

Decorator class for all subclasses of a class

I'm using a library with classes that all inherit from one super class, and the methods in each subclass return objects with the same keys, for example

class Store:

    def check_schedule(self, name):
        return

    def check_inventory(self, product):
        return


class Bakery(Store):

    def check_schedule(self, name):
        # Some unique code to Bakery
        return {
            'name': '...',
            'hours': '...',
            'maxHours': '...',
        }

    def check_inventory(self, product):
        # Some unique code to Bakery
        return {
            'amount': '...',
            'price': '...',
        }


class Tools(Store):

    def check_schedule(self, name):
        # Some unique code to Tools
        return {
            'name': '...',
            'hours': '...',
            'maxHours': '...',
        }

    def check_inventory(self, product):
        # Some unique code to Tools
        return {
            'amount': '...',
            'price': '...',
        }

I want to add a decorator subclass to some of the methods to manipulate response data, and I want this decorator on every subclass. For example, if I wanted to convert the responses to German, this decorator would look like

class GermanStore(Tools or Bakery):

    def translate(self, object):
        # convert object to German
        return object

    def check_schedule(self, name):
        returnObject = super().check_schedule(name)
        return self.translate(returnObject)

    def check_inventory(self, product):
        returnObject = super().check_schedule(product)
        return self.translate(returnObject)

Is this possible? Is there a name for this type of architecture pattern?


The answer does not need to be python specific, but I am using python, so the feature would need to be available in python for the answer to be useful

Code only outputs a single row while trying to draw a rectangle

void fyllRektangel(int hojd, int bredd); 

    int main(){
        int hojd;       //Height
        int bredd;      //Width
        cin>>hojd;
        cin>>bredd;

        for(int r=1;r<=hojd;r+=1){
            for(int k=1;k<=bredd;k+=1)
                cout<<setw(4)<<"*";
            cout<<endl;



            return 0;
        }
    }

Why does my code only output a single row, but all the columns in my for loop? Im learning about patterns and the output is suppose to be of a rectangle where the width and height is input from the user.

A case of template method pattern: how would you refactor this?

I'm refactoring my Tic Tac Toe java project and I've stumbled upon an issue with (my comprehension of) the form template method pattern. In summary: I have created three player classes that implement variants of the minimax algorithm. I then created an abstract class to collect all the common methods of those classes. Then I realized that two of the three methods that call the recursive step of the variant of minimax algorithm are nearly identical. Talking about the public int sendMove() method.

Here's the call to the simple variant:

public class CpuMiniMax extends CommonTools implements Player  {
...
...
    public int sendMove() {
    int bestScore = Integer.MIN_VALUE;
    int score = 0;
    int position = 0;
    char opponentMark = myMark == 'X' ? 'O' : 'X';
    for (int i = 0; i < board.length; i++) {
        if (board[i] == ' ') {
            board[i] = myMark;
            score = miniMax(3, opponentMark, false); // <- the only difference
            board[i] = ' ';
            if (score > bestScore) {
                position = i;
                bestScore = score;
            }
        }
    }
    board[position] = myMark;
    return position;
    }
...
...
}

Here's the call to the alpha beta pruning variant:

public class CpuMiniMaxAlphaBetaPruning extends CommonTools implements Player  {
...
...
    public int sendMove() {
    int bestScore = Integer.MIN_VALUE;
    int score = 0;
    int position = 0;
    char opponentMark = myMark == 'X' ? 'O' : 'X';
    for (int i = 0; i < board.length; i++) {
        if (board[i] == ' ') {
            board[i] = myMark;
            score = miniMaxAlphaBetaPruning(3, opponentMark, Integer.MIN_VALUE, Integer.MAX_VALUE, false); // <- the only difference
            board[i] = ' ';
            if (score > bestScore) {
                position = i;
                bestScore = score;
            }
        }
    }
    board[position] = myMark;
    return position;
    }
...
...
}

And now for something completely different here's the call to an optimized alpha beta pruning:

public class CpuMiniMaxAlphaBetaPruningOptimized extends CommonTools implements Player {
...
...
public int sendMove() {
    int[] emptySquares = emptySquaresRandomizer();
    char opponentMark = myMark == 'X' ? 'O' : 'X';
    for (int i = 0; i < emptySquares.length; i++) {
        board[emptySquares[i]] = myMark;
        if (tris(myMark)) {
            return emptySquares[i];
        }
        board[emptySquares[i]] = ' ';
    }
    for (int i = 0; i < emptySquares.length; i++) {
        board[emptySquares[i]] = opponentMark;
        if (tris(opponentMark)) {
            board[emptySquares[i]] = myMark;
            return emptySquares[i];
        }
        board[emptySquares[i]] = ' ';
    }
    for (int i = 0; i < emptySquares.length; i++) {
        board[emptySquares[i]] = myMark;
        if (isFork(emptySquares, i)) {
            return emptySquares[i];
        }
        board[emptySquares[i]] = ' ';
    }
    int bestScore = Integer.MIN_VALUE;
    int score = 0;
    int position = 0;
    for (int i = 0; i < emptySquares.length; i++) {
        board[emptySquares[i]] = myMark;
        score = miniMaxAlphaBetaPruningOptimized(3, opponentMark, Integer.MIN_VALUE, Integer.MAX_VALUE, false);
        board[emptySquares[i]] = ' ';
        if (score > bestScore) {
            position = emptySquares[i];
            bestScore = score;
        }
    }
    board[position] = myMark;
    return position;
    }
...
...
}

So I decided to refactor more in my CommonTools abstract class:

public abstract class CommonTools {
...
...
    public int sendMove() {
    int bestScore = Integer.MIN_VALUE;
    int score = 0;
    int position = 0;
    char opponentMark = myMark == 'X' ? 'O' : 'X';
    for (int i = 0; i < board.length; i++) {
        if (board[i] == ' ') {
            board[i] = myMark;
            score = callRecursiveMiniMaxAlgorithm(opponentMark); // <- call to the method subclasses have to implement
            board[i] = ' ';
            if (score > bestScore) {
                position = i;
                bestScore = score;
            }
        }
    }
    board[position] = myMark;
    return position;
    }
...
...
    protected abstract int callRecursiveMiniMaxAlgorithm(char opponentMark); // <- the method subclasses have to implement
...
...
}

In this way I was able to eliminate duplication of code in my two classes CpuMiniMax and CpuMiniMaxAlphaBetaPruning just by deleting the public int sendMove() method and implementing the abstract method above, while I kept its implementation in my CpuMiniMaxAlphaBetaPruningOptimized class. The latter, extending the abstract class, has to implement the abstract method too of course. And this implementation would remain a stub since the class overrides the public int sendMove() defined in the abstract class. And this, for some reasons, quite bothers me. So my questions are: is this a correct use of the pattern (even if produces unused code)? How would you refactor?

Program stuck in Infinite loop

My program is going in infinite loop and does not print required output please help anyone

image

samedi 20 novembre 2021

What are the pros and cons of using TTL vs actively sending a request to invalidate a key to invalidate a key in a cache?

Are there any best practices around key invalidation for caches like Redis? Should I let the key fall out after the TTL expires or should I call a delete on the key in question to remove that key from cache?

Would the actively calling a delete operation put more load and hurt the throughput of my cache?

pls explain the compiler error in my pattern making code

#include<iostream>
using namespace std;

int main () {
int rows;
int columns;
    cout << "Pls enter the number of rows for pattern: "; 
    cin >> rows;
    cout << "Pls enter the number of columns for pattern: ";
    cin >> columns; 

    for (int i=1; i <= rows; i++) {
        for (int j=1; j <= columns; j++){
            cout << "*";
        }
            cout << endl;
    }

char yn;
    cout << "Is the program working as intended? (y/n)";
    cin >> yn;

    while (true) {
    if (yn == 'y' || yn == 'Y') {
        cout << "Thank You, for your response :)" << endl;
    }
    else if (yn == 'n' || yn == 'N') {
        cout << "We will try to improve ;)" << endl;
    }
    return 0; } 

}

At the end of this code the output tab of this terminal shows a message as:- c:/mingw/bin/…/lib/gcc/mingw32/6.3.0/…/…/…/…/mingw32/bin/ld.exe: cannot open output file pattern.exe: Permission denied collect2.exe: error: ld returned 1 exit status


terminal shows :- The term ‘./pattern’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was include d, verify that the path is correct and try again. At line:1 char:10

./pattern <<<< CategoryInfo : ObjectNotFound: (./pattern:String) , CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException


when i open this file as an applcation in .exe format (even though i saved it with a a name —> pattern.cpp), it :- it asks for number of rows and columns but no pattern is made, instead of making a pattern of ‘*’ it staright away asks if the program runs properly. :frowning:


What is wrong with my code? im a beginner who needs help.

vendredi 19 novembre 2021

How to return out of command pattern in controller so that application stops running (Java)?

I am designing a controller using the command pattern. The controller has a while loop inside that is scanning for user input. If user input matches a specific String, then a command class is executed. Here is a code snippit:

  public Controller(Readable in, Appendable out) {
    this.out = out;
    this.scan = new Scanner(in);
    this.commandMap = this.generateCommands();
  }

public void go(Model m) {

      while (scan.hasNext()) {
        
        String input = scan.next();
        Command command = this.commandMap.get(input);
          command.do(m);
        }
}

I usually use return to stop the application. However, when I use return inside one of the Command classes, the application keeps running. I think it just goes back to this upper loop. By the way, all my commands are public void.

Is there a way to exit/close the application from within the command classes? Like a "super" return? Or do I need to no longer make them void and if/else the return in the controller.

what polynomial global basis function mean

I tried to search the exact meaning and I don't find what I need ,I know a small change in x will affect to the whole basis function but how? can anyone explain it in an easier way?

What pattern or architecture should I implement by Laravel to structure this project?

The project is simple, and it has to do with formula 1 statistics. The UI looks a lot like a game menu. Going from "option" to "option" in the UI you end up in an "endpoint" page where the user can see the statistics of his like. It's tree structure where every "option" is a separate view on my project.

The user click "Race standings" to load a page. The user click a year on a form to see next page. The user click a race of that year then redirects to "race result" page. The logic for doing this is to create a nice UI so the user would like to spend time on the site and navigate through the pages.

I POST data from my view's forms to a controller's function. This function fetch the data from the database using my models and the post parameters, do the logic and return('thatView', compact('array' , 'array2', 'etc). php and javascript on the views manipulates the organized arrays fitting them into html. Arrays contains text data, for example array 1 could be the data of a race-result table.

The way my project is structure is very amateur. No patterns, no architecture, no anything good. Using directly the raceresult domain on the browser will result error. The needed parameters are missing as they cannot be set from the domain, it needs the previous page to post the data.

How could i structure my project better? What patterns could i use?